source
stringlengths
3
92
c
stringlengths
26
2.25M
composite.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC OOO M M PPPP OOO SSSSS IIIII TTTTT EEEEE % % C O O MM MM P P O O SS I T E % % C O O M M M PPPP O O SSS I T EEE % % C O O M M P O O SS I T E % % CCCC OOO M M P OOO SSSSS IIIII T EEEEE % % % % % % MagickCore Image Composite Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.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/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/constitute.h" #include "MagickCore/draw.h" #include "MagickCore/fx.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/image.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/memory_.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/quantum.h" #include "MagickCore/resample.h" #include "MagickCore/resource_.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" #include "MagickCore/threshold.h" #include "MagickCore/token.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #include "MagickCore/version.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p o s i t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompositeImage() returns the second image composited onto the first % at the specified offset, using the specified composite method. % % The format of the CompositeImage method is: % % MagickBooleanType CompositeImage(Image *image, % const Image *source_image,const CompositeOperator compose, % const MagickBooleanType clip_to_self,const ssize_t x_offset, % const ssize_t y_offset,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the canvas image, modified by he composition % % o source_image: the source image. % % o compose: This operator affects how the composite is applied to % the image. The operators and how they are utilized are listed here % http://www.w3.org/TR/SVG12/#compositing. % % o clip_to_self: set to MagickTrue to limit composition to area composed. % % o x_offset: the column offset of the composited image. % % o y_offset: the row offset of the composited image. % % Extra Controls from Image meta-data in 'image' (artifacts) % % o "compose:args" % A string containing extra numerical arguments for specific compose % methods, generally expressed as a 'geometry' or a comma separated list % of numbers. % % Compose methods needing such arguments include "BlendCompositeOp" and % "DisplaceCompositeOp". % % o exception: return any errors or warnings in this structure. % */ /* Composition based on the SVG specification: A Composition is defined by... Color Function : f(Sc,Dc) where Sc and Dc are the normizalized colors Blending areas : X = 1 for area of overlap, ie: f(Sc,Dc) Y = 1 for source preserved Z = 1 for canvas preserved Conversion to transparency (then optimized) Dca' = f(Sc, Dc)*Sa*Da + Y*Sca*(1-Da) + Z*Dca*(1-Sa) Da' = X*Sa*Da + Y*Sa*(1-Da) + Z*Da*(1-Sa) Where... Sca = Sc*Sa normalized Source color divided by Source alpha Dca = Dc*Da normalized Dest color divided by Dest alpha Dc' = Dca'/Da' the desired color value for this channel. Da' in in the follow formula as 'gamma' The resulting alpla value. Most functions use a blending mode of over (X=1,Y=1,Z=1) this results in the following optimizations... gamma = Sa+Da-Sa*Da; gamma = 1 - QuantumScale*alpha * QuantumScale*beta; opacity = QuantumScale*alpha*beta; // over blend, optimized 1-Gamma The above SVG definitions also define that Mathematical Composition methods should use a 'Over' blending mode for Alpha Channel. It however was not applied for composition modes of 'Plus', 'Minus', the modulus versions of 'Add' and 'Subtract'. Mathematical operator changes to be applied from IM v6.7... 1) Modulus modes 'Add' and 'Subtract' are obsoleted and renamed 'ModulusAdd' and 'ModulusSubtract' for clarity. 2) All mathematical compositions work as per the SVG specification with regard to blending. This now includes 'ModulusAdd' and 'ModulusSubtract'. 3) When the special channel flag 'sync' (syncronize channel updates) is turned off (enabled by default) then mathematical compositions are only performed on the channels specified, and are applied independantally of each other. In other words the mathematics is performed as 'pure' mathematical operations, rather than as image operations. */ static void HCLComposite(const MagickRealType hue,const MagickRealType chroma, const MagickRealType luma,MagickRealType *red,MagickRealType *green, MagickRealType *blue) { MagickRealType b, c, g, h, m, r, x; /* Convert HCL to RGB colorspace. */ assert(red != (MagickRealType *) NULL); assert(green != (MagickRealType *) NULL); assert(blue != (MagickRealType *) NULL); h=6.0*hue; c=chroma; x=c*(1.0-fabs(fmod(h,2.0)-1.0)); r=0.0; g=0.0; b=0.0; if ((0.0 <= h) && (h < 1.0)) { r=c; g=x; } else if ((1.0 <= h) && (h < 2.0)) { r=x; g=c; } else if ((2.0 <= h) && (h < 3.0)) { g=c; b=x; } else if ((3.0 <= h) && (h < 4.0)) { g=x; b=c; } else if ((4.0 <= h) && (h < 5.0)) { r=x; b=c; } else if ((5.0 <= h) && (h < 6.0)) { r=c; b=x; } m=luma-(0.298839*r+0.586811*g+0.114350*b); *red=QuantumRange*(r+m); *green=QuantumRange*(g+m); *blue=QuantumRange*(b+m); } static void CompositeHCL(const MagickRealType red,const MagickRealType green, const MagickRealType blue,MagickRealType *hue,MagickRealType *chroma, MagickRealType *luma) { MagickRealType b, c, g, h, max, r; /* Convert RGB to HCL colorspace. */ assert(hue != (MagickRealType *) NULL); assert(chroma != (MagickRealType *) NULL); assert(luma != (MagickRealType *) NULL); r=red; g=green; b=blue; max=MagickMax(r,MagickMax(g,b)); c=max-(MagickRealType) MagickMin(r,MagickMin(g,b)); h=0.0; if (c == 0) h=0.0; else if (red == max) h=fmod((g-b)/c+6.0,6.0); else if (green == max) h=((b-r)/c)+2.0; else if (blue == max) h=((r-g)/c)+4.0; *hue=(h/6.0); *chroma=QuantumScale*c; *luma=QuantumScale*(0.298839*r+0.586811*g+0.114350*b); } static MagickBooleanType CompositeOverImage(Image *image, const Image *source_image,const MagickBooleanType clip_to_self, const ssize_t x_offset,const ssize_t y_offset,ExceptionInfo *exception) { #define CompositeImageTag "Composite/Image" CacheView *image_view, *source_view; const char *value; MagickBooleanType clamp, status; MagickOffsetType progress; ssize_t y; /* Composite image. */ status=MagickTrue; progress=0; clamp=MagickTrue; value=GetImageArtifact(image,"compose:clamp"); if (value != (const char *) NULL) clamp=IsStringTrue(value); status=MagickTrue; progress=0; source_view=AcquireVirtualCacheView(source_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(source_image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *pixels; PixelInfo canvas_pixel, source_pixel; const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; if (clip_to_self != MagickFalse) { if (y < y_offset) continue; if ((y-y_offset) >= (ssize_t) source_image->rows) continue; } /* If pixels is NULL, y is outside overlay region. */ pixels=(Quantum *) NULL; p=(Quantum *) NULL; if ((y >= y_offset) && ((y-y_offset) < (ssize_t) source_image->rows)) { p=GetCacheViewVirtualPixels(source_view,0,y-y_offset, source_image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } pixels=p; if (x_offset < 0) p-=x_offset*(ssize_t) GetPixelChannels(source_image); } q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } GetPixelInfo(image,&canvas_pixel); GetPixelInfo(source_image,&source_pixel); for (x=0; x < (ssize_t) image->columns; x++) { double gamma; MagickRealType alpha, Da, Dc, Dca, Sa, Sc, Sca; ssize_t i; size_t channels; if (clip_to_self != MagickFalse) { if (x < x_offset) { q+=GetPixelChannels(image); continue; } if ((x-x_offset) >= (ssize_t) source_image->columns) break; } if ((pixels == (Quantum *) NULL) || (x < x_offset) || ((x-x_offset) >= (ssize_t) source_image->columns)) { Quantum source[MaxPixelChannels]; /* Virtual composite: Sc: source color. Dc: canvas color. */ (void) GetOneVirtualPixel(source_image,x-x_offset,y-y_offset,source, exception); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { MagickRealType pixel; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait source_traits=GetPixelChannelTraits(source_image, channel); if ((traits == UndefinedPixelTrait) || (source_traits == UndefinedPixelTrait)) continue; if (channel == AlphaPixelChannel) pixel=(MagickRealType) TransparentAlpha; else pixel=(MagickRealType) q[i]; q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); } q+=GetPixelChannels(image); continue; } /* Authentic composite: Sa: normalized source alpha. Da: normalized canvas alpha. */ Sa=QuantumScale*GetPixelAlpha(source_image,p); Da=QuantumScale*GetPixelAlpha(image,q); alpha=Sa+Da-Sa*Da; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { MagickRealType pixel; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait source_traits=GetPixelChannelTraits(source_image,channel); if (traits == UndefinedPixelTrait) continue; if ((source_traits == UndefinedPixelTrait) && (channel != AlphaPixelChannel)) continue; if (channel == AlphaPixelChannel) { /* Set alpha channel. */ pixel=QuantumRange*alpha; q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); continue; } /* Sc: source color. Dc: canvas color. */ Sc=(MagickRealType) GetPixelChannel(source_image,channel,p); Dc=(MagickRealType) q[i]; if ((traits & CopyPixelTrait) != 0) { /* Copy channel. */ q[i]=ClampToQuantum(Sc); continue; } /* Porter-Duff compositions: Sca: source normalized color multiplied by alpha. Dca: normalized canvas color multiplied by alpha. */ Sca=QuantumScale*Sa*Sc; Dca=QuantumScale*Da*Dc; gamma=PerceptibleReciprocal(alpha); pixel=QuantumRange*gamma*(Sca+Dca*(1.0-Sa)); q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); } p+=GetPixelChannels(source_image); channels=GetPixelChannels(source_image); if (p >= (pixels+channels*source_image->columns)) p=pixels; q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_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,CompositeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); return(status); } MagickExport MagickBooleanType CompositeImage(Image *image, const Image *composite,const CompositeOperator compose, const MagickBooleanType clip_to_self,const ssize_t x_offset, const ssize_t y_offset,ExceptionInfo *exception) { #define CompositeImageTag "Composite/Image" CacheView *source_view, *image_view; const char *value; GeometryInfo geometry_info; Image *canvas_image, *source_image; MagickBooleanType clamp, status; MagickOffsetType progress; MagickRealType amount, canvas_dissolve, midpoint, percent_luma, percent_chroma, source_dissolve, threshold; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(composite != (Image *) NULL); assert(composite->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); source_image=CloneImage(composite,0,0,MagickTrue,exception); if (source_image == (const Image *) NULL) return(MagickFalse); (void) SetImageColorspace(source_image,image->colorspace,exception); if ((compose == OverCompositeOp) || (compose == SrcOverCompositeOp)) { status=CompositeOverImage(image,source_image,clip_to_self,x_offset, y_offset,exception); source_image=DestroyImage(source_image); return(status); } amount=0.5; canvas_image=(Image *) NULL; canvas_dissolve=1.0; clamp=MagickTrue; value=GetImageArtifact(image,"compose:clamp"); if (value != (const char *) NULL) clamp=IsStringTrue(value); SetGeometryInfo(&geometry_info); percent_luma=100.0; percent_chroma=100.0; source_dissolve=1.0; threshold=0.05f; switch (compose) { case CopyCompositeOp: { if ((x_offset < 0) || (y_offset < 0)) break; if ((x_offset+(ssize_t) source_image->columns) > (ssize_t) image->columns) break; if ((y_offset+(ssize_t) source_image->rows) > (ssize_t) image->rows) break; if ((source_image->alpha_trait == UndefinedPixelTrait) && (image->alpha_trait != UndefinedPixelTrait)) (void) SetImageAlphaChannel(source_image,OpaqueAlphaChannel,exception); status=MagickTrue; source_view=AcquireVirtualCacheView(source_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(source_image,image,source_image->rows,1) #endif for (y=0; y < (ssize_t) source_image->rows; y++) { MagickBooleanType sync; const Quantum *p; Quantum *q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1, exception); q=GetCacheViewAuthenticPixels(image_view,x_offset,y+y_offset, source_image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) source_image->columns; x++) { ssize_t i; if (GetPixelReadMask(source_image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(source_image); i++) { PixelChannel channel = GetPixelChannelChannel(source_image,i); PixelTrait source_traits = GetPixelChannelTraits(source_image, channel); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((source_traits == UndefinedPixelTrait) || (traits == UndefinedPixelTrait)) continue; SetPixelChannel(image,channel,p[i],q); } p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,CompositeImageTag,(MagickOffsetType) y,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); source_image=DestroyImage(source_image); return(status); } case IntensityCompositeOp: { if ((x_offset < 0) || (y_offset < 0)) break; if ((x_offset+(ssize_t) source_image->columns) > (ssize_t) image->columns) break; if ((y_offset+(ssize_t) source_image->rows) > (ssize_t) image->rows) break; status=MagickTrue; source_view=AcquireVirtualCacheView(source_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(source_image,image,source_image->rows,1) #endif for (y=0; y < (ssize_t) source_image->rows; y++) { MagickBooleanType sync; const Quantum *p; Quantum *q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1, exception); q=GetCacheViewAuthenticPixels(image_view,x_offset,y+y_offset, source_image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) source_image->columns; x++) { if (GetPixelReadMask(source_image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); continue; } SetPixelAlpha(image,clamp != MagickFalse ? ClampPixel(GetPixelIntensity(source_image,p)) : ClampToQuantum(GetPixelIntensity(source_image,p)),q); p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,CompositeImageTag,(MagickOffsetType) y,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); source_image=DestroyImage(source_image); return(status); } case CopyAlphaCompositeOp: case ChangeMaskCompositeOp: { /* Modify canvas outside the overlaid region and require an alpha channel to exist, to add transparency. */ if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); break; } case BlurCompositeOp: { CacheView *canvas_view; double angle_range, angle_start, height, width; PixelInfo pixel; ResampleFilter *resample_filter; SegmentInfo blur; /* Blur Image by resampling dictated by an overlay gradient map: X = red_channel; Y = green_channel; compose:args = x_scale[,y_scale[,angle]]. */ canvas_image=CloneImage(image,0,0,MagickTrue,exception); if (canvas_image == (Image *) NULL) { source_image=DestroyImage(source_image); return(MagickFalse); } /* Gather the maximum blur sigma values from user. */ flags=NoValue; value=GetImageArtifact(image,"compose:args"); if (value != (const char *) NULL) flags=ParseGeometry(value,&geometry_info); if ((flags & WidthValue) == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "InvalidSetting","'%s' '%s'","compose:args",value); source_image=DestroyImage(source_image); canvas_image=DestroyImage(canvas_image); return(MagickFalse); } /* Users input sigma now needs to be converted to the EWA ellipse size. The filter defaults to a sigma of 0.5 so to make this match the users input the ellipse size needs to be doubled. */ width=2.0*geometry_info.rho; height=width; if ((flags & HeightValue) != 0) height=2.0*geometry_info.sigma; /* Default the unrotated ellipse width and height axis vectors. */ blur.x1=width; blur.x2=0.0; blur.y1=0.0; blur.y2=height; if ((flags & XValue) != 0 ) { MagickRealType angle; /* Rotate vectors if a rotation angle is given. */ angle=DegreesToRadians(geometry_info.xi); blur.x1=width*cos(angle); blur.x2=width*sin(angle); blur.y1=(-height*sin(angle)); blur.y2=height*cos(angle); } angle_start=0.0; angle_range=0.0; if ((flags & YValue) != 0 ) { /* Lets set a angle range and calculate in the loop. */ angle_start=DegreesToRadians(geometry_info.xi); angle_range=DegreesToRadians(geometry_info.psi)-angle_start; } /* Set up a gaussian cylindrical filter for EWA Bluring. As the minimum ellipse radius of support*1.0 the EWA algorithm can only produce a minimum blur of 0.5 for Gaussian (support=2.0) This means that even 'No Blur' will be still a little blurry! The solution (as well as the problem of preventing any user expert filter settings, is to set our own user settings, restore them afterwards. */ resample_filter=AcquireResampleFilter(image,exception); SetResampleFilter(resample_filter,GaussianFilter); /* Perform the variable blurring of each pixel in image. */ GetPixelInfo(image,&pixel); source_view=AcquireVirtualCacheView(source_image,exception); canvas_view=AcquireAuthenticCacheView(canvas_image,exception); for (y=0; y < (ssize_t) source_image->rows; y++) { MagickBooleanType sync; const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (((y+y_offset) < 0) || ((y+y_offset) >= (ssize_t) image->rows)) continue; p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1, exception); q=QueueCacheViewAuthenticPixels(canvas_view,0,y,canvas_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) source_image->columns; x++) { if (((x_offset+x) < 0) || ((x_offset+x) >= (ssize_t) image->columns)) { p+=GetPixelChannels(source_image); continue; } if (fabs(angle_range) > MagickEpsilon) { MagickRealType angle; angle=angle_start+angle_range*QuantumScale* GetPixelBlue(source_image,p); blur.x1=width*cos(angle); blur.x2=width*sin(angle); blur.y1=(-height*sin(angle)); blur.y2=height*cos(angle); } ScaleResampleFilter(resample_filter, blur.x1*QuantumScale*GetPixelRed(source_image,p), blur.y1*QuantumScale*GetPixelGreen(source_image,p), blur.x2*QuantumScale*GetPixelRed(source_image,p), blur.y2*QuantumScale*GetPixelGreen(source_image,p) ); (void) ResamplePixelColor(resample_filter,(double) x_offset+x, (double) y_offset+y,&pixel,exception); SetPixelViaPixelInfo(canvas_image,&pixel,q); p+=GetPixelChannels(source_image); q+=GetPixelChannels(canvas_image); } sync=SyncCacheViewAuthenticPixels(canvas_view,exception); if (sync == MagickFalse) break; } resample_filter=DestroyResampleFilter(resample_filter); source_view=DestroyCacheView(source_view); canvas_view=DestroyCacheView(canvas_view); source_image=DestroyImage(source_image); source_image=canvas_image; break; } case DisplaceCompositeOp: case DistortCompositeOp: { CacheView *canvas_view; MagickRealType horizontal_scale, vertical_scale; PixelInfo pixel; PointInfo center, offset; /* Displace/Distort based on overlay gradient map: X = red_channel; Y = green_channel; compose:args = x_scale[,y_scale[,center.x,center.y]] */ canvas_image=CloneImage(image,0,0,MagickTrue,exception); if (canvas_image == (Image *) NULL) { source_image=DestroyImage(source_image); return(MagickFalse); } SetGeometryInfo(&geometry_info); flags=NoValue; value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) flags=ParseGeometry(value,&geometry_info); if ((flags & (WidthValue | HeightValue)) == 0 ) { if ((flags & AspectValue) == 0) { horizontal_scale=(MagickRealType) (source_image->columns-1)/2.0; vertical_scale=(MagickRealType) (source_image->rows-1)/2.0; } else { horizontal_scale=(MagickRealType) (image->columns-1)/2.0; vertical_scale=(MagickRealType) (image->rows-1)/2.0; } } else { horizontal_scale=geometry_info.rho; vertical_scale=geometry_info.sigma; if ((flags & PercentValue) != 0) { if ((flags & AspectValue) == 0) { horizontal_scale*=(source_image->columns-1)/200.0; vertical_scale*=(source_image->rows-1)/200.0; } else { horizontal_scale*=(image->columns-1)/200.0; vertical_scale*=(image->rows-1)/200.0; } } if ((flags & HeightValue) == 0) vertical_scale=horizontal_scale; } /* Determine fixed center point for absolute distortion map Absolute distort == Displace offset relative to a fixed absolute point Select that point according to +X+Y user inputs. default = center of overlay image arg flag '!' = locations/percentage relative to background image */ center.x=(MagickRealType) x_offset; center.y=(MagickRealType) y_offset; if (compose == DistortCompositeOp) { if ((flags & XValue) == 0) if ((flags & AspectValue) != 0) center.x=(MagickRealType) ((image->columns-1)/2.0); else center.x=(MagickRealType) (x_offset+(source_image->columns-1)/ 2.0); else if ((flags & AspectValue) != 0) center.x=geometry_info.xi; else center.x=(MagickRealType) (x_offset+geometry_info.xi); if ((flags & YValue) == 0) if ((flags & AspectValue) != 0) center.y=(MagickRealType) ((image->rows-1)/2.0); else center.y=(MagickRealType) (y_offset+(source_image->rows-1)/2.0); else if ((flags & AspectValue) != 0) center.y=geometry_info.psi; else center.y=(MagickRealType) (y_offset+geometry_info.psi); } /* Shift the pixel offset point as defined by the provided, displacement/distortion map. -- Like a lens... */ GetPixelInfo(image,&pixel); image_view=AcquireVirtualCacheView(image,exception); source_view=AcquireVirtualCacheView(source_image,exception); canvas_view=AcquireAuthenticCacheView(canvas_image,exception); for (y=0; y < (ssize_t) source_image->rows; y++) { MagickBooleanType sync; const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (((y+y_offset) < 0) || ((y+y_offset) >= (ssize_t) image->rows)) continue; p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1, exception); q=QueueCacheViewAuthenticPixels(canvas_view,0,y,canvas_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) source_image->columns; x++) { if (((x_offset+x) < 0) || ((x_offset+x) >= (ssize_t) image->columns)) { p+=GetPixelChannels(source_image); continue; } /* Displace the offset. */ offset.x=(double) (horizontal_scale*(GetPixelRed(source_image,p)- (((MagickRealType) QuantumRange+1.0)/2.0)))/(((MagickRealType) QuantumRange+1.0)/2.0)+center.x+((compose == DisplaceCompositeOp) ? x : 0); offset.y=(double) (vertical_scale*(GetPixelGreen(source_image,p)- (((MagickRealType) QuantumRange+1.0)/2.0)))/(((MagickRealType) QuantumRange+1.0)/2.0)+center.y+((compose == DisplaceCompositeOp) ? y : 0); status=InterpolatePixelInfo(image,image_view, UndefinedInterpolatePixel,(double) offset.x,(double) offset.y, &pixel,exception); if (status == MagickFalse) break; /* Mask with the 'invalid pixel mask' in alpha channel. */ pixel.alpha=(MagickRealType) QuantumRange*(QuantumScale*pixel.alpha)* (QuantumScale*GetPixelAlpha(source_image,p)); SetPixelViaPixelInfo(canvas_image,&pixel,q); p+=GetPixelChannels(source_image); q+=GetPixelChannels(canvas_image); } if (x < (ssize_t) source_image->columns) break; sync=SyncCacheViewAuthenticPixels(canvas_view,exception); if (sync == MagickFalse) break; } canvas_view=DestroyCacheView(canvas_view); source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); source_image=DestroyImage(source_image); source_image=canvas_image; break; } case DissolveCompositeOp: { /* Geometry arguments to dissolve factors. */ value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); source_dissolve=geometry_info.rho/100.0; canvas_dissolve=1.0; if ((source_dissolve-MagickEpsilon) < 0.0) source_dissolve=0.0; if ((source_dissolve+MagickEpsilon) > 1.0) { canvas_dissolve=2.0-source_dissolve; source_dissolve=1.0; } if ((flags & SigmaValue) != 0) canvas_dissolve=geometry_info.sigma/100.0; if ((canvas_dissolve-MagickEpsilon) < 0.0) canvas_dissolve=0.0; } break; } case BlendCompositeOp: { value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); source_dissolve=geometry_info.rho/100.0; canvas_dissolve=1.0-source_dissolve; if ((flags & SigmaValue) != 0) canvas_dissolve=geometry_info.sigma/100.0; } break; } case MathematicsCompositeOp: { /* Just collect the values from "compose:args", setting. Unused values are set to zero automagically. Arguments are normally a comma separated list, so this probably should be changed to some 'general comma list' parser, (with a minimum number of values) */ SetGeometryInfo(&geometry_info); value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) (void) ParseGeometry(value,&geometry_info); break; } case ModulateCompositeOp: { /* Determine the luma and chroma scale. */ value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); percent_luma=geometry_info.rho; if ((flags & SigmaValue) != 0) percent_chroma=geometry_info.sigma; } break; } case ThresholdCompositeOp: { /* Determine the amount and threshold. */ value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); amount=geometry_info.rho; threshold=geometry_info.sigma; if ((flags & SigmaValue) == 0) threshold=0.05f; } threshold*=QuantumRange; break; } default: break; } /* Composite image. */ status=MagickTrue; progress=0; midpoint=((MagickRealType) QuantumRange+1.0)/2; source_view=AcquireVirtualCacheView(source_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(source_image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *pixels; MagickRealType blue, chroma, green, hue, luma, red; PixelInfo canvas_pixel, source_pixel; const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; if (clip_to_self != MagickFalse) { if (y < y_offset) continue; if ((y-y_offset) >= (ssize_t) source_image->rows) continue; } /* If pixels is NULL, y is outside overlay region. */ pixels=(Quantum *) NULL; p=(Quantum *) NULL; if ((y >= y_offset) && ((y-y_offset) < (ssize_t) source_image->rows)) { p=GetCacheViewVirtualPixels(source_view,0,y-y_offset, source_image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } pixels=p; if (x_offset < 0) p-=x_offset*(ssize_t) GetPixelChannels(source_image); } q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } hue=0.0; chroma=0.0; luma=0.0; GetPixelInfo(image,&canvas_pixel); GetPixelInfo(source_image,&source_pixel); for (x=0; x < (ssize_t) image->columns; x++) { double gamma; MagickRealType alpha, Da, Dc, Dca, DcaDa, Sa, SaSca, Sc, Sca; ssize_t i; size_t channels; if (clip_to_self != MagickFalse) { if (x < x_offset) { q+=GetPixelChannels(image); continue; } if ((x-x_offset) >= (ssize_t) source_image->columns) break; } if ((pixels == (Quantum *) NULL) || (x < x_offset) || ((x-x_offset) >= (ssize_t) source_image->columns)) { Quantum source[MaxPixelChannels]; /* Virtual composite: Sc: source color. Dc: canvas color. */ (void) GetOneVirtualPixel(source_image,x-x_offset,y-y_offset,source, exception); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { MagickRealType pixel; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait source_traits=GetPixelChannelTraits(source_image, channel); if ((traits == UndefinedPixelTrait) || (source_traits == UndefinedPixelTrait)) continue; switch (compose) { case AlphaCompositeOp: case ChangeMaskCompositeOp: case CopyAlphaCompositeOp: case DstAtopCompositeOp: case DstInCompositeOp: case InCompositeOp: case OutCompositeOp: case SrcInCompositeOp: case SrcOutCompositeOp: { if (channel == AlphaPixelChannel) pixel=(MagickRealType) TransparentAlpha; else pixel=(MagickRealType) q[i]; break; } case ClearCompositeOp: case CopyCompositeOp: case ReplaceCompositeOp: case SrcCompositeOp: { if (channel == AlphaPixelChannel) pixel=(MagickRealType) TransparentAlpha; else pixel=0.0; break; } case BlendCompositeOp: case DissolveCompositeOp: { if (channel == AlphaPixelChannel) pixel=canvas_dissolve*GetPixelAlpha(source_image,source); else pixel=(MagickRealType) source[channel]; break; } default: { pixel=(MagickRealType) source[channel]; break; } } q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); } q+=GetPixelChannels(image); continue; } /* Authentic composite: Sa: normalized source alpha. Da: normalized canvas alpha. */ Sa=QuantumScale*GetPixelAlpha(source_image,p); Da=QuantumScale*GetPixelAlpha(image,q); switch (compose) { case BumpmapCompositeOp: { alpha=GetPixelIntensity(source_image,p)*Sa; break; } case ColorBurnCompositeOp: case ColorDodgeCompositeOp: case DarkenCompositeOp: case DifferenceCompositeOp: case DivideDstCompositeOp: case DivideSrcCompositeOp: case ExclusionCompositeOp: case FreezeCompositeOp: case HardLightCompositeOp: case HardMixCompositeOp: case InterpolateCompositeOp: case LightenCompositeOp: case LinearBurnCompositeOp: case LinearDodgeCompositeOp: case LinearLightCompositeOp: case MathematicsCompositeOp: case MinusDstCompositeOp: case MinusSrcCompositeOp: case MultiplyCompositeOp: case NegateCompositeOp: case OverlayCompositeOp: case PegtopLightCompositeOp: case PinLightCompositeOp: case ReflectCompositeOp: case ScreenCompositeOp: case SoftBurnCompositeOp: case SoftDodgeCompositeOp: case SoftLightCompositeOp: case StampCompositeOp: case VividLightCompositeOp: { alpha=RoundToUnity(Sa+Da-Sa*Da); break; } case DstAtopCompositeOp: case DstInCompositeOp: case InCompositeOp: case SrcInCompositeOp: { alpha=Sa*Da; break; } case DissolveCompositeOp: { alpha=source_dissolve*Sa*(-canvas_dissolve*Da)+source_dissolve*Sa+ canvas_dissolve*Da; break; } case DstOverCompositeOp: case OverCompositeOp: case SrcOverCompositeOp: { alpha=Sa+Da-Sa*Da; break; } case DstOutCompositeOp: { alpha=Da*(1.0-Sa); break; } case OutCompositeOp: case SrcOutCompositeOp: { alpha=Sa*(1.0-Da); break; } case BlendCompositeOp: case PlusCompositeOp: { alpha=RoundToUnity(source_dissolve*Sa+canvas_dissolve*Da); break; } case XorCompositeOp: { alpha=Sa+Da-2.0*Sa*Da; break; } case ModulusAddCompositeOp: { if ((Sa+Da) <= 1.0) { alpha=(Sa+Da); break; } alpha=((Sa+Da)-1.0); break; } case ModulusSubtractCompositeOp: { if ((Sa-Da) >= 0.0) { alpha=(Sa-Da); break; } alpha=((Sa-Da)+1.0); break; } default: { alpha=1.0; break; } } switch (compose) { case ColorizeCompositeOp: case HueCompositeOp: case LuminizeCompositeOp: case ModulateCompositeOp: case RMSECompositeOp: case SaturateCompositeOp: { GetPixelInfoPixel(source_image,p,&source_pixel); GetPixelInfoPixel(image,q,&canvas_pixel); break; } default: break; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { MagickRealType pixel, sans; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait source_traits = GetPixelChannelTraits(source_image,channel); if (traits == UndefinedPixelTrait) continue; if ((channel == AlphaPixelChannel) && ((traits & UpdatePixelTrait) != 0)) { /* Set alpha channel. */ switch (compose) { case AlphaCompositeOp: { pixel=QuantumRange*Sa; break; } case AtopCompositeOp: case CopyBlackCompositeOp: case CopyBlueCompositeOp: case CopyCyanCompositeOp: case CopyGreenCompositeOp: case CopyMagentaCompositeOp: case CopyRedCompositeOp: case CopyYellowCompositeOp: case SrcAtopCompositeOp: case DstCompositeOp: case NoCompositeOp: { pixel=QuantumRange*Da; break; } case ChangeMaskCompositeOp: { MagickBooleanType equivalent; if (Da < 0.5) { pixel=(MagickRealType) TransparentAlpha; break; } equivalent=IsFuzzyEquivalencePixel(source_image,p,image,q); if (equivalent != MagickFalse) pixel=(MagickRealType) TransparentAlpha; else pixel=(MagickRealType) OpaqueAlpha; break; } case ClearCompositeOp: { pixel=(MagickRealType) TransparentAlpha; break; } case ColorizeCompositeOp: case HueCompositeOp: case LuminizeCompositeOp: case RMSECompositeOp: case SaturateCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=QuantumRange*Da; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=QuantumRange*Sa; break; } if (Sa < Da) { pixel=QuantumRange*Da; break; } pixel=QuantumRange*Sa; break; } case CopyAlphaCompositeOp: { if (source_image->alpha_trait == UndefinedPixelTrait) pixel=GetPixelIntensity(source_image,p); else pixel=QuantumRange*Sa; break; } case BlurCompositeOp: case CopyCompositeOp: case DisplaceCompositeOp: case DistortCompositeOp: case DstAtopCompositeOp: case ReplaceCompositeOp: case SrcCompositeOp: { pixel=QuantumRange*Sa; break; } case DarkenIntensityCompositeOp: { pixel=Sa*GetPixelIntensity(source_image,p) < Da*GetPixelIntensity(image,q) ? Sa : Da; break; } case DifferenceCompositeOp: { pixel=QuantumRange*fabs(Sa-Da); break; } case FreezeCompositeOp: { pixel=QuantumRange*(1.0-(1.0-Sa)*(1.0-Sa)* PerceptibleReciprocal(Da)); if (pixel < 0.0) pixel=0.0; break; } case InterpolateCompositeOp: { pixel=QuantumRange*(0.5-0.25*cos(MagickPI*Sa)-0.25* cos(MagickPI*Da)); break; } case LightenIntensityCompositeOp: { pixel=Sa*GetPixelIntensity(source_image,p) > Da*GetPixelIntensity(image,q) ? Sa : Da; break; } case ModulateCompositeOp: { pixel=QuantumRange*Da; break; } case MultiplyCompositeOp: { pixel=QuantumRange*Sa*Da; break; } case NegateCompositeOp: { pixel=QuantumRange*((1.0-Sa-Da)); break; } case ReflectCompositeOp: { pixel=QuantumRange*(Sa*Sa*PerceptibleReciprocal(1.0-Da)); if (pixel > QuantumRange) pixel=QuantumRange; break; } case StampCompositeOp: { pixel=QuantumRange*(Sa+Da*Da-1.0); break; } case StereoCompositeOp: { pixel=QuantumRange*(Sa+Da)/2; break; } default: { pixel=QuantumRange*alpha; break; } } q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); continue; } if (source_traits == UndefinedPixelTrait) continue; /* Sc: source color. Dc: canvas color. */ Sc=(MagickRealType) GetPixelChannel(source_image,channel,p); Dc=(MagickRealType) q[i]; if ((traits & CopyPixelTrait) != 0) { /* Copy channel. */ q[i]=ClampToQuantum(Dc); continue; } /* Porter-Duff compositions: Sca: source normalized color multiplied by alpha. Dca: normalized canvas color multiplied by alpha. */ Sca=QuantumScale*Sa*Sc; Dca=QuantumScale*Da*Dc; SaSca=Sa*PerceptibleReciprocal(Sca); DcaDa=Dca*PerceptibleReciprocal(Da); switch (compose) { case DarkenCompositeOp: case LightenCompositeOp: case ModulusSubtractCompositeOp: { gamma=PerceptibleReciprocal(1.0-alpha); break; } default: { gamma=PerceptibleReciprocal(alpha); break; } } pixel=Dc; switch (compose) { case AlphaCompositeOp: { pixel=QuantumRange*Sa; break; } case AtopCompositeOp: case SrcAtopCompositeOp: { pixel=QuantumRange*(Sca*Da+Dca*(1.0-Sa)); break; } case BlendCompositeOp: { pixel=gamma*(source_dissolve*Sa*Sc+canvas_dissolve*Da*Dc); break; } case CopyCompositeOp: case ReplaceCompositeOp: case SrcCompositeOp: { pixel=QuantumRange*Sca; break; } case BlurCompositeOp: case DisplaceCompositeOp: case DistortCompositeOp: { pixel=Sc; break; } case BumpmapCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } pixel=QuantumScale*GetPixelIntensity(source_image,p)*Dc; break; } case ChangeMaskCompositeOp: { pixel=Dc; break; } case ClearCompositeOp: { pixel=0.0; break; } case ColorBurnCompositeOp: { if ((Sca == 0.0) && (Dca == Da)) { pixel=QuantumRange*gamma*(Sa*Da+Dca*(1.0-Sa)); break; } if (Sca == 0.0) { pixel=QuantumRange*gamma*(Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Sa*Da-Sa*Da*MagickMin(1.0,(1.0-DcaDa)* SaSca)+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case ColorDodgeCompositeOp: { if ((Sca*Da+Dca*Sa) >= Sa*Da) pixel=QuantumRange*gamma*(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa)); else pixel=QuantumRange*gamma*(Dca*Sa*Sa*PerceptibleReciprocal(Sa-Sca)+ Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case ColorizeCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=Sc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &sans,&sans,&luma); CompositeHCL(source_pixel.red,source_pixel.green,source_pixel.blue, &hue,&chroma,&sans); HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case CopyAlphaCompositeOp: { pixel=Dc; break; } case CopyBlackCompositeOp: { if (channel == BlackPixelChannel) pixel=(MagickRealType) GetPixelBlack(source_image,p); break; } case CopyBlueCompositeOp: case CopyYellowCompositeOp: { if (channel == BluePixelChannel) pixel=(MagickRealType) GetPixelBlue(source_image,p); break; } case CopyGreenCompositeOp: case CopyMagentaCompositeOp: { if (channel == GreenPixelChannel) pixel=(MagickRealType) GetPixelGreen(source_image,p); break; } case CopyRedCompositeOp: case CopyCyanCompositeOp: { if (channel == RedPixelChannel) pixel=(MagickRealType) GetPixelRed(source_image,p); break; } case DarkenCompositeOp: { /* Darken is equivalent to a 'Minimum' method OR a greyscale version of a binary 'Or' OR the 'Intersection' of pixel sets. */ if ((Sca*Da) < (Dca*Sa)) { pixel=QuantumRange*(Sca+Dca*(1.0-Sa)); break; } pixel=QuantumRange*(Dca+Sca*(1.0-Da)); break; } case DarkenIntensityCompositeOp: { pixel=Sa*GetPixelIntensity(source_image,p) < Da*GetPixelIntensity(image,q) ? Sc : Dc; break; } case DifferenceCompositeOp: { pixel=QuantumRange*gamma*(Sca+Dca-2.0*MagickMin(Sca*Da,Dca*Sa)); break; } case DissolveCompositeOp: { pixel=gamma*(source_dissolve*Sa*Sc-source_dissolve*Sa* canvas_dissolve*Da*Dc+canvas_dissolve*Da*Dc); break; } case DivideDstCompositeOp: { if ((fabs((double) Sca) < MagickEpsilon) && (fabs((double) Dca) < MagickEpsilon)) { pixel=QuantumRange*gamma*(Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } if (fabs((double) Dca) < MagickEpsilon) { pixel=QuantumRange*gamma*(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Sca*Da*Da/Dca+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case DivideSrcCompositeOp: { if ((fabs((double) Dca) < MagickEpsilon) && (fabs((double) Sca) < MagickEpsilon)) { pixel=QuantumRange*gamma*(Dca*(1.0-Sa)+Sca*(1.0-Da)); break; } if (fabs((double) Sca) < MagickEpsilon) { pixel=QuantumRange*gamma*(Da*Sa+Dca*(1.0-Sa)+Sca*(1.0-Da)); break; } pixel=QuantumRange*gamma*(Dca*Sa*SaSca+Dca*(1.0-Sa)+Sca*(1.0-Da)); break; } case DstAtopCompositeOp: { pixel=QuantumRange*(Dca*Sa+Sca*(1.0-Da)); break; } case DstCompositeOp: case NoCompositeOp: { pixel=QuantumRange*Dca; break; } case DstInCompositeOp: { pixel=QuantumRange*gamma*(Dca*Sa); break; } case DstOutCompositeOp: { pixel=QuantumRange*gamma*(Dca*(1.0-Sa)); break; } case DstOverCompositeOp: { pixel=QuantumRange*gamma*(Dca+Sca*(1.0-Da)); break; } case ExclusionCompositeOp: { pixel=QuantumRange*gamma*(Sca*Da+Dca*Sa-2.0*Sca*Dca+Sca*(1.0-Da)+ Dca*(1.0-Sa)); break; } case FreezeCompositeOp: { pixel=QuantumRange*gamma*(1.0-(1.0-Sca)*(1.0-Sca)* PerceptibleReciprocal(Dca)); if (pixel < 0.0) pixel=0.0; break; } case HardLightCompositeOp: { if ((2.0*Sca) < Sa) { pixel=QuantumRange*gamma*(2.0*Sca*Dca+Sca*(1.0-Da)+Dca*(1.0- Sa)); break; } pixel=QuantumRange*gamma*(Sa*Da-2.0*(Da-Dca)*(Sa-Sca)+Sca*(1.0-Da)+ Dca*(1.0-Sa)); break; } case HardMixCompositeOp: { pixel=gamma*(((Sca+Dca) < 1.0) ? 0.0 : QuantumRange); break; } case HueCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=Sc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &hue,&chroma,&luma); CompositeHCL(source_pixel.red,source_pixel.green,source_pixel.blue, &hue,&sans,&sans); HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case InCompositeOp: case SrcInCompositeOp: { pixel=QuantumRange*(Sca*Da); break; } case InterpolateCompositeOp: { pixel=QuantumRange*(0.5-0.25*cos(MagickPI*Sca)-0.25* cos(MagickPI*Dca)); break; } case LinearBurnCompositeOp: { /* LinearBurn: as defined by Abode Photoshop, according to http://www.simplefilter.de/en/basics/mixmods.html is: f(Sc,Dc) = Sc + Dc - 1 */ pixel=QuantumRange*gamma*(Sca+Dca-Sa*Da); break; } case LinearDodgeCompositeOp: { pixel=gamma*(Sa*Sc+Da*Dc); break; } case LinearLightCompositeOp: { /* LinearLight: as defined by Abode Photoshop, according to http://www.simplefilter.de/en/basics/mixmods.html is: f(Sc,Dc) = Dc + 2*Sc - 1 */ pixel=QuantumRange*gamma*((Sca-Sa)*Da+Sca+Dca); break; } case LightenCompositeOp: { if ((Sca*Da) > (Dca*Sa)) { pixel=QuantumRange*(Sca+Dca*(1.0-Sa)); break; } pixel=QuantumRange*(Dca+Sca*(1.0-Da)); break; } case LightenIntensityCompositeOp: { /* Lighten is equivalent to a 'Maximum' method OR a greyscale version of a binary 'And' OR the 'Union' of pixel sets. */ pixel=Sa*GetPixelIntensity(source_image,p) > Da*GetPixelIntensity(image,q) ? Sc : Dc; break; } case LuminizeCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=Sc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &hue,&chroma,&luma); CompositeHCL(source_pixel.red,source_pixel.green,source_pixel.blue, &sans,&sans,&luma); HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case MathematicsCompositeOp: { /* 'Mathematics' a free form user control mathematical composition is defined as... f(Sc,Dc) = A*Sc*Dc + B*Sc + C*Dc + D Where the arguments A,B,C,D are (currently) passed to composite as a command separated 'geometry' string in "compose:args" image artifact. A = a->rho, B = a->sigma, C = a->xi, D = a->psi Applying the SVG transparency formula (see above), we get... Dca' = Sa*Da*f(Sc,Dc) + Sca*(1.0-Da) + Dca*(1.0-Sa) Dca' = A*Sca*Dca + B*Sca*Da + C*Dca*Sa + D*Sa*Da + Sca*(1.0-Da) + Dca*(1.0-Sa) */ pixel=QuantumRange*gamma*(geometry_info.rho*Sca*Dca+ geometry_info.sigma*Sca*Da+geometry_info.xi*Dca*Sa+ geometry_info.psi*Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case MinusDstCompositeOp: { pixel=gamma*(Sa*Sc+Da*Dc-2.0*Da*Dc*Sa); break; } case MinusSrcCompositeOp: { /* Minus source from canvas. f(Sc,Dc) = Sc - Dc */ pixel=gamma*(Da*Dc+Sa*Sc-2.0*Sa*Sc*Da); break; } case ModulateCompositeOp: { ssize_t offset; if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } offset=(ssize_t) (GetPixelIntensity(source_image,p)-midpoint); if (offset == 0) { pixel=Dc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &hue,&chroma,&luma); luma+=(0.01*percent_luma*offset)/midpoint; chroma*=0.01*percent_chroma; HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case ModulusAddCompositeOp: { if ((Sca+Dca) <= 1.0) { pixel=QuantumRange*(Sca+Dca); break; } pixel=QuantumRange*((Sca+Dca)-1.0); break; } case ModulusSubtractCompositeOp: { if ((Sca-Dca) >= 0.0) { pixel=QuantumRange*(Sca-Dca); break; } pixel=QuantumRange*((Sca-Dca)+1.0); break; } case MultiplyCompositeOp: { pixel=QuantumRange*gamma*(Sca*Dca+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case NegateCompositeOp: { pixel=QuantumRange*(1.0-fabs(1.0-Sca-Dca)); break; } case OutCompositeOp: case SrcOutCompositeOp: { pixel=QuantumRange*(Sca*(1.0-Da)); break; } case OverCompositeOp: case SrcOverCompositeOp: { pixel=QuantumRange*gamma*(Sca+Dca*(1.0-Sa)); break; } case OverlayCompositeOp: { if ((2.0*Dca) < Da) { pixel=QuantumRange*gamma*(2.0*Dca*Sca+Dca*(1.0-Sa)+Sca*(1.0- Da)); break; } pixel=QuantumRange*gamma*(Da*Sa-2.0*(Sa-Sca)*(Da-Dca)+Dca*(1.0-Sa)+ Sca*(1.0-Da)); break; } case PegtopLightCompositeOp: { /* PegTop: A Soft-Light alternative: A continuous version of the Softlight function, producing very similar results. f(Sc,Dc) = Dc^2*(1-2*Sc) + 2*Sc*Dc http://www.pegtop.net/delphi/articles/blendmodes/softlight.htm. */ if (fabs((double) Da) < MagickEpsilon) { pixel=QuantumRange*gamma*Sca; break; } pixel=QuantumRange*gamma*(Dca*Dca*(Sa-2.0*Sca)/Da+Sca*(2.0*Dca+1.0- Da)+Dca*(1.0-Sa)); break; } case PinLightCompositeOp: { /* PinLight: A Photoshop 7 composition method http://www.simplefilter.de/en/basics/mixmods.html f(Sc,Dc) = Dc<2*Sc-1 ? 2*Sc-1 : Dc>2*Sc ? 2*Sc : Dc */ if ((Dca*Sa) < (Da*(2.0*Sca-Sa))) { pixel=QuantumRange*gamma*(Sca*(Da+1.0)-Sa*Da+Dca*(1.0-Sa)); break; } if ((Dca*Sa) > (2.0*Sca*Da)) { pixel=QuantumRange*gamma*(Sca*Da+Sca+Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Sca*(1.0-Da)+Dca); break; } case PlusCompositeOp: { pixel=QuantumRange*(Sca+Dca); break; } case ReflectCompositeOp: { pixel=QuantumRange*gamma*(Sca*Sca*PerceptibleReciprocal(1.0-Dca)); if (pixel > QuantumRange) pixel=QuantumRange; break; } case RMSECompositeOp: { double gray; if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=Sc; break; } gray=sqrt( (canvas_pixel.red-source_pixel.red)* (canvas_pixel.red-source_pixel.red)+ (canvas_pixel.green-source_pixel.green)* (canvas_pixel.green-source_pixel.green)+ (canvas_pixel.blue-source_pixel.blue)* (canvas_pixel.blue-source_pixel.blue)/3.0); switch (channel) { case RedPixelChannel: pixel=gray; break; case GreenPixelChannel: pixel=gray; break; case BluePixelChannel: pixel=gray; break; default: pixel=Dc; break; } break; } case SaturateCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=Sc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &hue,&chroma,&luma); CompositeHCL(source_pixel.red,source_pixel.green,source_pixel.blue, &sans,&chroma,&sans); HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case ScreenCompositeOp: { /* Screen: a negated multiply: f(Sc,Dc) = 1.0-(1.0-Sc)*(1.0-Dc) */ pixel=QuantumRange*gamma*(Sca+Dca-Sca*Dca); break; } case SoftBurnCompositeOp: { if ((Sca+Dca) < 1.0) pixel=QuantumRange*gamma*(0.5*Dca*PerceptibleReciprocal(1.0-Sca)); else pixel=QuantumRange*gamma*(1.0-0.5*(1.0-Sca)* PerceptibleReciprocal(Dca)); break; } case SoftDodgeCompositeOp: { if ((Sca+Dca) < 1.0) pixel=QuantumRange*gamma*(0.5*Sca*PerceptibleReciprocal(1.0-Dca)); else pixel=QuantumRange*gamma*(1.0-0.5*(1.0-Dca)* PerceptibleReciprocal(Sca)); break; } case SoftLightCompositeOp: { if ((2.0*Sca) < Sa) { pixel=QuantumRange*gamma*(Dca*(Sa+(2.0*Sca-Sa)*(1.0-DcaDa))+ Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } if (((2.0*Sca) > Sa) && ((4.0*Dca) <= Da)) { pixel=QuantumRange*gamma*(Dca*Sa+Da*(2.0*Sca-Sa)*(4.0*DcaDa* (4.0*DcaDa+1.0)*(DcaDa-1.0)+7.0*DcaDa)+Sca*(1.0-Da)+ Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Dca*Sa+Da*(2.0*Sca-Sa)*(pow(DcaDa,0.5)- DcaDa)+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case StampCompositeOp: { pixel=QuantumRange*(Sca+Dca*Dca-1.0); break; } case StereoCompositeOp: { if (channel == RedPixelChannel) pixel=(MagickRealType) GetPixelRed(source_image,p); break; } case ThresholdCompositeOp: { MagickRealType delta; delta=Sc-Dc; if ((MagickRealType) fabs((double) (2.0*delta)) < threshold) { pixel=gamma*Dc; break; } pixel=gamma*(Dc+delta*amount); break; } case VividLightCompositeOp: { /* VividLight: A Photoshop 7 composition method. See http://www.simplefilter.de/en/basics/mixmods.html. f(Sc,Dc) = (2*Sc < 1) ? 1-(1-Dc)/(2*Sc) : Dc/(2*(1-Sc)) */ if ((fabs((double) Sa) < MagickEpsilon) || (fabs((double) (Sca-Sa)) < MagickEpsilon)) { pixel=QuantumRange*gamma*(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } if ((2.0*Sca) <= Sa) { pixel=QuantumRange*gamma*(Sa*(Da+Sa*(Dca-Da)* PerceptibleReciprocal(2.0*Sca))+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Dca*Sa*Sa*PerceptibleReciprocal(2.0* (Sa-Sca))+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case XorCompositeOp: { pixel=QuantumRange*(Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } default: { pixel=Sc; break; } } q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); } p+=GetPixelChannels(source_image); channels=GetPixelChannels(source_image); if (p >= (pixels+channels*source_image->columns)) p=pixels; q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_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,CompositeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); if (canvas_image != (Image * ) NULL) canvas_image=DestroyImage(canvas_image); else source_image=DestroyImage(source_image); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T e x t u r e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TextureImage() repeatedly tiles the texture image across and down the image % canvas. % % The format of the TextureImage method is: % % MagickBooleanType TextureImage(Image *image,const Image *texture, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o texture_image: This image is the texture to layer on the background. % */ MagickExport MagickBooleanType TextureImage(Image *image,const Image *texture, ExceptionInfo *exception) { #define TextureImageTag "Texture/Image" CacheView *image_view, *texture_view; Image *texture_image; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (texture == (const Image *) NULL) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); texture_image=CloneImage(texture,0,0,MagickTrue,exception); if (texture_image == (const Image *) NULL) return(MagickFalse); (void) TransformImageColorspace(texture_image,image->colorspace,exception); (void) SetImageVirtualPixelMethod(texture_image,TileVirtualPixelMethod, exception); status=MagickTrue; if ((image->compose != CopyCompositeOp) && ((image->compose != OverCompositeOp) || (image->alpha_trait != UndefinedPixelTrait) || (texture_image->alpha_trait != UndefinedPixelTrait))) { /* Tile texture onto the image background. */ for (y=0; y < (ssize_t) image->rows; y+=(ssize_t) texture_image->rows) { ssize_t x; if (status == MagickFalse) continue; for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) texture_image->columns) { MagickBooleanType thread_status; thread_status=CompositeImage(image,texture_image,image->compose, MagickTrue,x+texture_image->tile_offset.x,y+ texture_image->tile_offset.y,exception); if (thread_status == MagickFalse) { status=thread_status; break; } } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,TextureImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } (void) SetImageProgress(image,TextureImageTag,(MagickOffsetType) image->rows,image->rows); texture_image=DestroyImage(texture_image); return(status); } /* Tile texture onto the image background (optimized). */ status=MagickTrue; texture_view=AcquireVirtualCacheView(texture_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(texture_image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; const Quantum *p, *pixels; ssize_t x; Quantum *q; size_t width; if (status == MagickFalse) continue; pixels=GetCacheViewVirtualPixels(texture_view,texture_image->tile_offset.x, (y+texture_image->tile_offset.y) % texture_image->rows, texture_image->columns,1,exception); q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if ((pixels == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) texture_image->columns) { ssize_t j; p=pixels; width=texture_image->columns; if ((x+(ssize_t) width) > (ssize_t) image->columns) width=image->columns-x; for (j=0; j < (ssize_t) width; j++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(texture_image); i++) { PixelChannel channel = GetPixelChannelChannel(texture_image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait texture_traits=GetPixelChannelTraits(texture_image, channel); if ((traits == UndefinedPixelTrait) || (texture_traits == UndefinedPixelTrait)) continue; SetPixelChannel(image,channel,p[i],q); } p+=GetPixelChannels(texture_image); q+=GetPixelChannels(image); } } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,TextureImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } texture_view=DestroyCacheView(texture_view); image_view=DestroyCacheView(image_view); texture_image=DestroyImage(texture_image); return(status); }
5690.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 4000. */ #include "3mm.h" /* Array initialization. */ static void init_array(int ni, int nj, int nk, int nl, int nm, DATA_TYPE POLYBENCH_2D(A,NI,NK,ni,nk), DATA_TYPE POLYBENCH_2D(B,NK,NJ,nk,nj), DATA_TYPE POLYBENCH_2D(C,NJ,NM,nj,nm), DATA_TYPE POLYBENCH_2D(D,NM,NL,nm,nl)) { int i, j; for (i = 0; i < ni; i++) for (j = 0; j < nk; j++) A[i][j] = ((DATA_TYPE) i*j) / ni; for (i = 0; i < nk; i++) for (j = 0; j < nj; j++) B[i][j] = ((DATA_TYPE) i*(j+1)) / nj; for (i = 0; i < nj; i++) for (j = 0; j < nm; j++) C[i][j] = ((DATA_TYPE) i*(j+3)) / nl; for (i = 0; i < nm; i++) for (j = 0; j < nl; j++) D[i][j] = ((DATA_TYPE) i*(j+2)) / nk; } /* 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 nl, DATA_TYPE POLYBENCH_2D(G,NI,NL,ni,nl)) { int i, j; for (i = 0; i < ni; i++) for (j = 0; j < nl; j++) { fprintf (stderr, DATA_PRINTF_MODIFIER, G[i][j]); if ((i * ni + 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_3mm(int ni, int nj, int nk, int nl, int nm, DATA_TYPE POLYBENCH_2D(E,NI,NJ,ni,nj), DATA_TYPE POLYBENCH_2D(A,NI,NK,ni,nk), DATA_TYPE POLYBENCH_2D(B,NK,NJ,nk,nj), DATA_TYPE POLYBENCH_2D(F,NJ,NL,nj,nl), DATA_TYPE POLYBENCH_2D(C,NJ,NM,nj,nm), DATA_TYPE POLYBENCH_2D(D,NM,NL,nm,nl), DATA_TYPE POLYBENCH_2D(G,NI,NL,ni,nl)) { int i, j, k; #pragma scop { /* E := A*B */ #pragma omp parallel for schedule(static, 28) simd for (i = 0; i < _PB_NI; i++) { for (j = 0; j < _PB_NJ; j++) { E[i][j] = 0; for (k = 0; k < _PB_NK; ++k) E[i][j] += A[i][k] * B[k][j]; } } /* F := C*D */ #pragma omp parallel for schedule(static, 28) simd for (i = 0; i < _PB_NJ; i++) { for (j = 0; j < _PB_NL; j++) { F[i][j] = 0; for (k = 0; k < _PB_NM; ++k) F[i][j] += C[i][k] * D[k][j]; } } /* G := E*F */ #pragma omp parallel for schedule(static, 28) simd for (i = 0; i < _PB_NI; i++) { for (j = 0; j < _PB_NL; j++) { G[i][j] = 0; for (k = 0; k < _PB_NJ; ++k) G[i][j] += E[i][k] * F[k][j]; } } } #pragma endscop } int main(int argc, char** argv) { /* Retrieve problem size. */ int ni = NI; int nj = NJ; int nk = NK; int nl = NL; int nm = NM; /* Variable declaration/allocation. */ POLYBENCH_2D_ARRAY_DECL(E, DATA_TYPE, NI, NJ, ni, nj); POLYBENCH_2D_ARRAY_DECL(A, DATA_TYPE, NI, NK, ni, nk); POLYBENCH_2D_ARRAY_DECL(B, DATA_TYPE, NK, NJ, nk, nj); POLYBENCH_2D_ARRAY_DECL(F, DATA_TYPE, NJ, NL, nj, nl); POLYBENCH_2D_ARRAY_DECL(C, DATA_TYPE, NJ, NM, nj, nm); POLYBENCH_2D_ARRAY_DECL(D, DATA_TYPE, NM, NL, nm, nl); POLYBENCH_2D_ARRAY_DECL(G, DATA_TYPE, NI, NL, ni, nl); /* Initialize array(s). */ init_array (ni, nj, nk, nl, nm, POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(B), POLYBENCH_ARRAY(C), POLYBENCH_ARRAY(D)); /* Start timer. */ polybench_start_instruments; /* Run kernel. */ kernel_3mm (ni, nj, nk, nl, nm, POLYBENCH_ARRAY(E), POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(B), POLYBENCH_ARRAY(F), POLYBENCH_ARRAY(C), POLYBENCH_ARRAY(D), POLYBENCH_ARRAY(G)); /* Stop and print timer. */ 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, nl, POLYBENCH_ARRAY(G))); /* Be clean. */ POLYBENCH_FREE_ARRAY(E); POLYBENCH_FREE_ARRAY(A); POLYBENCH_FREE_ARRAY(B); POLYBENCH_FREE_ARRAY(F); POLYBENCH_FREE_ARRAY(C); POLYBENCH_FREE_ARRAY(D); POLYBENCH_FREE_ARRAY(G); return 0; }
HybridRepCenterOrbitals.h
////////////////////////////////////////////////////////////////////////////////////// // This file is distributed under the University of Illinois/NCSA Open Source License. // See LICENSE file in top directory for details. // // Copyright (c) 2019 QMCPACK developers. // // File developed by: Ye Luo, yeluo@anl.gov, Argonne National Laboratory // // File created by: Ye Luo, yeluo@anl.gov, Argonne National Laboratory // ////////////////////////////////////////////////////////////////////////////////////// /** @file HybridRepCenterOrbitals.h * * Hybrid representation atomic centered orbitals */ #ifndef QMCPLUSPLUS_HYBRIDREP_CENTER_ORBITALS_H #define QMCPLUSPLUS_HYBRIDREP_CENTER_ORBITALS_H #include "Particle/DistanceTableData.h" #include "QMCWaveFunctions/LCAO/SoaSphericalTensor.h" #include "spline2/MultiBspline1D.hpp" #include "Numerics/SmoothFunctions.hpp" namespace qmcplusplus { template<typename ST> class AtomicOrbitals { public: static const int D = 3; using AtomicSplineType = typename bspline_traits<ST, 1>::SplineType; using AtomicBCType = typename bspline_traits<ST, 1>::BCType; using AtomicSingleSplineType = UBspline_1d_d; using PointType = TinyVector<ST, D>; using value_type = ST; using vContainer_type = aligned_vector<ST>; private: // near core cutoff ST rmin; // far from core cutoff, rmin_sqrt>=rmin ST rmin_sqrt; ST cutoff, cutoff_buffer, spline_radius, non_overlapping_radius; int spline_npoints, BaseN; int NumBands, Npad; PointType center_pos; const int lmax, lm_tot; SoaSphericalTensor<ST> Ylm; vContainer_type l_vals; vContainer_type r_power_minus_l; ///1D spline of radial functions of all the orbitals std::shared_ptr<MultiBspline1D<ST>> SplineInst; vContainer_type localV, localG, localL; public: AtomicOrbitals(int Lmax) : lmax(Lmax), lm_tot((Lmax + 1) * (Lmax + 1)), Ylm(Lmax) { r_power_minus_l.resize(lm_tot); l_vals.resize(lm_tot); for (int l = 0; l <= lmax; l++) for (int m = -l; m <= l; m++) l_vals[l * (l + 1) + m] = l; rmin = std::exp(std::log(std::numeric_limits<ST>::min()) / std::max(Lmax, 1)); rmin = std::max(rmin, std::numeric_limits<ST>::epsilon()); rmin_sqrt = std::max(rmin, std::sqrt(std::numeric_limits<ST>::epsilon())); } // accessing functions, const only ST getCutoff() const { return cutoff; } ST getCutoffBuffer() const { return cutoff_buffer; } ST getSplineRadius() const { return spline_radius; } ST getNonOverlappingRadius() const { return non_overlapping_radius; } int getSplineNpoints() const { return spline_npoints; } int getLmax() const { return lmax; } const PointType& getCenterPos() const { return center_pos; } inline void resizeStorage(size_t Nb) { NumBands = Nb; Npad = getAlignedSize<ST>(Nb); localV.resize(Npad * lm_tot); localG.resize(Npad * lm_tot); localL.resize(Npad * lm_tot); create_spline(); } void bcast_tables(Communicate* comm) { chunked_bcast(comm, SplineInst->getSplinePtr()); } void gather_tables(Communicate* comm, std::vector<int>& offset) { gatherv(comm, SplineInst->getSplinePtr(), Npad, offset); } template<typename PT, typename VT> inline void set_info(const PT& R, const VT& cutoff_in, const VT& cutoff_buffer_in, const VT& spline_radius_in, const VT& non_overlapping_radius_in, const int spline_npoints_in) { center_pos[0] = R[0]; center_pos[1] = R[1]; center_pos[2] = R[2]; cutoff = cutoff_in; cutoff_buffer = cutoff_buffer_in; spline_radius = spline_radius_in; spline_npoints = spline_npoints_in; non_overlapping_radius = non_overlapping_radius_in; BaseN = spline_npoints + 2; } inline void create_spline() { AtomicBCType bc; bc.lCode = FLAT; bc.rCode = NATURAL; Ugrid grid; grid.start = 0.0; grid.end = spline_radius; grid.num = spline_npoints; SplineInst = std::make_shared<MultiBspline1D<ST>>(); SplineInst->create(grid, bc, lm_tot * Npad); } inline size_t getSplineSizeInBytes() const { return SplineInst->sizeInByte(); } inline void flush_zero() { SplineInst->flush_zero(); } inline void set_spline(AtomicSingleSplineType* spline, int lm, int ispline) { SplineInst->copy_spline(spline, lm * Npad + ispline, 0, BaseN); } bool read_splines(hdf_archive& h5f) { einspline_engine<AtomicSplineType> bigtable(SplineInst->getSplinePtr()); int lmax_in, spline_npoints_in; ST spline_radius_in; if (!h5f.readEntry(lmax_in, "l_max") || lmax_in != lmax) return false; if (!h5f.readEntry(spline_radius_in, "spline_radius") || spline_radius_in != spline_radius) return false; if (!h5f.readEntry(spline_npoints_in, "spline_npoints") || spline_npoints_in != spline_npoints) return false; return h5f.readEntry(bigtable, "radial_spline"); } bool write_splines(hdf_archive& h5f) { bool success = true; success = success && h5f.writeEntry(spline_radius, "spline_radius"); success = success && h5f.writeEntry(spline_npoints, "spline_npoints"); success = success && h5f.writeEntry(lmax, "l_max"); success = success && h5f.writeEntry(center_pos, "position"); einspline_engine<AtomicSplineType> bigtable(SplineInst->getSplinePtr()); success = success && h5f.writeEntry(bigtable, "radial_spline"); return success; } //evaluate only V template<typename VV> inline void evaluate_v(const ST& r, const PointType& dr, VV& myV) { if (r > std::numeric_limits<ST>::epsilon()) Ylm.evaluateV(dr[0] / r, dr[1] / r, dr[2] / r); else Ylm.evaluateV(0, 0, 1); const ST* restrict Ylm_v = Ylm[0]; constexpr ST czero(0); ST* restrict val = myV.data(); ST* restrict local_val = localV.data(); std::fill(myV.begin(), myV.end(), czero); SplineInst->evaluate(r, localV); for (size_t lm = 0; lm < lm_tot; lm++) { #pragma omp simd aligned(val, local_val: QMC_SIMD_ALIGNMENT) for (size_t ib = 0; ib < myV.size(); ib++) val[ib] += Ylm_v[lm] * local_val[ib]; local_val += Npad; } } template<typename DISPL, typename VM> inline void evaluateValues(const DISPL& Displacements, const int center_idx, const ST& r, VM& multi_myV) { if (r <= std::numeric_limits<ST>::epsilon()) Ylm.evaluateV(0, 0, 1); const ST* restrict Ylm_v = Ylm[0]; const size_t m = multi_myV.cols(); constexpr ST czero(0); std::fill(multi_myV.begin(), multi_myV.end(), czero); SplineInst->evaluate(r, localV); for (int ivp = 0; ivp < Displacements.size(); ivp++) { PointType dr = Displacements[ivp][center_idx]; if (r > std::numeric_limits<ST>::epsilon()) Ylm.evaluateV(-dr[0] / r, -dr[1] / r, -dr[2] / r); ST* restrict val = multi_myV[ivp]; ST* restrict local_val = localV.data(); for (size_t lm = 0; lm < lm_tot; lm++) { #pragma omp simd aligned(val, local_val: QMC_SIMD_ALIGNMENT) for (size_t ib = 0; ib < m; ib++) val[ib] += Ylm_v[lm] * local_val[ib]; local_val += Npad; } } } //evaluate VGL template<typename VV, typename GV> inline void evaluate_vgl(const ST& r, const PointType& dr, VV& myV, GV& myG, VV& myL) { ST drx, dry, drz, rhatx, rhaty, rhatz, rinv; if (r > rmin) { rinv = 1.0 / r; } else { rinv = 0; } drx = dr[0]; dry = dr[1]; drz = dr[2]; rhatx = drx * rinv; rhaty = dry * rinv; rhatz = drz * rinv; Ylm.evaluateVGL(drx, dry, drz); const ST* restrict Ylm_v = Ylm[0]; const ST* restrict Ylm_gx = Ylm[1]; const ST* restrict Ylm_gy = Ylm[2]; const ST* restrict Ylm_gz = Ylm[3]; ST* restrict g0 = myG.data(0); ST* restrict g1 = myG.data(1); ST* restrict g2 = myG.data(2); constexpr ST czero(0), cone(1), chalf(0.5); std::fill(myV.begin(), myV.end(), czero); std::fill(g0, g0 + Npad, czero); std::fill(g1, g1 + Npad, czero); std::fill(g2, g2 + Npad, czero); std::fill(myL.begin(), myL.end(), czero); ST* restrict val = myV.data(); ST* restrict lapl = myL.data(); ST* restrict local_val = localV.data(); ST* restrict local_grad = localG.data(); ST* restrict local_lapl = localL.data(); SplineInst->evaluate_vgl(r, localV, localG, localL); if (r > rmin_sqrt) { // far from core r_power_minus_l[0] = cone; ST r_power_temp = cone; for (int l = 1; l <= lmax; l++) { r_power_temp *= rinv; for (int m = -l, lm = l * l; m <= l; m++, lm++) r_power_minus_l[lm] = r_power_temp; } for (size_t lm = 0; lm < lm_tot; lm++) { const ST& l_val = l_vals[lm]; const ST& r_power = r_power_minus_l[lm]; const ST Ylm_rescale = Ylm_v[lm] * r_power; const ST rhat_dot_G = (rhatx * Ylm_gx[lm] + rhaty * Ylm_gy[lm] + rhatz * Ylm_gz[lm]) * r_power; #pragma omp simd aligned(val, g0, g1, g2, lapl, local_val, local_grad, local_lapl: QMC_SIMD_ALIGNMENT) for (size_t ib = 0; ib < myV.size(); ib++) { const ST local_v = local_val[ib]; const ST local_g = local_grad[ib]; const ST local_l = local_lapl[ib]; // value const ST Vpart = l_val * rinv * local_v; val[ib] += Ylm_rescale * local_v; // grad const ST factor1 = local_g * Ylm_rescale; const ST factor2 = local_v * r_power; const ST factor3 = -Vpart * Ylm_rescale; g0[ib] += factor1 * rhatx + factor2 * Ylm_gx[lm] + factor3 * rhatx; g1[ib] += factor1 * rhaty + factor2 * Ylm_gy[lm] + factor3 * rhaty; g2[ib] += factor1 * rhatz + factor2 * Ylm_gz[lm] + factor3 * rhatz; // laplacian lapl[ib] += (local_l + (local_g * (2 - l_val) - Vpart) * rinv) * Ylm_rescale + (local_g - Vpart) * rhat_dot_G; } local_val += Npad; local_grad += Npad; local_lapl += Npad; } } else if (r > rmin) { // the possibility of reaching here is very very low std::cout << "Warning: an electron is very close to an ion, distance=" << r << " be careful!" << std::endl; // near core, kill divergence in the laplacian r_power_minus_l[0] = cone; ST r_power_temp = cone; for (int l = 1; l <= lmax; l++) { r_power_temp *= rinv; for (int m = -l, lm = l * l; m <= l; m++, lm++) r_power_minus_l[lm] = r_power_temp; } for (size_t lm = 0; lm < lm_tot; lm++) { const ST& l_val = l_vals[lm]; const ST& r_power = r_power_minus_l[lm]; const ST Ylm_rescale = Ylm_v[lm] * r_power; const ST rhat_dot_G = (Ylm_gx[lm] * rhatx + Ylm_gy[lm] * rhaty + Ylm_gz[lm] * rhatz) * r_power * r; #pragma omp simd aligned(val, g0, g1, g2, lapl, local_val, local_grad, local_lapl: QMC_SIMD_ALIGNMENT) for (size_t ib = 0; ib < myV.size(); ib++) { const ST local_v = local_val[ib]; const ST local_g = local_grad[ib]; const ST local_l = local_lapl[ib]; // value const ST Vpart = Ylm_rescale * local_v; val[ib] += Vpart; // grad const ST factor1 = local_g * Ylm_rescale; const ST factor2 = local_v * r_power; const ST factor3 = -l_val * Vpart * rinv; g0[ib] += factor1 * rhatx + factor2 * Ylm_gx[lm] + factor3 * rhatx; g1[ib] += factor1 * rhaty + factor2 * Ylm_gy[lm] + factor3 * rhaty; g2[ib] += factor1 * rhatz + factor2 * Ylm_gz[lm] + factor3 * rhatz; // laplacian lapl[ib] += local_l * (cone - chalf * l_val) * (3 * Ylm_rescale + rhat_dot_G); } local_val += Npad; local_grad += Npad; local_lapl += Npad; } } else { std::cout << "Warning: an electron is on top of an ion!" << std::endl; // strictly zero #pragma omp simd aligned(val, lapl, local_val, local_lapl: QMC_SIMD_ALIGNMENT) for (size_t ib = 0; ib < myV.size(); ib++) { // value val[ib] = Ylm_v[0] * local_val[ib]; // laplacian lapl[ib] = local_lapl[ib] * static_cast<ST>(3) * Ylm_v[0]; } local_val += Npad; local_grad += Npad; local_lapl += Npad; if (lm_tot > 0) { //std::cout << std::endl; for (size_t lm = 1; lm < 4; lm++) { #pragma omp simd aligned(g0, g1, g2, local_grad: QMC_SIMD_ALIGNMENT) for (size_t ib = 0; ib < myV.size(); ib++) { const ST local_g = local_grad[ib]; // grad g0[ib] += local_g * Ylm_gx[lm]; g1[ib] += local_g * Ylm_gy[lm]; g2[ib] += local_g * Ylm_gz[lm]; } local_grad += Npad; } } } } template<typename VV, typename GV, typename HT> void evaluate_vgh(const ST& r, const PointType& dr, VV& myV, GV& myG, HT& myH) { //Needed to do tensor product here APP_ABORT("AtomicOrbitals::evaluate_vgh"); } }; template<typename ST> class HybridRepCenterOrbitals { public: static const int D = 3; using PointType = typename AtomicOrbitals<ST>::PointType; using RealType = typename DistanceTableData::RealType; using PosType = typename DistanceTableData::PosType; private: ///atomic centers std::vector<AtomicOrbitals<ST>> AtomicCenters; ///table index int myTableID; ///mapping supercell to primitive cell std::vector<int> Super2Prim; ///r from distance table RealType dist_r; ///dr from distance table PosType dist_dr; ///for APBC PointType r_image; ///smooth function value RealType f; ///smooth function first derivative RealType df_dr; ///smooth function second derivative RealType d2f_dr2; ///smoothing schemes enum class smoothing_schemes { CONSISTENT = 0, SMOOTHALL, SMOOTHPARTIAL } smooth_scheme; /// smoothing function smoothing_functions smooth_func_id; public: HybridRepCenterOrbitals() {} void set_info(const ParticleSet& ions, ParticleSet& els, const std::vector<int>& mapping) { myTableID = els.addTable(ions); Super2Prim = mapping; } inline void resizeStorage(size_t Nb) { size_t SplineCoefsBytes = 0; for (int ic = 0; ic < AtomicCenters.size(); ic++) { AtomicCenters[ic].resizeStorage(Nb); SplineCoefsBytes += AtomicCenters[ic].getSplineSizeInBytes(); } app_log() << "MEMORY " << SplineCoefsBytes / (1 << 20) << " MB allocated " << "for the atomic radial splines in hybrid orbital representation" << std::endl; } void bcast_tables(Communicate* comm) { for (int ic = 0; ic < AtomicCenters.size(); ic++) AtomicCenters[ic].bcast_tables(comm); } void gather_atomic_tables(Communicate* comm, std::vector<int>& offset) { if (comm->size() == 1) return; for (int ic = 0; ic < AtomicCenters.size(); ic++) AtomicCenters[ic].gather_tables(comm, offset); } inline void flush_zero() { for (int ic = 0; ic < AtomicCenters.size(); ic++) AtomicCenters[ic].flush_zero(); } bool read_splines(hdf_archive& h5f) { bool success = true; size_t ncenter; success = success && h5f.push("atomic_centers", false); success = success && h5f.readEntry(ncenter, "number_of_centers"); if (!success) return success; if (ncenter != AtomicCenters.size()) success = false; // read splines of each center for (int ic = 0; ic < AtomicCenters.size(); ic++) { std::ostringstream gname; gname << "center_" << ic; success = success && h5f.push(gname.str().c_str(), false); success = success && AtomicCenters[ic].read_splines(h5f); h5f.pop(); } h5f.pop(); return success; } bool write_splines(hdf_archive& h5f) { bool success = true; int ncenter = AtomicCenters.size(); success = success && h5f.push("atomic_centers", true); success = success && h5f.writeEntry(ncenter, "number_of_centers"); // write splines of each center for (int ic = 0; ic < AtomicCenters.size(); ic++) { std::ostringstream gname; gname << "center_" << ic; success = success && h5f.push(gname.str().c_str(), true); success = success && AtomicCenters[ic].write_splines(h5f); h5f.pop(); } h5f.pop(); return success; } template<typename Cell> inline int get_bc_sign(const PointType& r, const Cell& PrimLattice, TinyVector<int, D>& HalfG) { int bc_sign = 0; PointType shift_unit = PrimLattice.toUnit(r - r_image); for (int i = 0; i < D; i++) { ST img = round(shift_unit[i]); bc_sign += HalfG[i] * (int)img; } return bc_sign; } //evaluate only V template<typename VV> inline RealType evaluate_v(const ParticleSet& P, const int iat, VV& myV) { const auto& ei_dist = P.getDistTable(myTableID); const int center_idx = ei_dist.get_first_neighbor(iat, dist_r, dist_dr, P.activePtcl == iat); if (center_idx < 0) abort(); auto& myCenter = AtomicCenters[Super2Prim[center_idx]]; if (dist_r < myCenter.getCutoff()) { PointType dr(-dist_dr[0], -dist_dr[1], -dist_dr[2]); r_image = myCenter.getCenterPos() + dr; myCenter.evaluate_v(dist_r, dr, myV); return smooth_function(myCenter.getCutoffBuffer(), myCenter.getCutoff(), dist_r); } return RealType(-1); } /* check if the batched algorithm is safe to operate * @param VP virtual particle set * @return true if it is safe * * When the reference electron in the NLPP evaluation has a distance larger than the non overlapping radius of the reference center. * Some qudrature points may get its SPOs evaluated from the nearest center which is not the reference center. * The batched algorthm forces the evaluation on the reference center and introduce some error. * In this case, the non-batched algorithm should be used. */ bool is_batched_safe(const VirtualParticleSet& VP) { const int center_idx = VP.refSourcePtcl; auto& myCenter = AtomicCenters[Super2Prim[center_idx]]; return VP.refPS.getDistTable(myTableID).getDistRow(VP.refPtcl)[center_idx] < myCenter.getNonOverlappingRadius(); } // C2C, C2R cases template<typename VM> inline RealType evaluateValuesC2X(const VirtualParticleSet& VP, VM& multi_myV) { const int center_idx = VP.refSourcePtcl; dist_r = VP.refPS.getDistTable(myTableID).getDistRow(VP.refPtcl)[center_idx]; auto& myCenter = AtomicCenters[Super2Prim[center_idx]]; if (dist_r < myCenter.getCutoff()) { myCenter.evaluateValues(VP.getDistTable(myTableID).getDisplacements(), center_idx, dist_r, multi_myV); return smooth_function(myCenter.getCutoffBuffer(), myCenter.getCutoff(), dist_r); } return RealType(-1); } // R2R case template<typename VM, typename Cell, typename SV> inline RealType evaluateValuesR2R(const VirtualParticleSet& VP, const Cell& PrimLattice, TinyVector<int, D>& HalfG, VM& multi_myV, SV& bc_signs) { const int center_idx = VP.refSourcePtcl; dist_r = VP.refPS.getDistTable(myTableID).getDistRow(VP.refPtcl)[center_idx]; auto& myCenter = AtomicCenters[Super2Prim[center_idx]]; if (dist_r < myCenter.getCutoff()) { const auto& displ = VP.getDistTable(myTableID).getDisplacements(); for (int ivp = 0; ivp < VP.getTotalNum(); ivp++) { r_image = myCenter.getCenterPos() - displ[ivp][center_idx]; bc_signs[ivp] = get_bc_sign(VP.R[ivp], PrimLattice, HalfG); ; } myCenter.evaluateValues(displ, center_idx, dist_r, multi_myV); return smooth_function(myCenter.getCutoffBuffer(), myCenter.getCutoff(), dist_r); } return RealType(-1); } //evaluate only VGL template<typename VV, typename GV> inline RealType evaluate_vgl(const ParticleSet& P, const int iat, VV& myV, GV& myG, VV& myL) { const auto& ei_dist = P.getDistTable(myTableID); const int center_idx = ei_dist.get_first_neighbor(iat, dist_r, dist_dr, P.activePtcl == iat); if (center_idx < 0) abort(); auto& myCenter = AtomicCenters[Super2Prim[center_idx]]; if (dist_r < myCenter.getCutoff()) { PointType dr(-dist_dr[0], -dist_dr[1], -dist_dr[2]); r_image = myCenter.getCenterPos() + dr; myCenter.evaluate_vgl(dist_r, dr, myV, myG, myL); return smooth_function(myCenter.getCutoffBuffer(), myCenter.getCutoff(), dist_r); } return RealType(-1); } //evaluate only VGH template<typename VV, typename GV, typename HT> inline RealType evaluate_vgh(const ParticleSet& P, const int iat, VV& myV, GV& myG, HT& myH) { const auto& ei_dist = P.getDistTable(myTableID); const int center_idx = ei_dist.get_first_neighbor(iat, dist_r, dist_dr, P.activePtcl == iat); if (center_idx < 0) abort(); auto& myCenter = AtomicCenters[Super2Prim[center_idx]]; if (dist_r < myCenter.getCutoff()) { PointType dr(-dist_dr[0], -dist_dr[1], -dist_dr[2]); r_image = myCenter.getCenterPos() + dr; myCenter.evaluate_vgh(dist_r, dr, myV, myG, myH); return smooth_function(myCenter.getCutoffBuffer(), myCenter.getCutoff(), dist_r); } return RealType(-1); } // interpolate buffer region, value only template<typename VV> inline void interpolate_buffer_v(VV& psi, const VV& psi_AO) const { const RealType cone(1); for (size_t i = 0; i < psi.size(); i++) psi[i] = psi_AO[i] * f + psi[i] * (cone - f); } // interpolate buffer region, value, gradients and laplacian template<typename VV, typename GV> inline void interpolate_buffer_vgl(VV& psi, GV& dpsi, VV& d2psi, const VV& psi_AO, const GV& dpsi_AO, const VV& d2psi_AO) const { const RealType cone(1), ctwo(2); const RealType rinv(1.0 / dist_r); if (smooth_scheme == smoothing_schemes::CONSISTENT) for (size_t i = 0; i < psi.size(); i++) { // psi, dpsi, d2psi are all consistent d2psi[i] = d2psi_AO[i] * f + d2psi[i] * (cone - f) + df_dr * rinv * ctwo * dot(dpsi[i] - dpsi_AO[i], dist_dr) + (psi_AO[i] - psi[i]) * (d2f_dr2 + ctwo * rinv * df_dr); dpsi[i] = dpsi_AO[i] * f + dpsi[i] * (cone - f) + df_dr * rinv * dist_dr * (psi[i] - psi_AO[i]); psi[i] = psi_AO[i] * f + psi[i] * (cone - f); } else if (smooth_scheme == smoothing_schemes::SMOOTHALL) for (size_t i = 0; i < psi.size(); i++) { d2psi[i] = d2psi_AO[i] * f + d2psi[i] * (cone - f); dpsi[i] = dpsi_AO[i] * f + dpsi[i] * (cone - f); psi[i] = psi_AO[i] * f + psi[i] * (cone - f); } else if (smooth_scheme == smoothing_schemes::SMOOTHPARTIAL) for (size_t i = 0; i < psi.size(); i++) { // dpsi, d2psi are consistent but psi is not. d2psi[i] = d2psi_AO[i] * f + d2psi[i] * (cone - f) + df_dr * rinv * ctwo * dot(dpsi[i] - dpsi_AO[i], dist_dr); dpsi[i] = dpsi_AO[i] * f + dpsi[i] * (cone - f); psi[i] = psi_AO[i] * f + psi[i] * (cone - f); } else throw std::runtime_error("Unknown smooth scheme!"); } inline RealType smooth_function(const ST& cutoff_buffer, const ST& cutoff, const RealType r) { const RealType cone(1); if (r < cutoff_buffer) return cone; const RealType scale = cone / (cutoff - cutoff_buffer); const RealType x = (r - cutoff_buffer) * scale; f = smoothing(smooth_func_id, x, df_dr, d2f_dr2); df_dr *= scale; d2f_dr2 *= scale * scale; return f; } template<class BSPLINESPO> friend class HybridRepSetReader; }; } // namespace qmcplusplus #endif
convolution_3x3_pack8to1_int8.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2022 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. #if !(__AVX512VNNI__ || __AVXVNNI__ || __AVX2__ || __XOP__) #if NCNN_RUNTIME_CPU && NCNN_AVX512VNNI && __AVX512F__ && !__AVX512VNNI__ void conv3x3s1_winograd43_transform_kernel_pack8to1_int8_sse_avx512vnni(const Mat& kernel, Mat& kernel_tm_pack8to1, int inch, int outch, const Option& opt); void conv3x3s1_winograd43_pack8to1_int8_sse_avx512vnni(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Option& opt); #endif #if NCNN_RUNTIME_CPU && NCNN_AVXVNNI && __AVX2__ && !__AVXVNNI__ void conv3x3s1_winograd43_transform_kernel_pack8to1_int8_sse_avxvnni(const Mat& kernel, Mat& kernel_tm_pack8to1, int inch, int outch, const Option& opt); void conv3x3s1_winograd43_pack8to1_int8_sse_avxvnni(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Option& opt); #endif #if NCNN_RUNTIME_CPU && NCNN_AVX2 && __AVX__ && !__AVX2__ void conv3x3s1_winograd43_transform_kernel_pack8to1_int8_sse_avx2(const Mat& kernel, Mat& kernel_tm_pack8to1, int inch, int outch, const Option& opt); void conv3x3s1_winograd43_pack8to1_int8_sse_avx2(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Option& opt); #endif #if NCNN_RUNTIME_CPU && NCNN_XOP && __SSE2__ && !__XOP__ void conv3x3s1_winograd43_transform_kernel_pack8to1_int8_sse_xop(const Mat& kernel, Mat& kernel_tm_pack8to1, int inch, int outch, const Option& opt); void conv3x3s1_winograd43_pack8to1_int8_sse_xop(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Option& opt); #endif #endif static void conv3x3s1_winograd43_transform_kernel_pack8to1_int8_sse(const Mat& kernel, Mat& kernel_tm_pack8to1, int inch, int outch, const Option& opt) { #if !(__AVX512VNNI__ || __AVXVNNI__ || __AVX2__ || __XOP__) #if NCNN_RUNTIME_CPU && NCNN_AVX512VNNI && __AVX512F__ && !__AVX512VNNI__ if (ncnn::cpu_support_x86_avx512_vnni()) { conv3x3s1_winograd43_transform_kernel_pack8to1_int8_sse_avx512vnni(kernel, kernel_tm_pack8to1, inch, outch, opt); return; } #endif #if NCNN_RUNTIME_CPU && NCNN_AVXVNNI && __AVX2__ && !__AVXVNNI__ if (ncnn::cpu_support_x86_avx_vnni()) { conv3x3s1_winograd43_transform_kernel_pack8to1_int8_sse_avxvnni(kernel, kernel_tm_pack8to1, inch, outch, opt); return; } #endif #if NCNN_RUNTIME_CPU && NCNN_AVX2 && __AVX__ && !__AVX2__ if (ncnn::cpu_support_x86_avx2()) { conv3x3s1_winograd43_transform_kernel_pack8to1_int8_sse_avx2(kernel, kernel_tm_pack8to1, inch, outch, opt); return; } #endif #if NCNN_RUNTIME_CPU && NCNN_XOP && __SSE2__ && !__XOP__ if (ncnn::cpu_support_x86_xop()) { conv3x3s1_winograd43_transform_kernel_pack8to1_int8_sse_xop(kernel, kernel_tm_pack8to1, inch, outch, opt); return; } #endif #endif // winograd43 transform kernel Mat kernel_tm(6 * 6, inch, outch, (size_t)2u); const short ktm[6][3] = { {6, 0, 0}, {-4, -4, -4}, {-4, 4, -4}, {1, 2, 4}, {1, -2, 4}, {0, 0, 6} }; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { for (int q = 0; q < inch; q++) { const signed char* kernel0 = (const signed char*)kernel + p * inch * 9 + q * 9; short* kernel_tm0 = kernel_tm.channel(p).row<short>(q); // transform kernel const signed char* k0 = kernel0; const signed char* k1 = kernel0 + 3; const signed char* k2 = kernel0 + 6; // h short tmp[6][3]; for (int i = 0; i < 6; i++) { tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2]; tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2]; tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2]; } // U for (int j = 0; j < 6; j++) { short* tmpp = &tmp[j][0]; for (int i = 0; i < 6; i++) { kernel_tm0[j * 6 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2]; } } } } // interleave // src = 36-inch-outch // dst = 4b-8a-inch/8a-36-outch/4b kernel_tm_pack8to1.create(8 * inch / 8, 36, outch / 4 + outch % 4, (size_t)2u * 4, 4); int p = 0; for (; p + 3 < outch; p += 4) { const Mat k0 = kernel_tm.channel(p); const Mat k1 = kernel_tm.channel(p + 1); const Mat k2 = kernel_tm.channel(p + 2); const Mat k3 = kernel_tm.channel(p + 3); Mat g0 = kernel_tm_pack8to1.channel(p / 4); for (int k = 0; k < 36; k++) { short* g00 = g0.row<short>(k); for (int q = 0; q + 7 < inch; q += 8) { #if __AVXVNNI__ || __AVX512VNNI__ || __XOP__ for (int i = 0; i < 4; i++) { const short* k00 = k0.row<const short>(q + i * 2); const short* k10 = k1.row<const short>(q + i * 2); const short* k20 = k2.row<const short>(q + i * 2); const short* k30 = k3.row<const short>(q + i * 2); const short* k01 = k0.row<const short>(q + i * 2 + 1); const short* k11 = k1.row<const short>(q + i * 2 + 1); const short* k21 = k2.row<const short>(q + i * 2 + 1); const short* k31 = k3.row<const short>(q + i * 2 + 1); g00[0] = k00[k]; g00[1] = k01[k]; g00[2] = k10[k]; g00[3] = k11[k]; g00[4] = k20[k]; g00[5] = k21[k]; g00[6] = k30[k]; g00[7] = k31[k]; g00 += 8; } #else for (int i = 0; i < 8; i++) { g00[0] = k0.row<const short>(q + i)[k]; g00[1] = k1.row<const short>(q + i)[k]; g00[2] = k2.row<const short>(q + i)[k]; g00[3] = k3.row<const short>(q + i)[k]; g00 += 4; } #endif } } } for (; p < outch; p++) { const Mat k0 = kernel_tm.channel(p); Mat g0 = kernel_tm_pack8to1.channel(p / 4 + p % 4); for (int k = 0; k < 36; k++) { short* g00 = g0.row<short>(k); for (int q = 0; q + 7 < inch; q += 8) { for (int i = 0; i < 8; i++) { g00[0] = k0.row<const short>(q + i)[k]; g00 += 1; } } } } } static void conv3x3s1_winograd43_pack8to1_int8_sse(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Option& opt) { #if !(__AVX512VNNI__ || __AVXVNNI__ || __AVX2__ || __XOP__) #if NCNN_RUNTIME_CPU && NCNN_AVX512VNNI && __AVX512F__ && !__AVX512VNNI__ if (ncnn::cpu_support_x86_avx512_vnni()) { conv3x3s1_winograd43_pack8to1_int8_sse_avx512vnni(bottom_blob, top_blob, kernel_tm, opt); return; } #endif #if NCNN_RUNTIME_CPU && NCNN_AVXVNNI && __AVX2__ && !__AVXVNNI__ if (ncnn::cpu_support_x86_avx_vnni()) { conv3x3s1_winograd43_pack8to1_int8_sse_avxvnni(bottom_blob, top_blob, kernel_tm, opt); return; } #endif #if NCNN_RUNTIME_CPU && NCNN_AVX2 && __AVX__ && !__AVX2__ if (ncnn::cpu_support_x86_avx2()) { conv3x3s1_winograd43_pack8to1_int8_sse_avx2(bottom_blob, top_blob, kernel_tm, opt); return; } #endif #if NCNN_RUNTIME_CPU && NCNN_XOP && __SSE2__ && !__XOP__ if (ncnn::cpu_support_x86_xop()) { conv3x3s1_winograd43_pack8to1_int8_sse_xop(bottom_blob, top_blob, kernel_tm, opt); return; } #endif #endif int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; // size_t elemsize = bottom_blob.elemsize; int elempack = bottom_blob.elempack; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // pad to 4n+2 Mat bottom_blob_bordered = bottom_blob; outw = (outw + 3) / 4 * 4; outh = (outh + 3) / 4 * 4; w = outw + 2; h = outh + 2; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, BORDER_CONSTANT, 0.f, opt); // BEGIN transform input Mat bottom_blob_tm; { int w_tm = outw / 4 * 6; int h_tm = outh / 4 * 6; const int tiles = w_tm / 6 * h_tm / 6; bottom_blob_tm.create(tiles, 36, inch, 2u * elempack, elempack, opt.workspace_allocator); // const float itm[4][4] = { // {4.0f, 0.0f, -5.0f, 0.0f, 1.0f, 0.0f}, // {0.0f,-4.0f, -4.0f, 1.0f, 1.0f, 0.0f}, // {0.0f, 4.0f, -4.0f,-1.0f, 1.0f, 0.0f}, // {0.0f,-2.0f, -1.0f, 2.0f, 1.0f, 0.0f}, // {0.0f, 2.0f, -1.0f,-2.0f, 1.0f, 0.0f}, // {0.0f, 4.0f, 0.0f,-5.0f, 0.0f, 1.0f} // }; // 0 = 4 * r00 - 5 * r02 + r04 // 1 = -4 * (r01 + r02) + r04 + r03 // 2 = 4 * (r01 - r02) + r04 - r03 // 3 = -2 * (r01 - r03) + r04 - r02 // 4 = 2 * (r01 - r03) + r04 - r02 // 5 = 4 * r01 - 5 * r03 + r05 #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < inch; q++) { const Mat img0 = bottom_blob_bordered.channel(q); Mat img0_tm = bottom_blob_tm.channel(q); short tmp[6][6][8]; // tile for (int i = 0; i < h_tm / 6; i++) { for (int j = 0; j < w_tm / 6; j++) { const signed char* r0 = img0.row<const signed char>(i * 4) + (j * 4) * 8; for (int m = 0; m < 6; m++) { // TODO use _mm_cvtepi8_epi16 on sse4.1 __m128i _r00_01 = _mm_loadu_si128((const __m128i*)r0); __m128i _r02_03 = _mm_loadu_si128((const __m128i*)(r0 + 16)); __m128i _r04_05 = _mm_loadu_si128((const __m128i*)(r0 + 32)); __m128i _extr0001 = _mm_cmpgt_epi8(_mm_setzero_si128(), _r00_01); __m128i _extr0203 = _mm_cmpgt_epi8(_mm_setzero_si128(), _r02_03); __m128i _extr0405 = _mm_cmpgt_epi8(_mm_setzero_si128(), _r04_05); __m128i _r00 = _mm_unpacklo_epi8(_r00_01, _extr0001); __m128i _r01 = _mm_unpackhi_epi8(_r00_01, _extr0001); __m128i _r02 = _mm_unpacklo_epi8(_r02_03, _extr0203); __m128i _r03 = _mm_unpackhi_epi8(_r02_03, _extr0203); __m128i _r04 = _mm_unpacklo_epi8(_r04_05, _extr0405); __m128i _r05 = _mm_unpackhi_epi8(_r04_05, _extr0405); __m128i _v5 = _mm_set1_epi16(5); __m128i _tmp0m = _mm_sub_epi16(_mm_add_epi16(_mm_slli_epi16(_r00, 2), _r04), _mm_mullo_epi16(_r02, _v5)); __m128i _tmp1m = _mm_sub_epi16(_mm_add_epi16(_r04, _r03), _mm_slli_epi16(_mm_add_epi16(_r01, _r02), 2)); __m128i _tmp2m = _mm_add_epi16(_mm_sub_epi16(_r04, _r03), _mm_slli_epi16(_mm_sub_epi16(_r01, _r02), 2)); __m128i _tmp3m = _mm_sub_epi16(_mm_sub_epi16(_r04, _r02), _mm_slli_epi16(_mm_sub_epi16(_r01, _r03), 1)); __m128i _tmp4m = _mm_add_epi16(_mm_sub_epi16(_r04, _r02), _mm_slli_epi16(_mm_sub_epi16(_r01, _r03), 1)); __m128i _tmp5m = _mm_sub_epi16(_mm_add_epi16(_mm_slli_epi16(_r01, 2), _r05), _mm_mullo_epi16(_r03, _v5)); _mm_storeu_si128((__m128i*)tmp[0][m], _tmp0m); _mm_storeu_si128((__m128i*)tmp[1][m], _tmp1m); _mm_storeu_si128((__m128i*)tmp[2][m], _tmp2m); _mm_storeu_si128((__m128i*)tmp[3][m], _tmp3m); _mm_storeu_si128((__m128i*)tmp[4][m], _tmp4m); _mm_storeu_si128((__m128i*)tmp[5][m], _tmp5m); r0 += w * 8; } short* r0_tm_0 = (short*)img0_tm + (i * w_tm / 6 + j) * 8; short* r0_tm_1 = r0_tm_0 + tiles * 8; short* r0_tm_2 = r0_tm_0 + tiles * 16; short* r0_tm_3 = r0_tm_0 + tiles * 24; short* r0_tm_4 = r0_tm_0 + tiles * 32; short* r0_tm_5 = r0_tm_0 + tiles * 40; for (int m = 0; m < 6; m++) { __m128i _tmp00 = _mm_loadu_si128((const __m128i*)tmp[m][0]); __m128i _tmp01 = _mm_loadu_si128((const __m128i*)tmp[m][1]); __m128i _tmp02 = _mm_loadu_si128((const __m128i*)tmp[m][2]); __m128i _tmp03 = _mm_loadu_si128((const __m128i*)tmp[m][3]); __m128i _tmp04 = _mm_loadu_si128((const __m128i*)tmp[m][4]); __m128i _tmp05 = _mm_loadu_si128((const __m128i*)tmp[m][5]); __m128i _v5 = _mm_set1_epi16(5); __m128i _r0tm0 = _mm_sub_epi16(_mm_add_epi16(_mm_slli_epi16(_tmp00, 2), _tmp04), _mm_mullo_epi16(_tmp02, _v5)); __m128i _r0tm1 = _mm_sub_epi16(_mm_add_epi16(_tmp04, _tmp03), _mm_slli_epi16(_mm_add_epi16(_tmp01, _tmp02), 2)); __m128i _r0tm2 = _mm_add_epi16(_mm_sub_epi16(_tmp04, _tmp03), _mm_slli_epi16(_mm_sub_epi16(_tmp01, _tmp02), 2)); __m128i _r0tm3 = _mm_sub_epi16(_mm_sub_epi16(_tmp04, _tmp02), _mm_slli_epi16(_mm_sub_epi16(_tmp01, _tmp03), 1)); __m128i _r0tm4 = _mm_add_epi16(_mm_sub_epi16(_tmp04, _tmp02), _mm_slli_epi16(_mm_sub_epi16(_tmp01, _tmp03), 1)); __m128i _r0tm5 = _mm_sub_epi16(_mm_add_epi16(_mm_slli_epi16(_tmp01, 2), _tmp05), _mm_mullo_epi16(_tmp03, _v5)); _mm_storeu_si128((__m128i*)r0_tm_0, _r0tm0); _mm_storeu_si128((__m128i*)r0_tm_1, _r0tm1); _mm_storeu_si128((__m128i*)r0_tm_2, _r0tm2); _mm_storeu_si128((__m128i*)r0_tm_3, _r0tm3); _mm_storeu_si128((__m128i*)r0_tm_4, _r0tm4); _mm_storeu_si128((__m128i*)r0_tm_5, _r0tm5); r0_tm_0 += tiles * 48; r0_tm_1 += tiles * 48; r0_tm_2 += tiles * 48; r0_tm_3 += tiles * 48; r0_tm_4 += tiles * 48; r0_tm_5 += tiles * 48; } } } } } bottom_blob_bordered = Mat(); // END transform input // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 4 * 6; int h_tm = outh / 4 * 6; const int tiles = h_tm / 6 * w_tm / 6; // permute // bottom_blob_tm.create(tiles, 36, inch, elemsize, elempack, opt.workspace_allocator); Mat bottom_blob_tm2; #if __AVX2__ if (tiles >= 4) bottom_blob_tm2.create(4 * inch, tiles / 4 + (tiles % 4) / 2 + tiles % 2, 36, 2u * elempack, elempack, opt.workspace_allocator); else if (tiles >= 2) bottom_blob_tm2.create(2 * inch, tiles / 2 + tiles % 2, 36, 2u * elempack, elempack, opt.workspace_allocator); else // if (tiles >= 1) bottom_blob_tm2.create(1 * inch, tiles, 36, 2u * elempack, elempack, opt.workspace_allocator); #else if (tiles >= 2) bottom_blob_tm2.create(2 * inch, tiles / 2 + tiles % 2, 36, 2u * elempack, elempack, opt.workspace_allocator); else // if (tiles >= 1) bottom_blob_tm2.create(1 * inch, tiles, 36, 2u * elempack, elempack, opt.workspace_allocator); #endif #pragma omp parallel for num_threads(opt.num_threads) for (int r = 0; r < 36; r++) { Mat tm2 = bottom_blob_tm2.channel(r); // tile int i = 0; #if __AVX2__ for (; i + 3 < tiles; i += 4) { short* tmpptr = tm2.row<short>(i / 4); const short* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 8; for (int q = 0; q < inch; q++) { __m256i _r0 = _mm256_loadu_si256((const __m256i*)r0); __m256i _r1 = _mm256_loadu_si256((const __m256i*)(r0 + 16)); _mm256_storeu_si256((__m256i*)tmpptr, _r0); _mm256_storeu_si256((__m256i*)(tmpptr + 16), _r1); r0 += bottom_blob_tm.cstep * 8; tmpptr += 32; } } #endif for (; i + 1 < tiles; i += 2) { #if __AVX2__ short* tmpptr = tm2.row<short>(i / 4 + (i % 4) / 2); #else short* tmpptr = tm2.row<short>(i / 2); #endif const short* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 8; for (int q = 0; q < inch; q++) { __m128i _r0 = _mm_loadu_si128((const __m128i*)r0); __m128i _r1 = _mm_loadu_si128((const __m128i*)(r0 + 8)); _mm_storeu_si128((__m128i*)tmpptr, _r0); _mm_storeu_si128((__m128i*)(tmpptr + 8), _r1); r0 += bottom_blob_tm.cstep * 8; tmpptr += 16; } } for (; i < tiles; i++) { #if __AVX2__ short* tmpptr = tm2.row<short>(i / 4 + (i % 4) / 2 + i % 2); #else short* tmpptr = tm2.row<short>(i / 2 + i % 2); #endif const short* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 8; for (int q = 0; q < inch; q++) { __m128i _r0 = _mm_loadu_si128((const __m128i*)r0); _mm_storeu_si128((__m128i*)tmpptr, _r0); r0 += bottom_blob_tm.cstep * 8; tmpptr += 8; } } } bottom_blob_tm = Mat(); // permute end top_blob_tm.create(tiles, 36, outch, 4u, 1, opt.workspace_allocator); int nn_outch = 0; int remain_outch_start = 0; nn_outch = outch >> 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 4; int* output0_tm = top_blob_tm.channel(p); int* output1_tm = top_blob_tm.channel(p + 1); int* output2_tm = top_blob_tm.channel(p + 2); int* output3_tm = top_blob_tm.channel(p + 3); const Mat kernel0_tm = kernel_tm.channel(p / 4); for (int r = 0; r < 36; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); int i = 0; #if __AVX2__ for (; i + 3 < tiles; i += 4) { const short* r0 = bb2.row<const short>(i / 4); const short* k0 = kernel0_tm.row<const short>(r); int nn = inch; // inch always > 0 __m256i _sum0_1 = _mm256_setzero_si256(); __m256i _sum2_3 = _mm256_setzero_si256(); __m256i _sum4_5 = _mm256_setzero_si256(); __m256i _sum6_7 = _mm256_setzero_si256(); for (int j = 0; j < nn; j++) { // 0 1 2 3 4 5 6 7 8 9 a b c d e f __m256i _val0 = _mm256_loadu_si256((const __m256i*)r0); __m256i _w01 = _mm256_loadu_si256((const __m256i*)k0); __m256i _w23 = _mm256_loadu_si256((const __m256i*)(k0 + 16)); #if __AVXVNNI__ || __AVX512VNNI__ __m256i _val0_0123 = _mm256_permutevar8x32_epi32(_val0, _mm256_set_epi32(1, 1, 1, 1, 0, 0, 0, 0)); __m256i _val0_4567 = _mm256_permutevar8x32_epi32(_val0, _mm256_set_epi32(3, 3, 3, 3, 2, 2, 2, 2)); __m256i _val0_89ab = _mm256_permutevar8x32_epi32(_val0, _mm256_set_epi32(5, 5, 5, 5, 4, 4, 4, 4)); __m256i _val0_cdef = _mm256_permutevar8x32_epi32(_val0, _mm256_set_epi32(7, 7, 7, 7, 6, 6, 6, 6)); _sum0_1 = _mm256_dpwssd_epi32(_sum0_1, _w01, _val0_0123); _sum2_3 = _mm256_dpwssd_epi32(_sum2_3, _w01, _val0_89ab); _sum0_1 = _mm256_dpwssd_epi32(_sum0_1, _w23, _val0_4567); _sum2_3 = _mm256_dpwssd_epi32(_sum2_3, _w23, _val0_cdef); #else // 0 0 1 1 2 2 3 3 8 8 9 9 a a b b // 4 4 5 5 6 6 7 7 c c d d e e f f __m256i _val0_0123_89ab = _mm256_unpacklo_epi16(_val0, _val0); __m256i _val0_4567_cdef = _mm256_unpackhi_epi16(_val0, _val0); __m256i _val0_0123 = _mm256_permutevar8x32_epi32(_val0_0123_89ab, _mm256_set_epi32(3, 3, 2, 2, 1, 1, 0, 0)); __m256i _val0_4567 = _mm256_permutevar8x32_epi32(_val0_4567_cdef, _mm256_set_epi32(3, 3, 2, 2, 1, 1, 0, 0)); __m256i _val0_89ab = _mm256_permutevar8x32_epi32(_val0_0123_89ab, _mm256_set_epi32(7, 7, 6, 6, 5, 5, 4, 4)); __m256i _val0_cdef = _mm256_permutevar8x32_epi32(_val0_4567_cdef, _mm256_set_epi32(7, 7, 6, 6, 5, 5, 4, 4)); __m256i _sl00_01 = _mm256_mullo_epi16(_w01, _val0_0123); __m256i _sh00_01 = _mm256_mulhi_epi16(_w01, _val0_0123); __m256i _sl10_11 = _mm256_mullo_epi16(_w01, _val0_89ab); __m256i _sh10_11 = _mm256_mulhi_epi16(_w01, _val0_89ab); __m256i _sl02_03 = _mm256_mullo_epi16(_w23, _val0_4567); __m256i _sh02_03 = _mm256_mulhi_epi16(_w23, _val0_4567); __m256i _sl12_13 = _mm256_mullo_epi16(_w23, _val0_cdef); __m256i _sh12_13 = _mm256_mulhi_epi16(_w23, _val0_cdef); _sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpacklo_epi16(_sl00_01, _sh00_01)); _sum2_3 = _mm256_add_epi32(_sum2_3, _mm256_unpacklo_epi16(_sl10_11, _sh10_11)); _sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpacklo_epi16(_sl02_03, _sh02_03)); _sum2_3 = _mm256_add_epi32(_sum2_3, _mm256_unpacklo_epi16(_sl12_13, _sh12_13)); _sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpackhi_epi16(_sl00_01, _sh00_01)); _sum2_3 = _mm256_add_epi32(_sum2_3, _mm256_unpackhi_epi16(_sl10_11, _sh10_11)); _sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpackhi_epi16(_sl02_03, _sh02_03)); _sum2_3 = _mm256_add_epi32(_sum2_3, _mm256_unpackhi_epi16(_sl12_13, _sh12_13)); #endif __m256i _val1 = _mm256_loadu_si256((const __m256i*)(r0 + 16)); #if __AVXVNNI__ || __AVX512VNNI__ __m256i _val1_0123 = _mm256_permutevar8x32_epi32(_val1, _mm256_set_epi32(1, 1, 1, 1, 0, 0, 0, 0)); __m256i _val1_4567 = _mm256_permutevar8x32_epi32(_val1, _mm256_set_epi32(3, 3, 3, 3, 2, 2, 2, 2)); __m256i _val1_89ab = _mm256_permutevar8x32_epi32(_val1, _mm256_set_epi32(5, 5, 5, 5, 4, 4, 4, 4)); __m256i _val1_cdef = _mm256_permutevar8x32_epi32(_val1, _mm256_set_epi32(7, 7, 7, 7, 6, 6, 6, 6)); _sum4_5 = _mm256_dpwssd_epi32(_sum4_5, _w01, _val1_0123); _sum6_7 = _mm256_dpwssd_epi32(_sum6_7, _w01, _val1_89ab); _sum4_5 = _mm256_dpwssd_epi32(_sum4_5, _w23, _val1_4567); _sum6_7 = _mm256_dpwssd_epi32(_sum6_7, _w23, _val1_cdef); #else __m256i _val1_0123_89ab = _mm256_unpacklo_epi16(_val1, _val1); __m256i _val1_4567_cdef = _mm256_unpackhi_epi16(_val1, _val1); __m256i _val1_0123 = _mm256_permutevar8x32_epi32(_val1_0123_89ab, _mm256_set_epi32(3, 3, 2, 2, 1, 1, 0, 0)); __m256i _val1_4567 = _mm256_permutevar8x32_epi32(_val1_4567_cdef, _mm256_set_epi32(3, 3, 2, 2, 1, 1, 0, 0)); __m256i _val1_89ab = _mm256_permutevar8x32_epi32(_val1_0123_89ab, _mm256_set_epi32(7, 7, 6, 6, 5, 5, 4, 4)); __m256i _val1_cdef = _mm256_permutevar8x32_epi32(_val1_4567_cdef, _mm256_set_epi32(7, 7, 6, 6, 5, 5, 4, 4)); __m256i _sl04_05 = _mm256_mullo_epi16(_w01, _val1_0123); __m256i _sh04_05 = _mm256_mulhi_epi16(_w01, _val1_0123); __m256i _sl14_15 = _mm256_mullo_epi16(_w01, _val1_89ab); __m256i _sh14_15 = _mm256_mulhi_epi16(_w01, _val1_89ab); __m256i _sl06_07 = _mm256_mullo_epi16(_w23, _val1_4567); __m256i _sh06_07 = _mm256_mulhi_epi16(_w23, _val1_4567); __m256i _sl16_17 = _mm256_mullo_epi16(_w23, _val1_cdef); __m256i _sh16_17 = _mm256_mulhi_epi16(_w23, _val1_cdef); _sum4_5 = _mm256_add_epi32(_sum4_5, _mm256_unpacklo_epi16(_sl04_05, _sh04_05)); _sum6_7 = _mm256_add_epi32(_sum6_7, _mm256_unpacklo_epi16(_sl14_15, _sh14_15)); _sum4_5 = _mm256_add_epi32(_sum4_5, _mm256_unpacklo_epi16(_sl06_07, _sh06_07)); _sum6_7 = _mm256_add_epi32(_sum6_7, _mm256_unpacklo_epi16(_sl16_17, _sh16_17)); _sum4_5 = _mm256_add_epi32(_sum4_5, _mm256_unpackhi_epi16(_sl04_05, _sh04_05)); _sum6_7 = _mm256_add_epi32(_sum6_7, _mm256_unpackhi_epi16(_sl14_15, _sh14_15)); _sum4_5 = _mm256_add_epi32(_sum4_5, _mm256_unpackhi_epi16(_sl06_07, _sh06_07)); _sum6_7 = _mm256_add_epi32(_sum6_7, _mm256_unpackhi_epi16(_sl16_17, _sh16_17)); #endif r0 += 32; k0 += 32; } __m256i _sum0_2 = _mm256_permute2x128_si256(_sum0_1, _sum2_3, _MM_SHUFFLE(0, 2, 0, 0)); __m256i _sum1_3 = _mm256_permute2x128_si256(_sum0_1, _sum2_3, _MM_SHUFFLE(0, 3, 0, 1)); _sum0_2 = _mm256_add_epi32(_sum0_2, _sum1_3); __m256i _sum4_6 = _mm256_permute2x128_si256(_sum4_5, _sum6_7, _MM_SHUFFLE(0, 2, 0, 0)); __m256i _sum5_7 = _mm256_permute2x128_si256(_sum4_5, _sum6_7, _MM_SHUFFLE(0, 3, 0, 1)); _sum4_6 = _mm256_add_epi32(_sum4_6, _sum5_7); int sum[16]; _mm256_storeu_si256((__m256i*)sum, _sum0_2); _mm256_storeu_si256((__m256i*)(sum + 8), _sum4_6); output0_tm[0] = sum[0]; output1_tm[0] = sum[1]; output2_tm[0] = sum[2]; output3_tm[0] = sum[3]; output0_tm[1] = sum[4]; output1_tm[1] = sum[5]; output2_tm[1] = sum[6]; output3_tm[1] = sum[7]; output0_tm[2] = sum[8]; output1_tm[2] = sum[9]; output2_tm[2] = sum[10]; output3_tm[2] = sum[11]; output0_tm[3] = sum[12]; output1_tm[3] = sum[13]; output2_tm[3] = sum[14]; output3_tm[3] = sum[15]; output0_tm += 4; output1_tm += 4; output2_tm += 4; output3_tm += 4; } #endif for (; i + 1 < tiles; i += 2) { #if __AVX2__ const short* r0 = bb2.row<const short>(i / 4 + (i % 4) / 2); #else const short* r0 = bb2.row<const short>(i / 2); #endif const short* k0 = kernel0_tm.row<const short>(r); int nn = inch; // inch always > 0 #if __AVX2__ __m256i _sum0_1 = _mm256_setzero_si256(); __m256i _sum2_3 = _mm256_setzero_si256(); #else __m128i _sum0 = _mm_setzero_si128(); __m128i _sum1 = _mm_setzero_si128(); __m128i _sum2 = _mm_setzero_si128(); __m128i _sum3 = _mm_setzero_si128(); #endif for (int j = 0; j < nn; j++) { #if __AVX2__ // 0 1 2 3 4 5 6 7 8 9 a b c d e f __m256i _val = _mm256_loadu_si256((const __m256i*)r0); __m256i _w01 = _mm256_loadu_si256((const __m256i*)k0); __m256i _w23 = _mm256_loadu_si256((const __m256i*)(k0 + 16)); #if __AVXVNNI__ || __AVX512VNNI__ __m256i _val_0123 = _mm256_permutevar8x32_epi32(_val, _mm256_set_epi32(1, 1, 1, 1, 0, 0, 0, 0)); __m256i _val_4567 = _mm256_permutevar8x32_epi32(_val, _mm256_set_epi32(3, 3, 3, 3, 2, 2, 2, 2)); __m256i _val_89ab = _mm256_permutevar8x32_epi32(_val, _mm256_set_epi32(5, 5, 5, 5, 4, 4, 4, 4)); __m256i _val_cdef = _mm256_permutevar8x32_epi32(_val, _mm256_set_epi32(7, 7, 7, 7, 6, 6, 6, 6)); _sum0_1 = _mm256_dpwssd_epi32(_sum0_1, _w01, _val_0123); _sum2_3 = _mm256_dpwssd_epi32(_sum2_3, _w01, _val_89ab); _sum0_1 = _mm256_dpwssd_epi32(_sum0_1, _w23, _val_4567); _sum2_3 = _mm256_dpwssd_epi32(_sum2_3, _w23, _val_cdef); #else __m256i _val_0123_89ab = _mm256_unpacklo_epi16(_val, _val); __m256i _val_4567_cdef = _mm256_unpackhi_epi16(_val, _val); __m256i _val_0123 = _mm256_permutevar8x32_epi32(_val_0123_89ab, _mm256_set_epi32(3, 3, 2, 2, 1, 1, 0, 0)); __m256i _val_4567 = _mm256_permutevar8x32_epi32(_val_4567_cdef, _mm256_set_epi32(3, 3, 2, 2, 1, 1, 0, 0)); __m256i _val_89ab = _mm256_permutevar8x32_epi32(_val_0123_89ab, _mm256_set_epi32(7, 7, 6, 6, 5, 5, 4, 4)); __m256i _val_cdef = _mm256_permutevar8x32_epi32(_val_4567_cdef, _mm256_set_epi32(7, 7, 6, 6, 5, 5, 4, 4)); __m256i _sl00_01 = _mm256_mullo_epi16(_w01, _val_0123); __m256i _sh00_01 = _mm256_mulhi_epi16(_w01, _val_0123); __m256i _sl10_11 = _mm256_mullo_epi16(_w01, _val_89ab); __m256i _sh10_11 = _mm256_mulhi_epi16(_w01, _val_89ab); __m256i _sl02_03 = _mm256_mullo_epi16(_w23, _val_4567); __m256i _sh02_03 = _mm256_mulhi_epi16(_w23, _val_4567); __m256i _sl12_13 = _mm256_mullo_epi16(_w23, _val_cdef); __m256i _sh12_13 = _mm256_mulhi_epi16(_w23, _val_cdef); _sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpacklo_epi16(_sl00_01, _sh00_01)); _sum2_3 = _mm256_add_epi32(_sum2_3, _mm256_unpacklo_epi16(_sl10_11, _sh10_11)); _sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpacklo_epi16(_sl02_03, _sh02_03)); _sum2_3 = _mm256_add_epi32(_sum2_3, _mm256_unpacklo_epi16(_sl12_13, _sh12_13)); _sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpackhi_epi16(_sl00_01, _sh00_01)); _sum2_3 = _mm256_add_epi32(_sum2_3, _mm256_unpackhi_epi16(_sl10_11, _sh10_11)); _sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpackhi_epi16(_sl02_03, _sh02_03)); _sum2_3 = _mm256_add_epi32(_sum2_3, _mm256_unpackhi_epi16(_sl12_13, _sh12_13)); #endif #else // 0 1 2 3 4 5 6 7 __m128i _val0 = _mm_loadu_si128((const __m128i*)r0); __m128i _val1 = _mm_loadu_si128((const __m128i*)(r0 + 8)); __m128i _w0 = _mm_loadu_si128((const __m128i*)k0); __m128i _w1 = _mm_loadu_si128((const __m128i*)(k0 + 8)); __m128i _w2 = _mm_loadu_si128((const __m128i*)(k0 + 16)); __m128i _w3 = _mm_loadu_si128((const __m128i*)(k0 + 24)); #if __XOP__ __m128i _val0_01 = _mm_shuffle_epi32(_val0, _MM_SHUFFLE(0, 0, 0, 0)); __m128i _val0_23 = _mm_shuffle_epi32(_val0, _MM_SHUFFLE(1, 1, 1, 1)); __m128i _val0_45 = _mm_shuffle_epi32(_val0, _MM_SHUFFLE(2, 2, 2, 2)); __m128i _val0_67 = _mm_shuffle_epi32(_val0, _MM_SHUFFLE(3, 3, 3, 3)); __m128i _val1_01 = _mm_shuffle_epi32(_val1, _MM_SHUFFLE(0, 0, 0, 0)); __m128i _val1_23 = _mm_shuffle_epi32(_val1, _MM_SHUFFLE(1, 1, 1, 1)); __m128i _val1_45 = _mm_shuffle_epi32(_val1, _MM_SHUFFLE(2, 2, 2, 2)); __m128i _val1_67 = _mm_shuffle_epi32(_val1, _MM_SHUFFLE(3, 3, 3, 3)); _sum0 = _mm_maddd_epi16(_val0_01, _w0, _sum0); _sum1 = _mm_maddd_epi16(_val0_23, _w1, _sum1); _sum2 = _mm_maddd_epi16(_val1_01, _w0, _sum2); _sum3 = _mm_maddd_epi16(_val1_23, _w1, _sum3); _sum0 = _mm_maddd_epi16(_val0_45, _w2, _sum0); _sum1 = _mm_maddd_epi16(_val0_67, _w3, _sum1); _sum2 = _mm_maddd_epi16(_val1_45, _w2, _sum2); _sum3 = _mm_maddd_epi16(_val1_67, _w3, _sum3); #else // 0 0 1 1 2 2 3 3 // 4 4 5 5 6 6 7 7 __m128i _val0_0123 = _mm_unpacklo_epi16(_val0, _val0); __m128i _val0_4567 = _mm_unpackhi_epi16(_val0, _val0); __m128i _val1_0123 = _mm_unpacklo_epi16(_val1, _val1); __m128i _val1_4567 = _mm_unpackhi_epi16(_val1, _val1); __m128i _val0_01 = _mm_unpacklo_epi32(_val0_0123, _val0_0123); __m128i _val0_23 = _mm_unpackhi_epi32(_val0_0123, _val0_0123); __m128i _val0_45 = _mm_unpacklo_epi32(_val0_4567, _val0_4567); __m128i _val0_67 = _mm_unpackhi_epi32(_val0_4567, _val0_4567); __m128i _val1_01 = _mm_unpacklo_epi32(_val1_0123, _val1_0123); __m128i _val1_23 = _mm_unpackhi_epi32(_val1_0123, _val1_0123); __m128i _val1_45 = _mm_unpacklo_epi32(_val1_4567, _val1_4567); __m128i _val1_67 = _mm_unpackhi_epi32(_val1_4567, _val1_4567); __m128i _sl00 = _mm_mullo_epi16(_w0, _val0_01); __m128i _sh00 = _mm_mulhi_epi16(_w0, _val0_01); __m128i _sl10 = _mm_mullo_epi16(_w0, _val1_01); __m128i _sh10 = _mm_mulhi_epi16(_w0, _val1_01); __m128i _sl01 = _mm_mullo_epi16(_w1, _val0_23); __m128i _sh01 = _mm_mulhi_epi16(_w1, _val0_23); __m128i _sl11 = _mm_mullo_epi16(_w1, _val1_23); __m128i _sh11 = _mm_mulhi_epi16(_w1, _val1_23); __m128i _sl02 = _mm_mullo_epi16(_w2, _val0_45); __m128i _sh02 = _mm_mulhi_epi16(_w2, _val0_45); __m128i _sl12 = _mm_mullo_epi16(_w2, _val1_45); __m128i _sh12 = _mm_mulhi_epi16(_w2, _val1_45); __m128i _sl03 = _mm_mullo_epi16(_w3, _val0_67); __m128i _sh03 = _mm_mulhi_epi16(_w3, _val0_67); __m128i _sl13 = _mm_mullo_epi16(_w3, _val1_67); __m128i _sh13 = _mm_mulhi_epi16(_w3, _val1_67); _sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl00, _sh00)); _sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl00, _sh00)); _sum2 = _mm_add_epi32(_sum2, _mm_unpacklo_epi16(_sl10, _sh10)); _sum3 = _mm_add_epi32(_sum3, _mm_unpackhi_epi16(_sl10, _sh10)); _sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl01, _sh01)); _sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl01, _sh01)); _sum2 = _mm_add_epi32(_sum2, _mm_unpacklo_epi16(_sl11, _sh11)); _sum3 = _mm_add_epi32(_sum3, _mm_unpackhi_epi16(_sl11, _sh11)); _sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl02, _sh02)); _sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl02, _sh02)); _sum2 = _mm_add_epi32(_sum2, _mm_unpacklo_epi16(_sl12, _sh12)); _sum3 = _mm_add_epi32(_sum3, _mm_unpackhi_epi16(_sl12, _sh12)); _sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl03, _sh03)); _sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl03, _sh03)); _sum2 = _mm_add_epi32(_sum2, _mm_unpacklo_epi16(_sl13, _sh13)); _sum3 = _mm_add_epi32(_sum3, _mm_unpackhi_epi16(_sl13, _sh13)); #endif #endif r0 += 16; k0 += 32; } #if __AVX2__ __m256i _sum0_2 = _mm256_permute2x128_si256(_sum0_1, _sum2_3, _MM_SHUFFLE(0, 2, 0, 0)); __m256i _sum1_3 = _mm256_permute2x128_si256(_sum0_1, _sum2_3, _MM_SHUFFLE(0, 3, 0, 1)); _sum0_2 = _mm256_add_epi32(_sum0_2, _sum1_3); int sum[8]; _mm256_storeu_si256((__m256i*)sum, _sum0_2); #else _sum0 = _mm_add_epi32(_sum0, _sum1); _sum2 = _mm_add_epi32(_sum2, _sum3); int sum[8]; _mm_storeu_si128((__m128i*)sum, _sum0); _mm_storeu_si128((__m128i*)(sum + 4), _sum2); #endif output0_tm[0] = sum[0]; output1_tm[0] = sum[1]; output2_tm[0] = sum[2]; output3_tm[0] = sum[3]; output0_tm[1] = sum[4]; output1_tm[1] = sum[5]; output2_tm[1] = sum[6]; output3_tm[1] = sum[7]; output0_tm += 2; output1_tm += 2; output2_tm += 2; output3_tm += 2; } for (; i < tiles; i++) { #if __AVX2__ const short* r0 = bb2.row<const short>(i / 4 + (i % 4) / 2 + i % 2); #else const short* r0 = bb2.row<const short>(i / 2 + i % 2); #endif const short* k0 = kernel0_tm.row<const short>(r); int nn = inch; // inch always > 0 #if __AVX2__ __m256i _sum0_1 = _mm256_setzero_si256(); #else __m128i _sum0 = _mm_setzero_si128(); __m128i _sum1 = _mm_setzero_si128(); #endif for (int j = 0; j < nn; j++) { // 0 1 2 3 4 5 6 7 __m128i _val = _mm_loadu_si128((const __m128i*)r0); #if __AVX2__ __m256i _w01 = _mm256_loadu_si256((const __m256i*)k0); __m256i _w23 = _mm256_loadu_si256((const __m256i*)(k0 + 16)); #if __AVXVNNI__ || __AVX512VNNI__ // 0 1 0 1 x x x x // 0 1 0 1 0 1 0 1 __m128i _val_01 = _mm_shuffle_epi32(_val, _MM_SHUFFLE(0, 0, 0, 0)); __m128i _val_23 = _mm_shuffle_epi32(_val, _MM_SHUFFLE(1, 1, 1, 1)); __m128i _val_45 = _mm_shuffle_epi32(_val, _MM_SHUFFLE(2, 2, 2, 2)); __m128i _val_67 = _mm_shuffle_epi32(_val, _MM_SHUFFLE(3, 3, 3, 3)); __m256i _val_0123 = _mm256_inserti128_si256(_mm256_castsi128_si256(_val_01), _val_23, 1); __m256i _val_4567 = _mm256_inserti128_si256(_mm256_castsi128_si256(_val_45), _val_67, 1); _sum0_1 = _mm256_dpwssd_epi32(_sum0_1, _w01, _val_0123); _sum0_1 = _mm256_dpwssd_epi32(_sum0_1, _w23, _val_4567); #else // 0 0 1 1 2 2 3 3 // 4 4 5 5 6 6 7 7 __m256i _val_0123 = _mm256_castsi128_si256(_mm_unpacklo_epi16(_val, _val)); __m256i _val_4567 = _mm256_castsi128_si256(_mm_unpackhi_epi16(_val, _val)); _val_0123 = _mm256_permutevar8x32_epi32(_val_0123, _mm256_set_epi32(3, 3, 2, 2, 1, 1, 0, 0)); _val_4567 = _mm256_permutevar8x32_epi32(_val_4567, _mm256_set_epi32(3, 3, 2, 2, 1, 1, 0, 0)); __m256i _sl00_01 = _mm256_mullo_epi16(_w01, _val_0123); __m256i _sh00_01 = _mm256_mulhi_epi16(_w01, _val_0123); __m256i _sl02_03 = _mm256_mullo_epi16(_w23, _val_4567); __m256i _sh02_03 = _mm256_mulhi_epi16(_w23, _val_4567); _sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpacklo_epi16(_sl00_01, _sh00_01)); _sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpacklo_epi16(_sl02_03, _sh02_03)); _sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpackhi_epi16(_sl00_01, _sh00_01)); _sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpackhi_epi16(_sl02_03, _sh02_03)); #endif #else __m128i _w0 = _mm_loadu_si128((const __m128i*)k0); __m128i _w1 = _mm_loadu_si128((const __m128i*)(k0 + 8)); __m128i _w2 = _mm_loadu_si128((const __m128i*)(k0 + 16)); __m128i _w3 = _mm_loadu_si128((const __m128i*)(k0 + 24)); #if __XOP__ __m128i _val01 = _mm_shuffle_epi32(_val, _MM_SHUFFLE(0, 0, 0, 0)); __m128i _val23 = _mm_shuffle_epi32(_val, _MM_SHUFFLE(1, 1, 1, 1)); __m128i _val45 = _mm_shuffle_epi32(_val, _MM_SHUFFLE(2, 2, 2, 2)); __m128i _val67 = _mm_shuffle_epi32(_val, _MM_SHUFFLE(3, 3, 3, 3)); _sum0 = _mm_maddd_epi16(_val01, _w0, _sum0); _sum1 = _mm_maddd_epi16(_val23, _w1, _sum1); _sum0 = _mm_maddd_epi16(_val45, _w2, _sum0); _sum1 = _mm_maddd_epi16(_val67, _w3, _sum1); #else // 0 0 1 1 2 2 3 3 // 4 4 5 5 6 6 7 7 __m128i _val_0123 = _mm_unpacklo_epi16(_val, _val); __m128i _val_4567 = _mm_unpackhi_epi16(_val, _val); __m128i _val01 = _mm_unpacklo_epi32(_val_0123, _val_0123); __m128i _val23 = _mm_unpackhi_epi32(_val_0123, _val_0123); __m128i _val45 = _mm_unpacklo_epi32(_val_4567, _val_4567); __m128i _val67 = _mm_unpackhi_epi32(_val_4567, _val_4567); __m128i _sl0 = _mm_mullo_epi16(_w0, _val01); __m128i _sh0 = _mm_mulhi_epi16(_w0, _val01); __m128i _sl1 = _mm_mullo_epi16(_w1, _val23); __m128i _sh1 = _mm_mulhi_epi16(_w1, _val23); __m128i _sl2 = _mm_mullo_epi16(_w2, _val45); __m128i _sh2 = _mm_mulhi_epi16(_w2, _val45); __m128i _sl3 = _mm_mullo_epi16(_w3, _val67); __m128i _sh3 = _mm_mulhi_epi16(_w3, _val67); _sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl0, _sh0)); _sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl0, _sh0)); _sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl1, _sh1)); _sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl1, _sh1)); _sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl2, _sh2)); _sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl2, _sh2)); _sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl3, _sh3)); _sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl3, _sh3)); #endif #endif r0 += 8; k0 += 32; } #if __AVX2__ __m128i _sum0 = _mm256_extracti128_si256(_sum0_1, 0); __m128i _sum1 = _mm256_extracti128_si256(_sum0_1, 1); #endif _sum0 = _mm_add_epi32(_sum0, _sum1); int sum[4]; _mm_storeu_si128((__m128i*)sum, _sum0); output0_tm[0] = sum[0]; output1_tm[0] = sum[1]; output2_tm[0] = sum[2]; output3_tm[0] = sum[3]; output0_tm += 1; output1_tm += 1; output2_tm += 1; output3_tm += 1; } } } remain_outch_start += nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { int* output0_tm = top_blob_tm.channel(p); const Mat kernel0_tm = kernel_tm.channel(p / 4 + p % 4); for (int r = 0; r < 36; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); int i = 0; #if __AVX2__ for (; i + 3 < tiles; i += 4) { const short* r0 = bb2.row<const short>(i / 4); const short* k0 = kernel0_tm.row<const short>(r); __m128i _sum0 = _mm_setzero_si128(); __m128i _sum1 = _mm_setzero_si128(); __m128i _sum2 = _mm_setzero_si128(); __m128i _sum3 = _mm_setzero_si128(); __m128i _sum4 = _mm_setzero_si128(); __m128i _sum5 = _mm_setzero_si128(); __m128i _sum6 = _mm_setzero_si128(); __m128i _sum7 = _mm_setzero_si128(); for (int q = 0; q < inch; q++) { __m128i _val0 = _mm_loadu_si128((const __m128i*)r0); __m128i _val1 = _mm_loadu_si128((const __m128i*)(r0 + 8)); __m128i _val2 = _mm_loadu_si128((const __m128i*)(r0 + 16)); __m128i _val3 = _mm_loadu_si128((const __m128i*)(r0 + 24)); __m128i _w0 = _mm_loadu_si128((const __m128i*)k0); __m128i _sl0 = _mm_mullo_epi16(_val0, _w0); __m128i _sh0 = _mm_mulhi_epi16(_val0, _w0); __m128i _sl1 = _mm_mullo_epi16(_val1, _w0); __m128i _sh1 = _mm_mulhi_epi16(_val1, _w0); __m128i _sl2 = _mm_mullo_epi16(_val2, _w0); __m128i _sh2 = _mm_mulhi_epi16(_val2, _w0); __m128i _sl3 = _mm_mullo_epi16(_val3, _w0); __m128i _sh3 = _mm_mulhi_epi16(_val3, _w0); _sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl0, _sh0)); _sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl0, _sh0)); _sum2 = _mm_add_epi32(_sum2, _mm_unpacklo_epi16(_sl1, _sh1)); _sum3 = _mm_add_epi32(_sum3, _mm_unpackhi_epi16(_sl1, _sh1)); _sum4 = _mm_add_epi32(_sum4, _mm_unpacklo_epi16(_sl2, _sh2)); _sum5 = _mm_add_epi32(_sum5, _mm_unpackhi_epi16(_sl2, _sh2)); _sum6 = _mm_add_epi32(_sum6, _mm_unpacklo_epi16(_sl3, _sh3)); _sum7 = _mm_add_epi32(_sum7, _mm_unpackhi_epi16(_sl3, _sh3)); k0 += 8; r0 += 32; } _sum0 = _mm_add_epi32(_sum0, _sum1); _sum2 = _mm_add_epi32(_sum2, _sum3); _sum4 = _mm_add_epi32(_sum4, _sum5); _sum6 = _mm_add_epi32(_sum6, _sum7); output0_tm[0] = _mm_reduce_add_epi32(_sum0); output0_tm[1] = _mm_reduce_add_epi32(_sum2); output0_tm[2] = _mm_reduce_add_epi32(_sum4); output0_tm[3] = _mm_reduce_add_epi32(_sum6); output0_tm += 4; } #endif for (; i + 1 < tiles; i += 2) { #if __AVX2__ const short* r0 = bb2.row<const short>(i / 4 + (i % 4) / 2); #else const short* r0 = bb2.row<const short>(i / 2); #endif const short* k0 = kernel0_tm.row<const short>(r); __m128i _sum0 = _mm_setzero_si128(); __m128i _sum1 = _mm_setzero_si128(); __m128i _sum2 = _mm_setzero_si128(); __m128i _sum3 = _mm_setzero_si128(); for (int q = 0; q < inch; q++) { __m128i _val0 = _mm_loadu_si128((const __m128i*)r0); __m128i _val1 = _mm_loadu_si128((const __m128i*)(r0 + 8)); __m128i _w0 = _mm_loadu_si128((const __m128i*)k0); __m128i _sl0 = _mm_mullo_epi16(_val0, _w0); __m128i _sh0 = _mm_mulhi_epi16(_val0, _w0); __m128i _sl1 = _mm_mullo_epi16(_val1, _w0); __m128i _sh1 = _mm_mulhi_epi16(_val1, _w0); _sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl0, _sh0)); _sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl0, _sh0)); _sum2 = _mm_add_epi32(_sum2, _mm_unpacklo_epi16(_sl1, _sh1)); _sum3 = _mm_add_epi32(_sum3, _mm_unpackhi_epi16(_sl1, _sh1)); k0 += 8; r0 += 16; } _sum0 = _mm_add_epi32(_sum0, _sum1); _sum2 = _mm_add_epi32(_sum2, _sum3); output0_tm[0] = _mm_reduce_add_epi32(_sum0); output0_tm[1] = _mm_reduce_add_epi32(_sum2); output0_tm += 2; } for (; i < tiles; i++) { #if __AVX2__ const short* r0 = bb2.row<const short>(i / 4 + (i % 4) / 2 + i % 2); #else const short* r0 = bb2.row<const short>(i / 2 + i % 2); #endif const short* k0 = kernel0_tm.row<const short>(r); __m128i _sum0 = _mm_setzero_si128(); __m128i _sum1 = _mm_setzero_si128(); for (int q = 0; q < inch; q++) { __m128i _val = _mm_loadu_si128((const __m128i*)r0); __m128i _w0 = _mm_loadu_si128((const __m128i*)k0); __m128i _sl0 = _mm_mullo_epi16(_val, _w0); __m128i _sh0 = _mm_mulhi_epi16(_val, _w0); _sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl0, _sh0)); _sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl0, _sh0)); k0 += 8; r0 += 8; } _sum0 = _mm_add_epi32(_sum0, _sum1); output0_tm[0] = _mm_reduce_add_epi32(_sum0); output0_tm++; } } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; if (outw == top_blob.w && outh == top_blob.h) { top_blob_bordered = top_blob; } else { top_blob_bordered.create(outw, outh, outch, 4u, 1, opt.workspace_allocator); } { // const float otm[4][6] = { // {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 1.0f} // }; // 0 = r00 + (r01 + r02) + (r03 + r04) // 1 = (r01 - r02) + (r03 - r04) * 2 // 2 = (r01 + r02) + (r03 + r04) * 4 // 3 = r05 + (r01 - r02) + (r03 - r04) * 8 int w_tm = outw / 4 * 6; int h_tm = outh / 4 * 6; const int tiles = w_tm / 6 * h_tm / 6; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { const Mat out0_tm = top_blob_tm.channel(p); Mat out0 = top_blob_bordered.channel(p); int tmp[4][6]; // tile for (int i = 0; i < outh / 4; i++) { for (int j = 0; j < outw / 4; j++) { // top_blob_tm.create(tiles, 36, outch, 4u, 1, opt.workspace_allocator); const int* output0_tm_0 = (const int*)out0_tm + (i * w_tm / 6 + j) * 1; const int* output0_tm_1 = output0_tm_0 + tiles * 1; const int* output0_tm_2 = output0_tm_0 + tiles * 2; const int* output0_tm_3 = output0_tm_0 + tiles * 3; const int* output0_tm_4 = output0_tm_0 + tiles * 4; const int* output0_tm_5 = output0_tm_0 + tiles * 5; int* output0 = out0.row<int>(i * 4) + j * 4; // 0 = r00 + (r01 + r02) + (r03 + r04) // 1 = (r01 - r02) + (r03 - r04) * 2 // 2 = (r01 + r02) + (r03 + r04) * 4 // 3 = r05 + (r01 - r02) + (r03 - r04) * 8 // TODO sse optimize for (int m = 0; m < 5; m++) { int tmp02a = output0_tm_1[0] + output0_tm_2[0]; int tmp13a = output0_tm_1[0] - output0_tm_2[0]; int tmp02b = output0_tm_3[0] + output0_tm_4[0]; int tmp13b = output0_tm_3[0] - output0_tm_4[0]; tmp[0][m] = output0_tm_0[0] + tmp02a + tmp02b; tmp[1][m] = tmp13a + tmp13b * 2; tmp[2][m] = tmp02a + tmp02b * 4; tmp[3][m] = output0_tm_5[0] * 4 + tmp13a + tmp13b * 8; output0_tm_0 += tiles * 6; output0_tm_1 += tiles * 6; output0_tm_2 += tiles * 6; output0_tm_3 += tiles * 6; output0_tm_4 += tiles * 6; output0_tm_5 += tiles * 6; } for (int m = 5; m < 6; m++) { int tmp02a = output0_tm_1[0] + output0_tm_2[0]; int tmp13a = output0_tm_1[0] - output0_tm_2[0]; int tmp02b = output0_tm_3[0] + output0_tm_4[0]; int tmp13b = output0_tm_3[0] - output0_tm_4[0]; tmp[0][m] = (output0_tm_0[0] + tmp02a + tmp02b) * 4; tmp[1][m] = (tmp13a + tmp13b * 2) * 4; tmp[2][m] = (tmp02a + tmp02b * 4) * 4; tmp[3][m] = (output0_tm_5[0] * 4 + tmp13a + tmp13b * 8) * 4; output0_tm_0 += tiles * 6; output0_tm_1 += tiles * 6; output0_tm_2 += tiles * 6; output0_tm_3 += tiles * 6; output0_tm_4 += tiles * 6; output0_tm_5 += tiles * 6; } for (int m = 0; m < 4; m++) { const int* tmp0 = tmp[m]; int tmp02a = tmp0[1] + tmp0[2]; int tmp13a = tmp0[1] - tmp0[2]; int tmp02b = tmp0[3] + tmp0[4]; int tmp13b = tmp0[3] - tmp0[4]; output0[0] = (tmp0[0] + tmp02a + tmp02b) / 576; output0[1] = (tmp13a + tmp13b * 2) / 576; output0[2] = (tmp02a + tmp02b * 4) / 576; output0[3] = (tmp0[5] + tmp13a + tmp13b * 8) / 576; output0 += outw; } } } } } // END transform output // cut result pad copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt); }
lu_decomposition.h
/** * @file lu_decomposition.h * @author [Krishna Vedala](https://github.com/kvedala) * @brief Functions associated with [LU * Decomposition](https://en.wikipedia.org/wiki/LU_decomposition) * of a square matrix. */ #pragma once #include <iostream> #include <valarray> #include <vector> #ifdef _OPENMP #include <omp.h> #endif /** Define matrix type as a `std::vector` of `std::valarray` */ template <typename T> using matrix = std::vector<std::valarray<T>>; /** Perform LU decomposition on matrix * \param[in] A matrix to decompose * \param[out] L output L matrix * \param[out] U output U matrix * \returns 0 if no errors * \returns negative if error occurred */ template <typename T> int lu_decomposition(const matrix<T> &A, matrix<double> *L, matrix<double> *U) { int row, col, j; int mat_size = A.size(); if (mat_size != A[0].size()) { // check matrix is a square matrix std::cerr << "Not a square matrix!\n"; return -1; } // regularize each row for (row = 0; row < mat_size; row++) { // Upper triangular matrix #ifdef _OPENMP #pragma omp for #endif for (col = row; col < mat_size; col++) { // Summation of L[i,j] * U[j,k] double lu_sum = 0.; for (j = 0; j < row; j++) { lu_sum += L[0][row][j] * U[0][j][col]; } // Evaluate U[i,k] U[0][row][col] = A[row][col] - lu_sum; } // Lower triangular matrix #ifdef _OPENMP #pragma omp for #endif for (col = row; col < mat_size; col++) { if (row == col) { L[0][row][col] = 1.; continue; } // Summation of L[i,j] * U[j,k] double lu_sum = 0.; for (j = 0; j < row; j++) { lu_sum += L[0][col][j] * U[0][j][row]; } // Evaluate U[i,k] L[0][col][row] = (A[col][row] - lu_sum) / U[0][row][row]; } } return 0; } /** * Compute determinant of an NxN square matrix using LU decomposition. * Using LU decomposition, the determinant is given by the product of diagonal * elements of matrices L and U. * * @tparam T datatype of input matrix - int, unsigned int, double, etc * @param A input square matrix * @return determinant of matrix A */ template <typename T> double determinant_lu(const matrix<T> &A) { matrix<double> L(A.size(), std::valarray<double>(A.size())); matrix<double> U(A.size(), std::valarray<double>(A.size())); if (lu_decomposition(A, &L, &U) < 0) return 0; double result = 1.f; for (size_t i = 0; i < A.size(); i++) { result *= L[i][i] * U[i][i]; } return result; }
GB_unop__abs_int8_int8.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__abs_int8_int8) // op(A') function: GB (_unop_tran__abs_int8_int8) // C type: int8_t // A type: int8_t // cast: int8_t cij = aij // unaryop: cij = GB_IABS (aij) #define GB_ATYPE \ int8_t #define GB_CTYPE \ int8_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_IABS (x) ; // casting #define GB_CAST(z, aij) \ int8_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ int8_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int8_t z = aij ; \ Cx [pC] = GB_IABS (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ABS || GxB_NO_INT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__abs_int8_int8) ( int8_t *Cx, // Cx and Ax may be aliased const int8_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++) { int8_t aij = Ax [p] ; int8_t z = aij ; Cx [p] = GB_IABS (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 ; int8_t aij = Ax [p] ; int8_t z = aij ; Cx [p] = GB_IABS (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__abs_int8_int8) ( 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
convert.c
/* This file is part of ParTI!. ParTI! 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 3 of the License, or (at your option) any later version. ParTI! 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 Lesser General Public License along with ParTI!. If not, see <http://www.gnu.org/licenses/>. */ #include <HiParTI.h> #include "../sptensor.h" #include "hicoo.h" /** * Compare two coordinates, in the order of mode-0,...,N-1. One from the sparse tensor, the other is specified. * @param tsr a pointer to a sparse tensor * @return 1, z > item; otherwise, 0. */ static int ptiLargerThanCoordinates( ptiSparseTensor *tsr, const ptiNnzIndex z, const ptiIndex * item) { ptiIndex nmodes = tsr->nmodes; ptiIndex i1, i2; for(ptiIndex m=0; m<nmodes; ++m) { i1 = tsr->inds[m].data[z]; i2 = item[m]; if(i1 > i2) { return 1; break; } } return 0; } /** * Compare two coordinates, in the order of mode-0,...,N-1. One from the sparse tensor, the other is specified. * @param tsr a pointer to a sparse tensor * @return 1, z < item; otherwise, 0. */ static int ptiSmallerThanCoordinates( ptiSparseTensor *tsr, const ptiNnzIndex z, const ptiIndex * item) { ptiIndex nmodes = tsr->nmodes; ptiIndex i1, i2; for(ptiIndex m=0; m<nmodes; ++m) { i1 = tsr->inds[m].data[z]; i2 = item[m]; if(i1 < i2) { return 1; break; } } return 0; } /** * Compare two coordinates, in the order of mode-0,...,N-1. One from the sparse tensor, the other is specified. * @param tsr a pointer to a sparse tensor * @return 1, z = item; otherwise, 0. */ static int ptiEqualWithCoordinates( ptiSparseTensor *tsr, const ptiNnzIndex z, const ptiIndex * item) { ptiIndex nmodes = tsr->nmodes; ptiIndex i1, i2; for(ptiIndex m=0; m<nmodes; ++m) { i1 = tsr->inds[m].data[z]; i2 = item[m]; if(i1 != i2) { return 0; break; } } return 1; } /** * Compare two specified coordinates. * @param tsr a pointer to a sparse tensor * @return 1, z == item; otherwise, 0. */ static int ptiEqualWithTwoCoordinates( const ptiIndex * item1, const ptiIndex * item2, const ptiIndex nmodes) { ptiIndex i1, i2; for(ptiIndex m=0; m<nmodes; ++m) { i1 = item1[m]; i2 = item2[m]; if(i1 != i2) { return 0; break; } } return 1; } /** * Check if a nonzero item is in the range of two given coordinates, in the order of mode-0,...,N-1. * @param tsr a pointer to a sparse tensor * @return 1, yes; 0, no. */ static int ptiCoordinatesInRange( ptiSparseTensor *tsr, const ptiNnzIndex z, const ptiIndex * range_begin, const ptiIndex * range_end) { if ( (ptiLargerThanCoordinates(tsr, z, range_begin) == 1 || ptiEqualWithCoordinates(tsr, z, range_begin) == 1) && ptiSmallerThanCoordinates(tsr, z, range_end) == 1) { return 1; } return 0; } /** * Compute the beginning of the next block * @param tsr a pointer to a sparse tensor * @return out_item the beginning indices of the next block */ static int ptiNextBlockBegin( ptiIndex * out_item, ptiSparseTensor *tsr, const ptiIndex * in_item, const ptiElementIndex sb) { ptiIndex nmodes = tsr->nmodes; for(int32_t m=nmodes-1; m>=0; --m) { if(in_item[m] < tsr->ndims[m]-1) { out_item[m] = in_item[m]+sb-1 < tsr->ndims[m] ? in_item[m]+sb-1 : tsr->ndims[m] - 1; break; } } return 0; } /** * Compute the end of this block * @param tsr a pointer to a sparse tensor * @return out_item the end indices of this block */ static int ptiBlockEnd( ptiIndex * out_item, ptiSparseTensor *tsr, const ptiIndex * in_item, const ptiElementIndex sb) { ptiIndex nmodes = tsr->nmodes; for(ptiIndex m=0; m<nmodes; ++m) { ptiAssert(in_item[m] < tsr->ndims[m]); out_item[m] = in_item[m]+sb < tsr->ndims[m] ? in_item[m]+sb : tsr->ndims[m]; // exclusive } return 0; } /** * Locate the beginning of the block/kernel containing the coordinates * @param tsr a pointer to a sparse tensor * @return out_item the beginning indices of this block */ static int ptiLocateBeginCoord( ptiIndex * out_item, ptiSparseTensor *tsr, const ptiIndex * in_item, const ptiElementIndex bits) { ptiIndex nmodes = tsr->nmodes; for(ptiIndex m=0; m<nmodes; ++m) { out_item[m] = in_item[m] >> bits; } return 0; } /** * Compute the strides for kernels, mode order N-1, ..., 0 (row-like major) * @param tsr a pointer to a sparse tensor * @return out_item the beginning indices of this block */ static int ptiKernelStrides( ptiIndex * strides, ptiSparseTensor *tsr, const ptiIndex sk) { ptiIndex nmodes = tsr->nmodes; ptiIndex kernel_size = 0; // TODO: efficiently use bitwise operation strides[nmodes-1] = 1; for(ptiIndex m=nmodes-2; m>=1; --m) { kernel_size = (ptiIndex)(tsr->ndims[m+1] + sk - 1) / sk; strides[m] = strides[m+1] * kernel_size; } kernel_size = (ptiIndex)(tsr->ndims[1] + sk - 1) / sk; strides[0] = strides[1] * kernel_size; return 0; } /** * Compute the end of this kernel * @param tsr a pointer to a sparse tensor * @return out_item the end indices of this block */ static int ptiKernelEnd( ptiIndex * out_item, ptiSparseTensor *tsr, const ptiIndex * in_item, const ptiIndex sk) { ptiIndex nmodes = tsr->nmodes; for(ptiIndex m=0; m<nmodes; ++m) { ptiAssert(in_item[m] < tsr->ndims[m]); out_item[m] = in_item[m]+sk < tsr->ndims[m] ? in_item[m]+sk : tsr->ndims[m]; // exclusive } return 0; } /** * Record mode pointers for kernel rows, from a sorted tensor. * @param mptr a vector of pointers as a dense array * @param tsr a pointer to a sparse tensor * @return mode pointers */ int ptiGetRowBlockPointers( ptiNnzIndexVector *mptr, ptiSparseTensor *tsr, const ptiIndex sk) { ptiNnzIndex nnz = tsr->nnz; ptiIndex i = tsr->inds[0].data[0]; ptiNnzIndex k = 0; // count blocks ptiNnzIndex knnz = 0; // #Nonzeros per block mptr->data[0] = 0; while(1) { /* check if mode-0 index in block-b */ if(i >= sk * k && i < sk * (k+1)) { ++ knnz; break; } else { ++ k; mptr->data[k] = knnz + mptr->data[k-1]; knnz = 0; } } for(ptiNnzIndex z=1; z<nnz; ++z) { i = tsr->inds[0].data[z]; /* Compare with the next block row index */ while(1) { if(i >= sk * k && i < sk * (k+1)) { ++ knnz; break; } else { ++ k; mptr->data[k] = knnz + mptr->data[k-1]; knnz = 0; } } } ptiAssert(k < (tsr->ndims[0] + sk -1 ) / sk); ptiAssert(mptr->data[mptr->len-1] + knnz == nnz); return 0; } /** * Record mode pointers for kernel rows, from a sorted tensor. * @param kptr a vector of kernel pointers * @param tsr a pointer to a sparse tensor * @return mode pointers */ int ptiSetKernelPointers( ptiNnzIndexVector *kptr, ptiNnzIndexVector *knnzs, ptiSparseTensor *tsr, const ptiElementIndex sk_bits) { ptiIndex nmodes = tsr->nmodes; ptiNnzIndex nnz = tsr->nnz; ptiNnzIndex k = 0; // count kernels ptiNnzIndex knnz = 0; // #Nonzeros per kernel int result = 0; result = ptiAppendNnzIndexVector(kptr, 0); pti_CheckError(result, "HiSpTns Convert", NULL); ptiIndex * coord = (ptiIndex *)malloc(nmodes * sizeof(*coord)); ptiIndex * kernel_coord = (ptiIndex *)malloc(nmodes * sizeof(*kernel_coord)); ptiIndex * kernel_coord_prior = (ptiIndex *)malloc(nmodes * sizeof(*kernel_coord_prior)); /* Process first nnz to get the first kernel_coord_prior */ for(ptiIndex m=0; m<nmodes; ++m) coord[m] = tsr->inds[m].data[0]; // first nonzero indices result = ptiLocateBeginCoord(kernel_coord_prior, tsr, coord, sk_bits); pti_CheckError(result, "HiSpTns Convert", NULL); for(ptiNnzIndex z=0; z<nnz; ++z) { for(ptiIndex m=0; m<nmodes; ++m) coord[m] = tsr->inds[m].data[z]; result = ptiLocateBeginCoord(kernel_coord, tsr, coord, sk_bits); pti_CheckError(result, "HiSpTns Convert", NULL); if(ptiEqualWithTwoCoordinates(kernel_coord, kernel_coord_prior, nmodes) == 1) { ++ knnz; } else { ++ k; result = ptiAppendNnzIndexVector(kptr, knnz + kptr->data[k-1]); pti_CheckError(result, "HiSpTns Convert", NULL); result = ptiAppendNnzIndexVector(knnzs, knnz); pti_CheckError(result, "HiSpTns Convert", NULL); for(ptiIndex m=0; m<nmodes; ++m) kernel_coord_prior[m] = kernel_coord[m]; knnz = 1; } } ptiAssert(k < kptr->len); ptiAssert(kptr->data[kptr->len-1] + knnz == nnz); /* Set the last element for kptr */ ptiAppendNnzIndexVector(kptr, nnz); ptiAppendNnzIndexVector(knnzs, knnz); free(coord); free(kernel_coord); free(kernel_coord_prior); return 0; } /** * Set scheduler for kernels. * @param kschr nmodes kernel schedulers. * @param tsr a pointer to a sparse tensor * @return mode pointers */ static int ptiSetKernelScheduler( ptiIndexVector **kschr, ptiIndex *nkiters, ptiNnzIndexVector * const kptr, ptiSparseTensor *tsr, const ptiElementIndex sk_bits) { ptiIndex nmodes = tsr->nmodes; ptiIndex * ndims = tsr->ndims; int result = 0; ptiIndex * coord = (ptiIndex *)malloc(nmodes * sizeof(*coord)); ptiIndex * kernel_coord = (ptiIndex *)malloc(nmodes * sizeof(*kernel_coord)); for(ptiNnzIndex k=0; k<kptr->len - 1; ++k) { ptiNnzIndex z = kptr->data[k]; for(ptiIndex m=0; m<nmodes; ++m) coord[m] = tsr->inds[m].data[z]; result = ptiLocateBeginCoord(kernel_coord, tsr, coord, sk_bits); pti_CheckError(result, "HiSpTns Convert", NULL); for(ptiIndex m=0; m<nmodes; ++m) { result = ptiAppendIndexVector(&(kschr[m][kernel_coord[m]]), k); pti_CheckError(result, "HiSpTns Convert", NULL); } } free(coord); free(kernel_coord); ptiIndex sk = (ptiIndex)pow(2, sk_bits); ptiIndex tmp; for(ptiIndex m=0; m<nmodes; ++m) { tmp = 0; ptiIndex kernel_ndim = (ndims[m] + sk - 1) / sk; for(ptiIndex i=0; i<kernel_ndim; ++i) { if(tmp < kschr[m][i].len) tmp = kschr[m][i].len; } nkiters[m] = tmp; } return 0; } /** * Pre-process COO sparse tensor by permuting, sorting, and record pointers to blocked rows. Kernels in Row-major order, blocks and elements are in Z-Morton order. * @param tsr a pointer to a sparse tensor * @return mode pointers */ int ptiPreprocessSparseTensor( ptiNnzIndexVector * kptr, ptiIndexVector **kschr, ptiIndex *nkiters, ptiIndexVector **kschr_balanced, ptiIndexVector **kschr_balanced_pos, ptiIndex *nkpars, ptiIndexVector * kschr_rest, ptiNnzIndexVector * knnzs, ptiSparseTensor *tsr, const ptiElementIndex sb_bits, const ptiElementIndex sk_bits, int const tk) { ptiNnzIndex nnz = tsr->nnz; int result; // TODO: possible permute modes to improve parallelism /* Sort tsr in a Row-major Block order to get all kernels. Not use Morton-order for kernels: 1. better support for higher-order tensors by limiting kernel size, because Morton key bit <= 128; */ ptiTimer rowblock_sort_timer; ptiNewTimer(&rowblock_sort_timer, 0); ptiStartTimer(rowblock_sort_timer); ptiSparseTensorSortIndexRowBlock(tsr, 1, 0, nnz, sk_bits, tk); // Parallelized inside ptiStopTimer(rowblock_sort_timer); ptiPrintElapsedTime(rowblock_sort_timer, "\t\trowblock sorting"); ptiFreeTimer(rowblock_sort_timer); #if PARTI_DEBUG == 3 printf("Sorted by ptiSparseTensorSortIndexRowBlock.\n"); ptiAssert(ptiDumpSparseTensor(tsr, 0, stdout) == 0); #endif ptiTimer set_kernel_timer; ptiNewTimer(&set_kernel_timer, 0); ptiStartTimer(set_kernel_timer); result = ptiSetKernelPointers(kptr, knnzs, tsr, sk_bits); pti_CheckError(result, "HiSpTns Preprocess", NULL); result = ptiSetKernelScheduler(kschr, nkiters, kptr, tsr, sk_bits); pti_CheckError(result, "HiSpTns Preprocess", NULL); // printf("OK\n"); fflush(stdout); /* Set balanced data structures: kschr_balanced, kschr_rest */ ptiNnzIndex avg_nnzk = tsr->nnz / (kptr->len - 1); ptiNnzIndex max_nnzk = 0; for(ptiIndex k=0; k<kptr->len - 1; ++k) { ptiNnzIndex nnzk = knnzs->data[k]; if(max_nnzk < nnzk) max_nnzk = nnzk; } // ptiNnzIndex par_nnzk_th = 20 * avg_nnzk; // threshold for nnzk per thread ptiNnzIndex par_nnzk_th = 5 * max_nnzk; // threshold for nnzk per thread printf("par_nnzk_th: %lu\n", par_nnzk_th); ptiIndex sk = (ptiIndex)pow(2, sk_bits); // printf("OK-2\n"); fflush(stdout); for(ptiIndex m=0; m < tsr->nmodes; ++m) { // Loop kschr for each mode ptiIndexVector * restrict kschr_mode = kschr[m]; ptiIndexVector * restrict kschr_balanced_mode = kschr_balanced[m]; ptiIndexVector * restrict kschr_balanced_pos_mode = kschr_balanced_pos[m]; ptiIndex kernel_ndim = (tsr->ndims[m] + sk - 1)/sk; for(ptiIndex i=0; i < kernel_ndim; ++i) { ptiAppendIndexVector(&(kschr_balanced_pos_mode[i]), 0); } ptiIndex j_rest = nkiters[m]; ptiIndex npars = 0; int tag_rest = 0; ptiIndex count_nk = 0; ptiIndex empty_schr_rows_th = 1.0 * kernel_ndim > 1 ? 1.0 * kernel_ndim : 1; printf("[mode %u] empty_schr_rows_th: %u\n", m, empty_schr_rows_th); while(tag_rest == 0 && count_nk < kptr->len - 1) { // Loop for partitions. tag_rest = 1, maybe there is no rest. /* Check two ranges: npars and j or tmp_j !!! */ ptiIndex max_nnzk_per_col = 0, par_nnzk = 0; ptiIndex count_empty_schr_rows = 0; for(ptiIndex i=0; i < kernel_ndim; ++i) { // Find the max nnzk if(count_empty_schr_rows > empty_schr_rows_th) { tag_rest = 1; break; } if(npars >= kschr_balanced_pos_mode[i].len) { ++ count_empty_schr_rows; continue; } else { ptiIndex j = kschr_balanced_pos_mode[i].data[npars]; if(j >= kschr_mode[i].len) { ++ count_empty_schr_rows; continue; } ptiIndex kernel_num = kschr_mode[i].data[j]; ptiNnzIndex kernel_nnz = knnzs->data[kernel_num]; if (max_nnzk_per_col < kernel_nnz) { max_nnzk_per_col = kernel_nnz; } } } // End of i if(tag_rest == 1) { // an empty superblock met, to kschr_rest for(ptiIndex i=0; i < kernel_ndim; ++i) { if(npars >= kschr_balanced_pos_mode[i].len) continue; ptiIndex j2 = kschr_balanced_pos_mode[i].data[npars]; for(; j2 < kschr_mode[i].len; ++j2) { ptiAppendIndexVector(&kschr_rest[m], kschr_mode[i].data[j2]); ++ count_nk; } } } else { // all non-empty superblocks for this column, to kschr_balanced, kschr_balanced_pos /* set par_nnzk */ if(max_nnzk_per_col > par_nnzk_th) { par_nnzk = max_nnzk_per_col; // split according to the superblock with the max nnzk } else { par_nnzk = par_nnzk_th; } /* Real partition */ for(ptiIndex i=0; i < kernel_ndim; ++i) { if(npars >= kschr_balanced_pos_mode[i].len) continue; ptiIndex tmp_j = kschr_balanced_pos_mode[i].data[npars]; if(tmp_j >= kschr_mode[i].len) continue; ptiIndex kernel_num = kschr_mode[i].data[tmp_j]; ptiNnzIndex sum_nnzk = knnzs->data[kernel_num]; while(sum_nnzk <= par_nnzk) { ptiAppendIndexVector(&(kschr_balanced_mode[i]), kernel_num); ++ count_nk; ++ tmp_j; if(tmp_j < kschr_mode[i].len) { kernel_num = kschr_mode[i].data[tmp_j]; // j + 1 sum_nnzk += knnzs->data[kernel_num]; } else { break; } } // End of while ptiAppendIndexVector(&(kschr_balanced_pos_mode[i]), tmp_j); } ++ npars; } // printf("count_nk: %u\n", count_nk); fflush(stdout); } // End of while nkpars[m] = npars; // kschr_balanced_pos.len is npars + 1. } // End loop of modes ptiStopTimer(set_kernel_timer); ptiPrintElapsedTime(set_kernel_timer, "\t\tSet Kernel Ptrs"); ptiFreeTimer(set_kernel_timer); ptiTimer morton_sort_timer; ptiNewTimer(&morton_sort_timer, 0); ptiStartTimer(morton_sort_timer); /* Sort blocks in each kernel in Morton-order */ ptiNnzIndex k_begin, k_end; /* Loop for all kernels, 0-kptr.len for OMP code */ #pragma omp parallel for num_threads(tk) for(ptiNnzIndex k=0; k<kptr->len - 1; ++k) { k_begin = kptr->data[k]; k_end = kptr->data[k+1]; // exclusive /* Sort blocks in each kernel in Morton-order */ ptiSparseTensorSortIndexMorton(tsr, 1, k_begin, k_end, sb_bits, tk); // ptiSparseTensorSortIndexRowBlock(tsr, 1, k_begin, k_end, sb_bits, tk); #if PARTI_DEBUG == 3 printf("Kernel %"HIPARTI_PRI_NNZ_INDEX ": Sorted by ptiSparseTensorSortIndexMorton.\n", k); ptiAssert(ptiDumpSparseTensor(tsr, 0, stdout) == 0); #endif } ptiStopTimer(morton_sort_timer); ptiPrintElapsedTime(morton_sort_timer, "\t\tMorton sorting"); // ptiPrintElapsedTime(morton_sort_timer, "\t\t2nd Rowblock sorting"); ptiFreeTimer(morton_sort_timer); return 0; } /** * Pre-process COO sparse tensor by permuting, sorting, and record pointers to blocked rows for TTM. Kernels, blocks are both in row-major order, elements in a block is in an arbitrary order. * @param tsr a pointer to a sparse tensor * @return mode pointers */ int ptiPreprocessSparseTensor_RowBlock( ptiNnzIndexVector * kptr, ptiIndexVector **kschr, ptiIndex *nkiters, ptiIndex *nfibs, ptiNnzIndexVector * knnzs, ptiSparseTensor *tsr, const ptiElementIndex sb_bits, const ptiElementIndex sk_bits, int const tk) { ptiNnzIndex nnz = tsr->nnz; int result; /* Sort tsr in a Row-major Block order to get all kernels. */ ptiSparseTensorSortIndexRowBlock(tsr, 1, 0, nnz, sk_bits, tk); result = ptiSetKernelPointers(kptr, knnzs, tsr, sk_bits); pti_CheckError(result, "HiSpTns Preprocess", NULL); // result = ptiSetKernelScheduler(kschr, nkiters, kptr, tsr, sk_bits); // pti_CheckError(result, "HiSpTns Preprocess", NULL); /* Sort blocks in each kernel in Row-major block order. */ ptiNnzIndex k_begin, k_end; /* Loop for all kernels, 0-kptr.len for OMP code */ for(ptiNnzIndex k=0; k<kptr->len - 1; ++k) { k_begin = kptr->data[k]; k_end = kptr->data[k+1]; // exclusive ptiSparseTensorSortIndexRowBlock(tsr, 1, k_begin, k_end, sb_bits, tk); } return 0; } int ptiSparseTensorToHiCOO( ptiSparseTensorHiCOO *hitsr, ptiNnzIndex *max_nnzb, ptiSparseTensor *tsr, const ptiElementIndex sb_bits, const ptiElementIndex sk_bits, const ptiElementIndex sc_bits, int const tk) { ptiAssert(sk_bits >= sb_bits); ptiAssert(sc_bits >= sb_bits); ptiIndex i; int result; ptiIndex nmodes = tsr->nmodes; ptiNnzIndex nnz = tsr->nnz; ptiElementIndex sb = pow(2, sb_bits); ptiIndex sc = pow(2, sc_bits); /* Set HiCOO parameters. ndims for type conversion, size_t -> ptiIndex */ ptiIndex * ndims = malloc(nmodes * sizeof *ndims); pti_CheckOSError(!ndims, "HiSpTns Convert"); for(i = 0; i < nmodes; ++i) { ndims[i] = (ptiIndex)tsr->ndims[i]; } result = ptiNewSparseTensorHiCOO(hitsr, (ptiIndex)tsr->nmodes, ndims, (ptiNnzIndex)tsr->nnz, sb_bits, sk_bits, sc_bits); pti_CheckError(result, "HiSpTns Convert", NULL); /* Pre-process tensor to get hitsr->kptr, values are nonzero locations. */ ptiTimer sort_timer; ptiNewTimer(&sort_timer, 0); ptiStartTimer(sort_timer); ptiPreprocessSparseTensor(&hitsr->kptr, hitsr->kschr, hitsr->nkiters, hitsr->kschr_balanced, hitsr->kschr_balanced_pos, hitsr->nkpars, hitsr->kschr_rest, &hitsr->knnzs, tsr, sb_bits, sk_bits, tk); ptiStopTimer(sort_timer); ptiPrintElapsedTime(sort_timer, "\tHiCOO sorting (rowblock + morton)"); ptiFreeTimer(sort_timer); #if PARTI_DEBUG >= 2 printf("Kernels: Row-major, blocks: Morton-order sorted:\n"); ptiAssert(ptiDumpSparseTensor(tsr, 0, stdout) == 0); printf("hitsr->kptr:\n"); ptiDumpNnzIndexVector(&hitsr->kptr, stdout); #endif ptiTimer gen_timer; ptiNewTimer(&gen_timer, 0); ptiStartTimer(gen_timer); /* Temporary storage */ ptiIndex * block_begin = (ptiIndex *)malloc(nmodes * sizeof(*block_begin)); ptiIndex * block_end = (ptiIndex *)malloc(nmodes * sizeof(*block_end)); ptiIndex * block_begin_prior = (ptiIndex *)malloc(nmodes * sizeof(*block_begin_prior)); ptiIndex * block_coord = (ptiIndex *)malloc(nmodes * sizeof(*block_coord)); ptiNnzIndex k_begin, k_end; // #Nonzeros locations ptiNnzIndex nk = 0; // #Kernels ptiNnzIndex nc = 0; // #Chunks ptiNnzIndex nb = 1; // #Blocks // counting from the first nnz ptiNnzIndex nb_tmp = 0; ptiNnzIndex ne = 0; // #Nonzeros per block ptiIndex eindex = 0; ptiBlockIndex chunk_size = 0; /* different appending methods: * elements: append every nonzero entry * blocks: append when seeing a new block. * chunks: appending when seeting a new chunk. Notice the boundary of kernels and the last chunk of the whole tensor may be larger than the sc. * kernels: append when seeing a new kernel. Not appending a vector, just write data into an allocated array. */ /* Process first nnz */ for(ptiIndex m=0; m<nmodes; ++m) block_coord[m] = tsr->inds[m].data[0]; // first nonzero indices result = ptiLocateBeginCoord(block_begin_prior, tsr, block_coord, sb_bits); pti_CheckError(result, "HiSpTns Convert", NULL); for(ptiIndex m=0; m<nmodes; ++m) ptiAppendBlockIndexVector(&hitsr->binds[m], (ptiBlockIndex)block_begin_prior[m]); ptiAppendNnzIndexVector(&hitsr->bptr, 0); /* Loop for all kernels, 0 - hitsr->kptr.len - 1 for OMP code */ for(ptiNnzIndex k=0; k<hitsr->kptr.len - 1; ++k) { k_begin = hitsr->kptr.data[k]; k_end = hitsr->kptr.data[k+1]; // exclusive nb_tmp = k == 0 ? 0: nb; /* Modify kptr pointing to block locations */ hitsr->kptr.data[k] = nb_tmp; ++ nk; /* Only append a chunk for the new kernel, the last chunk in the old kernel may be larger than sc */ ptiAppendNnzIndexVector(&hitsr->cptr, nb_tmp); // printf("cptr 1:\n"); // ptiDumpNnzIndexVector(&hitsr->cptr, stdout); ++ nc; chunk_size = 0; /* Loop nonzeros in each kernel */ for(ptiNnzIndex z = k_begin; z < k_end; ++z) { #if PARTI_DEBUG == 5 printf("z: %"HIPARTI_PRI_NNZ_INDEX "\n", z); #endif for(ptiIndex m=0; m<nmodes; ++m) block_coord[m] = tsr->inds[m].data[z]; // first nonzero indices #if PARTI_DEBUG == 5 printf("block_coord:\n"); ptiAssert(ptiDumpIndexArray(block_coord, nmodes, stdout) == 0); #endif result = ptiLocateBeginCoord(block_begin, tsr, block_coord, sb_bits); // pti_CheckError(result, "HiSpTns Convert", NULL); #if PARTI_DEBUG == 5 printf("block_begin_prior:\n"); ptiAssert(ptiDumpIndexArray(block_begin_prior, nmodes, stdout) == 0); printf("block_begin:\n"); ptiAssert(ptiDumpIndexArray(block_begin, nmodes, stdout) == 0); #endif result = ptiBlockEnd(block_end, tsr, block_begin, sb); // exclusive // pti_CheckError(result, "HiSpTns Convert", NULL); /* Append einds and values */ for(ptiIndex m=0; m<nmodes; ++m) { eindex = tsr->inds[m].data[z] < (block_begin[m] << sb_bits) ? tsr->inds[m].data[z] : tsr->inds[m].data[z] - (block_begin[m] << sb_bits); ptiAssert(eindex < sb); ptiAppendElementIndexVector(&hitsr->einds[m], (ptiElementIndex)eindex); } ptiAppendValueVector(&hitsr->values, tsr->values.data[z]); /* z in the same block with last z */ if (ptiEqualWithTwoCoordinates(block_begin, block_begin_prior, nmodes) == 1) { /* ne: #Elements in current block */ ++ ne; } else { /* New block */ /* ne: #Elements in the last block */ /* Append block bptr and bidx */ ptiAppendNnzIndexVector(&hitsr->bptr, (ptiBlockIndex)z); for(ptiIndex m=0; m<nmodes; ++m) ptiAppendBlockIndexVector(&hitsr->binds[m], (ptiBlockIndex)block_begin[m]); for(ptiIndex m=0; m<nmodes; ++m) block_begin_prior[m] = block_begin[m]; /* ne: old block's number of nonzeros */ // if(chunk_size + ne > sc || ne >= sc) { // if(chunk_size + ne >= sc && chunk_size > 0) { // calculate the prior block // /* Append a chunk ending by the old block */ // ptiAppendNnzIndexVector(&hitsr->cptr, nb-1); // // printf("cptr 2:\n"); // // ptiDumpNnzIndexVector(&hitsr->cptr, stdout); // ++ nc; // chunk_size = ne; // } else { // chunk_size += ne; // } if(chunk_size + ne >= sc) { // calculate the prior block /* Append a chunk ending by the old block */ ptiAppendNnzIndexVector(&hitsr->cptr, nb); // printf("cptr 2:\n"); // ptiDumpNnzIndexVector(&hitsr->cptr, stdout); // printf("nb: %u, chunk_size: %u, ne: %u\n", nb, chunk_size, ne); ++ nc; chunk_size = 0; } else { chunk_size += ne; } ++ nb; ne = 1; } // End new block #if PARTI_DEBUG == 5 printf("nk: %u, nc: %u, nb: %u, ne: %u, chunk_size: %lu\n\n", nk, nc, nb, ne, chunk_size); #endif } // End z loop } // End k loop ptiAssert(nb <= nnz); ptiAssert(nb == hitsr->binds[0].len); // ptiAssert(nc <= nb); ptiAssert(nk == hitsr->kptr.len - 1); /* Last element for kptr, cptr, bptr */ hitsr->kptr.data[hitsr->kptr.len - 1] = hitsr->bptr.len; ptiAppendNnzIndexVector(&hitsr->cptr, hitsr->bptr.len); ptiAppendNnzIndexVector(&hitsr->bptr, nnz); *max_nnzb = hitsr->bptr.data[1] - hitsr->bptr.data[0]; ptiNnzIndex sum_nnzb = 0; for(ptiIndex i=0; i < hitsr->bptr.len - 1; ++i) { ptiNnzIndex nnzb = hitsr->bptr.data[i+1] - hitsr->bptr.data[i]; sum_nnzb += nnzb; if(*max_nnzb < nnzb) { *max_nnzb = nnzb; } } ptiAssert(sum_nnzb == hitsr->nnz); ptiStopTimer(gen_timer); ptiPrintElapsedTime(gen_timer, "\tGenerate HiCOO"); ptiFreeTimer(gen_timer); free(block_begin); free(block_end); free(block_begin_prior); free(block_coord); return 0; }
HDF5SubdomainDumperMPI.h
// // HDF5SubdomainDumperMPI.h // Cubism // // Created by Fabian Wermelinger 2018-08-03 // Copyright 2018 ETH Zurich. All rights reserved. // #ifndef HDF5SUBDOMAINDUMPERMPI_H_UAFPTNPL #define HDF5SUBDOMAINDUMPERMPI_H_UAFPTNPL #include <cassert> #include <iostream> #include <vector> #include <string> #include <sstream> #include <mpi.h> #include "HDF5Dumper.h" CUBISM_NAMESPACE_BEGIN /////////////////////////////////////////////////////////////////////////////// // helpers namespace SubdomainTypesMPI { template <typename TGrid> class Subdomain : public SubdomainTypes::Subdomain<TGrid> { public: template <typename TSubdomain> static std::vector<TSubdomain> getEntities(ArgumentParser& parser, TGrid& grid) { return SubdomainTypes::Subdomain<TGrid>::template getEntities<TSubdomain>(parser, grid); } public: typedef TGrid GridType; // bb_start: cell index within which the bounding box start (lower left) lies // bb_end: cell index within which the bounding box end (upper right) lies Subdomain(TGrid* grid, const int id, const double start[3], const double end[3], const double* h[3], const int bb_start[3]=0, const int bb_end[3]=0) : SubdomainTypes::Subdomain<TGrid>(grid, id, start, end, h, bb_start, bb_end), m_suboffset{0} { int myrank; int color = static_cast<int>( this->m_valid ); MPI_Comm comm = this->m_grid->getCartComm(); MPI_Comm subcomm; MPI_Comm_rank(comm, &myrank); MPI_Comm_split(comm, color, myrank, &subcomm); int pe_coords[3]; this->m_grid->peindex(pe_coords); // compute offsets this->m_max_size = 1; unsigned long g_max_size = 0; if (this->m_valid) { // 1. determine dimension and create cartesian sub-communicator int pe_shift[3] = { pe_coords[0], pe_coords[1], pe_coords[2] }; MPI_Bcast(pe_shift, 3, MPI_INT, 0, subcomm); for (int i = 0; i < 3; ++i) pe_coords[i] -= pe_shift[i]; int pe_subdims[3]; for (int i = 0; i < 3; ++i) { MPI_Allreduce(&pe_coords[i], &pe_subdims[i], 1, MPI_INT, MPI_MAX, subcomm); pe_subdims[i] += 1; // shift from index to dimension space } MPI_Comm subcartcomm; int periodic[3] = {true}; MPI_Cart_create(subcomm, 3, pe_subdims, periodic, false, &subcartcomm); // 2. compute file offsets using reduced 1D communicators int subdims[][3] = { {true, false, false}, {false, true, false}, {false, false, true} }; for (int i = 0; i < 3; ++i) { MPI_Comm dimcomm; MPI_Cart_sub(subcartcomm, subdims[i], &dimcomm); MPI_Exscan(&this->m_subcount[i], &m_suboffset[i], 1, MPI_INT, MPI_SUM, dimcomm); MPI_Comm_free(&dimcomm); } MPI_Comm_free(&subcartcomm); // 3. reduce maximum element size of subdomain to all // others in the sub-communicator for (int i = 0; i < 3; ++i) this->m_max_size *= static_cast<unsigned long>( this->m_subcount[i] ); MPI_Allreduce(&(this->m_max_size), &g_max_size, 1, MPI_UNSIGNED_LONG, MPI_MAX, subcomm); } MPI_Comm_free(&subcomm); // 4. update maximum size globally MPI_Allreduce(&g_max_size, &(this->m_max_size), 1, MPI_UNSIGNED_LONG, MPI_MAX, comm); } Subdomain(const Subdomain& c) = default; inline const int (&offset() const)[3] { return m_suboffset; } virtual void show(const std::string prefix="") const { std::cout << prefix << "subdomain" << this->m_id << ":" << std::endl; std::cout << prefix << "ID = " << this->m_id << std::endl; std::cout << prefix << "START = (" << this->m_start[0] << ", " << this->m_start[1] << ", " << this->m_start[2] << ")" << std::endl; std::cout << prefix << "END = (" << this->m_end[0] << ", " << this->m_end[1] << ", " << this->m_end[2] << ")" << std::endl; std::cout << prefix << "BBOX_START = (" << this->m_bbox_start[0] << ", " << this->m_bbox_start[1] << ", " << this->m_bbox_start[2] << ")" << std::endl; std::cout << prefix << "BBOX_END = (" << this->m_bbox_end[0] << ", " << this->m_bbox_end[1] << ", " << this->m_bbox_end[2] << ")" << std::endl; std::cout << prefix << "DIM = (" << this->m_subdim[0] << ", " << this->m_subdim[1] << ", " << this->m_subdim[2] << ")" << std::endl; std::cout << prefix << "SUBDIM = (" << this->m_subcount[0] << ", " << this->m_subcount[1] << ", " << this->m_subcount[2] << ")" << std::endl; std::cout << prefix << "OFFSET = (" << this->m_suboffset[0] << ", " << this->m_suboffset[1] << ", " << this->m_suboffset[2] << ")" << std::endl; std::cout << prefix << "MAXSIZE = " << this->m_max_size << std::endl; std::cout << prefix << "VALID = " << this->m_valid << std::endl; std::cout << prefix << "NUMBER OF BLOCKS = " << this->m_intersecting_blocks.size() << std::endl; } protected: int m_suboffset[3]; // index offset for my subdomain }; } /////////////////////////////////////////////////////////////////////////////// // Dumpers // // The following requirements for the data TStreamer are required: // TStreamer::NCHANNELS : Number of data elements (1=Scalar, 3=Vector, 9=Tensor) // TStreamer::operate : Data access methods for read and write // TStreamer::getAttributeName : Attribute name of the date ("Scalar", "Vector", "Tensor") template<typename TStreamer, typename hdf5Real, typename TSubdomain> void DumpSubdomainHDF5MPI(const TSubdomain& subdomain, const typename TSubdomain::GridType::Real t, const std::string &fileroot, const std::string &dirname = ".", const bool bXMF = true) { #ifdef CUBISM_USE_HDF typedef typename TSubdomain::GridType::BlockType B; std::string filename_h5 = fileroot + ".h5"; std::string fullpath_h5 = dirname + "/" + filename_h5; std::string fullpath_xmf = dirname + "/" + fileroot + ".xmf"; int rank; MPI_Comm comm = subdomain.getGrid()->getCartComm(); MPI_Comm_rank(comm, &rank); herr_t status; hid_t file_id, dataset_id, fspace_id, fapl_id, mspace_id; /////////////////////////////////////////////////////////////////////////// // write mesh std::vector<int> mesh_dims; std::vector<std::string> dset_name; dset_name.push_back("/vx"); dset_name.push_back("/vy"); dset_name.push_back("/vz"); if (0 == rank) { H5open(); fapl_id = H5Pcreate(H5P_FILE_ACCESS); file_id = H5Fcreate(fullpath_h5.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, fapl_id); status = H5Pclose(fapl_id); for (size_t i = 0; i < 3; ++i) { const int nCells = subdomain.dim(i); const double* const h = subdomain.grid_spacing(i); std::vector<double> vertices(nCells+1, subdomain.start(i)); mesh_dims.push_back(vertices.size()); for (int j = 0; j < nCells; ++j) vertices[j+1] = vertices[j] + h[j];; hsize_t dim[1] = {vertices.size()}; fspace_id = H5Screate_simple(1, dim, NULL); #ifndef CUBISM_ON_FERMI dataset_id = H5Dcreate(file_id, dset_name[i].c_str(), H5T_NATIVE_DOUBLE, fspace_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); #else dataset_id = H5Dcreate2(file_id, dset_name[i].c_str(), H5T_NATIVE_DOUBLE, fspace_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); #endif status = H5Dwrite(dataset_id, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, vertices.data()); status = H5Sclose(fspace_id); status = H5Dclose(dataset_id); } // shutdown h5 file status = H5Fclose(file_id); H5close(); } MPI_Barrier(comm); /////////////////////////////////////////////////////////////////////////// // startup file H5open(); fapl_id = H5Pcreate(H5P_FILE_ACCESS); status = H5Pset_fapl_mpio(fapl_id, comm, MPI_INFO_NULL); if(status<0) H5Eprint1(stdout); file_id = H5Fopen(fullpath_h5.c_str(), H5F_ACC_RDWR, fapl_id); status = H5Pclose(fapl_id); if(status<0) H5Eprint1(stdout); /////////////////////////////////////////////////////////////////////////// // write data std::vector<BlockInfo> infos_sub = subdomain.getBlocksInfo(); static const unsigned int NCHANNELS = TStreamer::NCHANNELS; const unsigned int NX = subdomain.count()[0]; const unsigned int NY = subdomain.count()[1]; const unsigned int NZ = subdomain.count()[2]; const unsigned int DX = subdomain.dim()[0]; const unsigned int DY = subdomain.dim()[1]; const unsigned int DZ = subdomain.dim()[2]; if (rank==0) { std::cout << "Allocating " << (subdomain.max_size() * NCHANNELS * sizeof(hdf5Real))/(1024.*1024.) << " MB of HDF5 subdomain data"; std::cout << " (Total " << (DX * DY * DZ * NCHANNELS * sizeof(hdf5Real))/(1024.*1024.) << " MB)" << std::endl; } hsize_t count[4] = { NZ, NY, NX, NCHANNELS }; hsize_t dims[4] = { DZ, DY, DX, NCHANNELS }; hsize_t offset[4] = { static_cast<hsize_t>(subdomain.offset()[2]), static_cast<hsize_t>(subdomain.offset()[1]), static_cast<hsize_t>(subdomain.offset()[0]), 0 }; hdf5Real * array_all = NULL; if (subdomain.valid()) { array_all = new hdf5Real[NX * NY * NZ * NCHANNELS]; const int bbox_start[3] = { subdomain.bbox_start()[0], subdomain.bbox_start()[1], subdomain.bbox_start()[2] }; const int bbox_end[3] = { subdomain.bbox_end()[0], subdomain.bbox_end()[1], subdomain.bbox_end()[2] }; #pragma omp parallel for for(int i=0; i<(int)infos_sub.size(); i++) { BlockInfo& info = infos_sub[i]; const B& b = *(B*)info.ptrBlock; const int idx[3] = { info.index[0], info.index[1], info.index[2] }; for(int iz=0; iz<static_cast<int>(B::sizeZ); iz++) for(int iy=0; iy<static_cast<int>(B::sizeY); iy++) for(int ix=0; ix<static_cast<int>(B::sizeX); ix++) { // cell local check: continue if the cell does not // intersect the subdomain bounding box. int gx = idx[0]*B::sizeX + ix; int gy = idx[1]*B::sizeY + iy; int gz = idx[2]*B::sizeZ + iz; const bool b_containedX = (bbox_start[0] <= gx) && (gx <= bbox_end[0]); const bool b_containedY = (bbox_start[1] <= gy) && (gy <= bbox_end[1]); const bool b_containedZ = (bbox_start[2] <= gz) && (gz <= bbox_end[2]); if (!(b_containedX && b_containedY && b_containedZ)) continue; hdf5Real output[NCHANNELS]; for(unsigned int j=0; j<NCHANNELS; ++j) output[j] = 0; TStreamer::operate(b, ix, iy, iz, (hdf5Real*)output); // shift the indices to subdomain index space gx -= bbox_start[0]; gy -= bbox_start[1]; gz -= bbox_start[2]; hdf5Real * const ptr = array_all + NCHANNELS*(gx + NX * (gy + NY * gz)); for(unsigned int j=0; j<NCHANNELS; ++j) ptr[j] = output[j]; } } } fapl_id = H5Pcreate(H5P_DATASET_XFER); H5Pset_dxpl_mpio(fapl_id, H5FD_MPIO_COLLECTIVE); fspace_id = H5Screate_simple(4, dims, NULL); #ifndef CUBISM_ON_FERMI dataset_id = H5Dcreate(file_id, "data", get_hdf5_type<hdf5Real>(), fspace_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); #else dataset_id = H5Dcreate2(file_id, "data", get_hdf5_type<hdf5Real>(), fspace_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); #endif fspace_id = H5Dget_space(dataset_id); H5Sselect_hyperslab(fspace_id, H5S_SELECT_SET, offset, NULL, count, NULL); mspace_id = H5Screate_simple(4, count, NULL); if (!subdomain.valid()) { H5Sselect_none(fspace_id); H5Sselect_none(mspace_id); } status = H5Dwrite(dataset_id, get_hdf5_type<hdf5Real>(), mspace_id, fspace_id, fapl_id, array_all); if (status < 0) H5Eprint1(stdout); status = H5Sclose(mspace_id); if(status<0) H5Eprint1(stdout); status = H5Sclose(fspace_id); if(status<0) H5Eprint1(stdout); status = H5Dclose(dataset_id); if(status<0) H5Eprint1(stdout); status = H5Pclose(fapl_id); if(status<0) H5Eprint1(stdout); status = H5Fclose(file_id); if(status<0) H5Eprint1(stdout); H5close(); if (subdomain.valid()) delete [] array_all; if (bXMF && rank==0) { FILE *xmf = 0; xmf = fopen(fullpath_xmf.c_str(), "w"); fprintf(xmf, "<?xml version=\"1.0\" ?>\n"); fprintf(xmf, "<!DOCTYPE Xdmf SYSTEM \"Xdmf.dtd\" []>\n"); fprintf(xmf, "<Xdmf Version=\"2.0\">\n"); fprintf(xmf, " <Domain>\n"); fprintf(xmf, " <Grid GridType=\"Uniform\">\n"); fprintf(xmf, " <Time Value=\"%e\"/>\n\n", t); fprintf(xmf, " <Topology TopologyType=\"3DRectMesh\" Dimensions=\"%d %d %d\"/>\n\n", mesh_dims[2], mesh_dims[1], mesh_dims[0]); fprintf(xmf, " <Geometry GeometryType=\"VxVyVz\">\n"); fprintf(xmf, " <DataItem Name=\"mesh_vx\" Dimensions=\"%d\" NumberType=\"Float\" Precision=\"8\" Format=\"HDF\">\n", mesh_dims[0]); fprintf(xmf, " %s:/vx\n", filename_h5.c_str()); fprintf(xmf, " </DataItem>\n"); fprintf(xmf, " <DataItem Name=\"mesh_vy\" Dimensions=\"%d\" NumberType=\"Float\" Precision=\"8\" Format=\"HDF\">\n", mesh_dims[1]); fprintf(xmf, " %s:/vy\n", filename_h5.c_str()); fprintf(xmf, " </DataItem>\n"); fprintf(xmf, " <DataItem Name=\"mesh_vz\" Dimensions=\"%d\" NumberType=\"Float\" Precision=\"8\" Format=\"HDF\">\n", mesh_dims[2]); fprintf(xmf, " %s:/vz\n", filename_h5.c_str()); fprintf(xmf, " </DataItem>\n"); fprintf(xmf, " </Geometry>\n\n"); fprintf(xmf, " <Attribute Name=\"data\" AttributeType=\"%s\" Center=\"Cell\">\n", TStreamer::getAttributeName()); fprintf(xmf, " <DataItem Dimensions=\"%d %d %d %d\" NumberType=\"Float\" Precision=\"%d\" Format=\"HDF\">\n",(int)dims[0], (int)dims[1], (int)dims[2], (int)dims[3], (int)sizeof(hdf5Real)); fprintf(xmf, " %s:/data\n", filename_h5.c_str()); fprintf(xmf, " </DataItem>\n"); fprintf(xmf, " </Attribute>\n"); fprintf(xmf, " </Grid>\n"); fprintf(xmf, " </Domain>\n"); fprintf(xmf, "</Xdmf>\n"); fclose(xmf); } #else #warning USE OF HDF WAS DISABLED AT COMPILE TIME #endif } CUBISM_NAMESPACE_END #endif /* HDF5SUBDOMAINDUMPERMPI_H_UAFPTNPL */
decomp.h
/*! /* Software SPAMS v2.2 - Copyright 2009-2011 Julien Mairal * * This file is part of SPAMS. * * SPAMS 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 of the License, or * (at your option) any later version. * * SPAMS 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 SPAMS. If not, see <http://www.gnu.org/licenses/>. * * * \file * toolbox decomp * * by Julien Mairal * julien.mairal@inria.fr * * File decomp.h * \brief Contains sparse decomposition algorithms * It requires the toolbox linalg */ #ifndef DECOMP_H #define DECOMP_H #include <utils.h> /* ************************** * Greedy Forward Selection * **************************/ /// Forward Selection (or Orthogonal matching pursuit) /// Address the problem of: /// \forall i, \min_{\alpha_i} ||X_i-D\alpha_i||_2^2 /// s.t. ||\alphai||_0 <= L or /// \forall i, \min_{\alpha_i} ||\alpha_i||_0 /// s.t. ||\X_i-D\alpha_i||_2^2 <= epsilon /// This function is /// * based on Cholesky decompositions /// * parallel /// * optimized for a large number of signals (precompute the Gramm matrix template <typename T> void omp(const Matrix<T>& X, const Matrix<T>& D, SpMatrix<T>& spalpha, const int *L, const T* eps, const T* lambda, const bool vecL = false, const bool vecEps = false, const bool Lambda=false, const int numThreads=-1, Matrix<T>* path = NULL); template <typename T> void omp_mask(const Matrix<T>& X, const Matrix<T>& D, SpMatrix<T>& spalpha, const Matrix<bool>& mask, const int *L, const T* eps, const T* lambda, const bool vecL = false, const bool vecEps = false, const bool Lambda=false, const int numThreads=-1, Matrix<T>* path = NULL); /// Auxiliary function of omp template <typename T> void coreORMP(Vector<T>& scores, Vector<T>& norm, Vector<T>& tmp, Matrix<T>& Un, Matrix<T>& Undn, Matrix<T>& Unds, Matrix<T>& Gs, Vector<T>& Rdn, const AbstractMatrix<T>& G, Vector<int>& ind, Vector<T>& RUn, T& normX, const T* eps, const int* L, const T* lambda, T* path = NULL); /// Auxiliary function of omp template <typename T> void coreORMPB(Vector<T>& RtD, const AbstractMatrix<T>& G, Vector<int>& ind, Vector<T>& coeffs, T& normX, const int L, const T eps, const T lambda = 0); /* ************** * LARS - Lasso * **************/ /// Defines different types of problem, /// - constraint on the l1 norm of the coefficients /// - constraint on the reconstruction error /// - l1-sparsity penalty enum constraint_type { L1COEFFS, L2ERROR, PENALTY, SPARSITY, L2ERROR2, PENALTY2}; /// Implementation of LARS-Lasso for solving /// \forall i, \min_{\alpha_i} ||X_i-D\alpha_i||_2^2 /// s.t. ||\alphai||_1 <= constraint or /// \forall i, \min_{\alpha_i} ||\alpha_i||_1 /// s.t. ||\X_i-D\alpha_i||_2^2 <= constraint or /// \forall i, \min_{\alpha_i} constraint*||\alpha_i||_1 + ... /// ... ||\X_i-D\alpha_i||_2^2 <= T /// Optionally, the solution might be positive (boolean pos), and a /// Least-Square can be solved as a post-processing step. /// L is a maximum number of coefficients. /// This function is /// * efficient (Cholesky-based) /// * parallel /// * optimized for a big number of signals (precompute the Gramm matrix template <typename T> void lasso(const Matrix<T>& X, const Matrix<T>& D, SpMatrix<T>& spalpha, int L, const T constraint, const T lambda2 = 0, constraint_type mode = PENALTY, const bool pos = false, const bool ols = false, const int numThreads=-1, Matrix<T>* path = NULL, const int length_path=-1); template <typename T> void lasso(const Data<T>& X, const AbstractMatrix<T>& G, const AbstractMatrix<T>& DtX, SpMatrix<T>& spalpha, int L, const T constraint, constraint_type mode = PENALTY, const bool pos = false, const bool ols = false, const int numThreads=-1, Matrix<T>* path = NULL, const int length_path=-1); /// second implementation using matrix inversion lemma template <typename T> void lasso2(const Matrix<T>& X, const Matrix<T>& D, SpMatrix<T>& spalpha, int L, const T constraint,const T lambda2=0, constraint_type mode = PENALTY, const bool pos = false, const int numThreads = -1, Matrix<T>* path = NULL, const int length_path=-1); template <typename T> void lasso2(const Data<T>& X, const AbstractMatrix<T>& G, const AbstractMatrix<T>& DtX, SpMatrix<T>& spalpha, int L, const T constraint, constraint_type mode = PENALTY, const bool pos = false, const int numThreads = -1, Matrix<T>* path = NULL, const int length_path=-1); /// second implementation using matrix inversion lemma template <typename T> void lasso_mask(const Matrix<T>& X, const Matrix<T>& D, SpMatrix<T>& spalpha, const Matrix<bool>& mask, int L, const T constraint,const T lambda2=0, constraint_type mode = PENALTY, const bool pos = false, const int numThreads = -1); /// second implementation using matrix inversion lemma template <typename T> void lassoReweighted(const Matrix<T>& X, const Matrix<T>& D, SpMatrix<T>& spalpha, int L, const T constraint, constraint_type mode, const bool pos, const T sigma, const int numThreads = -1); /// Auxiliary function for lasso template <typename T> void coreLARS(Vector<T>& Rdn, Vector<T>& Xdn, Vector<T>& A, Vector<T>& u, Vector<T>& sig, Vector<T>& av, Vector<T>& RUn, Matrix<T>& Un, Matrix<T>& Unds, Matrix<T>& Gs, Matrix<T>& Gsa, Matrix<T>& workT, Matrix<T>& R, const AbstractMatrix<T>& G,T& normX, Vector<int>& ind,Vector<T>& coeffs,const T constraint, const bool ols = false, const bool pos =false, constraint_type mode = L1COEFFS, T* path = NULL, int length_path=-1); template <typename T> void coreLARS2(Vector<T>& DtR, const AbstractMatrix<T>& G, Matrix<T>& Gs, Matrix<T>& Ga, Matrix<T>& invGs, Vector<T>& u, Vector<T>& coeffs, Vector<int>& ind, Matrix<T>& work, T& normX, const constraint_type mode, const T constraint, const bool pos = false, T* pr_path = NULL, int length_path = -1); template <typename T> void coreLARS2W(Vector<T>& DtR, AbstractMatrix<T>& G, Matrix<T>& Gs, Matrix<T>& Ga, Matrix<T>& invGs, Vector<T>& u, Vector<T>& coeffs, const Vector<T>& weights, Vector<int>& ind, Matrix<T>& work, T& normX, const constraint_type mode, const T constraint, const bool pos = false); /// Auxiliary functoni for coreLARS (Cholesky downdate) template <typename T> void downDateLasso(int& j,int& minBasis,T& normX,const bool ols, const bool pos, Vector<T>& Rdn, int* ind, T* coeffs, Vector<T>& sig, Vector<T>& av, Vector<T>& Xdn, Vector<T>& RUn,Matrix<T>& Unm, Matrix<T>& Gsm, Matrix<T>& Gsam, Matrix<T>& Undsm, Matrix<T>& Rm); /* ************************ * Iterative thresholding * ************************/ /// Implementation of IST for solving /// \forall i, \min_{\alpha_i} ||\alpha_i||_1 /// s.t. ||\X_i-D\alpha_i||_2^2 <= constraint or /// \forall i, \min_{\alpha_i} constraint*||\alpha_i||_1 + ... /// ... ||\X_i-D\alpha_i||_2^2 <= T template <typename T> void ist(const Matrix<T>& X, const Matrix<T>& D, SpMatrix<T>& spalpha, T lambda, constraint_type mode, const int itermax=500, const T tol = 0.5, const int numThreads = -1); template <typename T> void ist(const Matrix<T>& X, const Matrix<T>& D, Matrix<T>& spalpha, T lambda, constraint_type mode, const int itermax=500, const T tol = 0.5, const int numThreads=-1); /// coreIST template <typename T> void coreIST(const AbstractMatrix<T>& G, Vector<T>& DtR, Vector<T>& coeffs, const T thrs, const int itermax = 500, const T tol = 0.5); /// coreIST constrained template <typename T> void coreISTconstrained(const AbstractMatrix<T>& G, Vector<T>& DtR, Vector<T>& coeffs, const T normX2, const T thrs, const int itermax = 500, const T tol = 0.5); /// ist for group Lasso template <typename T> void ist_groupLasso(const Matrix<T>* XT, const Matrix<T>& D, Matrix<T>* alphaT, const int Ngroups, const T lambda, const constraint_type mode, const int itermax = 500, const T tol = 0.5, const int numThreads = -1); /// Auxiliary function for ist_groupLasso template <typename T> void coreGroupIST(const Matrix<T>& G, Matrix<T>& RtD, Matrix<T>& alphat, const T thrs, const int itermax=500, const T tol = 0.5); /// Auxiliary function for ist_groupLasso template <typename T> void coreGroupISTConstrained(const Matrix<T>& G, Matrix<T>& RtD, Matrix<T>& alphat, const T normR, const T eps, const int itermax=500, const T tol = 0.5); /// auxiliary function for ist_groupLasso template <typename T> T computeError(const T normX2,const Vector<T>& norms, const Matrix<T>& G,const Matrix<T>& RtD,const Matrix<T>& alphat); /// auxiliary function for ist_groupLasso template <typename T> T computeError(const T normX2, const Matrix<T>& G,const Vector<T>& DtR,const Vector<T>& coeffs, SpVector<T>& coeffs_tmp); /* ****************** * Simultaneous OMP * *****************/ template <typename T> void somp(const Matrix<T>* X, const Matrix<T>& D, SpMatrix<T>* spalpha, const int Ngroups, const int L, const T* pr_eps, const bool adapt=false, const int numThreads=-1); template <typename T> void somp(const Matrix<T>* X, const Matrix<T>& D, SpMatrix<T>* spalpha, const int Ngroups, const int L, const T eps, const int numThreads=-1); template <typename T> void coreSOMP(const Matrix<T>& X, const Matrix<T>& D, const Matrix<T>& G, Matrix<T>& vM, Vector<int>& rv, const int L, const T eps); /* ********************* * Implementation of OMP * *********************/ /// Forward Selection (or Orthogonal matching pursuit) /// Address the problem of: /// \forall i, \min_{\alpha_i} ||X_i-D\alpha_i||_2^2 /// s.t. ||\alphai||_0 <= L or /// \forall i, \min_{\alpha_i} ||\alpha_i||_0 /// s.t. ||\X_i-D\alpha_i||_2^2 <= epsilon /// This function is /// * efficient (Cholesky-based) /// * parallel /// * optimized for a big number of signals (precompute the Gramm matrix template <typename T> void omp(const Matrix<T>& X, const Matrix<T>& D, SpMatrix<T>& spalpha, const int* pL, const T* peps, const T* pLambda, const bool vecL, const bool vecEps, const bool vecLambda, const int numThreads, Matrix<T>* path) { int L; if (!vecL) { L=*pL; } else { Vector<int> vL(const_cast<int*>(pL),X.n()); L=vL.maxval(); } spalpha.clear(); if (L <= 0) return; const int M = X.n(); const int K = D.n(); L = MIN(X.m(),MIN(L,K)); Matrix<T> vM(L,M); Matrix<int> rM(L,M); ProdMatrix<T> G(D, K < 25000 && M > 10); int NUM_THREADS=init_omp(numThreads); Vector<T>* scoresT=new Vector<T>[NUM_THREADS]; Vector<T>* normT=new Vector<T>[NUM_THREADS]; Vector<T>* tmpT=new Vector<T>[NUM_THREADS]; Vector<T>* RdnT=new Vector<T>[NUM_THREADS]; Matrix<T>* UnT=new Matrix<T>[NUM_THREADS]; Matrix<T>* UndnT=new Matrix<T>[NUM_THREADS]; Matrix<T>* UndsT=new Matrix<T>[NUM_THREADS]; Matrix<T>* GsT=new Matrix<T>[NUM_THREADS]; for (int i = 0; i<NUM_THREADS; ++i) { scoresT[i].resize(K); normT[i].resize(K); tmpT[i].resize(K); RdnT[i].resize(K); UnT[i].resize(L,L); UnT[i].setZeros(); UndnT[i].resize(K,L); UndsT[i].resize(L,L); GsT[i].resize(K,L); } int i; #pragma omp parallel for private(i) for (i = 0; i< M; ++i) { #ifdef _OPENMP int numT=omp_get_thread_num(); #else int numT=0; #endif Vector<T> Xi; X.refCol(i,Xi); T normX = Xi.nrm2sq(); Vector<int> ind; rM.refCol(i,ind); ind.set(-1); Vector<T> RUn; vM.refCol(i,RUn); Vector<T>& Rdn=RdnT[numT]; D.multTrans(Xi,Rdn); coreORMP(scoresT[numT],normT[numT],tmpT[numT],UnT[numT],UndnT[numT],UndsT[numT], GsT[numT],Rdn,G,ind,RUn, normX, vecEps ? peps+i : peps, vecL ? pL+i : pL, vecLambda ? pLambda+i : pLambda, path && i==0 ? path->rawX() : NULL); } delete[](scoresT); delete[](normT); delete[](tmpT); delete[](RdnT); delete[](UnT); delete[](UndnT); delete[](UndsT); delete[](GsT); /// convert the sparse matrix into a proper format spalpha.convert(vM,rM,K); }; template <typename T> void omp_mask(const Matrix<T>& X, const Matrix<T>& D, SpMatrix<T>& spalpha, const Matrix<bool>& mask, const int *pL, const T* peps, const T* pLambda, const bool vecL, const bool vecEps, const bool vecLambda, const int numThreads, Matrix<T>* path) { int L; if (!vecL) { L=*pL; } else { Vector<int> vL(const_cast<int*>(pL),X.n()); L=vL.maxval(); } spalpha.clear(); if (L <= 0) return; const int M = X.n(); const int K = D.n(); L = MIN(X.m(),MIN(L,K)); Matrix<T> vM(L,M); Matrix<int> rM(L,M); ProdMatrix<T> G(D, K < 25000 && M > 10); int NUM_THREADS=init_omp(numThreads); Vector<T>* scoresT=new Vector<T>[NUM_THREADS]; Vector<T>* normT=new Vector<T>[NUM_THREADS]; Vector<T>* tmpT=new Vector<T>[NUM_THREADS]; Vector<T>* RdnT=new Vector<T>[NUM_THREADS]; Matrix<T>* UnT=new Matrix<T>[NUM_THREADS]; Matrix<T>* UndnT=new Matrix<T>[NUM_THREADS]; Matrix<T>* UndsT=new Matrix<T>[NUM_THREADS]; Matrix<T>* GsT=new Matrix<T>[NUM_THREADS]; ProdMatrix<T>* GT=new ProdMatrix<T>[NUM_THREADS]; Matrix<T>* DmaskT=new Matrix<T>[NUM_THREADS]; Vector<T>* XmaskT=new Vector<T>[NUM_THREADS]; for (int i = 0; i<NUM_THREADS; ++i) { DmaskT[i].resize(D.m(),D.n()); XmaskT[i].resize(X.m()); scoresT[i].resize(K); normT[i].resize(K); tmpT[i].resize(K); RdnT[i].resize(K); UnT[i].resize(L,L); UnT[i].setZeros(); UndnT[i].resize(K,L); UndsT[i].resize(L,L); GsT[i].resize(K,L); } int i; #pragma omp parallel for private(i) for (i = 0; i< M; ++i) { #ifdef _OPENMP int numT=omp_get_thread_num(); #else int numT=0; #endif Vector<T> Xi; X.refCol(i,Xi); Vector<int> ind; rM.refCol(i,ind); ind.set(-1); Vector<T> RUn; vM.refCol(i,RUn); Vector<bool> maski; mask.refCol(i,maski); Vector<T>& Rdn=RdnT[numT]; if (maski.allfalse()) continue; if (maski.alltrue()) { D.multTrans(Xi,Rdn); T normX = Xi.nrm2sq(); coreORMP(scoresT[numT],normT[numT],tmpT[numT],UnT[numT],UndnT[numT],UndsT[numT], GsT[numT],Rdn,G,ind,RUn, normX, vecEps ? peps+i : peps, vecL ? pL+i : pL, vecLambda ? pLambda+i : pLambda, path && i==0 ? path->rawX() : NULL); } else { D.copyMask(DmaskT[numT],maski); Xi.copyMask(XmaskT[numT],maski); T normX = XmaskT[numT].nrm2sq(); DmaskT[numT].multTrans(XmaskT[numT],Rdn); GT[numT].setMatrices(DmaskT[numT],false); GT[numT].addDiag(T(1e-10)); T eps_mask= (vecEps ? *(peps+i) : *peps)*XmaskT[numT].n()/Xi.n(); coreORMP(scoresT[numT],normT[numT],tmpT[numT], UnT[numT],UndnT[numT],UndsT[numT], GsT[numT],Rdn,GT[numT],ind,RUn, normX, &eps_mask, vecL ? pL+i : pL, vecLambda ? pLambda+i : pLambda, path && i==0 ? path->rawX() : NULL); DmaskT[numT].setm(D.m()); DmaskT[numT].setn(D.n()); XmaskT[numT].setn(X.m()); } } delete[](GT); delete[](XmaskT); delete[](DmaskT); delete[](scoresT); delete[](normT); delete[](tmpT); delete[](RdnT); delete[](UnT); delete[](UndnT); delete[](UndsT); delete[](GsT); /// convert the sparse matrix into a proper format spalpha.convert(vM,rM,K); }; /// Auxiliary function of omp template <typename T> void coreORMPB(Vector<T>& RtD, const AbstractMatrix<T>& G, Vector<int>& ind, Vector<T>& coeffs, T& normX, const int L, const T eps, const T lambda) { const int K = G.n(); Vector<T> scores(K); Vector<T> norm(K); Vector<T> tmp(K); Matrix<T> Un(L,L); Matrix<T> Undn(K,L); Matrix<T> Unds(L,L); Matrix<T> Gs(K,L); ind.set(-1); coreORMP(scores,norm,tmp,Un,Undn,Unds,Gs,RtD,G,ind,coeffs,normX,&eps,&L,&lambda); }; /// Auxiliary function of omp template <typename T> void coreORMP(Vector<T>& scores, Vector<T>& norm, Vector<T>& tmp, Matrix<T>& Un, Matrix<T>& Undn, Matrix<T>& Unds, Matrix<T>& Gs, Vector<T>& Rdn, const AbstractMatrix<T>& G, Vector<int>& ind, Vector<T>& RUn, T& normX, const T* peps, const int* pL, const T* plambda, T* path) { const T eps = abs<T>(*peps); const int L = MIN(*pL,Gs.n()); const T lambda=*plambda; if ((normX <= eps) || L == 0) return; const int K = scores.n(); scores.copy(Rdn); norm.set(T(1.0)); Un.setZeros(); // permit unsafe low level access T* const prUn = Un.rawX(); T* const prUnds = Unds.rawX(); T* const prUndn = Undn.rawX(); T* const prGs = Gs.rawX(); T* const prRUn= RUn.rawX(); if (path) memset(path,0,K*L*sizeof(T)); int j; for (j = 0; j<L; ++j) { const int currentInd=scores.fmax(); if (norm[currentInd] < 1e-8) { ind[j]=-1; break; } const T invNorm=T(1.0)/sqrt(norm[currentInd]); const T RU=Rdn[currentInd]*invNorm; const T delta = RU*RU; if (delta < 2*lambda) { break; } RUn[j]=RU; normX -= delta; ind[j]=currentInd; //for (int k = 0; k<j; ++k) prUn[j*L+k]=0.0; //prUn[j*L+j]=T(1.0); // for (int k = 0; k<j; ++k) prUnds[k*L+j]=prUndn[k*K+currentInd]; // MGS algorithm, Update Un // int iter = norm[currentInd] < 0.5 ? 2 : 1; //int iter=1; // for (int k = 0; k<iter; ++k) { /// for (int l = 0; l<j; ++l) { // T scal=-cblas_dot<T>(j+1-l,prUn+j*L+l,1,prUnds+l*L+l,1); // T scal = -prUnds[l*L+j]; // cblas_axpy<T>(l+1,scal,prUn+l*L,1,prUn+j*L,1); // } // } prUn[j*L+j]=-T(1.0); cblas_copy<T>(j,prUndn+currentInd,K,prUn+j*L,1); cblas_trmv<T>(CblasColMajor,CblasUpper,CblasNoTrans,CblasNonUnit,j,prUn,L,prUn+j*L,1); cblas_scal<T>(j+1,-invNorm,prUn+j*L,1); if (j == L-1 || (normX <= eps)) { ++j; break; } if (path) { T* last_path=path+(L-1)*K; cblas_copy<T>(j+1,prRUn,1,last_path,1); cblas_trmv<T>(CblasColMajor,CblasUpper,CblasNoTrans,CblasNonUnit, j+1,prUn,L,last_path,1); for (int k = 0; k<=j; ++k) { path[j*K+ind[k]]=last_path[k]; } } // update the variables Gs, Undn, Unds, Rdn, norm, scores Vector<T> Gsj; Gs.refCol(j,Gsj); G.copyCol(currentInd,Gsj); cblas_gemv<T>(CblasColMajor,CblasNoTrans,K,j+1,T(1.0),prGs,K,prUn+j*L,1, T(0.0),prUndn+j*K,1); // prUnds[j*L+j] = prUndn[j*K+currentInd]; Vector<T> Undnj; Undn.refCol(j,Undnj); Rdn.add(Undnj,-RUn[j]); tmp.sqr(Undnj); norm.sub(tmp); scores.sqr(Rdn); scores.div(norm); for (int k = 0; k<=j; ++k) scores[ind[k]]=T(); } // compute the final coefficients cblas_trmv<T>(CblasColMajor,CblasUpper,CblasNoTrans,CblasNonUnit, j,prUn,L,prRUn,1); if (path) { memset(path+(L-1)*K,0,L*sizeof(T)); for (int k = 0; k<j; ++k) { path[(j-1)*K+ind[k]]=prRUn[k]; } } }; /* ************** * LARS - Lasso * **************/ /// Implementation of LARS-Lasso for solving /// \forall i, \min_{\alpha_i} ||X_i-D\alpha_i||_2^2 /// s.t. ||\alphai||_1 <= constraint or /// \forall i, \min_{\alpha_i} ||\alpha_i||_1 /// s.t. ||\X_i-D\alpha_i||_2^2 <= constraint or /// \forall i, \min_{\alpha_i} constraint*||\alpha_i||_1 + ... /// ... ||\X_i-D\alpha_i||_2^2 <= T /// Optionally, the solution might be positive (boolean pos), and a /// Least-Square can be solved as a post-processing step. /// L is a maximum number of coefficients. /// This function is /// * efficient (Cholesky-based) /// * parallel /// * optimized for a big number of signals (precompute the Gramm matrix template <typename T> void lasso(const Matrix<T>& X, const Matrix<T>& D, SpMatrix<T>& spalpha, int L, const T lambda, const T lambda2, constraint_type mode, const bool pos, const bool ols, const int numThreads, Matrix<T>* path, const int length_path) { ProdMatrix<T> G(D, X.n() > 10 && D.n() < 50000); G.addDiag(MAX(lambda2,1e-10)); ProdMatrix<T> DtX(D,X,false); lasso(X,G,DtX,spalpha,L,lambda,mode,pos,ols,numThreads,path,length_path); } template <typename T> void lasso(const Data<T>& X, const AbstractMatrix<T>& G, const AbstractMatrix<T>& DtX, SpMatrix<T>& spalpha, int L, const T lambda, constraint_type mode, const bool pos, const bool ols, const int numThreads, Matrix<T>* path, const int length_path) { spalpha.clear(); const int M = X.n(); const int K = G.n(); Matrix<T> vM; Matrix<int> rM; vM.resize(L,M); rM.resize(L,M); if (L <= 0) return; if (path) path->setZeros(); int NUM_THREADS=init_omp(numThreads); //ProdMatrix<T> G(D, K < 25000 && M > 10); Vector<T>* RdnT=new Vector<T>[NUM_THREADS]; Vector<T>* XdnT =new Vector<T>[NUM_THREADS]; Vector<T>* AT=new Vector<T>[NUM_THREADS]; Vector<T>* uT=new Vector<T>[NUM_THREADS]; Vector<T>* sigT=new Vector<T>[NUM_THREADS]; Vector<T>* avT=new Vector<T>[NUM_THREADS]; Vector<T>* RUnT = new Vector<T>[NUM_THREADS]; Matrix<T>* UnT=new Matrix<T>[NUM_THREADS]; Matrix<T>* RT=new Matrix<T>[NUM_THREADS]; Matrix<T>* UndsT=new Matrix<T>[NUM_THREADS]; Matrix<T>* GsT=new Matrix<T>[NUM_THREADS]; Matrix<T>* GsaT=new Matrix<T>[NUM_THREADS]; Matrix<T>* workT=new Matrix<T>[NUM_THREADS]; for (int i = 0; i<NUM_THREADS; ++i) { RdnT[i].resize(K); if (ols) XdnT[i].resize(K); AT[i].resize(K); uT[i].resize(L); sigT[i].resize(L); avT[i].resize(L); if (ols) RUnT[i].resize(L); UnT[i].resize(L,L); UnT[i].setZeros(); UndsT[i].resize(L,L); UndsT[i].setZeros(); GsT[i].resize(K,L); GsaT[i].resize(L,L); workT[i].resize(K,2); RT[i].resize(L,L); } Vector<T> norms; X.norm_2sq_cols(norms); int i; #pragma omp parallel for private(i) for (i = 0; i< M; ++i) { #ifdef _OPENMP int numT=omp_get_thread_num(); #else int numT=0; #endif T normX = norms[i]; Vector<int> ind; rM.refCol(i,ind); Vector<T> coeffs; vM.refCol(i,coeffs); coeffs.setZeros(); Vector<T>& Rdn=RdnT[numT]; DtX.copyCol(i,Rdn); coreLARS(Rdn,XdnT[numT], AT[numT], uT[numT], sigT[numT], avT[numT], RUnT[numT], UnT[numT], UndsT[numT], GsT[numT], GsaT[numT], workT[numT],RT[numT],G,normX, ind,coeffs,lambda,ols,pos, mode,path && i==0 ? path->rawX() : NULL, length_path); } delete[](RdnT); delete[](XdnT); delete[](AT); delete[](uT); delete[](sigT); delete[](avT); delete[](RUnT); delete[](UnT); delete[](RT); delete[](UndsT); delete[](GsT); delete[](GsaT); delete[](workT); /// convert the sparse matrix into a proper format spalpha.convert(vM,rM,K); }; /// Auxiliary function for lasso template <typename T> void coreLARS(Vector<T>& Rdnv, Vector<T>& Xdnv, Vector<T>& Av, Vector<T>& uv, Vector<T>& sigv, Vector<T>& avv, Vector<T>& RUnv, Matrix<T>& Unm, Matrix<T>& Undsm, Matrix<T>& Gsm, Matrix<T>& Gsam, Matrix<T>& workm, Matrix<T>& Rm, const AbstractMatrix<T>& Gm,T& normX, Vector<int>& indv,Vector<T>& coeffsv,const T constraint, const bool ols,const bool pos, constraint_type mode, T* path, int length_path) { if (mode == L2ERROR && normX < constraint) return; const int LL = Gsm.n(); const int K = Gsm.m(); const int L = MIN(LL,K); if (length_path <= 1) length_path=4*L; // permit unsafe fast low level access T* const Rdn = Rdnv.rawX(); T* const Xdn = Xdnv.rawX(); T* const A = Av.rawX(); T* const u = uv.rawX(); T* const sig = sigv.rawX(); T* const av = avv.rawX(); T* const RUn = RUnv.rawX(); T* const Un = Unm.rawX(); T* const Unds = Undsm.rawX(); T* const Gs = Gsm.rawX(); T* const Gsa = Gsam.rawX(); T* const work = workm.rawX(); //T* const G = Gm.rawX(); T* const R = Rm.rawX(); int* ind = indv.rawX(); T* coeffs = coeffsv.rawX(); coeffsv.setZeros(); indv.set(-1); if (ols) Xdnv.copy(Rdnv); int currentInd= pos ? Rdnv.max() : Rdnv.fmax(); bool newAtom=true; T Cmax; int iter=1; T thrs = 0.0; int* const ind_orig = ind; T* const coeffs_orig = coeffs; int j; for (j = 0; j<L; ++j) { if (newAtom) { ind[j]=currentInd; if (pos) { Cmax = Rdn[currentInd]; sig[j]=1.0; } else { Cmax = abs<T>(Rdn[currentInd]); sig[j] = SIGN(Rdn[currentInd]); } for (int k = 0; k<=j; ++k) Un[j*L+k]=0.0; Un[j*L+j]=1.0; Gm.extract_rawCol(currentInd,Gs+K*j); for (int k = 0; k<j; ++k) Gs[K*j+ind[k]] *= sig[k]; if (sig[j] < 0) { Rdn[currentInd]=-Rdn[currentInd]; if (ols) Xdn[currentInd]=-Xdn[currentInd]; cblas_scal<T>(K,sig[j],Gs+K*j,1); cblas_scal<T>(j+1,sig[j],Gs+currentInd,K); } cblas_copy<T>(j+1,Gs+currentInd,K,Gsa+j*L,1); for (int k = 0; k<j; ++k) Gsa[k*L+j]=Gsa[j*L+k]; // <d_j,d_i> cblas_copy<T>(j,Gsa+j*L,1,Unds+j,L); // <U_j final,d_i> cblas_trmv<T>(CblasColMajor,CblasUpper,CblasTrans,CblasNonUnit, j+1,Un,L,Unds+j,L); // norm2 T norm2=Gsa[j*L+j]; for (int k = 0; k<j; ++k) norm2 -= Unds[k*L+j]*Unds[k*L+j]; if (norm2 < 1e-15) { ind[j]=-1; // cerr << "bad exit" << endl; break; } // int iter2 = norm2 < 0.5 ? 2 : 1; // for(int k = 0; k<iter2; ++k) { // for (int l = 0; l<j; ++l) { // T scal=-cblas_dot<T>(j+1-l,Un+j*L+l,1,Unds+l*L+l,1); // cblas_axpy<T>(l+1,scal,Un+l*L,1,Un+j*L,1); // } // } Un[j*L+j]=-T(1.0); cblas_copy<T>(j,Unds+j,L,Un+j*L,1); cblas_trmv<T>(CblasColMajor,CblasUpper,CblasNoTrans,CblasNonUnit,j,Un,L,Un+j*L,1); /// Un is the orthogonalized vectors in the D basis T invNorm=1.0/sqrt(norm2); cblas_scal<T>(j+1,-invNorm,Un+j*L,1); Unds[j*L+j]=cblas_dot<T>(j+1,Un+j*L,1,Gsa+j*L,1); } for (int k = 0; k<=j; ++k) u[k]=T(1.0); cblas_trmv<T>(CblasColMajor,CblasUpper,CblasTrans,CblasNonUnit, j+1,Un,L,u,1); T a = T(1.0)/cblas_nrm2<T>(j+1,u,1); cblas_trmv<T>(CblasColMajor,CblasUpper,CblasNoTrans,CblasNonUnit, j+1,Un,L,u,1); cblas_scal<T>(j+1,a,u,1); cblas_gemv<T>(CblasColMajor,CblasNoTrans,K,j+1,T(1.0),Gs,K,u,1,T(0.0),A,1); T potentNorm=0.0; if (!ols) { for (int k = 0; k<=j; ++k) potentNorm += Rdn[ind[k]]*u[k]; } if (pos) { for (int k = 0; k<K; ++k) { T diff = a-A[k]; work[k]= diff <= 0 ? INFINITY : (Cmax-Rdn[k])/diff; } for (int k = 0; k<=j; ++k) { work[ind[k]]=INFINITY; } for (int k = 0; k<K; ++k) if (work[k] <=0) work[k]=INFINITY; currentInd =cblas_iamin<T>(K,work,1); } else { memset(work,0,2*K*sizeof(T)); for (int k = 0; k<=j; ++k) { const int index=2*ind[k]; work[index]=INFINITY; work[index+1]=INFINITY; } for (int k = 0; k<K; ++k) { const int index=2*k; if (!work[index]) { const T diff1=a-A[k]; work[index]= diff1 <= 0 ? INFINITY : (Cmax-Rdn[k])/diff1; const T diff2=a+A[k]; work[index+1]=diff2 <= 0 ? INFINITY : (Cmax+Rdn[k])/diff2; } } currentInd =cblas_iamin<T>(2*K,work,1); } T gamma=work[currentInd]; T gammaMin=0; int minBasis=0; //if (j == L-1) gamma=potentNorm; if (mode == PENALTY) { gamma=MIN(gamma,(Cmax-constraint)/a); } // if (j > 0) { vDiv<T>(j+1,coeffs,u,work); cblas_scal<T>(j+1,-T(1.0),work,1); /// voir pour petites valeurs for (int k=0; k<=j; ++k) if (coeffs[k]==0 || work[k] <=0) work[k]=INFINITY; minBasis=cblas_iamin<T>(j+1,work,1); gammaMin=work[minBasis]; if (gammaMin < gamma) gamma=gammaMin; // } if (mode == L1COEFFS) { T Tu = 0.0; for (int k = 0; k<=j; ++k) Tu += u[k]; if (Tu > EPSILON) gamma= MIN(gamma,(constraint-thrs)/Tu); thrs+=gamma*Tu; } // compute the norm of the residdual if (ols == 0) { const T t = gamma*gamma - 2*gamma*potentNorm; if (t > 0 || isnan(t) || isinf(t)) { // cerr << "bad bad exit" << endl; // cerr << t << endl; ind[j]=-1; break; } normX += t; } else { // plan the last orthogonal projection if (newAtom) { RUn[j]=0.0; for (int k = 0; k<=j; ++k) RUn[j] += Xdn[ind[k]]* Un[j*L+k]; normX -= RUn[j]*RUn[j]; } } // Update the coefficients cblas_axpy<T>(j+1,gamma,u,1,coeffs,1); if (pos) { for (int k = 0; k<j+1; ++k) if (coeffs[k] < 0) coeffs[k]=0; } cblas_axpy<T>(K,-gamma,A,1,Rdn,1); if (!pos) currentInd/= 2; if (path) { for (int k = 0; k<=j; ++k) path[iter*K+ind[k]]=coeffs[k]*sig[k]; } if (gamma == gammaMin) { downDateLasso<T>(j,minBasis,normX,ols,pos,Rdnv,ind,coeffs,sigv, avv,Xdnv, RUnv, Unm, Gsm, Gsam,Undsm,Rm); newAtom=false; Cmax=abs<T>(Rdn[ind[0]]); --j; } else { newAtom=true; } ++iter; if (mode == PENALTY) { thrs=abs<T>(Rdn[ind[0]]); } if ((j == L-1) || (mode == PENALTY && (thrs - constraint < 1e-15)) || (mode == L1COEFFS && (thrs - constraint > -1e-15)) || (newAtom && mode == L2ERROR && (normX - constraint < 1e-15)) || (normX < 1e-15) || (iter >= length_path)) { // cerr << "exit" << endl; // PRINT_F(thrs) // PRINT_F(constraint) // PRINT_F(normX) break; } } if (ols) { cblas_copy<T>(j+1,RUn,1,coeffs,1); cblas_trmv<T>(CblasColMajor,CblasUpper,CblasNoTrans,CblasNonUnit, j+1,Un,L,coeffs,1); } vMul<T>(j+1,coeffs,sig,coeffs); }; /// Auxiliary functoni for coreLARS (Cholesky downdate) template <typename T> inline void downDateLasso(int& j,int& minBasis,T& normX,const bool ols, const bool pos, Vector<T>& Rdnv, int* ind, T* coeffs, Vector<T>& sigv, Vector<T>& avv, Vector<T>& Xdnv, Vector<T>& RUnv,Matrix<T>& Unm, Matrix<T>& Gsm, Matrix<T>& Gsam, Matrix<T>& Undsm, Matrix<T>& Rm) { int k,l; const int L = Gsm.n(); const int K = Gsm.m(); T* const Rdn = Rdnv.rawX(); T* const Xdn = Xdnv.rawX(); T* const sig = sigv.rawX(); T* const av = avv.rawX(); T* const RUn = RUnv.rawX(); T* const Un = Unm.rawX(); T* const Unds = Undsm.rawX(); T* const Gs = Gsm.rawX(); T* const Gsa = Gsam.rawX(); T* const R = Rm.rawX(); int indB=ind[minBasis]; if (!pos && sig[minBasis] < 0) { // Update Rdn Rdn[indB]=-Rdn[indB]; if (ols) Xdn[indB]=-Xdn[indB]; } int num=j-minBasis; for (int k = 0; k<num*num;++k) R[k]=0.0; for (int k = 0; k<num; ++k) R[k*num+k]=1.0; // Update Un for (int k = minBasis+1; k<=j; ++k) { T a = -Un[k*L+minBasis]/Un[minBasis*L+minBasis]; av[k-minBasis-1] = a; cblas_axpy<T>(minBasis,a,Un+minBasis*L,1,Un+k*L,1); } for (int k = minBasis+1; k<=j; ++k) { cblas_copy<T>(minBasis,Un+k*L,1,Un+(k-1)*L,1); cblas_copy<T>(num,Un+k*L+minBasis+1,1,Un+(k-1)*L+minBasis,1); } T alpha=1.0; T alphab,gamma,lambda; for (int k = 0; k<num; ++k) { alphab=alpha+av[k]*av[k]; R[k*num+k]=sqrt(alphab/alpha); gamma=av[k]*R[k*num+k]/alphab; alpha=alphab; cblas_copy<T>(num-k-1,av+k+1,1,R+k*num+k+1,1); cblas_scal<T>(num-k-1,gamma,R+k*num+k+1,1); } if (num > 0) { trtri<T>(low,nonUnit,num,R,num); cblas_trmm<T>(CblasColMajor,CblasRight,CblasLower,CblasTrans,CblasNonUnit, j,num,T(1.0),R,num,Un+minBasis*L,L); } // Update Unds for (int k = minBasis+1; k<=j; ++k) cblas_axpy<T>(j-minBasis,av[k-minBasis-1],Unds+minBasis*L+minBasis+1,1, Unds+k*L+minBasis+1,1); for (int k = 0; k<minBasis; ++k) for (int l = minBasis+1; l<=j; ++l) Unds[k*L+l-1]=Unds[k*L+l]; for (int k = minBasis+1; k<=j; ++k) cblas_copy<T>(j-minBasis,Unds+k*L+minBasis+1,1,Unds+(k-1)*L+minBasis,1); if (num > 0) cblas_trmm<T>(CblasColMajor,CblasRight,CblasLower,CblasTrans,CblasNonUnit, j-minBasis,num,T(1.0),R,num,Unds+minBasis*L+minBasis,L); for (int k = minBasis+1; k<=j; ++k) for (int l = 0; l<k; ++l) Unds[k*L+l]=0.0; // Update Gs for (int k = minBasis+1; k<=j; ++k) { cblas_copy<T>(K,Gs+k*K,1,Gs+(k-1)*K,1); } if (!pos && sig[minBasis] < T(0.0)) cblas_scal<T>(j,T(-1.0),Gs+indB,K); // Update Gsa for (int k = minBasis+1; k<=j; ++k) { cblas_copy<T>(minBasis,Gsa+k*L,1,Gsa+(k-1)*L,1); cblas_copy<T>(j-minBasis,Gsa+k*L+minBasis+1,1,Gsa+(k-1)*L+minBasis,1); } for (int k = 0; k<minBasis; ++k) { for (int l = minBasis+1; l<=j; ++l) Gsa[k*L+l-1]=Gsa[k*L+l]; } // Update sig for (int k = minBasis+1; k<=j && !pos; ++k) sig[k-1]=sig[k]; // Update ind for (int k = minBasis+1; k<=j; ++k) ind[k-1]=ind[k]; ind[j]=-1; for (int k = minBasis+1; k<=j; ++k) coeffs[k-1]=coeffs[k]; coeffs[j]=0.0; if (ols) { // Update RUn and normX for (int k = minBasis; k<=j; ++k) normX += RUn[k]*RUn[k]; for (int k = minBasis; k<j; ++k) { RUn[k]=0.0; for (int l = 0; l<=k; ++l) RUn[k] += Xdn[ind[l]]* Un[k*L+l]; normX -= RUn[k]*RUn[k]; } } // Update j --j; } /// second implementation using matrix inversion lemma template <typename T> void lassoReweighted(const Matrix<T>& X, const Matrix<T>& D, SpMatrix<T>& spalpha, int L, const T constraint, constraint_type mode, const bool pos, const T sigma, const int numThreads) { spalpha.clear(); const int M = X.n(); const int K = D.n(); Matrix<T> vM; Matrix<int> rM; vM.resize(L,M); rM.resize(L,M); const int iterR = 30; if (L <= 0) return; int NUM_THREADS=init_omp(numThreads); //ProdMatrix<T> G(D, K < 25000 && M > 10); ProdMatrix<T> G(D, K < 50000); //Matrix<T> G; //D.XtX(G); G.addDiag(1e-10); Vector<T>* DtRT=new Vector<T>[NUM_THREADS]; Vector<T>* DtRRT=new Vector<T>[NUM_THREADS]; Vector<T>* uT=new Vector<T>[NUM_THREADS]; Vector<T>* weightsT=new Vector<T>[NUM_THREADS]; Vector<int>* inddT=new Vector<int>[NUM_THREADS]; Matrix<T>* GsT=new Matrix<T>[NUM_THREADS]; Matrix<T>* GaT=new Matrix<T>[NUM_THREADS]; Matrix<T>* invGsT=new Matrix<T>[NUM_THREADS]; Matrix<T>* workT=new Matrix<T>[NUM_THREADS]; Matrix<T>* GT=new Matrix<T>[NUM_THREADS]; for (int i = 0; i<NUM_THREADS; ++i) { DtRT[i].resize(K); DtRRT[i].resize(K); uT[i].resize(K); weightsT[i].resize(K); GT[i].resize(K,K); inddT[i].resize(K); GsT[i].resize(L,L); invGsT[i].resize(L,L); GaT[i].resize(K,L); workT[i].resize(K,3); workT[i].setZeros(); } int i; #pragma omp parallel for private(i) for (i = 0; i< M; ++i) { #ifdef _OPENMP int numT=omp_get_thread_num(); #else int numT=0; #endif Vector<T> Xi; X.refCol(i,Xi); T normXo = Xi.nrm2sq(); T normX = normXo; Vector<int> ind; rM.refCol(i,ind); Vector<T> coeffs; vM.refCol(i,coeffs); Vector<T>& DtR=DtRT[numT]; Vector<T>& DtRR = DtRRT[numT]; D.multTrans(Xi,DtR); DtRR.copy(DtR); coreLARS2(DtRR,G,GsT[numT],GaT[numT],invGsT[numT],uT[numT],coeffs, ind,workT[numT],normX,mode,constraint,pos); //Matrix<T>& GG = GT[numT]; Vector<T>& weights = weightsT[numT]; //Vector<int>& indd = inddT[numT]; for (int j = 0; j<iterR; ++j) { const T sig = sigma*pow(0.7,iterR-1-j); weights.set(sig); for (int k = 0; k<K; ++k) { if (ind[k] != -1) { weights[ind[k]] = MAX(1e-4,sig*exp(-sig*abs<T>(coeffs[k]))); } else { break; } } DtRR.copy(DtR); normX=normXo; coreLARS2W(DtRR,G,GsT[numT],GaT[numT],invGsT[numT],uT[numT],coeffs,weights, ind,workT[numT],normX,mode,constraint,pos); } } delete[](DtRT); delete[](DtRRT); delete[](inddT); delete[](uT); delete[](weightsT); delete[](GsT); delete[](GT); delete[](GaT); delete[](invGsT); delete[](workT); /// convert the sparse matrix into a proper format spalpha.convert(vM,rM,K); } template <typename T> void lassoWeight(const Matrix<T>& X, const Matrix<T>& D, const Matrix<T>& weights, SpMatrix<T>& spalpha, int L, const T constraint, constraint_type mode, const bool pos, const int numThreads) { spalpha.clear(); const int M = X.n(); const int K = D.n(); Matrix<T> vM; Matrix<int> rM; vM.resize(L,M); rM.resize(L,M); if (L <= 0) return; int NUM_THREADS=init_omp(numThreads); //ProdMatrix<T> G(D, K < 25000 && M > 10); ProdMatrix<T> G(D, K < 50000); //Matrix<T> G; //D.XtX(G); G.addDiag(1e-10); Vector<T>* DtRT=new Vector<T>[NUM_THREADS]; Vector<T>* uT=new Vector<T>[NUM_THREADS]; Matrix<T>* GsT=new Matrix<T>[NUM_THREADS]; Matrix<T>* GaT=new Matrix<T>[NUM_THREADS]; Matrix<T>* invGsT=new Matrix<T>[NUM_THREADS]; Matrix<T>* workT=new Matrix<T>[NUM_THREADS]; for (int i = 0; i<NUM_THREADS; ++i) { DtRT[i].resize(K); uT[i].resize(K); uT[i].setZeros(); GsT[i].resize(L,L); invGsT[i].resize(L,L); GaT[i].resize(K,L); workT[i].resize(K,3); workT[i].setZeros(); } int i; #pragma omp parallel for private(i) for (i = 0; i< M; ++i) { #ifdef _OPENMP int numT=omp_get_thread_num(); #else int numT=0; #endif Vector<T> Xi; X.refCol(i,Xi); T normX = Xi.nrm2sq(); Vector<int> ind; rM.refCol(i,ind); Vector<T> coeffs; vM.refCol(i,coeffs); Vector<T>& DtR=DtRT[numT]; D.multTrans(Xi,DtR); Vector<T> we; weights.refCol(i,we); coreLARS2W(DtR,G,GsT[numT],GaT[numT],invGsT[numT],uT[numT],coeffs,we, ind,workT[numT],normX,mode,constraint,pos); } delete[](DtRT); delete[](uT); delete[](GsT); delete[](GaT); delete[](invGsT); delete[](workT); /// convert the sparse matrix into a proper format spalpha.convert(vM,rM,K); }; template <typename T> void lassoWeightPreComputed(const Matrix<T>& X, const Matrix<T>& G, const Matrix<T>& DtR, const Matrix<T>& weights, SpMatrix<T>& spalpha, int L, const T constraint, constraint_type mode, const bool pos, const int numThreads) { spalpha.clear(); const int M = X.n(); const int K = G.n(); Matrix<T> vM; Matrix<int> rM; vM.resize(L,M); rM.resize(L,M); if (L <= 0) return; int NUM_THREADS=init_omp(numThreads); Vector<T>* DtRT=new Vector<T>[NUM_THREADS]; Vector<T>* uT=new Vector<T>[NUM_THREADS]; Matrix<T>* GsT=new Matrix<T>[NUM_THREADS]; Matrix<T>* GaT=new Matrix<T>[NUM_THREADS]; Matrix<T>* invGsT=new Matrix<T>[NUM_THREADS]; Matrix<T>* workT=new Matrix<T>[NUM_THREADS]; for (int i = 0; i<NUM_THREADS; ++i) { DtRT[i].resize(K); uT[i].resize(K); uT[i].setZeros(); GsT[i].resize(L,L); invGsT[i].resize(L,L); GaT[i].resize(K,L); workT[i].resize(K,3); workT[i].setZeros(); } int i; #pragma omp parallel for private(i) for (i = 0; i< M; ++i) { #ifdef _OPENMP int numT=omp_get_thread_num(); #else int numT=0; #endif Vector<T> Xi; X.refCol(i,Xi); T normX = Xi.nrm2sq(); Vector<int> ind; rM.refCol(i,ind); Vector<T> coeffs; vM.refCol(i,coeffs); Vector<T>& DtRi=DtRT[numT]; DtR.copyCol(i,DtRi); Vector<T> we; weights.refCol(i,we); coreLARS2W(DtRi,G,GsT[numT],GaT[numT],invGsT[numT],uT[numT],coeffs,we, ind,workT[numT],normX,mode,constraint,pos); } delete[](DtRT); delete[](uT); delete[](GsT); delete[](GaT); delete[](invGsT); delete[](workT); /// convert the sparse matrix into a proper format spalpha.convert(vM,rM,K); }; /// second implementation using matrix inversion lemma template <typename T> void lasso_mask(const Matrix<T>& X, const Matrix<T>& D, SpMatrix<T>& spalpha, const Matrix<bool>& mask, int L, const T constraint,const T lambda2, constraint_type mode, const bool pos, const int numThreads) { spalpha.clear(); const int M = X.n(); const int K = D.n(); Matrix<T> vM; Matrix<int> rM; vM.resize(L,M); rM.resize(L,M); if (L <= 0) return; int NUM_THREADS=init_omp(numThreads); ProdMatrix<T> G(D,K < 25000 && M > 10); G.addDiag(MAX(lambda2,1e-10)); Vector<T>* DtRT=new Vector<T>[NUM_THREADS]; Vector<T>* uT=new Vector<T>[NUM_THREADS]; Vector<T>* XmaskT=new Vector<T>[NUM_THREADS]; Matrix<T>* GsT=new Matrix<T>[NUM_THREADS]; ProdMatrix<T>* GT=new ProdMatrix<T>[NUM_THREADS]; Matrix<T>* DmaskT=new Matrix<T>[NUM_THREADS]; Matrix<T>* GaT=new Matrix<T>[NUM_THREADS]; Matrix<T>* invGsT=new Matrix<T>[NUM_THREADS]; Matrix<T>* workT=new Matrix<T>[NUM_THREADS]; for (int i = 0; i<NUM_THREADS; ++i) { DmaskT[i].resize(D.m(),D.n()); DtRT[i].resize(K); uT[i].resize(K); XmaskT[i].resize(X.m()); uT[i].setZeros(); GsT[i].resize(L,L); invGsT[i].resize(L,L); GaT[i].resize(K,L); workT[i].resize(K,3); workT[i].setZeros(); } int i; #pragma omp parallel for private(i) for (i = 0; i< M; ++i) { #ifdef _OPENMP int numT=omp_get_thread_num(); #else int numT=0; #endif Vector<T> Xi; X.refCol(i,Xi); Vector<bool> maski; mask.refCol(i,maski); Vector<int> ind; rM.refCol(i,ind); Vector<T> coeffs; vM.refCol(i,coeffs); Vector<T>& DtR=DtRT[numT]; if (maski.allfalse()) continue; if (maski.alltrue()) { T normX = Xi.nrm2sq(); D.multTrans(Xi,DtR); coreLARS2(DtR,G,GsT[numT],GaT[numT],invGsT[numT],uT[numT],coeffs, ind,workT[numT],normX,mode,constraint,pos); } else { D.copyMask(DmaskT[numT],maski); Xi.copyMask(XmaskT[numT],maski); T constraint_mask = mode == PENALTY || mode == L2ERROR ? constraint*XmaskT[numT].n()/Xi.n() : constraint; T normX = XmaskT[numT].nrm2sq(); DmaskT[numT].multTrans(XmaskT[numT],DtR); GT[numT].setMatrices(DmaskT[numT],false); GT[numT].addDiag(MAX(lambda2,T(1e-10))); coreLARS2(DtR,GT[numT], GsT[numT],GaT[numT],invGsT[numT],uT[numT],coeffs, ind,workT[numT],normX,mode,constraint_mask,pos); DmaskT[numT].setm(D.m()); DmaskT[numT].setn(D.n()); XmaskT[numT].setn(X.m()); } } delete[](GT); delete[](XmaskT); delete[](DmaskT); delete[](DtRT); delete[](uT); delete[](GsT); delete[](GaT); delete[](invGsT); delete[](workT); /// convert the sparse matrix into a proper format spalpha.convert(vM,rM,K); }; template <typename T> void lasso2(const Matrix<T>& X, const Matrix<T>& D, SpMatrix<T>& spalpha, int L, const T constraint, const T lambda2, constraint_type mode, const bool pos, const int numThreads, Matrix<T>* path, int length_path) { ProdMatrix<T> G(D,X.n() > 10 && D.n() < 50000); ProdMatrix<T> DtX(D,X,false); G.addDiag(MAX(lambda2,1e-10)); lasso2(X,G,DtX,spalpha,L,constraint,mode,pos,numThreads,path, length_path); } template <typename T> void lasso2(const Data<T>& X, const AbstractMatrix<T>& G, const AbstractMatrix<T>& DtX, SpMatrix<T>& spalpha, int L, const T constraint, constraint_type mode, const bool pos, const int numThreads, Matrix<T>* path, int length_path) { spalpha.clear(); const int M = X.n(); const int K = G.n(); Matrix<T> vM; Matrix<int> rM; vM.resize(L,M); rM.resize(L,M); if (L <= 0) return; if (path) path->setZeros(); int NUM_THREADS=init_omp(numThreads); Vector<T>* DtRT=new Vector<T>[NUM_THREADS]; Vector<T>* uT=new Vector<T>[NUM_THREADS]; Matrix<T>* GsT=new Matrix<T>[NUM_THREADS]; Matrix<T>* GaT=new Matrix<T>[NUM_THREADS]; Matrix<T>* invGsT=new Matrix<T>[NUM_THREADS]; Matrix<T>* workT=new Matrix<T>[NUM_THREADS]; for (int i = 0; i<NUM_THREADS; ++i) { DtRT[i].resize(K); uT[i].resize(K); uT[i].setZeros(); GsT[i].resize(L,L); invGsT[i].resize(L,L); GaT[i].resize(K,L); workT[i].resize(K,3); workT[i].setZeros(); } int i; Vector<T> norms; X.norm_2sq_cols(norms); #pragma omp parallel for private(i) for (i = 0; i< M; ++i) { #ifdef _OPENMP int numT=omp_get_thread_num(); #else int numT=0; #endif // Vector<T> Xi; // X.refCol(i,Xi); // T normX = Xi.nrm2sq(); T normX = norms[i]; Vector<int> ind; rM.refCol(i,ind); Vector<T> coeffs; vM.refCol(i,coeffs); Vector<T>& DtR=DtRT[numT]; DtX.copyCol(i,DtR); //D.multTrans(Xi,DtR); coreLARS2(DtR,G,GsT[numT],GaT[numT],invGsT[numT], uT[numT],coeffs, ind,workT[numT],normX,mode,constraint,pos, path && i==0 ? path->rawX() : NULL,length_path); } delete[](DtRT); delete[](uT); delete[](GsT); delete[](GaT); delete[](invGsT); delete[](workT); /// convert the sparse matrix into a proper format spalpha.convert(vM,rM,K); }; /// Auxiliary function for lasso template <typename T> void coreLARS2(Vector<T>& DtR, const AbstractMatrix<T>& G, Matrix<T>& Gs, Matrix<T>& Ga, Matrix<T>& invGs, Vector<T>& u, Vector<T>& coeffs, Vector<int>& ind, Matrix<T>& work, T& normX, const constraint_type mode, const T constraint, const bool pos, T* path, int length_path) { const int LL = Gs.n(); const int K = G.n(); const int L = MIN(LL,K); if (length_path <= 1) length_path=4*L; coeffs.setZeros(); ind.set(-1); T* const pr_Gs = Gs.rawX(); T* const pr_invGs = invGs.rawX(); T* const pr_Ga = Ga.rawX(); T* const pr_work = work.rawX(); T* const pr_u = u.rawX(); T* const pr_DtR = DtR.rawX(); T* const pr_coeffs = coeffs.rawX(); int* const pr_ind = ind.rawX(); // Find the most correlated element int currentInd = pos ? DtR.max() : DtR.fmax(); if (mode == PENALTY && abs(DtR[currentInd]) < constraint) return; if (mode == L2ERROR && normX < constraint) return; bool newAtom=true; int i; int iter=0; T thrs = 0; for (i = 0; i<L; ++i) { ++iter; if (newAtom) { pr_ind[i]=currentInd; // cerr << "Add " << currentInd << endl; G.extract_rawCol(pr_ind[i],pr_Ga+i*K); for (int j = 0; j<=i; ++j) pr_Gs[i*LL+j]=pr_Ga[i*K+pr_ind[j]]; // Update inverse of Gs if (i == 0) { pr_invGs[0]=T(1.0)/pr_Gs[0]; } else { cblas_symv<T>(CblasColMajor,CblasUpper,i,T(1.0), pr_invGs,LL,pr_Gs+i*LL,1,T(0.0),pr_u,1); const T schur = T(1.0)/(pr_Gs[i*LL+i]-cblas_dot<T>(i,pr_u,1,pr_Gs+i*LL,1)); pr_invGs[i*LL+i]=schur; // cblas_copy<T>(i,pr_u,1,pr_invGs+i*LL,1); memcpy(pr_invGs+i*LL,pr_u,i*sizeof(T)); cblas_scal<T>(i,-schur,pr_invGs+i*LL,1); cblas_syr<T>(CblasColMajor,CblasUpper,i,schur,pr_u,1, pr_invGs,LL); } } // Compute the path direction for (int j = 0; j<=i; ++j) pr_work[j]= pr_DtR[pr_ind[j]] > 0 ? T(1.0) : T(-1.0); cblas_symv<T>(CblasColMajor,CblasUpper,i+1,T(1.0),pr_invGs,LL, pr_work,1,T(0.0),pr_u,1); // Compute the step on the path T step_max = INFINITY; int first_zero = -1; for (int j = 0; j<=i; ++j) { T ratio = -pr_coeffs[j]/pr_u[j]; if (ratio > 0 && ratio <= step_max) { step_max=ratio; first_zero=j; } } // PRINT_F(step_max) T current_correlation = abs<T>(pr_DtR[pr_ind[0]]); cblas_gemv<T>(CblasColMajor,CblasNoTrans,K,i+1,T(1.0),pr_Ga, K,pr_u,1,T(0.0),pr_work+2*K,1); memcpy(pr_work+K,pr_work+2*K,K*sizeof(T)); memcpy(pr_work,pr_work+K,K*sizeof(T)); // cblas_copy<T>(K,pr_work+2*K,1,pr_work+K,1); // cblas_copy<T>(K,pr_work+2*K,1,pr_work,1); for (int j = 0; j<=i; ++j) { pr_work[pr_ind[j]]=INFINITY; pr_work[pr_ind[j]+K]=INFINITY; } for (int j = 0; j<K; ++j) { pr_work[j] = ((pr_work[j] < INFINITY) && (pr_work[j] > T(-1.0))) ? (pr_DtR[j]+current_correlation)/(T(1.0)+pr_work[j]) : INFINITY; } // work.print("work"); for (int j = 0; j<K; ++j) { pr_work[j+K] = ((pr_work[j+K] < INFINITY) && (pr_work[j+K] < T(1.0))) ? (current_correlation-pr_DtR[j])/(T(1.0)-pr_work[j+K]) : INFINITY; } // work.print("work"); if (pos) { for (int j = 0; j<K; ++j) { pr_work[j]=INFINITY; } } // work.print("work"); // coeffs.print("coeffs"); int index = cblas_iamin<T>(2*K,pr_work,1); T step = pr_work[index]; // Choose next element currentInd = index % K; // compute the coefficients of the polynome representing normX^2 T coeff1 = 0; for (int j = 0; j<=i; ++j) coeff1 += pr_DtR[pr_ind[j]] > 0 ? pr_u[j] : -pr_u[j]; T coeff2 = 0; for (int j = 0; j<=i; ++j) coeff2 += pr_DtR[pr_ind[j]]*pr_u[j]; T coeff3 = normX-constraint; T step_max2; if (mode == PENALTY) { step_max2 = current_correlation-constraint; } else if (mode == L2ERROR) { /// L2ERROR const T delta = coeff2*coeff2-coeff1*coeff3; step_max2 = delta < 0 ? INFINITY : (coeff2-sqrt(delta))/coeff1; step_max2 = MIN(current_correlation,step_max2); } else { /// L1COEFFS step_max2 = coeff1 < 0 ? INFINITY : (constraint-thrs)/coeff1; step_max2 = MIN(current_correlation,step_max2); } step = MIN(MIN(step,step_max2),step_max); if (step == INFINITY) break; // stop the path // Update coefficients cblas_axpy<T>(i+1,step,pr_u,1,pr_coeffs,1); if (pos) { for (int j = 0; j<i+1; ++j) if (pr_coeffs[j] < 0) pr_coeffs[j]=0; } // Update correlations cblas_axpy<T>(K,-step,pr_work+2*K,1,pr_DtR,1); // Update normX normX += coeff1*step*step-2*coeff2*step; // Update norm1 thrs += step*coeff1; if (path) { for (int k = 0; k<=i; ++k) path[iter*K+ind[k]]=pr_coeffs[k]; } // Choose next action if (step == step_max) { // cerr << "Remove " << pr_ind[first_zero] << endl; /// Downdate, remove first_zero /// Downdate Ga, Gs, invGs, ind, coeffs for (int j = first_zero; j<i; ++j) { cblas_copy<T>(K,pr_Ga+(j+1)*K,1,pr_Ga+j*K,1); pr_ind[j]=pr_ind[j+1]; pr_coeffs[j]=pr_coeffs[j+1]; } pr_ind[i]=-1; pr_coeffs[i]=0; for (int j = first_zero; j<i; ++j) { cblas_copy<T>(first_zero,pr_Gs+(j+1)*LL,1,pr_Gs+j*LL,1); cblas_copy<T>(i-first_zero,pr_Gs+(j+1)*LL+first_zero+1,1, pr_Gs+j*LL+first_zero,1); } const T schur = pr_invGs[first_zero*LL+first_zero]; cblas_copy<T>(first_zero,pr_invGs+first_zero*LL,1,pr_u,1); cblas_copy<T>(i-first_zero,pr_invGs+(first_zero+1)*LL+first_zero,LL, pr_u+first_zero,1); for (int j = first_zero; j<i; ++j) { cblas_copy<T>(first_zero,pr_invGs+(j+1)*LL,1,pr_invGs+j*LL,1); cblas_copy<T>(i-first_zero,pr_invGs+(j+1)*LL+first_zero+1,1, pr_invGs+j*LL+first_zero,1); } cblas_syr<T>(CblasColMajor,CblasUpper,i,T(-1.0)/schur, pr_u,1,pr_invGs,LL); newAtom=false; i=i-2; } else { newAtom=true; } if ((iter >= length_path-1) || abs(step) < 1e-15 || step == step_max2 || (normX < 1e-15) || (i == (L-1)) || (mode == L2ERROR && normX - constraint < 1e-15) || (mode == L1COEFFS && (constraint-thrs < 1e-15))) { break; } } } /// Auxiliary function for lasso template <typename T> void coreLARS2W(Vector<T>& DtR, AbstractMatrix<T>& G, Matrix<T>& Gs, Matrix<T>& Ga, Matrix<T>& invGs, Vector<T>& u, Vector<T>& coeffs, const Vector<T>& weights, Vector<int>& ind, Matrix<T>& work, T& normX, const constraint_type mode, const T constraint, const bool pos) { const int LL = Gs.n(); const int K = G.n(); const int L = MIN(LL,K); coeffs.setZeros(); ind.set(-1); T* const pr_Gs = Gs.rawX(); T* const pr_invGs = invGs.rawX(); T* const pr_Ga = Ga.rawX(); // T* const pr_G = G.rawX(); T* const pr_work = work.rawX(); T* const pr_u = u.rawX(); T* const pr_DtR = DtR.rawX(); T* const pr_coeffs = coeffs.rawX(); T* const pr_weights = weights.rawX(); int* const pr_ind = ind.rawX(); DtR.div(weights); // Find the most correlated element int currentInd = pos ? DtR.max() : DtR.fmax(); if (mode == PENALTY && abs(DtR[currentInd]) < constraint) return; if (mode == L2ERROR && normX < constraint) return; bool newAtom=true; int i; int iter=0; T thrs = 0; for (i = 0; i<L; ++i) { ++iter; if (newAtom) { pr_ind[i]=currentInd; // Update upper part of Gs and Ga G.extract_rawCol(pr_ind[i],pr_Ga+i*K); for (int j = 0; j<=i; ++j) pr_Gs[i*LL+j]=pr_Ga[i*K+pr_ind[j]]; // Update inverse of Gs if (i == 0) { pr_invGs[0]=T(1.0)/pr_Gs[0]; } else { cblas_symv<T>(CblasColMajor,CblasUpper,i,T(1.0), pr_invGs,LL,pr_Gs+i*LL,1,T(0.0),pr_u,1); const T schur = T(1.0)/(pr_Gs[i*LL+i]-cblas_dot<T>(i,pr_u,1,pr_Gs+i*LL,1)); pr_invGs[i*LL+i]=schur; cblas_copy<T>(i,pr_u,1,pr_invGs+i*LL,1); cblas_scal<T>(i,-schur,pr_invGs+i*LL,1); cblas_syr<T>(CblasColMajor,CblasUpper,i,schur,pr_u,1, pr_invGs,LL); } } // Compute the path direction for (int j = 0; j<=i; ++j) pr_work[j]= pr_DtR[pr_ind[j]] > 0 ? weights[pr_ind[j]] : -weights[pr_ind[j]]; cblas_symv<T>(CblasColMajor,CblasUpper,i+1,T(1.0),pr_invGs,LL, pr_work,1,T(0.0),pr_u,1); // Compute the step on the path T step_max = INFINITY; int first_zero = -1; for (int j = 0; j<=i; ++j) { T ratio = -pr_coeffs[j]/pr_u[j]; if (ratio > 0 && ratio <= step_max) { step_max=ratio; first_zero=j; } } T current_correlation = abs<T>(pr_DtR[pr_ind[0]]); cblas_gemv<T>(CblasColMajor,CblasNoTrans,K,i+1,T(1.0),pr_Ga, K,pr_u,1,T(0.0),pr_work+2*K,1); vDiv<T>(K,pr_work+2*K,pr_weights,pr_work+2*K); cblas_copy<T>(K,pr_work+2*K,1,pr_work+K,1); cblas_copy<T>(K,pr_work+2*K,1,pr_work,1); for (int j = 0; j<=i; ++j) { pr_work[pr_ind[j]]=INFINITY; pr_work[pr_ind[j]+K]=INFINITY; } for (int j = 0; j<K; ++j) { pr_work[j] = ((pr_work[j] < INFINITY) && (pr_work[j] > T(-1.0))) ? (pr_DtR[j]+current_correlation)/(T(1.0)+pr_work[j]) : INFINITY; } for (int j = 0; j<K; ++j) { pr_work[j+K] = ((pr_work[j+K] < INFINITY) && (pr_work[j+K] < T(1.0))) ? (current_correlation-pr_DtR[j])/(T(1.0)-pr_work[j+K]) : INFINITY; } if (pos) { for (int j = 0; j<K; ++j) { pr_work[j]=INFINITY; } } int index = cblas_iamin<T>(2*K,pr_work,1); T step = pr_work[index]; // Choose next element currentInd = index % K; // compute the coefficients of the polynome representing normX^2 T coeff1 = 0; for (int j = 0; j<=i; ++j) coeff1 += pr_DtR[pr_ind[j]] > 0 ? pr_weights[pr_ind[j]]*pr_u[j] : -pr_weights[pr_ind[j]]*pr_u[j]; T coeff2 = 0; for (int j = 0; j<=i; ++j) coeff2 += pr_DtR[pr_ind[j]]*pr_u[j]*pr_weights[pr_ind[j]]; T coeff3 = normX-constraint; T step_max2; if (mode == PENALTY) { step_max2 = current_correlation-constraint; } else if (mode == L2ERROR) { /// L2ERROR const T delta = coeff2*coeff2-coeff1*coeff3; step_max2 = delta < 0 ? INFINITY : (coeff2-sqrt(delta))/coeff1; } else { /// L1COEFFS step_max2 = coeff1 < 0 ? INFINITY : (constraint-thrs)/coeff1; } step = MIN(MIN(step,step_max2),step_max); if (step == INFINITY) break; // stop the path // Update coefficients cblas_axpy<T>(i+1,step,pr_u,1,pr_coeffs,1); // Update correlations cblas_axpy<T>(K,-step,pr_work+2*K,1,pr_DtR,1); // Update normX normX += coeff1*step*step-2*coeff2*step; // Update norm1 thrs += step*coeff1; if (step == step_max) { /// Downdate, remove first_zero /// Downdate Ga, Gs, invGs, ind, coeffs for (int j = first_zero; j<i; ++j) { cblas_copy<T>(K,pr_Ga+(j+1)*K,1,pr_Ga+j*K,1); pr_ind[j]=pr_ind[j+1]; pr_coeffs[j]=pr_coeffs[j+1]; } pr_ind[i]=-1; pr_coeffs[i]=0; for (int j = first_zero; j<i; ++j) { cblas_copy<T>(first_zero,pr_Gs+(j+1)*LL,1,pr_Gs+j*LL,1); cblas_copy<T>(i-first_zero,pr_Gs+(j+1)*LL+first_zero+1,1, pr_Gs+j*LL+first_zero,1); } const T schur = pr_invGs[first_zero*LL+first_zero]; cblas_copy<T>(first_zero,pr_invGs+first_zero*LL,1,pr_u,1); cblas_copy<T>(i-first_zero,pr_invGs+(first_zero+1)*LL+first_zero,LL, pr_u+first_zero,1); for (int j = first_zero; j<i; ++j) { cblas_copy<T>(first_zero,pr_invGs+(j+1)*LL,1,pr_invGs+j*LL,1); cblas_copy<T>(i-first_zero,pr_invGs+(j+1)*LL+first_zero+1,1, pr_invGs+j*LL+first_zero,1); } cblas_syr<T>(CblasColMajor,CblasUpper,i,T(-1.0)/schur, pr_u,1,pr_invGs,LL); newAtom=false; i=i-2; } else { newAtom=true; } // Choose next action if (iter > 4*L || abs(step) < 1e-10 || step == step_max2 || (normX < 1e-10) || (i == (L-1)) || (mode == L2ERROR && normX - constraint < 1e-10) || (mode == L1COEFFS && (constraint-thrs < 1e-10))) { break; } } } /* ************************ * Iterative thresholding * ************************/ /// Implementation of IST for solving /// \forall i, \min_{\alpha_i} ||\alpha_i||_1 /// s.t. ||\X_i-D\alpha_i||_2^2 <= constraint or /// \forall i, \min_{\alpha_i} constraint*||\alpha_i||_1 + ... /// ... ||\X_i-D\alpha_i||_2^2 <= lambda template <typename T> void ist(const Matrix<T>& X, const Matrix<T>& D, SpMatrix<T>& spalpha, T lambda, constraint_type mode, const int itermax, const T tol, const int numThreads) { Matrix<T> alpha; spalpha.toFull(alpha); spalpha.clear(); ist(X,D,alpha,lambda,mode,itermax,tol,numThreads); alpha.toSparse(spalpha); } template <typename T> void ist(const Matrix<T>& X, const Matrix<T>& D, Matrix<T>& alpha, T lambda, constraint_type mode, const int itermax, const T tol, const int numThreads) { if (mode == L1COEFFS) { std::cerr << "Mode not implemented" << std::endl; return; } int K=D.n(); int M=X.n(); alpha.resize(K,M); if (!D.isNormalized()) { cerr << "Current implementation of IST does not support non-normalized dictionaries" << endl; return; } /// compute the Gram Matrix G=D'D //CachedProdMatrix<T> G(D, K < 20000 && M*K/10 > K); //ProdMatrix<T> G(D, K < 20000 && M*K/10 > K); Matrix<T> G; D.XtX(G); // for (int i = 0; i<K; ++i) G[i*K+i] += 1e-6; G.addDiag(1e-12); ProdMatrix<T> DtX(D,X,false); int NUM_THREADS=init_omp(numThreads); Vector<T>* DtRT= new Vector<T>[NUM_THREADS]; SpVector<T>* spAlphaT= new SpVector<T>[NUM_THREADS]; for (int i = 0; i<NUM_THREADS; ++i) { DtRT[i].resize(K); spAlphaT[i].resize(K); }; int i; #pragma omp parallel for private(i) for (i = 0; i< M; ++i) { #ifdef _OPENMP int numT=omp_get_thread_num(); #else int numT=0; #endif Vector<T> coeffs; alpha.refCol(i,coeffs); Vector<T>& DtR=DtRT[numT]; SpVector<T>& spAlpha=spAlphaT[numT]; T norm1 = coeffs.asum(); // Compute DtR DtX.copyCol(i,DtR); Vector<T> Xi; X.refCol(i,Xi); T normX2 = Xi.nrm2sq(); if (norm1 > EPSILON) { coeffs.toSparse(spAlpha); G.mult(spAlpha,DtR,-1.0,1.0); } if (mode == PENALTY) { coreIST(G,DtR,coeffs,lambda,itermax,tol); } else { coreISTconstrained(G,DtR,coeffs,normX2,lambda,itermax,tol); } } delete[](DtRT); delete[](spAlphaT); } /*template <typename T> inline void generalCD(const AbstractMatrix<T>& G, Vector<T>& DtRv, Vector<T>& coeffsv, const T lambda, const int itermax, const T tol) { Vector<T> diag; G.diag(diag); const int K = G.n(); T* const coeffs = coeffsv.rawX(); T* const DtR = DtRv.rawX(); for (int iter=0; iter < itermax; ++iter) { if (iter % 5 == 0) { T eps1=DtRv.fmaxval()/lambda-1; if (eps1 <= tol) { T eps2=1e10; for (int jj=0; jj<K; ++jj) { if (coeffs[jj] > 0) { eps2=MIN(DtR[jj],eps2); } else if (coeffs[jj] < 0) { eps2=MIN(-DtR[jj],eps2); } } eps2=-(eps2/lambda-1); if (eps2 <= tol) break; } } for (int j = 0; j <K; ++j) { T crit=DtR[j]+coeffs[j]*diag[j]; if (crit > lambda) { T diff=coeffs[j]; coeffs[j]=(crit-lambda)/diag[j]; diff-=coeffs[j]; G.add_rawCol(j,DtR,diff); } else if (crit < -lambda) { T diff=coeffs[j]; coeffs[j]=(crit+lambda)/diag[j]; diff-=coeffs[j]; G.add_rawCol(j,DtR,diff); } else if (coeffs[j]) { G.add_rawCol(j,DtR,coeffs[j]); coeffs[j]=T(); } } } }*/ template <typename T> inline void coreIST(const AbstractMatrix<T>& G, Vector<T>& DtRv, Vector<T>& coeffsv, const T thrs, const int itermax, const T tol) { const int K = G.n(); T* const coeffs = coeffsv.rawX(); T* const DtR = DtRv.rawX(); // T* const prG = G.rawX(); const T lambda_init=thrs; T maxDtR = DtRv.fmaxval(); T norm1=coeffsv.asum(); T lambda=lambda_init; vAdd(K,DtR,coeffs,DtR); for (int iter=0; iter < itermax; ++iter) { for (int j = 0; j <K; ++j) { if (DtR[j] > lambda) { T diff=coeffs[j]; coeffs[j]=DtR[j]-lambda; diff-=coeffs[j]; DtR[j]-=diff; G.add_rawCol(j,DtR,diff); //cblas_axpy(K,diff,prG+j*K,1,DtR,1); } else if (DtR[j] < -lambda) { T diff=coeffs[j]; coeffs[j]=DtR[j]+lambda; diff-=coeffs[j]; DtR[j]-=diff; G.add_rawCol(j,DtR,diff); //cblas_axpy(K,diff,prG+j*K,1,DtR,1); } else if (coeffs[j]) { T diff=coeffs[j]; coeffs[j]=T(); DtR[j]-=diff; G.add_rawCol(j,DtR,diff); //cblas_axpy(K,diff,prG+j*K,1,DtR,1); } } if (iter % 5 == 1) { vSub(K,DtR,coeffs,DtR); maxDtR = DtRv.fmaxval(); norm1 =T(); T DtRa = T(); for (int j = 0; j<K; ++j) { if (coeffs[j]) { norm1 += abs(coeffs[j]); DtRa += DtR[j]*coeffs[j]; } } vAdd(K,DtR,coeffs,DtR); const T kappa = -DtRa+norm1*maxDtR; if (abs(lambda - maxDtR) < tol && kappa <= tol) break; } } } /// coreIST constrained template <typename T> void coreISTconstrained(const AbstractMatrix<T>& G, Vector<T>& DtRv, Vector<T>& coeffsv, const T normX2, const T eps, const int itermax, const T tol) { const int K = G.n(); T* const coeffs = coeffsv.rawX(); T* const DtR = DtRv.rawX(); // T* const prG = G.rawX(); T err = normX2; T norm1 = coeffsv.asum(); if (!norm1 && err <= eps) return; T current_tol = 10.0*tol; T maxDtR = DtRv.fmaxval(); T lambda = maxDtR; T lambdasq= lambda*lambda; if (!norm1) { lambdasq *= eps/err; lambda=sqrt(lambdasq); } Vector<int> indices(K); indices.set(-1); int* const pr_indices=indices.rawX(); int count; for (int iter=0; iter < itermax; ++iter) { count=0; T old_err = err; for (int j = 0; j <K; ++j) { // Soft-thresholding T old_coeff = coeffs[j]; T diff = DtR[j]+old_coeff; if (diff > lambda) { coeffs[j] = diff - lambda; err+=lambdasq-DtR[j]*DtR[j]; pr_indices[count++]=j; } else if (diff < - lambda) { coeffs[j] = diff + lambda; err+=lambdasq-DtR[j]*DtR[j]; pr_indices[count++]=j; } else { coeffs[j]=T(); if (old_coeff) { err+=diff*diff-DtR[j]*DtR[j]; } } // Update DtR diff = old_coeff-coeffs[j]; if (diff) { G.add_rawCol(j,DtR,diff); //cblas_axpy<T>(K,old_coeff-coeffs[j],prG+j*K,1,DtR,1); } } maxDtR = DtRv.fmaxval(); norm1 =T(); T DtRa = T(); for (int j = 0; j<count; ++j) { const int ind = pr_indices[j]; norm1 += abs(coeffs[ind]); DtRa += DtR[ind]*coeffs[ind]; } if (norm1-DtRa/maxDtR <= current_tol) { const bool change = ((old_err > eps) && err < eps+current_tol) || (old_err < eps && err > eps-current_tol); if (change) { if (current_tol == tol) { break; } else { current_tol = MAX(current_tol*0.5,tol); } } lambdasq *= eps/err; lambda=sqrt(lambdasq); } } }; /// ist for group Lasso template <typename T> void ist_groupLasso(const Matrix<T>* XT, const Matrix<T>& D, Matrix<T>* alphaT, const int Ngroups, const T lambda, const constraint_type mode, const int itermax, const T tol, const int numThreads) { int K=D.n(); int n = D.m(); if (!D.isNormalized()) { cerr << "Current implementation of block coordinate descent does not support non-normalized dictionaries" << endl; return; } if (mode == L1COEFFS) { std::cerr << "Mode not implemented" << std::endl; return; } /// compute the Gram Matrix G=D'D Matrix<T> G; D.XtX(G); int NUM_THREADS=init_omp(numThreads); Matrix<T>* RtDT = new Matrix<T>[NUM_THREADS]; Matrix<T>* alphatT = new Matrix<T>[NUM_THREADS]; int i; #pragma omp parallel for private(i) for (i = 0; i< Ngroups; ++i) { #ifdef _OPENMP int numT=omp_get_thread_num(); #else int numT=0; #endif const Matrix<T>& X = XT[i]; int M = X.n(); Matrix<T>& alphat = alphatT[numT]; alphaT[i].transpose(alphat); Matrix<T>& RtD = RtDT[numT]; X.mult(D,RtD,true,false); Vector<T> col, col2; T norm1 = alphat.asum(); T normX2; if (!norm1) { Vector<T> DtR_mean(K); Vector<T> coeffs_mean(K); coeffs_mean.setZeros(); RtD.meanRow(DtR_mean); coeffs_mean.setZeros(); if (mode == PENALTY) { coreIST(G,DtR_mean,coeffs_mean,lambda/T(2.0),itermax,tol); } else { Vector<T> meanVec(n); X.meanCol(meanVec); normX2=meanVec.nrm2sq(); coreISTconstrained(G,DtR_mean,coeffs_mean,normX2, lambda,itermax,tol); SpVector<T> spalpha(K); normX2-=computeError(normX2,G,DtR_mean,coeffs_mean,spalpha); normX2=X.normFsq()-M*normX2; } alphat.fillRow(coeffs_mean); } if (M > 1) { for (int j = 0; j<K; ++j) { alphat.refCol(j,col); const T nrm=col.nrm2sq(); if (nrm) { G.refCol(j,col2); RtD.rank1Update(col,col2,T(-1.0)); } } if (mode == PENALTY) { coreGroupIST(G,RtD,alphat,sqr<T>(M)*lambda/T(2.0),itermax,sqr<T>(M)*tol); } else { coreGroupISTConstrained(G,RtD,alphat,normX2,M*lambda,itermax,sqr<T>(M)*tol); } } alphat.transpose(alphaT[i]); } delete[](RtDT); delete[](alphatT); }; template <typename T> void coreGroupIST(const Matrix<T>& G, Matrix<T>& RtDm, Matrix<T>& coeffsm, const T thrs, const int itermax, const T tol) { const int K = G.n(); const int M = RtDm.m(); T* const prG = G.rawX(); T* const RtD = RtDm.rawX(); T* const coeffs = coeffsm.rawX(); const T lambda_init=thrs; T lambda=lambda_init; Vector<T> old_coeffv(M); T* const old_coeff = old_coeffv.rawX(); Vector<T> normsv(K); T* const norms = normsv.rawX(); coeffsm.norm_2_cols(normsv); Vector<T> normRtDv(K); Vector<int> activatev(K); activatev.set(3); int* const activate=activatev.rawX(); for (int iter=0; iter < itermax; ++iter) { for (int j = 0; j <K; ++j) { if (activate[j] >= 0) { if (norms[j]) { cblas_copy(M,coeffs+j*M,1,old_coeff,1); vAdd(M,coeffs+j*M,RtD+j*M,coeffs+j*M); const T nrm = cblas_nrm2(M,coeffs+j*M,1); if (nrm > lambda) { norms[j]=nrm-lambda; cblas_scal(M,norms[j]/nrm,coeffs+j*M,1); vSub(M,old_coeff,coeffs+j*M,old_coeff); cblas_ger(CblasColMajor,M,K,T(1.0),old_coeff,1,prG+j*K,1,RtD,M); activate[j]=5; } else { memset(coeffs+j*M,0,M*sizeof(T)); norms[j]=T(); cblas_ger(CblasColMajor,M,K,T(1.0),old_coeff,1,prG+j*K,1,RtD,M); --activate[j]; } } else { cblas_copy(M,RtD+j*M,1,old_coeff,1); const T nrm = cblas_nrm2(M,old_coeff,1); if (nrm > lambda) { norms[j]=nrm-lambda; cblas_copy(M,old_coeff,1,coeffs+j*M,1); cblas_scal(M,norms[j]/nrm,coeffs+j*M,1); cblas_ger(CblasColMajor,M,K,T(-1.0),coeffs+j*M,1,prG+j*K,1,RtD,M); activate[j]=5; } else { activate[j] = (activate[j] == 0) ? -10 : activate[j]-1; } } } else { ++activate[j]; } } if (iter % 5 == 4) { T norm1=normsv.asum(); RtDm.norm_2sq_cols(normRtDv); T maxDtR = sqr(normRtDv.maxval()); T DtRa=T(); for (int j = 0; j<K; ++j) { if (norms[j]) { DtRa += cblas_dot(M,coeffs+j*M,1,RtD+j*M,1); } } if ((maxDtR - lambda) < (tol*maxDtR/norm1) && norm1-DtRa/maxDtR < tol) break; } } }; /// Auxiliary function for ist_groupLasso template <typename T> void coreGroupISTConstrained(const Matrix<T>& G, Matrix<T>& RtDm, Matrix<T>& coeffsm, const T normR, const T eps, const int itermax, const T tol) { const int K = G.n(); const int M = RtDm.m(); T* const prG = G.rawX(); T* const RtD = RtDm.rawX(); T* const coeffs = coeffsm.rawX(); T err = normR; Vector<T> old_coeffv(M); T* const old_coeff = old_coeffv.rawX(); Vector<T> normsv(K); T* const norms = normsv.rawX(); coeffsm.norm_2_cols(normsv); Vector<T> normRtDv(K); RtDm.norm_2sq_cols(normRtDv); Vector<int> activatev(K); activatev.set(3); int* const activate=activatev.rawX(); T norm1 = normsv.sum(); if (!norm1 && err <= eps) return; T current_tol = 10.0*tol; T maxDtR = sqr(normRtDv.maxval()); T lambda = maxDtR; T lambdasq= lambda*lambda; if (!norm1) { lambdasq *= eps/err; lambda=sqrt(lambdasq); } for (int iter=0; iter < itermax; ++iter) { T old_err = err; for (int j = 0; j <K; ++j) { if (activate[j] >= 0) { if (norms[j]) { cblas_copy(M,coeffs+j*M,1,old_coeff,1); vAdd(M,coeffs+j*M,RtD+j*M,coeffs+j*M); const T nrm = cblas_nrm2(M,coeffs+j*M,1); if (nrm > lambda) { norms[j]=nrm-lambda; cblas_scal(M,norms[j]/nrm,coeffs+j*M,1); vSub(M,old_coeff,coeffs+j*M,old_coeff); err += cblas_dot(M,old_coeff,1,old_coeff,1) +2*cblas_dot(M,old_coeff,1,RtD+j*M,1); cblas_ger(CblasColMajor,M,K,T(1.0),old_coeff,1,prG+j*K,1,RtD,M); activate[j]=3; } else { memset(coeffs+j*M,0,M*sizeof(T)); norms[j]=T(); err += cblas_dot(M,old_coeff,1,old_coeff,1) +2*cblas_dot(M,old_coeff,1,RtD+j*M,1); cblas_ger(CblasColMajor,M,K,T(1.0),old_coeff,1,prG+j*K,1,RtD,M); --activate[j]; } } else { cblas_copy(M,RtD+j*M,1,old_coeff,1); const T nrm = cblas_nrm2(M,old_coeff,1); if (nrm > lambda) { norms[j]=nrm-lambda; cblas_copy(M,old_coeff,1,coeffs+j*M,1); cblas_scal(M,norms[j]/nrm,coeffs+j*M,1); err += cblas_dot(M,coeffs+j*M,1,coeffs+j*M,1) -2*cblas_dot(M,coeffs+j*M,1,RtD+j*M,1); cblas_ger(CblasColMajor,M,K,T(-1.0),coeffs+j*M,1,prG+j*K,1,RtD,M); activate[j]=3; } else { activate[j] = (activate[j] == 0) ? -3 : activate[j]-1; } } } else { ++activate[j]; } } norm1 = normsv.sum(); RtDm.norm_2sq_cols(normRtDv); maxDtR = sqr(normRtDv.maxval()); T DtRa=T(); for (int j = 0; j<K; ++j) { if (norms[j]) { DtRa += cblas_dot(M,coeffs+j*M,1,RtD+j*M,1); } } if (norm1-DtRa/maxDtR <= current_tol) { const T tol_bis=current_tol*maxDtR; const bool change = ((old_err > eps) && err < eps+tol_bis) || (old_err < eps && err > eps-tol_bis); if (change) { if (current_tol == tol) { break; } else { current_tol = MAX(current_tol*0.5,tol); } } lambdasq *= eps/err; lambda=sqrt(lambdasq); } } }; /// auxiliary function for ist_groupLasso template <typename T> T computeError(const T normX2,const Vector<T>& norms, const Matrix<T>& G,const Matrix<T>& RtD,const Matrix<T>& alphat) { T err2 = normX2; Vector<T> col,col2; for (int j = 0; j<G.n(); ++j) { if (norms[j] > EPSILON) { alphat.refCol(j,col); RtD.refCol(j,col2); err2 -= 2*col.dot(col2); T add = 0.0; for (int k = 0; k<j; ++k) { if (norms[k] > EPSILON) { alphat.refCol(k,col2); add -= G(j,k)*col.dot(col2); } } add += add - G(j,j)*col.nrm2sq(); err2 += add; } } return err2; } /// auxiliary function for template <typename T> T computeError(const T normX2, const Matrix<T>& G,const Vector<T>& DtR,const Vector<T>& coeffs, SpVector<T>& spAlpha) { coeffs.toSparse(spAlpha); return normX2 -G.quad(spAlpha)-2*DtR.dot(spAlpha); }; /* ****************** * Simultaneous OMP * *****************/ template <typename T> void somp(const Matrix<T>* X, const Matrix<T>& D, SpMatrix<T>* spalpha, const int Ngroups, const int L, const T eps,const int numThreads) { somp(X,D,spalpha,Ngroups,L,&eps,false,numThreads); } template <typename T> void somp(const Matrix<T>* XT, const Matrix<T>& D, SpMatrix<T>* spalphaT, const int Ngroups, const int LL, const T* eps, const bool adapt, const int numThreads) { if (LL <= 0) return; const int K = D.n(); const int L = MIN(D.m(),MIN(LL,K)); if (!D.isNormalized()) { cerr << "Current implementation of OMP does not support non-normalized dictionaries" << endl; return; } /// compute the Gram Matrix G=D'D Matrix<T> G; D.XtX(G); int NUM_THREADS=init_omp(numThreads); int i; #pragma omp parallel for private(i) for (i = 0; i< Ngroups; ++i) { const Matrix<T>& X = XT[i]; const int M = X.n(); SpMatrix<T>& spalpha = spalphaT[i]; spalpha.clear(); Vector<int> rv; Matrix<T> vM; T thrs = adapt ? eps[i] : M*(*eps); coreSOMP(X,D,G,vM,rv,L,thrs); spalpha.convert2(vM,rv,K); } } template <typename T> void coreSOMP(const Matrix<T>& X, const Matrix<T>& D, const Matrix<T>& G, Matrix<T>& v, Vector<int>& r, const int L, const T eps) { const int K = G.n(); const int n = D.m(); const int M = X.n(); const bool big_mode = M*K*(n+L) > 2*(M*n*n+K*n*(n+L)); r.resize(L); r.set(-1); v.resize(0,X.n()); if (M == 1) { Vector<T> scores(K); Vector<T> norm(K); Vector<T> tmp(K); Matrix<T> Un(L,L); Un.setZeros(); Matrix<T> Undn(K,L); Matrix<T> Unds(L,L); Matrix<T> Gs(K,L); Vector<T> Rdn(K); Vector<T> Xt(X.rawX(),n); D.multTrans(Xt,Rdn); Vector<T> RUn(L); T normX = Xt.nrm2sq(); T lambda=0; coreORMP(scores,norm,tmp,Un,Undn,Unds,Gs,Rdn,G,r,RUn,normX,&eps,&L,&lambda); int count=0; for (int i = 0; i<L; ++i) { if (r[i] == -1) break; ++count; } v.resize(count,X.n()); Vector<T> v1(v.rawX(),count); Vector<T> v2(RUn.rawX(),count); v1.copy(v2); return; } Matrix<T> XXtD; Matrix<T> XtD; T E; if (big_mode) { Matrix<T> XXt; X.XXt(XXt); E = XXt.trace(); if (E < eps) return; XXt.mult(D,XXtD); } else { E=X.normFsq(); if (E < eps) return; X.mult(D,XtD,true); } Matrix<T> A(K,L); A.setZeros(); Matrix<T> B(L,K); B.setZeros(); Matrix<T> S(L,L); S.setZeros(); Matrix<T> Fs(K,L); Fs.setZeros(); Matrix<T> Gs(K,L); Gs.setZeros(); Matrix<T> As(L,L); As.setZeros(); Vector<T> tmp(K); Vector<T> e(K); G.diag(e); Vector<T> f(K); if (big_mode) { for (int i = 0; i<K; ++i) { Vector<T> di; D.refCol(i,di); Vector<T> di2; XXtD.refCol(i,di2); f[i]=di.dot(di2); } } else { XtD.norm_2sq_cols(f); } Vector<T> c(L); c.setZeros(); Vector<T> scores(K); /// permit unsafe fast low level accesses T* const prAs = As.rawX(); T* const prA = A.rawX(); T* const prS = S.rawX(); T* const prGs = Gs.rawX(); T* const prFs = Fs.rawX(); T* const prB = B.rawX(); T* const pr_c = c.rawX(); T* const pr_tmp = tmp.rawX(); int j; for (j = 0; j<L; ++j) { scores.copy(f); scores.div(e); for (int k = 0; k<j; ++k) scores[r[k]]=-1.0; const int currentInd = scores.max(); const T invNorm=T(1.0)/sqrt(e[currentInd]); if (invNorm > 1e3) { j=j-1; break; } r[j]=currentInd; E -= scores[currentInd]; for (int k = 0; k<j; ++k) prS[j*L+k]=T(); prS[j*L+j]=T(1.0); for (int k = 0; k<j; ++k) prAs[k*L+j]=prA[k*K+currentInd]; /// Cholesky update with partial reorthogonalization int iter = invNorm > 1.41 ? 2 : 1; for (int k = 0; k<iter; ++k) { for (int l = 0; l<j; ++l) { T scal = -cblas_dot<T>(j-l+1,prAs+l*L+l,1,prS+j*L+l,1); cblas_axpy<T>(l+1,scal,prS+l*L,1,prS+j*L,1); } } cblas_scal<T>(j+1,invNorm,prS+j*L,1); if (j == L-1 || E <= eps) { ++j; break; } /// Update e,f,scores,A,B,As,Bs,Fs,Gs,S,c /// Gs,S,A,As, e, Fs, B,c Vector<T> Gsj; Gs.refCol(j,Gsj); G.copyCol(currentInd,Gsj); cblas_gemv<T>(CblasColMajor,CblasNoTrans,K,j+1,T(1.0),prGs,K,prS+j*L,1, T(0.0),prA+j*K,1); prAs[j*L+j]=prA[j*K+currentInd]; Vector<T> Aj; A.refCol(j,Aj); tmp.sqr(Aj); e.sub(tmp); Vector<T> Fsj; Fs.refCol(j,Fsj); if (big_mode) { Vector<T> di; D.refCol(currentInd,di); XXtD.multTrans(di,Fsj); } else { Vector<T> di; XtD.refCol(currentInd,di); XtD.multTrans(di,Fsj); } cblas_gemv<T>(CblasColMajor,CblasNoTrans,K,j+1,T(1.0),prFs,K,prS+j*L,1, T(0.0),prB+j,L); for (int k = 0; k<j;++k) pr_c[k]=T(); for (int k = 0; k<=j;++k) cblas_axpy<T>(j,prS[j*L+k],prB+r[k]*L,1,pr_c,1); f.add(tmp,f[currentInd]*invNorm*invNorm); if (j > 0) { cblas_gemv<T>(CblasColMajor,CblasNoTrans,K,j,T(1.0),prA,K,pr_c,1, T(0.0),pr_tmp,1); } else { tmp.setZeros(); } cblas_axpy<T>(K,T(-1.0),prB+j,L,pr_tmp,1); tmp.mult(tmp,Aj); f.add(tmp,T(2.0)); } A.clear(); B.clear(); Fs.clear(); Gs.clear(); As.clear(); if (j == 0) return; Matrix<T> SSt; S.upperTriXXt(SSt,j); Matrix<T> Dg(n,j); for (int i = 0; i<j;++i) { Vector<T> Dgi; Dg.refCol(i,Dgi); D.copyCol(r[i],Dgi); } Matrix<T> SStDt; SSt.mult(Dg,SStDt,false,true); SStDt.mult(X,v); }; #endif // DECOMP_H
GB_unaryop__identity_int8_fp64.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_int8_fp64 // op(A') function: GB_tran__identity_int8_fp64 // C type: int8_t // A type: double // cast: int8_t cij ; GB_CAST_SIGNED(cij,aij,8) // unaryop: cij = aij #define GB_ATYPE \ double #define GB_CTYPE \ int8_t // 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 = x ; // casting #define GB_CASTING(z, x) \ int8_t z ; GB_CAST_SIGNED(z,x,8) ; // 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_INT8 || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__identity_int8_fp64 ( int8_t *restrict Cx, const double *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_int8_fp64 ( 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
single2.c
/* * a pragma immediately following another */ #include <stdio.h> #ifdef _OPENMP #include <omp.h> #endif void foo(void) { int num_threads =0; #pragma omp parallel #pragma omp single num_threads = omp_get_num_threads(); } void sort_par (int size) { #pragma omp parallel #pragma omp single nowait #pragma omp task untied sort_par(size); }
flowinfo_ipv4_dst.c
/* * Copyright 2014-2016 Nippon Telegraph and Telephone Corporation. * * 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. */ /** * @file flowinfo_ipv4_dst.c * @brief Optimized flow database for dataplane, for ipv4_dst */ #include <stdlib.h> #include "openflow.h" #include "lagopus_apis.h" #include "lagopus/flowdb.h" #include "pktbuf.h" #include "packet.h" #include "lagopus/flowinfo.h" #define OXM_FIELD_TYPE(field) ((field) >> 1) #define IPV4_DST_BITLEN (32) static lagopus_result_t add_flow_ipv4_dst_mask(struct flowinfo *, struct flow *); static lagopus_result_t del_flow_ipv4_dst_mask(struct flowinfo *, struct flow *); static struct flow * match_flow_ipv4_dst_mask(struct flowinfo *, struct lagopus_packet *, int32_t *); static struct flow * find_flow_ipv4_dst_mask(struct flowinfo *, struct flow *); static void destroy_flowinfo_ipv4_dst_mask(struct flowinfo *); static lagopus_result_t add_flow_ipv4_dst(struct flowinfo *, struct flow *); static lagopus_result_t del_flow_ipv4_dst(struct flowinfo *, struct flow *); static struct flow * match_flow_ipv4_dst(struct flowinfo *, struct lagopus_packet *, int32_t *); static struct flow * find_flow_ipv4_dst(struct flowinfo *, struct flow *); static void destroy_flowinfo_ipv4_dst(struct flowinfo *); static lagopus_result_t get_match_ipv4_dst(const struct match_list *match_list, uint32_t *ipv4_dst, uint32_t *mask) { const struct match *match; TAILQ_FOREACH(match, match_list, entry) { if (match->oxm_field == (OFPXMT_OFB_IPV4_DST << 1) + 1) { OS_MEMCPY(ipv4_dst, match->oxm_value, sizeof(*ipv4_dst)); OS_MEMCPY(mask, &match->oxm_value[4], sizeof(*mask)); break; } if (OXM_FIELD_TYPE(match->oxm_field) == OFPXMT_OFB_IPV4_DST) { OS_MEMCPY(ipv4_dst, match->oxm_value, sizeof(*ipv4_dst)); *mask = 0xffffffff; break; } } if (match == NULL) { return LAGOPUS_RESULT_NOT_FOUND; } return LAGOPUS_RESULT_OK; } struct flowinfo * new_flowinfo_ipv4_dst_mask(void) { struct flowinfo *self; self = calloc(1, sizeof(struct flowinfo)); if (self != NULL) { self->nflow = 0; self->nnext = 0; self->next = malloc(1); self->misc = new_flowinfo_ipv4_src_mask(); self->add_func = add_flow_ipv4_dst_mask; self->del_func = del_flow_ipv4_dst_mask; self->match_func = match_flow_ipv4_dst_mask; self->find_func = find_flow_ipv4_dst_mask; self->destroy_func = destroy_flowinfo_ipv4_dst_mask; } return self; } static void destroy_flowinfo_ipv4_dst_mask(struct flowinfo *self) { struct flowinfo *flowinfo; unsigned int i; for (i = 0; i < self->nnext; i++) { flowinfo = self->next[i]; flowinfo->destroy_func(flowinfo); } free(self->next); free(self); } static void freeup_flowinfo(void *val) { struct flowinfo *flowinfo; flowinfo = val; flowinfo->destroy_func(flowinfo); } struct flowinfo * new_flowinfo_ipv4_dst(void) { struct flowinfo *self; self = calloc(1, sizeof(struct flowinfo)); if (self != NULL) { lagopus_hashmap_create(&self->hashmap, LAGOPUS_HASHMAP_TYPE_ONE_WORD, freeup_flowinfo); /* misc is not used */ self->add_func = add_flow_ipv4_dst; self->del_func = del_flow_ipv4_dst; self->match_func = match_flow_ipv4_dst; self->find_func = find_flow_ipv4_dst; self->destroy_func = destroy_flowinfo_ipv4_dst; } return self; } static void destroy_flowinfo_ipv4_dst(struct flowinfo *self) { lagopus_hashmap_destroy(&self->hashmap, true); free(self); } static lagopus_result_t add_flow_ipv4_dst_mask(struct flowinfo *self, struct flow *flow) { struct flowinfo *flowinfo; uint32_t ipv4_dst, mask; lagopus_result_t rv; unsigned int i; rv = get_match_ipv4_dst(&flow->match_list, &ipv4_dst, &mask); if (rv == LAGOPUS_RESULT_OK) { rv = LAGOPUS_RESULT_NOT_FOUND; for (i = 0; i < self->nnext; i++) { if (self->next[i]->userdata == mask) { flowinfo = self->next[i]; rv = LAGOPUS_RESULT_OK; break; } } if (rv == LAGOPUS_RESULT_NOT_FOUND) { /* new node. */ flowinfo = new_flowinfo_ipv4_dst(); flowinfo->userdata = mask; self->next = realloc(self->next, (unsigned long)(self->nnext + 1) * sizeof(struct flowinfo *)); self->next[self->nnext] = flowinfo; self->nnext++; } rv = flowinfo->add_func(flowinfo, flow); } else { rv = self->misc->add_func(self->misc, flow); } if (rv == LAGOPUS_RESULT_OK) { self->nflow++; } return rv; } static lagopus_result_t del_flow_ipv4_dst_mask(struct flowinfo *self, struct flow *flow) { struct flowinfo *flowinfo; uint32_t ipv4_dst, mask; lagopus_result_t rv; unsigned int i; rv = get_match_ipv4_dst(&flow->match_list, &ipv4_dst, &mask); if (rv == LAGOPUS_RESULT_OK) { rv = LAGOPUS_RESULT_NOT_FOUND; for (i = 0; i < self->nnext; i++) { if (self->next[i]->userdata == mask) { flowinfo = self->next[i]; rv = LAGOPUS_RESULT_OK; break; } } if (rv == LAGOPUS_RESULT_NOT_FOUND) { return LAGOPUS_RESULT_NOT_FOUND; } rv = flowinfo->del_func(flowinfo, flow); if (flowinfo->nflow == 0) { flowinfo->destroy_func(flowinfo); self->nnext--; memmove(&self->next[i], &self->next[i + 1], (size_t)(self->nnext - i)); } } else { rv = self->misc->del_func(self->misc, flow); } if (rv == LAGOPUS_RESULT_OK) { self->nflow--; } return rv; } static struct flow * match_flow_ipv4_dst_mask(struct flowinfo *self, struct lagopus_packet *pkt, int32_t *pri) { struct flowinfo *flowinfo; struct flow *flow[self->nnext], *matched, *alt_flow; struct flow mismatched = { .priority = 0, .flags = 0, .idle_timeout = 0, .hard_timeout = 0, .match_list = {NULL, NULL}, .instruction_list = {NULL, NULL}, .field_bits = 0 }; unsigned int i; matched = &mismatched; //#pragma omp parallel for for (i = 0; i < self->nnext; i++) { flowinfo = self->next[i]; flow[i] = flowinfo->match_func(flowinfo, pkt, pri); } for (i = 0; i < self->nnext; i++) { if (flow[i] != NULL && flow[i]->priority > matched->priority) { matched = flow[i]; } } alt_flow = self->misc->match_func(self->misc, pkt, pri); if (alt_flow != NULL) { matched = alt_flow; } if (matched == &mismatched) { matched = NULL; } return matched; } static struct flow * find_flow_ipv4_dst_mask(struct flowinfo *self, struct flow *flow) { struct flowinfo *flowinfo; uint32_t ipv4_dst, mask; lagopus_result_t rv; unsigned int i; rv = get_match_ipv4_dst(&flow->match_list, &ipv4_dst, &mask); if (rv == LAGOPUS_RESULT_OK) { rv = LAGOPUS_RESULT_NOT_FOUND; for (i = 0; i < self->nnext; i++) { if (self->next[i]->userdata == mask) { flowinfo = self->next[i]; rv = LAGOPUS_RESULT_OK; break; } } if (rv == LAGOPUS_RESULT_NOT_FOUND) { return NULL; } } else { flowinfo = self->misc; } return flowinfo->find_func(flowinfo, flow); } static lagopus_result_t add_flow_ipv4_dst(struct flowinfo *self, struct flow *flow) { struct flowinfo *flowinfo; uint32_t ipv4_dst, mask; lagopus_result_t rv; rv = get_match_ipv4_dst(&flow->match_list, &ipv4_dst, &mask); if (rv == LAGOPUS_RESULT_OK) { rv = lagopus_hashmap_find_no_lock(&self->hashmap, (void *)ipv4_dst, (void *)&flowinfo); if (rv != LAGOPUS_RESULT_OK) { void *val; flowinfo = new_flowinfo_ipv4(); val = flowinfo; lagopus_hashmap_add_no_lock(&self->hashmap, (void *)ipv4_dst, (void *)&val, false); } rv = flowinfo->add_func(flowinfo, flow); if (rv == LAGOPUS_RESULT_OK) { self->nflow++; } } return rv; } static lagopus_result_t del_flow_ipv4_dst(struct flowinfo *self, struct flow *flow) { uint32_t ipv4_dst, mask; lagopus_result_t rv; rv = get_match_ipv4_dst(&flow->match_list, &ipv4_dst, &mask); if (rv == LAGOPUS_RESULT_OK) { struct flowinfo *flowinfo; rv = lagopus_hashmap_find_no_lock(&self->hashmap, (void *)ipv4_dst, (void *)&flowinfo); if (rv == LAGOPUS_RESULT_OK) { flowinfo->del_func(flowinfo, flow); } if (rv == LAGOPUS_RESULT_OK) { self->nflow--; } } return rv; } static struct flow * match_flow_ipv4_dst(struct flowinfo *self, struct lagopus_packet *pkt, int32_t *pri) { struct flowinfo *flowinfo; uint32_t ipv4_dst; struct flow *flow; lagopus_result_t rv; flow = NULL; ipv4_dst = (pkt->ipv4->ip_dst.s_addr & (uint32_t)self->userdata); rv = lagopus_hashmap_find_no_lock(&self->hashmap, (void *)ipv4_dst, (void *)&flowinfo); if (rv == LAGOPUS_RESULT_OK) { flow = flowinfo->match_func(flowinfo, pkt, pri); } return flow; } static struct flow * find_flow_ipv4_dst(struct flowinfo *self, struct flow *flow) { struct flowinfo *flowinfo; uint32_t ipv4_dst, mask; lagopus_result_t rv; rv = get_match_ipv4_dst(&flow->match_list, &ipv4_dst, &mask); if (rv == LAGOPUS_RESULT_OK) { rv = lagopus_hashmap_find_no_lock(&self->hashmap, (void *)ipv4_dst, (void *)&flowinfo); if (rv != LAGOPUS_RESULT_OK) { return NULL; } return flowinfo->find_func(flowinfo, flow); } else { return self->misc->find_func(self->misc, flow); } }
GB_unaryop__ainv_uint32_int32.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__ainv_uint32_int32 // op(A') function: GB_tran__ainv_uint32_int32 // C type: uint32_t // A type: int32_t // cast: uint32_t cij = (uint32_t) aij // unaryop: cij = -aij #define GB_ATYPE \ int32_t #define GB_CTYPE \ uint32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int32_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_AINV || GxB_NO_UINT32 || GxB_NO_INT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__ainv_uint32_int32 ( uint32_t *restrict Cx, const int32_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__ainv_uint32_int32 ( 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
3d25pt.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-2, 3D 25 point stencil * 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) #ifndef min #define min(x,y) ((x) < (y)? (x) : (y)) #endif /* 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, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); double ***roc2 = (double ***) malloc(sizeof(double**)); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); roc2 = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); roc2[i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); roc2[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] = 8; tile_size[1] = 8; tile_size[2] = 8; 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); roc2[i][j][k] = 2.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 const double coef0 = -0.28472; const double coef1 = 0.16000; const double coef2 = -0.02000; const double coef3 = 0.00254; const double coef4 = -0.00018; 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 >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) { for (t1=-1;t1<=Nt-1;t1++) { lbp=ceild(t1+1,2); ubp=min(floord(4*Nt+Nz-9,8),floord(4*t1+Nz-2,8)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(ceild(t1,2),ceild(8*t2-Nz+5,8));t3<=min(floord(4*Nt+Ny-9,8),floord(4*t1+Ny-1,8));t3++) { for (t4=max(max(ceild(t1-14,16),ceild(8*t2-Nz-51,64)),ceild(8*t3-Ny-51,64));t4<=min(min(floord(4*Nt+Nx-9,64),floord(4*t1+Nx-1,64)),floord(8*t3+Nx-5,64));t4++) { for (t5=max(max(max(max(0,ceild(8*t2-Nz+5,4)),ceild(8*t3-Ny+5,4)),ceild(64*t4-Nx+5,4)),t1);t5<=min(min(min(2*t3,Nt-1),t1+1),16*t4+14);t5++) { for (t6=max(max(8*t2,4*t5+4),-8*t1+8*t2+8*t5-7);t6<=min(min(8*t2+7,-8*t1+8*t2+8*t5),4*t5+Nz-5);t6++) { for (t7=max(8*t3,4*t5+4);t7<=min(8*t3+7,4*t5+Ny-5);t7++) { lbv=max(64*t4,4*t5+4); ubv=min(64*t4+63,4*t5+Nx-5); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((2.0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) - A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (roc2[ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (((((coef0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef1 * (((((A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef2 * (((((A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef3 * (((((A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef4 * (((((A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])))));; } } } } } } } } } /* 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(4, "constant") #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(roc2[i][j]); } free(A[0][i]); free(A[1][i]); free(roc2[i]); } free(A[0]); free(A[1]); free(roc2); return 0; }
array_max_omp.c
/* --- File array_max_omp.c --- */ #include <stdio.h> #include <stdlib.h> #include <time.h> int main(int argc, char **argv) { struct timespec ts_start, ts_end; float time_total; int size = 1e7; int *rand_nums; int i; int curr_max; time_t t; rand_nums=malloc(size*sizeof(int)); /* Intialize random number generator */ srand((unsigned) time(&t)); /* Initialize array with random values */ for (i=0; i<size; i++) { rand_nums[i] = rand(); } curr_max = 0.0; /* Get start time */ clock_gettime(CLOCK_MONOTONIC, &ts_start); #pragma omp parallel for reduction(max:curr_max) for (i=0; i<size; i++) { if (curr_max < rand_nums[i]) { curr_max = rand_nums[i]; } } /* Get end time */ clock_gettime(CLOCK_MONOTONIC, &ts_end); time_total = (ts_end.tv_sec - ts_start.tv_sec)*1e9 + \ (ts_end.tv_nsec - ts_start.tv_nsec); printf("Total time is %f ms\n", time_total/1e6); printf("Max value is %d\n", curr_max); }
testcase_1.c
int *var=6; struct mystruct *ms=&var; int auto, static, inline; extern void *k; int p; int p; int p; int *hh(char *p); int main(int b) { int auto=2,b=3,c; c=auto+b; printf("%d",c); struct player { int a; double c; }; int *jj=&auto; System.out.print("java here"); char echo[3]="bash here"; myprintf("CS3300 here"); printf(echo); /* mixing things here a bit */ if(a==9) { //NO-OP } if(a==1) hh(++jj); else if(a==2) hh(jj++); else if(a==3) hh(*jj++); else { //NO-OP } struct player *p; p->a=1; p->b=2.4; //#pragma omp parallel for for(a=1;a<=5;a++) static(a); int *p; float *j; p=&auto; j=0x1234; printf("*j=%p",(char *)j); void *static=&c; int a=5,b=8,c; c=a<=>b; hh(p); return(0); } int *hh(char *p) { int n=7; scanf("%d",&n); if(n==0) printf("%d\n",n+1); else if(n==1) printf("%d\n",n+2); return(NULL); }
GB_unop__conj_fc64_fc64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary 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_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__conj_fc64_fc64 // op(A') function: GB_unop_tran__conj_fc64_fc64 // C type: GxB_FC64_t // A type: GxB_FC64_t // cast: GxB_FC64_t cij = aij // unaryop: cij = conj (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 = conj (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] = conj (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_CONJ || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__conj_fc64_fc64 ( GxB_FC64_t *Cx, // Cx and Ax may be aliased const GxB_FC64_t *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #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] = conj (z) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__conj_fc64_fc64 ( GrB_Matrix C, const GrB_Matrix A, 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 #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unaryop__identity_fp32_fp32.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_fp32_fp32 // op(A') function: GB_tran__identity_fp32_fp32 // C type: float // A type: float // cast: float cij = (float) aij // unaryop: cij = aij #define GB_ATYPE \ float #define GB_CTYPE \ float // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CASTING(z, x) \ float z = (float) 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_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__identity_fp32_fp32 ( float *restrict Cx, const float *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_fp32_fp32 ( 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
dfwavelet.c
/* * Copyright 2013-2015 The Regents of the University of California. * All rights reserved. Use of this source code is governed by * a BSD-style license which can be found in the LICENSE file. * * Authors: * 2013 Frank Ong <frankong@berkeley.edu> * 2013 Martin Uecker, Pat Virtue, and Mark Murphy * * * Ong F, Uecker M, Tariq U, Hsiao A, Alley MT, Vasanawala SS, Lustig M. * Robust 4D Flow Denoising using Divergence-free Wavelet Transform, * Magn Reson Med 2015; 73: 828-842. */ #define _GNU_SOURCE #include <math.h> #include <string.h> #include <assert.h> #include <complex.h> #ifdef _WIN32 #include "win/rand_r.h" #endif #include "num/multind.h" #include "misc/misc.h" #include "dfwavelet.h" #include "dfwavelet_impl.h" #ifdef USE_CUDA #include "dfwavelet_kernels.h" #endif #define str_eq(s1,s2) (!strcmp ((s1),(s2))) /******** Header *********/ static void dffwt3_cpu(struct dfwavelet_plan_s* plan, data_t* out_wcdf1,data_t* out_wcdf2,data_t* out_wcn, data_t* in_vx,data_t* in_vy,data_t* in_vz); static void dfiwt3_cpu(struct dfwavelet_plan_s* plan, data_t* out_vx,data_t* out_vy,data_t* out_vz, data_t* in_wcdf1,data_t* in_wcdf2,data_t* in_wcn); static void dfsoftthresh_cpu(struct dfwavelet_plan_s* plan,scalar_t dfthresh, scalar_t nthresh, data_t* out_wcdf1,data_t* out_wcdf2,data_t* out_wcn); static void dfwavthresh3_cpu(struct dfwavelet_plan_s* plan,scalar_t dfthresh, scalar_t nthresh,data_t* out_vx,data_t* out_vy,data_t* out_vz,data_t* in_vx,data_t* in_vy,data_t* in_vz); void dflincomb_cpu(struct dfwavelet_plan_s* plan,data_t* wc1,data_t* wc2,data_t* wc3); void dfunlincomb_cpu(struct dfwavelet_plan_s* plan,data_t* wc1,data_t* wc2,data_t* wc3); static void fwt3_cpu(struct dfwavelet_plan_s* plan, data_t* out, data_t* in,int dir); static void iwt3_cpu(struct dfwavelet_plan_s* plan, data_t* out, data_t* in,int dir); static void circshift_cpu(struct dfwavelet_plan_s* plan, data_t *data); static void circunshift_cpu(struct dfwavelet_plan_s* plan, data_t *data); static void conv_down_3d(data_t *out, data_t *in, int size1, int skip1, int size2, int skip2, int size3, int skip3, scalar_t *filter, int filterLen); static void conv_up_3d(data_t *out, data_t *in, int size1, int skip1, int size2, int skip2, int size3, int skip3, scalar_t *filter, int filterLen); static void mult(data_t* in,scalar_t scalar,int maxInd); static void create_numLevels(struct dfwavelet_plan_s* plan); static void create_wavelet_sizes(struct dfwavelet_plan_s* plan); static void create_wavelet_filters(struct dfwavelet_plan_s* plan); static void get_noise_amp (struct dfwavelet_plan_s* plan); struct dfwavelet_plan_s* prepare_dfwavelet_plan(int numdims, long* imSize, long* minSize, data_t* res,int use_gpu) { struct dfwavelet_plan_s* plan = (struct dfwavelet_plan_s*) malloc(sizeof(struct dfwavelet_plan_s)); plan->use_gpu = use_gpu; plan->numdims = numdims; plan->imSize = (long*) malloc(sizeof(long)*numdims); plan->minSize = (long*) malloc(sizeof(long)*numdims); plan->res = (data_t*) malloc(sizeof(data_t)*numdims); plan->percentZero = -1; plan->noiseAmp = NULL; // Get imSize, numPixel, numdims plan->numPixel = 1; int i; for (i = 0; i < numdims; i++) { plan->imSize[i] = imSize[i]; plan->numPixel *= imSize[i]; plan->minSize[i] = minSize[i]; plan->res[i] = res[i]; } create_wavelet_filters(plan); create_numLevels(plan); create_wavelet_sizes(plan); plan->randShift = (int*) malloc(sizeof(int)*plan->numdims); memset(plan->randShift,0,sizeof(int)*plan->numdims); get_noise_amp(plan); return plan; } void dfwavelet_forward(struct dfwavelet_plan_s* plan, data_t* out_wcdf1, data_t* out_wcdf2, data_t* out_wcn, data_t* in_vx, data_t* in_vy, data_t* in_vz) { if(plan->use_gpu==0) dffwt3_cpu(plan,out_wcdf1,out_wcdf2,out_wcn,in_vx,in_vy,in_vz); #ifdef USE_CUDA if(plan->use_gpu==1) dffwt3_gpu(plan,out_wcdf1,out_wcdf2,out_wcn,in_vx,in_vy,in_vz); if(plan->use_gpu==2) dffwt3_gpuHost(plan,out_wcdf1,out_wcdf2,out_wcn,in_vx,in_vy,in_vz); #endif } void dfwavelet_inverse(struct dfwavelet_plan_s* plan, data_t* out_vx,data_t* out_vy,data_t* out_vz, data_t* in_wcdf1,data_t* in_wcdf2,data_t* in_wcn) { if(plan->use_gpu==0) dfiwt3_cpu(plan,out_vx,out_vy,out_vz,in_wcdf1,in_wcdf2,in_wcn); #ifdef USE_CUDA if(plan->use_gpu==1) dfiwt3_gpu(plan,out_vx,out_vy,out_vz,in_wcdf1,in_wcdf2,in_wcn); if(plan->use_gpu==2) dfiwt3_gpuHost(plan,out_vx,out_vy,out_vz,in_wcdf1,in_wcdf2,in_wcn); #endif } void dfsoft_thresh(struct dfwavelet_plan_s* plan, scalar_t dfthresh, scalar_t nthresh,data_t* wcdf1,data_t* wcdf2, data_t* wcn) { if(plan->use_gpu==0) dfsoftthresh_cpu(plan,dfthresh,nthresh,wcdf1,wcdf2,wcn); #ifdef USE_CUDA if(plan->use_gpu==1) dfsoftthresh_gpu(plan,dfthresh,nthresh,wcdf1,wcdf2,wcn); if(plan->use_gpu==2) dfsoftthresh_gpuHost(plan,dfthresh,nthresh,wcdf1,wcdf2,wcn); #endif } void dfwavelet_thresh(struct dfwavelet_plan_s* plan, scalar_t dfthresh, scalar_t nthresh,data_t* out_vx, data_t* out_vy, data_t* out_vz, data_t* in_vx,data_t* in_vy, data_t* in_vz) { if(plan->use_gpu==0) dfwavthresh3_cpu(plan,dfthresh,nthresh,out_vx,out_vy,out_vz, in_vx,in_vy,in_vz); #ifdef USE_CUDA if(plan->use_gpu==1) dfwavthresh3_gpu(plan,dfthresh,nthresh, out_vx,out_vy,out_vz, in_vx,in_vy,in_vz); if(plan->use_gpu==2) dfwavthresh3_gpuHost(plan,dfthresh,nthresh,out_vx,out_vy,out_vz,in_vx,in_vy,in_vz); #endif } static int dfrand_lim(unsigned int* state, int limit) { int divisor = RAND_MAX/(limit+1); int retval = 0; do { retval = rand_r(state) / divisor; } while (retval > limit); return retval; } void dfwavelet_new_randshift (struct dfwavelet_plan_s* plan) { int i; int maxShift = 1 << (plan->numLevels); for(i = 0; i < plan->numdims; i++) { // Generate random shift value between 0 and maxShift plan->randShift[i] = dfrand_lim(&plan->state, maxShift); } } void dfwavelet_clear_randshift (struct dfwavelet_plan_s* plan) { memset(plan->randShift, 0, plan->numdims*sizeof(int)); } void dfwavelet_free(struct dfwavelet_plan_s* plan) { free(plan->imSize); free(plan->minSize); free(plan->lod0); free(plan->lod1); free(plan->res); free(plan->waveSizes); free(plan->randShift); if (plan->noiseAmp!=NULL) free(plan->noiseAmp); free(plan); } ////////////// Private Functions ////////////// void dffwt3_cpu(struct dfwavelet_plan_s* plan, data_t* out_wcdf1,data_t* out_wcdf2,data_t* out_wcn, data_t* in_vx,data_t* in_vy,data_t* in_vz) { fwt3_cpu(plan,out_wcdf1,in_vx,0); fwt3_cpu(plan,out_wcdf2,in_vy,1); fwt3_cpu(plan,out_wcn,in_vz,2); mult(out_wcdf1,1/plan->res[0],plan->numCoeff); mult(out_wcdf2,1/plan->res[1],plan->numCoeff); mult(out_wcn,1/plan->res[2],plan->numCoeff); dflincomb_cpu(plan,out_wcdf1,out_wcdf2,out_wcn); } void dfiwt3_cpu(struct dfwavelet_plan_s* plan, data_t* out_vx,data_t* out_vy,data_t* out_vz, data_t* in_wcdf1,data_t* in_wcdf2,data_t* in_wcn) { dfunlincomb_cpu(plan,in_wcdf1,in_wcdf2,in_wcn); mult(in_wcdf1,plan->res[0],plan->numCoeff); mult(in_wcdf2,plan->res[1],plan->numCoeff); mult(in_wcn,plan->res[2],plan->numCoeff); iwt3_cpu(plan,out_vx,in_wcdf1,0); iwt3_cpu(plan,out_vy,in_wcdf2,1); iwt3_cpu(plan,out_vz,in_wcn,2); } void dfsoftthresh_cpu(struct dfwavelet_plan_s* plan,scalar_t dfthresh, scalar_t nthresh, data_t* wcdf1,data_t* wcdf2,data_t* wcn) { data_t* HxLyLz1 = wcdf1 + plan->waveSizes[0]*plan->waveSizes[1]*plan->waveSizes[2]; data_t* HxLyLz2 = wcdf2 + plan->waveSizes[0]*plan->waveSizes[1]*plan->waveSizes[2]; data_t* HxLyLz3 = wcn + plan->waveSizes[0]*plan->waveSizes[1]*plan->waveSizes[2]; int l; for (l = 1; l <= plan->numLevels; ++l){ HxLyLz1 += 7*plan->waveSizes[0 + 3*l]*plan->waveSizes[1 + 3*l]*plan->waveSizes[2 + 3*l]; HxLyLz2 += 7*plan->waveSizes[0 + 3*l]*plan->waveSizes[1 + 3*l]*plan->waveSizes[2 + 3*l]; HxLyLz3 += 7*plan->waveSizes[0 + 3*l]*plan->waveSizes[1 + 3*l]*plan->waveSizes[2 + 3*l]; } int dxNext = plan->waveSizes[0 + 3*plan->numLevels]; int dyNext = plan->waveSizes[1 + 3*plan->numLevels]; int dzNext = plan->waveSizes[2 + 3*plan->numLevels]; int blockSize = dxNext*dyNext*dzNext; int naInd = 0; for (l = plan->numLevels; l >= 1; --l) { dxNext = plan->waveSizes[0 + 3*l]; dyNext = plan->waveSizes[1 + 3*l]; dzNext = plan->waveSizes[2 + 3*l]; blockSize = dxNext*dyNext*dzNext; HxLyLz1 = HxLyLz1 - 7*blockSize; HxLyLz2 = HxLyLz2 - 7*blockSize; HxLyLz3 = HxLyLz3 - 7*blockSize; int bandInd; for (bandInd=0; bandInd<7*3;bandInd++) { data_t *subband; scalar_t lambda; if (bandInd<7) { subband = HxLyLz1 + bandInd*blockSize; lambda = dfthresh * plan->noiseAmp[naInd]; } else if (bandInd<14) { subband = HxLyLz2 + (bandInd-7)*blockSize; lambda = dfthresh * plan->noiseAmp[naInd]; } else { subband = HxLyLz3 + (bandInd-14)*blockSize; lambda = nthresh * plan->noiseAmp[naInd]; } // SoftThresh float const eps = 1.1921e-7f; #pragma omp parallel for for(int i = 0; i < blockSize; i++) { scalar_t norm = cabs(subband[i]); scalar_t red = norm - lambda; red = 0.5f*(red + fabs(red)); red = red / (norm + eps); subband[i] = red * subband[i]; } naInd++; } } } void dfwavthresh3_cpu(struct dfwavelet_plan_s* plan,scalar_t dfthresh, scalar_t nthresh,data_t* out_vx,data_t* out_vy,data_t* out_vz,data_t* in_vx,data_t* in_vy,data_t* in_vz) { data_t *wcdf1,*wcdf2,*wcn; wcdf1 = (data_t*) malloc(sizeof(data_t)*plan->numCoeff); wcdf2 = (data_t*) malloc(sizeof(data_t)*plan->numCoeff); wcn = (data_t*) malloc(sizeof(data_t)*plan->numCoeff); dffwt3_cpu(plan, wcdf1,wcdf2,wcn,in_vx,in_vy,in_vz); dfsoftthresh_cpu(plan,dfthresh,nthresh,wcdf1,wcdf2,wcn); dfiwt3_cpu(plan,out_vx,out_vy,out_vz,wcdf1,wcdf2,wcn); free(wcdf1); free(wcdf2); free(wcn); } void dflincomb_cpu(struct dfwavelet_plan_s* plan,data_t* wc1,data_t* wc2,data_t* wc3) { data_t* HxLyLz1 = wc1 + plan->waveSizes[0]*plan->waveSizes[1]*plan->waveSizes[2]; data_t* HxLyLz2 = wc2 + plan->waveSizes[0]*plan->waveSizes[1]*plan->waveSizes[2]; data_t* HxLyLz3 = wc3 + plan->waveSizes[0]*plan->waveSizes[1]*plan->waveSizes[2]; int l; for (l = 1; l <= plan->numLevels; ++l){ HxLyLz1 += 7*plan->waveSizes[0 + 3*l]*plan->waveSizes[1 + 3*l]*plan->waveSizes[2 + 3*l]; HxLyLz2 += 7*plan->waveSizes[0 + 3*l]*plan->waveSizes[1 + 3*l]*plan->waveSizes[2 + 3*l]; HxLyLz3 += 7*plan->waveSizes[0 + 3*l]*plan->waveSizes[1 + 3*l]*plan->waveSizes[2 + 3*l]; } int dxNext = plan->waveSizes[0 + 3*plan->numLevels]; int dyNext = plan->waveSizes[1 + 3*plan->numLevels]; int dzNext = plan->waveSizes[2 + 3*plan->numLevels]; int blockSize = dxNext*dyNext*dzNext; int i,j,k; for (l = plan->numLevels; l >= 1; --l) { dxNext = plan->waveSizes[0 + 3*l]; dyNext = plan->waveSizes[1 + 3*l]; dzNext = plan->waveSizes[2 + 3*l]; blockSize = dxNext*dyNext*dzNext; HxLyLz1 = HxLyLz1 - 7*blockSize; HxLyLz2 = HxLyLz2 - 7*blockSize; HxLyLz3 = HxLyLz3 - 7*blockSize; data_t* LxHyLz1 = HxLyLz1 + blockSize; data_t* HxHyLz1 = LxHyLz1 + blockSize; data_t* LxLyHz1 = HxHyLz1 + blockSize; data_t* HxLyHz1 = LxLyHz1 + blockSize; data_t* LxHyHz1 = HxLyHz1 + blockSize; data_t* HxHyHz1 = LxHyHz1 + blockSize; data_t* LxHyLz2 = HxLyLz2 + blockSize; data_t* HxHyLz2 = LxHyLz2 + blockSize; data_t* LxLyHz2 = HxHyLz2 + blockSize; data_t* HxLyHz2 = LxLyHz2 + blockSize; data_t* LxHyHz2 = HxLyHz2 + blockSize; data_t* HxHyHz2 = LxHyHz2 + blockSize; data_t* LxHyLz3 = HxLyLz3 + blockSize; data_t* HxHyLz3 = LxHyLz3 + blockSize; data_t* LxLyHz3 = HxHyLz3 + blockSize; data_t* HxLyHz3 = LxLyHz3 + blockSize; data_t* LxHyHz3 = HxLyHz3 + blockSize; data_t* HxHyHz3 = LxHyHz3 + blockSize; #pragma omp parallel for private(i,j,k) for (k=0;k<dzNext;k++) for (j=0;j<dyNext;j++) for (i=0;i<dxNext;i++) { int ind = i+j*dxNext+k*dxNext*dyNext; data_t wcx100 = HxLyLz1[ind]; data_t wcy100 = HxLyLz2[ind]; data_t wcz100 = HxLyLz3[ind]; data_t wcx010 = LxHyLz1[ind]; data_t wcy010 = LxHyLz2[ind]; data_t wcz010 = LxHyLz3[ind]; data_t wcx001 = LxLyHz1[ind]; data_t wcy001 = LxLyHz2[ind]; data_t wcz001 = LxLyHz3[ind]; data_t wcx110 = HxHyLz1[ind]; data_t wcy110 = HxHyLz2[ind]; data_t wcz110 = HxHyLz3[ind]; data_t wcx101 = HxLyHz1[ind]; data_t wcy101 = HxLyHz2[ind]; data_t wcz101 = HxLyHz3[ind]; data_t wcx011 = LxHyHz1[ind]; data_t wcy011 = LxHyHz2[ind]; data_t wcz011 = LxHyHz3[ind]; data_t wcx111 = HxHyHz1[ind]; data_t wcy111 = HxHyHz2[ind]; data_t wcz111 = HxHyHz3[ind]; HxLyLz1[ind] = wcy100; LxHyLz1[ind] = wcx010; LxLyHz1[ind] = wcy001; HxLyLz2[ind] = wcz100; LxHyLz2[ind] = wcz010; LxLyHz2[ind] = wcx001; HxLyLz3[ind] = wcx100; LxHyLz3[ind] = wcy010; LxLyHz3[ind] = wcz001; HxHyLz1[ind] = 0.5*(wcx110-wcy110); HxLyHz1[ind] = 0.5*(wcz101-wcx101); LxHyHz1[ind] = 0.5*(wcy011-wcz011); HxHyLz2[ind] = wcz110; HxLyHz2[ind] = wcy101; LxHyHz2[ind] = wcx011; HxHyLz3[ind] = 0.5*(wcx110+wcy110); HxLyHz3[ind] = 0.5*(wcz101+wcx101); LxHyHz3[ind] = 0.5*(wcy011+wcz011); HxHyHz1[ind] = 1/3.*(-2*wcx111+wcy111+wcz111); HxHyHz2[ind] = 1/3.*(-wcx111+2*wcy111-wcz111); HxHyHz3[ind] = 1/3.*(wcx111+wcy111+wcz111); } #pragma omp barrier #pragma omp parallel for private(i,j,k) for (k=0;k<dzNext;k++) for (j=0;j<dyNext;j++) for (i=0;i<dxNext;i++) { int ind = i+j*dxNext+k*dxNext*dyNext; int indxs = ind-1; int indys = ind-dxNext; int indzs = ind-dxNext*dyNext; if (i==0) indxs = 0; if (j==0) indys = 0; if (k==0) indzs = 0; data_t wcy100 = HxLyLz1[ind]; data_t wcy100s = HxLyLz1[indys]; data_t wcz100 = HxLyLz2[ind]; data_t wcz100s = HxLyLz2[indzs]; data_t wcx010 = LxHyLz1[ind]; data_t wcx010s = LxHyLz1[indxs]; data_t wcz010 = LxHyLz2[ind]; data_t wcz010s = LxHyLz2[indzs]; data_t wcx001 = LxLyHz2[ind]; data_t wcx001s = LxLyHz2[indxs]; data_t wcy001 = LxLyHz1[ind]; data_t wcy001s = LxLyHz1[indys]; data_t wcz110 = HxHyLz2[ind]; data_t wcz110s = HxHyLz2[indzs]; data_t wcy101 = HxLyHz2[ind]; data_t wcy101s = HxLyHz2[indys]; data_t wcx011 = LxHyHz2[ind]; data_t wcx011s = LxHyHz2[indxs]; HxLyLz3[ind] = HxLyLz3[ind]+0.25*(wcy100-wcy100s+wcz100-wcz100s); LxHyLz3[ind] = LxHyLz3[ind]+0.25*(wcx010-wcx010s+wcz010-wcz010s); LxLyHz3[ind] = LxLyHz3[ind]+0.25*(wcx001-wcx001s+wcy001-wcy001s); HxHyLz3[ind] = HxHyLz3[ind] + 0.125*(wcz110-wcz110s); HxLyHz3[ind] = HxLyHz3[ind] + 0.125*(wcy101-wcy101s); LxHyHz3[ind] = LxHyHz3[ind] + 0.125*(wcx011-wcx011s); } } } void dfunlincomb_cpu(struct dfwavelet_plan_s* plan,data_t* wc1,data_t* wc2,data_t* wc3) { data_t* HxLyLz1 = wc1 + plan->waveSizes[0]*plan->waveSizes[1]*plan->waveSizes[2]; data_t* HxLyLz2 = wc2 + plan->waveSizes[0]*plan->waveSizes[1]*plan->waveSizes[2]; data_t* HxLyLz3 = wc3 + plan->waveSizes[0]*plan->waveSizes[1]*plan->waveSizes[2]; int l; for (l = 1; l <= plan->numLevels; ++l){ HxLyLz1 += 7*plan->waveSizes[0 + 3*l]*plan->waveSizes[1 + 3*l]*plan->waveSizes[2 + 3*l]; HxLyLz2 += 7*plan->waveSizes[0 + 3*l]*plan->waveSizes[1 + 3*l]*plan->waveSizes[2 + 3*l]; HxLyLz3 += 7*plan->waveSizes[0 + 3*l]*plan->waveSizes[1 + 3*l]*plan->waveSizes[2 + 3*l]; } int dxNext = plan->waveSizes[0 + 3*plan->numLevels]; int dyNext = plan->waveSizes[1 + 3*plan->numLevels]; int dzNext = plan->waveSizes[2 + 3*plan->numLevels]; int blockSize = dxNext*dyNext*dzNext; int i,j,k; for (l = plan->numLevels; l >= 1; --l) { dxNext = plan->waveSizes[0 + 3*l]; dyNext = plan->waveSizes[1 + 3*l]; dzNext = plan->waveSizes[2 + 3*l]; blockSize = dxNext*dyNext*dzNext; HxLyLz1 = HxLyLz1 - 7*blockSize; HxLyLz2 = HxLyLz2 - 7*blockSize; HxLyLz3 = HxLyLz3 - 7*blockSize; data_t* LxHyLz1 = HxLyLz1 + blockSize; data_t* HxHyLz1 = LxHyLz1 + blockSize; data_t* LxLyHz1 = HxHyLz1 + blockSize; data_t* HxLyHz1 = LxLyHz1 + blockSize; data_t* LxHyHz1 = HxLyHz1 + blockSize; data_t* HxHyHz1 = LxHyHz1 + blockSize; data_t* LxHyLz2 = HxLyLz2 + blockSize; data_t* HxHyLz2 = LxHyLz2 + blockSize; data_t* LxLyHz2 = HxHyLz2 + blockSize; data_t* HxLyHz2 = LxLyHz2 + blockSize; data_t* LxHyHz2 = HxLyHz2 + blockSize; data_t* HxHyHz2 = LxHyHz2 + blockSize; data_t* LxHyLz3 = HxLyLz3 + blockSize; data_t* HxHyLz3 = LxHyLz3 + blockSize; data_t* LxLyHz3 = HxHyLz3 + blockSize; data_t* HxLyHz3 = LxLyHz3 + blockSize; data_t* LxHyHz3 = HxLyHz3 + blockSize; data_t* HxHyHz3 = LxHyHz3 + blockSize; #pragma omp parallel for private(i,j,k) for (k=0;k<dzNext;k++) for (j=0;j<dyNext;j++) for (i=0;i<dxNext;i++) { int ind = i+j*dxNext+k*dxNext*dyNext; data_t df1_100 = HxLyLz1[ind]; data_t df2_100 = HxLyLz2[ind]; data_t n_100 = HxLyLz3[ind]; data_t df1_010 = LxHyLz1[ind]; data_t df2_010 = LxHyLz2[ind]; data_t n_010 = LxHyLz3[ind]; data_t df1_001 = LxLyHz1[ind]; data_t df2_001 = LxLyHz2[ind]; data_t n_001 = LxLyHz3[ind]; data_t df1_110 = HxHyLz1[ind]; data_t df2_110 = HxHyLz2[ind]; data_t n_110 = HxHyLz3[ind]; data_t df1_101 = HxLyHz1[ind]; data_t df2_101 = HxLyHz2[ind]; data_t n_101 = HxLyHz3[ind]; data_t df1_011 = LxHyHz1[ind]; data_t df2_011 = LxHyHz2[ind]; data_t n_011 = LxHyHz3[ind]; data_t df1_111 = HxHyHz1[ind]; data_t df2_111 = HxHyHz2[ind]; data_t n_111 = HxHyHz3[ind]; HxLyLz2[ind] = df1_100; LxHyLz1[ind] = df1_010; LxLyHz2[ind] = df1_001; HxLyLz3[ind] = df2_100; LxHyLz3[ind] = df2_010; LxLyHz1[ind] = df2_001; HxLyLz1[ind] = n_100; LxHyLz2[ind] = n_010; LxLyHz3[ind] = n_001; HxHyLz3[ind] = df2_110; HxLyHz2[ind] = df2_101; LxHyHz1[ind] = df2_011; HxHyLz1[ind] = (df1_110+n_110); HxLyHz3[ind] = (df1_101+n_101); LxHyHz2[ind] = (df1_011+n_011); HxHyLz2[ind] = (-df1_110+n_110); HxLyHz1[ind] = (-df1_101+n_101); LxHyHz3[ind] = (-df1_011+n_011); HxHyHz1[ind] = (-df1_111+n_111); HxHyHz2[ind] = (df2_111+n_111); HxHyHz3[ind] = df1_111-df2_111+n_111; } #pragma omp barrier #pragma omp parallel for private(i,j,k) for (k=0;k<dzNext;k++) for (j=0;j<dyNext;j++) for (i=0;i<dxNext;i++) { int ind = i+j*dxNext+k*dxNext*dyNext; int indxs = ind-1; int indys = ind-dxNext; int indzs = ind-dxNext*dyNext; if (i==0) indxs = 0; if (j==0) indys = 0; if (k==0) indzs = 0; data_t df1_100 = HxLyLz2[ind]; data_t df1_100s = HxLyLz2[indys]; data_t df2_100 = HxLyLz3[ind]; data_t df2_100s = HxLyLz3[indzs]; data_t df1_010 = LxHyLz1[ind]; data_t df1_010s = LxHyLz1[indxs]; data_t df2_010 = LxHyLz3[ind]; data_t df2_010s = LxHyLz3[indzs]; data_t df2_001 = LxLyHz1[ind]; data_t df2_001s = LxLyHz1[indxs]; data_t df1_001 = LxLyHz2[ind]; data_t df1_001s = LxLyHz2[indys]; data_t df2_110 = HxHyLz3[ind]; data_t df2_110s = HxHyLz3[indzs]; data_t df2_101 = HxLyHz2[ind]; data_t df2_101s = HxLyHz2[indys]; data_t df2_011 = LxHyHz1[ind]; data_t df2_011s = LxHyHz1[indxs]; HxLyLz1[ind] = HxLyLz1[ind]-0.25*(df1_100-df1_100s+df2_100-df2_100s); LxHyLz2[ind] = LxHyLz2[ind]-0.25*(df1_010-df1_010s+df2_010-df2_010s); LxLyHz3[ind] = LxLyHz3[ind]-0.25*(df2_001-df2_001s+df1_001-df1_001s); HxHyLz1[ind] = HxHyLz1[ind] - 0.125*(df2_110-df2_110s); HxLyHz3[ind] = HxLyHz3[ind] - 0.125*(df2_101-df2_101s); LxHyHz2[ind] = LxHyHz2[ind] - 0.125*(df2_011-df2_011s); HxHyLz2[ind] = HxHyLz2[ind] - 0.125*(df2_110-df2_110s); HxLyHz1[ind] = HxLyHz1[ind] - 0.125*(df2_101-df2_101s); LxHyHz3[ind] = LxHyHz3[ind] - 0.125*(df2_011-df2_011s); } } } void fwt3_cpu(struct dfwavelet_plan_s* plan, data_t* coeff, data_t* inImage,int dir) { circshift_cpu(plan,inImage); data_t* origInImage = inImage; data_t* HxLyLz = coeff + plan->waveSizes[0]*plan->waveSizes[1]*plan->waveSizes[2]; int l; for (l = 1; l <= plan->numLevels; ++l){ HxLyLz += 7*plan->waveSizes[0 + 3*l]*plan->waveSizes[1 + 3*l]*plan->waveSizes[2 + 3*l]; } int dx = plan->imSize[0]; int dy = plan->imSize[1]; int dz = plan->imSize[2]; int dxNext = plan->waveSizes[0 + 3*plan->numLevels]; int dyNext = plan->waveSizes[1 + 3*plan->numLevels]; int dzNext = plan->waveSizes[2 + 3*plan->numLevels]; int blockSize = dxNext*dyNext*dzNext; data_t* LxLyLz = (data_t*) malloc(sizeof(data_t)*blockSize); data_t* tempz = (data_t*) malloc(sizeof(data_t)*dx*dy*dzNext); data_t* tempyz = (data_t*) malloc(sizeof(data_t)*dx*dyNext*dzNext); data_t* tempxyz = (data_t*) malloc(sizeof(data_t)*blockSize); // Assign Filters scalar_t *lodx,*lody,*lodz,*hidx,*hidy,*hidz; lodx = plan->lod0; lody = plan->lod0; lodz = plan->lod0; hidx = plan->hid0; hidy = plan->hid0; hidz = plan->hid0; if (dir==0) { lodx = plan->lod1; hidx = plan->hid1; } if (dir==1) { lody = plan->lod1; hidy = plan->hid1; } if (dir==2) { lodz = plan->lod1; hidz = plan->hid1; } for (l = plan->numLevels; l >= 1; --l) { dxNext = plan->waveSizes[0 + 3*l]; dyNext = plan->waveSizes[1 + 3*l]; dzNext = plan->waveSizes[2 + 3*l]; blockSize = dxNext*dyNext*dzNext; HxLyLz = HxLyLz - 7*blockSize; data_t* LxHyLz = HxLyLz + blockSize; data_t* HxHyLz = LxHyLz + blockSize; data_t* LxLyHz = HxHyLz + blockSize; data_t* HxLyHz = LxLyHz + blockSize; data_t* LxHyHz = HxLyHz + blockSize; data_t* HxHyHz = LxHyHz + blockSize; int dxy = dx*dy; int newdz = (dz + plan->filterLen-1) / 2; int newdy = (dy + plan->filterLen-1) / 2; int newdxy = dx*newdy; // Lz conv_down_3d(tempz, inImage, dz, dxy, dx, 1, dy, dx, lodz,plan->filterLen); // LyLz conv_down_3d(tempyz, tempz, dy, dx, dx, 1, newdz, dxy, lody,plan->filterLen); conv_down_3d(LxLyLz, tempyz, dx, 1, newdy, dx, newdz, newdxy, lodx,plan->filterLen); conv_down_3d(HxLyLz, tempyz, dx, 1, newdy, dx, newdz, newdxy, hidx,plan->filterLen); // HyLz conv_down_3d(tempyz, tempz, dy, dx, dx, 1, newdz, dxy, hidy,plan->filterLen); conv_down_3d(LxHyLz, tempyz, dx, 1, newdy, dx, newdz, newdxy, lodx,plan->filterLen); conv_down_3d(HxHyLz, tempyz, dx, 1, newdy, dx, newdz, newdxy, hidx,plan->filterLen); // Hz conv_down_3d(tempz, inImage, dz, dxy, dx, 1, dy, dx, hidz,plan->filterLen); // LyHz conv_down_3d(tempyz, tempz, dy, dx, dx, 1, newdz, dxy, lody,plan->filterLen); conv_down_3d(LxLyHz, tempyz, dx, 1, newdy, dx, newdz, newdxy, lodx,plan->filterLen); conv_down_3d(HxLyHz, tempyz, dx, 1, newdy, dx, newdz, newdxy, hidx,plan->filterLen); // HyHz conv_down_3d(tempyz, tempz, dy, dx, dx, 1, newdz, dxy, hidy,plan->filterLen); conv_down_3d(LxHyHz, tempyz, dx, 1, newdy, dx, newdz, newdxy, lodx,plan->filterLen); conv_down_3d(HxHyHz, tempyz, dx, 1, newdy, dx, newdz, newdxy, hidx,plan->filterLen); memcpy(tempxyz, LxLyLz, blockSize*sizeof(data_t)); inImage = tempxyz; dx = dxNext; dy = dyNext; dz = dzNext; } // Final LxLyLz memcpy(coeff, inImage, plan->waveSizes[0]*plan->waveSizes[1]*plan->waveSizes[2]*sizeof(data_t)); free(LxLyLz); free(tempz); free(tempyz); free(tempxyz); circunshift_cpu(plan,origInImage); } void iwt3_cpu(struct dfwavelet_plan_s* plan, data_t* outImage, data_t* coeff,int dir) { // Workspace dimensions int dxWork = plan->waveSizes[0 + 3*plan->numLevels]*2-1 + plan->filterLen-1; int dyWork = plan->waveSizes[1 + 3*plan->numLevels]*2-1 + plan->filterLen-1; int dzWork = plan->waveSizes[2 + 3*plan->numLevels]*2-1 + plan->filterLen-1; int dyWork2 = plan->waveSizes[1 + 3*(plan->numLevels-1)]*2-1 + plan->filterLen-1; int dzWork2 = plan->waveSizes[2 + 3*(plan->numLevels-1)]*2-1 + plan->filterLen-1; // Workspace data_t* tempyz = (data_t*) malloc(sizeof(data_t)*dxWork*dyWork2*dzWork2); data_t* tempz = (data_t*) malloc(sizeof(data_t)*dxWork*dyWork*dzWork2); data_t* tempFull = (data_t*) malloc(sizeof(data_t)*dxWork*dyWork*dzWork); int dx = plan->waveSizes[0]; int dy = plan->waveSizes[1]; int dz = plan->waveSizes[2]; // Assign Filters scalar_t *lorx,*lory,*lorz,*hirx,*hiry,*hirz; lorx = plan->lor0; lory = plan->lor0; lorz = plan->lor0; hirx = plan->hir0; hiry = plan->hir0; hirz = plan->hir0; if (dir==0) { lorx = plan->lor1; hirx = plan->hir1; } if (dir==1) { lory = plan->lor1; hiry = plan->hir1; } if (dir==2) { lorz = plan->lor1; hirz = plan->hir1; } memcpy(outImage, coeff, dx*dy*dz*sizeof(data_t)); data_t* HxLyLz = coeff + dx*dy*dz; int level; for (level = 1; level < plan->numLevels+1; ++level) { dx = plan->waveSizes[0 + 3*level]; dy = plan->waveSizes[1 + 3*level]; dz = plan->waveSizes[2 + 3*level]; int blockSize = dx*dy*dz; data_t* LxHyLz = HxLyLz + blockSize; data_t* HxHyLz = LxHyLz + blockSize; data_t* LxLyHz = HxHyLz + blockSize; data_t* HxLyHz = LxLyHz + blockSize; data_t* LxHyHz = HxLyHz + blockSize; data_t* HxHyHz = LxHyHz + blockSize; data_t* LxLyLz = outImage; int newdx = 2*dx-1 + plan->filterLen-1; int newdy = 2*dy-1 + plan->filterLen-1; int newdz = 2*dz-1 + plan->filterLen-1; int dxy = dx*dy; int newdxy = newdx*dy; int newnewdxy = newdx*newdy; memset(tempFull, 0, newnewdxy*newdz*sizeof(data_t)); memset(tempz, 0, newnewdxy*dz*sizeof(data_t)); memset(tempyz, 0, newdxy*dz*sizeof(data_t)); conv_up_3d(tempyz, LxLyLz, dx, 1, dy, dx, dz, dxy, lorx,plan->filterLen); conv_up_3d(tempyz, HxLyLz, dx, 1, dy, dx, dz, dxy, hirx,plan->filterLen); conv_up_3d(tempz, tempyz, dy, newdx, newdx, 1, dz, newdxy, lory,plan->filterLen); memset(tempyz, 0, newdxy*dz*sizeof(data_t)); conv_up_3d(tempyz, LxHyLz, dx, 1, dy, dx, dz, dxy, lorx,plan->filterLen); conv_up_3d(tempyz, HxHyLz, dx, 1, dy, dx, dz, dxy, hirx,plan->filterLen); conv_up_3d(tempz, tempyz, dy, newdx, newdx, 1, dz, newdxy, hiry,plan->filterLen); conv_up_3d(tempFull, tempz, dz, newnewdxy, newdx, 1, newdy, newdx, lorz,plan->filterLen); memset(tempz, 0, newnewdxy*dz*sizeof(data_t)); memset(tempyz, 0, newdxy*dz*sizeof(data_t)); conv_up_3d(tempyz, LxLyHz, dx, 1, dy, dx, dz, dxy, lorx,plan->filterLen); conv_up_3d(tempyz, HxLyHz, dx, 1, dy, dx, dz, dxy, hirx,plan->filterLen); conv_up_3d(tempz, tempyz, dy, newdx, newdx, 1, dz, newdxy, lory,plan->filterLen); memset(tempyz, 0, newdxy*dz*sizeof(data_t)); conv_up_3d(tempyz, LxHyHz, dx, 1, dy, dx, dz, dxy, lorx,plan->filterLen); conv_up_3d(tempyz, HxHyHz, dx, 1, dy, dx, dz, dxy, hirx,plan->filterLen); conv_up_3d(tempz, tempyz, dy, newdx, newdx, 1, dz, newdxy, hiry,plan->filterLen); conv_up_3d(tempFull, tempz, dz, newnewdxy, newdx, 1, newdy, newdx, hirz,plan->filterLen); // Crop center of workspace int dxNext = plan->waveSizes[0+3*(level+1)]; int dyNext = plan->waveSizes[1+3*(level+1)]; int dzNext = plan->waveSizes[2+3*(level+1)]; int dxyNext = dxNext*dyNext; dxWork = (2*dx-1 + plan->filterLen-1); dyWork = (2*dy-1 + plan->filterLen-1); dzWork = (2*dz-1 + plan->filterLen-1); int dxyWork = dxWork*dyWork; int xOffset = (int) ((dxWork - dxNext) / 2.0); int yOffset = (int) ((dyWork - dyNext) / 2.0); int zOffset = (int) ((dzWork - dzNext) / 2.0); int k,j; for (k = 0; k < dzNext; ++k){ for (j = 0; j < dyNext; ++j){ memcpy(outImage+j*dxNext + k*dxyNext, tempFull+xOffset + (yOffset+j)*dxWork + (zOffset+k)*dxyWork, dxNext*sizeof(data_t)); } } HxLyLz += 7*blockSize; } free(tempyz); free(tempz); free(tempFull); circunshift_cpu(plan,outImage); } void circshift_cpu(struct dfwavelet_plan_s* plan, data_t *data) { if (plan->randshift) dfwavelet_new_randshift(plan); // Return if no shifts int zeroShift = 1; int i; for (i = 0; i< plan->numdims; i++) { zeroShift &= (plan->randShift[i]==0); } if(zeroShift) { return; } // Copy data data_t* dataCopy = malloc(sizeof(data_t)*plan->numPixel); memcpy(dataCopy, data, plan->numPixel*sizeof(data_t)); if (plan->numdims==2) { int dx,dy,r0,r1,j,i,index,indexShifted; dx = plan->imSize[0]; dy = plan->imSize[1]; r0 = plan->randShift[0]; r1 = plan->randShift[1]; #pragma omp parallel for private(index, j, i,indexShifted) for(j = 0; j < dy; j++) { for(i = 0; i < dx; i++) { index = i+j*dx; indexShifted = (((i+r0) + (j+r1)*dx)%(dx*dy)+dx*dy)%(dx*dy); data[indexShifted] = dataCopy[index]; } } } if (plan->numdims==3) { int dx,dy,dz,r0,r1,r2,k,j,i,index,indexShifted; dx = plan->imSize[0]; dy = plan->imSize[1]; dz = plan->imSize[2]; r0 = plan->randShift[0]; r1 = plan->randShift[1]; r2 = plan->randShift[2]; #pragma omp parallel for private(index, k, j, i,indexShifted) for (k = 0; k < dz; k++) { for(j = 0; j < dy; j++) { for(i = 0; i < dx; i++) { index = i+j*dx+k*dx*dy; indexShifted = ((i+r0 + (j+r1)*dx + (k+r2)*dx*dy)%(dx*dy*dz)+(dx*dy*dz))%(dx*dy*dz); data[indexShifted] = dataCopy[index]; } } } } #pragma omp barrier free(dataCopy); } void circunshift_cpu(struct dfwavelet_plan_s* plan, data_t *data) { // Return if no shifts int zeroShift = 1; int i; for (i = 0; i< plan->numdims; i++) { zeroShift &= (plan->randShift[i]==0); } if(zeroShift) { return; } // Copy data data_t* dataCopy = malloc(sizeof(data_t)*plan->numPixel); memcpy(dataCopy, data, plan->numPixel*sizeof(data_t)); if (plan->numdims==2) { int dx,dy,r0,r1,j,i,index,indexShifted; dx = plan->imSize[0]; dy = plan->imSize[1]; r0 = plan->randShift[0]; r1 = plan->randShift[1]; #pragma omp parallel for private(index, j, i,indexShifted) for(j = 0; j < dy; j++) { for(i = 0; i < dx; i++) { index = i+j*dx; indexShifted = (((i+r0) + (j+r1)*dx)%(dx*dy)+dx*dy)%(dx*dy); data[index] = dataCopy[indexShifted]; } } } if (plan->numdims==3) { int dx,dy,dz,r0,r1,r2,k,j,i,index,indexShifted; dx = plan->imSize[0]; dy = plan->imSize[1]; dz = plan->imSize[2]; r0 = plan->randShift[0]; r1 = plan->randShift[1]; r2 = plan->randShift[2]; #pragma omp parallel for private(index, k, j, i,indexShifted) for (k = 0; k < dz; k++) { for(j = 0; j < dy; j++) { for(i = 0; i < dx; i++) { index = i+j*dx+k*dx*dy; indexShifted = ((i+r0 + (j+r1)*dx + (k+r2)*dx*dy)%(dx*dy*dz)+(dx*dy*dz))%(dx*dy*dz); data[index] = dataCopy[indexShifted]; } } } } free(dataCopy); } /********** Helper Function *********/ void conv_down_3d(data_t *out, data_t *in, int size1, int skip1, int size2, int skip2, int size3, int skip3, scalar_t *filter, int filterLen) { int outSize1 = (size1 + filterLen-1) / 2; // Adjust out skip 2 and 3 if needed int outSkip2; if(skip2 > skip1) { outSkip2 = outSize1*skip2/size1; } else { outSkip2 = skip2; } int outSkip3; if(skip3 > skip1) { outSkip3 = outSize1*skip3/size1; } else { outSkip3 = skip3; } int i32; #pragma omp parallel for for (i32 = 0; i32 < size2*size3; ++i32) { int i2 = i32 % size2; int i3 = i32 / size2; int i1; for (i1 = 0; i1 < outSize1; ++i1) { out[i3*outSkip3 + i2*outSkip2 + i1*skip1] = 0.0f; int k; for (k = 0; k < filterLen; ++k) { int out_i1 = 2*i1+1 - (filterLen-1) + k; if (out_i1 < 0) out_i1 = -out_i1-1; if (out_i1 >= size1) out_i1 = size1-1 - (out_i1-size1); out[i3*outSkip3 + i2*outSkip2 + i1*skip1] += in[i3*skip3 + i2*skip2 + out_i1*skip1] * filter[filterLen-1-k]; } } } } void conv_up_3d(data_t *out, data_t *in, int size1, int skip1, int size2, int skip2, int size3, int skip3, scalar_t *filter, int filterLen) { int outSize1 = 2*size1-1 + filterLen-1; // Adjust out skip 2 and 3 if needed int outSkip2; if(skip2 > skip1) { outSkip2 = outSize1*skip2/size1; } else { outSkip2 = skip2; } int outSkip3; if(skip3 > skip1) { outSkip3 = outSize1*skip3/size1; } else { outSkip3 = skip3; } int i32; #pragma omp parallel for for (i32 = 0; i32 < size2*size3; ++i32) { int i2 = i32 % size2; int i3 = i32 / size2; int i1; for (i1 = 0; i1 < outSize1; ++i1) { int k; for (k = (i1 - (filterLen-1)) & 1; k < filterLen; k += 2){ int in_i1 = (i1 - (filterLen-1) + k) >> 1; if (in_i1 >= 0 && in_i1 < size1) out[i3*outSkip3 + i2*outSkip2 + i1*skip1] += in[i3*skip3 + i2*skip2 + in_i1*skip1] * filter[filterLen-1-k]; } } } } void mult(data_t* in,scalar_t scale,int numMax) { int i; for(i=0; i<numMax;i++) in[i]*=scale; } void create_numLevels(struct dfwavelet_plan_s* plan) { int numdims = plan->numdims; int filterLen = plan->filterLen; int bandSize, l, minSize; plan->numLevels = 10000000; int d; for (d = 0; d < numdims; d++) { bandSize = plan->imSize[d]; minSize = plan->minSize[d]; l = 0; while (bandSize > minSize) { ++l; bandSize = (bandSize + filterLen - 1) / 2; } l--; plan->numLevels = (l < plan->numLevels) ? l : plan->numLevels; } } void create_wavelet_sizes(struct dfwavelet_plan_s* plan) { int numdims = plan->numdims; int filterLen = plan->filterLen; int numLevels = plan->numLevels; int numSubCoef; plan->waveSizes = (long*) malloc(sizeof(long)*numdims*(numLevels+2)); // Get number of subband per level, (3 for 2d, 7 for 3d) // Set the last bandSize to be imSize int d,l; int numSubband = 1; for (d = 0; d<numdims; d++) { plan->waveSizes[d + numdims*(numLevels+1)] = plan->imSize[d]; numSubband <<= 1; } numSubband--; // Get numCoeff and waveSizes // Each bandSize[l] is (bandSize[l+1] + filterLen - 1)/2 plan->numCoeff = 0; for (l = plan->numLevels; l >= 1; --l) { numSubCoef = 1; for (d = 0; d < numdims; d++) { plan->waveSizes[d + numdims*l] = (plan->waveSizes[d + numdims*(l+1)] + filterLen - 1) / 2; numSubCoef *= plan->waveSizes[d + numdims*l]; } plan->numCoeff += numSubband*numSubCoef; if (l==1) plan->numCoarse = numSubCoef; } numSubCoef = 1; for (d = 0; d < numdims; d++) { plan->waveSizes[d] = plan->waveSizes[numdims+d]; numSubCoef *= plan->waveSizes[d]; } plan->numCoeff += numSubCoef; } /* All filter coefficients are obtained from http://wavelets.pybytes.com/ */ void create_wavelet_filters(struct dfwavelet_plan_s* plan) { int filterLen = 0; scalar_t* filter1, *filter2; filterLen = 6; // CDF 2.2 and CDF 3.1 Wavelet scalar_t cdf22[] = { 0.0,-0.17677669529663689,0.35355339059327379,1.0606601717798214,0.35355339059327379,-0.17677669529663689, 0.0,0.35355339059327379,-0.70710678118654757,0.35355339059327379,0.0,0.0, 0.0,0.35355339059327379,0.70710678118654757,0.35355339059327379,0.0,0.0, 0.0,0.17677669529663689,0.35355339059327379,-1.0606601717798214,0.35355339059327379,0.17677669529663689 }; scalar_t cdf31[] = { 0.0,-0.35355339059327379,1.0606601717798214,1.0606601717798214,-0.35355339059327379,0.0 , 0.0,-0.17677669529663689,0.53033008588991071,-0.53033008588991071,0.17677669529663689,0.0, 0.0,0.17677669529663689,0.53033008588991071,0.53033008588991071,0.17677669529663689,0.0, 0.0,-0.35355339059327379,-1.0606601717798214,1.0606601717798214,0.35355339059327379,0.0 }; filter1 = cdf22; filter2 = cdf31; // Allocate filters contiguously (for convenience) plan->filterLen = filterLen; plan->lod0 = (scalar_t*) malloc(sizeof(scalar_t) * 4 * filterLen); memcpy(plan->lod0, filter1, 4*filterLen*sizeof(scalar_t)); plan->lod1 = (scalar_t*) malloc(sizeof(scalar_t) * 4 * filterLen); memcpy(plan->lod1, filter2, 4*filterLen*sizeof(scalar_t)); plan->hid0 = plan->lod0 + 1*filterLen; plan->lor0 = plan->lod0 + 2*filterLen; plan->hir0 = plan->lod0 + 3*filterLen; plan->hid1 = plan->lod1 + 1*filterLen; plan->lor1 = plan->lod1 + 2*filterLen; plan->hir1 = plan->lod1 + 3*filterLen; } #ifndef M_PI #define M_PI 3.14159265358979323846 #endif static data_t drand() /* uniform distribution, (0..1] */ { return (rand()+1.0)/(RAND_MAX+1.0); } static void random_normal(data_t* in,int length) /* normal distribution, centered on 0, std dev 1 */ { int i; for (i=0;i<length;i++) in[i] = sqrt(-2*log(drand())) * cos(2*M_PI*drand()); } void get_noise_amp(struct dfwavelet_plan_s* plan) { if (plan->noiseAmp==NULL) { // Generate Gaussian w/ mean=0, std=1 data data_t* vx,*vy,*vz; data_t* wcdf1,*wcdf2,*wcn; vx = (data_t*) malloc(sizeof(data_t)*plan->numPixel); vy = (data_t*) malloc(sizeof(data_t)*plan->numPixel); vz = (data_t*) malloc(sizeof(data_t)*plan->numPixel); random_normal(vx,plan->numPixel); random_normal(vy,plan->numPixel); random_normal(vz,plan->numPixel); wcdf1 = (data_t*) malloc(sizeof(data_t)*plan->numCoeff); wcdf2 = (data_t*) malloc(sizeof(data_t)*plan->numCoeff); wcn = (data_t*) malloc(sizeof(data_t)*plan->numCoeff); // Get Wavelet Coefficients int temp_use_gpu = plan->use_gpu; if (plan->use_gpu==1) plan->use_gpu = 2; dfwavelet_forward(plan,wcdf1,wcdf2,wcn,vx,vy,vz); plan->use_gpu = temp_use_gpu; // Get Noise Amp for each subband data_t* HxLyLz1 = wcdf1 + plan->waveSizes[0]*plan->waveSizes[1]*plan->waveSizes[2]; data_t* HxLyLz2 = wcdf2 + plan->waveSizes[0]*plan->waveSizes[1]*plan->waveSizes[2]; data_t* HxLyLz3 = wcn + plan->waveSizes[0]*plan->waveSizes[1]*plan->waveSizes[2]; int l; for (l = 1; l <= plan->numLevels; ++l){ HxLyLz1 += 7*plan->waveSizes[0 + 3*l]*plan->waveSizes[1 + 3*l]*plan->waveSizes[2 + 3*l]; HxLyLz2 += 7*plan->waveSizes[0 + 3*l]*plan->waveSizes[1 + 3*l]*plan->waveSizes[2 + 3*l]; HxLyLz3 += 7*plan->waveSizes[0 + 3*l]*plan->waveSizes[1 + 3*l]*plan->waveSizes[2 + 3*l]; } int numBand = 7*plan->numLevels*3; plan->noiseAmp = (scalar_t*) malloc(sizeof(scalar_t)*numBand); int naInd = 0; for (l = plan->numLevels; l >= 1; --l) { int dxNext = plan->waveSizes[0 + 3*l]; int dyNext = plan->waveSizes[1 + 3*l]; int dzNext = plan->waveSizes[2 + 3*l]; int blockSize = dxNext*dyNext*dzNext; HxLyLz1 = HxLyLz1 - 7*blockSize; HxLyLz2 = HxLyLz2 - 7*blockSize; HxLyLz3 = HxLyLz3 - 7*blockSize; int bandInd; //#pragma omp parallel for private(bandInd) for (bandInd=0; bandInd<7*3;bandInd++) { data_t *subband; if (bandInd<7) { subband = HxLyLz1 + bandInd*blockSize; } else if (bandInd<14) { subband = HxLyLz2 + (bandInd-7)*blockSize; } else { subband = HxLyLz3 + (bandInd-14)*blockSize; } data_t sig = 0; data_t mean = 0; data_t mean_old; int i; for (i=0; i<blockSize; i++) { scalar_t x = subband[i]; mean_old = mean; mean = mean_old + (x-mean_old)/(i+1); sig = sig + (x - mean_old)*(x-mean); } sig = sqrt(sig/(blockSize-1)); plan->noiseAmp[naInd] = sig; naInd++; } } free(vx); free(vy); free(vz); free(wcdf1); free(wcdf2); free(wcn); } }
detector.c
#include "darknet.h" static int coco_ids[] = {1,2,3,4,5,6,7,8,9,10,11,13,14,15,16,17,18,19,20,21,22,23,24,25,27,28,31,32,33,34,35,36,37,38,39,40,41,42,43,44,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,67,70,72,73,74,75,76,77,78,79,80,81,82,84,85,86,87,88,89,90}; void train_detector(char *datacfg, char *cfgfile, char *weightfile, int *gpus, int ngpus, int clear) { list *options = read_data_cfg(datacfg); char *train_images = option_find_str(options, "train", "data/train.list"); char *backup_directory = option_find_str(options, "backup", "/backup/"); srand(time(0)); char *base = basecfg(cfgfile); printf("%s\n", base); float avg_loss = -1; network **nets = calloc(ngpus, sizeof(network)); srand(time(0)); int seed = rand(); int i; for(i = 0; i < ngpus; ++i){ srand(seed); #ifdef GPU cuda_set_device(gpus[i]); #endif nets[i] = load_network(cfgfile, weightfile, clear); nets[i]->learning_rate *= ngpus; } srand(time(0)); network *net = nets[0]; int imgs = net->batch * net->subdivisions * ngpus; printf("Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay); data train, buffer; layer l = net->layers[net->n - 1]; int classes = l.classes; float jitter = l.jitter; list *plist = get_paths(train_images); //int N = plist->size; char **paths = (char **)list_to_array(plist); load_args args = get_base_args(net); args.coords = l.coords; args.paths = paths; args.n = imgs; args.m = plist->size; args.classes = classes; args.jitter = jitter; args.num_boxes = l.max_boxes; args.d = &buffer; args.type = DETECTION_DATA; //args.type = INSTANCE_DATA; args.threads = 64; pthread_t load_thread = load_data(args); double time; int count = 0; //while(i*imgs < N*120){ while(get_current_batch(net) < net->max_batches){ if(l.random && count++%10 == 0){ printf("Resizing\n"); int dim = (rand() % 10 + 10) * 32; if (get_current_batch(net)+200 > net->max_batches) dim = 608; //int dim = (rand() % 4 + 16) * 32; printf("%d\n", dim); args.w = dim; args.h = dim; pthread_join(load_thread, 0); train = buffer; free_data(train); load_thread = load_data(args); #pragma omp parallel for for(i = 0; i < ngpus; ++i){ resize_network(nets[i], dim, dim); } net = nets[0]; } time=what_time_is_it_now(); pthread_join(load_thread, 0); train = buffer; load_thread = load_data(args); /* int k; for(k = 0; k < l.max_boxes; ++k){ box b = float_to_box(train.y.vals[10] + 1 + k*5); if(!b.x) break; printf("loaded: %f %f %f %f\n", b.x, b.y, b.w, b.h); } */ /* int zz; for(zz = 0; zz < train.X.cols; ++zz){ image im = float_to_image(net->w, net->h, 3, train.X.vals[zz]); int k; for(k = 0; k < l.max_boxes; ++k){ box b = float_to_box(train.y.vals[zz] + k*5, 1); printf("%f %f %f %f\n", b.x, b.y, b.w, b.h); draw_bbox(im, b, 1, 1,0,0); } show_image(im, "truth11"); cvWaitKey(0); save_image(im, "truth11"); } */ printf("Loaded: %lf seconds\n", what_time_is_it_now()-time); time=what_time_is_it_now(); float loss = 0; #ifdef GPU if(ngpus == 1){ loss = train_network(net, train); } else { loss = train_networks(nets, ngpus, train, 4); } #else loss = train_network(net, train); #endif if (avg_loss < 0) avg_loss = loss; avg_loss = avg_loss*.9 + loss*.1; i = get_current_batch(net); printf("%ld: %f, %f avg, %f rate, %lf seconds, %d images\n", get_current_batch(net), loss, avg_loss, get_current_rate(net), what_time_is_it_now()-time, i*imgs); if(i%100==0){ #ifdef GPU if(ngpus != 1) sync_nets(nets, ngpus, 0); #endif char buff[256]; sprintf(buff, "%s/%s.backup", backup_directory, base); save_weights(net, buff); } if(i%10000==0 || (i < 1000 && i%100 == 0)){ #ifdef GPU if(ngpus != 1) sync_nets(nets, ngpus, 0); #endif char buff[256]; sprintf(buff, "%s/%s_%d.weights", backup_directory, base, i); save_weights(net, buff); } free_data(train); } #ifdef GPU if(ngpus != 1) sync_nets(nets, ngpus, 0); #endif char buff[256]; sprintf(buff, "%s/%s_final.weights", backup_directory, base); save_weights(net, buff); } static int get_coco_image_id(char *filename) { char *p = strrchr(filename, '/'); char *c = strrchr(filename, '_'); if(c) p = c; return atoi(p+1); } static void print_cocos(FILE *fp, char *image_path, detection *dets, int num_boxes, int classes, int w, int h) { int i, j; int image_id = get_coco_image_id(image_path); for(i = 0; i < num_boxes; ++i){ float xmin = dets[i].bbox.x - dets[i].bbox.w/2.; float xmax = dets[i].bbox.x + dets[i].bbox.w/2.; float ymin = dets[i].bbox.y - dets[i].bbox.h/2.; float ymax = dets[i].bbox.y + dets[i].bbox.h/2.; if (xmin < 0) xmin = 0; if (ymin < 0) ymin = 0; if (xmax > w) xmax = w; if (ymax > h) ymax = h; float bx = xmin; float by = ymin; float bw = xmax - xmin; float bh = ymax - ymin; for(j = 0; j < classes; ++j){ if (dets[i].prob[j]) fprintf(fp, "{\"image_id\":%d, \"category_id\":%d, \"bbox\":[%f, %f, %f, %f], \"score\":%f},\n", image_id, coco_ids[j], bx, by, bw, bh, dets[i].prob[j]); } } } void print_detector_detections(FILE **fps, char *id, detection *dets, int total, int classes, int w, int h) { int i, j; for(i = 0; i < total; ++i){ float xmin = dets[i].bbox.x - dets[i].bbox.w/2. + 1; float xmax = dets[i].bbox.x + dets[i].bbox.w/2. + 1; float ymin = dets[i].bbox.y - dets[i].bbox.h/2. + 1; float ymax = dets[i].bbox.y + dets[i].bbox.h/2. + 1; if (xmin < 1) xmin = 1; if (ymin < 1) ymin = 1; if (xmax > w) xmax = w; if (ymax > h) ymax = h; for(j = 0; j < classes; ++j){ if (dets[i].prob[j]){ fprintf(fps[j], "%s %f %f %f %f %f\n", id, dets[i].prob[j], xmin, ymin, xmax, ymax); } printf( "%s %f %f %f %f %f\n", id, dets[i].prob[j], xmin, ymin, xmax, ymax); } } } void print_imagenet_detections(FILE *fp, int id, detection *dets, int total, int classes, int w, int h) { int i, j; for(i = 0; i < total; ++i){ float xmin = dets[i].bbox.x - dets[i].bbox.w/2.; float xmax = dets[i].bbox.x + dets[i].bbox.w/2.; float ymin = dets[i].bbox.y - dets[i].bbox.h/2.; float ymax = dets[i].bbox.y + dets[i].bbox.h/2.; if (xmin < 0) xmin = 0; if (ymin < 0) ymin = 0; if (xmax > w) xmax = w; if (ymax > h) ymax = h; for(j = 0; j < classes; ++j){ int class = j; if (dets[i].prob[class]) fprintf(fp, "%d %d %f %f %f %f %f\n", id, j+1, dets[i].prob[class], xmin, ymin, xmax, ymax); } } } void validate_detector_flip(char *datacfg, char *cfgfile, char *weightfile, char *outfile) { int j; list *options = read_data_cfg(datacfg); char *valid_images = option_find_str(options, "valid", "data/train.list"); char *name_list = option_find_str(options, "names", "data/names.list"); char *prefix = option_find_str(options, "results", "results"); char **names = get_labels(name_list); char *mapf = option_find_str(options, "map", 0); int *map = 0; if (mapf) map = read_map(mapf); network *net = load_network(cfgfile, weightfile, 0); set_batch_network(net, 2); fprintf(stderr, "Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay); srand(time(0)); list *plist = get_paths(valid_images); char **paths = (char **)list_to_array(plist); layer l = net->layers[net->n-1]; int classes = l.classes; char buff[1024]; char *type = option_find_str(options, "eval", "voc"); FILE *fp = 0; FILE **fps = 0; int coco = 0; int imagenet = 0; if(0==strcmp(type, "coco")){ if(!outfile) outfile = "coco_results"; snprintf(buff, 1024, "%s/%s.json", prefix, outfile); fp = fopen(buff, "w"); fprintf(fp, "[\n"); coco = 1; } else if(0==strcmp(type, "imagenet")){ if(!outfile) outfile = "imagenet-detection"; snprintf(buff, 1024, "%s/%s.txt", prefix, outfile); fp = fopen(buff, "w"); imagenet = 1; classes = 200; } else { if(!outfile) outfile = "comp4_det_test_"; fps = calloc(classes, sizeof(FILE *)); for(j = 0; j < classes; ++j){ snprintf(buff, 1024, "%s/%s%s.txt", prefix, outfile, names[j]); fps[j] = fopen(buff, "w"); } } int m = plist->size; int i=0; int t; float thresh = .005; float nms = .45; int nthreads = 4; image *val = calloc(nthreads, sizeof(image)); image *val_resized = calloc(nthreads, sizeof(image)); image *buf = calloc(nthreads, sizeof(image)); image *buf_resized = calloc(nthreads, sizeof(image)); pthread_t *thr = calloc(nthreads, sizeof(pthread_t)); image input = make_image(net->w, net->h, net->c*2); load_args args = {0}; args.w = net->w; args.h = net->h; //args.type = IMAGE_DATA; args.type = LETTERBOX_DATA; for(t = 0; t < nthreads; ++t){ args.path = paths[i+t]; args.im = &buf[t]; args.resized = &buf_resized[t]; thr[t] = load_data_in_thread(args); } double start = what_time_is_it_now(); for(i = nthreads; i < m+nthreads; i += nthreads){ fprintf(stderr, "%d\n", i); for(t = 0; t < nthreads && i+t-nthreads < m; ++t){ pthread_join(thr[t], 0); val[t] = buf[t]; val_resized[t] = buf_resized[t]; } for(t = 0; t < nthreads && i+t < m; ++t){ args.path = paths[i+t]; args.im = &buf[t]; args.resized = &buf_resized[t]; thr[t] = load_data_in_thread(args); } for(t = 0; t < nthreads && i+t-nthreads < m; ++t){ char *path = paths[i+t-nthreads]; char *id = basecfg(path); copy_cpu(net->w*net->h*net->c, val_resized[t].data, 1, input.data, 1); flip_image(val_resized[t]); copy_cpu(net->w*net->h*net->c, val_resized[t].data, 1, input.data + net->w*net->h*net->c, 1); network_predict(net, input.data); int w = val[t].w; int h = val[t].h; int num = 0; detection *dets = get_network_boxes(net, w, h, thresh, .5, map, 0, &num); if (nms) do_nms_sort(dets, num, classes, nms); if (coco){ print_cocos(fp, path, dets, num, classes, w, h); } else if (imagenet){ print_imagenet_detections(fp, i+t-nthreads+1, dets, num, classes, w, h); } else { print_detector_detections(fps, id, dets, num, classes, w, h); } free_detections(dets, num); free(id); free_image(val[t]); free_image(val_resized[t]); } } for(j = 0; j < classes; ++j){ if(fps) fclose(fps[j]); } if(coco){ fseek(fp, -2, SEEK_CUR); fprintf(fp, "\n]\n"); fclose(fp); } fprintf(stderr, "Total Detection Time: %f Seconds\n", what_time_is_it_now() - start); } void validate_detector(char *datacfg, char *cfgfile, char *weightfile, char *outfile) { int j; list *options = read_data_cfg(datacfg); char *valid_images = option_find_str(options, "valid", "data/train.list"); char *name_list = option_find_str(options, "names", "data/names.list"); char *prefix = option_find_str(options, "results", "results"); char **names = get_labels(name_list); char *mapf = option_find_str(options, "map", 0); int *map = 0; if (mapf) map = read_map(mapf); network *net = load_network(cfgfile, weightfile, 0); set_batch_network(net, 1); fprintf(stderr, "Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay); srand(time(0)); list *plist = get_paths(valid_images); char **paths = (char **)list_to_array(plist); layer l = net->layers[net->n-1]; int classes = l.classes; char buff[1024]; char *type = option_find_str(options, "eval", "voc"); FILE *fp = 0; FILE **fps = 0; int coco = 0; int imagenet = 0; if(0==strcmp(type, "coco")){ if(!outfile) outfile = "coco_results"; snprintf(buff, 1024, "%s/%s.json", prefix, outfile); fp = fopen(buff, "w"); fprintf(fp, "[\n"); coco = 1; } else if(0==strcmp(type, "imagenet")){ if(!outfile) outfile = "imagenet-detection"; snprintf(buff, 1024, "%s/%s.txt", prefix, outfile); fp = fopen(buff, "w"); imagenet = 1; classes = 200; } else { if(!outfile) outfile = "comp4_det_test_"; fps = calloc(classes, sizeof(FILE *)); for(j = 0; j < classes; ++j){ snprintf(buff, 1024, "%s/%s%s.txt", prefix, outfile, names[j]); fps[j] = fopen(buff, "w"); } } int m = plist->size; int i=0; int t; float thresh = .005; float nms = .45; int nthreads = 4; image *val = calloc(nthreads, sizeof(image)); image *val_resized = calloc(nthreads, sizeof(image)); image *buf = calloc(nthreads, sizeof(image)); image *buf_resized = calloc(nthreads, sizeof(image)); pthread_t *thr = calloc(nthreads, sizeof(pthread_t)); load_args args = {0}; args.w = net->w; args.h = net->h; //args.type = IMAGE_DATA; args.type = LETTERBOX_DATA; for(t = 0; t < nthreads; ++t){ args.path = paths[i+t]; args.im = &buf[t]; args.resized = &buf_resized[t]; thr[t] = load_data_in_thread(args); } double start = what_time_is_it_now(); for(i = nthreads; i < m+nthreads; i += nthreads){ fprintf(stderr, "%d\n", i); for(t = 0; t < nthreads && i+t-nthreads < m; ++t){ pthread_join(thr[t], 0); val[t] = buf[t]; val_resized[t] = buf_resized[t]; } for(t = 0; t < nthreads && i+t < m; ++t){ args.path = paths[i+t]; args.im = &buf[t]; args.resized = &buf_resized[t]; thr[t] = load_data_in_thread(args); } for(t = 0; t < nthreads && i+t-nthreads < m; ++t){ char *path = paths[i+t-nthreads]; char *id = basecfg(path); float *X = val_resized[t].data; network_predict(net, X); int w = val[t].w; int h = val[t].h; int nboxes = 0; detection *dets = get_network_boxes(net, w, h, thresh, .5, map, 0, &nboxes); if (nms) do_nms_sort(dets, nboxes, classes, nms); if (coco){ print_cocos(fp, path, dets, nboxes, classes, w, h); } else if (imagenet){ print_imagenet_detections(fp, i+t-nthreads+1, dets, nboxes, classes, w, h); } else { print_detector_detections(fps, id, dets, nboxes, classes, w, h); } free_detections(dets, nboxes); free(id); free_image(val[t]); free_image(val_resized[t]); } } for(j = 0; j < classes; ++j){ if(fps) fclose(fps[j]); } if(coco){ fseek(fp, -2, SEEK_CUR); fprintf(fp, "\n]\n"); fclose(fp); } fprintf(stderr, "Total Detection Time: %f Seconds\n", what_time_is_it_now() - start); } void validate_detector_recall(char *cfgfile, char *weightfile) { network *net = load_network(cfgfile, weightfile, 0); set_batch_network(net, 1); fprintf(stderr, "Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay); srand(time(0)); list *plist = get_paths("data/coco_val_5k.list"); char **paths = (char **)list_to_array(plist); layer l = net->layers[net->n-1]; int j, k; int m = plist->size; int i=0; float thresh = .001; float iou_thresh = .5; float nms = .4; int total = 0; int correct = 0; int proposals = 0; float avg_iou = 0; for(i = 0; i < m; ++i){ char *path = paths[i]; image orig = load_image_color(path, 0, 0); image sized = resize_image(orig, net->w, net->h); char *id = basecfg(path); network_predict(net, sized.data); int nboxes = 0; detection *dets = get_network_boxes(net, sized.w, sized.h, thresh, .5, 0, 1, &nboxes); if (nms) do_nms_obj(dets, nboxes, 1, nms); char labelpath[4096]; find_replace(path, "images", "labels", labelpath); find_replace(labelpath, "JPEGImages", "labels", labelpath); find_replace(labelpath, ".jpg", ".txt", labelpath); find_replace(labelpath, ".JPEG", ".txt", labelpath); int num_labels = 0; box_label *truth = read_boxes(labelpath, &num_labels); for(k = 0; k < nboxes; ++k){ if(dets[k].objectness > thresh){ ++proposals; } } for (j = 0; j < num_labels; ++j) { ++total; box t = {truth[j].x, truth[j].y, truth[j].w, truth[j].h}; float best_iou = 0; for(k = 0; k < l.w*l.h*l.n; ++k){ float iou = box_iou(dets[k].bbox, t); if(dets[k].objectness > thresh && iou > best_iou){ best_iou = iou; } } avg_iou += best_iou; if(best_iou > iou_thresh){ ++correct; } } fprintf(stderr, "%5d %5d %5d\tRPs/Img: %.2f\tIOU: %.2f%%\tRecall:%.2f%%\n", i, correct, total, (float)proposals/(i+1), avg_iou*100/total, 100.*correct/total); free(id); free_image(orig); free_image(sized); } } void test_detector(char *datacfg, char *cfgfile, char *weightfile, char *filename, float thresh, float hier_thresh, char *outfile, int fullscreen) { list *options = read_data_cfg(datacfg); char *name_list = option_find_str(options, "names", "data/names.list"); char **names = get_labels(name_list); image **alphabet = load_alphabet(); network *net = load_network(cfgfile, weightfile, 0); set_batch_network(net, 1); srand(2222222); double time; char buff[256]; char *input = buff; float nms=.45; while(1){ if(filename){ strncpy(input, filename, 256); } else { printf("Enter Image Path: "); fflush(stdout); input = fgets(input, 256, stdin); if(!input) return; strtok(input, "\n"); } image im = load_image_color(input,0,0); image sized = letterbox_image(im, net->w, net->h); save_image(sized, "image_sized"); //image sized = resize_image(im, net->w, net->h); //image sized2 = resize_max(im, net->w); //image sized = crop_image(sized2, -((net->w - sized2.w)/2), -((net->h - sized2.h)/2), net->w, net->h); //resize_network(net, sized.w, sized.h); layer l = net->layers[net->n-1]; printf("input should be%d, %d\n", net->h, net->w); float *X = sized.data; FILE* bufffil = fopen("dknet_buffer", "w"); for(int i =0;i<1248; i++){ for(int j =0;j<1248; j++){ fprintf(bufffil, "%d,%d,%f\n", i, j,X[i]); } } printf("%f\n", X[(1248 * 1248) - 1]); fclose(bufffil); printf("wrote buffer\n"); time=what_time_is_it_now(); network_predict(net, X); printf("%s: Predicted in %f seconds.\n", input, what_time_is_it_now()-time); int nboxes = 0; detection *dets = get_network_boxes(net, im.w, im.h, thresh, hier_thresh, 0, 1, &nboxes); printf("%d\n", nboxes); //if (nms) do_nms_obj(boxes, probs, l.w*l.h*l.n, l.classes, nms); if (nms) do_nms_sort(dets, nboxes, l.classes, nms); draw_detections(im, dets, nboxes, thresh, names, alphabet, l.classes); free_detections(dets, nboxes); if(outfile){ save_image(im, outfile); } else{ save_image(im, "predictions"); #ifdef OPENCV make_window("predictions", 512, 512, 0); show_image(im, "predictions", 0); #endif } free_image(im); free_image(sized); if (filename) break; } } /* void censor_detector(char *datacfg, char *cfgfile, char *weightfile, int cam_index, const char *filename, int class, float thresh, int skip) { #ifdef OPENCV char *base = basecfg(cfgfile); network *net = load_network(cfgfile, weightfile, 0); set_batch_network(net, 1); srand(2222222); CvCapture * cap; int w = 1280; int h = 720; if(filename){ cap = cvCaptureFromFile(filename); }else{ cap = cvCaptureFromCAM(cam_index); } if(w){ cvSetCaptureProperty(cap, CV_CAP_PROP_FRAME_WIDTH, w); } if(h){ cvSetCaptureProperty(cap, CV_CAP_PROP_FRAME_HEIGHT, h); } if(!cap) error("Couldn't connect to webcam.\n"); cvNamedWindow(base, CV_WINDOW_NORMAL); cvResizeWindow(base, 512, 512); float fps = 0; int i; float nms = .45; while(1){ image in = get_image_from_stream(cap); //image in_s = resize_image(in, net->w, net->h); image in_s = letterbox_image(in, net->w, net->h); layer l = net->layers[net->n-1]; float *X = in_s.data; network_predict(net, X); int nboxes = 0; detection *dets = get_network_boxes(net, in.w, in.h, thresh, 0, 0, 0, &nboxes); //if (nms) do_nms_obj(boxes, probs, l.w*l.h*l.n, l.classes, nms); if (nms) do_nms_sort(dets, nboxes, l.classes, nms); for(i = 0; i < nboxes; ++i){ if(dets[i].prob[class] > thresh){ box b = dets[i].bbox; int left = b.x-b.w/2.; int top = b.y-b.h/2.; censor_image(in, left, top, b.w, b.h); } } show_image(in, base); cvWaitKey(10); free_detections(dets, nboxes); free_image(in_s); free_image(in); float curr = 0; fps = .9*fps + .1*curr; for(i = 0; i < skip; ++i){ image in = get_image_from_stream(cap); free_image(in); } } #endif } void extract_detector(char *datacfg, char *cfgfile, char *weightfile, int cam_index, const char *filename, int class, float thresh, int skip) { #ifdef OPENCV char *base = basecfg(cfgfile); network *net = load_network(cfgfile, weightfile, 0); set_batch_network(net, 1); srand(2222222); CvCapture * cap; int w = 1280; int h = 720; if(filename){ cap = cvCaptureFromFile(filename); }else{ cap = cvCaptureFromCAM(cam_index); } if(w){ cvSetCaptureProperty(cap, CV_CAP_PROP_FRAME_WIDTH, w); } if(h){ cvSetCaptureProperty(cap, CV_CAP_PROP_FRAME_HEIGHT, h); } if(!cap) error("Couldn't connect to webcam.\n"); cvNamedWindow(base, CV_WINDOW_NORMAL); cvResizeWindow(base, 512, 512); float fps = 0; int i; int count = 0; float nms = .45; while(1){ image in = get_image_from_stream(cap); //image in_s = resize_image(in, net->w, net->h); image in_s = letterbox_image(in, net->w, net->h); layer l = net->layers[net->n-1]; show_image(in, base); int nboxes = 0; float *X = in_s.data; network_predict(net, X); detection *dets = get_network_boxes(net, in.w, in.h, thresh, 0, 0, 1, &nboxes); //if (nms) do_nms_obj(boxes, probs, l.w*l.h*l.n, l.classes, nms); if (nms) do_nms_sort(dets, nboxes, l.classes, nms); for(i = 0; i < nboxes; ++i){ if(dets[i].prob[class] > thresh){ box b = dets[i].bbox; int size = b.w*in.w > b.h*in.h ? b.w*in.w : b.h*in.h; int dx = b.x*in.w-size/2.; int dy = b.y*in.h-size/2.; image bim = crop_image(in, dx, dy, size, size); char buff[2048]; sprintf(buff, "results/extract/%07d", count); ++count; save_image(bim, buff); free_image(bim); } } free_detections(dets, nboxes); free_image(in_s); free_image(in); float curr = 0; fps = .9*fps + .1*curr; for(i = 0; i < skip; ++i){ image in = get_image_from_stream(cap); free_image(in); } } #endif } */ /* void network_detect(network *net, image im, float thresh, float hier_thresh, float nms, detection *dets) { network_predict_image(net, im); layer l = net->layers[net->n-1]; int nboxes = num_boxes(net); fill_network_boxes(net, im.w, im.h, thresh, hier_thresh, 0, 0, dets); if (nms) do_nms_sort(dets, nboxes, l.classes, nms); } */ void run_detector(int argc, char **argv) { char *prefix = find_char_arg(argc, argv, "-prefix", 0); float thresh = find_float_arg(argc, argv, "-thresh", .5); float hier_thresh = find_float_arg(argc, argv, "-hier", .5); int cam_index = find_int_arg(argc, argv, "-c", 0); int frame_skip = find_int_arg(argc, argv, "-s", 0); int avg = find_int_arg(argc, argv, "-avg", 3); if(argc < 4){ fprintf(stderr, "usage: %s %s [train/test/valid] [cfg] [weights (optional)]\n", argv[0], argv[1]); return; } char *gpu_list = find_char_arg(argc, argv, "-gpus", 0); char *outfile = find_char_arg(argc, argv, "-out", 0); int *gpus = 0; int gpu = 0; int ngpus = 0; if(gpu_list){ printf("%s\n", gpu_list); int len = strlen(gpu_list); ngpus = 1; int i; for(i = 0; i < len; ++i){ if (gpu_list[i] == ',') ++ngpus; } gpus = calloc(ngpus, sizeof(int)); for(i = 0; i < ngpus; ++i){ gpus[i] = atoi(gpu_list); gpu_list = strchr(gpu_list, ',')+1; } } else { gpu = gpu_index; gpus = &gpu; ngpus = 1; } int clear = find_arg(argc, argv, "-clear"); int fullscreen = find_arg(argc, argv, "-fullscreen"); int width = find_int_arg(argc, argv, "-w", 0); int height = find_int_arg(argc, argv, "-h", 0); int fps = find_int_arg(argc, argv, "-fps", 0); //int class = find_int_arg(argc, argv, "-class", 0); char *datacfg = argv[3]; char *cfg = argv[4]; char *weights = (argc > 5) ? argv[5] : 0; char *filename = (argc > 6) ? argv[6]: 0; if(0==strcmp(argv[2], "test")) test_detector(datacfg, cfg, weights, filename, thresh, hier_thresh, outfile, fullscreen); else if(0==strcmp(argv[2], "train")) train_detector(datacfg, cfg, weights, gpus, ngpus, clear); else if(0==strcmp(argv[2], "valid")) validate_detector(datacfg, cfg, weights, outfile); else if(0==strcmp(argv[2], "valid2")) validate_detector_flip(datacfg, cfg, weights, outfile); else if(0==strcmp(argv[2], "recall")) validate_detector_recall(cfg, weights); else if(0==strcmp(argv[2], "demo")) { list *options = read_data_cfg(datacfg); int classes = option_find_int(options, "classes", 20); char *name_list = option_find_str(options, "names", "data/names.list"); char **names = get_labels(name_list); demo(cfg, weights, thresh, cam_index, filename, names, classes, frame_skip, prefix, avg, hier_thresh, width, height, fps, fullscreen); } //else if(0==strcmp(argv[2], "extract")) extract_detector(datacfg, cfg, weights, cam_index, filename, class, thresh, frame_skip); //else if(0==strcmp(argv[2], "censor")) censor_detector(datacfg, cfg, weights, cam_index, filename, class, thresh, frame_skip); }
mpncflint.c
/* $Header$ */ /* mpncflint -- netCDF file interpolator */ /* Purpose: Linearly interpolate a third netCDF file from two input files */ /* Copyright (C) 1995--present Charlie Zender This file is part of NCO, the netCDF Operators. NCO is free software. You may redistribute and/or modify NCO under the terms of the 3-Clause BSD License. You are permitted to link NCO with the HDF, netCDF, OPeNDAP, and UDUnits libraries and to distribute the resulting executables under the terms of the BSD, but in addition obeying the extra stipulations of the HDF, netCDF, OPeNDAP, and UDUnits licenses. This program 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 3-Clause BSD License for more details. The original author of this software, Charlie Zender, seeks to improve it with your suggestions, contributions, bug-reports, and patches. Please contact the NCO project at http://nco.sf.net or write to Charlie Zender Department of Earth System Science University of California, Irvine Irvine, CA 92697-3100 */ /* Usage: ncflint -O -D 2 in.nc in.nc ~/foo.nc ncflint -O -i lcl_time_hr,9.0 -v lcl_time_hr /data/zender/arese/clm/951030_0800_arese_clm.nc /data/zender/arese/clm/951030_1100_arese_clm.nc ~/foo.nc; ncks -H foo.nc ncflint -O -w 0.66666,0.33333 -v lcl_time_hr /data/zender/arese/clm/951030_0800_arese_clm.nc /data/zender/arese/clm/951030_1100_arese_clm.nc ~/foo.nc; ncks -H foo.nc ncflint -O -w 0.66666 -v lcl_time_hr /data/zender/arese/clm/951030_0800_arese_clm.nc /data/zender/arese/clm/951030_1100_arese_clm.nc ~/foo.nc; ncks -H foo.nc ncdiff -O foo.nc /data/zender/arese/clm/951030_0900_arese_clm.nc foo2.nc;ncks -H foo2.nc | m */ #ifdef HAVE_CONFIG_H # include <config.h> /* Autotools tokens */ #endif /* !HAVE_CONFIG_H */ /* Standard C headers */ #include <math.h> /* sin cos cos sin 3.14159 */ #include <stdio.h> /* stderr, FILE, NULL, etc. */ #include <stdlib.h> /* atof, atoi, malloc, getopt */ #include <string.h> /* strcmp() */ #include <sys/stat.h> /* stat() */ #include <time.h> /* machine time */ #include <unistd.h> /* POSIX stuff */ #ifndef HAVE_GETOPT_LONG # include "nco_getopt.h" #else /* HAVE_GETOPT_LONG */ # ifdef HAVE_GETOPT_H # include <getopt.h> # endif /* !HAVE_GETOPT_H */ #endif /* HAVE_GETOPT_LONG */ /* 3rd party vendors */ #ifdef ENABLE_MPI #include <mpi.h> /* MPI definitions */ #include "nco_mpi.h" /* MPI utilities */ #endif /* !ENABLE_MPI */ #include <netcdf.h> /* netCDF definitions and C library */ /* #define MAIN_PROGRAM_FILE MUST precede #include libnco.h */ #define MAIN_PROGRAM_FILE #include "libnco.h" /* netCDF Operator (NCO) library */ int main(int argc,char **argv) { char **fl_lst_abb=NULL; /* Option a */ char **fl_lst_in; char **gaa_arg=NULL; /* [sng] Global attribute arguments */ char **ntp_lst_in; char **var_lst_in=NULL_CEWI; char *aux_arg[NC_MAX_DIMS]; char *cmd_ln; char *cnk_arg[NC_MAX_DIMS]; char *cnk_map_sng=NULL_CEWI; /* [sng] Chunking map */ char *cnk_plc_sng=NULL_CEWI; /* [sng] Chunking policy */ char *fl_in_1=NULL; /* fl_in_1 is nco_realloc'd when not NULL */ char *fl_in_2=NULL; /* fl_in_2 is nco_realloc'd when not NULL */ char *fl_out=NULL; /* Option o */ char *fl_out_tmp=NULL; /* MPI CEWI */ char *fl_pth=NULL; /* Option p */ char *fl_pth_lcl=NULL; /* Option l */ char *lmt_arg[NC_MAX_DIMS]; char *ntp_nm=NULL; /* Option i */ char *opt_crr=NULL; /* [sng] String representation of current long-option name */ char *optarg_lcl=NULL; /* [sng] Local copy of system optarg */ char *sng_cnv_rcd=NULL_CEWI; /* [sng] strtol()/strtoul() return code */ const char * const CVS_Id="$Id$"; const char * const CVS_Revision="$Revision$"; const char * const opt_sht_lst="34567ACcD:d:Fhi:L:l:Oo:p:rRSt:v:xw:-:"; cnk_dmn_sct **cnk_dmn=NULL_CEWI; dmn_sct **dim; dmn_sct **dmn_out; double ntp_val_out=double_CEWI; /* Option i */ double wgt_val_1=0.5; /* Option w */ double wgt_val_2=0.5; /* Option w */ extern char *optarg; extern int optind; /* Using naked stdin/stdout/stderr in parallel region generates warning Copy appropriate filehandle to variable scoped shared in parallel clause */ FILE * const fp_stderr=stderr; /* [fl] stderr filehandle CEWI */ FILE * const fp_stdout=stdout; /* [fl] stdout filehandle CEWI */ int *in_id_1_arr; int *in_id_2_arr; int abb_arg_nbr=0; int aux_nbr=0; /* [nbr] Number of auxiliary coordinate hyperslabs specified */ int cnk_map=nco_cnk_map_nil; /* [enm] Chunking map */ int cnk_nbr=0; /* [nbr] Number of chunk sizes */ int cnk_plc=nco_cnk_plc_nil; /* [enm] Chunking policy */ int dfl_lvl=NCO_DFL_LVL_UNDEFINED; /* [enm] Deflate level */ int fl_idx; int fl_nbr=0; int fl_in_fmt_1; /* [enm] Input file format */ int fl_in_fmt_2; /* [enm] Input file format */ int fl_out_fmt=NCO_FORMAT_UNDEFINED; /* [enm] Output file format */ int fll_md_old; /* [enm] Old fill mode */ int gaa_nbr=0; /* [nbr] Number of global attributes to add */ int has_mss_val=False; int idx; int jdx; int in_id_1; int in_id_2; int lmt_nbr=0; /* Option d. NB: lmt_nbr gets incremented */ int log_lvl=0; /* [enm] netCDF library debugging verbosity [0..5] */ int md_open; /* [enm] Mode flag for nc_open() call */ int nbr_dmn_fl; int nbr_dmn_xtr; int nbr_ntp; int nbr_var_fix; /* nbr_var_fix gets incremented */ int nbr_var_fl; int nbr_var_prc; /* nbr_var_prc gets incremented */ int xtr_nbr=0; /* xtr_nbr won't otherwise be set for -c with no -v */ int opt; int out_id; int rcd=NC_NOERR; /* [rcd] Return code */ int thr_idx; /* [idx] Index of current thread */ int thr_nbr=int_CEWI; /* [nbr] Thread number Option t */ int var_lst_in_nbr=0; lmt_sct **aux=NULL_CEWI; /* Auxiliary coordinate limits */ lmt_sct **lmt; lmt_all_sct **lmt_all_lst; /* List of *lmt_all structures */ cnv_sct *cnv; /* [sct] Convention structure */ nco_bool CMD_LN_NTP_VAR=False; /* Option i */ nco_bool CMD_LN_NTP_WGT=True; /* Option w */ nco_bool DO_CONFORM=False; /* Did nco_var_cnf_dmn() find truly conforming variables? */ nco_bool EXCLUDE_INPUT_LIST=False; /* Option c */ nco_bool EXTRACT_ALL_COORDINATES=False; /* Option c */ nco_bool EXTRACT_ASSOCIATED_COORDINATES=True; /* Option C */ nco_bool FILE_1_RETRIEVED_FROM_REMOTE_LOCATION; nco_bool FILE_2_RETRIEVED_FROM_REMOTE_LOCATION; nco_bool FL_LST_IN_FROM_STDIN=False; /* [flg] fl_lst_in comes from stdin */ nco_bool FORCE_APPEND=False; /* Option A */ nco_bool FORCE_OVERWRITE=False; /* Option O */ nco_bool FORTRAN_IDX_CNV=False; /* Option F */ nco_bool HISTORY_APPEND=True; /* Option h */ nco_bool HPSS_TRY=False; /* [flg] Search HPSS for unfound files */ nco_bool MSA_USR_RDR=False; /* [flg] Multi-Slab Algorithm returns hyperslabs in user-specified order*/ nco_bool MUST_CONFORM=False; /* Must nco_var_cnf_dmn() find truly conforming variables? */ nco_bool RAM_CREATE=False; /* [flg] Create file in RAM */ nco_bool RAM_OPEN=False; /* [flg] Open (netCDF3-only) file(s) in RAM */ nco_bool SHARE_CREATE=False; /* [flg] Create (netCDF3-only) file(s) with unbuffered I/O */ nco_bool SHARE_OPEN=False; /* [flg] Open (netCDF3-only) file(s) with unbuffered I/O */ nco_bool RM_RMT_FL_PST_PRC=True; /* Option R */ nco_bool WRT_TMP_FL=True; /* [flg] Write output to temporary file */ nco_bool flg_mmr_cln=False; /* [flg] Clean memory prior to exit */ nm_id_sct *dmn_lst; nm_id_sct *xtr_lst=NULL; /* xtr_lst may be alloc()'d from NULL with -c option */ size_t bfr_sz_hnt=NC_SIZEHINT_DEFAULT; /* [B] Buffer size hint */ size_t cnk_csh_byt=NCO_CNK_CSH_BYT_DFL; /* [B] Chunk cache size */ size_t cnk_min_byt=NCO_CNK_SZ_MIN_BYT_DFL; /* [B] Minimize size of variable to chunk */ size_t cnk_sz_byt=0UL; /* [B] Chunk size in bytes */ size_t cnk_sz_scl=0UL; /* [nbr] Chunk size scalar */ size_t hdr_pad=0UL; /* [B] Pad at end of header section */ val_unn val_gnr_unn; /* Generic container for arrival point or weight */ var_sct *wgt_1=NULL_CEWI; var_sct *wgt_2=NULL_CEWI; var_sct *wgt_out_1=NULL; var_sct *wgt_out_2=NULL; var_sct **var; var_sct **var_fix; var_sct **var_fix_out; var_sct **var_out; var_sct **var_prc_1; var_sct **var_prc_2; var_sct **var_prc_out; #ifdef ENABLE_MPI /* Declare all MPI-specific variables here */ MPI_Status mpi_stt; /* [enm] Status check to decode msg_tag_typ */ nco_bool TKN_WRT_FREE=True; /* [flg] Write-access to output file is available */ int fl_nm_lng; /* [nbr] Output file name length */ int msg_bfr[msg_bfr_lng]; /* [bfr] Buffer containing var, idx, tkn_wrt_rsp */ int msg_tag_typ; /* [enm] MPI message tag type */ int prc_rnk; /* [idx] Process rank */ int prc_nbr=0; /* [nbr] Number of MPI processes */ int tkn_wrt_rsp; /* [enm] Response to request for write token */ int var_wrt_nbr=0; /* [nbr] Variables written to output file until now */ int rnk_wrk; /* [idx] Worker rank */ int wrk_id_bfr[wrk_id_bfr_lng]; /* [bfr] Buffer for rnk_wrk */ #endif /* !ENABLE_MPI */ static struct option opt_lng[]={ /* Structure ordered by short option key if possible */ /* Long options with no argument, no short option counterpart */ {"clean",no_argument,0,0}, /* [flg] Clean memory prior to exit */ {"mmr_cln",no_argument,0,0}, /* [flg] Clean memory prior to exit */ {"drt",no_argument,0,0}, /* [flg] Allow dirty memory on exit */ {"dirty",no_argument,0,0}, /* [flg] Allow dirty memory on exit */ {"mmr_drt",no_argument,0,0}, /* [flg] Allow dirty memory on exit */ {"ram_all",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) in RAM */ {"create_ram",no_argument,0,0}, /* [flg] Create file in RAM */ {"open_ram",no_argument,0,0}, /* [flg] Open (netCDF3) file(s) in RAM */ {"diskless_all",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) in RAM */ {"share_all",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) with unbuffered I/O */ {"create_share",no_argument,0,0}, /* [flg] Create (netCDF3) file(s) with unbuffered I/O */ {"open_share",no_argument,0,0}, /* [flg] Open (netCDF3) file(s) with unbuffered I/O */ {"unbuffered_io",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) with unbuffered I/O */ {"uio",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) with unbuffered I/O */ {"wrt_tmp_fl",no_argument,0,0}, /* [flg] Write output to temporary file */ {"write_tmp_fl",no_argument,0,0}, /* [flg] Write output to temporary file */ {"no_tmp_fl",no_argument,0,0}, /* [flg] Do not write output to temporary file */ {"version",no_argument,0,0}, {"vrs",no_argument,0,0}, /* Long options with argument, no short option counterpart */ {"bfr_sz_hnt",required_argument,0,0}, /* [B] Buffer size hint */ {"buffer_size_hint",required_argument,0,0}, /* [B] Buffer size hint */ {"cnk_byt",required_argument,0,0}, /* [B] Chunk size in bytes */ {"chunk_byte",required_argument,0,0}, /* [B] Chunk size in bytes */ {"cnk_dmn",required_argument,0,0}, /* [nbr] Chunk size */ {"chunk_dimension",required_argument,0,0}, /* [nbr] Chunk size */ {"cnk_map",required_argument,0,0}, /* [nbr] Chunking map */ {"chunk_map",required_argument,0,0}, /* [nbr] Chunking map */ {"cnk_min",required_argument,0,0}, /* [B] Minimize size of variable to chunk */ {"chunk_min",required_argument,0,0}, /* [B] Minimize size of variable to chunk */ {"cnk_plc",required_argument,0,0}, /* [nbr] Chunking policy */ {"chunk_policy",required_argument,0,0}, /* [nbr] Chunking policy */ {"cnk_scl",required_argument,0,0}, /* [nbr] Chunk size scalar */ {"chunk_scalar",required_argument,0,0}, /* [nbr] Chunk size scalar */ {"fl_fmt",required_argument,0,0}, {"file_format",required_argument,0,0}, {"gaa",required_argument,0,0}, /* [sng] Global attribute add */ {"glb_att_add",required_argument,0,0}, /* [sng] Global attribute add */ {"hdr_pad",required_argument,0,0}, {"header_pad",required_argument,0,0}, {"log_lvl",required_argument,0,0}, /* [enm] netCDF library debugging verbosity [0..5] */ {"log_level",required_argument,0,0}, /* [enm] netCDF library debugging verbosity [0..5] */ /* Long options with short counterparts */ {"3",no_argument,0,'3'}, {"4",no_argument,0,'4'}, {"netcdf4",no_argument,0,'4'}, {"5",no_argument,0,'5'}, {"64bit_data",no_argument,0,'5'}, {"cdf5",no_argument,0,'5'}, {"pnetcdf",no_argument,0,'5'}, {"64bit_offset",no_argument,0,'6'}, {"7",no_argument,0,'7'}, {"append",no_argument,0,'A'}, {"coords",no_argument,0,'c'}, {"crd",no_argument,0,'c'}, {"xtr_ass_var",no_argument,0,'c'}, {"xcl_ass_var",no_argument,0,'C'}, {"no_coords",no_argument,0,'C'}, {"no_crd",no_argument,0,'C'}, {"dbg_lvl",required_argument,0,'D'}, {"debug",required_argument,0,'D'}, {"nco_dbg_lvl",required_argument,0,'D'}, {"dimension",required_argument,0,'d'}, {"dmn",required_argument,0,'d'}, {"fortran",no_argument,0,'F'}, {"ftn",no_argument,0,'F'}, {"history",no_argument,0,'h'}, {"hst",no_argument,0,'h'}, {"interpolate",required_argument,0,'i'}, {"ntp",required_argument,0,'i'}, {"dfl_lvl",required_argument,0,'L'}, /* [enm] Deflate level */ {"deflate",required_argument,0,'L'}, /* [enm] Deflate level */ {"local",required_argument,0,'l'}, {"lcl",required_argument,0,'l'}, {"overwrite",no_argument,0,'O'}, {"ovr",no_argument,0,'O'}, {"output",required_argument,0,'o'}, {"fl_out",required_argument,0,'o'}, {"path",required_argument,0,'p'}, {"retain",no_argument,0,'R'}, {"rtn",no_argument,0,'R'}, {"revision",no_argument,0,'r'}, {"suspend", no_argument,0,'S'}, {"thr_nbr",required_argument,0,'t'}, {"variable",required_argument,0,'v'}, {"weight",required_argument,0,'w'}, {"wgt_var",no_argument,0,'w'}, {"auxiliary",required_argument,0,'X'}, {"exclude",no_argument,0,'x'}, {"xcl",no_argument,0,'x'}, {"help",no_argument,0,'?'}, {"hlp",no_argument,0,'?'}, {0,0,0,0} }; /* end opt_lng */ int opt_idx=0; /* Index of current long option into opt_lng array */ #ifdef ENABLE_MPI /* MPI Initialization */ MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD,&prc_nbr); MPI_Comm_rank(MPI_COMM_WORLD,&prc_rnk); #endif /* !ENABLE_MPI */ /* Start clock and save command line */ cmd_ln=nco_cmd_ln_sng(argc,argv); /* Get program name and set program enum (e.g., nco_prg_id=ncra) */ nco_prg_nm=nco_prg_prs(argv[0],&nco_prg_id); /* Parse command line arguments */ while(1){ /* getopt_long_only() allows one dash to prefix long options */ opt=getopt_long(argc,argv,opt_sht_lst,opt_lng,&opt_idx); /* NB: access to opt_crr is only valid when long_opt is detected */ if(opt == EOF) break; /* Parse positional arguments once getopt_long() returns EOF */ opt_crr=(char *)strdup(opt_lng[opt_idx].name); /* Process long options without short option counterparts */ if(opt == 0){ if(!strcmp(opt_crr,"bfr_sz_hnt") || !strcmp(opt_crr,"buffer_size_hint")){ bfr_sz_hnt=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif cnk */ if(!strcmp(opt_crr,"cnk_byt") || !strcmp(opt_crr,"chunk_byte")){ cnk_sz_byt=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif cnk_byt */ if(!strcmp(opt_crr,"cnk_min") || !strcmp(opt_crr,"chunk_min")){ cnk_min_byt=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif cnk_min */ if(!strcmp(opt_crr,"cnk_dmn") || !strcmp(opt_crr,"chunk_dimension")){ /* Copy limit argument for later processing */ cnk_arg[cnk_nbr]=(char *)strdup(optarg); cnk_nbr++; } /* endif cnk */ if(!strcmp(opt_crr,"cnk_scl") || !strcmp(opt_crr,"chunk_scalar")){ cnk_sz_scl=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif cnk */ if(!strcmp(opt_crr,"cnk_map") || !strcmp(opt_crr,"chunk_map")){ /* Chunking map */ cnk_map_sng=(char *)strdup(optarg); cnk_map=nco_cnk_map_get(cnk_map_sng); } /* endif cnk */ if(!strcmp(opt_crr,"cnk_plc") || !strcmp(opt_crr,"chunk_policy")){ /* Chunking policy */ cnk_plc_sng=(char *)strdup(optarg); cnk_plc=nco_cnk_plc_get(cnk_plc_sng); } /* endif cnk */ if(!strcmp(opt_crr,"mmr_cln") || !strcmp(opt_crr,"clean")) flg_mmr_cln=True; /* [flg] Clean memory prior to exit */ if(!strcmp(opt_crr,"drt") || !strcmp(opt_crr,"mmr_drt") || !strcmp(opt_crr,"dirty")) flg_mmr_cln=False; /* [flg] Clean memory prior to exit */ if(!strcmp(opt_crr,"fl_fmt") || !strcmp(opt_crr,"file_format")) rcd=nco_create_mode_prs(optarg,&fl_out_fmt); if(!strcmp(opt_crr,"gaa") || !strcmp(opt_crr,"glb_att_add")){ gaa_arg=(char **)nco_realloc(gaa_arg,(gaa_nbr+1)*sizeof(char *)); gaa_arg[gaa_nbr++]=(char *)strdup(optarg); } /* endif gaa */ if(!strcmp(opt_crr,"hdr_pad") || !strcmp(opt_crr,"header_pad")){ hdr_pad=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif "hdr_pad" */ if(!strcmp(opt_crr,"log_lvl") || !strcmp(opt_crr,"log_level")){ log_lvl=(int)strtol(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtol",sng_cnv_rcd); nc_set_log_level(log_lvl); } /* !log_lvl */ if(!strcmp(opt_crr,"ram_all") || !strcmp(opt_crr,"create_ram") || !strcmp(opt_crr,"diskless_all")) RAM_CREATE=True; /* [flg] Create (netCDF3) file(s) in RAM */ if(!strcmp(opt_crr,"ram_all") || !strcmp(opt_crr,"open_ram") || !strcmp(opt_crr,"diskless_all")) RAM_OPEN=True; /* [flg] Open (netCDF3) file(s) in RAM */ if(!strcmp(opt_crr,"share_all") || !strcmp(opt_crr,"unbuffered_io") || !strcmp(opt_crr,"uio") || !strcmp(opt_crr,"create_share")) SHARE_CREATE=True; /* [flg] Create (netCDF3) file(s) with unbuffered I/O */ if(!strcmp(opt_crr,"share_all") || !strcmp(opt_crr,"unbuffered_io") || !strcmp(opt_crr,"uio") || !strcmp(opt_crr,"open_share")) SHARE_OPEN=True; /* [flg] Open (netCDF3) file(s) with unbuffered I/O */ if(!strcmp(opt_crr,"vrs") || !strcmp(opt_crr,"version")){ (void)nco_vrs_prn(CVS_Id,CVS_Revision); nco_exit(EXIT_SUCCESS); } /* endif "vrs" */ if(!strcmp(opt_crr,"wrt_tmp_fl") || !strcmp(opt_crr,"write_tmp_fl")) WRT_TMP_FL=True; if(!strcmp(opt_crr,"no_tmp_fl")) WRT_TMP_FL=False; } /* opt != 0 */ /* Process short options */ switch(opt){ case 0: /* Long options have already been processed, return */ break; case '3': /* Request netCDF3 output storage format */ fl_out_fmt=NC_FORMAT_CLASSIC; break; case '4': /* Request netCDF4 output storage format */ fl_out_fmt=NC_FORMAT_NETCDF4; break; case '5': /* Request netCDF3 64-bit offset+data storage (i.e., pnetCDF) format */ fl_out_fmt=NC_FORMAT_CDF5; break; case '6': /* Request netCDF3 64-bit offset output storage format */ fl_out_fmt=NC_FORMAT_64BIT_OFFSET; break; case '7': /* Request netCDF4-classic output storage format */ fl_out_fmt=NC_FORMAT_NETCDF4_CLASSIC; break; case 'A': /* Toggle FORCE_APPEND */ FORCE_APPEND=!FORCE_APPEND; break; case 'C': /* Extract all coordinates associated with extracted variables? */ EXTRACT_ASSOCIATED_COORDINATES=False; break; case 'c': EXTRACT_ALL_COORDINATES=True; break; case 'D': /* The debugging level. Default is 0. */ nco_dbg_lvl=(unsigned short int)strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); break; case 'd': /* Copy limit argument for later processing */ lmt_arg[lmt_nbr]=(char *)strdup(optarg); lmt_nbr++; break; case 'F': /* Toggle index convention. Default is 0-based arrays (C-style). */ FORTRAN_IDX_CNV=!FORTRAN_IDX_CNV; break; case 'h': /* Toggle appending to history global attribute */ HISTORY_APPEND=!HISTORY_APPEND; break; case 'i': /* Name of variable to guide interpolation. Default is none */ ntp_lst_in=nco_lst_prs_2D(optarg,",",&nbr_ntp); if(nbr_ntp > 2){ (void)fprintf(stdout,"%s: ERROR too many arguments to -i\n",nco_prg_nm_get()); nco_exit(EXIT_FAILURE); } /* end if */ ntp_nm=ntp_lst_in[0]; ntp_val_out=strtod(ntp_lst_in[1],&sng_cnv_rcd); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtod",sng_cnv_rcd); CMD_LN_NTP_VAR=True; CMD_LN_NTP_WGT=False; break; case 'L': /* [enm] Deflate level. Default is 0. */ dfl_lvl=(int)strtol(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtol",sng_cnv_rcd); break; case 'l': /* Local path prefix for files retrieved from remote file system */ fl_pth_lcl=(char *)strdup(optarg); break; case 'O': /* Toggle FORCE_OVERWRITE */ FORCE_OVERWRITE=!FORCE_OVERWRITE; break; case 'o': /* Name of output file */ fl_out=(char *)strdup(optarg); break; case 'p': /* Common file path */ fl_pth=(char *)strdup(optarg); break; case 'R': /* Toggle removal of remotely-retrieved-files. Default is True. */ RM_RMT_FL_PST_PRC=!RM_RMT_FL_PST_PRC; break; case 'r': /* Print CVS program information and copyright notice */ (void)nco_vrs_prn(CVS_Id,CVS_Revision); (void)nco_lbr_vrs_prn(); (void)nco_cpy_prn(); (void)nco_cnf_prn(); nco_exit(EXIT_SUCCESS); break; #ifdef ENABLE_MPI case 'S': /* Suspend with signal handler to facilitate debugging */ if(signal(SIGUSR1,nco_cnt_run) == SIG_ERR) (void)fprintf(fp_stdout,"%s: ERROR Could not install suspend handler.\n",nco_prg_nm); while(!nco_spn_lck_brk) usleep(nco_spn_lck_us); /* Spinlock. fxm: should probably insert a sched_yield */ break; #endif /* !ENABLE_MPI */ case 't': /* Thread number */ thr_nbr=(int)strtol(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtol",sng_cnv_rcd); break; case 'v': /* Variables to extract/exclude */ /* Replace commas with hashes when within braces (convert back later) */ optarg_lcl=(char *)strdup(optarg); (void)nco_rx_comma2hash(optarg_lcl); var_lst_in=nco_lst_prs_2D(optarg_lcl,",",&var_lst_in_nbr); optarg_lcl=(char *)nco_free(optarg_lcl); xtr_nbr=var_lst_in_nbr; break; case 'w': /* Weight(s) for interpolation. Default is wgt_val_1=wgt_val_2=0.5 */ ntp_lst_in=nco_lst_prs_2D(optarg,",",&nbr_ntp); if(nbr_ntp > 2){ (void)fprintf(stdout,"%s: ERROR too many arguments to -w\n",nco_prg_nm_get()); nco_exit(EXIT_FAILURE); }else if(nbr_ntp == 2){ wgt_val_1=strtod(ntp_lst_in[0],&sng_cnv_rcd); if(*sng_cnv_rcd) nco_sng_cnv_err(ntp_lst_in[0],"strtod",sng_cnv_rcd); wgt_val_2=strtod(ntp_lst_in[1],&sng_cnv_rcd); if(*sng_cnv_rcd) nco_sng_cnv_err(ntp_lst_in[1],"strtod",sng_cnv_rcd); }else if(nbr_ntp == 1){ wgt_val_1=strtod(ntp_lst_in[0],&sng_cnv_rcd); if(*sng_cnv_rcd) nco_sng_cnv_err(ntp_lst_in[0],"strtod",sng_cnv_rcd); wgt_val_2=1.0-wgt_val_1; } /* end else */ CMD_LN_NTP_WGT=True; break; case 'X': /* Copy auxiliary coordinate argument for later processing */ aux_arg[aux_nbr]=(char *)strdup(optarg); aux_nbr++; MSA_USR_RDR=True; /* [flg] Multi-Slab Algorithm returns hyperslabs in user-specified order */ break; case 'x': /* Exclude rather than extract variables specified with -v */ EXCLUDE_INPUT_LIST=True; break; case '?': /* Print proper usage */ (void)nco_usg_prn(); nco_exit(EXIT_SUCCESS); break; case '-': /* Long options are not allowed */ (void)fprintf(stderr,"%s: ERROR Long options are not available in this build. Use single letter options instead.\n",nco_prg_nm_get()); nco_exit(EXIT_FAILURE); break; default: /* Print proper usage */ (void)fprintf(stdout,"%s ERROR in command-line syntax/options. Please reformulate command accordingly.\n",nco_prg_nm_get()); (void)nco_usg_prn(); nco_exit(EXIT_FAILURE); break; } /* end switch */ if(opt_crr) opt_crr=(char *)nco_free(opt_crr); } /* end while loop */ if(CMD_LN_NTP_VAR && CMD_LN_NTP_WGT){ (void)fprintf(stdout,"%s: ERROR interpolating variable (-i) and fixed weight(s) (-w) both set\n",nco_prg_nm_get()); nco_exit(EXIT_FAILURE); }else if(!CMD_LN_NTP_VAR && !CMD_LN_NTP_WGT){ (void)fprintf(stdout,"%s: ERROR interpolating variable (-i) or fixed weight(s) (-w) must be set\n",nco_prg_nm_get()); nco_exit(EXIT_FAILURE); } /* end else */ /* Process positional arguments and fill-in filenames */ fl_lst_in=nco_fl_lst_mk(argv,argc,optind,&fl_nbr,&fl_out,&FL_LST_IN_FROM_STDIN,FORCE_OVERWRITE); /* Make uniform list of user-specified chunksizes */ if(cnk_nbr > 0) cnk_dmn=nco_cnk_prs(cnk_nbr,cnk_arg); /* Make uniform list of user-specified dimension limits */ lmt=nco_lmt_prs(lmt_nbr,lmt_arg); /* Initialize thread information */ thr_nbr=nco_openmp_ini(thr_nbr); in_id_1_arr=(int *)nco_malloc(thr_nbr*sizeof(int)); in_id_2_arr=(int *)nco_malloc(thr_nbr*sizeof(int)); /* Parse filenames */ fl_idx=0; /* Input file _1 */ fl_in_1=nco_fl_nm_prs(fl_in_1,fl_idx,&fl_nbr,fl_lst_in,abb_arg_nbr,fl_lst_abb,fl_pth); if(nco_dbg_lvl >= nco_dbg_fl) (void)fprintf(stderr,"\nInput file %d is %s; ",fl_idx,fl_in_1); /* Make sure file is on local system and is readable or die trying */ fl_in_1=nco_fl_mk_lcl(fl_in_1,fl_pth_lcl,&FILE_1_RETRIEVED_FROM_REMOTE_LOCATION); if(nco_dbg_lvl >= nco_dbg_fl) (void)fprintf(stderr,"local file %s:\n",fl_in_1); /* Open file once per thread to improve caching */ if(RAM_OPEN) md_open=NC_NOWRITE|NC_DISKLESS; else md_open=NC_NOWRITE; if(SHARE_OPEN) md_open=md_open|NC_SHARE; for(thr_idx=0;thr_idx<thr_nbr;thr_idx++) rcd+=nco_fl_open(fl_in_1,md_open,&bfr_sz_hnt,in_id_1_arr+thr_idx); in_id_1=in_id_1_arr[0]; fl_idx=1; /* Input file _2 */ fl_in_2=nco_fl_nm_prs(fl_in_2,fl_idx,&fl_nbr,fl_lst_in,abb_arg_nbr,fl_lst_abb,fl_pth); if(nco_dbg_lvl >= nco_dbg_fl) (void)fprintf(stderr,"\nInput file %d is %s; ",fl_idx,fl_in_2); /* Make sure file is on local system and is readable or die trying */ fl_in_2=nco_fl_mk_lcl(fl_in_2,fl_pth_lcl,&FILE_2_RETRIEVED_FROM_REMOTE_LOCATION); if(nco_dbg_lvl >= nco_dbg_fl) (void)fprintf(stderr,"local file %s:\n",fl_in_2); /* Open file once per thread to improve caching */ if(RAM_OPEN) md_open=NC_NOWRITE|NC_DISKLESS; else md_open=NC_NOWRITE; for(thr_idx=0;thr_idx<thr_nbr;thr_idx++) rcd+=nco_fl_open(fl_in_2,md_open,&bfr_sz_hnt,in_id_2_arr+thr_idx); in_id_2=in_id_2_arr[0]; /* Parse auxiliary coordinates */ if(aux_nbr > 0){ int aux_idx_nbr; aux=nco_aux_evl(in_id_1,aux_nbr,aux_arg,&aux_idx_nbr); if(aux_idx_nbr > 0){ lmt=(lmt_sct **)nco_realloc(lmt,(lmt_nbr+aux_idx_nbr)*sizeof(lmt_sct *)); int lmt_nbr_new=lmt_nbr+aux_idx_nbr; int aux_idx=0; for(int lmt_idx=lmt_nbr;lmt_idx<lmt_nbr_new;lmt_idx++) lmt[lmt_idx]=aux[aux_idx++]; lmt_nbr=lmt_nbr_new; } /* endif aux */ } /* endif aux_nbr */ /* Get number of variables and dimensions in file */ (void)nco_inq(in_id_1,&nbr_dmn_fl,&nbr_var_fl,(int *)NULL,(int *)NULL); (void)nco_inq_format(in_id_1,&fl_in_fmt_1); (void)nco_inq_format(in_id_2,&fl_in_fmt_2); /* Form initial extraction list which may include extended regular expressions */ xtr_lst=nco_var_lst_mk(in_id_1,nbr_var_fl,var_lst_in,EXCLUDE_INPUT_LIST,EXTRACT_ALL_COORDINATES,&xtr_nbr); /* Change included variables to excluded variables */ if(EXCLUDE_INPUT_LIST) xtr_lst=nco_var_lst_xcl(in_id_1,nbr_var_fl,xtr_lst,&xtr_nbr); /* Determine conventions (ARM/CCM/CCSM/CF/MPAS) for treating file */ cnv=nco_cnv_ini(in_id_1); /* Add all coordinate variables to extraction list */ if(EXTRACT_ALL_COORDINATES) xtr_lst=nco_var_lst_crd_add(in_id_1,nbr_dmn_fl,nbr_var_fl,xtr_lst,&xtr_nbr,cnv); /* Extract coordinates associated with extracted variables */ if(EXTRACT_ASSOCIATED_COORDINATES) xtr_lst=nco_var_lst_crd_ass_add(in_id_1,xtr_lst,&xtr_nbr,cnv); /* Sort extraction list by variable ID for fastest I/O */ if(xtr_nbr > 1) xtr_lst=nco_lst_srt_nm_id(xtr_lst,xtr_nbr,False); /* We now have final list of variables to extract. Phew. */ /* Find coordinate/dimension values associated with user-specified limits NB: nco_lmt_evl() with same nc_id contains OpenMP critical region */ for(idx=0;idx<lmt_nbr;idx++) (void)nco_lmt_evl(in_id_1,lmt[idx],0L,FORTRAN_IDX_CNV); /* Place all dimensions in lmt_all_lst */ lmt_all_lst=(lmt_all_sct **)nco_malloc(nbr_dmn_fl*sizeof(lmt_all_sct *)); /* Initialize lmt_all_sct's */ (void)nco_msa_lmt_all_ntl(in_id_1,MSA_USR_RDR,lmt_all_lst,nbr_dmn_fl,lmt,lmt_nbr); /* Find dimensions associated with variables to be extracted */ dmn_lst=nco_dmn_lst_ass_var(in_id_1,xtr_lst,xtr_nbr,&nbr_dmn_xtr); /* Fill-in dimension structure for all extracted dimensions */ dim=(dmn_sct **)nco_malloc(nbr_dmn_xtr*sizeof(dmn_sct *)); for(idx=0;idx<nbr_dmn_xtr;idx++) dim[idx]=nco_dmn_fll(in_id_1,dmn_lst[idx].id,dmn_lst[idx].nm); /* Dimension list no longer needed */ dmn_lst=nco_nm_id_lst_free(dmn_lst,nbr_dmn_xtr); /* Duplicate input dimension structures for output dimension structures */ dmn_out=(dmn_sct **)nco_malloc(nbr_dmn_xtr*sizeof(dmn_sct *)); for(idx=0;idx<nbr_dmn_xtr;idx++){ dmn_out[idx]=nco_dmn_dpl(dim[idx]); (void)nco_dmn_xrf(dim[idx],dmn_out[idx]); } /* end loop over idx */ /* Merge hyperslab limit information into dimension structures */ if(nbr_dmn_fl > 0) (void)nco_dmn_lmt_all_mrg(dmn_out,nbr_dmn_xtr,lmt_all_lst,nbr_dmn_fl); /* Fill-in variable structure list for all extracted variables */ var=(var_sct **)nco_malloc(xtr_nbr*sizeof(var_sct *)); var_out=(var_sct **)nco_malloc(xtr_nbr*sizeof(var_sct *)); for(idx=0;idx<xtr_nbr;idx++){ var[idx]=nco_var_fll(in_id_1,xtr_lst[idx].id,xtr_lst[idx].nm,dim,nbr_dmn_xtr); var_out[idx]=nco_var_dpl(var[idx]); (void)nco_xrf_var(var[idx],var_out[idx]); (void)nco_xrf_dmn(var_out[idx]); } /* end loop over idx */ /* Extraction list no longer needed */ xtr_lst=nco_nm_id_lst_free(xtr_lst,xtr_nbr); /* Divide variable lists into lists of fixed variables and variables to be processed */ (void)nco_var_lst_dvd(var,var_out,xtr_nbr,cnv,True,nco_pck_plc_nil,nco_pck_map_nil,(dmn_sct **)NULL,0,&var_fix,&var_fix_out,&nbr_var_fix,&var_prc_1,&var_prc_out,&nbr_var_prc); /* Assign zero to start and unity to stride vectors in output variables */ (void)nco_var_srd_srt_set(var_out,xtr_nbr); #ifdef ENABLE_MPI if(prc_rnk == rnk_mgr){ /* MPI manager code */ #endif /* !ENABLE_MPI */ /* Make output and input files consanguinous */ if(fl_out_fmt == NCO_FORMAT_UNDEFINED) fl_out_fmt=fl_in_fmt_1; /* Open output file */ fl_out_tmp=nco_fl_out_open(fl_out,&FORCE_APPEND,FORCE_OVERWRITE,fl_out_fmt,&bfr_sz_hnt,RAM_CREATE,RAM_OPEN,SHARE_CREATE,SHARE_OPEN,WRT_TMP_FL,&out_id); /* Copy global attributes */ (void)nco_att_cpy(in_id_1,out_id,NC_GLOBAL,NC_GLOBAL,(nco_bool)True); /* Catenate time-stamped command line to "history" global attribute */ if(HISTORY_APPEND) (void)nco_hst_att_cat(out_id,cmd_ln); if(HISTORY_APPEND && FORCE_APPEND) (void)nco_prv_att_cat(fl_in_1,in_id_1,out_id); if(gaa_nbr > 0) (void)nco_glb_att_add(out_id,gaa_arg,gaa_nbr); if(HISTORY_APPEND) (void)nco_vrs_att_cat(out_id); if(thr_nbr > 1 && HISTORY_APPEND) (void)nco_thr_att_cat(out_id,thr_nbr); #ifdef ENABLE_MPI /* Initialize MPI task information */ if(prc_nbr > 0 && HISTORY_APPEND) (void)nco_mpi_att_cat(out_id,prc_nbr); #endif /* !ENABLE_MPI */ /* Define dimensions in output file */ (void)nco_dmn_dfn(fl_out,out_id,dmn_out,nbr_dmn_xtr); /* Define variables in output file, copy their attributes */ (void)nco_var_dfn(in_id_1,fl_out,out_id,var_out,xtr_nbr,(dmn_sct **)NULL,(int)0,nco_pck_plc_nil,nco_pck_map_nil,dfl_lvl); /* Set chunksize parameters */ if(fl_out_fmt == NC_FORMAT_NETCDF4 || fl_out_fmt == NC_FORMAT_NETCDF4_CLASSIC) (void)nco_cnk_sz_set(out_id,lmt_all_lst,nbr_dmn_fl,&cnk_map,&cnk_plc,cnk_sz_scl,cnk_dmn,cnk_nbr); /* Turn-off default filling behavior to enhance efficiency */ nco_set_fill(out_id,NC_NOFILL,&fll_md_old); /* Take output file out of define mode */ if(hdr_pad == 0UL){ (void)nco_enddef(out_id); }else{ (void)nco__enddef(out_id,hdr_pad); if(nco_dbg_lvl >= nco_dbg_scl) (void)fprintf(stderr,"%s: INFO Padding header with %lu extra bytes\n",nco_prg_nm_get(),(unsigned long)hdr_pad); } /* hdr_pad */ #ifdef ENABLE_MPI } /* prc_rnk != rnk_mgr */ /* Manager obtains output filename and broadcasts to workers */ if(prc_rnk == rnk_mgr) fl_nm_lng=(int)strlen(fl_out_tmp); MPI_Bcast(&fl_nm_lng,1,MPI_INT,0,MPI_COMM_WORLD); if(prc_rnk != rnk_mgr) fl_out_tmp=(char *)nco_malloc((fl_nm_lng+1)*sizeof(char)); MPI_Bcast(fl_out_tmp,fl_nm_lng+1,MPI_CHAR,0,MPI_COMM_WORLD); if(prc_rnk == rnk_mgr){ /* MPI manager code */ TKN_WRT_FREE=False; #endif /* !ENABLE_MPI */ /* Copy variable data for non-processed variables */ (void)nco_msa_var_val_cpy(in_id_1,out_id,var_fix,nbr_var_fix,lmt_all_lst,nbr_dmn_fl); #ifdef ENABLE_MPI /* Close output file so workers can open it */ nco_close(out_id); TKN_WRT_FREE=True; } /* prc_rnk != rnk_mgr */ #endif /* !ENABLE_MPI */ /* Perform various error-checks on input file */ if(False) (void)nco_fl_cmp_err_chk(); /* ncflint-specific stuff: */ /* Find the weighting variable in input file */ if(CMD_LN_NTP_VAR){ int ntp_id_1; int ntp_id_2; var_sct *ntp_1; var_sct *ntp_2; var_sct *ntp_var_out; /* Turn arrival point into pseudo-variable */ val_gnr_unn.d=ntp_val_out; /* Generic container for arrival point or weight */ ntp_var_out=scl_mk_var(val_gnr_unn,NC_DOUBLE); rcd=nco_inq_varid(in_id_1,ntp_nm,&ntp_id_1); rcd=nco_inq_varid(in_id_2,ntp_nm,&ntp_id_2); ntp_1=nco_var_fll(in_id_1,ntp_id_1,ntp_nm,dim,nbr_dmn_xtr); ntp_2=nco_var_fll(in_id_2,ntp_id_2,ntp_nm,dim,nbr_dmn_xtr); /* Currently, only support scalar variables */ if(ntp_1->sz > 1 || ntp_2->sz > 1){ (void)fprintf(stdout,"%s: ERROR interpolation variable %s must be scalar\n",nco_prg_nm_get(),ntp_nm); nco_exit(EXIT_FAILURE); } /* end if */ /* Retrieve interpolation variable */ /* NB: nco_var_get() with same nc_id contains OpenMP critical region */ (void)nco_var_get(in_id_1,ntp_1); (void)nco_var_get(in_id_2,ntp_2); /* Weights must be NC_DOUBLE */ ntp_1=nco_var_cnf_typ((nc_type)NC_DOUBLE,ntp_1); ntp_2=nco_var_cnf_typ((nc_type)NC_DOUBLE,ntp_2); /* Check for degenerate case */ if(ntp_1->val.dp[0] == ntp_2->val.dp[0]){ (void)fprintf(stdout,"%s: ERROR Interpolation variable %s is identical (%g) in input files, therefore unable to interpolate.\n",nco_prg_nm_get(),ntp_nm,ntp_1->val.dp[0]); nco_exit(EXIT_FAILURE); } /* end if */ /* Turn weights into pseudo-variables */ wgt_1=nco_var_dpl(ntp_2); wgt_2=nco_var_dpl(ntp_var_out); /* Subtract to find interpolation distances */ (void)nco_var_sbt(ntp_1->type,ntp_1->sz,ntp_1->has_mss_val,ntp_1->mss_val,ntp_var_out->val,wgt_1->val); (void)nco_var_sbt(ntp_1->type,ntp_1->sz,ntp_1->has_mss_val,ntp_1->mss_val,ntp_1->val,wgt_2->val); (void)nco_var_sbt(ntp_1->type,ntp_1->sz,ntp_1->has_mss_val,ntp_1->mss_val,ntp_1->val,ntp_2->val); /* Normalize to obtain final interpolation weights */ (void)nco_var_dvd(wgt_1->type,wgt_1->sz,wgt_1->has_mss_val,wgt_1->mss_val,ntp_2->val,wgt_1->val); (void)nco_var_dvd(wgt_2->type,wgt_2->sz,wgt_2->has_mss_val,wgt_2->mss_val,ntp_2->val,wgt_2->val); if(ntp_1) ntp_1=nco_var_free(ntp_1); if(ntp_2) ntp_2=nco_var_free(ntp_2); if(ntp_var_out) ntp_var_out=nco_var_free(ntp_var_out); } /* end if CMD_LN_NTP_VAR */ if(CMD_LN_NTP_WGT){ val_gnr_unn.d=wgt_val_1; /* Generic container for arrival point or weight */ wgt_1=scl_mk_var(val_gnr_unn,NC_DOUBLE); val_gnr_unn.d=wgt_val_2; /* Generic container for arrival point or weight */ wgt_2=scl_mk_var(val_gnr_unn,NC_DOUBLE); } /* end if CMD_LN_NTP_WGT */ if(nco_dbg_lvl > nco_dbg_scl) (void)fprintf(stderr,"wgt_1 = %g, wgt_2 = %g\n",wgt_1->val.dp[0],wgt_2->val.dp[0]); /* Create structure list for second file */ var_prc_2=(var_sct **)nco_malloc(nbr_var_prc*sizeof(var_sct *)); /* Loop over each interpolated variable */ #ifdef ENABLE_MPI if(prc_rnk == rnk_mgr){ /* MPI manager code */ /* Compensate for incrementing on each worker's first message */ var_wrt_nbr=-prc_nbr+1; idx=0; /* While variables remain to be processed or written... */ while(var_wrt_nbr < nbr_var_prc){ /* Receive message from any worker */ MPI_Recv(wrk_id_bfr,wrk_id_bfr_lng,MPI_INT,MPI_ANY_SOURCE,MPI_ANY_TAG,MPI_COMM_WORLD,&mpi_stt); /* Obtain MPI message tag type */ msg_tag_typ=mpi_stt.MPI_TAG; /* Get sender's prc_rnk */ rnk_wrk=wrk_id_bfr[0]; /* Allocate next variable, if any, to worker */ if(msg_tag_typ == msg_tag_wrk_rqs){ var_wrt_nbr++; /* [nbr] Number of variables written */ /* Worker closed output file before sending msg_tag_wrk_rqs */ TKN_WRT_FREE=True; if(idx > nbr_var_prc-1){ msg_bfr[0]=idx_all_wrk_ass; /* [enm] All variables already assigned */ msg_bfr[1]=out_id; /* Output file ID */ }else{ /* Tell requesting worker to allocate space for next variable */ msg_bfr[0]=idx; /* [idx] Variable to be processed */ msg_bfr[1]=out_id; /* Output file ID */ msg_bfr[2]=var_prc_out[idx]->id; /* [id] Variable ID in output file */ /* Point to next variable on list */ idx++; } /* endif idx */ MPI_Send(msg_bfr,msg_bfr_lng,MPI_INT,rnk_wrk,msg_tag_wrk_rsp,MPI_COMM_WORLD); /* msg_tag_typ != msg_tag_wrk_rqs */ }else if(msg_tag_typ == msg_tag_tkn_wrt_rqs){ /* Allocate token if free, else ask worker to try later */ if(TKN_WRT_FREE){ TKN_WRT_FREE=False; msg_bfr[0]=tkn_wrt_rqs_xcp; /* Accept request for write token */ }else{ msg_bfr[0]=tkn_wrt_rqs_dny; /* Deny request for write token */ } /* !TKN_WRT_FREE */ MPI_Send(msg_bfr,msg_bfr_lng,MPI_INT,rnk_wrk,msg_tag_tkn_wrt_rsp,MPI_COMM_WORLD); } /* msg_tag_typ != msg_tag_tkn_wrt_rqs */ } /* end while var_wrt_nbr < nbr_var_prc */ }else{ /* prc_rnk != rnk_mgr, end Manager code begin Worker code */ wrk_id_bfr[0]=prc_rnk; while(1){ /* While work remains... */ /* Send msg_tag_wrk_rqs */ wrk_id_bfr[0]=prc_rnk; MPI_Send(wrk_id_bfr,wrk_id_bfr_lng,MPI_INT,rnk_mgr,msg_tag_wrk_rqs,MPI_COMM_WORLD); /* Receive msg_tag_wrk_rsp */ MPI_Recv(msg_bfr,msg_bfr_lng,MPI_INT,0,msg_tag_wrk_rsp,MPI_COMM_WORLD,&mpi_stt); idx=msg_bfr[0]; out_id=msg_bfr[1]; if(idx == idx_all_wrk_ass) break; else{ var_prc_out[idx]->id=msg_bfr[2]; /* Process this variable same as UP code */ #else /* !ENABLE_MPI */ #ifdef _OPENMP /* OpenMP notes: shared(): msk and wgt are not altered within loop private(): wgt_avg does not need initialization */ #pragma omp parallel for default(none) firstprivate(wgt_1,wgt_2,wgt_out_1,wgt_out_2) private(DO_CONFORM,idx,in_id_1,in_id_2,has_mss_val) shared(MUST_CONFORM,nco_dbg_lvl,dim,fl_in_1,fl_in_2,fl_out,in_id_1_arr,in_id_2_arr,nbr_dmn_xtr,nbr_var_prc,out_id,nco_prg_nm,var_prc_1,var_prc_2,var_prc_out,lmt_all_lst,nbr_dmn_fl) #endif /* !_OPENMP */ /* UP and SMP codes main loop over variables */ for(idx=0;idx<nbr_var_prc;idx++){ #endif /* !ENABLE_MPI */ if(nco_dbg_lvl >= nco_dbg_var) (void)fprintf(fp_stderr,"%s, ",var_prc_1[idx]->nm); if(nco_dbg_lvl >= nco_dbg_var) (void)fflush(fp_stderr); in_id_1=in_id_1_arr[omp_get_thread_num()]; in_id_2=in_id_2_arr[omp_get_thread_num()]; var_prc_2[idx]=nco_var_dpl(var_prc_1[idx]); (void)nco_var_mtd_refresh(in_id_2,var_prc_2[idx]); /* NB: nco_var_get() with same nc_id contains OpenMP critical region */ (void)nco_msa_var_get(in_id_1,var_prc_1[idx],lmt_all_lst,nbr_dmn_fl); (void)nco_msa_var_get(in_id_2,var_prc_2[idx],lmt_all_lst,nbr_dmn_fl); wgt_out_1=nco_var_cnf_dmn(var_prc_1[idx],wgt_1,wgt_out_1,MUST_CONFORM,&DO_CONFORM); wgt_out_2=nco_var_cnf_dmn(var_prc_2[idx],wgt_2,wgt_out_2,MUST_CONFORM,&DO_CONFORM); var_prc_1[idx]=nco_var_cnf_typ((nc_type)NC_DOUBLE,var_prc_1[idx]); var_prc_2[idx]=nco_var_cnf_typ((nc_type)NC_DOUBLE,var_prc_2[idx]); /* Allocate and, if necesssary, initialize space for processed variable */ var_prc_out[idx]->sz=var_prc_1[idx]->sz; /* NB: must not try to free() same tally buffer twice */ /* var_prc_out[idx]->tally=var_prc_1[idx]->tally=(long *)nco_malloc(var_prc_out[idx]->sz*sizeof(long int));*/ var_prc_out[idx]->tally=(long *)nco_malloc(var_prc_out[idx]->sz*sizeof(long int)); (void)nco_zero_long(var_prc_out[idx]->sz,var_prc_out[idx]->tally); /* Weight variable by taking product of weight with variable */ (void)nco_var_mlt(var_prc_1[idx]->type,var_prc_1[idx]->sz,var_prc_1[idx]->has_mss_val,var_prc_1[idx]->mss_val,wgt_out_1->val,var_prc_1[idx]->val); (void)nco_var_mlt(var_prc_2[idx]->type,var_prc_2[idx]->sz,var_prc_2[idx]->has_mss_val,var_prc_2[idx]->mss_val,wgt_out_2->val,var_prc_2[idx]->val); /* Change missing_value of var_prc_2, if any, to missing_value of var_prc_1, if any */ has_mss_val=nco_mss_val_cnf(var_prc_1[idx],var_prc_2[idx]); /* NB: fxm: use tally to determine when to "unweight" answer? TODO */ (void)nco_var_add_tll_ncflint(var_prc_1[idx]->type,var_prc_1[idx]->sz,has_mss_val,var_prc_1[idx]->mss_val,var_prc_out[idx]->tally,var_prc_1[idx]->val,var_prc_2[idx]->val); /* Re-cast output variable to original type */ var_prc_2[idx]=nco_var_cnf_typ(var_prc_out[idx]->type,var_prc_2[idx]); #ifdef ENABLE_MPI /* Obtain token and prepare to write */ while(1){ /* Send msg_tag_tkn_wrt_rqs repeatedly until token obtained */ wrk_id_bfr[0]=prc_rnk; MPI_Send(wrk_id_bfr,wrk_id_bfr_lng,MPI_INT,rnk_mgr,msg_tag_tkn_wrt_rqs,MPI_COMM_WORLD); MPI_Recv(msg_bfr,msg_bfr_lng,MPI_INT,rnk_mgr,msg_tag_tkn_wrt_rsp,MPI_COMM_WORLD,&mpi_stt); tkn_wrt_rsp=msg_bfr[0]; /* Wait then re-send request */ if(tkn_wrt_rsp == tkn_wrt_rqs_dny) sleep(tkn_wrt_rqs_ntv); else break; } /* end while loop waiting for write token */ /* Worker has token---prepare to write */ if(tkn_wrt_rsp == tkn_wrt_rqs_xcp){ if(RAM_OPEN) md_open=NC_WRITE|NC_SHARE|NC_DISKLESS; else md_open=NC_WRITE|NC_SHARE; rcd=nco_fl_open(fl_out_tmp,md_open,&bfr_sz_hnt,&out_id); /* Set chunksize parameters */ if(fl_out_fmt == NC_FORMAT_NETCDF4 || fl_out_fmt == NC_FORMAT_NETCDF4_CLASSIC) (void)nco_cnk_sz_set(out_id,lmt_all_lst,nbr_dmn_fl,&cnk_map,&cnk_plc,cnk_sz_scl,cnk_dmn,cnk_nbr); /* Turn-off default filling behavior to enhance efficiency */ nco_set_fill(out_id,NC_NOFILL,&fll_md_old); #else /* !ENABLE_MPI */ #ifdef _OPENMP #pragma omp critical #endif /* _OPENMP */ #endif /* !ENABLE_MPI */ /* Common code for UP, SMP, and MPI */ { /* begin OpenMP critical */ /* Copy interpolations to output file */ if(var_prc_out[idx]->nbr_dim == 0){ (void)nco_put_var1(out_id,var_prc_out[idx]->id,var_prc_out[idx]->srt,var_prc_2[idx]->val.vp,var_prc_2[idx]->type); }else{ /* end if variable is scalar */ (void)nco_put_vara(out_id,var_prc_out[idx]->id,var_prc_out[idx]->srt,var_prc_out[idx]->cnt,var_prc_2[idx]->val.vp,var_prc_2[idx]->type); } /* end else */ } /* end OpenMP critical */ /* Free dynamically allocated buffers */ if(var_prc_1[idx]) var_prc_1[idx]=nco_var_free(var_prc_1[idx]); if(var_prc_2[idx]) var_prc_2[idx]=nco_var_free(var_prc_2[idx]); if(var_prc_out[idx]) var_prc_out[idx]=nco_var_free(var_prc_out[idx]); #ifdef ENABLE_MPI /* Close output file and increment written counter */ nco_close(out_id); var_wrt_nbr++; } /* endif tkn_wrt_rqs_xcp */ } /* end else !idx_all_wrk_ass */ } /* end while loop requesting work/token */ } /* endif Worker */ #else /* !ENABLE_MPI */ } /* end (OpenMP parallel for) loop over idx */ #endif /* !ENABLE_MPI */ if(nco_dbg_lvl >= nco_dbg_fl) (void)fprintf(stderr,"\n"); /* Close input netCDF files */ for(thr_idx=0;thr_idx<thr_nbr;thr_idx++) nco_close(in_id_1_arr[thr_idx]); for(thr_idx=0;thr_idx<thr_nbr;thr_idx++) nco_close(in_id_2_arr[thr_idx]); #ifdef ENABLE_MPI /* Manager moves output file (closed by workers) from temporary to permanent location */ if(prc_rnk == rnk_mgr) (void)nco_fl_mv(fl_out_tmp,fl_out); #else /* !ENABLE_MPI */ /* Close output file and move it from temporary to permanent location */ (void)nco_fl_out_cls(fl_out,fl_out_tmp,out_id); #endif /* end !ENABLE_MPI */ /* Remove local copy of file */ if(FILE_1_RETRIEVED_FROM_REMOTE_LOCATION && RM_RMT_FL_PST_PRC) (void)nco_fl_rm(fl_in_1); if(FILE_2_RETRIEVED_FROM_REMOTE_LOCATION && RM_RMT_FL_PST_PRC) (void)nco_fl_rm(fl_in_2); /* Clean memory unless dirty memory allowed */ if(flg_mmr_cln){ /* ncflint-specific memory */ if(fl_in_1) fl_in_1=(char *)nco_free(fl_in_1); if(fl_in_2) fl_in_2=(char *)nco_free(fl_in_2); if(in_id_arr_1) in_id_arr_1=(int *)nco_free(in_id_arr_1); if(in_id_arr_2) in_id_arr_2=(int *)nco_free(in_id_arr_2); var_prc_1=(var_sct **)nco_free(var_prc_1); var_prc_2=(var_sct **)nco_free(var_prc_2); if(wgt_1) wgt_1=(var_sct *)nco_var_free(wgt_1); if(wgt_2) wgt_2=(var_sct *)nco_var_free(wgt_2); if(wgt_out_1) wgt_out_1=(var_sct *)nco_var_free(wgt_out_1); if(wgt_out_2) wgt_out_2=(var_sct *)nco_var_free(wgt_out_2); /* NB: free lmt[] is now referenced within lmt_all_lst[idx] */ for(idx=0;idx<nbr_dmn_fl;idx++) for(jdx=0;jdx<lmt_all_lst[idx]->lmt_dmn_nbr;jdx++) lmt_all_lst[idx]->lmt_dmn[jdx]=nco_lmt_free(lmt_all_lst[idx]->lmt_dmn[jdx]); if(nbr_dmn_fl > 0) lmt_all_lst=nco_lmt_all_lst_free(lmt_all_lst,nbr_dmn_fl); lmt=(lmt_sct**)nco_free(lmt); /* NCO-generic clean-up */ /* Free individual strings/arrays */ if(cmd_ln) cmd_ln=(char *)nco_free(cmd_ln); if(cnk_map_sng) cnk_map_sng=(char *)nco_free(cnk_map_sng); if(cnk_plc_sng) cnk_plc_sng=(char *)nco_free(cnk_plc_sng); if(fl_out) fl_out=(char *)nco_free(fl_out); if(fl_out_tmp) fl_out_tmp=(char *)nco_free(fl_out_tmp); if(fl_pth) fl_pth=(char *)nco_free(fl_pth); if(fl_pth_lcl) fl_pth_lcl=(char *)nco_free(fl_pth_lcl); /* Free lists of strings */ if(fl_lst_in && fl_lst_abb == NULL) fl_lst_in=nco_sng_lst_free(fl_lst_in,fl_nbr); if(fl_lst_in && fl_lst_abb) fl_lst_in=nco_sng_lst_free(fl_lst_in,1); if(fl_lst_abb) fl_lst_abb=nco_sng_lst_free(fl_lst_abb,abb_arg_nbr); if(gaa_nbr > 0) gaa_arg=nco_sng_lst_free(gaa_arg,gaa_nbr); if(var_lst_in_nbr > 0) var_lst_in=nco_sng_lst_free(var_lst_in,var_lst_in_nbr); /* Free limits */ for(idx=0;idx<lmt_nbr;idx++) lmt_arg[idx]=(char *)nco_free(lmt_arg[idx]); for(idx=0;idx<aux_nbr;idx++) aux_arg[idx]=(char *)nco_free(aux_arg[idx]); if(aux_nbr > 0) aux=(lmt_sct **)nco_free(aux); /* Free chunking information */ for(idx=0;idx<cnk_nbr;idx++) cnk_arg[idx]=(char *)nco_free(cnk_arg[idx]); if(cnk_nbr > 0) cnk_dmn=nco_cnk_lst_free(cnk_dmn,cnk_nbr); /* Free dimension lists */ if(nbr_dmn_xtr > 0) dim=nco_dmn_lst_free(dim,nbr_dmn_xtr); if(nbr_dmn_xtr > 0) dmn_out=nco_dmn_lst_free(dmn_out,nbr_dmn_xtr); /* Free variable lists */ /* ncflint free()s _prc variables at end of main loop */ var=(var_sct **)nco_free(var); var_out=(var_sct **)nco_free(var_out); var_prc_out=(var_sct **)nco_free(var_prc_out); if(nbr_var_fix > 0) var_fix=nco_var_lst_free(var_fix,nbr_var_fix); if(nbr_var_fix > 0) var_fix_out=nco_var_lst_free(var_fix_out,nbr_var_fix); } /* !flg_mmr_cln */ #ifdef ENABLE_MPI MPI_Finalize(); #endif /* !ENABLE_MPI */ if(rcd != NC_NOERR) nco_err_exit(rcd,"main"); nco_exit_gracefully(); return EXIT_SUCCESS; } /* end main() */
main.c
/*====================================================================== Maratis Tiny C Library version 1.0 ------------------------------------------------------------------------ Copyright (c) 2015 Anael Seghezzi <www.maratis3d.com> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ========================================================================*/ /* raytracing test */ #define M_MATH_IMPLEMENTATION #define M_IMAGE_IMPLEMENTATION #include <m_math.h> #include <m_image.h> #include "../test.h" #define USE_NOISE /* comment to disable 3d noise (simple sphere raytracing) */ static struct m_image test_buffer = M_IMAGE_IDENTITY(); /* approximative noise */ static struct m_image rand_image = M_IMAGE_IDENTITY(); static struct m_image tmp = M_IMAGE_IDENTITY(); void init_noise(void) { int i; m_image_create(&rand_image, M_FLOAT, 16, 16, 2); for (i = 0; i < rand_image.size; i++) ((float *)rand_image.data)[i] = (float)rand() / (float)RAND_MAX; } void destroy_noise(void) { m_image_destroy(&rand_image); } float fast_noise(float x, float y, float z) { float values[2]; float i = z - floorf(z); m_image_sub_pixel(&rand_image, x + z + 8, y + z + 8, values); return values[0] * (1.0f - i) + values[1] * i; } #define GET_RAY(ray, px, py, pz, hw, hh, ratio)\ {\ float3 pt = {((float)px - hw) / hw, (-((float)py - hh) / hh) * ratio, pz};\ float ptl = 1.0f / M_LENGHT3(pt);\ ray.x = pt.x * ptl;\ ray.y = pt.y * ptl;\ ray.z = pt.z * ptl;\ } static void draw(void) { float *data = (float *)test_buffer.data; int w = test_buffer.width; int h = test_buffer.height; int y; float3 sphere_pos; float3 light_dir; float z_near = 1e-4; float ambient = 0.15f; float sphere_radius2; float sphere_tex_unit; float hw = w * 0.5f; float hh = h * 0.5f; float ratio = (float)test_height / (float)test_width; /* light */ light_dir.x = 0.5f; light_dir.y = 0.25f; light_dir.z = -0.5f; /* sphere */ sphere_radius2 = 150; sphere_pos.x = cosf(test_t * 0.025f) * 20.0f; sphere_pos.y = 0.0f; sphere_pos.z = 50.0f + (sinf(test_t * 0.025f) + 1.0f) * 70.0f; sphere_tex_unit = 0.25f; /* clear */ memset(test_buffer.data, 0, test_buffer.size * sizeof(float)); /* raytrace */ #pragma omp parallel for schedule(dynamic, 8) for (y = 0; y < h; y++) { float *pixel = data + y * w * 3; int x; for (x = 0; x < w; x++) { float3 origin = {0, 0, 0}; float3 ray, march_dir; float march_step; float idist, dist = 0, Z = 1e20; /* get ray from pixel position */ GET_RAY(ray, x, y, 1.35f, hw, hh, ratio); march_step = 0.25f; march_dir.x = ray.x * march_step; march_dir.y = ray.y * march_step; march_dir.z = ray.z * march_step; /* sphere */ m_3d_ray_sphere_intersection_in_out(&origin, &ray, &sphere_pos, sphere_radius2, &dist, &idist); if (dist > z_near) { if (dist < Z) { float3 rd = {ray.x * dist, ray.y * dist, ray.z * dist}; float3 pos = {origin.x + rd.x, origin.y + rd.y, origin.z + rd.z}; /* simple sphere */ #ifndef USE_NOISE { float3 normal; float diffuse; M_SUB3(normal, pos, sphere_pos); M_NORMALIZE3(normal, normal); diffuse = M_DOT3(normal, light_dir); diffuse = M_MAX(0, diffuse); pixel[0] = ambient + diffuse; pixel[1] = ambient + diffuse; pixel[2] = ambient + diffuse; Z = dist; } /* volumetric ray marching inside a sphere (perlin noise test) */ #else { float3 march = pos; /* starting at sphere intersection */ int i; for (i = 0; i < 256; i++) { float3 vcoord = { (march.x - sphere_pos.x) * sphere_tex_unit, (march.y - sphere_pos.y) * sphere_tex_unit, (march.z - sphere_pos.z) * sphere_tex_unit }; float perlin = fast_noise(vcoord.x, vcoord.y, vcoord.z); if (perlin > 0.6f) { /* render */ float3 normal; float diffuse; if (i == 0) { /* sphere normal */ M_SUB3(normal, pos, sphere_pos); M_NORMALIZE3(normal, normal); } else { /* volume normal */ normal.x = perlin - fast_noise(vcoord.x + 0.0001f, vcoord.y, vcoord.z); normal.y = perlin - fast_noise(vcoord.x, vcoord.y + 0.0001f, vcoord.z); normal.z = perlin - fast_noise(vcoord.x, vcoord.y, vcoord.z + 0.0001f); M_NORMALIZE3(normal, normal); } diffuse = M_DOT3(normal, light_dir); diffuse = M_MAX(0, diffuse); pixel[0] = ambient + diffuse; pixel[1] = ambient + diffuse; pixel[2] = ambient + diffuse; Z = dist; break; } /* march */ M_ADD3(march, march, march_dir); dist += march_step; if (dist > idist) /* out of the sphere */ break; } } #endif } } pixel += 3; } } } void main_loop(void) { draw(); test_swap_buffer(&test_buffer); test_update(); } int main(int argc, char **argv) { if (! test_create("M - RaytracingTest", 256, 256)) return EXIT_FAILURE; m_image_create(&test_buffer, M_FLOAT, 256, 256, 3); init_noise(); #ifdef __EMSCRIPTEN__ emscripten_set_main_loop(main_loop, 0, 1); #else while (test_state) { main_loop(); thrd_yield(); } #endif m_image_destroy(&test_buffer); destroy_noise(); test_destroy(); return EXIT_SUCCESS; }
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 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % 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/memory-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/property.h" #include "MagickCore/resample.h" #include "MagickCore/resample-private.h" #include "MagickCore/resource_.h" #include "MagickCore/splay-tree.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 PrimitiveExtentPad 4296.0 #define MaxBezierCoordinates 67108864 #define ThrowPointExpectedException(token,exception) \ { \ (void) ThrowMagickException(exception,GetMagickModule(),DrawError, \ "NonconformingDrawingPrimitiveDefinition","`%s'",token); \ status=MagickFalse; \ break; \ } /* 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 _MVGInfo { PrimitiveInfo **primitive_info; size_t *extent; ssize_t offset; PointInfo point; ExceptionInfo *exception; } MVGInfo; 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 Image *DrawClippingMask(Image *,const DrawInfo *,const char *,const char *, ExceptionInfo *); static MagickBooleanType DrawStrokePolygon(Image *,const DrawInfo *,const PrimitiveInfo *, ExceptionInfo *), RenderMVGContent(Image *,const DrawInfo *,const size_t,ExceptionInfo *), TraceArc(MVGInfo *,const PointInfo,const PointInfo,const PointInfo), TraceArcPath(MVGInfo *,const PointInfo,const PointInfo,const PointInfo, const double,const MagickBooleanType,const MagickBooleanType), TraceBezier(MVGInfo *,const size_t), TraceCircle(MVGInfo *,const PointInfo,const PointInfo), TraceEllipse(MVGInfo *,const PointInfo,const PointInfo,const PointInfo), TraceLine(PrimitiveInfo *,const PointInfo,const PointInfo), TraceRectangle(PrimitiveInfo *,const PointInfo,const PointInfo), TraceRoundRectangle(MVGInfo *,const PointInfo,const PointInfo,PointInfo), TraceSquareLinecap(PrimitiveInfo *,const size_t,const double); static PrimitiveInfo *TraceStrokePolygon(const DrawInfo *,const PrimitiveInfo *,ExceptionInfo *); static ssize_t TracePath(MVGInfo *,const char *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % 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 *) AcquireCriticalMemory(sizeof(*draw_info)); 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 *) AcquireCriticalMemory(sizeof(*clone_info)); GetDrawInfo(image_info,clone_info); if (draw_info == (DrawInfo *) NULL) return(clone_info); exception=AcquireExceptionInfo(); if (draw_info->id != (char *) NULL) (void) CloneString(&clone_info->id,draw_info->id); if (draw_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->compliance=draw_info->compliance; 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) { ssize_t x; for (x=0; fabs(draw_info->dash_pattern[x]) >= MagickEpsilon; x++) ; clone_info->dash_pattern=(double *) AcquireQuantumMemory((size_t) (2*x+2), sizeof(*clone_info->dash_pattern)); if (clone_info->dash_pattern == (double *) NULL) ThrowFatalException(ResourceLimitFatalError, "UnableToAllocateDashPattern"); (void) memset(clone_info->dash_pattern,0,(size_t) (2*x+2)* sizeof(*clone_info->dash_pattern)); (void) memcpy(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) memcpy(clone_info->gradient.stops,draw_info->gradient.stops, (size_t) number_stops*sizeof(*clone_info->gradient.stops)); } clone_info->bounds=draw_info->bounds; 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->clip_path=draw_info->clip_path; clone_info->clip_units=draw_info->clip_units; if (draw_info->clip_mask != (char *) NULL) (void) CloneString(&clone_info->clip_mask,draw_info->clip_mask); if (draw_info->clipping_mask != (Image *) NULL) clone_info->clipping_mask=CloneImage(draw_info->clipping_mask,0,0, MagickTrue,exception); if (draw_info->composite_mask != (Image *) NULL) clone_info->composite_mask=CloneImage(draw_info->composite_mask,0,0, MagickTrue,exception); clone_info->render=draw_info->render; 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 PathInfo *path_info, % ExceptionInfo *excetion) % % A description of each parameter follows: % % o 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. % % */ static PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info) { ssize_t i; if (polygon_info->edges != (EdgeInfo *) NULL) { for (i=0; i < (ssize_t) polygon_info->number_edges; i++) if (polygon_info->edges[i].points != (PointInfo *) NULL) 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)); } #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int DrawCompareEdges(const void *p_edge,const void *q_edge) { #define DrawCompareEdge(p,q) \ { \ if (((p)-(q)) < 0.0) \ return(-1); \ if (((p)-(q)) > 0.0) \ return(1); \ } const PointInfo *p, *q; /* Edge sorting for right-handed coordinate system. */ p=((const EdgeInfo *) p_edge)->points; q=((const EdgeInfo *) q_edge)->points; DrawCompareEdge(p[0].y,q[0].y); DrawCompareEdge(p[0].x,q[0].x); DrawCompareEdge((p[1].x-p[0].x)*(q[1].y-q[0].y),(p[1].y-p[0].y)* (q[1].x-q[0].x)); DrawCompareEdge(p[1].y,q[1].y); DrawCompareEdge(p[1].x,q[1].x); return(0); } #if defined(__cplusplus) || defined(c_plusplus) } #endif static void LogPolygonInfo(const PolygonInfo *polygon_info) { EdgeInfo *p; 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; 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, ExceptionInfo *exception) { long direction, next_direction; PointInfo point, *points; PolygonInfo *polygon_info; SegmentInfo bounds; 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) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return((PolygonInfo *) NULL); } number_edges=16; polygon_info->edges=(EdgeInfo *) AcquireQuantumMemory(number_edges, sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonInfo(polygon_info)); } (void) memset(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) memset(&point,0,sizeof(point)); (void) memset(&bounds,0,sizeof(bounds)); polygon_info->edges[edge].number_points=(size_t) n; polygon_info->edges[edge].scanline=0.0; polygon_info->edges[edge].highwater=0; polygon_info->edges[edge].ghostline=ghostline; polygon_info->edges[edge].direction=(ssize_t) direction; polygon_info->edges[edge].points=points; polygon_info->edges[edge].bounds=bounds; polygon_info->number_edges=0; 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) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); points=(PointInfo *) RelinquishMagickMemory(points); return(DestroyPolygonInfo(polygon_info)); } } 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++; polygon_info->number_edges=edge; } if (points == (PointInfo *) NULL) { number_points=16; points=(PointInfo *) AcquireQuantumMemory((size_t) number_points, sizeof(*points)); if (points == (PointInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonInfo(polygon_info)); } } 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) < MagickEpsilon) && (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) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); points=(PointInfo *) RelinquishMagickMemory(points); return(DestroyPolygonInfo(polygon_info)); } } 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; polygon_info->number_edges=edge+1; points=(PointInfo *) NULL; number_points=16; points=(PointInfo *) AcquireQuantumMemory((size_t) number_points, sizeof(*points)); if (points == (PointInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonInfo(polygon_info)); } 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) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonInfo(polygon_info)); } } 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) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonInfo(polygon_info)); } } 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++; polygon_info->number_edges=edge; } } polygon_info->number_edges=edge; polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(polygon_info->edges, polygon_info->number_edges,sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonInfo(polygon_info)); } for (i=0; i < (ssize_t) polygon_info->number_edges; i++) { EdgeInfo *edge_info; edge_info=polygon_info->edges+i; edge_info->points=(PointInfo *) ResizeQuantumMemory(edge_info->points, edge_info->number_points,sizeof(*edge_info->points)); if (edge_info->points == (PointInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonInfo(polygon_info)); } } qsort(polygon_info->edges,(size_t) polygon_info->number_edges, sizeof(*polygon_info->edges),DrawCompareEdges); 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,ExceptionInfo *exception) % % A description of each parameter follows: % % o 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) { 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, ExceptionInfo *exception) { MagickBooleanType closed_subpath; PathInfo *path_info; PathInfoCode code; PointInfo p, q; 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) (3UL*i+1UL), sizeof(*path_info)); if (path_info == (PathInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return((PathInfo *) NULL); } coordinates=0; closed_subpath=MagickFalse; 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) { /* New subpath. */ coordinates=(ssize_t) primitive_info[i].coordinates; p=primitive_info[i].point; start=n; code=MoveToCode; closed_subpath=primitive_info[i].closed_subpath; } coordinates--; if ((code == MoveToCode) || (coordinates <= 0) || (fabs(q.x-primitive_info[i].point.x) >= MagickEpsilon) || (fabs(q.y-primitive_info[i].point.y) >= MagickEpsilon)) { /* Eliminate duplicate points. */ path_info[n].code=code; path_info[n].point=primitive_info[i].point; q=primitive_info[i].point; n++; } if (coordinates > 0) continue; /* next point in current subpath */ if (closed_subpath != MagickFalse) { closed_subpath=MagickFalse; continue; } /* Mark the p point as open if the subpath is not closed. */ 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); path_info=(PathInfo *) ResizeQuantumMemory(path_info,(size_t) (n+1), sizeof(*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) { assert(draw_info != (DrawInfo *) NULL); if (draw_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(draw_info->signature == MagickCoreSignature); if (draw_info->id != (char *) NULL) draw_info->id=DestroyString(draw_info->id); 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); if (draw_info->clipping_mask != (Image *) NULL) draw_info->clipping_mask=DestroyImage(draw_info->clipping_mask); if (draw_info->composite_mask != (Image *) NULL) draw_info->composite_mask=DestroyImage(draw_info->composite_mask); draw_info->signature=(~MagickCoreSignature); draw_info=(DrawInfo *) RelinquishMagickMemory(draw_info); return(draw_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; 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 >= MagickEpsilon) { 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 < -MagickEpsilon) { 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 >= MagickEpsilon) { 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 < -MagickEpsilon) { 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; 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=CastDoubleToLong(ceil(edge.y1-0.5)); stop=CastDoubleToLong(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) shared(status) \ magick_number_threads(source,image,stop-start,1) #endif for (y=start; y <= stop; y++) { PixelInfo composite, pixel; PointInfo point; ssize_t x; Quantum *magick_restrict q; SegmentInfo inverse_edge; ssize_t x_offset; if (status == MagickFalse) continue; inverse_edge=AffineEdge(source,&inverse_affine,(double) y,&edge); if (inverse_edge.x2 < inverse_edge.x1) continue; q=GetCacheViewAuthenticPixels(image_view,CastDoubleToLong( ceil(inverse_edge.x1-0.5)),y,(size_t) CastDoubleToLong(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=CastDoubleToLong(ceil(inverse_edge.x1-0.5)); x <= CastDoubleToLong(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; status=InterpolatePixelInfo(source,source_view,UndefinedInterpolatePixel, point.x,point.y,&pixel,exception); if (status == MagickFalse) break; 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: % % MagickBooleanType 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 MagickBooleanType DrawBoundingRectangles(Image *image, const DrawInfo *draw_info,const PolygonInfo *polygon_info, ExceptionInfo *exception) { double mid; DrawInfo *clone_info; MagickStatusType status; PointInfo end, resolution, start; PrimitiveInfo primitive_info[6]; ssize_t i; SegmentInfo bounds; ssize_t coordinates; (void) memset(primitive_info,0,sizeof(primitive_info)); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); status=QueryColorCompliance("#000F",AllCompliance,&clone_info->fill, exception); if (status == MagickFalse) { clone_info=DestroyDrawInfo(clone_info); return(MagickFalse); } resolution.x=96.0; resolution.y=96.0; if (clone_info->density != (char *) NULL) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(clone_info->density,&geometry_info); if ((flags & RhoValue) != 0) resolution.x=geometry_info.rho; resolution.y=resolution.x; if ((flags & SigmaValue) != 0) resolution.y=geometry_info.sigma; } mid=(resolution.x/96.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) status=QueryColorCompliance("#f00",AllCompliance,&clone_info->stroke, exception); else status=QueryColorCompliance("#0f0",AllCompliance,&clone_info->stroke, exception); if (status == MagickFalse) break; 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; status&=TraceRectangle(primitive_info,start,end); primitive_info[0].method=ReplaceMethod; coordinates=(ssize_t) primitive_info[0].coordinates; primitive_info[coordinates].primitive=UndefinedPrimitive; status=DrawPrimitive(image,clone_info,primitive_info,exception); if (status == MagickFalse) break; } if (i < (ssize_t) polygon_info->number_edges) { clone_info=DestroyDrawInfo(clone_info); return(status == 0 ? MagickFalse : MagickTrue); } } status=QueryColorCompliance("#00f",AllCompliance,&clone_info->stroke, exception); if (status == MagickFalse) { clone_info=DestroyDrawInfo(clone_info); return(MagickFalse); } 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; status&=TraceRectangle(primitive_info,start,end); primitive_info[0].method=ReplaceMethod; coordinates=(ssize_t) primitive_info[0].coordinates; primitive_info[coordinates].primitive=UndefinedPrimitive; status=DrawPrimitive(image,clone_info,primitive_info,exception); clone_info=DestroyDrawInfo(clone_info); return(status == 0 ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % 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 *id,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o id: the clip path id. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType DrawClipPath(Image *image, const DrawInfo *draw_info,const char *id,ExceptionInfo *exception) { const char *clip_path; Image *clipping_mask; MagickBooleanType status; clip_path=GetImageArtifact(image,id); if (clip_path == (const char *) NULL) return(MagickFalse); clipping_mask=DrawClippingMask(image,draw_info,draw_info->clip_mask,clip_path, exception); if (clipping_mask == (Image *) NULL) return(MagickFalse); status=SetImageMask(image,WritePixelMask,clipping_mask,exception); clipping_mask=DestroyImage(clipping_mask); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w C l i p p i n g M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawClippingMask() draws the clip path and returns it as an image clipping % mask. % % The format of the DrawClippingMask method is: % % Image *DrawClippingMask(Image *image,const DrawInfo *draw_info, % const char *id,const char *clip_path,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o id: the clip path id. % % o clip_path: the clip path. % % o exception: return any errors or warnings in this structure. % */ static Image *DrawClippingMask(Image *image,const DrawInfo *draw_info, const char *id,const char *clip_path,ExceptionInfo *exception) { DrawInfo *clone_info; Image *clip_mask, *separate_mask; MagickStatusType status; /* Draw a clip path. */ 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); clip_mask=AcquireImage((const ImageInfo *) NULL,exception); status=SetImageExtent(clip_mask,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImage(clip_mask)); status=SetImageMask(clip_mask,WritePixelMask,(Image *) NULL,exception); status=QueryColorCompliance("#0000",AllCompliance, &clip_mask->background_color,exception); clip_mask->background_color.alpha=(MagickRealType) TransparentAlpha; clip_mask->background_color.alpha_trait=BlendPixelTrait; status=SetImageBackgroundColor(clip_mask,exception); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"\nbegin clip-path %s", id); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); (void) CloneString(&clone_info->primitive,clip_path); status=QueryColorCompliance("#ffffff",AllCompliance,&clone_info->fill, exception); if (clone_info->clip_mask != (char *) NULL) clone_info->clip_mask=DestroyString(clone_info->clip_mask); status=QueryColorCompliance("#00000000",AllCompliance,&clone_info->stroke, exception); clone_info->stroke_width=0.0; clone_info->alpha=OpaqueAlpha; clone_info->clip_path=MagickTrue; status=RenderMVGContent(clip_mask,clone_info,0,exception); clone_info=DestroyDrawInfo(clone_info); separate_mask=SeparateImage(clip_mask,AlphaChannel,exception); if (separate_mask == (Image *) NULL) status=MagickFalse; else { clip_mask=DestroyImage(clip_mask); clip_mask=separate_mask; status&=NegateImage(clip_mask,MagickFalse,exception); } if (status == MagickFalse) clip_mask=DestroyImage(clip_mask); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end clip-path"); return(clip_mask); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w C o m p o s i t e M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawCompositeMask() draws the mask path and returns it as an image mask. % % The format of the DrawCompositeMask method is: % % Image *DrawCompositeMask(Image *image,const DrawInfo *draw_info, % const char *id,const char *mask_path,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o id: the mask path id. % % o mask_path: the mask path. % % o exception: return any errors or warnings in this structure. % */ static Image *DrawCompositeMask(Image *image,const DrawInfo *draw_info, const char *id,const char *mask_path,ExceptionInfo *exception) { Image *composite_mask, *separate_mask; DrawInfo *clone_info; MagickStatusType status; /* Draw a mask path. */ 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); composite_mask=AcquireImage((const ImageInfo *) NULL,exception); status=SetImageExtent(composite_mask,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImage(composite_mask)); status=SetImageMask(composite_mask,CompositePixelMask,(Image *) NULL, exception); status=QueryColorCompliance("#0000",AllCompliance, &composite_mask->background_color,exception); composite_mask->background_color.alpha=(MagickRealType) TransparentAlpha; composite_mask->background_color.alpha_trait=BlendPixelTrait; (void) SetImageBackgroundColor(composite_mask,exception); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"\nbegin mask-path %s", id); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); (void) CloneString(&clone_info->primitive,mask_path); status=QueryColorCompliance("#ffffff",AllCompliance,&clone_info->fill, exception); status=QueryColorCompliance("#00000000",AllCompliance,&clone_info->stroke, exception); clone_info->stroke_width=0.0; clone_info->alpha=OpaqueAlpha; status=RenderMVGContent(composite_mask,clone_info,0,exception); clone_info=DestroyDrawInfo(clone_info); separate_mask=SeparateImage(composite_mask,AlphaChannel,exception); if (separate_mask != (Image *) NULL) { composite_mask=DestroyImage(composite_mask); composite_mask=separate_mask; status=NegateImage(composite_mask,MagickFalse,exception); if (status == MagickFalse) composite_mask=DestroyImage(composite_mask); } if (status == MagickFalse) composite_mask=DestroyImage(composite_mask); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end mask-path"); return(composite_mask); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + 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) { double length, maximum_length, offset, scale, total_length; DrawInfo *clone_info; MagickStatusType status; PrimitiveInfo *dash_polygon; double dx, dy; ssize_t i; 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+32UL),sizeof(*dash_polygon)); if (dash_polygon == (PrimitiveInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } (void) memset(dash_polygon,0,(2UL*number_vertices+32UL)* sizeof(*dash_polygon)); 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]; offset=fabs(draw_info->dash_offset) >= MagickEpsilon ? 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]; 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(dx,dy); if (maximum_length > (double) (MaxBezierCoordinates >> 2)) continue; if (fabs(length) < MagickEpsilon) { if (fabs(draw_info->dash_pattern[n]) >= MagickEpsilon) n++; if (fabs(draw_info->dash_pattern[n]) < MagickEpsilon) n=0; length=scale*draw_info->dash_pattern[n]; } 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*PerceptibleReciprocal(maximum_length)); dash_polygon[0].point.y=(double) (primitive_info[i-1].point.y+dy* total_length*PerceptibleReciprocal(maximum_length)); j=1; } else { if ((j+1) > (ssize_t) 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*PerceptibleReciprocal(maximum_length)); dash_polygon[j].point.y=(double) (primitive_info[i-1].point.y+dy* total_length*PerceptibleReciprocal(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); if (status == MagickFalse) break; } if (fabs(draw_info->dash_pattern[n]) >= MagickEpsilon) n++; if (fabs(draw_info->dash_pattern[n]) < MagickEpsilon) n=0; length=scale*draw_info->dash_pattern[n]; } length-=(maximum_length-total_length); if ((n & 0x01) != 0) continue; dash_polygon[j]=primitive_info[i]; dash_polygon[j].coordinates=1; j++; } if ((status != MagickFalse) && (total_length < maximum_length) && ((n & 0x01) == 0) && (j > 1)) { dash_polygon[j]=primitive_info[i-1]; dash_polygon[j].point.x+=MagickEpsilon; dash_polygon[j].point.y+=MagickEpsilon; 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 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))))*PerceptibleReciprocal(gradient->radii.x); v.y=(double) (((x-gradient->center.x)*sin(DegreesToRadians( gradient->angle)))-((y-gradient->center.y)*cos(DegreesToRadians( gradient->angle))))*PerceptibleReciprocal(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) <= MagickEpsilon) 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) shared(status) \ magick_number_threads(image,image,bounding_box.height-bounding_box.y,1) #endif for (y=bounding_box.y; y < (ssize_t) bounding_box.height; y++) { double alpha, offset; PixelInfo composite, pixel; Quantum *magick_restrict q; 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*=PerceptibleReciprocal(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 != CastDoubleToLong(ceil(gradient_vector->x1-0.5))) || (y != CastDoubleToLong(ceil(gradient_vector->y1-0.5)))) { offset=GetStopColorOffset(gradient,x,y); if (gradient->type != RadialGradient) offset*=PerceptibleReciprocal(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 != CastDoubleToLong(ceil(gradient_vector->x1-0.5))) || (y != CastDoubleToLong(ceil(gradient_vector->y1-0.5)))) { offset=GetStopColorOffset(gradient,x,y); if (gradient->type != RadialGradient) offset*=PerceptibleReciprocal(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: { double repeat; MagickBooleanType antialias; antialias=MagickFalse; repeat=0.0; if ((x != CastDoubleToLong(ceil(gradient_vector->x1-0.5))) || (y != CastDoubleToLong(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=PerceptibleReciprocal(length)*repeat; } 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*PerceptibleReciprocal(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 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 MagickBooleanType CheckPrimitiveExtent(MVGInfo *mvg_info, const double pad) { char *text = (char *) NULL; double extent; size_t quantum; ssize_t i; /* Check if there is enough storage for drawing primitives. */ quantum=sizeof(**mvg_info->primitive_info); extent=(double) mvg_info->offset+pad+(PrimitiveExtentPad+1)*(double) quantum; if (extent <= (double) *mvg_info->extent) return(MagickTrue); if ((extent >= (double) MAGICK_SSIZE_MAX) || (IsNaN(extent) != 0)) return(MagickFalse); for (i=0; i < mvg_info->offset; i++) if (((*mvg_info->primitive_info)[i].primitive == TextPrimitive) || ((*mvg_info->primitive_info)[i].primitive == ImagePrimitive)) if ((*mvg_info->primitive_info)[i].text != (char *) NULL) text=(*mvg_info->primitive_info)[i].text; *mvg_info->primitive_info=(PrimitiveInfo *) ResizeQuantumMemory( *mvg_info->primitive_info,(size_t) (extent+1),quantum); if (*mvg_info->primitive_info != (PrimitiveInfo *) NULL) { *mvg_info->extent=(size_t) extent; for (i=mvg_info->offset+1; i <= (ssize_t) extent; i++) { (*mvg_info->primitive_info)[i].primitive=UndefinedPrimitive; (*mvg_info->primitive_info)[i].text=(char *) NULL; } return(MagickTrue); } /* Reallocation failed, allocate a primitive to facilitate unwinding. */ (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); *mvg_info->primitive_info=(PrimitiveInfo *) AcquireCriticalMemory((size_t) (PrimitiveExtentPad+1)*quantum); (void) memset(*mvg_info->primitive_info,0,(size_t) ((PrimitiveExtentPad+1)* quantum)); *mvg_info->extent=1; (*mvg_info->primitive_info)[0].text=text; mvg_info->offset=0; return(MagickFalse); } static inline double GetDrawValue(const char *magick_restrict string, char **magick_restrict sentinal) { char **magick_restrict q; double value; q=sentinal; value=InterpretLocaleValue(string,q); sentinal=q; return(value); } static int MVGMacroCompare(const void *target,const void *source) { const char *p, *q; p=(const char *) target; q=(const char *) source; return(strcmp(p,q)); } static SplayTreeInfo *GetMVGMacros(const char *primitive) { char *macro, *token; const char *q; size_t extent; SplayTreeInfo *macros; /* Scan graphic primitives for definitions and classes. */ if (primitive == (const char *) NULL) return((SplayTreeInfo *) NULL); macros=NewSplayTree(MVGMacroCompare,RelinquishMagickMemory, RelinquishMagickMemory); macro=AcquireString(primitive); token=AcquireString(primitive); extent=strlen(token)+MagickPathExtent; for (q=primitive; *q != '\0'; ) { if (GetNextToken(q,&q,extent,token) < 1) break; if (*token == '\0') break; if (LocaleCompare("push",token) == 0) { const char *end, *start; (void) GetNextToken(q,&q,extent,token); if (*q == '"') { char name[MagickPathExtent]; const char *p; ssize_t n; /* Named macro (e.g. push graphic-context "wheel"). */ (void) GetNextToken(q,&q,extent,token); start=q; end=q; (void) CopyMagickString(name,token,MagickPathExtent); n=1; for (p=q; *p != '\0'; ) { if (GetNextToken(p,&p,extent,token) < 1) break; if (*token == '\0') break; if (LocaleCompare(token,"pop") == 0) { end=p-strlen(token)-1; n--; } if (LocaleCompare(token,"push") == 0) n++; if ((n == 0) && (end > start)) { /* Extract macro. */ (void) GetNextToken(p,&p,extent,token); (void) CopyMagickString(macro,start,(size_t) (end-start)); (void) AddValueToSplayTree(macros,ConstantString(name), ConstantString(macro)); break; } } } } } token=DestroyString(token); macro=DestroyString(macro); return(macros); } static inline MagickBooleanType IsPoint(const char *point) { char *p; double value; value=GetDrawValue(point,&p); return((fabs(value) < MagickEpsilon) && (p == point) ? MagickFalse : MagickTrue); } static inline MagickBooleanType TracePoint(PrimitiveInfo *primitive_info, const PointInfo point) { primitive_info->coordinates=1; primitive_info->closed_subpath=MagickFalse; primitive_info->point=point; return(MagickTrue); } static MagickBooleanType RenderMVGContent(Image *image, const DrawInfo *draw_info,const size_t depth,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, coordinates, cursor, factor, primitive_extent; DrawInfo *clone_info, **graphic_context; MagickBooleanType proceed; MagickStatusType status; MVGInfo mvg_info; PointInfo point; PrimitiveInfo *primitive_info; PrimitiveType primitive_type; const char *p; ssize_t i, x; SegmentInfo bounds; size_t extent, number_points, number_stops; SplayTreeInfo *macros; ssize_t defsDepth, j, k, n, symbolDepth; StopInfo *stops; TypeMetric metrics; 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 (depth > MagickMaxRecursionDepth) ThrowBinaryException(DrawError,"VectorGraphicsNestedTooDeeply", image->filename); if ((draw_info->primitive == (char *) NULL) || (*draw_info->primitive == '\0')) return(MagickFalse); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"begin draw-image"); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (image->alpha_trait == UndefinedPixelTrait) { status=SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); if (status == MagickFalse) return(MagickFalse); } if ((*draw_info->primitive == '@') && (strlen(draw_info->primitive) > 1) && (*(draw_info->primitive+1) != '-') && (depth == 0)) primitive=FileToString(draw_info->primitive+1,~0UL,exception); else primitive=AcquireString(draw_info->primitive); if (primitive == (char *) NULL) return(MagickFalse); primitive_extent=(double) strlen(primitive); (void) SetImageArtifact(image,"mvg:vector-graphics",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=(size_t) PrimitiveExtentPad; primitive_info=(PrimitiveInfo *) AcquireQuantumMemory((size_t) (number_points+1),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); } (void) memset(primitive_info,0,(size_t) (number_points+1)* sizeof(*primitive_info)); (void) memset(&mvg_info,0,sizeof(mvg_info)); mvg_info.primitive_info=(&primitive_info); mvg_info.extent=(&number_points); mvg_info.exception=exception; 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; defsDepth=0; symbolDepth=0; cursor=0.0; macros=GetMVGMacros(primitive); status=MagickTrue; for (q=primitive; *q != '\0'; ) { /* Interpret graphic primitive. */ if (GetNextToken(q,&q,MagickPathExtent,keyword) < 1) break; 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); *token='\0'; switch (*keyword) { case ';': break; case 'a': case 'A': { if (LocaleCompare("affine",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); affine.sx=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); affine.rx=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); affine.ry=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); affine.sy=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); affine.tx=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); affine.ty=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); 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) { (void) GetNextToken(q,&q,extent,token); status&=QueryColorCompliance(token,AllCompliance, &graphic_context[n]->border_color,exception); break; } status=MagickFalse; break; } case 'c': case 'C': { if (LocaleCompare("class",keyword) == 0) { const char *mvg_class; (void) GetNextToken(q,&q,extent,token); if (*token == '\0') { status=MagickFalse; break; } if (LocaleCompare(token,graphic_context[n]->id) == 0) break; mvg_class=(const char *) GetValueFromSplayTree(macros,token); if ((graphic_context[n]->render != MagickFalse) && (mvg_class != (const char *) NULL) && (p > primitive)) { char *elements; ssize_t offset; /* Inject class elements in stream. */ offset=(ssize_t) (p-primitive); elements=AcquireString(primitive); elements[offset]='\0'; (void) ConcatenateString(&elements,mvg_class); (void) ConcatenateString(&elements,"\n"); (void) ConcatenateString(&elements,q); primitive=DestroyString(primitive); primitive=elements; q=primitive+offset; } break; } if (LocaleCompare("clip-path",keyword) == 0) { const char *clip_path; /* Take a node from within the MVG document, and duplicate it here. */ (void) GetNextToken(q,&q,extent,token); if (*token == '\0') { status=MagickFalse; break; } (void) CloneString(&graphic_context[n]->clip_mask,token); clip_path=(const char *) GetValueFromSplayTree(macros,token); if (clip_path != (const char *) NULL) { if (graphic_context[n]->clipping_mask != (Image *) NULL) graphic_context[n]->clipping_mask= DestroyImage(graphic_context[n]->clipping_mask); graphic_context[n]->clipping_mask=DrawClippingMask(image, graphic_context[n],token,clip_path,exception); if (graphic_context[n]->compliance != SVGCompliance) { clip_path=(const char *) GetValueFromSplayTree(macros, graphic_context[n]->clip_mask); if (clip_path != (const char *) NULL) (void) SetImageArtifact(image, graphic_context[n]->clip_mask,clip_path); status&=DrawClipPath(image,graphic_context[n], graphic_context[n]->clip_mask,exception); } } break; } if (LocaleCompare("clip-rule",keyword) == 0) { ssize_t fill_rule; (void) GetNextToken(q,&q,extent,token); fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse, token); if (fill_rule == -1) { status=MagickFalse; break; } graphic_context[n]->fill_rule=(FillRule) fill_rule; break; } if (LocaleCompare("clip-units",keyword) == 0) { ssize_t clip_units; (void) 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; } if (LocaleCompare("compliance",keyword) == 0) { /* MVG compliance associates a clipping mask with an image; SVG compliance associates a clipping mask with a graphics context. */ (void) GetNextToken(q,&q,extent,token); graphic_context[n]->compliance=(ComplianceType) ParseCommandOption( MagickComplianceOptions,MagickFalse,token); break; } if (LocaleCompare("currentColor",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); break; } status=MagickFalse; break; } case 'd': case 'D': { if (LocaleCompare("decorate",keyword) == 0) { ssize_t decorate; (void) GetNextToken(q,&q,extent,token); decorate=ParseCommandOption(MagickDecorateOptions,MagickFalse, token); if (decorate == -1) { status=MagickFalse; break; } graphic_context[n]->decorate=(DecorationType) decorate; break; } if (LocaleCompare("density",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->density,token); break; } if (LocaleCompare("direction",keyword) == 0) { ssize_t direction; (void) 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) { (void) 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) { const char *mvg_class; (void) GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; mvg_class=(const char *) GetValueFromSplayTree(macros,token); if (mvg_class != (const char *) NULL) { (void) DrawPatternPath(image,draw_info,mvg_class, &graphic_context[n]->fill_pattern,exception); break; } (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); break; } 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; break; } if (LocaleCompare("fill-opacity",keyword) == 0) { double opacity; (void) GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; opacity=MagickMin(MagickMax(factor* GetDrawValue(token,&next_token),0.0),1.0); if (token == next_token) ThrowPointExpectedException(token,exception); if (graphic_context[n]->compliance == SVGCompliance) graphic_context[n]->fill_alpha*=opacity; else graphic_context[n]->fill_alpha=QuantumRange*opacity; if (graphic_context[n]->fill.alpha != TransparentAlpha) graphic_context[n]->fill.alpha=graphic_context[n]->fill_alpha; else graphic_context[n]->fill.alpha=(MagickRealType) ClampToQuantum(QuantumRange*(1.0-opacity)); break; } if (LocaleCompare("fill-rule",keyword) == 0) { ssize_t fill_rule; (void) GetNextToken(q,&q,extent,token); fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse, token); if (fill_rule == -1) { status=MagickFalse; break; } graphic_context[n]->fill_rule=(FillRule) fill_rule; break; } if (LocaleCompare("font",keyword) == 0) { (void) 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) { (void) GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->family,token); break; } if (LocaleCompare("font-size",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->pointsize=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("font-stretch",keyword) == 0) { ssize_t stretch; (void) GetNextToken(q,&q,extent,token); stretch=ParseCommandOption(MagickStretchOptions,MagickFalse,token); if (stretch == -1) { status=MagickFalse; break; } graphic_context[n]->stretch=(StretchType) stretch; break; } if (LocaleCompare("font-style",keyword) == 0) { ssize_t style; (void) GetNextToken(q,&q,extent,token); style=ParseCommandOption(MagickStyleOptions,MagickFalse,token); if (style == -1) { status=MagickFalse; break; } graphic_context[n]->style=(StyleType) style; break; } if (LocaleCompare("font-weight",keyword) == 0) { ssize_t weight; (void) 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) { (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("gravity",keyword) == 0) { ssize_t gravity; (void) GetNextToken(q,&q,extent,token); gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,token); if (gravity == -1) { status=MagickFalse; break; } 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; (void) GetNextToken(q,&q,extent,token); compose=ParseCommandOption(MagickComposeOptions,MagickFalse,token); if (compose == -1) { status=MagickFalse; break; } graphic_context[n]->compose=(CompositeOperator) compose; break; } if (LocaleCompare("interline-spacing",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->interline_spacing=GetDrawValue(token, &next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("interword-spacing",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->interword_spacing=GetDrawValue(token, &next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } status=MagickFalse; break; } case 'k': case 'K': { if (LocaleCompare("kerning",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->kerning=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } status=MagickFalse; break; } case 'l': case 'L': { if (LocaleCompare("letter-spacing",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); if (IsPoint(token) == MagickFalse) break; clone_info=CloneDrawInfo((ImageInfo *) NULL,graphic_context[n]); clone_info->text=AcquireString(" "); status&=GetTypeMetrics(image,clone_info,&metrics,exception); graphic_context[n]->kerning=metrics.width* GetDrawValue(token,&next_token); clone_info=DestroyDrawInfo(clone_info); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("line",keyword) == 0) { primitive_type=LinePrimitive; break; } status=MagickFalse; break; } case 'm': case 'M': { if (LocaleCompare("mask",keyword) == 0) { const char *mask_path; /* Take a node from within the MVG document, and duplicate it here. */ (void) GetNextToken(q,&q,extent,token); mask_path=(const char *) GetValueFromSplayTree(macros,token); if (mask_path != (const char *) NULL) { if (graphic_context[n]->composite_mask != (Image *) NULL) graphic_context[n]->composite_mask= DestroyImage(graphic_context[n]->composite_mask); graphic_context[n]->composite_mask=DrawCompositeMask(image, graphic_context[n],token,mask_path,exception); if (graphic_context[n]->compliance != SVGCompliance) status=SetImageMask(image,CompositePixelMask, graphic_context[n]->composite_mask,exception); } break; } status=MagickFalse; break; } case 'o': case 'O': { if (LocaleCompare("offset",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("opacity",keyword) == 0) { double opacity; (void) GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; opacity=MagickMin(MagickMax(factor* GetDrawValue(token,&next_token),0.0),1.0); if (token == next_token) ThrowPointExpectedException(token,exception); if (graphic_context[n]->compliance == SVGCompliance) { graphic_context[n]->fill_alpha*=opacity; graphic_context[n]->stroke_alpha*=opacity; } else { graphic_context[n]->fill_alpha=QuantumRange*opacity; graphic_context[n]->stroke_alpha=QuantumRange*opacity; } 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) { if (GetNextToken(q,&q,extent,token) < 1) break; if (LocaleCompare("class",token) == 0) break; if (LocaleCompare("clip-path",token) == 0) break; if (LocaleCompare("defs",token) == 0) { defsDepth--; graphic_context[n]->render=defsDepth > 0 ? MagickFalse : MagickTrue; 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) && (graphic_context[n]->compliance != SVGCompliance)) if (LocaleCompare(graphic_context[n]->clip_mask, graphic_context[n-1]->clip_mask) != 0) status=SetImageMask(image,WritePixelMask,(Image *) NULL, exception); graphic_context[n]=DestroyDrawInfo(graphic_context[n]); n--; break; } if (LocaleCompare("mask",token) == 0) break; if (LocaleCompare("pattern",token) == 0) break; if (LocaleCompare("symbol",token) == 0) { symbolDepth--; graphic_context[n]->render=symbolDepth > 0 ? MagickFalse : MagickTrue; break; } status=MagickFalse; break; } if (LocaleCompare("push",keyword) == 0) { if (GetNextToken(q,&q,extent,token) < 1) break; if (LocaleCompare("class",token) == 0) { /* Class context. */ for (p=q; *q != '\0'; ) { if (GetNextToken(q,&q,extent,token) < 1) break; if (LocaleCompare(token,"pop") != 0) continue; (void) GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"class") != 0) continue; break; } (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("clip-path",token) == 0) { (void) GetNextToken(q,&q,extent,token); for (p=q; *q != '\0'; ) { if (GetNextToken(q,&q,extent,token) < 1) break; if (LocaleCompare(token,"pop") != 0) continue; (void) GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"clip-path") != 0) continue; break; } if ((q == (char *) NULL) || (p == (char *) NULL) || ((q-4) < p)) { status=MagickFalse; break; } (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("defs",token) == 0) { defsDepth++; graphic_context[n]->render=defsDepth > 0 ? MagickFalse : MagickTrue; break; } if (LocaleCompare("gradient",token) == 0) { char key[2*MagickPathExtent], name[MagickPathExtent], type[MagickPathExtent]; SegmentInfo segment; (void) GetNextToken(q,&q,extent,token); (void) CopyMagickString(name,token,MagickPathExtent); (void) GetNextToken(q,&q,extent,token); (void) CopyMagickString(type,token,MagickPathExtent); (void) GetNextToken(q,&q,extent,token); segment.x1=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); segment.y1=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); segment.x2=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); segment.y2=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); if (LocaleCompare(type,"radial") == 0) { (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); } for (p=q; *q != '\0'; ) { if (GetNextToken(q,&q,extent,token) < 1) break; if (LocaleCompare(token,"pop") != 0) continue; (void) GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"gradient") != 0) continue; break; } if ((q == (char *) NULL) || (p == (char *) NULL) || ((q-4) < p)) { status=MagickFalse; 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); (void) 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]); if (*q == '"') { (void) GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->id,token); } break; } if (LocaleCompare("mask",token) == 0) { (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("pattern",token) == 0) { char key[2*MagickPathExtent], name[MagickPathExtent]; RectangleInfo region; (void) GetNextToken(q,&q,extent,token); (void) CopyMagickString(name,token,MagickPathExtent); (void) GetNextToken(q,&q,extent,token); region.x=CastDoubleToLong(ceil(GetDrawValue(token, &next_token)-0.5)); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); region.y=CastDoubleToLong(ceil(GetDrawValue(token, &next_token)-0.5)); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); region.width=(size_t) CastDoubleToLong(floor(GetDrawValue( token,&next_token)+0.5)); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); region.height=(size_t) floor(GetDrawValue(token,&next_token)+ 0.5); if (token == next_token) ThrowPointExpectedException(token,exception); for (p=q; *q != '\0'; ) { if (GetNextToken(q,&q,extent,token) < 1) break; if (LocaleCompare(token,"pop") != 0) continue; (void) GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"pattern") != 0) continue; break; } if ((q == (char *) NULL) || (p == (char *) NULL) || ((q-4) < p)) { status=MagickFalse; 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) region.width,(double) region.height,(double) region.x,(double) region.y); (void) SetImageArtifact(image,key,geometry); (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("symbol",token) == 0) { symbolDepth++; graphic_context[n]->render=symbolDepth > 0 ? MagickFalse : MagickTrue; 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) { (void) GetNextToken(q,&q,extent,token); angle=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); 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) { (void) GetNextToken(q,&q,extent,token); affine.sx=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); affine.sy=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("skewX",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); angle=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); affine.ry=sin(DegreesToRadians(angle)); break; } if (LocaleCompare("skewY",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); angle=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); 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; } (void) GetNextToken(q,&q,extent,token); status&=QueryColorCompliance(token,AllCompliance,&stop_color, exception); stops[number_stops-1].color=stop_color; (void) GetNextToken(q,&q,extent,token); factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; stops[number_stops-1].offset=factor*GetDrawValue(token, &next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("stroke",keyword) == 0) { const char *mvg_class; (void) GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; mvg_class=(const char *) GetValueFromSplayTree(macros,token); if (mvg_class != (const char *) NULL) { (void) DrawPatternPath(image,draw_info,mvg_class, &graphic_context[n]->stroke_pattern,exception); break; } (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); break; } 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; break; } if (LocaleCompare("stroke-antialias",keyword) == 0) { (void) 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; (void) GetNextToken(r,&r,extent,token); if (*token == ',') (void) GetNextToken(r,&r,extent,token); for (x=0; IsPoint(token) != MagickFalse; x++) { (void) GetNextToken(r,&r,extent,token); if (*token == ',') (void) GetNextToken(r,&r,extent,token); } graphic_context[n]->dash_pattern=(double *) AcquireQuantumMemory((size_t) (2*x+2), 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; } (void) memset(graphic_context[n]->dash_pattern,0,(size_t) (2*x+2)*sizeof(*graphic_context[n]->dash_pattern)); for (j=0; j < x; j++) { (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); graphic_context[n]->dash_pattern[j]=GetDrawValue(token, &next_token); if (token == next_token) ThrowPointExpectedException(token,exception); 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; } (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("stroke-dashoffset",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->dash_offset=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("stroke-linecap",keyword) == 0) { ssize_t linecap; (void) GetNextToken(q,&q,extent,token); linecap=ParseCommandOption(MagickLineCapOptions,MagickFalse,token); if (linecap == -1) { status=MagickFalse; break; } graphic_context[n]->linecap=(LineCap) linecap; break; } if (LocaleCompare("stroke-linejoin",keyword) == 0) { ssize_t linejoin; (void) GetNextToken(q,&q,extent,token); linejoin=ParseCommandOption(MagickLineJoinOptions,MagickFalse, token); if (linejoin == -1) { status=MagickFalse; break; } graphic_context[n]->linejoin=(LineJoin) linejoin; break; } if (LocaleCompare("stroke-miterlimit",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->miterlimit=StringToUnsignedLong(token); break; } if (LocaleCompare("stroke-opacity",keyword) == 0) { double opacity; (void) GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; opacity=MagickMin(MagickMax(factor* GetDrawValue(token,&next_token),0.0),1.0); if (token == next_token) ThrowPointExpectedException(token,exception); if (graphic_context[n]->compliance == SVGCompliance) graphic_context[n]->stroke_alpha*=opacity; else graphic_context[n]->stroke_alpha=QuantumRange*opacity; if (graphic_context[n]->stroke.alpha != TransparentAlpha) graphic_context[n]->stroke.alpha=graphic_context[n]->stroke_alpha; else graphic_context[n]->stroke.alpha=(MagickRealType) ClampToQuantum(QuantumRange*(1.0-opacity)); break; } if (LocaleCompare("stroke-width",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; graphic_context[n]->stroke_width=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } status=MagickFalse; break; } case 't': case 'T': { if (LocaleCompare("text",keyword) == 0) { primitive_type=TextPrimitive; cursor=0.0; break; } if (LocaleCompare("text-align",keyword) == 0) { ssize_t align; (void) GetNextToken(q,&q,extent,token); align=ParseCommandOption(MagickAlignOptions,MagickFalse,token); if (align == -1) { status=MagickFalse; break; } graphic_context[n]->align=(AlignType) align; break; } if (LocaleCompare("text-anchor",keyword) == 0) { ssize_t align; (void) GetNextToken(q,&q,extent,token); align=ParseCommandOption(MagickAlignOptions,MagickFalse,token); if (align == -1) { status=MagickFalse; break; } graphic_context[n]->align=(AlignType) align; break; } if (LocaleCompare("text-antialias",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->text_antialias=StringToLong(token) != 0 ? MagickTrue : MagickFalse; break; } if (LocaleCompare("text-undercolor",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); status&=QueryColorCompliance(token,AllCompliance, &graphic_context[n]->undercolor,exception); break; } if (LocaleCompare("translate",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); affine.tx=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); affine.ty=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); cursor=0.0; break; } status=MagickFalse; break; } case 'u': case 'U': { if (LocaleCompare("use",keyword) == 0) { const char *use; /* Get a macro from the MVG document, and "use" it here. */ (void) GetNextToken(q,&q,extent,token); use=(const char *) GetValueFromSplayTree(macros,token); if (use != (const char *) NULL) { clone_info=CloneDrawInfo((ImageInfo *) NULL,graphic_context[n]); (void) CloneString(&clone_info->primitive,use); status=RenderMVGContent(image,clone_info,depth+1,exception); clone_info=DestroyDrawInfo(clone_info); } break; } status=MagickFalse; break; } case 'v': case 'V': { if (LocaleCompare("viewbox",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.x=CastDoubleToLong(ceil( GetDrawValue(token,&next_token)-0.5)); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.y=CastDoubleToLong(ceil( GetDrawValue(token,&next_token)-0.5)); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.width=(size_t) CastDoubleToLong( floor(GetDrawValue(token,&next_token)+0.5)); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.height=(size_t) CastDoubleToLong( floor(GetDrawValue(token,&next_token)+0.5)); if (token == next_token) ThrowPointExpectedException(token,exception); break; } status=MagickFalse; break; } case 'w': case 'W': { if (LocaleCompare("word-spacing",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->interword_spacing=GetDrawValue(token, &next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } status=MagickFalse; break; } default: { status=MagickFalse; break; } } if (status == MagickFalse) break; if ((fabs(affine.sx-1.0) >= MagickEpsilon) || (fabs(affine.rx) >= MagickEpsilon) || (fabs(affine.ry) >= MagickEpsilon) || (fabs(affine.sy-1.0) >= MagickEpsilon) || (fabs(affine.tx) >= MagickEpsilon) || (fabs(affine.ty) >= MagickEpsilon)) { 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) && (q > p)) (void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",(int) (q-p-1),p); continue; } /* Parse the primitive attributes. */ for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) if ((primitive_info[i].primitive == TextPrimitive) || (primitive_info[i].primitive == ImagePrimitive)) if (primitive_info[i].text != (char *) NULL) primitive_info[i].text=DestroyString(primitive_info[i].text); i=0; mvg_info.offset=i; j=0; primitive_info[0].point.x=0.0; primitive_info[0].point.y=0.0; primitive_info[0].coordinates=0; primitive_info[0].method=FloodfillMethod; primitive_info[0].closed_subpath=MagickFalse; for (x=0; *q != '\0'; x++) { /* Define points. */ if (IsPoint(q) == MagickFalse) break; (void) GetNextToken(q,&q,extent,token); point.x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); point.y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,(const char **) NULL,extent,token); if (*token == ',') (void) 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; primitive_info[i].closed_subpath=MagickFalse; i++; mvg_info.offset=i; if (i < (ssize_t) number_points) continue; status&=CheckPrimitiveExtent(&mvg_info,(double) number_points); } if (status == MagickFalse) break; if ((primitive_info[j].primitive == TextPrimitive) || (primitive_info[j].primitive == ImagePrimitive)) if (primitive_info[j].text != (char *) NULL) primitive_info[j].text=DestroyString(primitive_info[j].text); primitive_info[j].primitive=primitive_type; primitive_info[j].coordinates=(size_t) x; primitive_info[j].method=FloodfillMethod; primitive_info[j].closed_subpath=MagickFalse; /* 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. */ coordinates=(double) primitive_info[j].coordinates; switch (primitive_type) { case RectanglePrimitive: { coordinates*=5.0; break; } case RoundRectanglePrimitive: { double alpha, beta, radius; alpha=bounds.x2-bounds.x1; beta=bounds.y2-bounds.y1; radius=hypot(alpha,beta); coordinates*=5.0; coordinates+=2.0*((size_t) ceil((double) MagickPI*radius))+6.0* BezierQuantum+360.0; break; } case BezierPrimitive: { coordinates=(BezierQuantum*(double) primitive_info[j].coordinates); break; } case PathPrimitive: { char *s, *t; (void) GetNextToken(q,&q,extent,token); coordinates=1.0; t=token; for (s=token; *s != '\0'; s=t) { double value; value=GetDrawValue(s,&t); (void) value; if (s == t) { t++; continue; } coordinates++; } for (s=token; *s != '\0'; s++) if (strspn(s,"AaCcQqSsTt") != 0) coordinates+=(20.0*BezierQuantum)+360.0; break; } default: break; } if (status == MagickFalse) break; if (((size_t) (i+coordinates)) >= number_points) { /* Resize based on speculative points required by primitive. */ number_points+=coordinates+1; if (number_points < (size_t) coordinates) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); break; } mvg_info.offset=i; status&=CheckPrimitiveExtent(&mvg_info,(double) number_points); } status&=CheckPrimitiveExtent(&mvg_info,PrimitiveExtentPad); if (status == MagickFalse) break; mvg_info.offset=j; switch (primitive_type) { case PointPrimitive: default: { if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } status&=TracePoint(primitive_info+j,primitive_info[j].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case LinePrimitive: { double dx, dy, maximum_length; if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } 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(dx,dy); if (maximum_length > (MaxBezierCoordinates/100.0)) ThrowPointExpectedException(keyword,exception); status&=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; } status&=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; } if ((primitive_info[j+2].point.x < 0.0) || (primitive_info[j+2].point.y < 0.0)) { status=MagickFalse; break; } if ((primitive_info[j+1].point.x-primitive_info[j].point.x) < 0.0) { status=MagickFalse; break; } if ((primitive_info[j+1].point.y-primitive_info[j].point.y) < 0.0) { status=MagickFalse; break; } status&=TraceRoundRectangle(&mvg_info,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) { status=MagickFalse; break; } status&=TraceArc(&mvg_info,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; } if ((primitive_info[j+1].point.x < 0.0) || (primitive_info[j+1].point.y < 0.0)) { status=MagickFalse; break; } status&=TraceEllipse(&mvg_info,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; } status&=TraceCircle(&mvg_info,primitive_info[j].point, primitive_info[j+1].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case PolylinePrimitive: { if (primitive_info[j].coordinates < 1) { status=MagickFalse; break; } break; } case PolygonPrimitive: { if (primitive_info[j].coordinates < 3) { status=MagickFalse; break; } primitive_info[i]=primitive_info[j]; primitive_info[i].coordinates=0; primitive_info[j].coordinates++; primitive_info[j].closed_subpath=MagickTrue; i++; break; } case BezierPrimitive: { if (primitive_info[j].coordinates < 3) { status=MagickFalse; break; } status&=TraceBezier(&mvg_info,primitive_info[j].coordinates); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case PathPrimitive: { coordinates=(double) TracePath(&mvg_info,token,exception); if (coordinates < 0.0) { status=MagickFalse; break; } i=(ssize_t) (j+coordinates); break; } case AlphaPrimitive: case ColorPrimitive: { ssize_t method; if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } (void) GetNextToken(q,&q,extent,token); method=ParseCommandOption(MagickMethodOptions,MagickFalse,token); if (method == -1) { status=MagickFalse; break; } primitive_info[j].method=(PaintMethod) method; break; } case TextPrimitive: { if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } if (*token != ',') (void) GetNextToken(q,&q,extent,token); (void) CloneString(&primitive_info[j].text,token); /* Compute text cursor offset. */ clone_info=CloneDrawInfo((ImageInfo *) NULL,graphic_context[n]); if ((fabs(mvg_info.point.x-primitive_info->point.x) < MagickEpsilon) && (fabs(mvg_info.point.y-primitive_info->point.y) < MagickEpsilon)) { mvg_info.point=primitive_info->point; primitive_info->point.x+=cursor; } else { mvg_info.point=primitive_info->point; cursor=0.0; } clone_info->render=MagickFalse; clone_info->text=AcquireString(token); status&=GetTypeMetrics(image,clone_info,&metrics,exception); clone_info=DestroyDrawInfo(clone_info); cursor+=metrics.width; if (graphic_context[n]->compliance != SVGCompliance) cursor=0.0; break; } case ImagePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } (void) GetNextToken(q,&q,extent,token); (void) CloneString(&primitive_info[j].text,token); break; } } mvg_info.offset=i; if (status == 0) break; primitive_info[i].primitive=UndefinedPrimitive; if ((image->debug != MagickFalse) && (q > p)) (void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",(int) (q-p),p); /* Sanity check. */ status&=CheckPrimitiveExtent(&mvg_info,ExpandAffine( &graphic_context[n]->affine)); if (status == 0) break; status&=CheckPrimitiveExtent(&mvg_info,(double) graphic_context[n]->stroke_width); if (status == 0) break; 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]->compliance != SVGCompliance) && (graphic_context[n]->clip_mask != (char *) NULL) && (LocaleCompare(graphic_context[n]->clip_mask, graphic_context[n-1]->clip_mask) != 0)) { const char *clip_path; clip_path=(const char *) GetValueFromSplayTree(macros, graphic_context[n]->clip_mask); if (clip_path != (const char *) NULL) (void) SetImageArtifact(image,graphic_context[n]->clip_mask, clip_path); status&=DrawClipPath(image,graphic_context[n], graphic_context[n]->clip_mask,exception); } status&=DrawPrimitive(image,graphic_context[n],primitive_info, exception); } 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. */ macros=DestroySplayTree(macros); token=DestroyString(token); if (primitive_info != (PrimitiveInfo *) NULL) { for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) if ((primitive_info[i].primitive == TextPrimitive) || (primitive_info[i].primitive == ImagePrimitive)) if (primitive_info[i].text != (char *) NULL) primitive_info[i].text=DestroyString(primitive_info[i].text); primitive_info=(PrimitiveInfo *) RelinquishMagickMemory(primitive_info); } primitive=DestroyString(primitive); if (stops != (StopInfo *) NULL) stops=(StopInfo *) RelinquishMagickMemory(stops); 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); } MagickExport MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info, ExceptionInfo *exception) { return(RenderMVGContent(image,draw_info,0,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % 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("#00000000",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); 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->stroke_pattern=DestroyImage(clone_info->stroke_pattern); (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=RenderMVGContent(*pattern,clone_info,0,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 **DestroyPolygonTLS(PolygonInfo **polygon_info) { 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 **AcquirePolygonTLS(const PrimitiveInfo *primitive_info, ExceptionInfo *exception) { PathInfo *magick_restrict path_info; PolygonInfo **polygon_info; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); polygon_info=(PolygonInfo **) AcquireQuantumMemory(number_threads, sizeof(*polygon_info)); if (polygon_info == (PolygonInfo **) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return((PolygonInfo **) NULL); } (void) memset(polygon_info,0,number_threads*sizeof(*polygon_info)); path_info=ConvertPrimitiveToPath(primitive_info,exception); if (path_info == (PathInfo *) NULL) return(DestroyPolygonTLS(polygon_info)); polygon_info[0]=ConvertPathToPolygon(path_info,exception); if (polygon_info[0] == (PolygonInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonTLS(polygon_info)); } path_info=(PathInfo *) RelinquishMagickMemory(path_info); return(polygon_info); } static MagickBooleanType ClonePolygonEdgesTLS(PolygonInfo **polygon_info, const size_t number_threads,ExceptionInfo *exception) { ssize_t i; for (i=1; i < (ssize_t) number_threads; i++) { EdgeInfo *edge_info; ssize_t j; polygon_info[i]=(PolygonInfo *) AcquireMagickMemory( sizeof(*polygon_info[i])); if (polygon_info[i] == (PolygonInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } polygon_info[i]->number_edges=0; edge_info=polygon_info[0]->edges; polygon_info[i]->edges=(EdgeInfo *) AcquireQuantumMemory( polygon_info[0]->number_edges,sizeof(*edge_info)); if (polygon_info[i]->edges == (EdgeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } (void) memcpy(polygon_info[i]->edges,edge_info, polygon_info[0]->number_edges*sizeof(*edge_info)); for (j=0; j < (ssize_t) polygon_info[i]->number_edges; j++) polygon_info[i]->edges[j].points=(PointInfo *) NULL; polygon_info[i]->number_edges=polygon_info[0]->number_edges; for (j=0; j < (ssize_t) polygon_info[i]->number_edges; j++) { edge_info=polygon_info[0]->edges+j; polygon_info[i]->edges[j].points=(PointInfo *) AcquireQuantumMemory( edge_info->number_points,sizeof(*edge_info)); if (polygon_info[i]->edges[j].points == (PointInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } (void) memcpy(polygon_info[i]->edges[j].points,edge_info->points, edge_info->number_points*sizeof(*edge_info->points)); } } return(MagickTrue); } static size_t DestroyEdge(PolygonInfo *polygon_info,const ssize_t edge) { assert(edge < (ssize_t) polygon_info->number_edges); polygon_info->edges[edge].points=(PointInfo *) RelinquishMagickMemory( polygon_info->edges[edge].points); polygon_info->number_edges--; if (edge < (ssize_t) polygon_info->number_edges) (void) memmove(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); } 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; const PointInfo *q; EdgeInfo *p; 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)) { p--; (void) DestroyEdge(polygon_info,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=PerceptibleReciprocal(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) >= MagickEpsilon) 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) < MagickEpsilon) { beta=1.0; if (fabs(distance-1.0) >= MagickEpsilon) 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 != 0 ? 1 : -1; continue; } i=(ssize_t) MagickMax((double) p->highwater,1.0); for ( ; i < (ssize_t) (p->number_points-1); 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 != 0 ? 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) { typedef struct _ExtentInfo { ssize_t x1, y1, x2, y2; } ExtentInfo; CacheView *image_view; const char *artifact; double mid; EdgeInfo *p; ExtentInfo poly_extent; MagickBooleanType fill, status; PolygonInfo **magick_restrict polygon_info; SegmentInfo bounds; size_t number_threads; ssize_t i, y; 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 <= 1) return(MagickTrue); /* Compute bounding box. */ polygon_info=AcquirePolygonTLS(primitive_info,exception); if (polygon_info == (PolygonInfo **) NULL) return(MagickFalse); 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; artifact=GetImageArtifact(image,"draw:render-bounding-rectangles"); if (IsStringTrue(artifact) != MagickFalse) (void) DrawBoundingRectangles(image,draw_info,polygon_info[0],exception); 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.y1-=(mid+1.0); bounds.x2+=(mid+1.0); bounds.y2+=(mid+1.0); if ((bounds.x1 >= (double) image->columns) || (bounds.y1 >= (double) image->rows) || (bounds.x2 <= 0.0) || (bounds.y2 <= 0.0)) { polygon_info=DestroyPolygonTLS(polygon_info); return(MagickTrue); /* virtual polygon */ } bounds.x1=bounds.x1 < 0.0 ? 0.0 : bounds.x1 >= (double) image->columns-1.0 ? (double) image->columns-1.0 : bounds.x1; bounds.y1=bounds.y1 < 0.0 ? 0.0 : bounds.y1 >= (double) image->rows-1.0 ? (double) image->rows-1.0 : bounds.y1; bounds.x2=bounds.x2 < 0.0 ? 0.0 : bounds.x2 >= (double) image->columns-1.0 ? (double) image->columns-1.0 : bounds.x2; bounds.y2=bounds.y2 < 0.0 ? 0.0 : bounds.y2 >= (double) image->rows-1.0 ? (double) image->rows-1.0 : bounds.y2; poly_extent.x1=CastDoubleToLong(ceil(bounds.x1-0.5)); poly_extent.y1=CastDoubleToLong(ceil(bounds.y1-0.5)); poly_extent.x2=CastDoubleToLong(floor(bounds.x2+0.5)); poly_extent.y2=CastDoubleToLong(floor(bounds.y2+0.5)); number_threads=GetMagickNumberThreads(image,image,poly_extent.y2- poly_extent.y1+1,1); status=ClonePolygonEdgesTLS(polygon_info,number_threads,exception); if (status == MagickFalse) { polygon_info=DestroyPolygonTLS(polygon_info); return(status); } image_view=AcquireAuthenticCacheView(image,exception); if ((primitive_info->coordinates == 1) || (polygon_info[0]->number_edges == 0)) { /* Draw point. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ num_threads(number_threads) #endif for (y=poly_extent.y1; y <= poly_extent.y2; y++) { PixelInfo pixel; ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; x=poly_extent.x1; q=GetCacheViewAuthenticPixels(image_view,x,y,(size_t) (poly_extent.x2- x+1),1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } GetPixelInfo(image,&pixel); for ( ; x <= poly_extent.x2; x++) { if ((x == CastDoubleToLong(ceil(primitive_info->point.x-0.5))) && (y == CastDoubleToLong(ceil(primitive_info->point.y-0.5)))) { GetFillColor(draw_info,x-poly_extent.x1,y-poly_extent.y1,&pixel, exception); SetPixelViaPixelInfo(image,&pixel,q); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); polygon_info=DestroyPolygonTLS(polygon_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " end draw-polygon"); return(status); } /* Draw polygon or line. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ num_threads(number_threads) #endif for (y=poly_extent.y1; y <= poly_extent.y2; y++) { const int id = GetOpenMPThreadId(); Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,poly_extent.x1,y,(size_t) (poly_extent.x2-poly_extent.x1+1),1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=poly_extent.x1; x <= poly_extent.x2; x++) { double fill_alpha, stroke_alpha; PixelInfo fill_color, stroke_color; /* 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.5 ? 1.0 : 0.0; stroke_alpha=stroke_alpha > 0.5 ? 1.0 : 0.0; } GetFillColor(draw_info,x-poly_extent.x1,y-poly_extent.y1,&fill_color, exception); CompositePixelOver(image,&fill_color,fill_alpha*fill_color.alpha,q, (double) GetPixelAlpha(image,q),q); GetStrokeColor(draw_info,x-poly_extent.x1,y-poly_extent.y1,&stroke_color, exception); CompositePixelOver(image,&stroke_color,stroke_alpha*stroke_color.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=DestroyPolygonTLS(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, point, q; ssize_t i, x; ssize_t coordinates, y; x=CastDoubleToLong(ceil(primitive_info->point.x-0.5)); y=CastDoubleToLong(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) >= MagickEpsilon) || (fabs(q.y-point.y) >= MagickEpsilon)) (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) >= MagickEpsilon) || (fabs(p.y-point.y) >= MagickEpsilon)) (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; 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); } status=MagickTrue; if ((IsGrayColorspace(image->colorspace) != MagickFalse) && ((IsPixelInfoGray(&draw_info->fill) == MagickFalse) || (IsPixelInfoGray(&draw_info->stroke) == MagickFalse))) status&=SetImageColorspace(image,sRGBColorspace,exception); if (draw_info->compliance == SVGCompliance) { status&=SetImageMask(image,WritePixelMask,draw_info->clipping_mask, exception); status&=SetImageMask(image,CompositePixelMask,draw_info->composite_mask, exception); } x=CastDoubleToLong(ceil(primitive_info->point.x-0.5)); y=CastDoubleToLong(ceil(primitive_info->point.y-0.5)); image_view=AcquireAuthenticCacheView(image,exception); switch (primitive_info->primitive) { case AlphaPrimitive: { if (image->alpha_trait == UndefinedPixelTrait) status&=SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); switch (primitive_info->method) { case PointMethod: default: { PixelInfo pixel; 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); status&=SyncCacheViewAuthenticPixels(image_view,exception); break; } case ReplaceMethod: { PixelInfo pixel, target; status&=GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target, exception); GetPixelInfo(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { 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); } status&=SyncCacheViewAuthenticPixels(image_view,exception); if (status == MagickFalse) break; } break; } case FloodfillMethod: case FillToBorderMethod: { ChannelType channel_mask; PixelInfo target; status&=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: { PixelInfo pixel; for (y=0; y < (ssize_t) image->rows; y++) { 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); } status&=SyncCacheViewAuthenticPixels(image_view,exception); if (status == MagickFalse) break; } break; } } break; } case ColorPrimitive: { switch (primitive_info->method) { case PointMethod: default: { PixelInfo pixel; 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); status&=SyncCacheViewAuthenticPixels(image_view,exception); break; } case ReplaceMethod: { PixelInfo pixel, target; status&=GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target, exception); for (y=0; y < (ssize_t) image->rows; y++) { 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); } status&=SyncCacheViewAuthenticPixels(image_view,exception); if (status == MagickFalse) break; } break; } case FloodfillMethod: case FillToBorderMethod: { PixelInfo target; status&=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: { PixelInfo pixel; GetPixelInfo(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { 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); } status&=SyncCacheViewAuthenticPixels(image_view,exception); if (status == MagickFalse) break; } break; } } break; } case ImagePrimitive: { AffineMatrix affine; char composite_geometry[MagickPathExtent]; Image *composite_image, *composite_images; ImageInfo *clone_info; RectangleInfo geometry; ssize_t x1, y1; if (primitive_info->text == (char *) NULL) break; clone_info=AcquireImageInfo(); composite_images=(Image *) NULL; if (LocaleNCompare(primitive_info->text,"data:",5) == 0) composite_images=ReadInlineImage(clone_info,primitive_info->text, exception); else if (*primitive_info->text != '\0') { MagickBooleanType path_status; struct stat attributes; /* Read composite image. */ (void) CopyMagickString(clone_info->filename,primitive_info->text, MagickPathExtent); (void) SetImageInfo(clone_info,1,exception); (void) CopyMagickString(clone_info->filename,primitive_info->text, MagickPathExtent); if (clone_info->size != (char *) NULL) clone_info->size=DestroyString(clone_info->size); if (clone_info->extract != (char *) NULL) clone_info->extract=DestroyString(clone_info->extract); path_status=GetPathAttributes(clone_info->filename,&attributes); if (path_status != MagickFalse) { if (S_ISCHR(attributes.st_mode) == 0) composite_images=ReadImage(clone_info,exception); else (void) ThrowMagickException(exception,GetMagickModule(), FileOpenError,"UnableToOpenFile","`%s'", clone_info->filename); } else if ((LocaleCompare(clone_info->magick,"ftp") != 0) && (LocaleCompare(clone_info->magick,"http") != 0) && (LocaleCompare(clone_info->magick,"https") != 0)) composite_images=ReadImage(clone_info,exception); else (void) ThrowMagickException(exception,GetMagickModule(), FileOpenError,"UnableToOpenFile","`%s'",clone_info->filename); } clone_info=DestroyImageInfo(clone_info); if (composite_images == (Image *) NULL) { status=MagickFalse; break; } composite_image=RemoveFirstImageFromList(&composite_images); composite_images=DestroyImageList(composite_images); (void) SetImageProgressMonitor(composite_image,(MagickProgressMonitor) NULL,(void *) NULL); x1=CastDoubleToLong(ceil(primitive_info[1].point.x-0.5)); y1=CastDoubleToLong(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; status&=TransformImage(&composite_image,(char *) NULL, composite_geometry,exception); } if (composite_image->alpha_trait == UndefinedPixelTrait) status&=SetImageAlphaChannel(composite_image,OpaqueAlphaChannel, exception); if (draw_info->alpha != OpaqueAlpha) status&=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) || (draw_info->compose == SrcOverCompositeOp)) status&=DrawAffineImage(image,composite_image,&affine,exception); else status&=CompositeImage(image,composite_image,draw_info->compose, MagickTrue,geometry.x,geometry.y,exception); composite_image=DestroyImage(composite_image); break; } case PointPrimitive: { PixelInfo fill_color; 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); status&=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]) >= MagickEpsilon) && (fabs(scale*draw_info->stroke_width) >= MagickEpsilon) && (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); if (status != MagickFalse) status&=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))) { double point_x, point_y; MagickBooleanType closed_path; /* Draw strokes while respecting line cap/join attributes. */ closed_path=primitive_info[0].closed_subpath; i=(ssize_t) primitive_info[0].coordinates; point_x=fabs(primitive_info[i-1].point.x-primitive_info[0].point.x); point_y=fabs(primitive_info[i-1].point.y-primitive_info[0].point.y); if ((point_x < MagickEpsilon) && (point_y < MagickEpsilon)) closed_path=MagickTrue; if ((((draw_info->linecap == RoundCap) || (closed_path != MagickFalse)) && (draw_info->linejoin == RoundJoin)) || (primitive_info[i].primitive != UndefinedPrimitive)) { status&=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); if (status != MagickFalse) status&=DrawStrokePolygon(image,draw_info,primitive_info,exception); break; } status&=DrawPolygonPrimitive(image,draw_info,primitive_info,exception); break; } } image_view=DestroyCacheView(image_view); if (draw_info->compliance == SVGCompliance) { status&=SetImageMask(image,WritePixelMask,(Image *) NULL,exception); status&=SetImageMask(image,CompositePixelMask,(Image *) NULL,exception); } 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 MagickBooleanType DrawRoundLinecap(Image *image, const DrawInfo *draw_info,const PrimitiveInfo *primitive_info, ExceptionInfo *exception) { PrimitiveInfo linecap[5]; ssize_t i; for (i=0; i < 4; i++) linecap[i]=(*primitive_info); linecap[0].coordinates=4; linecap[1].point.x+=2.0*MagickEpsilon; linecap[2].point.x+=2.0*MagickEpsilon; linecap[2].point.y+=2.0*MagickEpsilon; linecap[3].point.y+=2.0*MagickEpsilon; linecap[4].primitive=UndefinedPrimitive; return(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; 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) { if (p->coordinates == 1) continue; stroke_polygon=TraceStrokePolygon(draw_info,p,exception); if (stroke_polygon == (PrimitiveInfo *) NULL) { status=0; break; } status&=DrawPolygonPrimitive(image,clone_info,stroke_polygon,exception); stroke_polygon=(PrimitiveInfo *) RelinquishMagickMemory(stroke_polygon); if (status == 0) break; q=p+p->coordinates-1; closed_path=p->closed_subpath; if ((draw_info->linecap == RoundCap) && (closed_path == MagickFalse)) { status&=DrawRoundLinecap(image,draw_info,p,exception); status&=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) memset(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) memset(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("#FFF0",AllCompliance,&draw_info->stroke, exception); draw_info->stroke_antialias=clone_info->antialias; 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->clip_path=MagickFalse; draw_info->debug=IsEventLogging(); 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) >= MagickEpsilon) 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=GetDrawValue(option,&next_token); option=GetImageOption(clone_info,"interword-spacing"); if (option != (const char *) NULL) draw_info->interword_spacing=GetDrawValue(option,&next_token); option=GetImageOption(clone_info,"kerning"); if (option != (const char *) NULL) draw_info->kerning=GetDrawValue(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=GetDrawValue(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; 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 MagickBooleanType TraceArc(MVGInfo *mvg_info,const PointInfo start, const PointInfo end,const PointInfo degrees) { PointInfo center, radius; center.x=0.5*(end.x+start.x); center.y=0.5*(end.y+start.y); radius.x=fabs(center.x-start.x); radius.y=fabs(center.y-start.y); return(TraceEllipse(mvg_info,center,radius,degrees)); } static MagickBooleanType TraceArcPath(MVGInfo *mvg_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; MagickStatusType status; PointInfo center, points[3], radii; double cosine, sine; PrimitiveInfo *primitive_info; PrimitiveInfo *p; ssize_t i; size_t arc_segments; ssize_t offset; offset=mvg_info->offset; primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; primitive_info->coordinates=0; if ((fabs(start.x-end.x) < MagickEpsilon) && (fabs(start.y-end.y) < MagickEpsilon)) return(TracePoint(primitive_info,end)); radii.x=fabs(arc.x); radii.y=fabs(arc.y); if ((radii.x < MagickEpsilon) || (radii.y < MagickEpsilon)) return(TraceLine(primitive_info,start,end)); 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 < MagickEpsilon) return(TraceLine(primitive_info,start,end)); 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; if (fabs(alpha*alpha+beta*beta) < MagickEpsilon) return(TraceLine(primitive_info,start,end)); 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) CastDoubleToLong(ceil(fabs((double) (theta/(0.5* MagickPI+MagickEpsilon))))); status=MagickTrue; 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; status&=TraceBezier(mvg_info,4); if (status == 0) break; p=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=p->coordinates; p+=p->coordinates; } if (status == 0) return(MagickFalse); mvg_info->offset=offset; primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickFalse; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } return(MagickTrue); } static MagickBooleanType TraceBezier(MVGInfo *mvg_info, const size_t number_coordinates) { double alpha, *coefficients, weight; PointInfo end, point, *points; PrimitiveInfo *primitive_info; PrimitiveInfo *p; ssize_t i, j; size_t control_points, quantum; /* Allocate coefficients. */ primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; 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) MAGICK_SSIZE_MAX) { (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } if (alpha > (double) quantum) quantum=(size_t) alpha; alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y); if (alpha > (double) MAGICK_SSIZE_MAX) { (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } if (alpha > (double) quantum) quantum=(size_t) alpha; } } primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; quantum=MagickMin(quantum/number_coordinates,BezierQuantum); coefficients=(double *) AcquireQuantumMemory(number_coordinates, sizeof(*coefficients)); points=(PointInfo *) AcquireQuantumMemory(quantum,number_coordinates* sizeof(*points)); if ((coefficients == (double *) NULL) || (points == (PointInfo *) NULL)) { if (points != (PointInfo *) NULL) points=(PointInfo *) RelinquishMagickMemory(points); if (coefficients != (double *) NULL) coefficients=(double *) RelinquishMagickMemory(coefficients); (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } control_points=quantum*number_coordinates; if (CheckPrimitiveExtent(mvg_info,(double) control_points+1) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; /* 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++) { if (TracePoint(p,points[i]) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } p+=p->coordinates; } if (TracePoint(p,end) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickFalse; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickTrue); } static MagickBooleanType TraceCircle(MVGInfo *mvg_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; return(TraceEllipse(mvg_info,start,offset,degrees)); } static MagickBooleanType TraceEllipse(MVGInfo *mvg_info,const PointInfo center, const PointInfo radii,const PointInfo arc) { double coordinates, delta, step, x, y; PointInfo angle, point; PrimitiveInfo *primitive_info; PrimitiveInfo *p; ssize_t i; /* Ellipses are just short segmented polys. */ primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; primitive_info->coordinates=0; if ((fabs(radii.x) < MagickEpsilon) || (fabs(radii.y) < MagickEpsilon)) return(MagickTrue); delta=2.0*PerceptibleReciprocal(MagickMax(radii.x,radii.y)); step=MagickPI/8.0; if ((delta >= 0.0) && (delta < (MagickPI/8.0))) step=MagickPI/4.0/(MagickPI*PerceptibleReciprocal(delta)/2.0); angle.x=DegreesToRadians(arc.x); y=arc.y; while (y < arc.x) y+=360.0; angle.y=DegreesToRadians(y); coordinates=ceil((angle.y-angle.x)/step+1.0); if (CheckPrimitiveExtent(mvg_info,coordinates) == MagickFalse) return(MagickFalse); primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; for (p=primitive_info; angle.x < angle.y; angle.x+=step) { point.x=cos(fmod(angle.x,DegreesToRadians(360.0)))*radii.x+center.x; point.y=sin(fmod(angle.x,DegreesToRadians(360.0)))*radii.y+center.y; if (TracePoint(p,point) == MagickFalse) return(MagickFalse); p+=p->coordinates; } point.x=cos(fmod(angle.y,DegreesToRadians(360.0)))*radii.x+center.x; point.y=sin(fmod(angle.y,DegreesToRadians(360.0)))*radii.y+center.y; if (TracePoint(p,point) == MagickFalse) return(MagickFalse); p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickFalse; x=fabs(primitive_info[0].point.x- primitive_info[primitive_info->coordinates-1].point.x); y=fabs(primitive_info[0].point.y- primitive_info[primitive_info->coordinates-1].point.y); if ((x < MagickEpsilon) && (y < MagickEpsilon)) primitive_info->closed_subpath=MagickTrue; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } return(MagickTrue); } static MagickBooleanType TraceLine(PrimitiveInfo *primitive_info, const PointInfo start,const PointInfo end) { if (TracePoint(primitive_info,start) == MagickFalse) return(MagickFalse); if ((fabs(start.x-end.x) < MagickEpsilon) && (fabs(start.y-end.y) < MagickEpsilon)) { primitive_info->primitive=PointPrimitive; primitive_info->coordinates=1; return(MagickTrue); } if (TracePoint(primitive_info+1,end) == MagickFalse) return(MagickFalse); (primitive_info+1)->primitive=primitive_info->primitive; primitive_info->coordinates=2; primitive_info->closed_subpath=MagickFalse; return(MagickTrue); } static ssize_t TracePath(MVGInfo *mvg_info,const char *path, ExceptionInfo *exception) { char *next_token, token[MagickPathExtent]; const char *p; double x, y; int attribute, last_attribute; MagickBooleanType status; 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}; PrimitiveInfo *primitive_info; PrimitiveType primitive_type; PrimitiveInfo *q; ssize_t i; size_t number_coordinates, z_count; ssize_t subpath_offset; subpath_offset=mvg_info->offset; primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; status=MagickTrue; attribute=0; number_coordinates=0; z_count=0; primitive_type=primitive_info->primitive; q=primitive_info; for (p=path; *p != '\0'; ) { if (status == MagickFalse) break; 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 = 0.0; MagickBooleanType large_arc = MagickFalse, sweep = MagickFalse; PointInfo arc = {0.0, 0.0}; /* Elliptical arc. */ do { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); arc.x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); arc.y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); angle=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); large_arc=StringToLong(token) != 0 ? MagickTrue : MagickFalse; (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); sweep=StringToLong(token) != 0 ? MagickTrue : MagickFalse; if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); end.x=(double) (attribute == (int) 'A' ? x : point.x+x); end.y=(double) (attribute == (int) 'A' ? y : point.y+y); if (TraceArcPath(mvg_info,point,end,arc,angle,large_arc,sweep) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=q->coordinates; 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': { /* Cubic Bézier curve. */ do { points[0]=point; for (i=1; i < 4; i++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); 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]; if (TraceBezier(mvg_info,4) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=q->coordinates; q+=q->coordinates; point=end; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'H': case 'h': { do { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); point.x=(double) (attribute == (int) 'H' ? x: point.x+x); if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; if (TracePoint(q,point) == MagickFalse) return(-1); mvg_info->offset+=q->coordinates; q+=q->coordinates; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'l': case 'L': { /* Line to. */ do { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); point.x=(double) (attribute == (int) 'L' ? x : point.x+x); point.y=(double) (attribute == (int) 'L' ? y : point.y+y); if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; if (TracePoint(q,point) == MagickFalse) return(-1); mvg_info->offset+=q->coordinates; q+=q->coordinates; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'M': case 'm': { /* Move to. */ if (mvg_info->offset != subpath_offset) { primitive_info=(*mvg_info->primitive_info)+subpath_offset; primitive_info->coordinates=(size_t) (q-primitive_info); number_coordinates+=primitive_info->coordinates; primitive_info=q; subpath_offset=mvg_info->offset; } i=0; do { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); 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++; if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; if (TracePoint(q,point) == MagickFalse) return(-1); mvg_info->offset+=q->coordinates; q+=q->coordinates; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'q': case 'Q': { /* Quadratic Bézier curve. */ do { points[0]=point; for (i=1; i < 3; i++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); 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]; if (TraceBezier(mvg_info,3) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=q->coordinates; q+=q->coordinates; point=end; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 's': case 'S': { /* Cubic Bézier curve. */ 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++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); 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]; if (TraceBezier(mvg_info,4) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=q->coordinates; q+=q->coordinates; point=end; last_attribute=attribute; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 't': case 'T': { /* Quadratic Bézier curve. */ 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++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); end.x=(double) (attribute == (int) 'T' ? x : point.x+x); end.y=(double) (attribute == (int) 'T' ? y : point.y+y); points[i]=end; } if (status == MagickFalse) break; if (strchr("QqTt",last_attribute) == (char *) NULL) { points[0]=point; points[1]=point; } for (i=0; i < 3; i++) (q+i)->point=points[i]; if (TraceBezier(mvg_info,3) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=q->coordinates; q+=q->coordinates; point=end; last_attribute=attribute; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'v': case 'V': { /* Line to. */ do { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); point.y=(double) (attribute == (int) 'V' ? y : point.y+y); if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; if (TracePoint(q,point) == MagickFalse) return(-1); mvg_info->offset+=q->coordinates; q+=q->coordinates; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'z': case 'Z': { /* Close path. */ point=start; if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; if (TracePoint(q,point) == MagickFalse) return(-1); mvg_info->offset+=q->coordinates; q+=q->coordinates; primitive_info=(*mvg_info->primitive_info)+subpath_offset; primitive_info->coordinates=(size_t) (q-primitive_info); primitive_info->closed_subpath=MagickTrue; number_coordinates+=primitive_info->coordinates; primitive_info=q; subpath_offset=mvg_info->offset; z_count++; break; } default: { ThrowPointExpectedException(token,exception); break; } } } if (status == MagickFalse) return(-1); primitive_info=(*mvg_info->primitive_info)+subpath_offset; 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((ssize_t) number_coordinates); } static MagickBooleanType TraceRectangle(PrimitiveInfo *primitive_info, const PointInfo start,const PointInfo end) { PointInfo point; PrimitiveInfo *p; ssize_t i; p=primitive_info; if (TracePoint(p,start) == MagickFalse) return(MagickFalse); p+=p->coordinates; point.x=start.x; point.y=end.y; if (TracePoint(p,point) == MagickFalse) return(MagickFalse); p+=p->coordinates; if (TracePoint(p,end) == MagickFalse) return(MagickFalse); p+=p->coordinates; point.x=end.x; point.y=start.y; if (TracePoint(p,point) == MagickFalse) return(MagickFalse); p+=p->coordinates; if (TracePoint(p,start) == MagickFalse) return(MagickFalse); p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickTrue; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } return(MagickTrue); } static MagickBooleanType TraceRoundRectangle(MVGInfo *mvg_info, const PointInfo start,const PointInfo end,PointInfo arc) { PointInfo degrees, point, segment; PrimitiveInfo *primitive_info; PrimitiveInfo *p; ssize_t i; ssize_t offset; offset=mvg_info->offset; segment.x=fabs(end.x-start.x); segment.y=fabs(end.y-start.y); if ((segment.x < MagickEpsilon) || (segment.y < MagickEpsilon)) { (*mvg_info->primitive_info+mvg_info->offset)->coordinates=0; return(MagickTrue); } if (arc.x > (0.5*segment.x)) arc.x=0.5*segment.x; if (arc.y > (0.5*segment.y)) arc.y=0.5*segment.y; point.x=start.x+segment.x-arc.x; point.y=start.y+arc.y; degrees.x=270.0; degrees.y=360.0; if (TraceEllipse(mvg_info,point,arc,degrees) == MagickFalse) return(MagickFalse); p=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=p->coordinates; point.x=start.x+segment.x-arc.x; point.y=start.y+segment.y-arc.y; degrees.x=0.0; degrees.y=90.0; if (TraceEllipse(mvg_info,point,arc,degrees) == MagickFalse) return(MagickFalse); p=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=p->coordinates; point.x=start.x+arc.x; point.y=start.y+segment.y-arc.y; degrees.x=90.0; degrees.y=180.0; if (TraceEllipse(mvg_info,point,arc,degrees) == MagickFalse) return(MagickFalse); p=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=p->coordinates; point.x=start.x+arc.x; point.y=start.y+arc.y; degrees.x=180.0; degrees.y=270.0; if (TraceEllipse(mvg_info,point,arc,degrees) == MagickFalse) return(MagickFalse); p=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=p->coordinates; if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse) return(MagickFalse); p=(*mvg_info->primitive_info)+mvg_info->offset; if (TracePoint(p,(*mvg_info->primitive_info+offset)->point) == MagickFalse) return(MagickFalse); p+=p->coordinates; mvg_info->offset=offset; primitive_info=(*mvg_info->primitive_info)+offset; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickTrue; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } return(MagickTrue); } static MagickBooleanType TraceSquareLinecap(PrimitiveInfo *primitive_info, const size_t number_vertices,const double offset) { double distance; double dx, dy; 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) >= MagickEpsilon) || (fabs((double) dy) >= MagickEpsilon)) 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) >= MagickEpsilon) || (fabs((double) dy) >= MagickEpsilon)) 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); return(MagickTrue); } static PrimitiveInfo *TraceStrokePolygon(const DrawInfo *draw_info, const PrimitiveInfo *primitive_info,ExceptionInfo *exception) { #define MaxStrokePad (6*BezierQuantum+360) #define CheckPathExtent(pad_p,pad_q) \ { \ if ((pad_p) > MaxBezierCoordinates) \ stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p); \ else \ if ((ssize_t) (p+(pad_p)) >= (ssize_t) extent_p) \ { \ if (~extent_p < (pad_p)) \ stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p); \ else \ { \ extent_p+=(pad_p); \ stroke_p=(PointInfo *) ResizeQuantumMemory(stroke_p,extent_p+ \ MaxStrokePad,sizeof(*stroke_p)); \ } \ } \ if ((pad_q) > MaxBezierCoordinates) \ stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q); \ else \ if ((ssize_t) (q+(pad_q)) >= (ssize_t) extent_q) \ { \ if (~extent_q < (pad_q)) \ stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q); \ else \ { \ extent_q+=(pad_q); \ stroke_q=(PointInfo *) ResizeQuantumMemory(stroke_q,extent_q+ \ MaxStrokePad,sizeof(*stroke_q)); \ } \ } \ if ((stroke_p == (PointInfo *) NULL) || (stroke_q == (PointInfo *) NULL)) \ { \ if (stroke_p != (PointInfo *) NULL) \ stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p); \ if (stroke_q != (PointInfo *) NULL) \ stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q); \ polygon_primitive=(PrimitiveInfo *) \ RelinquishMagickMemory(polygon_primitive); \ (void) ThrowMagickException(exception,GetMagickModule(), \ ResourceLimitError,"MemoryAllocationFailed","`%s'",""); \ return((PrimitiveInfo *) NULL); \ } \ } typedef struct _StrokeSegment { double p, q; } StrokeSegment; double delta_theta, dot_product, mid, miterlimit; MagickBooleanType closed_path; PointInfo box_p[5], box_q[5], center, offset, *stroke_p, *stroke_q; PrimitiveInfo *polygon_primitive, *stroke_polygon; ssize_t i; size_t arc_segments, extent_p, extent_q, number_vertices; ssize_t j, n, p, q; StrokeSegment dx = {0.0, 0.0}, dy = {0.0, 0.0}, inverse_slope = {0.0, 0.0}, slope = {0.0, 0.0}, theta = {0.0, 0.0}; /* Allocate paths. */ number_vertices=primitive_info->coordinates; polygon_primitive=(PrimitiveInfo *) AcquireQuantumMemory((size_t) number_vertices+2UL,sizeof(*polygon_primitive)); if (polygon_primitive == (PrimitiveInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return((PrimitiveInfo *) NULL); } (void) memcpy(polygon_primitive,primitive_info,(size_t) number_vertices* sizeof(*polygon_primitive)); offset.x=primitive_info[number_vertices-1].point.x-primitive_info[0].point.x; offset.y=primitive_info[number_vertices-1].point.y-primitive_info[0].point.y; closed_path=(fabs(offset.x) < MagickEpsilon) && (fabs(offset.y) < MagickEpsilon) ? 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) >= MagickEpsilon) || (fabs(dy.p) >= MagickEpsilon)) break; } if (n == (ssize_t) number_vertices) { if ((draw_info->linecap != RoundCap) || (closed_path != MagickFalse)) { /* Zero length subpath. */ stroke_polygon=(PrimitiveInfo *) AcquireCriticalMemory( sizeof(*stroke_polygon)); stroke_polygon[0]=polygon_primitive[0]; stroke_polygon[0].coordinates=0; polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory( polygon_primitive); return(stroke_polygon); } n=(ssize_t) number_vertices-1L; } extent_p=2*number_vertices; extent_q=2*number_vertices; stroke_p=(PointInfo *) AcquireQuantumMemory((size_t) extent_p+MaxStrokePad, sizeof(*stroke_p)); stroke_q=(PointInfo *) AcquireQuantumMemory((size_t) extent_q+MaxStrokePad, sizeof(*stroke_q)); if ((stroke_p == (PointInfo *) NULL) || (stroke_q == (PointInfo *) NULL)) { if (stroke_p != (PointInfo *) NULL) stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p); if (stroke_q != (PointInfo *) NULL) stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q); polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return((PrimitiveInfo *) NULL); } slope.p=0.0; inverse_slope.p=0.0; if (fabs(dx.p) < MagickEpsilon) { if (dx.p >= 0.0) slope.p=dy.p < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon; else slope.p=dy.p < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon; } else if (fabs(dy.p) < MagickEpsilon) { if (dy.p >= 0.0) inverse_slope.p=dx.p < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon; else inverse_slope.p=dx.p < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon; } else { slope.p=dy.p/dx.p; inverse_slope.p=(-1.0*PerceptibleReciprocal(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)) (void) 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; stroke_q[p++]=box_q[0]; stroke_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) < MagickEpsilon) { if (dx.q >= 0.0) slope.q=dy.q < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon; else slope.q=dy.q < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon; } else if (fabs(dy.q) < MagickEpsilon) { if (dy.q >= 0.0) inverse_slope.q=dx.q < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon; else inverse_slope.q=dx.q < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon; } 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)) < MagickEpsilon) { 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); } DisableMSCWarning(4127) CheckPathExtent(MaxStrokePad,MaxStrokePad); RestoreMSCWarning dot_product=dx.q*dy.p-dx.p*dy.q; if (dot_product <= 0.0) switch (draw_info->linejoin) { case BevelJoin: { stroke_q[q++]=box_q[1]; stroke_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) stroke_p[p++]=box_p[4]; else { stroke_p[p++]=box_p[1]; stroke_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) { stroke_q[q++]=box_q[4]; stroke_p[p++]=box_p[4]; } else { stroke_q[q++]=box_q[1]; stroke_q[q++]=box_q[2]; stroke_p[p++]=box_p[1]; stroke_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) stroke_p[p++]=box_p[4]; else { stroke_p[p++]=box_p[1]; stroke_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) CastDoubleToLong(ceil((double) ((theta. q-theta.p)/(2.0*sqrt(PerceptibleReciprocal(mid)))))); DisableMSCWarning(4127) CheckPathExtent(MaxStrokePad,arc_segments+MaxStrokePad); RestoreMSCWarning stroke_q[q].x=box_q[1].x; stroke_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); stroke_q[q].x=(double) (center.x+mid*cos(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); stroke_q[q].y=(double) (center.y+mid*sin(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); q++; } stroke_q[q++]=box_q[2]; break; } default: break; } else switch (draw_info->linejoin) { case BevelJoin: { stroke_p[p++]=box_p[1]; stroke_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) stroke_q[q++]=box_q[4]; else { stroke_q[q++]=box_q[1]; stroke_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) { stroke_q[q++]=box_q[4]; stroke_p[p++]=box_p[4]; } else { stroke_q[q++]=box_q[1]; stroke_q[q++]=box_q[2]; stroke_p[p++]=box_p[1]; stroke_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) stroke_q[q++]=box_q[4]; else { stroke_q[q++]=box_q[1]; stroke_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) CastDoubleToLong(ceil((double) ((theta.p- theta.q)/(2.0*sqrt((double) (PerceptibleReciprocal(mid))))))); DisableMSCWarning(4127) CheckPathExtent(arc_segments+MaxStrokePad,MaxStrokePad); RestoreMSCWarning stroke_p[p++]=box_p[1]; for (j=1; j < (ssize_t) arc_segments; j++) { delta_theta=(double) (j*(theta.q-theta.p)/arc_segments); stroke_p[p].x=(double) (center.x+mid*cos(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); stroke_p[p].y=(double) (center.y+mid*sin(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); p++; } stroke_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; } stroke_p[p++]=box_p[1]; stroke_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) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p); stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q); polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory( polygon_primitive); return(stroke_polygon); } for (i=0; i < (ssize_t) p; i++) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=stroke_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=stroke_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); stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p); stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q); polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive); return(stroke_polygon); }
perftest.c
/** * Copyright (C) Mellanox Technologies Ltd. 2001-2014. ALL RIGHTS RESERVED. * Copyright (C) The University of Tennessee and The University * of Tennessee Research Foundation. 2015. ALL RIGHTS RESERVED. * Copyright (C) UT-Battelle, LLC. 2015. ALL RIGHTS RESERVED. * * See file LICENSE for terms. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "api/libperf.h" #include "lib/libperf_int.h" #include <ucs/sys/string.h> #include <ucs/sys/sys.h> #include <ucs/sys/sock.h> #include <ucs/debug/log.h> #include <sys/socket.h> #include <arpa/inet.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <netdb.h> #include <getopt.h> #include <string.h> #include <sys/types.h> #include <sys/poll.h> #include <locale.h> #if defined (HAVE_MPI) # include <mpi.h> #elif defined (HAVE_RTE) # include<rte.h> #endif #define MAX_BATCH_FILES 32 #define MAX_CPUS 1024 #define TL_RESOURCE_NAME_NONE "<none>" #define TEST_PARAMS_ARGS "t:n:s:W:O:w:D:i:H:oSCIqM:r:E:T:d:x:A:BUm:" #define TEST_ID_UNDEFINED -1 enum { TEST_FLAG_PRINT_RESULTS = UCS_BIT(0), TEST_FLAG_PRINT_TEST = UCS_BIT(1), TEST_FLAG_SET_AFFINITY = UCS_BIT(8), TEST_FLAG_NUMERIC_FMT = UCS_BIT(9), TEST_FLAG_PRINT_FINAL = UCS_BIT(10), TEST_FLAG_PRINT_CSV = UCS_BIT(11) }; typedef struct sock_rte_group { int is_server; int connfd; } sock_rte_group_t; typedef struct test_type { const char *name; ucx_perf_api_t api; ucx_perf_cmd_t command; ucx_perf_test_type_t test_type; const char *desc; const char *overhead_lat; unsigned window_size; } test_type_t; typedef struct perftest_params { ucx_perf_params_t super; int test_id; } perftest_params_t; struct perftest_context { perftest_params_t params; const char *server_addr; int port; int mpi; unsigned num_cpus; unsigned cpus[MAX_CPUS]; unsigned flags; unsigned num_batch_files; char *batch_files[MAX_BATCH_FILES]; char *test_names[MAX_BATCH_FILES]; sock_rte_group_t sock_rte_group; }; test_type_t tests[] = { {"am_lat", UCX_PERF_API_UCT, UCX_PERF_CMD_AM, UCX_PERF_TEST_TYPE_PINGPONG, "active message latency", "latency", 1}, {"put_lat", UCX_PERF_API_UCT, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_PINGPONG, "put latency", "latency", 1}, {"add_lat", UCX_PERF_API_UCT, UCX_PERF_CMD_ADD, UCX_PERF_TEST_TYPE_PINGPONG, "atomic add latency", "latency", 1}, {"get", UCX_PERF_API_UCT, UCX_PERF_CMD_GET, UCX_PERF_TEST_TYPE_STREAM_UNI, "get latency / bandwidth / message rate", "latency", 1}, {"fadd", UCX_PERF_API_UCT, UCX_PERF_CMD_FADD, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic fetch-and-add latency / rate", "latency", 1}, {"swap", UCX_PERF_API_UCT, UCX_PERF_CMD_SWAP, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic swap latency / rate", "latency", 1}, {"cswap", UCX_PERF_API_UCT, UCX_PERF_CMD_CSWAP, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic compare-and-swap latency / rate", "latency", 1}, {"am_bw", UCX_PERF_API_UCT, UCX_PERF_CMD_AM, UCX_PERF_TEST_TYPE_STREAM_UNI, "active message bandwidth / message rate", "overhead", 1}, {"put_bw", UCX_PERF_API_UCT, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_STREAM_UNI, "put bandwidth / message rate", "overhead", 1}, {"add_mr", UCX_PERF_API_UCT, UCX_PERF_CMD_ADD, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic add message rate", "overhead", 1}, {"tag_lat", UCX_PERF_API_UCP, UCX_PERF_CMD_TAG, UCX_PERF_TEST_TYPE_PINGPONG, "tag match latency", "latency", 1}, {"tag_bw", UCX_PERF_API_UCP, UCX_PERF_CMD_TAG, UCX_PERF_TEST_TYPE_STREAM_UNI, "tag match bandwidth", "overhead", 32}, {"tag_sync_lat", UCX_PERF_API_UCP, UCX_PERF_CMD_TAG_SYNC, UCX_PERF_TEST_TYPE_PINGPONG, "tag sync match latency", "latency", 1}, {"tag_sync_bw", UCX_PERF_API_UCP, UCX_PERF_CMD_TAG_SYNC, UCX_PERF_TEST_TYPE_STREAM_UNI, "tag sync match bandwidth", "overhead", 32}, {"ucp_put_lat", UCX_PERF_API_UCP, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_PINGPONG, "put latency", "latency", 1}, {"ucp_put_bw", UCX_PERF_API_UCP, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_STREAM_UNI, "put bandwidth", "overhead", 32}, {"ucp_get", UCX_PERF_API_UCP, UCX_PERF_CMD_GET, UCX_PERF_TEST_TYPE_STREAM_UNI, "get latency / bandwidth / message rate", "latency", 1}, {"ucp_add", UCX_PERF_API_UCP, UCX_PERF_CMD_ADD, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic add bandwidth / message rate", "overhead", 1}, {"ucp_fadd", UCX_PERF_API_UCP, UCX_PERF_CMD_FADD, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic fetch-and-add latency / bandwidth / rate", "latency", 1}, {"ucp_swap", UCX_PERF_API_UCP, UCX_PERF_CMD_SWAP, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic swap latency / bandwidth / rate", "latency", 1}, {"ucp_cswap", UCX_PERF_API_UCP, UCX_PERF_CMD_CSWAP, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic compare-and-swap latency / bandwidth / rate", "latency", 1}, {"stream_bw", UCX_PERF_API_UCP, UCX_PERF_CMD_STREAM, UCX_PERF_TEST_TYPE_STREAM_UNI, "stream bandwidth", "overhead", 1}, {"stream_lat", UCX_PERF_API_UCP, UCX_PERF_CMD_STREAM, UCX_PERF_TEST_TYPE_PINGPONG, "stream latency", "latency", 1}, {NULL} }; static int sock_io(int sock, ssize_t (*sock_call)(int, void *, size_t, int), int poll_events, void *data, size_t size, void (*progress)(void *arg), void *arg, const char *name) { size_t total = 0; struct pollfd pfd; int ret; while (total < size) { pfd.fd = sock; pfd.events = poll_events; pfd.revents = 0; ret = poll(&pfd, 1, 1); /* poll for 1ms */ if (ret > 0) { ucs_assert(ret == 1); ucs_assert(pfd.revents & poll_events); ret = sock_call(sock, (char*)data + total, size - total, 0); if (ret < 0) { ucs_error("%s() failed: %m", name); return -1; } total += ret; } else if ((ret < 0) && (errno != EINTR)) { ucs_error("poll(fd=%d) failed: %m", sock); return -1; } /* progress user context */ if (progress != NULL) { progress(arg); } } return 0; } static int safe_send(int sock, void *data, size_t size, void (*progress)(void *arg), void *arg) { typedef ssize_t (*sock_call)(int, void *, size_t, int); return sock_io(sock, (sock_call)send, POLLOUT, data, size, progress, arg, "send"); } static int safe_recv(int sock, void *data, size_t size, void (*progress)(void *arg), void *arg) { return sock_io(sock, recv, POLLIN, data, size, progress, arg, "recv"); } static void print_progress(char **test_names, unsigned num_names, const ucx_perf_result_t *result, unsigned flags, int final, int is_server, int is_multi_thread) { static const char *fmt_csv; static const char *fmt_numeric; static const char *fmt_plain; unsigned i; if (!(flags & TEST_FLAG_PRINT_RESULTS) || (!final && (flags & TEST_FLAG_PRINT_FINAL))) { return; } if (flags & TEST_FLAG_PRINT_CSV) { for (i = 0; i < num_names; ++i) { printf("%s,", test_names[i]); } } #if _OPENMP if (!final) { printf("[thread %d]", omp_get_thread_num()); } else if (flags & TEST_FLAG_PRINT_RESULTS) { printf("Final: "); } #endif if (is_multi_thread && final) { fmt_csv = "%4.0f,%.3f,%.2f,%.0f\n"; fmt_numeric = "%'18.0f %29.3f %22.2f %'24.0f\n"; fmt_plain = "%18.0f %29.3f %22.2f %23.0f\n"; printf((flags & TEST_FLAG_PRINT_CSV) ? fmt_csv : (flags & TEST_FLAG_NUMERIC_FMT) ? fmt_numeric : fmt_plain, (double)result->iters, result->latency.total_average * 1000000.0, result->bandwidth.total_average / (1024.0 * 1024.0), result->msgrate.total_average); } else { fmt_csv = "%4.0f,%.3f,%.3f,%.3f,%.2f,%.2f,%.0f,%.0f\n"; fmt_numeric = "%'18.0f %9.3f %9.3f %9.3f %11.2f %10.2f %'11.0f %'11.0f\n"; fmt_plain = "%18.0f %9.3f %9.3f %9.3f %11.2f %10.2f %11.0f %11.0f\n"; printf((flags & TEST_FLAG_PRINT_CSV) ? fmt_csv : (flags & TEST_FLAG_NUMERIC_FMT) ? fmt_numeric : fmt_plain, (double)result->iters, result->latency.typical * 1000000.0, result->latency.moment_average * 1000000.0, result->latency.total_average * 1000000.0, result->bandwidth.moment_average / (1024.0 * 1024.0), result->bandwidth.total_average / (1024.0 * 1024.0), result->msgrate.moment_average, result->msgrate.total_average); } fflush(stdout); } static void print_header(struct perftest_context *ctx) { const char *overhead_lat_str; const char *test_data_str; const char *test_api_str; test_type_t *test; unsigned i; test = (ctx->params.test_id == TEST_ID_UNDEFINED) ? NULL : &tests[ctx->params.test_id]; if ((ctx->flags & TEST_FLAG_PRINT_TEST) && (test != NULL)) { if (test->api == UCX_PERF_API_UCT) { test_api_str = "transport layer"; switch (ctx->params.super.uct.data_layout) { case UCT_PERF_DATA_LAYOUT_SHORT: test_data_str = "short"; break; case UCT_PERF_DATA_LAYOUT_SHORT_IOV: test_data_str = "short iov"; break; case UCT_PERF_DATA_LAYOUT_BCOPY: test_data_str = "bcopy"; break; case UCT_PERF_DATA_LAYOUT_ZCOPY: test_data_str = "zcopy"; break; default: test_data_str = "(undefined)"; break; } } else if (test->api == UCX_PERF_API_UCP) { test_api_str = "protocol layer"; test_data_str = "(automatic)"; /* TODO contig/stride/stream */ } else { return; } printf("+------------------------------------------------------------------------------------------+\n"); printf("| API: %-60s |\n", test_api_str); printf("| Test: %-60s |\n", test->desc); printf("| Data layout: %-60s |\n", test_data_str); printf("| Send memory: %-60s |\n", ucs_memory_type_names[ctx->params.super.send_mem_type]); printf("| Recv memory: %-60s |\n", ucs_memory_type_names[ctx->params.super.recv_mem_type]); printf("| Message size: %-60zu |\n", ucx_perf_get_message_size(&ctx->params.super)); } if (ctx->flags & TEST_FLAG_PRINT_CSV) { if (ctx->flags & TEST_FLAG_PRINT_RESULTS) { for (i = 0; i < ctx->num_batch_files; ++i) { printf("%s,", ucs_basename(ctx->batch_files[i])); } printf("iterations,typical_lat,avg_lat,overall_lat,avg_bw,overall_bw,avg_mr,overall_mr\n"); } } else { if (ctx->flags & TEST_FLAG_PRINT_RESULTS) { overhead_lat_str = (test == NULL) ? "overhead" : test->overhead_lat; printf("+--------------+--------------+-----------------------------+---------------------+-----------------------+\n"); printf("| | | %8s (usec) | bandwidth (MB/s) | message rate (msg/s) |\n", overhead_lat_str); printf("+--------------+--------------+---------+---------+---------+----------+----------+-----------+-----------+\n"); printf("| Stage | # iterations | typical | average | overall | average | overall | average | overall |\n"); printf("+--------------+--------------+---------+---------+---------+----------+----------+-----------+-----------+\n"); } else if (ctx->flags & TEST_FLAG_PRINT_TEST) { printf("+------------------------------------------------------------------------------------------+\n"); } } } static void print_test_name(struct perftest_context *ctx) { char buf[200]; unsigned i, pos; if (!(ctx->flags & TEST_FLAG_PRINT_CSV) && (ctx->num_batch_files > 0)) { strcpy(buf, "+--------------+--------------+---------+---------+---------+----------+----------+-----------+-----------+"); pos = 1; for (i = 0; i < ctx->num_batch_files; ++i) { if (i != 0) { buf[pos++] = '/'; } memcpy(&buf[pos], ctx->test_names[i], ucs_min(strlen(ctx->test_names[i]), sizeof(buf) - pos - 1)); pos += strlen(ctx->test_names[i]); } if (ctx->flags & TEST_FLAG_PRINT_RESULTS) { printf("%s\n", buf); } } } static void print_memory_type_usage(void) { ucs_memory_type_t it; for (it = UCS_MEMORY_TYPE_HOST; it < UCS_MEMORY_TYPE_LAST; it++) { if (ucx_perf_mem_type_allocators[it] != NULL) { printf(" %s - %s\n", ucs_memory_type_names[it], ucs_memory_type_descs[it]); } } } static void usage(const struct perftest_context *ctx, const char *program) { static const char* api_names[] = { [UCX_PERF_API_UCT] = "UCT", [UCX_PERF_API_UCP] = "UCP" }; test_type_t *test; int UCS_V_UNUSED rank; #ifdef HAVE_MPI MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (ctx->mpi && (rank != 0)) { return; } #endif #if defined (HAVE_MPI) printf(" Note: test can be also launched as an MPI application\n"); printf("\n"); #elif defined (HAVE_RTE) printf(" Note: this test can be also launched as an libRTE application\n"); printf("\n"); #endif printf(" Usage: %s [ server-hostname ] [ options ]\n", program); printf("\n"); printf(" Common options:\n"); printf(" -t <test> test to run:\n"); for (test = tests; test->name; ++test) { printf(" %13s - %s %s\n", test->name, api_names[test->api], test->desc); } printf("\n"); printf(" -s <size> list of scatter-gather sizes for single message (%zu)\n", ctx->params.super.msg_size_list[0]); printf(" for example: \"-s 16,48,8192,8192,14\"\n"); printf(" -m <send mem type>[,<recv mem type>]\n"); printf(" memory type of message for sender and receiver (host)\n"); print_memory_type_usage(); printf(" -n <iters> number of iterations to run (%"PRIu64")\n", ctx->params.super.max_iter); printf(" -w <iters> number of warm-up iterations (%"PRIu64")\n", ctx->params.super.warmup_iter); printf(" -c <cpulist> set affinity to this CPU list (separated by comma) (off)\n"); printf(" -O <count> maximal number of uncompleted outstanding sends\n"); printf(" -i <offset> distance between consecutive scatter-gather entries (%zu)\n", ctx->params.super.iov_stride); printf(" -T <threads> number of threads in the test (%d)\n", ctx->params.super.thread_count); printf(" -o do not progress the responder in one-sided tests\n"); printf(" -B register memory with NONBLOCK flag\n"); printf(" -b <file> read and execute tests from a batch file: every line in the\n"); printf(" file is a test to run, first word is test name, the rest of\n"); printf(" the line is command-line arguments for the test.\n"); printf(" -p <port> TCP port to use for data exchange (%d)\n", ctx->port); #ifdef HAVE_MPI printf(" -P <0|1> disable/enable MPI mode (%d)\n", ctx->mpi); #endif printf(" -h show this help message\n"); printf("\n"); printf(" Output format:\n"); printf(" -N use numeric formatting (thousands separator)\n"); printf(" -f print only final numbers\n"); printf(" -v print CSV-formatted output\n"); printf("\n"); printf(" UCT only:\n"); printf(" -d <device> device to use for testing\n"); printf(" -x <tl> transport to use for testing\n"); printf(" -D <layout> data layout for sender side:\n"); printf(" short - short messages (default, cannot be used for get)\n"); printf(" shortiov - short io-vector messages (only for active messages)\n"); printf(" bcopy - copy-out (cannot be used for atomics)\n"); printf(" zcopy - zero-copy (cannot be used for atomics)\n"); printf(" iov - scatter-gather list (iovec)\n"); printf(" -W <count> flow control window size, for active messages (%u)\n", ctx->params.super.uct.fc_window); printf(" -H <size> active message header size (%zu)\n", ctx->params.super.am_hdr_size); printf(" -A <mode> asynchronous progress mode (thread_spinlock)\n"); printf(" thread_spinlock - separate progress thread with spin locking\n"); printf(" thread_mutex - separate progress thread with mutex locking\n"); printf(" signal - signal-based timer\n"); printf("\n"); printf(" UCP only:\n"); printf(" -M <thread> thread support level for progress engine (single)\n"); printf(" single - only the master thread can access\n"); printf(" serialized - one thread can access at a time\n"); printf(" multi - multiple threads can access\n"); printf(" -D <layout>[,<layout>]\n"); printf(" data layout for sender and receiver side (contig)\n"); printf(" contig - Continuous datatype\n"); printf(" iov - Scatter-gather list\n"); printf(" -C use wild-card tag for tag tests\n"); printf(" -U force unexpected flow by using tag probe\n"); printf(" -r <mode> receive mode for stream tests (recv)\n"); printf(" recv : Use ucp_stream_recv_nb\n"); printf(" recv_data : Use ucp_stream_recv_data_nb\n"); printf(" -I create context with wakeup feature enabled\n"); printf(" -E <mode> wait mode for tests\n"); printf(" poll : repeatedly call worker_progress\n"); printf(" sleep : go to sleep after posting requests\n"); printf("\n"); printf(" NOTE: When running UCP tests, transport and device should be specified by\n"); printf(" environment variables: UCX_TLS and UCX_[SELF|SHM|NET]_DEVICES.\n"); printf("\n"); } static ucs_status_t parse_ucp_datatype_params(const char *opt_arg, ucp_perf_datatype_t *datatype) { const char *iov_type = "iov"; const size_t iov_type_size = strlen("iov"); const char *contig_type = "contig"; const size_t contig_type_size = strlen("contig"); if (0 == strncmp(opt_arg, iov_type, iov_type_size)) { *datatype = UCP_PERF_DATATYPE_IOV; } else if (0 == strncmp(opt_arg, contig_type, contig_type_size)) { *datatype = UCP_PERF_DATATYPE_CONTIG; } else { return UCS_ERR_INVALID_PARAM; } return UCS_OK; } static ucs_status_t parse_mem_type(const char *opt_arg, ucs_memory_type_t *mem_type) { ucs_memory_type_t it; for (it = UCS_MEMORY_TYPE_HOST; it < UCS_MEMORY_TYPE_LAST; it++) { if(!strcmp(opt_arg, ucs_memory_type_names[it]) && (ucx_perf_mem_type_allocators[it] != NULL)) { *mem_type = it; return UCS_OK; } } ucs_error("Unsupported memory type: \"%s\"", opt_arg); return UCS_ERR_INVALID_PARAM; } static ucs_status_t parse_mem_type_params(const char *opt_arg, ucs_memory_type_t *send_mem_type, ucs_memory_type_t *recv_mem_type) { const char *delim = ","; char *token = strtok((char*)opt_arg, delim); if (UCS_OK != parse_mem_type(token, send_mem_type)) { return UCS_ERR_INVALID_PARAM; } token = strtok(NULL, delim); if (NULL == token) { *recv_mem_type = *send_mem_type; return UCS_OK; } else { return parse_mem_type(token, recv_mem_type); } } static ucs_status_t parse_message_sizes_params(const char *opt_arg, ucx_perf_params_t *params) { const char delim = ','; size_t *msg_size_list, token_num, token_it; char *optarg_ptr, *optarg_ptr2; optarg_ptr = (char *)opt_arg; token_num = 0; /* count the number of given message sizes */ while ((optarg_ptr = strchr(optarg_ptr, delim)) != NULL) { ++optarg_ptr; ++token_num; } ++token_num; msg_size_list = realloc(params->msg_size_list, sizeof(*params->msg_size_list) * token_num); if (NULL == msg_size_list) { return UCS_ERR_NO_MEMORY; } params->msg_size_list = msg_size_list; optarg_ptr = (char *)opt_arg; errno = 0; for (token_it = 0; token_it < token_num; ++token_it) { params->msg_size_list[token_it] = strtoul(optarg_ptr, &optarg_ptr2, 10); if (((ERANGE == errno) && (ULONG_MAX == params->msg_size_list[token_it])) || ((errno != 0) && (params->msg_size_list[token_it] == 0)) || (optarg_ptr == optarg_ptr2)) { free(params->msg_size_list); params->msg_size_list = NULL; /* prevent double free */ ucs_error("Invalid option substring argument at position %lu", token_it); return UCS_ERR_INVALID_PARAM; } optarg_ptr = optarg_ptr2 + 1; } params->msg_size_cnt = token_num; return UCS_OK; } static ucs_status_t init_test_params(perftest_params_t *params) { memset(params, 0, sizeof(*params)); params->super.api = UCX_PERF_API_LAST; params->super.command = UCX_PERF_CMD_LAST; params->super.test_type = UCX_PERF_TEST_TYPE_LAST; params->super.thread_mode = UCS_THREAD_MODE_SINGLE; params->super.thread_count = 1; params->super.async_mode = UCS_ASYNC_THREAD_LOCK_TYPE; params->super.wait_mode = UCX_PERF_WAIT_MODE_LAST; params->super.max_outstanding = 0; params->super.warmup_iter = 10000; params->super.am_hdr_size = 8; params->super.alignment = ucs_get_page_size(); params->super.max_iter = 1000000l; params->super.max_time = 0.0; params->super.report_interval = 1.0; params->super.flags = UCX_PERF_TEST_FLAG_VERBOSE; params->super.uct.fc_window = UCT_PERF_TEST_MAX_FC_WINDOW; params->super.uct.data_layout = UCT_PERF_DATA_LAYOUT_SHORT; params->super.send_mem_type = UCS_MEMORY_TYPE_HOST; params->super.recv_mem_type = UCS_MEMORY_TYPE_HOST; params->super.msg_size_cnt = 1; params->super.iov_stride = 0; params->super.ucp.send_datatype = UCP_PERF_DATATYPE_CONTIG; params->super.ucp.recv_datatype = UCP_PERF_DATATYPE_CONTIG; strcpy(params->super.uct.dev_name, TL_RESOURCE_NAME_NONE); strcpy(params->super.uct.tl_name, TL_RESOURCE_NAME_NONE); params->super.msg_size_list = calloc(params->super.msg_size_cnt, sizeof(*params->super.msg_size_list)); if (params->super.msg_size_list == NULL) { return UCS_ERR_NO_MEMORY; } params->super.msg_size_list[0] = 8; params->test_id = TEST_ID_UNDEFINED; return UCS_OK; } static ucs_status_t parse_test_params(perftest_params_t *params, char opt, const char *opt_arg) { char *optarg2 = NULL; test_type_t *test; unsigned i; switch (opt) { case 'd': ucs_snprintf_zero(params->super.uct.dev_name, sizeof(params->super.uct.dev_name), "%s", opt_arg); return UCS_OK; case 'x': ucs_snprintf_zero(params->super.uct.tl_name, sizeof(params->super.uct.tl_name), "%s", opt_arg); return UCS_OK; case 't': for (i = 0; tests[i].name != NULL; ++i) { test = &tests[i]; if (!strcmp(opt_arg, test->name)) { params->super.api = test->api; params->super.command = test->command; params->super.test_type = test->test_type; params->test_id = i; break; } } if (params->test_id == TEST_ID_UNDEFINED) { ucs_error("Invalid option argument for -t"); return UCS_ERR_INVALID_PARAM; } return UCS_OK; case 'D': if (!strcmp(opt_arg, "short")) { params->super.uct.data_layout = UCT_PERF_DATA_LAYOUT_SHORT; } else if (!strcmp(opt_arg, "shortiov")) { params->super.uct.data_layout = UCT_PERF_DATA_LAYOUT_SHORT_IOV; } else if (!strcmp(opt_arg, "bcopy")) { params->super.uct.data_layout = UCT_PERF_DATA_LAYOUT_BCOPY; } else if (!strcmp(opt_arg, "zcopy")) { params->super.uct.data_layout = UCT_PERF_DATA_LAYOUT_ZCOPY; } else if (UCS_OK == parse_ucp_datatype_params(opt_arg, &params->super.ucp.send_datatype)) { optarg2 = strchr(opt_arg, ','); if (optarg2) { if (UCS_OK != parse_ucp_datatype_params(optarg2 + 1, &params->super.ucp.recv_datatype)) { return UCS_ERR_INVALID_PARAM; } } } else { ucs_error("Invalid option argument for -D"); return UCS_ERR_INVALID_PARAM; } return UCS_OK; case 'E': if (!strcmp(opt_arg, "poll")) { params->super.wait_mode = UCX_PERF_WAIT_MODE_POLL; return UCS_OK; } else if (!strcmp(opt_arg, "sleep")) { params->super.wait_mode = UCX_PERF_WAIT_MODE_SLEEP; return UCS_OK; } else { ucs_error("Invalid option argument for -E"); return UCS_ERR_INVALID_PARAM; } return UCS_OK; case 'i': params->super.iov_stride = atol(opt_arg); return UCS_OK; case 'n': params->super.max_iter = atol(opt_arg); return UCS_OK; case 's': return parse_message_sizes_params(opt_arg, &params->super); case 'H': params->super.am_hdr_size = atol(opt_arg); return UCS_OK; case 'W': params->super.uct.fc_window = atoi(opt_arg); return UCS_OK; case 'O': params->super.max_outstanding = atoi(opt_arg); return UCS_OK; case 'w': params->super.warmup_iter = atol(opt_arg); return UCS_OK; case 'o': params->super.flags |= UCX_PERF_TEST_FLAG_ONE_SIDED; return UCS_OK; case 'B': params->super.flags |= UCX_PERF_TEST_FLAG_MAP_NONBLOCK; return UCS_OK; case 'q': params->super.flags &= ~UCX_PERF_TEST_FLAG_VERBOSE; return UCS_OK; case 'C': params->super.flags |= UCX_PERF_TEST_FLAG_TAG_WILDCARD; return UCS_OK; case 'U': params->super.flags |= UCX_PERF_TEST_FLAG_TAG_UNEXP_PROBE; return UCS_OK; case 'I': params->super.flags |= UCX_PERF_TEST_FLAG_WAKEUP; return UCS_OK; case 'M': if (!strcmp(opt_arg, "single")) { params->super.thread_mode = UCS_THREAD_MODE_SINGLE; return UCS_OK; } else if (!strcmp(opt_arg, "serialized")) { params->super.thread_mode = UCS_THREAD_MODE_SERIALIZED; return UCS_OK; } else if (!strcmp(opt_arg, "multi")) { params->super.thread_mode = UCS_THREAD_MODE_MULTI; return UCS_OK; } else { ucs_error("Invalid option argument for -M"); return UCS_ERR_INVALID_PARAM; } case 'T': params->super.thread_count = atoi(opt_arg); return UCS_OK; case 'A': if (!strcmp(opt_arg, "thread") || !strcmp(opt_arg, "thread_spinlock")) { params->super.async_mode = UCS_ASYNC_MODE_THREAD_SPINLOCK; return UCS_OK; } else if (!strcmp(opt_arg, "thread_mutex")) { params->super.async_mode = UCS_ASYNC_MODE_THREAD_MUTEX; return UCS_OK; } else if (!strcmp(opt_arg, "signal")) { params->super.async_mode = UCS_ASYNC_MODE_SIGNAL; return UCS_OK; } else { ucs_error("Invalid option argument for -A"); return UCS_ERR_INVALID_PARAM; } case 'r': if (!strcmp(opt_arg, "recv_data")) { params->super.flags |= UCX_PERF_TEST_FLAG_STREAM_RECV_DATA; return UCS_OK; } else if (!strcmp(opt_arg, "recv")) { params->super.flags &= ~UCX_PERF_TEST_FLAG_STREAM_RECV_DATA; return UCS_OK; } return UCS_ERR_INVALID_PARAM; case 'm': if (UCS_OK != parse_mem_type_params(opt_arg, &params->super.send_mem_type, &params->super.recv_mem_type)) { return UCS_ERR_INVALID_PARAM; } return UCS_OK; default: return UCS_ERR_INVALID_PARAM; } } static ucs_status_t adjust_test_params(perftest_params_t *params, const char *error_prefix) { test_type_t *test; if (params->test_id == TEST_ID_UNDEFINED) { ucs_error("%smissing test name", error_prefix); return UCS_ERR_INVALID_PARAM; } test = &tests[params->test_id]; if (params->super.max_outstanding == 0) { params->super.max_outstanding = test->window_size; } return UCS_OK; } static ucs_status_t read_batch_file(FILE *batch_file, const char *file_name, int *line_num, perftest_params_t *params, char** test_name_p) { #define MAX_SIZE 256 #define MAX_ARG_SIZE 2048 ucs_status_t status; char buf[MAX_ARG_SIZE]; char error_prefix[MAX_ARG_SIZE]; int argc; char *argv[MAX_SIZE + 1]; int c; char *p; do { if (fgets(buf, sizeof(buf) - 1, batch_file) == NULL) { return UCS_ERR_NO_ELEM; } ++(*line_num); argc = 0; p = strtok(buf, " \t\n\r"); while (p && (argc < MAX_SIZE)) { argv[argc++] = p; p = strtok(NULL, " \t\n\r"); } argv[argc] = NULL; } while ((argc == 0) || (argv[0][0] == '#')); ucs_snprintf_safe(error_prefix, sizeof(error_prefix), "in batch file '%s' line %d: ", file_name, *line_num); optind = 1; while ((c = getopt (argc, argv, TEST_PARAMS_ARGS)) != -1) { status = parse_test_params(params, c, optarg); if (status != UCS_OK) { ucs_error("%s-%c %s: %s", error_prefix, c, optarg, ucs_status_string(status)); return status; } } status = adjust_test_params(params, error_prefix); if (status != UCS_OK) { return status; } *test_name_p = strdup(argv[0]); return UCS_OK; } static ucs_status_t parse_cpus(char *opt_arg, struct perftest_context *ctx) { char *endptr, *cpu_list = opt_arg; int cpu; ctx->num_cpus = 0; cpu = strtol(cpu_list, &endptr, 10); while (((*endptr == ',') || (*endptr == '\0')) && (ctx->num_cpus < MAX_CPUS)) { if (cpu < 0) { ucs_error("invalid cpu number detected: (%d)", cpu); return UCS_ERR_INVALID_PARAM; } ctx->cpus[ctx->num_cpus++] = cpu; if (*endptr == '\0') { break; } cpu_list = endptr + 1; /* skip the comma */ cpu = strtol(cpu_list, &endptr, 10); } if (*endptr == ',') { ucs_error("number of listed cpus exceeds the maximum supported value (%d)", MAX_CPUS); return UCS_ERR_INVALID_PARAM; } return UCS_OK; } static ucs_status_t parse_opts(struct perftest_context *ctx, int mpi_initialized, int argc, char **argv) { ucs_status_t status; int c; ucs_trace_func(""); ucx_perf_global_init(); /* initialize memory types */ status = init_test_params(&ctx->params); if (status != UCS_OK) { return status; } ctx->server_addr = NULL; ctx->num_batch_files = 0; ctx->port = 13337; ctx->flags = 0; ctx->mpi = mpi_initialized; optind = 1; while ((c = getopt (argc, argv, "p:b:Nfvc:P:h" TEST_PARAMS_ARGS)) != -1) { switch (c) { case 'p': ctx->port = atoi(optarg); break; case 'b': if (ctx->num_batch_files < MAX_BATCH_FILES) { ctx->batch_files[ctx->num_batch_files++] = optarg; } break; case 'N': ctx->flags |= TEST_FLAG_NUMERIC_FMT; break; case 'f': ctx->flags |= TEST_FLAG_PRINT_FINAL; break; case 'v': ctx->flags |= TEST_FLAG_PRINT_CSV; break; case 'c': ctx->flags |= TEST_FLAG_SET_AFFINITY; status = parse_cpus(optarg, ctx); if (status != UCS_OK) { return status; } break; case 'P': #ifdef HAVE_MPI ctx->mpi = atoi(optarg) && mpi_initialized; break; #endif case 'h': usage(ctx, ucs_basename(argv[0])); return UCS_ERR_CANCELED; default: status = parse_test_params(&ctx->params, c, optarg); if (status != UCS_OK) { usage(ctx, ucs_basename(argv[0])); return status; } break; } } if (optind < argc) { ctx->server_addr = argv[optind]; } return UCS_OK; } static unsigned sock_rte_group_size(void *rte_group) { return 2; } static unsigned sock_rte_group_index(void *rte_group) { sock_rte_group_t *group = rte_group; return group->is_server ? 0 : 1; } static void sock_rte_barrier(void *rte_group, void (*progress)(void *arg), void *arg) { #pragma omp barrier #pragma omp master { sock_rte_group_t *group = rte_group; const unsigned magic = 0xdeadbeef; unsigned snc; snc = magic; safe_send(group->connfd, &snc, sizeof(unsigned), progress, arg); snc = 0; safe_recv(group->connfd, &snc, sizeof(unsigned), progress, arg); ucs_assert(snc == magic); } #pragma omp barrier } static void sock_rte_post_vec(void *rte_group, const struct iovec *iovec, int iovcnt, void **req) { sock_rte_group_t *group = rte_group; size_t size; int i; size = 0; for (i = 0; i < iovcnt; ++i) { size += iovec[i].iov_len; } safe_send(group->connfd, &size, sizeof(size), NULL, NULL); for (i = 0; i < iovcnt; ++i) { safe_send(group->connfd, iovec[i].iov_base, iovec[i].iov_len, NULL, NULL); } } static void sock_rte_recv(void *rte_group, unsigned src, void *buffer, size_t max, void *req) { sock_rte_group_t *group = rte_group; int group_index; size_t size; group_index = sock_rte_group_index(rte_group); if (src == group_index) { return; } ucs_assert_always(src == (1 - group_index)); safe_recv(group->connfd, &size, sizeof(size), NULL, NULL); ucs_assert_always(size <= max); safe_recv(group->connfd, buffer, size, NULL, NULL); } static void sock_rte_report(void *rte_group, const ucx_perf_result_t *result, void *arg, int is_final, int is_multi_thread) { struct perftest_context *ctx = arg; print_progress(ctx->test_names, ctx->num_batch_files, result, ctx->flags, is_final, ctx->server_addr == NULL, is_multi_thread); } static ucx_perf_rte_t sock_rte = { .group_size = sock_rte_group_size, .group_index = sock_rte_group_index, .barrier = sock_rte_barrier, .post_vec = sock_rte_post_vec, .recv = sock_rte_recv, .exchange_vec = (ucx_perf_rte_exchange_vec_func_t)ucs_empty_function, .report = sock_rte_report, }; static ucs_status_t setup_sock_rte(struct perftest_context *ctx) { struct sockaddr_in inaddr; struct hostent *he; ucs_status_t status; int optval = 1; int sockfd, connfd; int ret; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { ucs_error("socket() failed: %m"); status = UCS_ERR_IO_ERROR; goto err; } if (ctx->server_addr == NULL) { optval = 1; status = ucs_socket_setopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); if (status != UCS_OK) { goto err_close_sockfd; } inaddr.sin_family = AF_INET; inaddr.sin_port = htons(ctx->port); inaddr.sin_addr.s_addr = INADDR_ANY; memset(inaddr.sin_zero, 0, sizeof(inaddr.sin_zero)); ret = bind(sockfd, (struct sockaddr*)&inaddr, sizeof(inaddr)); if (ret < 0) { ucs_error("bind() failed: %m"); status = UCS_ERR_INVALID_ADDR; goto err_close_sockfd; } ret = listen(sockfd, 10); if (ret < 0) { ucs_error("listen() failed: %m"); status = UCS_ERR_IO_ERROR; goto err_close_sockfd; } printf("Waiting for connection...\n"); /* Accept next connection */ connfd = accept(sockfd, NULL, NULL); if (connfd < 0) { ucs_error("accept() failed: %m"); status = UCS_ERR_IO_ERROR; goto err_close_sockfd; } close(sockfd); /* release the memory for the list of the message sizes allocated * during the initialization of the default testing parameters */ free(ctx->params.super.msg_size_list); ctx->params.super.msg_size_list = NULL; ret = safe_recv(connfd, &ctx->params, sizeof(ctx->params), NULL, NULL); if (ret) { status = UCS_ERR_IO_ERROR; goto err_close_connfd; } if (ctx->params.super.msg_size_cnt != 0) { ctx->params.super.msg_size_list = calloc(ctx->params.super.msg_size_cnt, sizeof(*ctx->params.super.msg_size_list)); if (NULL == ctx->params.super.msg_size_list) { status = UCS_ERR_NO_MEMORY; goto err_close_connfd; } ret = safe_recv(connfd, ctx->params.super.msg_size_list, sizeof(*ctx->params.super.msg_size_list) * ctx->params.super.msg_size_cnt, NULL, NULL); if (ret) { status = UCS_ERR_IO_ERROR; goto err_close_connfd; } } ctx->sock_rte_group.connfd = connfd; ctx->sock_rte_group.is_server = 1; } else { he = gethostbyname(ctx->server_addr); if (he == NULL || he->h_addr_list == NULL) { ucs_error("host %s not found: %s", ctx->server_addr, hstrerror(h_errno)); status = UCS_ERR_INVALID_ADDR; goto err_close_sockfd; } inaddr.sin_family = he->h_addrtype; inaddr.sin_port = htons(ctx->port); ucs_assert(he->h_length == sizeof(inaddr.sin_addr)); memcpy(&inaddr.sin_addr, he->h_addr_list[0], he->h_length); memset(inaddr.sin_zero, 0, sizeof(inaddr.sin_zero)); ret = connect(sockfd, (struct sockaddr*)&inaddr, sizeof(inaddr)); if (ret < 0) { ucs_error("connect() failed: %m"); status = UCS_ERR_UNREACHABLE; goto err_close_sockfd; } safe_send(sockfd, &ctx->params, sizeof(ctx->params), NULL, NULL); if (ctx->params.super.msg_size_cnt != 0) { safe_send(sockfd, ctx->params.super.msg_size_list, sizeof(*ctx->params.super.msg_size_list) * ctx->params.super.msg_size_cnt, NULL, NULL); } ctx->sock_rte_group.connfd = sockfd; ctx->sock_rte_group.is_server = 0; } if (ctx->sock_rte_group.is_server) { ctx->flags |= TEST_FLAG_PRINT_TEST; } else { ctx->flags |= TEST_FLAG_PRINT_RESULTS; } ctx->params.super.rte_group = &ctx->sock_rte_group; ctx->params.super.rte = &sock_rte; ctx->params.super.report_arg = ctx; return UCS_OK; err_close_connfd: close(connfd); goto err; err_close_sockfd: close(sockfd); err: return status; } static ucs_status_t cleanup_sock_rte(struct perftest_context *ctx) { close(ctx->sock_rte_group.connfd); return UCS_OK; } #if defined (HAVE_MPI) static unsigned mpi_rte_group_size(void *rte_group) { int size; MPI_Comm_size(MPI_COMM_WORLD, &size); return size; } static unsigned mpi_rte_group_index(void *rte_group) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); return rank; } static void mpi_rte_barrier(void *rte_group, void (*progress)(void *arg), void *arg) { int group_size, my_rank, i; MPI_Request *reqs; int nreqs = 0; int dummy; int flag; #pragma omp barrier #pragma omp master { /* * Naive non-blocking barrier implementation over send/recv, to call user * progress while waiting for completion. * Not using MPI_Ibarrier to be compatible with MPI-1. */ MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); MPI_Comm_size(MPI_COMM_WORLD, &group_size); /* allocate maximal possible number of requests */ reqs = (MPI_Request*)alloca(sizeof(*reqs) * group_size); if (my_rank == 0) { /* root gathers "ping" from all other ranks */ for (i = 1; i < group_size; ++i) { MPI_Irecv(&dummy, 0, MPI_INT, i /* source */, 1 /* tag */, MPI_COMM_WORLD, &reqs[nreqs++]); } } else { /* every non-root rank sends "ping" and waits for "pong" */ MPI_Send(&dummy, 0, MPI_INT, 0 /* dest */, 1 /* tag */, MPI_COMM_WORLD); MPI_Irecv(&dummy, 0, MPI_INT, 0 /* source */, 2 /* tag */, MPI_COMM_WORLD, &reqs[nreqs++]); } /* Waiting for receive requests */ do { MPI_Testall(nreqs, reqs, &flag, MPI_STATUSES_IGNORE); progress(arg); } while (!flag); if (my_rank == 0) { /* root sends "pong" to all ranks */ for (i = 1; i < group_size; ++i) { MPI_Send(&dummy, 0, MPI_INT, i /* dest */, 2 /* tag */, MPI_COMM_WORLD); } } } #pragma omp barrier } static void mpi_rte_post_vec(void *rte_group, const struct iovec *iovec, int iovcnt, void **req) { int group_size; int my_rank; int dest, i; MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); MPI_Comm_size(MPI_COMM_WORLD, &group_size); for (dest = 0; dest < group_size; ++dest) { if (dest == my_rank) { continue; } for (i = 0; i < iovcnt; ++i) { MPI_Send(iovec[i].iov_base, iovec[i].iov_len, MPI_BYTE, dest, i == (iovcnt - 1), /* Send last iov with tag == 1 */ MPI_COMM_WORLD); } } *req = (void*)(uintptr_t)1; } static void mpi_rte_recv(void *rte_group, unsigned src, void *buffer, size_t max, void *req) { MPI_Status status; size_t offset; int my_rank; int count; MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); if (src == my_rank) { return; } offset = 0; do { ucs_assert_always(offset < max); MPI_Recv(buffer + offset, max - offset, MPI_BYTE, src, MPI_ANY_TAG, MPI_COMM_WORLD, &status); MPI_Get_count(&status, MPI_BYTE, &count); offset += count; } while (status.MPI_TAG != 1); } static void mpi_rte_report(void *rte_group, const ucx_perf_result_t *result, void *arg, int is_final, int is_multi_thread) { struct perftest_context *ctx = arg; print_progress(ctx->test_names, ctx->num_batch_files, result, ctx->flags, is_final, ctx->server_addr == NULL, is_multi_thread); } #elif defined (HAVE_RTE) static unsigned ext_rte_group_size(void *rte_group) { rte_group_t group = (rte_group_t)rte_group; return rte_group_size(group); } static unsigned ext_rte_group_index(void *rte_group) { rte_group_t group = (rte_group_t)rte_group; return rte_group_rank(group); } static void ext_rte_barrier(void *rte_group, void (*progress)(void *arg), void *arg) { #pragma omp barrier #pragma omp master { rte_group_t group = (rte_group_t)rte_group; int rc; rc = rte_barrier(group); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_barrier"); } } #pragma omp barrier } static void ext_rte_post_vec(void *rte_group, const struct iovec* iovec, int iovcnt, void **req) { rte_group_t group = (rte_group_t)rte_group; rte_srs_session_t session; rte_iovec_t *r_vec; int i, rc; rc = rte_srs_session_create(group, 0, &session); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_session_create"); } r_vec = calloc(iovcnt, sizeof(rte_iovec_t)); if (r_vec == NULL) { return; } for (i = 0; i < iovcnt; ++i) { r_vec[i].iov_base = iovec[i].iov_base; r_vec[i].type = rte_datatype_uint8_t; r_vec[i].count = iovec[i].iov_len; } rc = rte_srs_set_data(session, "KEY_PERF", r_vec, iovcnt); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_set_data"); } *req = session; free(r_vec); } static void ext_rte_recv(void *rte_group, unsigned src, void *buffer, size_t max, void *req) { rte_group_t group = (rte_group_t)rte_group; rte_srs_session_t session = (rte_srs_session_t)req; void *rte_buffer = NULL; rte_iovec_t r_vec; uint32_t offset; int size; int rc; rc = rte_srs_get_data(session, rte_group_index_to_ec(group, src), "KEY_PERF", &rte_buffer, &size); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_get_data"); return; } r_vec.iov_base = buffer; r_vec.type = rte_datatype_uint8_t; r_vec.count = max; offset = 0; rte_unpack(&r_vec, rte_buffer, &offset); rc = rte_srs_session_destroy(session); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_session_destroy"); } free(rte_buffer); } static void ext_rte_exchange_vec(void *rte_group, void * req) { rte_srs_session_t session = (rte_srs_session_t)req; int rc; rc = rte_srs_exchange_data(session); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_exchange_data"); } } static void ext_rte_report(void *rte_group, const ucx_perf_result_t *result, void *arg, int is_final, int is_multi_thread) { struct perftest_context *ctx = arg; print_progress(ctx->test_names, ctx->num_batch_files, result, ctx->flags, is_final, ctx->server_addr == NULL, is_multi_thread); } static ucx_perf_rte_t ext_rte = { .group_size = ext_rte_group_size, .group_index = ext_rte_group_index, .barrier = ext_rte_barrier, .report = ext_rte_report, .post_vec = ext_rte_post_vec, .recv = ext_rte_recv, .exchange_vec = ext_rte_exchange_vec, }; #endif static ucs_status_t setup_mpi_rte(struct perftest_context *ctx) { #if defined (HAVE_MPI) static ucx_perf_rte_t mpi_rte = { .group_size = mpi_rte_group_size, .group_index = mpi_rte_group_index, .barrier = mpi_rte_barrier, .post_vec = mpi_rte_post_vec, .recv = mpi_rte_recv, .exchange_vec = (void*)ucs_empty_function, .report = mpi_rte_report, }; int size, rank; ucs_trace_func(""); MPI_Comm_size(MPI_COMM_WORLD, &size); if (size != 2) { ucs_error("This test should run with exactly 2 processes (actual: %d)", size); return UCS_ERR_INVALID_PARAM; } MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank == 1) { ctx->flags |= TEST_FLAG_PRINT_RESULTS; } ctx->params.super.rte_group = NULL; ctx->params.super.rte = &mpi_rte; ctx->params.super.report_arg = ctx; #elif defined (HAVE_RTE) ucs_trace_func(""); ctx->params.rte_group = NULL; ctx->params.rte = &mpi_rte; ctx->params.report_arg = ctx; rte_group_t group; rte_init(NULL, NULL, &group); if (1 == rte_group_rank(group)) { ctx->flags |= TEST_FLAG_PRINT_RESULTS; } ctx->params.super.rte_group = group; ctx->params.super.rte = &ext_rte; ctx->params.super.report_arg = ctx; #endif return UCS_OK; } static ucs_status_t cleanup_mpi_rte(struct perftest_context *ctx) { #ifdef HAVE_RTE rte_finalize(); #endif return UCS_OK; } static ucs_status_t check_system(struct perftest_context *ctx) { ucs_sys_cpuset_t cpuset; unsigned i, count, nr_cpus; int ret; ucs_trace_func(""); ret = sysconf(_SC_NPROCESSORS_CONF); if (ret < 0) { ucs_error("failed to get local cpu count: %m"); return UCS_ERR_INVALID_PARAM; } nr_cpus = ret; memset(&cpuset, 0, sizeof(cpuset)); if (ctx->flags & TEST_FLAG_SET_AFFINITY) { for (i = 0; i < ctx->num_cpus; i++) { if (ctx->cpus[i] >= nr_cpus) { ucs_error("cpu (%u) out of range (0..%u)", ctx->cpus[i], nr_cpus - 1); return UCS_ERR_INVALID_PARAM; } } for (i = 0; i < ctx->num_cpus; i++) { CPU_SET(ctx->cpus[i], &cpuset); } ret = ucs_sys_setaffinity(&cpuset); if (ret) { ucs_warn("sched_setaffinity() failed: %m"); return UCS_ERR_INVALID_PARAM; } } else { ret = ucs_sys_getaffinity(&cpuset); if (ret) { ucs_warn("sched_getaffinity() failed: %m"); return UCS_ERR_INVALID_PARAM; } count = 0; for (i = 0; i < CPU_SETSIZE; ++i) { if (CPU_ISSET(i, &cpuset)) { ++count; } } if (count > 2) { ucs_warn("CPU affinity is not set (bound to %u cpus)." " Performance may be impacted.", count); } } return UCS_OK; } static ucs_status_t clone_params(perftest_params_t *dest, const perftest_params_t *src) { size_t msg_size_list_size; *dest = *src; msg_size_list_size = dest->super.msg_size_cnt * sizeof(*dest->super.msg_size_list); dest->super.msg_size_list = malloc(msg_size_list_size); if (dest->super.msg_size_list == NULL) { return ((msg_size_list_size != 0) ? UCS_ERR_NO_MEMORY : UCS_OK); } memcpy(dest->super.msg_size_list, src->super.msg_size_list, msg_size_list_size); return UCS_OK; } static ucs_status_t run_test_recurs(struct perftest_context *ctx, const perftest_params_t *parent_params, unsigned depth) { perftest_params_t params; ucx_perf_result_t result; ucs_status_t status; FILE *batch_file; int line_num; ucs_trace_func("depth=%u, num_files=%u", depth, ctx->num_batch_files); if (parent_params->super.api == UCX_PERF_API_UCP) { if (strcmp(parent_params->super.uct.dev_name, TL_RESOURCE_NAME_NONE)) { ucs_warn("-d '%s' ignored for UCP test; see NOTES section in help message", parent_params->super.uct.dev_name); } if (strcmp(parent_params->super.uct.tl_name, TL_RESOURCE_NAME_NONE)) { ucs_warn("-x '%s' ignored for UCP test; see NOTES section in help message", parent_params->super.uct.tl_name); } } if (depth >= ctx->num_batch_files) { print_test_name(ctx); return ucx_perf_run(&parent_params->super, &result); } batch_file = fopen(ctx->batch_files[depth], "r"); if (batch_file == NULL) { ucs_error("Failed to open batch file '%s': %m", ctx->batch_files[depth]); return UCS_ERR_IO_ERROR; } line_num = 0; do { status = clone_params(&params, parent_params); if (status != UCS_OK) { goto out; } status = read_batch_file(batch_file, ctx->batch_files[depth], &line_num, &params, &ctx->test_names[depth]); if (status == UCS_OK) { run_test_recurs(ctx, &params, depth + 1); free(ctx->test_names[depth]); ctx->test_names[depth] = NULL; } free(params.super.msg_size_list); params.super.msg_size_list = NULL; } while (status == UCS_OK); if (status == UCS_ERR_NO_ELEM) { status = UCS_OK; } out: fclose(batch_file); return status; } static ucs_status_t run_test(struct perftest_context *ctx) { const char *error_prefix; ucs_status_t status; ucs_trace_func(""); setlocale(LC_ALL, "en_US"); /* no batch files, only command line params */ if (ctx->num_batch_files == 0) { error_prefix = (ctx->flags & TEST_FLAG_PRINT_RESULTS) ? "command line: " : ""; status = adjust_test_params(&ctx->params, error_prefix); if (status != UCS_OK) { return status; } } print_header(ctx); status = run_test_recurs(ctx, &ctx->params, 0); if (status != UCS_OK) { ucs_error("Failed to run test: %s", ucs_status_string(status)); } return status; } int main(int argc, char **argv) { struct perftest_context ctx; ucs_status_t status; int mpi_initialized; int mpi_rte; int ret; #ifdef HAVE_MPI int provided; mpi_initialized = !isatty(0) && /* Using MPI_THREAD_FUNNELED since ucx_perftest supports * using multiple threads when only the main one makes * MPI calls (which is also suitable for a single threaded * run). * MPI_THREAD_FUNNELED: * The process may be multi-threaded, but only the main * thread will make MPI calls (all MPI calls are funneled * to the main thread). */ (MPI_Init_thread(&argc, &argv, MPI_THREAD_FUNNELED, &provided) == 0); if (mpi_initialized && (provided != MPI_THREAD_FUNNELED)) { printf("MPI_Init_thread failed to set MPI_THREAD_FUNNELED. (provided = %d)\n", provided); ret = -1; goto out; } #else mpi_initialized = 0; #endif /* Parse command line */ status = parse_opts(&ctx, mpi_initialized, argc, argv); if (status != UCS_OK) { ret = (status == UCS_ERR_CANCELED) ? 0 : -127; goto out_msg_size_list; } #ifdef __COVERITY__ /* coverity[dont_call] */ mpi_rte = rand(); /* Shut up deadcode error */ #endif if (ctx.mpi) { mpi_rte = 1; } else { #ifdef HAVE_RTE mpi_rte = 1; #else mpi_rte = 0; #endif } status = check_system(&ctx); if (status != UCS_OK) { ret = -1; goto out_msg_size_list; } /* Create RTE */ status = (mpi_rte) ? setup_mpi_rte(&ctx) : setup_sock_rte(&ctx); if (status != UCS_OK) { ret = -1; goto out_msg_size_list; } /* Run the test */ status = run_test(&ctx); if (status != UCS_OK) { ret = -1; goto out_cleanup_rte; } ret = 0; out_cleanup_rte: (mpi_rte) ? cleanup_mpi_rte(&ctx) : cleanup_sock_rte(&ctx); out_msg_size_list: free(ctx.params.super.msg_size_list); #if HAVE_MPI out: #endif if (mpi_initialized) { #ifdef HAVE_MPI MPI_Finalize(); #endif } return ret; }
hypre_hopscotch_hash.c
/****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ #include "hypre_hopscotch_hash.h" static HYPRE_Int NearestPowerOfTwo( HYPRE_Int value ) { HYPRE_Int rc = 1; while (rc < value) { rc <<= 1; } return rc; } static void InitBucket(hypre_HopscotchBucket *b) { b->hopInfo = 0; b->hash = HYPRE_HOPSCOTCH_HASH_EMPTY; } static void InitBigBucket(hypre_BigHopscotchBucket *b) { b->hopInfo = 0; b->hash = HYPRE_HOPSCOTCH_HASH_EMPTY; } #ifdef HYPRE_CONCURRENT_HOPSCOTCH static void InitSegment(hypre_HopscotchSegment *s) { s->timestamp = 0; omp_init_lock(&s->lock); } static void DestroySegment(hypre_HopscotchSegment *s) { omp_destroy_lock(&s->lock); } #endif void hypre_UnorderedIntSetCreate( hypre_UnorderedIntSet *s, HYPRE_Int inCapacity, HYPRE_Int concurrencyLevel) { s->segmentMask = NearestPowerOfTwo(concurrencyLevel) - 1; if (inCapacity < s->segmentMask + 1) { inCapacity = s->segmentMask + 1; } //ADJUST INPUT ............................ HYPRE_Int adjInitCap = NearestPowerOfTwo(inCapacity+4096); HYPRE_Int num_buckets = adjInitCap + HYPRE_HOPSCOTCH_HASH_INSERT_RANGE + 1; s->bucketMask = adjInitCap - 1; HYPRE_Int i; //ALLOCATE THE SEGMENTS ................... #ifdef HYPRE_CONCURRENT_HOPSCOTCH s->segments = hypre_TAlloc(hypre_HopscotchSegment, s->segmentMask + 1, HYPRE_MEMORY_HOST); for (i = 0; i <= s->segmentMask; ++i) { InitSegment(&s->segments[i]); } #endif s->hopInfo = hypre_TAlloc(hypre_uint, num_buckets, HYPRE_MEMORY_HOST); s->key = hypre_TAlloc(HYPRE_Int, num_buckets, HYPRE_MEMORY_HOST); s->hash = hypre_TAlloc(HYPRE_Int, num_buckets, HYPRE_MEMORY_HOST); #ifdef HYPRE_CONCURRENT_HOPSCOTCH #pragma omp parallel for #endif for (i = 0; i < num_buckets; ++i) { s->hopInfo[i] = 0; s->hash[i] = HYPRE_HOPSCOTCH_HASH_EMPTY; } } void hypre_UnorderedBigIntSetCreate( hypre_UnorderedBigIntSet *s, HYPRE_Int inCapacity, HYPRE_Int concurrencyLevel) { s->segmentMask = NearestPowerOfTwo(concurrencyLevel) - 1; if (inCapacity < s->segmentMask + 1) { inCapacity = s->segmentMask + 1; } //ADJUST INPUT ............................ HYPRE_Int adjInitCap = NearestPowerOfTwo(inCapacity+4096); HYPRE_Int num_buckets = adjInitCap + HYPRE_HOPSCOTCH_HASH_INSERT_RANGE + 1; s->bucketMask = adjInitCap - 1; HYPRE_Int i; //ALLOCATE THE SEGMENTS ................... #ifdef HYPRE_CONCURRENT_HOPSCOTCH s->segments = hypre_TAlloc(hypre_HopscotchSegment, s->segmentMask + 1, HYPRE_MEMORY_HOST); for (i = 0; i <= s->segmentMask; ++i) { InitSegment(&s->segments[i]); } #endif s->hopInfo = hypre_TAlloc(hypre_uint, num_buckets, HYPRE_MEMORY_HOST); s->key = hypre_TAlloc(HYPRE_BigInt, num_buckets, HYPRE_MEMORY_HOST); s->hash = hypre_TAlloc(HYPRE_BigInt, num_buckets, HYPRE_MEMORY_HOST); #ifdef HYPRE_CONCURRENT_HOPSCOTCH #pragma omp parallel for #endif for (i = 0; i < num_buckets; ++i) { s->hopInfo[i] = 0; s->hash[i] = HYPRE_HOPSCOTCH_HASH_EMPTY; } } void hypre_UnorderedIntMapCreate( hypre_UnorderedIntMap *m, HYPRE_Int inCapacity, HYPRE_Int concurrencyLevel) { m->segmentMask = NearestPowerOfTwo(concurrencyLevel) - 1; if (inCapacity < m->segmentMask + 1) { inCapacity = m->segmentMask + 1; } //ADJUST INPUT ............................ HYPRE_Int adjInitCap = NearestPowerOfTwo(inCapacity+4096); HYPRE_Int num_buckets = adjInitCap + HYPRE_HOPSCOTCH_HASH_INSERT_RANGE + 1; m->bucketMask = adjInitCap - 1; HYPRE_Int i; //ALLOCATE THE SEGMENTS ................... #ifdef HYPRE_CONCURRENT_HOPSCOTCH m->segments = hypre_TAlloc(hypre_HopscotchSegment, m->segmentMask + 1, HYPRE_MEMORY_HOST); for (i = 0; i <= m->segmentMask; i++) { InitSegment(&m->segments[i]); } #endif m->table = hypre_TAlloc(hypre_HopscotchBucket, num_buckets, HYPRE_MEMORY_HOST); #ifdef HYPRE_CONCURRENT_HOPSCOTCH #pragma omp parallel for #endif for (i = 0; i < num_buckets; i++) { InitBucket(&m->table[i]); } } void hypre_UnorderedBigIntMapCreate( hypre_UnorderedBigIntMap *m, HYPRE_Int inCapacity, HYPRE_Int concurrencyLevel) { m->segmentMask = NearestPowerOfTwo(concurrencyLevel) - 1; if (inCapacity < m->segmentMask + 1) { inCapacity = m->segmentMask + 1; } //ADJUST INPUT ............................ HYPRE_Int adjInitCap = NearestPowerOfTwo(inCapacity+4096); HYPRE_Int num_buckets = adjInitCap + HYPRE_HOPSCOTCH_HASH_INSERT_RANGE + 1; m->bucketMask = adjInitCap - 1; HYPRE_Int i; //ALLOCATE THE SEGMENTS ................... #ifdef HYPRE_CONCURRENT_HOPSCOTCH m->segments = hypre_TAlloc(hypre_HopscotchSegment, m->segmentMask + 1, HYPRE_MEMORY_HOST); for (i = 0; i <= m->segmentMask; i++) { InitSegment(&m->segments[i]); } #endif m->table = hypre_TAlloc(hypre_BigHopscotchBucket, num_buckets, HYPRE_MEMORY_HOST); #ifdef HYPRE_CONCURRENT_HOPSCOTCH #pragma omp parallel for #endif for (i = 0; i < num_buckets; i++) { InitBigBucket(&m->table[i]); } } void hypre_UnorderedIntSetDestroy( hypre_UnorderedIntSet *s ) { hypre_TFree(s->hopInfo, HYPRE_MEMORY_HOST); hypre_TFree(s->key, HYPRE_MEMORY_HOST); hypre_TFree(s->hash, HYPRE_MEMORY_HOST); #ifdef HYPRE_CONCURRENT_HOPSCOTCH HYPRE_Int i; for (i = 0; i <= s->segmentMask; i++) { DestroySegment(&s->segments[i]); } hypre_TFree(s->segments, HYPRE_MEMORY_HOST); #endif } void hypre_UnorderedBigIntSetDestroy( hypre_UnorderedBigIntSet *s ) { hypre_TFree(s->hopInfo, HYPRE_MEMORY_HOST); hypre_TFree(s->key, HYPRE_MEMORY_HOST); hypre_TFree(s->hash, HYPRE_MEMORY_HOST); #ifdef HYPRE_CONCURRENT_HOPSCOTCH HYPRE_Int i; for (i = 0; i <= s->segmentMask; i++) { DestroySegment(&s->segments[i]); } hypre_TFree(s->segments, HYPRE_MEMORY_HOST); #endif } void hypre_UnorderedIntMapDestroy( hypre_UnorderedIntMap *m) { hypre_TFree(m->table, HYPRE_MEMORY_HOST); #ifdef HYPRE_CONCURRENT_HOPSCOTCH HYPRE_Int i; for (i = 0; i <= m->segmentMask; i++) { DestroySegment(&m->segments[i]); } hypre_TFree(m->segments, HYPRE_MEMORY_HOST); #endif } void hypre_UnorderedBigIntMapDestroy( hypre_UnorderedBigIntMap *m) { hypre_TFree(m->table, HYPRE_MEMORY_HOST); #ifdef HYPRE_CONCURRENT_HOPSCOTCH HYPRE_Int i; for (i = 0; i <= m->segmentMask; i++) { DestroySegment(&m->segments[i]); } hypre_TFree(m->segments, HYPRE_MEMORY_HOST); #endif } HYPRE_Int *hypre_UnorderedIntSetCopyToArray( hypre_UnorderedIntSet *s, HYPRE_Int *len ) { /*HYPRE_Int prefix_sum_workspace[hypre_NumThreads() + 1];*/ HYPRE_Int *prefix_sum_workspace; HYPRE_Int *ret_array = NULL; prefix_sum_workspace = hypre_TAlloc(HYPRE_Int, hypre_NumThreads() + 1, HYPRE_MEMORY_HOST); #ifdef HYPRE_CONCURRENT_HOPSCOTCH #pragma omp parallel #endif { HYPRE_Int n = s->bucketMask + HYPRE_HOPSCOTCH_HASH_INSERT_RANGE; HYPRE_Int i_begin, i_end; hypre_GetSimpleThreadPartition(&i_begin, &i_end, n); HYPRE_Int cnt = 0; HYPRE_Int i; for (i = i_begin; i < i_end; i++) { if (HYPRE_HOPSCOTCH_HASH_EMPTY != s->hash[i]) cnt++; } hypre_prefix_sum(&cnt, len, prefix_sum_workspace); #ifdef HYPRE_CONCURRENT_HOPSCOTCH #pragma omp barrier #pragma omp master #endif { ret_array = hypre_TAlloc(HYPRE_Int, *len, HYPRE_MEMORY_HOST); } #ifdef HYPRE_CONCURRENT_HOPSCOTCH #pragma omp barrier #endif for (i = i_begin; i < i_end; i++) { if (HYPRE_HOPSCOTCH_HASH_EMPTY != s->hash[i]) ret_array[cnt++] = s->key[i]; } } hypre_TFree(prefix_sum_workspace, HYPRE_MEMORY_HOST); return ret_array; } HYPRE_BigInt *hypre_UnorderedBigIntSetCopyToArray( hypre_UnorderedBigIntSet *s, HYPRE_Int *len ) { /*HYPRE_Int prefix_sum_workspace[hypre_NumThreads() + 1];*/ HYPRE_Int *prefix_sum_workspace; HYPRE_BigInt *ret_array = NULL; prefix_sum_workspace = hypre_TAlloc(HYPRE_Int, hypre_NumThreads() + 1, HYPRE_MEMORY_HOST); #ifdef HYPRE_CONCURRENT_HOPSCOTCH #pragma omp parallel #endif { HYPRE_Int n = s->bucketMask + HYPRE_HOPSCOTCH_HASH_INSERT_RANGE; HYPRE_Int i_begin, i_end; hypre_GetSimpleThreadPartition(&i_begin, &i_end, n); HYPRE_Int cnt = 0; HYPRE_Int i; for (i = i_begin; i < i_end; i++) { if (HYPRE_HOPSCOTCH_HASH_EMPTY != s->hash[i]) cnt++; } hypre_prefix_sum(&cnt, len, prefix_sum_workspace); #ifdef HYPRE_CONCURRENT_HOPSCOTCH #pragma omp barrier #pragma omp master #endif { ret_array = hypre_TAlloc(HYPRE_BigInt, *len, HYPRE_MEMORY_HOST); } #ifdef HYPRE_CONCURRENT_HOPSCOTCH #pragma omp barrier #endif for (i = i_begin; i < i_end; i++) { if (HYPRE_HOPSCOTCH_HASH_EMPTY != s->hash[i]) ret_array[cnt++] = s->key[i]; } } hypre_TFree(prefix_sum_workspace, HYPRE_MEMORY_HOST); return ret_array; }
sphkmeans.c
/*! \file \brief A parallel spherical k-means program \date Started 4/20/2013 \author George */ #include <GKlib.h> #include <bdmpi.h> #include <sys/types.h> #include <sys/time.h> #include <sys/resource.h> #include <unistd.h> /**************************************************************************/ /* data structures */ /**************************************************************************/ typedef struct { int npes, mype, nthreads; BDMPI_Comm comm; int nclusters; int ntrials, niters; char *filename; /* the total number of rows and their overall distribution */ int nrows, ncols; /* temporary files */ char mfile[8192]; char cfile[8192]; char cpfile[8192]; char bpfile[8192]; /* timers */ double totalTmr; double compTmr; double commTmr; } params_t; /**************************************************************************/ /* prototypes */ /**************************************************************************/ int LoadData(params_t *params); void WriteClustering(params_t *params); void PreprocessData(params_t *params); void ClusterData(params_t *params, int nrows); void ComputeClusteringStatistics(params_t *params); /**************************************************************************/ /**************************************************************************/ int main(int argc, char **argv) { params_t *params; int nrows; BDMPI_Status status; double max, current; setbuf(stdout, NULL); setbuf(stderr, NULL); BDMPI_Init(&argc, &argv); params = (params_t *)gk_malloc(sizeof(params_t), "params"); memset(params, 0, sizeof(params_t)); params->comm = BDMPI_COMM_WORLD; BDMPI_Comm_size(params->comm, &(params->npes)); BDMPI_Comm_rank(params->comm, &(params->mype)); if (argc != 6) { if (params->mype == 0) fprintf(stderr, "Usage: %s filename #clusters #trials #iters #threads\n", argv[0]); BDMPI_Finalize(); return EXIT_FAILURE; } params->filename = strdup(argv[1]); params->nclusters = atoi(argv[2]); params->ntrials = atoi(argv[3]); params->niters = atoi(argv[4]); params->nthreads = atoi(argv[5]); sprintf(params->mfile, "m%d.%d", (int)getpid(), params->mype); sprintf(params->cfile, "c%d.%d", (int)getpid(), params->mype); sprintf(params->cpfile, "cp%d.%d", (int)getpid(), params->mype); sprintf(params->bpfile, "bp%d.%d", (int)getpid(), params->mype); omp_set_num_threads(params->nthreads); gk_clearwctimer(params->totalTmr); gk_clearwctimer(params->compTmr); gk_clearwctimer(params->commTmr); BDMPI_Barrier(params->comm); BDMPI_Barrier(params->comm); gk_startwctimer(params->totalTmr); nrows = LoadData(params); PreprocessData(params); srand(params->mype+101); printf("[%03d] timestamp01: %zu\n", params->mype, (size_t)time(NULL)); ClusterData(params, nrows); printf("[%03d] timestamp02: %zu\n", params->mype, (size_t)time(NULL)); WriteClustering(params); BDMPI_Barrier(params->comm); BDMPI_Barrier(params->comm); gk_stopwctimer(params->totalTmr); /* print timing stats */ current = gk_getwctimer(params->compTmr); BDMPI_Reduce(&current, &max, 1, BDMPI_DOUBLE, BDMPI_MAX, 0, params->comm); if (params->mype == 0) printf(" compTmr: %10.4lf\n", max); current = gk_getwctimer(params->commTmr); BDMPI_Reduce(&current, &max, 1, BDMPI_DOUBLE, BDMPI_MAX, 0, params->comm); if (params->mype == 0) printf(" commTmr: %10.4lf\n", max); current = gk_getwctimer(params->totalTmr); BDMPI_Reduce(&current, &max, 1, BDMPI_DOUBLE, BDMPI_MAX, 0, params->comm); if (params->mype == 0) printf(" totalTmr: %10.4lf\n", max); BDMPI_Finalize(); return EXIT_SUCCESS; } /**************************************************************************/ /*! Reads a sparse matrix in headerless CSR format. The same matrix is read by everybody in order to simulate a large file clustering. \returns the local portion of the matrix. */ /**************************************************************************/ int LoadData0(params_t *params) { int mype = params->mype, npes = params->npes; size_t i, k, l, p, lnlen; int ncols, lnrows; size_t nrows, nnz, lnnz, cnnz; ssize_t *rowptr; int *rowind, ival; float *rowval=NULL, fval; char *line=NULL, *head, *tail; FILE *fpin; gk_csr_t *mat=NULL; BDMPI_Status status; long int fpos; mat = gk_csr_Create(); if (mype == 0) { if (!gk_fexists(params->filename)) gk_errexit(SIGERR, "File %s does not exist!\n", params->filename); gk_getfilestats(params->filename, &nrows, &nnz, NULL, NULL); if (nnz%2 == 1) gk_errexit(SIGERR, "LoadData: The number of non-zeros [%zu] is not an even number.\n", nnz); params->nrows = nrows; nnz = nnz/2; /* account for the values */ } /* send size info to everybody */ BDMPI_Bcast(&params->nrows, 1, BDMPI_INT, 0, params->comm); BDMPI_Bcast(&nnz, sizeof(size_t), BDMPI_BYTE, 0, params->comm); /* wait your turn */ if (mype != 0) BDMPI_Recv(&fpos, sizeof(long int), BDMPI_BYTE, mype-1, 1, params->comm, &status); else fpos = 0; lnnz = nnz; lnrows = params->nrows; if (mype == 0) printf("[%3d] lnrows: %d, lnnz: %zu\n", mype, lnrows, lnnz); rowptr = gk_zmalloc(lnrows+1, "LoadData: rowptr"); rowind = gk_imalloc(lnnz, "LoadData: rowind"); rowval = gk_fsmalloc(lnnz, 1.0, "LoadData: rowval"); params->nrows *= npes; /* duplicate the data to each pe */ fpos = 0; /* in order to read everything */ fpin = gk_fopen(params->filename, "r", "LoadData: fpin"); fseek(fpin, fpos, SEEK_SET); /* read the file, one row at a time */ cnnz = rowptr[0] = ncols = 0; for (i=0; i<lnrows; i++) { do { if (gk_getline(&line, &lnlen, fpin) == -1) gk_errexit(SIGERR, "Premature end of input file: file while reading row %zd\n", i); } while (line[0] == '%'); head = line; tail = NULL; /* parse the row */ while (1) { ival = (int)strtol(head, &tail, 0); if (tail == head) break; head = tail; fval = strtof(head, &tail); if (tail == head) gk_errexit(SIGERR, "Value could not be found for column! Row:%zd, NNZ:%zd\n", i, cnnz); head = tail; if (cnnz == lnnz) { /* adjust the memory */ lnnz = 1.2*lnnz; rowind = gk_irealloc(rowind, lnnz, "LoadData: rowind"); rowval = gk_frealloc(rowval, lnnz, "LoadData: rowval"); } rowind[cnnz] = ival; rowval[cnnz] = fval; cnnz++; ncols = (ncols < ival ? ival : ncols); } rowptr[i+1] = cnnz; } mat->nrows = lnrows; mat->ncols = ncols+1; mat->rowptr = rowptr; mat->rowind = rowind; mat->rowval = rowval; fpos = ftell(fpin); gk_fclose(fpin); gk_free((void **)&line, LTERM); gk_csr_Write(mat, params->mfile, GK_CSR_FMT_BINROW, 1, 0); gk_csr_Free(&mat); if (mype != npes-1) BDMPI_Send(&fpos, sizeof(long int), BDMPI_BYTE, mype+1, 1, params->comm); BDMPI_Allreduce(&ncols, &ncols, 1, BDMPI_INT, BDMPI_MAX, params->comm); params->ncols = ncols+1; if (mype == 0) printf("[%3d] params->nrows: %d, params->ncols: %d, cnnz: %zu\n", mype, params->nrows, params->ncols, cnnz); return lnrows; } /**************************************************************************/ /*! Reads a sparse matrix in binary CSR format. The same matrix is read by everybody in order to simulate a large file clustering. \returns the local portion of the matrix. */ /**************************************************************************/ int LoadData(params_t *params) { int mype=params->mype, npes=params->npes; int lrank, lsize; int lnrows, flag; size_t lnnz; gk_csr_t *mat=NULL; BDMPI_Status status; BDMPI_Comm_lrank(params->comm, &lrank); BDMPI_Comm_lsize(params->comm, &lsize); if (mype == 0) { if (!gk_fexists(params->filename)) gk_errexit(SIGERR, "File %s does not exist!\n", params->filename); } /* wait your turn */ if (lrank != 0) BDMPI_Recv(&flag, 1, BDMPI_INT, mype-1, 1, params->comm, &status); mat = gk_csr_Read(params->filename, GK_CSR_FMT_BINROW, 1, 0); lnrows = mat->nrows; lnnz = mat->rowptr[mat->nrows]; params->nrows = lnrows*npes; params->ncols = mat->ncols; if (mype == 0) printf("[%3d] lnrows: %d, lnnz: %zu\n", mype, mat->nrows, lnnz); BDMPI_Entercritical(); gk_csr_Write(mat, params->mfile, GK_CSR_FMT_BINROW, 1, 0); BDMPI_Exitcritical(); gk_csr_Free(&mat); if (lrank != lsize-1) BDMPI_Send(&flag, 1, BDMPI_INT, mype+1, 1, params->comm); if (mype == 0) printf("[%3d] params->nrows: %d, params->ncols: %d, tnnz: %zu\n", mype, params->nrows, params->ncols, npes*lnnz); return lnrows; } /**************************************************************************/ /*! Writes a clustering vector. It just let each process write its portion to the file in a round-robin fashion. */ /**************************************************************************/ void WriteClustering(params_t *params) { int npes=params->npes, mype=params->mype, dummy=0, *cvec; size_t i, nrows; BDMPI_Status status; FILE *fpout; char outfile[1024]; sprintf(outfile, "%s.part.%d", params->filename, params->nclusters); if (mype == 0) { BDMPI_Entercritical(); cvec = gk_i32readfilebin(params->bpfile, &nrows); BDMPI_Exitcritical(); unlink(params->bpfile); fpout = gk_fopen(outfile, "w", "outfile"); for (i=0; i<nrows; i++) fprintf(fpout, "%d\n", cvec[i]); gk_fclose(fpout); gk_free((void **)&cvec, LTERM); if (mype+1 < npes) BDMPI_Send(&dummy, 1, BDMPI_INT, mype+1, 1, params->comm); } else { BDMPI_Recv(&dummy, 1, BDMPI_INT, mype-1, 1, params->comm, &status); BDMPI_Entercritical(); cvec = gk_i32readfilebin(params->bpfile, &nrows); BDMPI_Exitcritical(); unlink(params->bpfile); fpout = gk_fopen(outfile, "a", "outfile"); for (i=0; i<nrows; i++) fprintf(fpout, "%d\n", cvec[i]); gk_fclose(fpout); gk_free((void **)&cvec, LTERM); if (mype+1 < npes) BDMPI_Send(&mype, 1, BDMPI_INT, mype+1, 1, params->comm); } } /**************************************************************************/ /*! This function performs various pre-processing steps on the matrix. */ /**************************************************************************/ void PreprocessData(params_t *params) { int mype=params->mype; gk_csr_t *mat; BDMPI_Entercritical(); mat = gk_csr_Read(params->mfile, GK_CSR_FMT_BINROW, 1, 0); BDMPI_Exitcritical(); gk_csr_Normalize(mat, GK_CSR_ROW, 2); BDMPI_Entercritical(); gk_csr_Write(mat, params->mfile, GK_CSR_FMT_BINROW, 1, 0); BDMPI_Exitcritical(); gk_csr_Free(&mat); } /**************************************************************************/ /*! This function computes the k-way clustering solution. */ /**************************************************************************/ void ClusterData(params_t *params, int nrows) { int npes=params->npes, mype=params->mype; size_t trial, iter, i, j, k, offset, nelmnts; int ncols, nclusters, *rowind, *cpart, *bcpart; int myrnum, grnum, p; int lnmoves, gnmoves; ssize_t *rowptr; float *rowval, *centers; float dnorms[params->nclusters], crval, bcrval; gk_csr_t *mat; BDMPI_Status status; nclusters = params->nclusters; ncols = params->ncols; /* perform a number of random trials */ for (bcrval=0.0, trial=0; trial<params->ntrials; trial++) { /* select the initial cluster seeds */ myrnum = rand(); BDMPI_Allreduce(&myrnum, &grnum, 1, BDMPI_INT, BDMPI_MAX, params->comm); if (myrnum == grnum) myrnum = mype; else myrnum = npes; BDMPI_Allreduce(&myrnum, &grnum, 1, BDMPI_INT, BDMPI_MIN, params->comm); if (grnum == mype) { /* this pe will be selecting the initial centers */ /* load the data */ BDMPI_Entercritical(); mat = gk_csr_Read(params->mfile, GK_CSR_FMT_BINROW, 1, 0); BDMPI_Exitcritical(); rowptr = mat->rowptr; rowind = mat->rowind; rowval = mat->rowval; centers = gk_fsmalloc(nclusters*ncols, 0.0, "centers"); /* pick the centers */ myrnum = RandomInRange(nrows/nclusters); for (k=0; k<nclusters; k++) { i = ((k+1)*myrnum)%nrows; for (j=rowptr[i]; j<rowptr[i+1]; j++) centers[rowind[j]*nclusters+k] = rowval[j]; } gk_csr_Free(&mat); BDMPI_Entercritical(); gk_fwritefilebin(params->cfile, nclusters*ncols, centers); BDMPI_Exitcritical(); gk_free((void **)&centers, LTERM); } /* get into the iterative refinement */ cpart = gk_ismalloc(nrows, -1, "cpart"); BDMPI_Entercritical(); gk_i32writefilebin(params->cpfile, nrows, cpart); BDMPI_Exitcritical(); gk_free((void **)&cpart, LTERM); for (iter=0; iter<params->niters; iter++) { if (grnum == mype) { /* root sends the centers to everybody else */ BDMPI_Entercritical(); centers = gk_freadfilebin(params->cfile, &nelmnts); BDMPI_Exitcritical(); for (p=0; p<npes; p++) { if (p != grnum) BDMPI_Send(centers, ncols*nclusters, BDMPI_FLOAT, p, 1, params->comm); } } else { /* everybody else receives the data */ centers = gk_fmalloc(nclusters*ncols, "centers"); BDMPI_Recv(centers, ncols*nclusters, BDMPI_FLOAT, grnum, 1, params->comm, &status); } printf("[%03d]%04zu.%04zu.0 ts: %d\n", mype, trial, iter, (int)time(NULL)); /* assign each local row to the closest cluster */ gk_startwctimer(params->compTmr); BDMPI_Entercritical(); mat = gk_csr_Read(params->mfile, GK_CSR_FMT_BINROW, 1, 0); rowptr = mat->rowptr; rowind = mat->rowind; rowval = mat->rowval; cpart = gk_i32readfilebin(params->cpfile, &nelmnts); BDMPI_Exitcritical(); lnmoves = 0; #pragma omp parallel default(none),\ shared(i, nrows, nclusters, rowptr, rowind, rowval, centers, cpart),\ private(j, k, offset),\ reduction(+:lnmoves) { float sims[nclusters]; #pragma omp for schedule(dynamic,32) for (i=0; i<nrows; i++) { for (k=0; k<nclusters; k++) sims[k] = 0.0; for (j=rowptr[i]; j<rowptr[i+1]; j++) { offset = rowind[j]*nclusters; for (k=0; k<nclusters; k++) sims[k] += rowval[j]*centers[offset+k]; } k = gk_fargmax(nclusters, sims, 1); if (k != cpart[i]) lnmoves++; cpart[i] = k; } } /* compute the new local centers */ gk_fset(nclusters*ncols, 0.0, centers); for (i=0; i<nrows; i++) { k = cpart[i]; for (j=rowptr[i]; j<rowptr[i+1]; j++) centers[rowind[j]*nclusters+k] += rowval[j]; } BDMPI_Entercritical(); gk_i32writefilebin(params->cpfile, nrows, cpart); BDMPI_Exitcritical(); gk_free((void **)&cpart, LTERM); gk_csr_Free(&mat); /* done with the matrix */ printf("[%03d]%04zu.%04zu.1 ts: %d\n", mype, trial, iter, (int)time(NULL)); if (mype == grnum) { float *rcenters; /* write the centers */ BDMPI_Entercritical(); gk_fwritefilebin(params->cfile, nclusters*ncols, centers); BDMPI_Exitcritical(); gk_free((void **)&centers, LTERM); /* get the data from everybody else */ for (p=0; p<npes-1; p++) { rcenters = gk_fmalloc(nclusters*ncols, "rcenters"); BDMPI_Recv(rcenters, ncols*nclusters, BDMPI_FLOAT, BDMPI_ANY_SOURCE, 2, params->comm, &status); BDMPI_Entercritical(); centers = gk_freadfilebin(params->cfile, &nelmnts); BDMPI_Exitcritical(); for (i=0; i<nclusters*ncols; i++) centers[i] += rcenters[i]; BDMPI_Entercritical(); gk_fwritefilebin(params->cfile, nclusters*ncols, centers); BDMPI_Exitcritical(); gk_free((void **)&rcenters, &centers, LTERM); } /* compute the new global centers */ for (k=0; k<nclusters; k++) dnorms[k] = 0.0; BDMPI_Entercritical(); centers = gk_freadfilebin(params->cfile, &nelmnts); BDMPI_Exitcritical(); for (i=0; i<ncols; i++) { offset = i*nclusters; for (k=0; k<nclusters; k++) dnorms[k] += centers[offset+k]*centers[offset+k]; } for (crval=0.0, k=0; k<nclusters; k++) { if (dnorms[k] > 0) { crval += sqrt(dnorms[k]); dnorms[k] = 1.0/sqrt(dnorms[k]); } } for (i=0; i<ncols; i++) { offset = i*nclusters; for (k=0; k<nclusters; k++) centers[offset+k] *= dnorms[k]; } //printf("trial: %2zd; iter: %3zd; crval: %.8e; bcrval: %.8e\n", trial, iter, crval, bcrval); BDMPI_Entercritical(); gk_fwritefilebin(params->cfile, nclusters*ncols, centers); BDMPI_Exitcritical(); gk_free((void **)&centers, LTERM); } else { BDMPI_Send(centers, ncols*nclusters, BDMPI_FLOAT, grnum, 2, params->comm); gk_free((void **)&centers, LTERM); } gk_stopwctimer(params->compTmr); /* see if you are done refining */ if (iter > 0) { BDMPI_Allreduce(&lnmoves, &gnmoves, 1, BDMPI_INT, BDMPI_SUM, params->comm); //printf("[%3d] lnmoves: %d, gnmoves: %d\n", mype, lnmoves, gnmoves); if (gnmoves == 0) break; } /* send the new crval to everybody */ BDMPI_Bcast(&crval, 1, BDMPI_FLOAT, grnum, params->comm); if (crval > bcrval) { char cmd[8192]; sprintf(cmd, "cp %s %s", params->cpfile, params->bpfile); GKASSERT(system(cmd) != -1); bcrval = crval; } } if (mype == 0) printf("[%3zu:%3zu] gnmoves: %8d; crval: %8.4e; bcrval: %8.4e\n", trial, iter, gnmoves, crval, bcrval); if (mype == grnum) unlink(params->cfile); unlink(params->cpfile); } /* compute the clustering statistics */ //ComputeClusteringStatistics(params); unlink(params->mfile); } /**************************************************************************/ /*! This function prints final statistics for the clustering solution. */ /**************************************************************************/ void ComputeClusteringStatistics(params_t *params) { int npes=params->npes, mype=params->mype, nclusters=params->nclusters, ncols=params->ncols; int nrows; size_t i, j, k, offset, nelmnts; int *cpart, *rowind, *pwgts; ssize_t *rowptr; float *rowval, *centers, *dnorms; float crval, tcrval; gk_csr_t *mat; centers = gk_fsmalloc(nclusters*ncols, 0.0, "centers"); pwgts = gk_ismalloc(nclusters, 0.0, "pwgts"); /* load the data */ mat = gk_csr_Read(params->mfile, GK_CSR_FMT_BINROW, 1, 0); nrows = mat->nrows; rowptr = mat->rowptr; rowind = mat->rowind; rowval = mat->rowval; cpart = gk_i32readfilebin(params->bpfile, &nelmnts); /* compute the local centers and local partition weights */ for (i=0; i<nrows; i++) { k = cpart[i]; pwgts[k]++; for (j=rowptr[i]; j<rowptr[i+1]; j++) { centers[rowind[j]*nclusters+k] += rowval[j]; } } gk_csr_Free(&mat); gk_free((void **)&cpart, LTERM); /* compute global centroids and partition weights */ BDMPI_Reduce(pwgts, pwgts, nclusters, BDMPI_INT, BDMPI_SUM, 0, params->comm); BDMPI_Reduce(centers, centers, nclusters*ncols, BDMPI_FLOAT, BDMPI_SUM, 0, params->comm); if (mype == 0) { dnorms = gk_fsmalloc(nclusters, 0.0, "dnorms"); for (i=0; i<ncols; i++) { offset = i*nclusters; for (k=0; k<nclusters; k++) dnorms[k] += centers[offset+k]*centers[offset+k]; } for (tcrval=0.0, k=0; k<nclusters; k++) { crval = (dnorms[k] > 0 ? sqrt(dnorms[k]) : 0.0); tcrval += crval; printf("Cluster: %4zu %6d %.4e\n", k, pwgts[k], crval); } printf("Overall: %.4e\n", tcrval); gk_free((void **)&dnorms, LTERM); } gk_free((void **)&centers, &pwgts, LTERM); }
bi_dir_ctx.h
/* * Copyright (c) 2018 Intel Corporation. All rights reserved. * This software is available to you under the BSD license below: * * 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. * * 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. */ static inline void bi_bw_ctx (int len, perf_metrics_t *metric_info) { double start = 0.0, end = 0.0; int dest = partner_node(metric_info); unsigned long int i, j; static int check_once = 0; if (!check_once) { /* check to see whether sender and receiver are the same process */ if (dest == metric_info->my_node) { fprintf(stderr, "Warning: Sender and receiver are the same " "process (%d)\n", dest); } /* hostname validation for all sender and receiver processes */ int status = check_hostname_validation(metric_info); if (status != 0) return; check_once++; } shmem_barrier_all(); #pragma omp parallel default(none) firstprivate(len, dest) private(i, j) \ shared(metric_info, start, end) num_threads(metric_info->nthreads) { const int thread_id = omp_get_thread_num(); shmem_ctx_t ctx; int err = shmem_ctx_create(SHMEM_CTX_PRIVATE, &ctx); if (err) { printf("PE %d, Thr. %d: Error, context creation failed\n", metric_info->my_node, thread_id); /* Exit with success to avoid test failures in automated testing */ shmem_global_exit(0); } for (i = 0; i < metric_info->warmup; i++) { for(j = 0; j < metric_info->window_size; j++) { #ifdef USE_NONBLOCKING_API shmem_ctx_putmem_nbi(ctx, metric_info->dest + thread_id * len, metric_info->src + thread_id * len, len, dest); #else shmem_ctx_putmem(ctx, metric_info->dest + thread_id * len, metric_info->src + thread_id * len, len, dest); #endif } shmem_ctx_quiet(ctx); } shmem_ctx_destroy(ctx); } shmem_barrier_all(); if (streaming_node(metric_info)) { #pragma omp parallel default(none) firstprivate(len, dest) private(i, j) \ shared(metric_info, start, end) num_threads(metric_info->nthreads) { const int thread_id = omp_get_thread_num(); shmem_ctx_t ctx; int err = shmem_ctx_create(SHMEM_CTX_PRIVATE, &ctx); if (err) { printf("PE %d, Thr. %d: Error, context creation failed\n", metric_info->my_node, thread_id); /* Exit with success to avoid test failures in automated testing */ shmem_global_exit(0); } #pragma omp barrier #pragma omp master { start = perf_shmemx_wtime(); } for (i = 0; i < metric_info->trials; i++) { for(j = 0; j < metric_info->window_size; j++) { #ifdef USE_NONBLOCKING_API shmem_ctx_putmem_nbi(ctx, metric_info->dest + thread_id * len, metric_info->src + thread_id * len, len, dest); #else shmem_ctx_putmem(ctx, metric_info->dest + thread_id * len, metric_info->src + thread_id * len, len, dest); #endif } shmem_ctx_quiet(ctx); } shmem_ctx_destroy(ctx); } } else { #pragma omp parallel default(none) firstprivate(len, dest) private(i, j) \ shared(metric_info, start, end) num_threads(metric_info->nthreads) { const int thread_id = omp_get_thread_num(); shmem_ctx_t ctx; int err = shmem_ctx_create(SHMEM_CTX_PRIVATE, &ctx); if (err) { printf("PE %d, Thr. %d: Error, context creation failed\n", metric_info->my_node, thread_id); /* Exit with success to avoid test failures in automated testing */ shmem_global_exit(0); } for (i = 0; i < metric_info->trials; i++) { for(j = 0; j < metric_info->window_size; j++) { #ifdef USE_NONBLOCKING_API shmem_ctx_putmem_nbi(ctx, metric_info->dest + thread_id * len, metric_info->src + thread_id * len, len, dest); #else shmem_ctx_putmem(ctx, metric_info->dest + thread_id * len, metric_info->src + thread_id * len, len, dest); #endif } shmem_ctx_quiet(ctx); } shmem_ctx_destroy(ctx); } } shmem_barrier_all(); if (streaming_node(metric_info)) { end = perf_shmemx_wtime(); calc_and_print_results(end, start, len, metric_info); } shmem_barrier_all(); }
data.h
/*! * Copyright (c) 2015-2021 by Contributors * \file data.h * \brief The input data structure of xgboost. * \author Tianqi Chen */ #ifndef XGBOOST_DATA_H_ #define XGBOOST_DATA_H_ #include <dmlc/base.h> #include <dmlc/data.h> #include <dmlc/serializer.h> #include <xgboost/base.h> #include <xgboost/span.h> #include <xgboost/host_device_vector.h> #include <memory> #include <numeric> #include <algorithm> #include <string> #include <utility> #include <vector> namespace xgboost { // forward declare dmatrix. class DMatrix; /*! \brief data type accepted by xgboost interface */ enum class DataType : uint8_t { kFloat32 = 1, kDouble = 2, kUInt32 = 3, kUInt64 = 4, kStr = 5 }; enum class FeatureType : uint8_t { kNumerical, kCategorical }; /*! * \brief Meta information about dataset, always sit in memory. */ class MetaInfo { public: /*! \brief number of data fields in MetaInfo */ static constexpr uint64_t kNumField = 11; /*! \brief number of rows in the data */ uint64_t num_row_{0}; // NOLINT /*! \brief number of columns in the data */ uint64_t num_col_{0}; // NOLINT /*! \brief number of nonzero entries in the data */ uint64_t num_nonzero_{0}; // NOLINT /*! \brief label of each instance */ HostDeviceVector<bst_float> labels_; // NOLINT /*! * \brief the index of begin and end of a group * needed when the learning task is ranking. */ std::vector<bst_group_t> group_ptr_; // NOLINT /*! \brief weights of each instance, optional */ HostDeviceVector<bst_float> weights_; // NOLINT /*! * \brief initialized margins, * if specified, xgboost will start from this init margin * can be used to specify initial prediction to boost from. */ HostDeviceVector<bst_float> base_margin_; // NOLINT /*! * \brief lower bound of the label, to be used for survival analysis (censored regression) */ HostDeviceVector<bst_float> labels_lower_bound_; // NOLINT /*! * \brief upper bound of the label, to be used for survival analysis (censored regression) */ HostDeviceVector<bst_float> labels_upper_bound_; // NOLINT /*! * \brief Name of type for each feature provided by users. Eg. "int"/"float"/"i"/"q" */ std::vector<std::string> feature_type_names; /*! * \brief Name for each feature. */ std::vector<std::string> feature_names; /* * \brief Type of each feature. Automatically set when feature_type_names is specifed. */ HostDeviceVector<FeatureType> feature_types; /* * \brief Weight of each feature, used to define the probability of each feature being * selected when using column sampling. */ HostDeviceVector<float> feature_weigths; /*! \brief default constructor */ MetaInfo() = default; MetaInfo(MetaInfo&& that) = default; MetaInfo& operator=(MetaInfo&& that) = default; MetaInfo& operator=(MetaInfo const& that) = delete; /*! * \brief Validate all metainfo. */ void Validate(int32_t device) const; MetaInfo Slice(common::Span<int32_t const> ridxs) const; /*! * \brief Get weight of each instances. * \param i Instance index. * \return The weight. */ inline bst_float GetWeight(size_t i) const { return weights_.Size() != 0 ? weights_.HostVector()[i] : 1.0f; } /*! \brief get sorted indexes (argsort) of labels by absolute value (used by cox loss) */ inline const std::vector<size_t>& LabelAbsSort() const { if (label_order_cache_.size() == labels_.Size()) { return label_order_cache_; } label_order_cache_.resize(labels_.Size()); std::iota(label_order_cache_.begin(), label_order_cache_.end(), 0); const auto& l = labels_.HostVector(); XGBOOST_PARALLEL_SORT(label_order_cache_.begin(), label_order_cache_.end(), [&l](size_t i1, size_t i2) {return std::abs(l[i1]) < std::abs(l[i2]);}); return label_order_cache_; } /*! \brief clear all the information */ void Clear(); /*! * \brief Load the Meta info from binary stream. * \param fi The input stream */ void LoadBinary(dmlc::Stream* fi); /*! * \brief Save the Meta info to binary stream * \param fo The output stream. */ void SaveBinary(dmlc::Stream* fo) const; /*! * \brief Set information in the meta info. * \param key The key of the information. * \param dptr The data pointer of the source array. * \param dtype The type of the source data. * \param num Number of elements in the source array. */ void SetInfo(const char* key, const void* dptr, DataType dtype, size_t num); /*! * \brief Set information in the meta info with array interface. * \param key The key of the information. * \param interface_str String representation of json format array interface. * * [ column_0, column_1, ... column_n ] * * Right now only 1 column is permitted. */ void SetInfo(const char* key, std::string const& interface_str); void GetInfo(char const* key, bst_ulong* out_len, DataType dtype, const void** out_dptr) const; void SetFeatureInfo(const char *key, const char **info, const bst_ulong size); void GetFeatureInfo(const char *field, std::vector<std::string>* out_str_vecs) const; /* * \brief Extend with other MetaInfo. * * \param that The other MetaInfo object. * * \param accumulate_rows Whether rows need to be accumulated in this function. If * client code knows number of rows in advance, set this * parameter to false. * \param check_column Whether the extend method should check the consistency of * columns. */ void Extend(MetaInfo const& that, bool accumulate_rows, bool check_column); private: /*! \brief argsort of labels */ mutable std::vector<size_t> label_order_cache_; }; /*! \brief Element from a sparse vector */ struct Entry { /*! \brief feature index */ bst_feature_t index; /*! \brief feature value */ bst_float fvalue; /*! \brief default constructor */ Entry() = default; /*! * \brief constructor with index and value * \param index The feature or row index. * \param fvalue The feature value. */ XGBOOST_DEVICE Entry(bst_feature_t index, bst_float fvalue) : index(index), fvalue(fvalue) {} /*! \brief reversely compare feature values */ inline static bool CmpValue(const Entry& a, const Entry& b) { return a.fvalue < b.fvalue; } inline bool operator==(const Entry& other) const { return (this->index == other.index && this->fvalue == other.fvalue); } }; /*! * \brief Parameters for constructing batches. */ struct BatchParam { /*! \brief The GPU device to use. */ int gpu_id; /*! \brief Maximum number of bins per feature for histograms. */ int max_bin{0}; /*! \brief Hessian, used for sketching with future approx implementation. */ common::Span<float> hess; /*! \brief Whether should DMatrix regenerate the batch. Only used for GHistIndex. */ bool regen {false}; BatchParam() = default; BatchParam(int32_t device, int32_t max_bin) : gpu_id{device}, max_bin{max_bin} {} /** * \brief Get batch with sketch weighted by hessian. The batch will be regenerated if * the span is changed, so caller should keep the span for each iteration. */ BatchParam(int32_t device, int32_t max_bin, common::Span<float> hessian, bool regenerate = false) : gpu_id{device}, max_bin{max_bin}, hess{hessian}, regen{regenerate} {} bool operator!=(const BatchParam& other) const { if (hess.empty() && other.hess.empty()) { return gpu_id != other.gpu_id || max_bin != other.max_bin; } return gpu_id != other.gpu_id || max_bin != other.max_bin || hess.data() != other.hess.data(); } }; struct HostSparsePageView { using Inst = common::Span<Entry const>; common::Span<bst_row_t const> offset; common::Span<Entry const> data; Inst operator[](size_t i) const { auto size = *(offset.data() + i + 1) - *(offset.data() + i); return {data.data() + *(offset.data() + i), static_cast<Inst::index_type>(size)}; } size_t Size() const { return offset.size() == 0 ? 0 : offset.size() - 1; } }; /*! * \brief In-memory storage unit of sparse batch, stored in CSR format. */ class SparsePage { public: // Offset for each row. HostDeviceVector<bst_row_t> offset; /*! \brief the data of the segments */ HostDeviceVector<Entry> data; size_t base_rowid {0}; /*! \brief an instance of sparse vector in the batch */ using Inst = common::Span<Entry const>; HostSparsePageView GetView() const { return {offset.ConstHostSpan(), data.ConstHostSpan()}; } /*! \brief constructor */ SparsePage() { this->Clear(); } /*! \return Number of instances in the page. */ inline size_t Size() const { return offset.Size() == 0 ? 0 : offset.Size() - 1; } /*! \return estimation of memory cost of this page */ inline size_t MemCostBytes() const { return offset.Size() * sizeof(size_t) + data.Size() * sizeof(Entry); } /*! \brief clear the page */ inline void Clear() { base_rowid = 0; auto& offset_vec = offset.HostVector(); offset_vec.clear(); offset_vec.push_back(0); data.HostVector().clear(); } /*! \brief Set the base row id for this page. */ inline void SetBaseRowId(size_t row_id) { base_rowid = row_id; } SparsePage GetTranspose(int num_columns) const; void SortRows() { auto ncol = static_cast<bst_omp_uint>(this->Size()); dmlc::OMPException exc; #pragma omp parallel for schedule(dynamic, 1) for (bst_omp_uint i = 0; i < ncol; ++i) { exc.Run([&]() { if (this->offset.HostVector()[i] < this->offset.HostVector()[i + 1]) { std::sort( this->data.HostVector().begin() + this->offset.HostVector()[i], this->data.HostVector().begin() + this->offset.HostVector()[i + 1], Entry::CmpValue); } }); } exc.Rethrow(); } /** * \brief Pushes external data batch onto this page * * \tparam AdapterBatchT * \param batch * \param missing * \param nthread * * \return The maximum number of columns encountered in this input batch. Useful when pushing many adapter batches to work out the total number of columns. */ template <typename AdapterBatchT> uint64_t Push(const AdapterBatchT& batch, float missing, int nthread); /*! * \brief Push a sparse page * \param batch the row page */ void Push(const SparsePage &batch); /*! * \brief Push a SparsePage stored in CSC format * \param batch The row batch to be pushed */ void PushCSC(const SparsePage& batch); }; class CSCPage: public SparsePage { public: CSCPage() : SparsePage() {} explicit CSCPage(SparsePage page) : SparsePage(std::move(page)) {} }; class SortedCSCPage : public SparsePage { public: SortedCSCPage() : SparsePage() {} explicit SortedCSCPage(SparsePage page) : SparsePage(std::move(page)) {} }; class EllpackPageImpl; /*! * \brief A page stored in ELLPACK format. * * This class uses the PImpl idiom (https://en.cppreference.com/w/cpp/language/pimpl) to avoid * including CUDA-specific implementation details in the header. */ class EllpackPage { public: /*! * \brief Default constructor. * * This is used in the external memory case. An empty ELLPACK page is constructed with its content * set later by the reader. */ EllpackPage(); /*! * \brief Constructor from an existing DMatrix. * * This is used in the in-memory case. The ELLPACK page is constructed from an existing DMatrix * in CSR format. */ explicit EllpackPage(DMatrix* dmat, const BatchParam& param); /*! \brief Destructor. */ ~EllpackPage(); EllpackPage(EllpackPage&& that); /*! \return Number of instances in the page. */ size_t Size() const; /*! \brief Set the base row id for this page. */ void SetBaseRowId(size_t row_id); const EllpackPageImpl* Impl() const { return impl_.get(); } EllpackPageImpl* Impl() { return impl_.get(); } private: std::unique_ptr<EllpackPageImpl> impl_; }; class GHistIndexMatrix; template<typename T> class BatchIteratorImpl { public: using iterator_category = std::forward_iterator_tag; // NOLINT virtual ~BatchIteratorImpl() = default; virtual const T& operator*() const = 0; virtual BatchIteratorImpl& operator++() = 0; virtual bool AtEnd() const = 0; virtual std::shared_ptr<T const> Page() const = 0; }; template<typename T> class BatchIterator { public: using iterator_category = std::forward_iterator_tag; // NOLINT explicit BatchIterator(BatchIteratorImpl<T>* impl) { impl_.reset(impl); } explicit BatchIterator(std::shared_ptr<BatchIteratorImpl<T>> impl) { impl_ = impl; } BatchIterator &operator++() { CHECK(impl_ != nullptr); ++(*impl_); return *this; } const T& operator*() const { CHECK(impl_ != nullptr); return *(*impl_); } bool operator!=(const BatchIterator&) const { CHECK(impl_ != nullptr); return !impl_->AtEnd(); } bool AtEnd() const { CHECK(impl_ != nullptr); return impl_->AtEnd(); } std::shared_ptr<T const> Page() const { return impl_->Page(); } private: std::shared_ptr<BatchIteratorImpl<T>> impl_; }; template<typename T> class BatchSet { public: explicit BatchSet(BatchIterator<T> begin_iter) : begin_iter_(std::move(begin_iter)) {} BatchIterator<T> begin() { return begin_iter_; } // NOLINT BatchIterator<T> end() { return BatchIterator<T>(nullptr); } // NOLINT private: BatchIterator<T> begin_iter_; }; struct XGBAPIThreadLocalEntry; /*! * \brief Internal data structured used by XGBoost during training. */ class DMatrix { public: /*! \brief default constructor */ DMatrix() = default; /*! \brief meta information of the dataset */ virtual MetaInfo& Info() = 0; virtual void SetInfo(const char *key, const void *dptr, DataType dtype, size_t num) { this->Info().SetInfo(key, dptr, dtype, num); } virtual void SetInfo(const char* key, std::string const& interface_str) { this->Info().SetInfo(key, interface_str); } /*! \brief meta information of the dataset */ virtual const MetaInfo& Info() const = 0; /*! \brief Get thread local memory for returning data from DMatrix. */ XGBAPIThreadLocalEntry& GetThreadLocal() const; /** * \brief Gets batches. Use range based for loop over BatchSet to access individual batches. */ template<typename T> BatchSet<T> GetBatches(const BatchParam& param = {}); template <typename T> bool PageExists() const; // the following are column meta data, should be able to answer them fast. /*! \return Whether the data columns single column block. */ virtual bool SingleColBlock() const = 0; /*! \brief virtual destructor */ virtual ~DMatrix(); /*! \brief Whether the matrix is dense. */ bool IsDense() const { return Info().num_nonzero_ == Info().num_row_ * Info().num_col_; } /*! * \brief Load DMatrix from URI. * \param uri The URI of input. * \param silent Whether print information during loading. * \param load_row_split Flag to read in part of rows, divided among the workers in distributed mode. * \param file_format The format type of the file, used for dmlc::Parser::Create. * By default "auto" will be able to load in both local binary file. * \param page_size Page size for external memory. * \return The created DMatrix. */ static DMatrix* Load(const std::string& uri, bool silent, bool load_row_split, const std::string& file_format = "auto"); /** * \brief Creates a new DMatrix from an external data adapter. * * \tparam AdapterT Type of the adapter. * \param [in,out] adapter View onto an external data. * \param missing Values to count as missing. * \param nthread Number of threads for construction. * \param cache_prefix (Optional) The cache prefix for external memory. * \param page_size (Optional) Size of the page. * * \return a Created DMatrix. */ template <typename AdapterT> static DMatrix* Create(AdapterT* adapter, float missing, int nthread, const std::string& cache_prefix = ""); /** * \brief Create a new Quantile based DMatrix used for histogram based algorithm. * * \tparam DataIterHandle External iterator type, defined in C API. * \tparam DMatrixHandle DMatrix handle, defined in C API. * \tparam DataIterResetCallback Callback for reset, prototype defined in C API. * \tparam XGDMatrixCallbackNext Callback for next, prototype defined in C API. * * \param iter External data iterator * \param proxy A hanlde to ProxyDMatrix * \param reset Callback for reset * \param next Callback for next * \param missing Value that should be treated as missing. * \param nthread number of threads used for initialization. * \param max_bin Maximum number of bins. * * \return A created quantile based DMatrix. */ template <typename DataIterHandle, typename DMatrixHandle, typename DataIterResetCallback, typename XGDMatrixCallbackNext> static DMatrix *Create(DataIterHandle iter, DMatrixHandle proxy, DataIterResetCallback *reset, XGDMatrixCallbackNext *next, float missing, int nthread, int max_bin); /** * \brief Create an external memory DMatrix with callbacks. * * \tparam DataIterHandle External iterator type, defined in C API. * \tparam DMatrixHandle DMatrix handle, defined in C API. * \tparam DataIterResetCallback Callback for reset, prototype defined in C API. * \tparam XGDMatrixCallbackNext Callback for next, prototype defined in C API. * * \param iter External data iterator * \param proxy A hanlde to ProxyDMatrix * \param reset Callback for reset * \param next Callback for next * \param missing Value that should be treated as missing. * \param nthread number of threads used for initialization. * \param cache Prefix of cache file path. * * \return A created external memory DMatrix. */ template <typename DataIterHandle, typename DMatrixHandle, typename DataIterResetCallback, typename XGDMatrixCallbackNext> static DMatrix *Create(DataIterHandle iter, DMatrixHandle proxy, DataIterResetCallback *reset, XGDMatrixCallbackNext *next, float missing, int32_t nthread, std::string cache); virtual DMatrix *Slice(common::Span<int32_t const> ridxs) = 0; /*! \brief Number of rows per page in external memory. Approximately 100MB per page for * dataset with 100 features. */ static const size_t kPageSize = 32UL << 12UL; protected: virtual BatchSet<SparsePage> GetRowBatches() = 0; virtual BatchSet<CSCPage> GetColumnBatches() = 0; virtual BatchSet<SortedCSCPage> GetSortedColumnBatches() = 0; virtual BatchSet<EllpackPage> GetEllpackBatches(const BatchParam& param) = 0; virtual BatchSet<GHistIndexMatrix> GetGradientIndex(const BatchParam& param) = 0; virtual bool EllpackExists() const = 0; virtual bool SparsePageExists() const = 0; }; template<> inline BatchSet<SparsePage> DMatrix::GetBatches(const BatchParam&) { return GetRowBatches(); } template<> inline bool DMatrix::PageExists<EllpackPage>() const { return this->EllpackExists(); } template<> inline bool DMatrix::PageExists<SparsePage>() const { return this->SparsePageExists(); } template<> inline BatchSet<CSCPage> DMatrix::GetBatches(const BatchParam&) { return GetColumnBatches(); } template<> inline BatchSet<SortedCSCPage> DMatrix::GetBatches(const BatchParam&) { return GetSortedColumnBatches(); } template<> inline BatchSet<EllpackPage> DMatrix::GetBatches(const BatchParam& param) { return GetEllpackBatches(param); } template<> inline BatchSet<GHistIndexMatrix> DMatrix::GetBatches(const BatchParam& param) { return GetGradientIndex(param); } } // namespace xgboost namespace dmlc { DMLC_DECLARE_TRAITS(is_pod, xgboost::Entry, true); namespace serializer { template <> struct Handler<xgboost::Entry> { inline static void Write(Stream* strm, const xgboost::Entry& data) { strm->Write(data.index); strm->Write(data.fvalue); } inline static bool Read(Stream* strm, xgboost::Entry* data) { return strm->Read(&data->index) && strm->Read(&data->fvalue); } }; } // namespace serializer } // namespace dmlc #endif // XGBOOST_DATA_H_
reduction.h
#ifndef __DACE_REDUCTION_H #define __DACE_REDUCTION_H #include <cstdint> #include "types.h" #include "math.h" // for ::min, ::max #ifdef __CUDACC__ #include "../../../external/cub/cub/device/device_segmented_reduce.cuh" #include "../../../external/cub/cub/device/device_reduce.cuh" #include "../../../external/cub/cub/block/block_reduce.cuh" #include "../../../external/cub/cub/iterator/counting_input_iterator.cuh" #include "../../../external/cub/cub/iterator/transform_input_iterator.cuh" #endif // Specializations for reductions implemented in frameworks like OpenMP, MPI namespace dace { // Internal type. See below for wcr_fixed external type, which selects // the implementation according to T's properties. template <ReductionType REDTYPE, typename T> struct _wcr_fixed { static DACE_HDFI void reduce(T *ptr, const T& value); static DACE_HDFI void reduce_atomic(T *ptr, const T& value); DACE_HDFI T operator()(const T &a, const T &b) const; }; // Custom reduction with a lambda function template <typename T> struct wcr_custom { template <typename WCR> static DACE_HDFI void reduce_atomic(WCR wcr, T *ptr, const T& value) { // The slowest kind of atomic operations (locked/compare-and-swap), // this should only happen in case of unrecognized lambdas #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 300 // Adapted from CUDA's pre-v8.0 double atomicAdd implementation T old = *ptr, assumed; do { assumed = old; old = atomicCAS(ptr, assumed, wcr(assumed, value)); } while (assumed != old); #else #pragma omp critical *ptr = wcr(*ptr, value); #endif } // Non-conflicting version --> no critical section template <typename WCR> static DACE_HDFI void reduce(WCR wcr, T *ptr, const T& value) { *ptr = wcr(*ptr, value); } }; template <typename T> struct _wcr_fixed<ReductionType::Sum, T> { static DACE_HDFI void reduce(T *ptr, const T& value) { *ptr += value; } static DACE_HDFI void reduce_atomic(T *ptr, const T& value) { #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 300 atomicAdd(ptr, value); #else #pragma omp atomic *ptr += value; #endif } DACE_HDFI T operator()(const T &a, const T &b) const { return a + b; } }; // Implementation of double atomicAdd for CUDA architectures prior to 6.0 #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 600 template <> struct _wcr_fixed<ReductionType::Sum, double> { static DACE_HDFI void reduce(double *ptr, const double& value) { *ptr += value; } static DACE_HDFI void reduce_atomic(double *ptr, const double& value) { unsigned long long int* address_as_ull = (unsigned long long int*)ptr; unsigned long long int old = *address_as_ull, assumed; do { assumed = old; old = atomicCAS(address_as_ull, assumed, __double_as_longlong(value + __longlong_as_double(assumed))); } while (assumed != old); } DACE_HDFI double operator()(const double &a, const double &b) const { return a + b; } }; #endif template <typename T> struct _wcr_fixed<ReductionType::Product, T> { static DACE_HDFI void reduce(T *ptr, const T& value) { *ptr *= value; } static DACE_HDFI void reduce_atomic(T *ptr, const T& value) { #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 300 wcr_custom<T>::reduce( _wcr_fixed<ReductionType::Product, T>(), ptr, value); #else #pragma omp atomic *ptr *= value; #endif } DACE_HDFI T operator()(const T &a, const T &b) const { return a * b; } }; template <typename T> struct _wcr_fixed<ReductionType::Min, T> { static DACE_HDFI void reduce(T *ptr, const T& value) { *ptr = ::min(*ptr, value); } static DACE_HDFI void reduce_atomic(T *ptr, const T& value) { #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 300 atomicMin(ptr, value); #else wcr_custom<T>::reduce( _wcr_fixed<ReductionType::Min, T>(), ptr, value); #endif } DACE_HDFI T operator()(const T &a, const T &b) const { return ::min(a, b); } }; template <typename T> struct _wcr_fixed<ReductionType::Max, T> { static DACE_HDFI void reduce(T *ptr, const T& value) { *ptr = ::max(*ptr, value); } static DACE_HDFI void reduce_atomic(T *ptr, const T& value) { #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 300 atomicMax(ptr, value); #else wcr_custom<T>::reduce( _wcr_fixed<ReductionType::Max, T>(), ptr, value); #endif } DACE_HDFI T operator()(const T &a, const T &b) const { return ::max(a, b); } }; template <typename T> struct _wcr_fixed<ReductionType::Logical_And, T> { static DACE_HDFI void reduce(T *ptr, const T& value) { *ptr = (*ptr && value); } static DACE_HDFI void reduce_atomic(T *ptr, const T& value) { #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 300 atomicAnd(ptr, value ? T(1) : T(0)); #else T val = (value ? T(1) : T(0)); #pragma omp atomic *ptr &= val; #endif } DACE_HDFI T operator()(const T &a, const T &b) const { return a && b; } }; template <typename T> struct _wcr_fixed<ReductionType::Bitwise_And, T> { static DACE_HDFI void reduce(T *ptr, const T& value) { *ptr &= value; } static DACE_HDFI void reduce_atomic(T *ptr, const T& value) { #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 300 atomicAnd(ptr, value); #else #pragma omp atomic *ptr &= value; #endif } DACE_HDFI T operator()(const T &a, const T &b) const { return a & b; } }; template <typename T> struct _wcr_fixed<ReductionType::Logical_Or, T> { static DACE_HDFI void reduce(T *ptr, const T& value) { *ptr = (*ptr || value); } static DACE_HDFI void reduce_atomic(T *ptr, const T& value) { #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 300 atomicOr(ptr, value ? T(1) : T(0)); #else T val = (value ? T(1) : T(0)); #pragma omp atomic *ptr |= val; #endif } DACE_HDFI T operator()(const T &a, const T &b) const { return a || b; } }; template <typename T> struct _wcr_fixed<ReductionType::Bitwise_Or, T> { static DACE_HDFI void reduce(T *ptr, const T& value) { *ptr |= value; } static DACE_HDFI void reduce_atomic(T *ptr, const T& value) { #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 300 atomicOr(ptr, value); #else #pragma omp atomic *ptr |= value; #endif } DACE_HDFI T operator()(const T &a, const T &b) const { return a | b; } }; template <typename T> struct _wcr_fixed<ReductionType::Logical_Xor, T> { static DACE_HDFI void reduce(T *ptr, const T& value) { *ptr = (*ptr != value); } static DACE_HDFI void reduce_atomic(T *ptr, const T& value) { #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 300 atomicXor(ptr, value ? T(1) : T(0)); #else T val = (value ? T(1) : T(0)); #pragma omp atomic *ptr ^= val; #endif } DACE_HDFI T operator()(const T &a, const T &b) const { return a != b; } }; template <typename T> struct _wcr_fixed<ReductionType::Bitwise_Xor, T> { static DACE_HDFI void reduce(T *ptr, const T& value) { *ptr ^= value; } static DACE_HDFI void reduce_atomic(T *ptr, const T& value) { #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 300 atomicXor(ptr, value); #else #pragma omp atomic *ptr ^= value; #endif } DACE_HDFI T operator()(const T &a, const T &b) const { return a ^ b; } }; ////////////////////////////////////////////////////////////////////////// // Specialization that regresses to critical section / locked update for // unsupported types template<typename T> using EnableIfScalar = typename std::enable_if<std::is_scalar<T>::value>::type; // Any vector type that is not of length 1, or struct/complex types // do not support atomics. In these cases, we regress to locked updates. template <ReductionType REDTYPE, typename T, typename SFINAE = void> struct wcr_fixed { static DACE_HDFI void reduce(T *ptr, const T& value) { _wcr_fixed<REDTYPE, T>::reduce(ptr, value); } static DACE_HDFI void reduce_atomic(T *ptr, const T& value) { wcr_custom<T>::template reduce_atomic( _wcr_fixed<REDTYPE, T>(), ptr, value); } }; // When atomics are supported, use _wcr_fixed normally template <ReductionType REDTYPE, typename T> struct wcr_fixed<REDTYPE, T, EnableIfScalar<T> > { static DACE_HDFI void reduce(T *ptr, const T& value) { _wcr_fixed<REDTYPE, T>::reduce(ptr, value); } static DACE_HDFI void reduce_atomic(T *ptr, const T& value) { _wcr_fixed<REDTYPE, T>::reduce_atomic(ptr, value); } DACE_HDFI T operator()(const T &a, const T &b) const { return _wcr_fixed<REDTYPE, T>()(a, b); } }; #ifdef __CUDACC__ struct StridedIteratorHelper { explicit StridedIteratorHelper(size_t stride) : stride(stride) {} size_t stride; __host__ __device__ __forceinline__ size_t operator()(const size_t &index) const { return index * stride; } }; inline auto stridedIterator(size_t stride) { cub::CountingInputIterator<int> counting_iterator(0); StridedIteratorHelper conversion_op(stride); cub::TransformInputIterator<int, decltype(conversion_op), decltype(counting_iterator)> itr(counting_iterator, conversion_op); return itr; } #endif } // namespace dace #endif // __DACE_REDUCTION_H
utility.h
#ifndef _UTILITY_H #define _UTILITY_H #include <algorithm> #include <chrono> #include <climits> #include <cmath> #include <cstring> #include <fstream> #include <iostream> #include <omp.h> #include <stdint.h> #include <stdlib.h> #include <unistd.h> #include <vector> //#include <numa.h> // #include <tbb/scalable_allocator.h> using namespace std; #define EPSILON 0.001 template <class T> struct ErrorTolerantEqual : public binary_function<T, T, bool> { ErrorTolerantEqual(const T &myepsilon) : epsilon(myepsilon){}; inline bool operator()(const T &a, const T &b) const { // According to the IEEE 754 standard, negative zero and positive zero // should compare as equal with the usual (numerical) comparison operators, // like the == operators of C++ if (a == b) // covers the "division by zero" case as well: max(a,b) can't be // zero if it fails return true; // covered the integral numbers case return (std::abs(a - b) < epsilon || (std::abs(a - b) / max(std::abs(a), std::abs(b))) < epsilon); } T epsilon; }; // Because identify reports ambiguity in PGI compilers template <typename T> struct myidentity : public std::unary_function<T, T> { const T operator()(const T &x) const { return x; } }; template <typename _ForwardIterator, typename _StrictWeakOrdering> bool my_is_sorted(_ForwardIterator __first, _ForwardIterator __last, _StrictWeakOrdering __comp) { if (__first == __last) return true; _ForwardIterator __next = __first; for (++__next; __next != __last; __first = __next, ++__next) if (__comp(*__next, *__first)) return false; return true; }; template <typename ITYPE> ITYPE CumulativeSum(ITYPE *arr, ITYPE size) { ITYPE prev; ITYPE tempnz = 0; for (ITYPE i = 0; i < size; ++i) { prev = arr[i]; arr[i] = tempnz; tempnz += prev; } return (tempnz); // return sum } template <typename _ForwardIter, typename T> void iota(_ForwardIter __first, _ForwardIter __last, T __value) { while (__first != __last) *__first++ = __value++; } template <typename T, typename I> T **allocate2D(I m, I n) { T **array = new T *[m]; for (I i = 0; i < m; ++i) array[i] = new T[n]; return array; } template <typename T, typename I> void deallocate2D(T **array, I m) { for (I i = 0; i < m; ++i) delete[] array[i]; delete[] array; } template <typename T> struct absdiff : binary_function<T, T, T> { T operator()(T const &arg1, T const &arg2) const { using std::abs; return abs(arg1 - arg2); } }; /* This function will return n % d. d must be one of: 1, 2, 4, 8, 16, 32, … */ inline unsigned int getModulo(unsigned int n, unsigned int d) { return (n & (d - 1)); } // Same requirement (d=2^k) here as well inline unsigned int getDivident(unsigned int n, unsigned int d) { while ((d = d >> 1)) n = n >> 1; return n; } // Memory allocation by C++-new / Aligned malloc / scalable malloc template <typename T> inline T *my_malloc(size_t array_size, bool init = true) { // // #ifdef TBB // cout << "Called TBB" <<endl; // T *a = (T *)scalable_malloc(sizeof(T) * array_size); // for (int i=0; i<array_size; ++i) // { // a[i] = T(); // } // return a; // #ifdef CPP // global_blockers[blocker_id] = static_cast<TripleNode*>(::operator new(SIZE * flops_by_row_blockers[blocker_id])); // T *a = static_cast<T*>(::operator new(array_size * sizeof(T))); // GraphBLAS Compatibility // T * a = new T[array_size]; auto a = static_cast<T*>(malloc(sizeof(T) * array_size)); // T *a; // a = (T*) aligned_alloc(4096, array_size * sizeof(T)); // #pragma omp parallel // { // cout << "Take a look " << omp_get_num_threads() << endl; // } if (init) { #pragma omp parallel for for(size_t i=0; i<array_size; i++) { a[i] = T(); } } return a; // #elif defined IMM // return (T *)_mm_malloc(sizeof(T) * array_size, 64); // #else // return (T *)scalable_malloc(sizeof(T) * array_size); // #endif } // Memory deallocation template <typename T> inline void my_free(T *a) { #ifdef CPP // GraphBLAS Compatibility // delete[] a; free(a); #elif defined IMM _mm_free(a); #elif defined TBB scalable_free(a); #else scalable_free(a); #endif } template <class T, class ...Ts> inline void my_free(T *a, Ts *...as) { my_free(a); my_free(as...); } // Prefix sum (Sequential) template <typename T> void seq_scan(T *in, T *out, T N) { out[0] = 0; for (T i = 0; i < N - 1; ++i) { out[i + 1] = out[i] + in[i]; } } // Prefix sum (Thread parallel) template <typename T> void scan(T *in, T *out, T N) { // if the array is comparatively small, use sequential scan instead if (N < (1 << 17)) { seq_scan(in, out, N); } else { int tnum = 1; #pragma omp parallel { tnum = omp_get_num_threads(); } T each_n = N / tnum; T *partial_sum = my_malloc<T>(tnum); #pragma omp parallel { // thead level prefix summing int tid = omp_get_thread_num(); T start = each_n * tid; T end = (tid < tnum - 1) ? start + each_n : N; out[start] = 0; for (T i = start; i < end - 1; ++i) { out[i + 1] = out[i] + in[i]; } // calculate offset in every thread partial_sum[tid] = out[end - 1] + in[end - 1]; #pragma omp barrier T offset = 0; for (int i = 0; i < tid; ++i) { offset += partial_sum[i]; } for (T i = start; i < end; ++i) { out[i] += offset; } } my_free<T>(partial_sum); } } // Sort by key template <typename IT, typename NT> inline void mergesort(IT *nnz_num, NT *nnz_sorting, IT *temp_num, NT *temp_sorting, IT left, IT right) { IT mid, i, j, k; if (left >= right) { return; } mid = (left + right) / 2; mergesort(nnz_num, nnz_sorting, temp_num, temp_sorting, left, mid); mergesort(nnz_num, nnz_sorting, temp_num, temp_sorting, mid + 1, right); for (i = left; i <= mid; ++i) { temp_num[i] = nnz_num[i]; temp_sorting[i] = nnz_sorting[i]; } for (i = mid + 1, j = right; i <= right; ++i, --j) { temp_sorting[i] = nnz_sorting[j]; temp_num[i] = nnz_num[j]; } i = left; j = right; for (k = left; k <= right; ++k) { if (temp_num[i] <= temp_num[j] && i <= mid) { nnz_num[k] = temp_num[i]; nnz_sorting[k] = temp_sorting[i++]; } else { nnz_num[k] = temp_num[j]; nnz_sorting[k] = temp_sorting[j--]; } } } // Sorting key-value template <typename IT, typename NT> inline void cpu_sorting_key_value(IT *key, NT *value, IT N) { IT *temp_key; NT *temp_value; temp_key = my_malloc<IT>(N); temp_value = my_malloc<NT>(N); mergesort(key, value, temp_key, temp_value, 0, N - 1); my_free<IT>(temp_key); my_free<NT>(temp_value); } // // query cpu cache // size_t i386_cpuid_caches() { // int i; // size_t total_avail_cache = 0; // for (i = 0; i < 32; i++) { // // Variables to hold the contents of the 4 i386 legacy registers // uint32_t eax, ebx, ecx, edx; // eax = 4; // get cache info // ecx = i; // cache id // __asm__( // "cpuid" // call i386 cpuid instruction // : "+a"(eax) // contains the cpuid command code, 4 for cache query // , // "=b"(ebx), "+c"(ecx) // contains the cache id // , // "=d"(edx)); // generates output in 4 registers eax, ebx, ecx and edx // // taken from http://download.intel.com/products/processor/manual/325462.pdf // // Vol. 2A 3-149 // int cache_type = eax & 0x1F; // if (cache_type == 0) // end of valid cache identifiers // break; // char const *cache_type_string; // switch (cache_type) { // case 1: // cache_type_string = "Data Cache"; // break; // case 2: // cache_type_string = "Instruction Cache"; // break; // case 3: // cache_type_string = "Unified Cache"; // break; // default: // cache_type_string = "Unknown Type Cache"; // break; // } // int cache_level = (eax >>= 5) & 0x7; // int cache_is_self_initializing = // (eax >>= 3) & 0x1; // does not need SW initialization // int cache_is_fully_associative = (eax >>= 1) & 0x1; // // taken from http://download.intel.com/products/processor/manual/325462.pdf // // 3-166 Vol. 2A ebx contains 3 integers of 10, 10 and 12 bits respectively // unsigned int cache_sets = ecx + 1; // unsigned int cache_coherency_line_size = (ebx & 0xFFF) + 1; // unsigned int cache_physical_line_partitions = ((ebx >>= 12) & 0x3FF) + 1; // unsigned int cache_ways_of_associativity = ((ebx >>= 10) & 0x3FF) + 1; // // Total cache size is the product // size_t cache_total_size = cache_ways_of_associativity * // cache_physical_line_partitions * // cache_coherency_line_size * cache_sets; // if (cache_type == 1 or cache_type == 3) // total_avail_cache = std::max(total_avail_cache, cache_total_size); // } // return total_avail_cache; // } // inline void write(__int128 x) // { // if(x<0) // { // putchar('-'); // x=-x; // } // if(x>9) // write(x/10); // putchar(x%10+'0'); // } #endif
test_core.c
/* * RELIC is an Efficient LIbrary for Cryptography * Copyright (c) 2012 RELIC Authors * * This file is part of RELIC. RELIC is legal property of its developers, * whose names are not listed here. Please refer to the COPYRIGHT file * for contact information. * * RELIC is free software; you can redistribute it and/or modify it under the * terms of the version 2.1 (or later) of the GNU Lesser General Public License * as published by the Free Software Foundation; or version 2.0 of the Apache * License as published by the Apache Software Foundation. See the LICENSE files * for more details. * * RELIC 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 LICENSE files for more details. * * You should have received a copy of the GNU Lesser General Public or the * Apache License along with RELIC. If not, see <https://www.gnu.org/licenses/> * or <https://www.apache.org/licenses/>. */ /** * @file * * Tests for configuration management. * * @ingroup test */ #include <stdio.h> #include "relic.h" #include "relic_test.h" #if defined(MULTI) #if MULTI == PTHREAD void *master(void *ptr) { int *code = (int *)ptr; core_init(); RLC_THROW(ERR_NO_MEMORY); if (err_get_code() != RLC_ERR) { *code = RLC_ERR; } else { *code = RLC_OK; } core_clean(); return NULL; } void *tester(void *ptr) { int *code = (int *)ptr; core_init(); if (err_get_code() != RLC_OK) { *code = RLC_ERR; } else { *code = RLC_OK; } core_clean(); return NULL; } #endif #endif int main(void) { int code = RLC_ERR; /* Initialize library with default configuration. */ if (core_init() != RLC_OK) { core_clean(); return 1; } util_banner("Tests for the CORE module:\n", 0); TEST_ONCE("the library context is consistent") { TEST_ASSERT(core_get() != NULL, end); } TEST_END; TEST_ONCE("switching the library context is correct") { ctx_t new_ctx, *old_ctx; /* Backup the old context. */ old_ctx = core_get(); /* Switch the library context. */ core_set(&new_ctx); /* Reinitialize library with new context. */ core_init(); /* Run function to manipulate the library context. */ RLC_THROW(ERR_NO_MEMORY); core_set(old_ctx); TEST_ASSERT(err_get_code() == RLC_OK, end); core_set(&new_ctx); TEST_ASSERT(err_get_code() == RLC_ERR, end); /* Now we need to finalize the new context. */ core_clean(); /* And restore the original context. */ core_set(old_ctx); } TEST_END; code = RLC_OK; #if defined(MULTI) #if MULTI == OPENMP TEST_ONCE("library context is thread-safe") { omp_set_num_threads(CORES); #pragma omp parallel shared(code) { if (omp_get_thread_num() == 0) { RLC_THROW(ERR_NO_MEMORY); if (err_get_code() != RLC_ERR) { code = RLC_ERR; } } else { core_init(); if (err_get_code() != RLC_OK) { code = RLC_ERR; } core_clean(); } } TEST_ASSERT(code == RLC_OK, end); core_init(); #pragma omp parallel copyin(core_ctx) shared(code) { if (core_get() == NULL) { code = RLC_ERR; } } TEST_ASSERT(code == RLC_OK, end); core_clean(); } TEST_END; #endif #if MULTI == PTHREAD TEST_ONCE("library context is thread-safe") { pthread_t thread[CORES]; int result[CORES] = { RLC_OK }; for (int i = 0; i < CORES; i++) { if (i == 0) { if (pthread_create(&(thread[0]), NULL, master, &(result[0]))) { code = RLC_ERR; } } else { if (pthread_create(&(thread[i]), NULL, tester, &(result[i]))) { code = RLC_ERR; } } if (result[i] != RLC_OK) { code = RLC_ERR; } } for (int i = 0; i < CORES; i++) { if (pthread_join(thread[i], NULL)) { code = RLC_ERR; } } TEST_ASSERT(code == RLC_OK, end); } TEST_END; #endif #endif util_banner("All tests have passed.\n", 0); end: core_clean(); return code; }
pvector.h
/* Copyright (c) 2015, The Regents of the University of California (Regents). 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. 3. Neither the name of the Regents nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ #ifndef PVECTOR_H_ #define PVECTOR_H_ #include <algorithm> /* Taken from GAP Benchmark Suite Class: pvector Author: Scott Beamer Vector class with ability to not initialize or do initialize in parallel - std::vector (when resizing) will always initialize, and does it serially - When pvector is resized, new elements are uninitialized - Resizing is not thread-safe */ template <typename T_> class pvector { public: typedef T_* iterator; pvector() : start_(nullptr), end_size_(nullptr), end_capacity_(nullptr) {} explicit pvector(size_t num_elements) { start_ = new T_[num_elements]; end_size_ = start_ + num_elements; end_capacity_ = end_size_; } pvector(size_t num_elements, T_ init_val) : pvector(num_elements) { fill(init_val); } pvector(iterator copy_begin, iterator copy_end) : pvector(copy_end - copy_begin) { #pragma omp parallel for for (size_t i=0; i < capacity(); i++) start_[i] = copy_begin[i]; } // don't want this to be copied, too much data to move pvector(const pvector &other) = delete; // prefer move because too much data to copy pvector(pvector &&other) : start_(other.start_), end_size_(other.end_size_), end_capacity_(other.end_capacity_) { other.start_ = nullptr; other.end_size_ = nullptr; other.end_capacity_ = nullptr; } pvector& operator= (const pvector &other) { resize(other.size()); #pragma omp parallel for for (size_t i=0; i < size(); i++) start_[i] = other[i]; return *this; } // want move assignment pvector& operator= (pvector &&other) { start_ = other.start_; end_size_ = other.end_size_; end_capacity_ = other.end_capacity_; other.start_ = nullptr; other.end_size_ = nullptr; other.end_capacity_ = nullptr; return *this; } ~pvector() { if (start_ != nullptr) delete[] start_; } // not thread-safe void reserve(size_t num_elements) { if (num_elements > capacity()) { T_ *new_range = new T_[num_elements]; #pragma omp parallel for for (size_t i=0; i < size(); i++) new_range[i] = start_[i]; end_size_ = new_range + size(); delete[] start_; start_ = new_range; end_capacity_ = start_ + num_elements; } } bool empty() { return end_size_ == start_; } void clear() { end_size_ = start_; } void resize(size_t num_elements) { reserve(num_elements); end_size_ = start_ + num_elements; } T_& operator[](size_t n) { return start_[n]; } const T_& operator[](size_t n) const { return start_[n]; } void push_back(T_ val) { if (size() == capacity()) { size_t new_size = capacity() == 0 ? 1 : capacity() * growth_factor; reserve(new_size); } *end_size_ = val; end_size_++; } void fill(T_ init_val) { #pragma omp parallel for for (T_* ptr=start_; ptr < end_size_; ptr++) *ptr = init_val; } size_t capacity() const { return end_capacity_ - start_; } size_t size() const { return end_size_ - start_; } iterator begin() const { return start_; } iterator end() const { return end_size_; } T_* data() const { return start_; } void swap(pvector &other) { std::swap(start_, other.start_); std::swap(end_size_, other.end_size_); std::swap(end_capacity_, other.end_capacity_); } const T_& front() const { return *start_; } T_& front() { return *start_; } const T_& back() const { return *(end_size_-1); } T_& back() { return *(end_size_-1); } private: T_* start_; T_* end_size_; T_* end_capacity_; static const size_t growth_factor = 2; }; #endif // PVECTOR_H_
atomic-3.c
/* { dg-do compile } */ /* { dg-options "-fopenmp -fdump-tree-gimple" } */ /* LLVM LOCAL test not applicable */ /* { dg-require-fdump "" } */ int *xyzzy; void f1(void) { #pragma omp atomic xyzzy++; } /* { dg-final { scan-tree-dump-times "xyzzy, 4" 1 "gimple" { target i?86-*-* x86_64-*-* ia64-*-* powerpc*-*-* alpha*-*-* } } } */ /* { dg-final { cleanup-tree-dump "gimple" } } */
adapter.h
/** * Implementation of a lock-free interpolation search tree. * Trevor Brown, 2019. */ #ifndef DS_ADAPTER_H #define DS_ADAPTER_H #define DS_ADAPTER_SUPPORTS_TERMINAL_ITERATE #include <iostream> #include "errors.h" #include "brown_ext_ist_lf_impl.h" #ifdef USE_TREE_STATS # define TREE_STATS_BYTES_AT_DEPTH # include "tree_stats.h" #endif #define NODE_T Node<K,V> #if defined IST_DISABLE_MULTICOUNTER_AT_ROOT # define RECORD_MANAGER_T record_manager<Reclaim, Alloc, Pool, NODE_T, KVPair<K,V>, RebuildOperation<K,V>> #else # define RECORD_MANAGER_T record_manager<Reclaim, Alloc, Pool, NODE_T, KVPair<K,V>, RebuildOperation<K,V>, MultiCounter> #endif #define DATA_STRUCTURE_T istree<K, V, Interpolator<K>, RECORD_MANAGER_T> template <typename T> struct ValidAllocatorTest { static constexpr bool value = false; }; template <typename T> struct ValidAllocatorTest<allocator_new<T>> { static constexpr bool value = true; }; template <typename Alloc> static bool isValidAllocator(void) { return ValidAllocatorTest<Alloc>::value; } template <typename T> struct ValidPoolTest { static constexpr bool value = false; }; template <typename T> struct ValidPoolTest<pool_none<T>> { static constexpr bool value = true; }; template <typename Pool> static bool isValidPool(void) { return ValidPoolTest<Pool>::value; } template <typename K> class Interpolator { public: bool less(const K& a, const K& b); double interpolate(const K& key, const K& rangeLeft, const K& rangeRight); }; template <> class Interpolator<long long> { public: int compare(const long long& a, const long long& b) { return (a < b) ? -1 : (a > b) ? 1 : 0; } // double interpolate(const long long& key, const long long& rangeLeft, const long long& rangeRight) { // if (rangeRight == rangeLeft) return 0; // return ((double) key - (double) rangeLeft) / ((double) rangeRight - (double) rangeLeft); // } }; template <typename K, typename V, class Reclaim = reclaimer_debra<K>, class Alloc = allocator_new<K>, class Pool = pool_none<K>> class ds_adapter { private: DATA_STRUCTURE_T * const ds; public: ds_adapter(const int NUM_THREADS, const K& unused1, const K& KEY_MAX, const V& NO_VALUE, Random64 * const unused3) : ds(new DATA_STRUCTURE_T(NUM_THREADS, KEY_MAX, NO_VALUE)) { if (!isValidAllocator<Alloc>()) { setbench_error("This data structure must be used with allocator_new.") } if (!isValidPool<Pool>()) { setbench_error("This data structure must be used with pool_none.") } if (NUM_THREADS > MAX_THREADS_POW2) { setbench_error("NUM_THREADS exceeds MAX_THREADS_POW2"); } } ds_adapter(const int NUM_THREADS , const K& unused1 , const K& KEY_MAX , const V& NO_VALUE , Random64 * const unused3 , const K * const initKeys , const V * const initValues , const size_t initNumKeys , const size_t initConstructionSeed /* note: randomness is used to ensure good tree structure whp */ ) : ds(new DATA_STRUCTURE_T(initKeys, initValues, initNumKeys, initConstructionSeed, NUM_THREADS, KEY_MAX, NO_VALUE)) { if (!isValidAllocator<Alloc>()) { setbench_error("This data structure must be used with allocator_new.") } if (!isValidPool<Pool>()) { setbench_error("This data structure must be used with pool_none.") } if (NUM_THREADS > MAX_THREADS_POW2) { setbench_error("NUM_THREADS exceeds MAX_THREADS_POW2"); } } ~ds_adapter() { delete ds; } void * getNoValue() { return ds->NO_VALUE; } void initThread(const int tid) { ds->initThread(tid); } void deinitThread(const int tid) { ds->deinitThread(tid); } bool contains(const int tid, const K& key) { return ds->contains(tid, key); } V insert(const int tid, const K& key, const V& val) { return ds->insert(tid, key, val); } V insertIfAbsent(const int tid, const K& key, const V& val) { return ds->insertIfAbsent(tid, key, val); } V erase(const int tid, const K& key) { return ds->erase(tid, key); } V find(const int tid, const K& key) { return ds->find(tid, key); } int rangeQuery(const int tid, const K& lo, const K& hi, K * const resultKeys, V * const resultValues) { setbench_error("not implemented"); } void printSummary() { auto recmgr = ds->debugGetRecMgr(); recmgr->printStatus(); // auto sizeBytes = ds->debugComputeSizeBytes(); // std::cout<<"endingSizeBytes="<<sizeBytes<<std::endl; } bool validateStructure() { // ds->debugGVPrint(); return true; } void printObjectSizes() { std::cout<<"size_node="<<(sizeof(NODE_T))<<std::endl; } // try to clean up: must only be called by a single thread as part of the test harness! void debugGCSingleThreaded() { ds->debugGetRecMgr()->debugGCSingleThreaded(); } #ifdef USE_TREE_STATS class NodeHandler { public: typedef casword_t NodePtrType; K minKey; K maxKey; NodeHandler(const K& _minKey, const K& _maxKey) { minKey = _minKey; maxKey = _maxKey; } class ChildIterator { private: size_t ix; NodePtrType node; // node being iterated over public: ChildIterator(NodePtrType _node) { node = _node; ix = 0; } bool hasNext() { return ix < CASWORD_TO_NODE(node)->degree; } NodePtrType next() { return CASWORD_TO_NODE(node)->ptr(ix++); } }; static bool isLeaf(NodePtrType node) { return IS_KVPAIR(node) || IS_VAL(node); } static ChildIterator getChildIterator(NodePtrType node) { return ChildIterator(node); } static size_t getNumChildren(NodePtrType node) { return isLeaf(node) ? 0 : CASWORD_TO_NODE(node)->degree; } static size_t getNumKeys(NodePtrType node) { if (IS_KVPAIR(node)) return 1; if (IS_VAL(node)) return 0; assert(IS_NODE(node)); auto n = CASWORD_TO_NODE(node); assert(IS_EMPTY_VAL(n->ptr(0)) || !IS_VAL(n->ptr(0))); size_t ret = 0; for (int i=1; i < n->degree; ++i) { if (!IS_EMPTY_VAL(n->ptr(i)) && IS_VAL(n->ptr(i))) ++ret; } return ret; } static size_t getSumOfKeys(NodePtrType node) { if (IS_KVPAIR(node)) return (size_t) CASWORD_TO_KVPAIR(node)->k; if (IS_VAL(node)) return 0; assert(IS_NODE(node)); auto n = CASWORD_TO_NODE(node); assert(IS_EMPTY_VAL(n->ptr(0)) || !IS_VAL(n->ptr(0))); size_t ret = 0; for (int i=1; i < n->degree; ++i) { if (!IS_EMPTY_VAL(n->ptr(i)) && IS_VAL(n->ptr(i))) ret += (size_t) n->key(i-1); } return ret; } static size_t getSizeInBytes(NodePtrType node) { if (IS_KVPAIR(node)) return sizeof(*CASWORD_TO_KVPAIR(node)); if (IS_VAL(node)) return 0; if (IS_NODE(node) && node != NODE_TO_CASWORD(NULL)) { auto child = CASWORD_TO_NODE(node); auto degree = child->degree; return sizeof(*child) + sizeof(K) * (degree - 1) + sizeof(casword_t) * degree; } return 0; } }; TreeStats<NodeHandler> * createTreeStats(const K& _minKey, const K& _maxKey) { return new TreeStats<NodeHandler>(new NodeHandler(_minKey, _maxKey), NODE_TO_CASWORD(ds->debug_getEntryPoint()), true); } #endif private: template<typename... Arguments> void iterate_helper_fn(int depth, void (*callback)(K key, V value, Arguments... args) , casword_t ptr, Arguments... args) { if (IS_VAL(ptr)) return; if (IS_KVPAIR(ptr)) { auto kvp = CASWORD_TO_KVPAIR(ptr); callback(kvp->k, kvp->v, args...); return; } assert(IS_NODE(ptr)); auto curr = CASWORD_TO_NODE(ptr); if (curr == NULL) return; for (int i=0;i<curr->degree;++i) { if (depth == 1) { // in interpolation search tree, root is massive... (root is really the child of the root pointer) //printf("got here %d\n", i); #pragma omp task iterate_helper_fn(1+depth, callback, curr->ptr(i), args...); } else { iterate_helper_fn(1+depth, callback, curr->ptr(i), args...); } if (i >= 1 && !IS_EMPTY_VAL(curr->ptr(i)) && IS_VAL(curr->ptr(i))) { // first val-slot cannot be non-empty value callback(curr->key(i-1), CASWORD_TO_VAL(curr->ptr(i)), args...); } } } public: template<typename... Arguments> void iterate(void (*callback)(K key, V value, Arguments... args), Arguments... args) { #pragma omp parallel { #pragma omp single iterate_helper_fn(0, callback, NODE_TO_CASWORD(ds->debug_getEntryPoint()), args...); } } }; #endif
nmt_mask.c
#include "config.h" #include "utils.h" static void apodize_mask_CX(long nside,flouble *mask_in,flouble *mask_out,flouble aposize,char *apotype) { long npix=he_nside2npix(nside); double aporad=aposize*M_PI/180; double x2_thr=1-cos(aporad); double inv_x2_thr=1./x2_thr; flouble *vec=my_malloc(3*npix*sizeof(flouble)); flouble *cthv=my_malloc(npix*sizeof(flouble)); flouble *phiv=my_malloc(npix*sizeof(flouble)); int apotyp=0; if(!strcmp(apotype,"C1")) apotyp=0; else if(!strcmp(apotype,"C2")) apotyp=1; else report_error(NMT_ERROR_APO,"Unknown apodization type %s\n",apotype); if(mask_out!=mask_in) memcpy(mask_out,mask_in,npix*sizeof(flouble)); //Get coords for each pixel #pragma omp parallel default(none) \ shared(vec,npix,nside,cthv,phiv) { long ip; #pragma omp for for(ip=0;ip<npix;ip++) { flouble *v=vec+3*ip; he_pix2vec_ring(nside,ip,v); cthv[ip]=v[2]; phiv[ip]=atan2(v[1],v[0]); if(phiv[ip]<0) phiv[ip]+=2*M_PI; } //end omp for }//end omp parallel int lenlist0=(int)(4*npix*(1-cos(1.2*aporad))); if(lenlist0 < 2) report_error(NMT_ERROR_APO,"Your apodization scale is too small for this pixel size\n"); #pragma omp parallel default(none) \ shared(vec,npix,x2_thr,inv_x2_thr,mask_in,mask_out) \ shared(nside,cthv,phiv,aporad,apotyp,lenlist0) { long ip; int *listpix=my_malloc(lenlist0*sizeof(int)); #pragma omp for schedule(dynamic) for(ip=0;ip<npix;ip++) { if(mask_in[ip]>0) { int j; int lenlist_half=lenlist0/2; flouble *v0=vec+3*ip; flouble x2dist=1000; he_query_disc(nside,cthv[ip],phiv[ip],1.2*aporad,listpix,&lenlist_half,1); for(j=0;j<lenlist_half;j++) { int ip2=listpix[j]; if(mask_in[ip2]<=0) { flouble *v1=vec+3*ip2; flouble x2=1-v0[0]*v1[0]-v0[1]*v1[1]-v0[2]*v1[2]; if(x2<x2dist) x2dist=x2; } } if(x2dist<x2_thr) { flouble f,xn; if(x2dist<=0) f=0; else { xn=sqrt(x2dist*inv_x2_thr); if(apotyp==0) f=xn-sin(xn*2*M_PI)/(2*M_PI); else f=0.5*(1-cos(xn*M_PI)); } mask_out[ip]*=f; } } } //end omp for free(listpix); }//end omp parallel free(vec); free(cthv); free(phiv); } static void apodize_mask_smooth(long nside,flouble *mask_in,flouble *mask_out,flouble aposize) { long npix=he_nside2npix(nside); nmt_curvedsky_info *cs=nmt_curvedsky_info_alloc(1,nside,-1,-1,-1,-1,-1,-1,-1); double aporad=aposize*M_PI/180; flouble *mask_dum=my_malloc(npix*sizeof(flouble)); fcomplex *alms_dum=my_malloc(he_nalms(3*nside-1)*sizeof(fcomplex)); memcpy(mask_dum,mask_in,npix*sizeof(flouble)); int lenlist0=(int)(4*npix*(1-cos(2.5*aporad))); if(lenlist0 < 2) report_error(NMT_ERROR_APO,"Your apodization scale is too small for this pixel size\n"); #pragma omp parallel default(none) \ shared(npix,mask_in,mask_dum,nside,aporad,lenlist0) { long ip; int *listpix=my_malloc(lenlist0*sizeof(int)); #pragma omp for schedule(dynamic) for(ip=0;ip<npix;ip++) { if(mask_in[ip]<=0) { int j; flouble v[3],cthv,phiv; int lenlist_half=lenlist0/2; he_pix2vec_ring(nside,ip,v); cthv=v[2]; phiv=atan2(v[1],v[0]); if(phiv<0) phiv+=2*M_PI; he_query_disc(nside,cthv,phiv,2.5*aporad,listpix,&lenlist_half,1); for(j=0;j<lenlist_half;j++) { int ip2=listpix[j]; #pragma omp atomic mask_dum[ip2]*=0; } } } //end omp for free(listpix); }//end omp parallel he_map2alm(cs,3*nside-1,1,0,&mask_dum,&alms_dum,3); he_alter_alm(3*nside-1,aporad*180*60*2.355/M_PI,alms_dum,alms_dum,NULL,0); he_alm2map(cs,3*nside-1,1,0,&mask_dum,&alms_dum); he_map_product(cs,mask_in,mask_dum,mask_out); free(mask_dum); free(alms_dum); free(cs); } void nmt_apodize_mask(long nside,flouble *mask_in,flouble *mask_out,flouble aposize,char *apotype) { if(aposize<0) report_error(NMT_ERROR_APO,"Apodization scale must be a positive number\n"); else if(aposize==0) memcpy(mask_out,mask_in,he_nside2npix(nside)*sizeof(flouble)); else { if((!strcmp(apotype,"C1")) || (!strcmp(apotype,"C2"))) { apodize_mask_CX(nside,mask_in,mask_out,aposize,apotype); } else if(!strcmp(apotype,"Smooth")) apodize_mask_smooth(nside,mask_in,mask_out,aposize); else report_error(NMT_ERROR_APO,"Unknown apodization type %s. Allowed: \"Smooth\", \"C1\", \"C2\"\n",apotype); } }
DifferentiableLutN.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 <cstdint> #include <random> #include "bb/StochasticLutModel.h" #include "bb/Tensor.h" #include "bb/FixedSizeConnectionTable.h" #include "bb/StochasticOperation.h" namespace bb { class DifferentiableLutModel : public StochasticLutModel { public: virtual Tensor GetMean(void) const = 0; virtual Tensor GetVar(void) const = 0; virtual double GetGamma(void) const = 0; virtual double GetBeta(void) const = 0; }; template <int N = 6, typename BinType = Bit, typename RealType = float> class DifferentiableLutN : public DifferentiableLutModel { using _super = StochasticLutModel; static int const NN = (1 << N); public: static inline std::string ModelName(void) { return "DifferentiableLut" + std::to_string(N); } static inline std::string ObjectName(void){ return ModelName() + "_" + DataType<BinType>::Name() + "_" + DataType<RealType>::Name(); } std::string GetModelName(void) const { return ModelName(); } std::string GetObjectName(void) const { return ObjectName(); } protected: bool m_host_only = false; bool m_lut_binarize = false; bool m_binary_mode = true; bool m_batch_norm = true; bool m_backward_break = false; bool m_flagClamp = false; indices_t m_input_shape; indices_t m_output_shape; FixedSizeConnectionTable<N> m_connection_table; RealType m_unbinarize_bias = (RealType)0.25; index_t m_max_tmp_mem_size = 256 * 1024 * 1024; std::string m_connection; std::shared_ptr<Tensor> m_W; std::shared_ptr<Tensor> m_dW; RealType m_momentum; RealType m_gamma; RealType m_beta; Tensor_<RealType> m_mean; // 平均値 Tensor_<RealType> m_rstd; // 標準偏差の逆数 Tensor_<RealType> m_running_mean; Tensor_<RealType> m_running_var; std::mt19937_64 m_mt; public: struct create_t { indices_t output_shape; //< 出力形状 bool batch_norm = true; bool binary = true; std::string connection; //< 結線ルール RealType momentum = (RealType)0.9; RealType gamma = (RealType)0.3; RealType beta = (RealType)0.5; std::uint64_t seed = 1; //< 乱数シード }; protected: DifferentiableLutN(create_t const &create) { // BB_ASSERT(!create.output_shape.empty()); m_output_shape = create.output_shape; m_connection = create.connection; m_batch_norm = create.batch_norm; m_binary_mode = create.binary; m_momentum = create.momentum; m_gamma = create.gamma; m_beta = create.beta; m_mt.seed(create.seed); m_W = std::make_shared<Tensor>(); m_dW = std::make_shared<Tensor>(); if ( DataType<BinType>::type == BB_TYPE_BIT ) { m_binary_mode = true; } } void CommandProc(std::vector<std::string> args) { _super::CommandProc(args); // バイナリモード設定 if ( DataType<BinType>::type != BB_TYPE_BIT ) { if ( args.size() == 2 && args[0] == "binary" ) { m_binary_mode = EvalBool(args[1]); } } // LUTバイナライズ設定 if ( args.size() == 2 && args[0] == "lut_binarize" ) { m_lut_binarize = EvalBool(args[1]); } // HostOnlyモード設定 if (args.size() == 2 && args[0] == "host_only") { m_host_only = EvalBool(args[1]); } // batch_norm設定 if (args.size() == 2 && args[0] == "batch_norm") { m_batch_norm = EvalBool(args[1]); } // momentum設定 if (args.size() == 2 && args[0] == "momentum") { m_momentum = (RealType)EvalReal(args[1]); } // backward_break if (args.size() == 2 && args[0] == "backward_break") { m_backward_break = EvalBool(args[1]); } } void PrintInfoText(std::ostream& os, std::string indent, int columns, int nest, int depth) const override { _super::PrintInfoText(os, indent, columns, nest, depth); // os << indent << " input shape : " << GetInputShape(); // os << indent << " output shape : " << GetOutputShape(); os << indent << " binary : " << m_binary_mode; os << indent << " batch_norm : " << m_batch_norm << std::endl; } public: ~DifferentiableLutN() {} static std::shared_ptr<DifferentiableLutN> Create(create_t const &create) { return std::shared_ptr<DifferentiableLutN>(new DifferentiableLutN(create)); } static std::shared_ptr<DifferentiableLutN> Create(indices_t const &output_shape, bool batch_norm = true, std::string connection = "") //, std::uint64_t seed = 1) { create_t create; create.output_shape = output_shape; create.connection = connection; create.batch_norm = batch_norm; create.seed = 1; //seed; return Create(create); } static std::shared_ptr<DifferentiableLutN> Create(index_t output_node_size, bool batch_norm = true, std::string connection = "") //, std::uint64_t seed = 1) { create_t create; create.output_shape.resize(1); create.output_shape[0] = output_node_size; create.connection = connection; create.batch_norm = batch_norm; create.seed = 1; // seed; return Create(create); } static std::shared_ptr<DifferentiableLutN> Create(void) { return Create(create_t()); } #ifdef BB_PYBIND11 static std::shared_ptr<DifferentiableLutN> CreatePy( indices_t const &output_shape, bool batch_norm = true, bool binary = true, std::string connection = "", double momentum = 0.0, double gamma = 0.3, double beta = 0.5, std::uint64_t seed = 1) { create_t create; create.output_shape = output_shape; create.batch_norm = batch_norm; create.binary = binary; create.connection = connection; create.momentum = (RealType)momentum; create.gamma = (RealType)gamma; create.beta = (RealType)beta; create.seed = seed; return Create(create); } #endif protected: // Serialize void DumpObjectData(std::ostream &os) const { // バージョン std::int64_t ver = 1; bb::SaveValue(os, ver); // 親クラス _super::DumpObjectData(os); // メンバ SaveValue(os, m_host_only); SaveValue(os, m_lut_binarize); SaveValue(os, m_binary_mode); SaveValue(os, m_batch_norm); SaveValue(os, m_flagClamp); SaveValue(os, m_input_shape); SaveValue(os, m_output_shape); m_connection_table.DumpObject(os); m_W->DumpObject(os); SaveValue(os, m_unbinarize_bias); SaveValue(os, m_momentum); SaveValue(os, m_gamma); SaveValue(os, m_beta); m_running_mean.DumpObject(os); m_running_var.DumpObject(os); } void LoadObjectData(std::istream &is) { // バージョン std::int64_t ver; bb::LoadValue(is, ver); BB_ASSERT(ver == 1); // 親クラス _super::LoadObjectData(is); // メンバ LoadValue(is, m_host_only); LoadValue(is, m_lut_binarize); LoadValue(is, m_binary_mode); LoadValue(is, m_batch_norm); LoadValue(is, m_flagClamp); LoadValue(is, m_input_shape); LoadValue(is, m_output_shape); m_connection_table.LoadObject(is); m_W->LoadObject(is); LoadValue(is, m_unbinarize_bias); LoadValue(is, m_momentum); LoadValue(is, m_gamma); LoadValue(is, m_beta); m_running_mean.LoadObject(is); m_running_var.LoadObject(is); // 再構築 m_dW->Resize(m_W->GetShape(), DataType<RealType>::type); m_dW->FillZero(); m_mean.Resize(m_output_shape); m_rstd.Resize(m_output_shape); } public: // Serialize(旧) void Save(std::ostream &os) const { _super::Save(os); SaveIndices(os, m_input_shape); SaveIndices(os, m_output_shape); m_connection_table.Save(os); m_W->Save(os); bb::SaveValue(os, m_momentum); bb::SaveValue(os, m_gamma); bb::SaveValue(os, m_beta); m_running_mean.Save(os); m_running_var.Save(os); } void Load(std::istream &is) { _super::Load(is); m_input_shape = LoadIndices(is); m_output_shape = LoadIndices(is); m_connection_table.Load(is); m_W->Load(is); bb::LoadValue(is, m_momentum); bb::LoadValue(is, m_gamma); bb::LoadValue(is, m_beta); m_running_mean.Load(is); m_running_var.Load(is); } #ifdef BB_WITH_CEREAL template <class Archive> void save(Archive& archive, std::uint32_t const version) const { _super::save(archive, version); archive(cereal::make_nvp("input_shape", m_input_shape)); archive(cereal::make_nvp("output_shape", m_output_shape)); archive(cereal::make_nvp("connection_table", m_connection_table)); archive(cereal::make_nvp("W", *m_W)); archive(cereal::make_nvp("gamma", m_gamma)); archive(cereal::make_nvp("beta", m_beta)); archive(cereal::make_nvp("running_mean", m_running_mean)); archive(cereal::make_nvp("running_var", m_running_var)); } template <class Archive> void load(Archive& archive, std::uint32_t const version) { _super::load(archive, version); archive(cereal::make_nvp("input_shape", m_input_shape)); archive(cereal::make_nvp("output_shape", m_output_shape)); archive(cereal::make_nvp("connection_table", m_connection_table)); archive(cereal::make_nvp("W", *m_W)); archive(cereal::make_nvp("gamma", m_gamma)); archive(cereal::make_nvp("beta", m_beta)); archive(cereal::make_nvp("running_mean", m_running_mean)); archive(cereal::make_nvp("running_var", m_running_var)); } void Save(cereal::JSONOutputArchive& archive) const { archive(cereal::make_nvp("DifferentiableLutN", *this)); } void Load(cereal::JSONInputArchive& archive) { archive(cereal::make_nvp("DifferentiableLutN", *this)); } #endif Tensor &W(void) override { return *m_W; } Tensor const &W(void) const override { return *m_W; } Tensor &dW(void) override { return *m_dW; } Tensor const &dW(void) const override { return *m_dW; } Tensor GetMean(void) const override { return (Tensor)m_running_mean; } Tensor GetVar(void) const override { return (Tensor)m_running_var; } double GetGamma(void) const override { return (double)m_gamma; } double GetBeta(void) const override { return (double)m_beta; } auto lock_W(void) { return m_W->Lock<RealType>(); } auto lock_W_const(void) const { return m_W->LockConst<RealType>(); } auto lock_dW(void) { return m_dW->Lock<RealType>(); } auto lock_dW_const(void) const { return m_dW->LockConst<RealType>(); } auto lock_mean(void) { return m_running_mean.Lock(); } auto lock_mean_const(void) const { return m_running_mean.LockConst(); } auto lock_var(void) { return m_running_var.Lock(); } auto lock_var_const(void) const { return m_running_var.LockConst(); } // debug auto lock_tmp_mean_const(void) const { return m_mean.LockConst(); } auto lock_tmp_rstd_const(void) const { return m_rstd.LockConst(); } /** * @brief 出力形状取得 * @detail 出力形状を取得する * @return 出力形状を返す */ indices_t GetOutputShape(void) const { return m_output_shape; } /** * @brief 入力形状取得 * @detail 入力形状を取得する * @return 入力形状を返す */ indices_t GetInputShape(void) const { return m_input_shape; } // connection management index_t GetNodeConnectionSize(index_t output_node) const { return m_connection_table.GetInputConnectionSize(output_node); } void SetNodeConnectionIndex(index_t output_node, index_t input_index, index_t input_node) { m_connection_table.SetInputConnection(output_node, input_index, input_node); } index_t GetNodeConnectionIndex(index_t output_node, index_t input_index) const { return m_connection_table.GetInputConnection(output_node, input_index); } /** * @brief 入力のshape設定 * @detail 入力のshape設定 * @param shape 新しいshape * @return なし */ indices_t SetInputShape(indices_t shape) { // 設定済みなら何もしない if ( shape == this->GetInputShape() ) { return this->GetOutputShape(); } // 形状設定 m_input_shape = shape; // 接続初期化 m_connection_table.SetShape(m_input_shape, m_output_shape); m_connection_table.InitializeConnection(m_mt(), m_connection); // パラメータ初期化(結局初期値は何が良いのかまだよくわからない) m_W->Resize ({this->GetOutputNodeSize(), NN}, DataType<RealType>::type); m_W->InitNormalDistribution(0.5, 0.01, m_mt()); m_dW->Resize({this->GetOutputNodeSize(), NN}, DataType<RealType>::type); m_dW->FillZero(); m_mean.Resize(m_output_shape); m_rstd.Resize(m_output_shape); m_running_mean.Resize(m_output_shape); m_running_mean = (RealType)0.0; m_running_var.Resize(m_output_shape); m_running_var = (RealType)1.0; return m_output_shape; } Variables GetParameters(void) { Variables parameters; if ( !this->m_parameter_lock ) { parameters.PushBack(m_W); } return parameters; } Variables GetGradients(void) { Variables gradients; if ( !this->m_parameter_lock ) { gradients.PushBack(m_dW); } return gradients; } // ノード単位でのForward計算 std::vector<double> ForwardNode(index_t node, std::vector<double> input_value) const { BB_ASSERT(input_value.size() == N); // パラメータクリップ if ( m_flagClamp ) { m_W->Clamp_inplace((RealType)0.0, (RealType)1.0); (const_cast<DifferentiableLutN*>(this))->m_flagClamp = false; } auto W_ptr = lock_W_const(); auto running_mean_ptr = m_running_mean.LockConst(); auto running_var_ptr = m_running_var.LockConst(); RealType W[(1 << N)]; for ( int i = 0; i < (1 << N); ++i) { W[i] = W_ptr(node, i); if ( m_lut_binarize ) { W[i] = ((W[i] > (RealType)0.5) ? (RealType)1.0 : (RealType)0.0); } } RealType mean = running_mean_ptr[node]; RealType var = running_var_ptr[node]; RealType rstd = (RealType)1.0 / std::sqrt(var); RealType x[N]; for ( int i = 0; i < N; ++i) { x[i] = (RealType)input_value[i]; if ( m_binary_mode ) { x[i] = (RealType)0.5 + ((x[i] > (RealType)0.5) ? +m_unbinarize_bias : -m_unbinarize_bias); } else { x[i] = std::min((RealType)1.0, std::max((RealType)0.0, x[i])); } } RealType y; StochasticOperation_Lut_Forward<RealType>(x, &y, W, N); if ( m_batch_norm ) { y = (y - mean) * rstd; y = y * m_gamma + m_beta; } if ( m_binary_mode ) { // binarize y = ((y > (RealType)0.5) ? (RealType)1.0 : (RealType)0.0); } else { // hard-tanh y = std::min(y, (RealType)1.0); y = std::max(y, (RealType)0.0); } std::vector<double> result; result.push_back((double)y); return result; } FrameBuffer Forward(FrameBuffer x_buf, bool train = true) { // SetInputShpaeされていなければ初回に設定 if (x_buf.GetShape() != this->GetInputShape()) { SetInputShape(x_buf.GetShape()); } // 出力を設定 FrameBuffer y_buf(x_buf.GetFrameSize(), this->GetOutputShape(), DataType<BinType>::type); // backwardの為に保存 if ( train ) { this->PushFrameBuffer(x_buf); } // パラメータクリップ if ( m_flagClamp ) { m_W->Clamp_inplace((RealType)0.0, (RealType)1.0); m_flagClamp = false; } if ( x_buf.GetType() != DataType<BinType>::type && x_buf.GetType() == BB_TYPE_BIT ) { x_buf = x_buf.ConvertTo(DataType<BinType>::type); x_buf.Clamp_inplace((BinType)0.0, (BinType)1.0); } BB_ASSERT(x_buf.GetType() == DataType<BinType>::type); if ( m_batch_norm ) { // with BatchNormalization #ifdef BB_WITH_CUDA // CUDA float if ( N >= 2 && N <= 6 && DataType<BinType>::type == BB_TYPE_FP32 && DataType<RealType>::type == BB_TYPE_FP32 && !m_host_only && x_buf.IsDeviceAvailable() && y_buf.IsDeviceAvailable() && Manager::IsDeviceAvailable()) { if ( train ) { auto x_ptr = x_buf.LockDeviceMemoryConst(); auto y_ptr = y_buf.LockDeviceMemory(true); auto input_table_ptr = m_connection_table.LockDeviceMemConst_InputTable(); auto W_ptr = m_W->LockDeviceMemoryConst(); auto mean_ptr = m_mean.LockDeviceMemory(true); auto rstd_ptr = m_rstd.LockDeviceMemory(true); auto running_mean_ptr = m_running_mean.LockDeviceMemory(); auto running_var_ptr = m_running_var.LockDeviceMemory(); bbcu_fp32_DifferentiableLutN_ForwardTraining<N> ( (float const *)x_ptr.GetAddr(), (float *)y_ptr.GetAddr(), (int const *)input_table_ptr.GetAddr(), (float const *)W_ptr.GetAddr(), (float *)mean_ptr.GetAddr(), (float *)rstd_ptr.GetAddr(), (float *)running_mean_ptr.GetAddr(), (float *)running_var_ptr.GetAddr(), (float )m_gamma, (float )m_beta, (float )m_momentum, (float )m_unbinarize_bias, (int )y_buf.GetNodeSize(), (int )y_buf.GetFrameSize(), (int )(y_buf.GetFrameStride() / sizeof(float)), (int )(m_lut_binarize ? 1 : 0), (int )(m_binary_mode ? 1 : 0) ); } else { auto x_ptr = x_buf.LockDeviceMemoryConst(); auto y_ptr = y_buf.LockDeviceMemory(true); auto input_table_ptr = m_connection_table.LockConst_InputTable(); auto W_ptr = m_W->LockDeviceMemoryConst(); auto running_mean_ptr = m_running_mean.LockDeviceMemory(); auto running_var_ptr = m_running_var.LockDeviceMemory(); bbcu_fp32_DifferentiableLutN_ForwardInference<N> ( (float const *)x_ptr.GetAddr(), (float *)y_ptr.GetAddr(), (int const *)input_table_ptr.GetAddr(), (float const *)W_ptr.GetAddr(), (float *)running_mean_ptr.GetAddr(), (float *)running_var_ptr.GetAddr(), (float )m_gamma, (float )m_beta, (float )m_unbinarize_bias, (int )y_buf.GetNodeSize(), (int )y_buf.GetFrameSize(), (int )(y_buf.GetFrameStride() / sizeof(float)), (int )(m_lut_binarize ? 1 : 0), (int )(m_binary_mode ? 1 : 0) ); } return y_buf; } // CUDA Bit if ( N >= 2 && N <= 6 && DataType<BinType>::type == BB_TYPE_BIT && DataType<RealType>::type == BB_TYPE_FP32 && !m_host_only && x_buf.IsDeviceAvailable() && y_buf.IsDeviceAvailable() && Manager::IsDeviceAvailable()) { if ( train ) { auto x_ptr = x_buf.LockDeviceMemoryConst(); auto y_ptr = y_buf.LockDeviceMemory(true); auto input_table_ptr = m_connection_table.LockDeviceMemConst_InputTable(); auto W_ptr = m_W->LockDeviceMemoryConst(); auto mean_ptr = m_mean.LockDeviceMemory(true); auto rstd_ptr = m_rstd.LockDeviceMemory(true); auto running_mean_ptr = m_running_mean.LockDeviceMemory(); auto running_var_ptr = m_running_var.LockDeviceMemory(); bbcu_bit_fp32_DifferentiableLutN_ForwardTraining<N> ( (int const *)x_ptr.GetAddr(), (int *)y_ptr.GetAddr(), (int const *)input_table_ptr.GetAddr(), (float const *)W_ptr.GetAddr(), (float *)mean_ptr.GetAddr(), (float *)rstd_ptr.GetAddr(), (float *)running_mean_ptr.GetAddr(), (float *)running_var_ptr.GetAddr(), (float )m_gamma, (float )m_beta, (float )m_momentum, (float )m_unbinarize_bias, (int )y_buf.GetNodeSize(), (int )y_buf.GetFrameSize(), (int )(y_buf.GetFrameStride() / sizeof(int)), (int )(m_lut_binarize ? 1 : 0) ); } else { auto x_ptr = x_buf.LockDeviceMemoryConst(); auto y_ptr = y_buf.LockDeviceMemory(true); auto input_table_ptr = m_connection_table.LockDeviceMemConst_InputTable(); auto W_ptr = m_W->LockDeviceMemoryConst(); auto running_mean_ptr = m_running_mean.LockDeviceMemoryConst(); auto running_var_ptr = m_running_var.LockDeviceMemoryConst(); bbcu_bit_fp32_DifferentiableLutN_ForwardInference<N> ( (int const *)x_ptr.GetAddr(), (int *)y_ptr.GetAddr(), (int const *)input_table_ptr.GetAddr(), (float const *)W_ptr.GetAddr(), (float const *)running_mean_ptr.GetAddr(), (float const *)running_var_ptr.GetAddr(), (float )m_gamma, (float )m_beta, (float )m_unbinarize_bias, (int )y_buf.GetNodeSize(), (int )y_buf.GetFrameSize(), (int )(y_buf.GetFrameStride() / sizeof(int)), (int )(m_lut_binarize ? 1 : 0) ); } return y_buf; } #endif { // Generic auto node_size = y_buf.GetNodeSize(); auto frame_size = y_buf.GetFrameSize(); RealType reciprocal_frame_size = (RealType)1.0 / frame_size; if ( train ) { auto x_ptr = x_buf.LockConst<BinType>(); auto y_ptr = y_buf.Lock<BinType>(); auto input_table_ptr = m_connection_table.LockConst_InputTable(); auto W_ptr = lock_W_const(); auto mean_ptr = m_mean.Lock(true); auto rstd_ptr = m_rstd.Lock(true); auto running_mean_ptr = m_running_mean.Lock(); auto running_var_ptr = m_running_var.Lock(); #pragma omp parallel for for ( index_t node = 0; node < node_size; ++node ) { RealType W[(1 << N)]; for ( int i = 0; i < (1 << N); ++i) { W[i] = W_ptr(node, i); if ( m_lut_binarize ) { W[i] = ((W[i] > (RealType)0.5) ? (RealType)1.0 : (RealType)0.0); } } // 平均と分散計測 RealType s1 = 0, c1 = 0, y1, t1; RealType s2 = 0, c2 = 0, y2, t2; for ( index_t frame = 0; frame < frame_size; ++frame ) { RealType x[N]; for ( int i = 0; i < N; ++i) { x[i] = (RealType)x_ptr.Get(frame, input_table_ptr(node, i)); if ( m_binary_mode ) { x[i] = (RealType)0.5 + ((x[i] > (RealType)0.5) ? +m_unbinarize_bias : -m_unbinarize_bias); } else { x[i] = std::min((RealType)1.0, std::max((RealType)0.0, x[i])); } } RealType y; StochasticOperation_Lut_Forward<RealType>(x, &y, W, N); // 集計 y1 = y - c1; t1 = s1 + y1; c1 = (t1 - s1) - y1; s1 = t1; y2 = (y * y) - c2; t2 = s2 + y2; c2 = (t2 - s2) - y2; s2 = t2; } RealType mean = s1 * reciprocal_frame_size; RealType var = std::max(1.0e-5f, (s2 * reciprocal_frame_size) - (mean * mean)); RealType rstd = (RealType)1.0 / std::sqrt(var); // 書き込み running_mean_ptr[node] = running_mean_ptr[node] * m_momentum + mean * ((RealType)1.0 - m_momentum); running_var_ptr[node] = running_var_ptr[node] * m_momentum + var * ((RealType)1.0 - m_momentum); mean_ptr[node] = mean; rstd_ptr[node] = rstd; // 正規化 for ( index_t frame = 0; frame < frame_size; ++frame ) { // Forward計算 RealType x[N]; for ( int i = 0; i < N; ++i) { x[i] = (RealType)x_ptr.Get(frame, input_table_ptr(node, i)); if ( m_binary_mode ) { x[i] = (RealType)0.5 + ((x[i] > (RealType)0.5) ? +m_unbinarize_bias : -m_unbinarize_bias); } else { x[i] = std::min((RealType)1.0, std::max((RealType)0.0, x[i])); } } RealType y; StochasticOperation_Lut_Forward<RealType>(x, &y, W, N); y = (y - mean) * rstd; y = y * m_gamma + m_beta; if ( m_binary_mode ) { // binarize y = ((y > (RealType)0.5) ? (RealType)1.0 : (RealType)0.0); } else { // hard-tanh y = std::min(y, (RealType)1.0); y = std::max(y, (RealType)0.0); } y_ptr.Set(frame, node, y); } } } else { auto x_ptr = x_buf.LockConst<BinType>(); auto y_ptr = y_buf.Lock<BinType>(); auto input_table_ptr = m_connection_table.LockConst_InputTable(); auto W_ptr = lock_W_const(); auto running_mean_ptr = m_running_mean.LockConst(); auto running_var_ptr = m_running_var.LockConst(); #pragma omp parallel for for ( index_t node = 0; node < node_size; ++node ) { RealType W[(1 << N)]; for ( int i = 0; i < (1 << N); ++i) { W[i] = W_ptr(node, i); if ( m_lut_binarize ) { W[i] = ((W[i] > (RealType)0.5) ? (RealType)1.0 : (RealType)0.0); } } RealType mean = running_mean_ptr[node]; RealType var = running_var_ptr[node]; RealType rstd = (RealType)1.0 / std::sqrt(var); // Forward計算 for ( index_t frame = 0; frame < frame_size; ++frame ) { RealType x[N]; for ( int i = 0; i < N; ++i) { x[i] = (RealType)x_ptr.Get(frame, input_table_ptr(node, i)); if ( m_binary_mode ) { x[i] = (RealType)0.5 + ((x[i] > (RealType)0.5) ? +m_unbinarize_bias : -m_unbinarize_bias); } else { x[i] = std::min((RealType)1.0, std::max((RealType)0.0, x[i])); } } RealType y; StochasticOperation_Lut_Forward<RealType>(x, &y, W, N); y = (y - mean) * rstd; y = y * m_gamma + m_beta; if ( m_binary_mode ) { // binarize y = ((y > (RealType)0.5) ? (RealType)1.0 : (RealType)0.0); } else { // hard-tanh y = std::min(y, (RealType)1.0); y = std::max(y, (RealType)0.0); } y_ptr.Set(frame, node, y); } } } return y_buf; } } else { // None BatchNormalization #ifdef BB_WITH_CUDA // CUDA float if ( N >= 2 && N <= 6 && DataType<BinType>::type == BB_TYPE_FP32 && DataType<RealType>::type == BB_TYPE_FP32 && !m_host_only && x_buf.IsDeviceAvailable() && y_buf.IsDeviceAvailable() && Manager::IsDeviceAvailable()) { auto x_ptr = x_buf.LockDeviceMemoryConst(); auto y_ptr = y_buf.LockDeviceMemory(true); auto input_table_ptr = m_connection_table.LockDeviceMemConst_InputTable(); auto W_ptr = m_W->LockDeviceMemoryConst(); bbcu_fp32_StochasticLut_Forward<N>( (float const *)x_ptr.GetAddr(), (float *)y_ptr.GetAddr(), (int const *)input_table_ptr.GetAddr(), (float const *)W_ptr.GetAddr(), (int )y_buf.GetNodeSize(), (int )y_buf.GetFrameSize(), (int )(y_buf.GetFrameStride() / sizeof(float)), (int )(m_binary_mode ? 1 : 0), (int )(m_lut_binarize ? 1 : 0), (float )m_unbinarize_bias ); return y_buf; } // CUDA Bit->bit if ( N >= 2 && N <= 6 && DataType<BinType>::type == BB_TYPE_BIT && DataType<RealType>::type == BB_TYPE_FP32 && !m_host_only && x_buf.IsDeviceAvailable() && y_buf.IsDeviceAvailable() && Manager::IsDeviceAvailable()) { auto x_ptr = x_buf.LockDeviceMemoryConst(); auto y_ptr = y_buf.LockDeviceMemory(true); auto input_table_ptr = m_connection_table.LockDeviceMemConst_InputTable(); auto W_ptr = m_W->LockDeviceMemoryConst(); bbcu_bit_bit_fp32_StochasticLut_Forward<N>( (int const *)x_ptr.GetAddr(), (int *)y_ptr.GetAddr(), (int const *)input_table_ptr.GetAddr(), (float const *)W_ptr.GetAddr(), (int )y_buf.GetNodeSize(), (int )y_buf.GetFrameSize(), (int )(y_buf.GetFrameStride() / sizeof(int)), (int )(m_lut_binarize ? 1 : 0), (float )m_unbinarize_bias ); return y_buf; } #endif { // generic auto node_size = y_buf.GetNodeSize(); auto frame_size = y_buf.GetFrameSize(); auto x_ptr = x_buf.LockConst<BinType>(); auto y_ptr = y_buf.Lock<BinType>(); auto input_table_ptr = m_connection_table.LockConst_InputTable(); auto W_ptr = lock_W_const(); #pragma omp parallel for for ( index_t node = 0; node < node_size; ++node ) { RealType W[(1 << N)]; for ( int i = 0; i < (1 << N); ++i) { W[i] = W_ptr(node, i); if ( m_lut_binarize ) { W[i] = ((W[i] > (RealType)0.5) ? (RealType)1.0 : (RealType)0.0); } } // calc Forward for ( index_t frame = 0; frame < frame_size; ++frame ) { RealType x[N]; for ( int i = 0; i < N; ++i) { x[i] = (RealType)x_ptr.Get(frame, input_table_ptr(node, i)); if ( m_binary_mode ) { x[i] = (RealType)0.5 + ((x[i] > (RealType)0.5) ? +m_unbinarize_bias : -m_unbinarize_bias); } else { x[i] = std::min((RealType)1.0, std::max((RealType)0.0, x[i])); } } RealType y; StochasticOperation_Lut_Forward<RealType>(x, &y, W, N); if ( m_binary_mode ) { // binarize y = ((y > (RealType)0.5) ? (RealType)1.0 : (RealType)0.0); } else { // clip y = std::min(y, (RealType)1.0); y = std::max(y, (RealType)0.0); } y_ptr.Set(frame, node, y); } } return y_buf; } } } FrameBuffer Backward(FrameBuffer dy_buf) { if (m_backward_break || dy_buf.Empty()) { m_dW = 0; return FrameBuffer(); } BB_ASSERT(dy_buf.GetType() == DataType<RealType>::type); m_flagClamp = true; FrameBuffer x_buf = this->PopFrameBuffer(); if ( x_buf.GetType() != DataType<BinType>::type ) { x_buf = x_buf.ConvertTo(DataType<BinType>::type); x_buf.Clamp_inplace((BinType)0.0, (BinType)1.0); } BB_ASSERT(x_buf.GetType() == DataType<BinType>::type); FrameBuffer dx_buf(dy_buf.GetFrameSize(), this->GetInputShape(), DataType<RealType>::type); auto input_shape = this->GetInputShape(); auto output_shape = this->GetOutputShape(); auto output_node_size = this->GetOutputNodeSize(); // tmp buffer index_t tmp_frame_size = m_max_tmp_mem_size / (sizeof(float) * output_node_size*N); tmp_frame_size = std::max(tmp_frame_size, (index_t)32); tmp_frame_size = ((tmp_frame_size + 31) & ~0x1f); tmp_frame_size = std::min(tmp_frame_size, dy_buf.GetFrameSize()); FrameBuffer tmp_buf(tmp_frame_size, {output_node_size*N}, DataType<RealType>::type); if ( m_batch_norm ) { auto mean = m_mean; auto rstd = m_rstd; if ( this->m_parameter_lock ) { mean = m_running_mean + 0; rstd = (RealType)1.0 / (m_running_var + (RealType)1.0e-7).Sqrt(); } // with BatchNormalization #ifdef BB_WITH_CUDA // CUDA float if ( N >= 2 && N <= 6 && DataType<BinType>::type == BB_TYPE_FP32 && DataType<RealType>::type == BB_TYPE_FP32 && !m_host_only && x_buf.IsDeviceAvailable() && dy_buf.IsDeviceAvailable() && tmp_buf.IsDeviceAvailable() && dx_buf.IsDeviceAvailable() && Manager::IsDeviceAvailable()) { Tensor_<RealType> dmean(output_shape); Tensor_<RealType> dvar(output_shape); auto x_ptr = x_buf.LockDeviceMemoryConst(); auto dy_ptr = dy_buf.LockDeviceMemoryConst(); auto dx_ptr = dx_buf.LockDeviceMemory(true); auto tmp_ptr = tmp_buf.LockDeviceMemory(true); auto reverse_table_ptr = m_connection_table.LockDeviceMemConst_ReverseTable(); auto input_table_ptr = m_connection_table.LockDeviceMemConst_InputTable(); auto W_ptr = m_W->LockDeviceMemoryConst(); auto dW_ptr = m_dW->LockDeviceMemory(); auto mean_ptr = mean.LockDeviceMemoryConst(); auto rstd_ptr = rstd.LockDeviceMemoryConst(); auto dmean_ptr = dmean.LockDeviceMemory(true); auto dvar_ptr = dvar.LockDeviceMemory(true); bbcu_fp32_DifferentiableLutN_Backward<N> ( (float const *)x_ptr.GetAddr(), (float const *)dy_ptr.GetAddr(), (float *)dx_ptr.GetAddr(), (float *)tmp_ptr.GetAddr(), (int const *)input_table_ptr.GetAddr(), (int const *)reverse_table_ptr.GetAddr(), (float const *)W_ptr.GetAddr(), (float *)dW_ptr.GetAddr(), (float const *)mean_ptr.GetAddr(), (float const *)rstd_ptr.GetAddr(), (float *)dmean_ptr.GetAddr(), (float *)dvar_ptr.GetAddr(), (float )m_gamma, (float )m_beta, (float )m_unbinarize_bias, (int )m_connection_table.GetReverseTableStride(), (int )dx_buf.GetNodeSize(), (int )dy_buf.GetNodeSize(), (int )dy_buf.GetFrameSize(), (int )(dy_buf.GetFrameStride() / sizeof(float)), (int )tmp_buf.GetFrameSize(), (int )(tmp_buf.GetFrameStride() / sizeof(float)), (int )(m_lut_binarize ? 1 : 0), (int )(m_binary_mode ? 1 : 0) ); return dx_buf; } // CUDA bit if ( N >= 2 && N <= 6 && DataType<BinType>::type == BB_TYPE_BIT && DataType<RealType>::type == BB_TYPE_FP32 && !m_host_only && x_buf.IsDeviceAvailable() && dy_buf.IsDeviceAvailable() && tmp_buf.IsDeviceAvailable() && dx_buf.IsDeviceAvailable() && Manager::IsDeviceAvailable()) { Tensor_<RealType> dmean(output_shape); Tensor_<RealType> dvar(output_shape); auto x_ptr = x_buf.LockDeviceMemoryConst(); auto dy_ptr = dy_buf.LockDeviceMemoryConst(); auto dx_ptr = dx_buf.LockDeviceMemory(true); auto tmp_ptr = tmp_buf.LockDeviceMemory(true); auto reverse_table_ptr = m_connection_table.LockDeviceMemConst_ReverseTable(); auto input_table_ptr = m_connection_table.LockDeviceMemConst_InputTable(); auto W_ptr = m_W->LockDeviceMemoryConst(); auto dW_ptr = m_dW->LockDeviceMemory(); auto mean_ptr = m_mean.LockDeviceMemoryConst(); auto rstd_ptr = m_rstd.LockDeviceMemoryConst(); auto dmean_ptr = dmean.LockDeviceMemory(true); auto dvar_ptr = dvar.LockDeviceMemory(true); bbcu_bit_fp32_DifferentiableLutN_Backward<N> ( (int const *)x_ptr.GetAddr(), (float const *)dy_ptr.GetAddr(), (float *)dx_ptr.GetAddr(), (float *)tmp_ptr.GetAddr(), (int const *)input_table_ptr.GetAddr(), (int const *)reverse_table_ptr.GetAddr(), (float const *)W_ptr.GetAddr(), (float *)dW_ptr.GetAddr(), (float const *)mean_ptr.GetAddr(), (float const *)rstd_ptr.GetAddr(), (float *)dmean_ptr.GetAddr(), (float *)dvar_ptr.GetAddr(), (float )m_gamma, (float )m_beta, (float )m_unbinarize_bias, (int )m_connection_table.GetReverseTableStride(), (int )dx_buf.GetNodeSize(), (int )dy_buf.GetNodeSize(), (int )dy_buf.GetFrameSize(), (int )(dy_buf.GetFrameStride() / sizeof(float)), (int )(x_buf.GetFrameStride() / sizeof(int)), (int )tmp_buf.GetFrameSize(), (int )(tmp_buf.GetFrameStride() / sizeof(int)), (int )m_lut_binarize ); return dx_buf; } #endif { // generic dx_buf.FillZero(); auto node_size = dy_buf.GetNodeSize(); auto frame_size = dy_buf.GetFrameSize(); auto reciprocal_frame_size = (RealType)1.0 / (RealType)frame_size; auto x_ptr = x_buf.LockConst<BinType>(); auto dy_ptr = dy_buf.LockConst<RealType>(); auto dx_ptr = dx_buf.Lock<RealType>(true); auto input_table_ptr = m_connection_table.LockConst_InputTable(); auto W_ptr = lock_W_const(); auto dW_ptr = lock_dW(); auto mean_ptr = m_mean.LockConst(); auto rstd_ptr = m_rstd.LockConst(); for ( index_t node = 0; node < node_size; ++node ) { RealType W[(1 << N)]; for ( int i = 0; i < (1 << N); ++i) { W[i] = W_ptr(node, i); if ( m_lut_binarize ) { W[i] = ((W[i] > (RealType)0.5) ? (RealType)1.0 : (RealType)0.0); } } RealType dW[(1 << N)] = {0}; // 平均分散の勾配計算 RealType mean = mean_ptr[node]; RealType rstd = rstd_ptr[node]; RealType rstd2 = rstd * rstd; RealType dmeanx = 0; RealType dstd = 0; for ( index_t frame = 0; frame < frame_size; ++frame ) { // x を再計算 RealType x_vec[N]; for ( int i = 0; i < N; ++i) { x_vec[i] = (RealType)x_ptr.Get(frame, input_table_ptr(node, i)); if ( m_binary_mode ) { x_vec[i] = (RealType)0.5 + ((x_vec[i] > (RealType)0.5) ? +m_unbinarize_bias : -m_unbinarize_bias); } else { x_vec[i] = std::min((RealType)1.0, std::max((RealType)0.0, x_vec[i])); } } RealType x; StochasticOperation_Lut_Forward<RealType>(x_vec, &x, W, N); // hard-tanh の入力 x を求める RealType tanh_x = ((x - mean) * rstd) * m_gamma + m_beta; // hard-tanh RealType dy = dy_ptr.Get(frame, node); if (tanh_x <= 0.0) { dy = 0.0; } if (tanh_x >= 1.0) { dy = 0.0; } // BatchNorm RealType xc = x - mean; // RealType xn = xc * rstd; RealType dxn = m_gamma * dy; dstd += -(dxn * xc * rstd2); dmeanx += -(dxn * rstd); } RealType dvar = dstd * rstd; RealType dmean = (dmeanx - (mean * dvar)) * reciprocal_frame_size; // 入力の勾配 dx を求める for ( index_t frame = 0; frame < frame_size; ++frame ) { // x を再計算 RealType x_vec[N]; for ( int i = 0; i < N; ++i) { x_vec[i] = (RealType)x_ptr.Get(frame, input_table_ptr(node, i)); if ( m_binary_mode ) { x_vec[i] = (RealType)0.5 + ((x_vec[i] > (RealType)0.5) ? +m_unbinarize_bias : -m_unbinarize_bias); } else { x_vec[i] = std::min((RealType)1.0, std::max((RealType)0.0, x_vec[i])); } } RealType x; StochasticOperation_Lut_Forward<RealType>(x_vec, &x, W, N); // hard-tanh の入力 x を求める RealType tanh_x = ((x - mean) * rstd) * m_gamma + m_beta; // hard-tanh RealType dy = dy_ptr.Get(frame, node); if (tanh_x <= 0.0) { dy = 0.0; } if (tanh_x >= 1.0) { dy = 0.0; } RealType dxn = dy * m_gamma; RealType dxc = dxn * rstd; RealType dx = dxc + dmean + (x * dvar * reciprocal_frame_size); RealType dx_vec[N]; StochasticOperation_Lut_Backward<RealType>(x_vec, dx_vec, &dx, W, dW, N); for ( int i = 0; i < N; ++i) { dx_ptr.Add(frame, input_table_ptr(node, i), dx_vec[i]); } } for ( int i = 0; i < (1 << N); ++i ) { dW_ptr(node, i) += dW[i]; } } return dx_buf; } } else { #ifdef BB_WITH_CUDA if ( N >= 2 && N <= 6 && DataType<BinType>::type == BB_TYPE_FP32 && DataType<RealType>::type == BB_TYPE_FP32 && !m_host_only && dy_buf.IsDeviceAvailable() && x_buf.IsDeviceAvailable() && dx_buf.IsDeviceAvailable() && Manager::IsDeviceAvailable()) { auto x_ptr = x_buf.LockDeviceMemoryConst(); auto dy_ptr = dy_buf.LockDeviceMemoryConst(); auto dx_ptr = dx_buf.LockDeviceMemory(true); auto reverse_table_ptr = m_connection_table.LockDeviceMemConst_ReverseTable(); auto input_table_ptr = m_connection_table.LockDeviceMemConst_InputTable(); auto W_ptr = m_W->LockDeviceMemoryConst(); auto dW_ptr = m_dW->LockDeviceMemory(); auto tmp_ptr = tmp_buf.LockDeviceMemory(); bbcu_fp32_StochasticLut_Backward<N>( (float const *)x_ptr.GetAddr(), (float const *)dy_ptr.GetAddr(), (float *)dx_ptr.GetAddr(), (float *)tmp_ptr.GetAddr(), (int const *)input_table_ptr.GetAddr(), (int const *)reverse_table_ptr.GetAddr(), (float const *)W_ptr.GetAddr(), (float *)dW_ptr.GetAddr(), (int )m_connection_table.GetReverseTableStride(), (int )dx_buf.GetNodeSize(), (int )dy_buf.GetNodeSize(), (int )dx_buf.GetFrameSize(), (int )(dx_buf.GetFrameStride() / sizeof(float)), (int )tmp_buf.GetFrameSize(), (int )(tmp_buf.GetFrameStride() / sizeof(float)), (int )(m_binary_mode ? 1 : 0), (int )(m_lut_binarize ? 1 : 0), (float )m_unbinarize_bias ); return dx_buf; } // LUT6 Bit CUDA if ( N == 6 && N >= 2 && N <= 6 && DataType<BinType>::type == BB_TYPE_BIT && DataType<RealType>::type == BB_TYPE_FP32 && !m_host_only && dy_buf.IsDeviceAvailable() && x_buf.IsDeviceAvailable() && dx_buf.IsDeviceAvailable() && Manager::IsDeviceAvailable()) { auto x_ptr = x_buf.LockDeviceMemoryConst(); auto dy_ptr = dy_buf.LockDeviceMemoryConst(); auto dx_ptr = dx_buf.LockDeviceMemory(true); auto reverse_table_ptr = m_connection_table.LockDeviceMemConst_ReverseTable(); auto input_table_ptr = m_connection_table.LockDeviceMemConst_InputTable(); auto W_ptr = m_W->LockDeviceMemoryConst(); auto dW_ptr = m_dW->LockDeviceMemory(); auto tmp_ptr = tmp_buf.LockDeviceMemory(); bbcu_bit_fp32_StochasticLut_Backward<N>( (int const *)x_ptr.GetAddr(), (float const *)dy_ptr.GetAddr(), (float *)dx_ptr.GetAddr(), (float *)tmp_ptr.GetAddr(), (int const *)input_table_ptr.GetAddr(), (int const *)reverse_table_ptr.GetAddr(), (float const *)W_ptr.GetAddr(), (float *)dW_ptr.GetAddr(), (int )m_connection_table.GetReverseTableStride(), (int )dx_buf.GetNodeSize(), (int )dy_buf.GetNodeSize(), (int )dx_buf.GetFrameSize(), (int )(dx_buf.GetFrameStride() / sizeof(float)), (int )(x_buf.GetFrameStride() / sizeof(int)), (int )tmp_buf.GetFrameSize(), (int )(tmp_buf.GetFrameStride() / sizeof(float)), (int )(m_lut_binarize ? 1 : 0), (float )m_unbinarize_bias ); return dx_buf; } #endif { // generic dx_buf.FillZero(); auto node_size = dy_buf.GetNodeSize(); auto frame_size = dy_buf.GetFrameSize(); // auto reciprocal_frame_size = (RealType)1.0 / (RealType)frame_size; auto x_ptr = x_buf.LockConst<BinType>(); auto dy_ptr = dy_buf.LockConst<RealType>(); auto dx_ptr = dx_buf.Lock<RealType>(true); auto input_table_ptr = m_connection_table.LockConst_InputTable(); auto W_ptr = lock_W_const(); auto dW_ptr = lock_dW(); for ( index_t node = 0; node < node_size; ++node ) { RealType W[(1 << N)]; for ( int i = 0; i < (1 << N); ++i) { W[i] = W_ptr(node, i); if ( m_lut_binarize ) { W[i] = ((W[i] > (RealType)0.5) ? (RealType)1.0 : (RealType)0.0); } } RealType dW[(1 << N)] = {0}; for ( index_t frame = 0; frame < frame_size; ++frame ) { RealType x_vec[N]; for ( int i = 0; i < N; ++i) { x_vec[i] = (RealType)x_ptr.Get(frame, input_table_ptr(node, i)); if ( m_binary_mode ) { x_vec[i] = (RealType)0.5 + ((x_vec[i] > (RealType)0.5) ? +m_unbinarize_bias : -m_unbinarize_bias); } else { x_vec[i] = std::min((RealType)1.0, std::max((RealType)0.0, x_vec[i])); } } RealType dy = dy_ptr.Get(frame, node); RealType dx_vec[N]; StochasticOperation_Lut_Backward<RealType>(x_vec, dx_vec, &dy, W, dW, N); for ( int i = 0; i < N; ++i) { dx_ptr.Add(frame, input_table_ptr(node, i), dx_vec[i]); } } for ( int i = 0; i < (1 << N); ++i ) { dW_ptr(node, i) += dW[i]; } } return dx_buf; } } } }; } // end of file
reduction-clauseModificado.c
#include <stdio.h> #include <stdlib.h> #ifdef _OPENMP #include <omp.h> #else #define omp_get_thread_num() 0 #endif int main(int argc, char **argv) { int i, n=20, a[n],suma=10; if(argc < 2) { fprintf(stderr,"Falta iteraciones\n"); exit(-1); } n = atoi(argv[1]); if (n>20) {n=20; printf("n=%d",n);} for (i=0; i<n; i++) a[i] = i; #pragma omp parallel for reduction(+:suma) for (i=0; i<n; i++) suma += a[i]; printf("Tras 'parallel' suma=%d\n",suma); }
libmsr_write_test.c
/** * @author Asim YarKhan (updated) * @author Vince Weaver (original version) */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "papi.h" #include "msr_core.h" #include "msr_rapl.h" #define MAX_EVENTS 128 char events[MAX_EVENTS][BUFSIZ]; char filenames[MAX_EVENTS][BUFSIZ]; int ompcpuloadprimes( int limit ) { int num, primes=0; #pragma omp parallel for schedule(dynamic) reduction(+ : primes) for (num = 1; num <= limit; num++) { int i = 2; while(i <= num) { if(num % i == 0) break; i++; } if(i == num) primes++; } return primes; } int main (int argc, char **argv) { int retval,cid,rapl_cid=-1,numcmp; int EventSet = PAPI_NULL; long long values[MAX_EVENTS]; int i,code,enum_retval; const PAPI_component_info_t *cmpinfo = NULL; long long start_time,write_start_time,write_end_time,read_start_time,read_end_time; char event_name[BUFSIZ]; union { long long ll; double dbl; } event_value_union; static int num_events=0; FILE *fileout; /* PAPI Initialization */ retval = PAPI_library_init( PAPI_VER_CURRENT ); if ( retval != PAPI_VER_CURRENT ) { fprintf(stderr,"PAPI_library_init failed\n"); exit(1); } /* Find the libmsr component */ numcmp = PAPI_num_components(); for(cid=0; cid<numcmp; cid++) { if ( (cmpinfo = PAPI_get_component_info(cid)) == NULL) { fprintf(stderr,"PAPI_get_component_info failed\n"); exit(1); } if (strstr(cmpinfo->name,"libmsr")) { rapl_cid=cid; printf("Found libmsr component at cid %d\n", rapl_cid); if (cmpinfo->disabled) { fprintf(stderr,"No libmsr events found: %s\n", cmpinfo->disabled_reason); exit(1); } break; } } /* Component not found */ if (cid==numcmp) { fprintf(stderr,"No libmsr component found\n"); exit(1); } /* Find events in the component */ code = PAPI_NATIVE_MASK; enum_retval = PAPI_enum_cmp_event( &code, PAPI_ENUM_FIRST, cid ); while ( enum_retval == PAPI_OK ) { retval = PAPI_event_code_to_name( code, event_name ); if ( retval != PAPI_OK ) { printf("Error translating %#x\n",code); exit(1); } printf("Found: %s\n",event_name); strncpy(events[num_events],event_name,BUFSIZ); sprintf(filenames[num_events],"results.%s",event_name); num_events++; if (num_events==MAX_EVENTS) { printf("Too many events! %d\n",num_events); exit(1); } enum_retval = PAPI_enum_cmp_event( &code, PAPI_ENUM_EVENTS, cid ); } if (num_events==0) { printf("Error! No libmsr events found!\n"); exit(1); } /* Open output file */ char fileoutname[]="libmsr_write_test_output.txt"; fileout=fopen( fileoutname ,"w" ); if ( fileout==NULL) { fprintf( stderr,"Could not open %s\n",fileoutname ); exit(1); } /* Create EventSet */ retval = PAPI_create_eventset( &EventSet ); if (retval != PAPI_OK) { fprintf(stderr,"Error creating eventset!\n"); } for(i=0;i<num_events;i++) { retval = PAPI_add_named_event( EventSet, events[i] ); if (retval != PAPI_OK) fprintf(stderr,"Error adding event %s\n",events[i]); } start_time=PAPI_get_real_nsec(); /* Grab the initial values for the events */ retval = PAPI_start( EventSet); if (retval != PAPI_OK) { fprintf(stderr,"PAPI_start() failed\n"); exit(1); } /* Initial checking read */ retval = PAPI_read( EventSet, values); if (retval != PAPI_OK) { fprintf(stderr,"PAPI_read() failed\n"); exit(1); } /* Write a header line */ fprintf( fileout, "ACTION TIME-STAMP TIME-FOR-UNIT-WORK TIME-OVERHEAD-RW\t" ); for(i=0; i<num_events; i++) fprintf( fileout, "%s\t", events[i]+9 ); fprintf( fileout, "\n" ); /* Read the initial values */ retval = PAPI_read( EventSet, values); if (retval != PAPI_OK) { fprintf(stderr,"PAPI_read() failed\n"); exit(1); } fprintf( fileout, "INITIAL %.3f 0\t", ((double)(PAPI_get_real_nsec()-start_time))/1.0e9 ); for(i=0; i<num_events; i++) { event_value_union.ll = values[i]; fprintf( fileout, "%.3f\t", event_value_union.dbl ); } fprintf( fileout, "\n" ); int rpt=0; int limit1base=10; int limit2base=10; while(rpt++<200) { //printf("rpt %d\n", rpt); if ( rpt % 10 == 0 ) { for (i=0; i<num_events; i++) { event_value_union.ll = values[i]; if ( !strcmp( events[i], "libmsr:::PKG_POWER_LIMIT_1:PACKAGE0" )) event_value_union.dbl=limit1base+(rpt/2); else if ( !strcmp( events[i], "libmsr:::PKG_TIME_WINDOW_POWER_LIMIT_1:PACKAGE0" )) event_value_union.dbl=1.0; else if ( !strcmp( events[i], "libmsr:::PKG_POWER_LIMIT_2:PACKAGE0" )) event_value_union.dbl=limit2base+(rpt/2); else if ( !strcmp( events[i], "libmsr:::PKG_TIME_WINDOW_POWER_LIMIT_2:PACKAGE0" )) event_value_union.dbl=1.0; else if ( !strcmp( events[i], "libmsr:::PKG_POWER_LIMIT_1:PACKAGE1" )) event_value_union.dbl=limit1base+(rpt/2); else if ( !strcmp( events[i], "libmsr:::PKG_TIME_WINDOW_POWER_LIMIT_1:PACKAGE1" )) event_value_union.dbl=1.0; else if ( !strcmp( events[i], "libmsr:::PKG_POWER_LIMIT_2:PACKAGE1" )) event_value_union.dbl=limit2base+(rpt/2); else if ( !strcmp( events[i], "libmsr:::PKG_TIME_WINDOW_POWER_LIMIT_2:PACKAGE1" )) event_value_union.dbl=1.0; else event_value_union.dbl=PAPI_NULL; values[i]=event_value_union.ll; } write_start_time=PAPI_get_real_nsec(); retval = PAPI_write( EventSet, values ); write_end_time=PAPI_get_real_nsec(); if (retval != PAPI_OK) { fprintf(stderr,"PAPI_write() failed\n"); exit(1); } fprintf( fileout, "SET %.3f \t0 \t", ((double)(PAPI_get_real_nsec()-start_time))/1.0e9 ); fprintf( fileout, "%.5e\t", ((double)(write_end_time-write_start_time))/1.0e9 ); for(i=0; i<num_events; i++) { event_value_union.ll = values[i]; fprintf( fileout, "%.3f\t", event_value_union.dbl ); } fprintf( fileout, "\n" ); } /* DO SOME WORK TO USE ENERGY */ //usleep(100000); double work_start_time=PAPI_get_real_nsec(); ompcpuloadprimes( 100000 ); double work_time=PAPI_get_real_nsec()-work_start_time; //printf("primescount %d\n", primescount); /* Read and output the values */ read_start_time=PAPI_get_real_nsec(); retval = PAPI_read( EventSet, values ); read_end_time=PAPI_get_real_nsec(); if (retval != PAPI_OK) { fprintf(stderr,"PAPI_read() failed\n"); exit(1); } fprintf( fileout, "READ %.3f\t %.3f\t", ((double)(PAPI_get_real_nsec()-start_time))/1.0e9, work_time/1.0e9 ); fprintf( fileout, "%.5e\t", ((double)(read_end_time-read_start_time))/1.0e9 ); for(i=0; i<num_events; i++) { event_value_union.ll = values[i]; fprintf( fileout, "%.3f\t", event_value_union.dbl ); } fprintf( fileout, "\n" ); } retval = PAPI_stop( EventSet, values); return 0; }
rt_dttmqr.c
#include "runtime.h" void RT_CORE_dttmqr(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_enum side, PLASMA_enum trans, int m1, int n1, int m2, int n2, int k, int ib, int nb, double *A1, int lda1, double *A2, int lda2, const double *V, int ldv, const double *T, int ldt) { plasma_context_t *plasma; plasma = plasma_context_self(); if (plasma->runtime == PLASMA_QUARK) { QUARK_CORE_dttmqr( quark, task_flags, side, trans, m1, n1, m2, n2, k, ib, nb, A1, lda1, A2, lda2, V, ldv, T, ldt); } else if (plasma->runtime == PLASMA_OMPSS) { double *WORK = malloc(ib*nb*sizeof(double)); int ldwork; #pragma omp target device (smp) copy_deps #pragma omp task inout([nb*nb]A1, [nb*nb]A2) in([nb*nb]V, [ib*nb]T) label (dttmqr) CORE_dttmqr(side, trans, m1, n1, m2, n2, k, ib, A1, lda1, A2, lda2, V, ldv, T, ldt, WORK, ldwork); } }
GB_unaryop__one_fp64_fp64.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__one_fp64_fp64 // op(A') function: GB_tran__one_fp64_fp64 // C type: double // A type: double // cast: ; // unaryop: cij = 1 #define GB_ATYPE \ double #define GB_CTYPE \ double // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ ; #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = 1 ; // casting #define GB_CASTING(z, 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_ONE || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__one_fp64_fp64 ( double *restrict Cx, const double *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__one_fp64_fp64 ( 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
core_dzamax.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @precisions normal z -> c d s * **/ #include "core_blas.h" #include "plasma_types.h" #include "core_lapack.h" #include <math.h> /******************************************************************************/ void core_omp_dzamax(int colrow, int m, int n, const plasma_complex64_t *A, int lda, double *values, plasma_sequence_t *sequence, plasma_request_t *request) { switch (colrow) { case PlasmaColumnwise: #pragma omp task depend(in:A[0:lda*n]) \ depend(out:values[0:n]) { if (sequence->status == PlasmaSuccess) { for (int j = 0; j < n; j++) { values[j] = core_dcabs1(A[lda*j]); for (int i = 1; i < m; i++) { double tmp = core_dcabs1(A[lda*j+i]); if (tmp > values[j]) values[j] = tmp; } } } } break; case PlasmaRowwise: #pragma omp task depend(in:A[0:lda*n]) \ depend(out:values[0:m]) { if (sequence->status == PlasmaSuccess) { for (int i = 0; i < m; i++) values[i] = core_dcabs1(A[i]); for (int j = 1; j < n; j++) { for (int i = 0; i < m; i++) { double tmp = core_dcabs1(A[lda*j+i]); if (tmp > values[i]) values[i] = tmp; } } } } break; } }
aarch64_vfabi_WidestDataSize.c
// RUN: %clang_cc1 -triple aarch64-linux-gnu -target-feature +sve -fopenmp -x c -emit-llvm %s -o - -femit-all-decls | FileCheck %s // RUN: %clang_cc1 -triple aarch64-linux-gnu -target-feature +sve -fopenmp-simd -x c -emit-llvm %s -o - -femit-all-decls | FileCheck %s // REQUIRES: aarch64-registered-target // Note: -fopemp and -fopenmp-simd behavior are expected to be the same. // This test checks the values of Widest Data Size (WDS), as defined // in https://github.com/ARM-software/abi-aa/tree/master/vfabia64 // // WDS is used to check the accepted values <N> of `simdlen(<N>)` when // targeting fixed-length SVE vector function names. The values of // `<N>` that are accepted are such that for X = WDS * <N> * 8, // 128-bit <= X <= 2048-bit and X is a multiple of 128-bit. #pragma omp declare simd simdlen(8) #pragma omp declare simd simdlen(16) #pragma omp declare simd simdlen(256) #pragma omp declare simd simdlen(272) char WDS_is_sizeof_char(char in); // WDS = 1, simdlen(8) and simdlen(272) are not generated. // CHECK-DAG: _ZGVsM16v_WDS_is_sizeof_char // CHECK-DAG: _ZGVsM256v_WDS_is_sizeof_char // CHECK-NOT: _ZGV{{.*}}_WDS_is_sizeof_char #pragma omp declare simd simdlen(4) #pragma omp declare simd simdlen(8) #pragma omp declare simd simdlen(128) #pragma omp declare simd simdlen(136) char WDS_is_sizeof_short(short in); // WDS = 2, simdlen(4) and simdlen(136) are not generated. // CHECK-DAG: _ZGVsM8v_WDS_is_sizeof_short // CHECK-DAG: _ZGVsM128v_WDS_is_sizeof_short // CHECK-NOT: _ZGV{{.*}}_WDS_is_sizeof_short #pragma omp declare simd linear(sin) notinbranch simdlen(2) #pragma omp declare simd linear(sin) notinbranch simdlen(4) #pragma omp declare simd linear(sin) notinbranch simdlen(64) #pragma omp declare simd linear(sin) notinbranch simdlen(68) void WDS_is_sizeof_float_pointee(float in, float *sin); // WDS = 4, simdlen(2) and simdlen(68) are not generated. // CHECK-DAG: _ZGVsM4vl4_WDS_is_sizeof_float_pointee // CHECK-DAG: _ZGVsM64vl4_WDS_is_sizeof_float_pointee // CHECK-NOT: _ZGV{{.*}}_WDS_is_sizeof_float_pointee #pragma omp declare simd linear(sin) notinbranch simdlen(2) #pragma omp declare simd linear(sin) notinbranch simdlen(4) #pragma omp declare simd linear(sin) notinbranch simdlen(32) #pragma omp declare simd linear(sin) notinbranch simdlen(34) void WDS_is_sizeof_double_pointee(float in, double *sin); // WDS = 8 because of the linear clause, simdlen(34) is not generated. // CHECK-DAG: _ZGVsM2vl8_WDS_is_sizeof_double_pointee // CHECK-DAG: _ZGVsM4vl8_WDS_is_sizeof_double_pointee // CHECK-DAG: _ZGVsM32vl8_WDS_is_sizeof_double_pointee // CHECK-NOT: _ZGV{{.*}}_WDS_is_sizeof_double_pointee #pragma omp declare simd simdlen(2) #pragma omp declare simd simdlen(4) #pragma omp declare simd simdlen(32) #pragma omp declare simd simdlen(34) double WDS_is_sizeof_double(double in); // WDS = 8, simdlen(34) is not generated. // CHECK-DAG: _ZGVsM2v_WDS_is_sizeof_double // CHECK-DAG: _ZGVsM4v_WDS_is_sizeof_double // CHECK-DAG: _ZGVsM32v_WDS_is_sizeof_double // CHECK-NOT: _ZGV{{.*}}_WDS_is_sizeof_double static char C; static short S; static float F; static double D; void do_something() { C = WDS_is_sizeof_char(C); C = WDS_is_sizeof_short(S); WDS_is_sizeof_float_pointee(F, &F); WDS_is_sizeof_double_pointee(F, &D); D = WDS_is_sizeof_double(D); }
OMPSparseMatrix.c
#include <omp.h> #include <stdlib.h> #include <stdio.h> int main (int argc, char* argv[]) { //Declarations double dampingFactor = 0.15; int numPage = atoi(argv[1]); int totalSize = numPage * numPage; double *aArray, *pageRank, *yArray; int *iA, *jA; aArray = (double*)malloc((2*numPage-1)*sizeof(double)); iA = (int*)malloc((numPage+1)*sizeof(int)); jA = (int*)malloc((2*numPage-1)*sizeof(int)); pageRank = (double*)malloc(numPage*sizeof(double)); yArray = (double*)malloc(numPage*sizeof(double)); int i, j, K, k; K = 1000; double startTime, endTime; //setup the sArray for (i = 0; i < 2*numPage - 1; i++) { if (i == 2 ) aArray[i] = 1.0; else aArray[i] = 0.5; } //setup the iA and initialize pagerank to 1/Numpage for (i = 0; i < numPage + 1; i++) { if (i == numPage) iA[i] = 2*numPage - 1; else if (i == 0) iA[i] = 0; else iA[i] = iA[i-1] + 2; if (i < numPage) pageRank[i] = 1/(double)numPage; } //setup jA jA[0] = 1; jA[1] = numPage -1; jA[2] = 0; jA[3] = 2; for (i = 4; i < 2*numPage-1; i++) { jA[i] = jA[i -2] + 1; } //start timer and perform MatVec on the CSR K-times startTime = omp_get_wtime(); for (k = 0; k < K; k++) { #pragma omp parallel for private(j) for (i = 0; i < numPage; i++) { yArray[i] = 0.0; for (j = iA[i]; j < iA[i+1]; j++) { yArray[i] += aArray[j] * pageRank[jA[j]]; } } #pragma omp master for (i = 0; i < numPage; i++) { //apply damping yArray[i] = ((1 - dampingFactor)*yArray[i]) + (dampingFactor / numPage); pageRank[i] = yArray[i]; } #pragma end master } endTime = omp_get_wtime(); //print pagerank or max and min values if (numPage < 20) { for (i = 0; i < numPage; i++) { printf("PR(%d) = %f \n", i, pageRank[i]); } } else { double max, min; max = pageRank[0]; min = pageRank[0]; for (i = 0; i < numPage; i++) { if (max < pageRank[i]) max = pageRank[i]; if (min > pageRank[i]) min = pageRank[i]; } printf("Min Pagerank = %f \n", min); printf("Max Pagerank = %f \n", max); } //print runtime printf("RUNTIME = %.16f\n", endTime - startTime); return 0; }
fmm.h
#ifndef fmm_h #define fmm_h #include <cstring> // std::memset #include <fstream> // std::ofstream #include <type_traits> // std::is_same #include "fmm_base.h" #include "intrinsics.h" #include "math_wrapper.h" namespace exafmm_t { template <typename T> class Fmm : public FmmBase<T> { public: /* precomputation matrices */ std::vector<std::vector<T>> matrix_UC2E_U; std::vector<std::vector<T>> matrix_UC2E_V; std::vector<std::vector<T>> matrix_DC2E_U; std::vector<std::vector<T>> matrix_DC2E_V; std::vector<std::vector<std::vector<T>>> matrix_M2M; std::vector<std::vector<std::vector<T>>> matrix_L2L; std::vector<M2LData> m2ldata; /* constructors */ Fmm() {} Fmm(int p_, int ncrit_, std::string filename_=std::string()) : FmmBase<T>(p_, ncrit_, filename_) {} /* precomputation */ //! Setup the sizes of precomputation matrices void initialize_matrix() { int& nsurf_ = this->nsurf; int& depth_ = this->depth; matrix_UC2E_V.resize(depth_+1, std::vector<T>(nsurf_*nsurf_)); matrix_UC2E_U.resize(depth_+1, std::vector<T>(nsurf_*nsurf_)); matrix_DC2E_V.resize(depth_+1, std::vector<T>(nsurf_*nsurf_)); matrix_DC2E_U.resize(depth_+1, std::vector<T>(nsurf_*nsurf_)); matrix_M2M.resize(depth_+1); matrix_L2L.resize(depth_+1); for (int level=0; level<=depth_; ++level) { matrix_M2M[level].resize(REL_COORD[M2M_Type].size(), std::vector<T>(nsurf_*nsurf_)); matrix_L2L[level].resize(REL_COORD[L2L_Type].size(), std::vector<T>(nsurf_*nsurf_)); } } //! Precompute M2M and L2L void precompute_M2M() { int& nsurf_ = this->nsurf; real_t parent_coord[3] = {0, 0, 0}; for (int level=0; level<=this->depth; level++) { RealVec parent_up_check_surf = surface(this->p, this->r0, level, parent_coord, 2.95); real_t s = this->r0 * powf(0.5, level+1); int npos = REL_COORD[M2M_Type].size(); // number of relative positions #pragma omp parallel for for(int i=0; i<npos; i++) { // compute kernel matrix ivec3& coord = REL_COORD[M2M_Type][i]; real_t child_coord[3] = {parent_coord[0] + coord[0]*s, parent_coord[1] + coord[1]*s, parent_coord[2] + coord[2]*s}; RealVec child_up_equiv_surf = surface(this->p, this->r0, level+1, child_coord, 1.05); std::vector<T> matrix_pc2ce(nsurf_*nsurf_); this->kernel_matrix(parent_up_check_surf, child_up_equiv_surf, matrix_pc2ce); // M2M std::vector<T> buffer(nsurf_*nsurf_); gemm(nsurf_, nsurf_, nsurf_, &(matrix_UC2E_U[level][0]), &matrix_pc2ce[0], &buffer[0]); gemm(nsurf_, nsurf_, nsurf_, &(matrix_UC2E_V[level][0]), &buffer[0], &(matrix_M2M[level][i][0])); // L2L matrix_pc2ce = transpose(matrix_pc2ce, nsurf_, nsurf_); gemm(nsurf_, nsurf_, nsurf_, &matrix_pc2ce[0], &(matrix_DC2E_V[level][0]), &buffer[0]); gemm(nsurf_, nsurf_, nsurf_, &buffer[0], &(matrix_DC2E_U[level][0]), &(matrix_L2L[level][i][0])); } } } //! Precompute UC2UE and DC2DE matrices void precompute_check2equiv() {} //! Precompute M2L void precompute_M2L(std::ofstream& file) {} //! Save precomputation matrices void save_matrix(std::ofstream& file) { file.write(reinterpret_cast<char*>(&this->r0), sizeof(real_t)); // r0 size_t size = this->nsurf * this->nsurf; for(int l=0; l<=this->depth; l++) { // UC2E, DC2E file.write(reinterpret_cast<char*>(&matrix_UC2E_U[l][0]), size*sizeof(T)); file.write(reinterpret_cast<char*>(&matrix_UC2E_V[l][0]), size*sizeof(T)); file.write(reinterpret_cast<char*>(&matrix_DC2E_U[l][0]), size*sizeof(T)); file.write(reinterpret_cast<char*>(&matrix_DC2E_V[l][0]), size*sizeof(T)); // M2M, L2L for (auto & vec : matrix_M2M[l]) { file.write(reinterpret_cast<char*>(&vec[0]), size*sizeof(T)); } for (auto & vec : matrix_L2L[l]) { file.write(reinterpret_cast<char*>(&vec[0]), size*sizeof(T)); } } } //! Check and load precomputation matrices void load_matrix() { int& nsurf_ = this->nsurf; int& depth_ = this->depth; size_t size_M2L = this->nfreq * 2 * NCHILD * NCHILD; size_t file_size = (2*REL_COORD[M2M_Type].size()+4) * nsurf_ * nsurf_ * (depth_+1) * sizeof(T) + REL_COORD[M2L_Type].size() * size_M2L * depth_ * sizeof(real_t) + 1 * sizeof(real_t); // +1 denotes r0 std::ifstream file(this->filename, std::ifstream::binary); if (file.good()) { file.seekg(0, file.end); if (size_t(file.tellg()) == file_size) { // if file size is correct file.seekg(0, file.beg); // move the position back to the beginning real_t r0_; file.read(reinterpret_cast<char*>(&r0_), sizeof(real_t)); if (this->r0 == r0_) { // if radius match size_t size = nsurf_ * nsurf_; for (int l=0; l<=depth_; l++) { // UC2E, DC2E file.read(reinterpret_cast<char*>(&matrix_UC2E_U[l][0]), size*sizeof(T)); file.read(reinterpret_cast<char*>(&matrix_UC2E_V[l][0]), size*sizeof(T)); file.read(reinterpret_cast<char*>(&matrix_DC2E_U[l][0]), size*sizeof(T)); file.read(reinterpret_cast<char*>(&matrix_DC2E_V[l][0]), size*sizeof(T)); // M2M, L2L for (auto& vec : matrix_M2M[l]) { file.read(reinterpret_cast<char*>(&vec[0]), size*sizeof(T)); } for (auto& vec : matrix_L2L[l]) { file.read(reinterpret_cast<char*>(&vec[0]), size*sizeof(T)); } } this->is_precomputed = true; } } } file.close(); } //! Precompute void precompute() { initialize_matrix(); load_matrix(); if (!this->is_precomputed) { precompute_check2equiv(); precompute_M2M(); std::remove(this->filename.c_str()); std::ofstream file(this->filename, std::ofstream::binary); save_matrix(file); precompute_M2L(file); file.close(); } } //! P2M operator void P2M(NodePtrs<T>& leafs) { int& nsurf_ = this->nsurf; real_t c[3] = {0,0,0}; std::vector<RealVec> up_check_surf; up_check_surf.resize(this->depth+1); for (int level=0; level<=this->depth; level++) { up_check_surf[level].resize(nsurf_*3); up_check_surf[level] = surface(this->p, this->r0, level, c, 2.95); } #pragma omp parallel for for (size_t i=0; i<leafs.size(); i++) { Node<T>* leaf = leafs[i]; int level = leaf->level; // calculate upward check potential induced by sources' charges RealVec check_coord(nsurf_*3); for (int k=0; k<nsurf_; k++) { check_coord[3*k+0] = up_check_surf[level][3*k+0] + leaf->x[0]; check_coord[3*k+1] = up_check_surf[level][3*k+1] + leaf->x[1]; check_coord[3*k+2] = up_check_surf[level][3*k+2] + leaf->x[2]; } this->potential_P2P(leaf->src_coord, leaf->src_value, check_coord, leaf->up_equiv); std::vector<T> buffer(nsurf_); std::vector<T> equiv(nsurf_); gemv(nsurf_, nsurf_, &(matrix_UC2E_U[level][0]), &(leaf->up_equiv[0]), &buffer[0]); gemv(nsurf_, nsurf_, &(matrix_UC2E_V[level][0]), &buffer[0], &equiv[0]); for (int k=0; k<nsurf_; k++) leaf->up_equiv[k] = equiv[k]; } } //! L2P operator void L2P(NodePtrs<T>& leafs) { int& nsurf_ = this->nsurf; real_t c[3] = {0,0,0}; std::vector<RealVec> dn_equiv_surf; dn_equiv_surf.resize(this->depth+1); for (int level=0; level<=this->depth; level++) { dn_equiv_surf[level].resize(nsurf_*3); dn_equiv_surf[level] = surface(this->p, this->r0, level, c, 2.95); } #pragma omp parallel for for (size_t i=0; i<leafs.size(); i++) { Node<T>* leaf = leafs[i]; int level = leaf->level; // down check surface potential -> equivalent surface charge std::vector<T> buffer(nsurf_); std::vector<T> equiv(nsurf_); gemv(nsurf_, nsurf_, &(matrix_DC2E_U[level][0]), &(leaf->dn_equiv[0]), &buffer[0]); gemv(nsurf_, nsurf_, &(matrix_DC2E_V[level][0]), &buffer[0], &equiv[0]); for (int k=0; k<nsurf_; k++) leaf->dn_equiv[k] = equiv[k]; // equivalent surface charge -> target potential RealVec equiv_coord(nsurf_*3); for (int k=0; k<nsurf_; k++) { equiv_coord[3*k+0] = dn_equiv_surf[level][3*k+0] + leaf->x[0]; equiv_coord[3*k+1] = dn_equiv_surf[level][3*k+1] + leaf->x[1]; equiv_coord[3*k+2] = dn_equiv_surf[level][3*k+2] + leaf->x[2]; } this->gradient_P2P(equiv_coord, leaf->dn_equiv, leaf->trg_coord, leaf->trg_value); } } //! M2M operator void M2M(Node<T>* node) { int& nsurf_ = this->nsurf; if (node->is_leaf) return; for (int octant=0; octant<8; octant++) { if (node->children[octant]) #pragma omp task untied M2M(node->children[octant]); } #pragma omp taskwait for (int octant=0; octant<8; octant++) { if (node->children[octant]) { Node<T>* child = node->children[octant]; std::vector<T> buffer(nsurf_); int level = node->level; gemv(nsurf_, nsurf_, &(matrix_M2M[level][octant][0]), &child->up_equiv[0], &buffer[0]); for (int k=0; k<nsurf_; k++) { node->up_equiv[k] += buffer[k]; } } } } //! L2L operator void L2L(Node<T>* node) { int& nsurf_ = this->nsurf; if (node->is_leaf) return; for (int octant=0; octant<8; octant++) { if (node->children[octant]) { Node<T>* child = node->children[octant]; std::vector<T> buffer(nsurf_); int level = node->level; gemv(nsurf_, nsurf_, &(matrix_L2L[level][octant][0]), &node->dn_equiv[0], &buffer[0]); for (int k=0; k<nsurf_; k++) child->dn_equiv[k] += buffer[k]; } } for (int octant=0; octant<8; octant++) { if (node->children[octant]) #pragma omp task untied L2L(node->children[octant]); } #pragma omp taskwait } void M2L_setup(NodePtrs<T>& nonleafs) { int& nsurf_ = this->nsurf; int& depth_ = this->depth; int npos = REL_COORD[M2L_Type].size(); // number of M2L relative positions m2ldata.resize(depth_); // initialize m2ldata // construct lists of target nodes for M2L operator at each level std::vector<NodePtrs<T>> trg_nodes(depth_); for (size_t i=0; i<nonleafs.size(); i++) { trg_nodes[nonleafs[i]->level].push_back(nonleafs[i]); } // prepare for m2ldata for each level for (int l=0; l<depth_; l++) { // construct M2L source nodes for current level std::set<Node<T>*> src_nodes_; for (size_t i=0; i<trg_nodes[l].size(); i++) { NodePtrs<T>& M2L_list = trg_nodes[l][i]->M2L_list; for (int k=0; k<npos; k++) { if (M2L_list[k]) src_nodes_.insert(M2L_list[k]); } } NodePtrs<T> src_nodes; auto it = src_nodes_.begin(); for (; it!=src_nodes_.end(); it++) { src_nodes.push_back(*it); } // prepare the indices of src_nodes & trg_nodes in all_up_equiv & all_dn_equiv std::vector<size_t> fft_offset(src_nodes.size()); // displacement in all_up_equiv std::vector<size_t> ifft_offset(trg_nodes[l].size()); // displacement in all_dn_equiv for (size_t i=0; i<src_nodes.size(); i++) { fft_offset[i] = src_nodes[i]->children[0]->idx * nsurf_; } for (size_t i=0; i<trg_nodes[l].size(); i++) { ifft_offset[i] = trg_nodes[l][i]->children[0]->idx * nsurf_; } // calculate interaction_offset_f & interaction_count_offset std::vector<size_t> interaction_offset_f; std::vector<size_t> interaction_count_offset; for (size_t i=0; i<src_nodes.size(); i++) { src_nodes[i]->idx_M2L = i; // node_id: node's index in src_nodes list } size_t nblk_trg = trg_nodes[l].size() * sizeof(real_t) / CACHE_SIZE; if (nblk_trg==0) nblk_trg = 1; size_t interaction_count_offset_ = 0; size_t fft_size = 2 * NCHILD * this->nfreq; for (size_t iblk_trg=0; iblk_trg<nblk_trg; iblk_trg++) { size_t blk_start = (trg_nodes[l].size()* iblk_trg ) / nblk_trg; size_t blk_end = (trg_nodes[l].size()*(iblk_trg+1)) / nblk_trg; for (int k=0; k<npos; k++) { for (size_t i=blk_start; i<blk_end; i++) { NodePtrs<T>& M2L_list = trg_nodes[l][i]->M2L_list; if (M2L_list[k]) { interaction_offset_f.push_back(M2L_list[k]->idx_M2L * fft_size); // src_node's displacement in fft_in interaction_offset_f.push_back( i * fft_size); // trg_node's displacement in fft_out interaction_count_offset_++; } } interaction_count_offset.push_back(interaction_count_offset_); } } m2ldata[l].fft_offset = fft_offset; m2ldata[l].ifft_offset = ifft_offset; m2ldata[l].interaction_offset_f = interaction_offset_f; m2ldata[l].interaction_count_offset = interaction_count_offset; } } void hadamard_product(std::vector<size_t>& interaction_count_offset, std::vector<size_t>& interaction_offset_f, AlignedVec& fft_in, AlignedVec& fft_out, std::vector<AlignedVec>& matrix_M2L) { size_t fft_size = 2 * NCHILD * this->nfreq; AlignedVec zero_vec0(fft_size, 0.); AlignedVec zero_vec1(fft_size, 0.); size_t npos = matrix_M2L.size(); size_t nblk_inter = interaction_count_offset.size(); // num of blocks of interactions size_t nblk_trg = nblk_inter / npos; // num of blocks based on trg_nodes int BLOCK_SIZE = CACHE_SIZE * 2 / sizeof(real_t); std::vector<real_t*> IN_(BLOCK_SIZE*nblk_inter); std::vector<real_t*> OUT_(BLOCK_SIZE*nblk_inter); // initialize fft_out with zero #pragma omp parallel for for (size_t i=0; i<fft_out.capacity()/fft_size; ++i) { std::memset(fft_out.data()+i*fft_size, 0, fft_size*sizeof(real_t)); } #pragma omp parallel for for (size_t iblk_inter=0; iblk_inter<nblk_inter; iblk_inter++) { size_t interaction_count_offset0 = (iblk_inter==0 ? 0 : interaction_count_offset[iblk_inter-1]); size_t interaction_count_offset1 = interaction_count_offset[iblk_inter]; size_t interaction_count = interaction_count_offset1 - interaction_count_offset0; for (size_t j=0; j<interaction_count; j++) { IN_ [BLOCK_SIZE*iblk_inter+j] = &fft_in[interaction_offset_f[(interaction_count_offset0+j)*2+0]]; OUT_[BLOCK_SIZE*iblk_inter+j] = &fft_out[interaction_offset_f[(interaction_count_offset0+j)*2+1]]; } IN_ [BLOCK_SIZE*iblk_inter+interaction_count] = &zero_vec0[0]; OUT_[BLOCK_SIZE*iblk_inter+interaction_count] = &zero_vec1[0]; } for (size_t iblk_trg=0; iblk_trg<nblk_trg; iblk_trg++) { #pragma omp parallel for for (int k=0; k<this->nfreq; k++) { for (size_t ipos=0; ipos<npos; ipos++) { size_t iblk_inter = iblk_trg*npos + ipos; size_t interaction_count_offset0 = (iblk_inter==0 ? 0 : interaction_count_offset[iblk_inter-1]); size_t interaction_count_offset1 = interaction_count_offset[iblk_inter]; size_t interaction_count = interaction_count_offset1 - interaction_count_offset0; real_t** IN = &IN_[BLOCK_SIZE*iblk_inter]; real_t** OUT= &OUT_[BLOCK_SIZE*iblk_inter]; real_t* M = &matrix_M2L[ipos][k*2*NCHILD*NCHILD]; // k-th freq's (row) offset in matrix_M2L for (size_t j=0; j<interaction_count; j+=2) { real_t* M_ = M; real_t* IN0 = IN [j+0] + k*NCHILD*2; // go to k-th freq chunk real_t* IN1 = IN [j+1] + k*NCHILD*2; real_t* OUT0 = OUT[j+0] + k*NCHILD*2; real_t* OUT1 = OUT[j+1] + k*NCHILD*2; matmult_8x8x2(M_, IN0, IN1, OUT0, OUT1); } } } } } void fft_up_equiv(std::vector<size_t>& fft_offset, std::vector<T>& all_up_equiv, AlignedVec& fft_in) {} void ifft_dn_check(std::vector<size_t>& ifft_offset, AlignedVec& fft_out, std::vector<T>& all_dn_equiv) {} void M2L(Nodes<T>& nodes) { int& nsurf_ = this->nsurf; int& nfreq_ = this->nfreq; int fft_size = 2 * NCHILD * nfreq_; int nnodes = nodes.size(); int npos = REL_COORD[M2L_Type].size(); // number of relative positions // allocate memory std::vector<T> all_up_equiv, all_dn_equiv; all_up_equiv.reserve(nnodes*nsurf_); all_dn_equiv.reserve(nnodes*nsurf_); std::vector<AlignedVec> matrix_M2L(npos, AlignedVec(fft_size*NCHILD, 0)); // setup ifstream of M2L precomputation matrix std::ifstream ifile(this->filename, std::ifstream::binary); ifile.seekg(0, ifile.end); size_t fsize = ifile.tellg(); // file size in bytes size_t msize = NCHILD * NCHILD * nfreq_ * 2 * sizeof(real_t); // size in bytes for each M2L matrix ifile.seekg(fsize - this->depth*npos*msize, ifile.beg); // go to the start of M2L section // collect all upward equivalent charges #pragma omp parallel for collapse(2) for (int i=0; i<nnodes; ++i) { for (int j=0; j<nsurf_; ++j) { all_up_equiv[i*nsurf_+j] = nodes[i].up_equiv[j]; all_dn_equiv[i*nsurf_+j] = nodes[i].dn_equiv[j]; } } // FFT-accelerate M2L for (int l=0; l<this->depth; ++l) { // load M2L matrix for current level for (int i=0; i<npos; ++i) { ifile.read(reinterpret_cast<char*>(matrix_M2L[i].data()), msize); } AlignedVec fft_in, fft_out; fft_in.reserve(m2ldata[l].fft_offset.size()*fft_size); fft_out.reserve(m2ldata[l].ifft_offset.size()*fft_size); fft_up_equiv(m2ldata[l].fft_offset, all_up_equiv, fft_in); hadamard_product(m2ldata[l].interaction_count_offset, m2ldata[l].interaction_offset_f, fft_in, fft_out, matrix_M2L); ifft_dn_check(m2ldata[l].ifft_offset, fft_out, all_dn_equiv); } // update all downward check potentials #pragma omp parallel for collapse(2) for (int i=0; i<nnodes; ++i) { for (int j=0; j<nsurf_; ++j) { nodes[i].dn_equiv[j] = all_dn_equiv[i*nsurf_+j]; } } ifile.close(); // close ifstream } }; /** Below are member function specializations */ template <> void Fmm<real_t>::precompute_check2equiv() { real_t c[3] = {0, 0, 0}; int& nsurf_ = this->nsurf; #pragma omp parallel for for (int level=0; level<=this->depth; ++level) { // compute kernel matrix RealVec up_check_surf = surface(this->p, this->r0, level, c, 2.95); RealVec up_equiv_surf = surface(this->p, this->r0, level, c, 1.05); RealVec matrix_c2e(nsurf_*nsurf_); // UC2UE this->kernel_matrix(up_check_surf, up_equiv_surf, matrix_c2e); // svd RealVec S(nsurf_*nsurf_); // singular values RealVec U(nsurf_*nsurf_), VT(nsurf_*nsurf_); svd(nsurf_, nsurf_, &matrix_c2e[0], &S[0], &U[0], &VT[0]); // pseudo-inverse real_t max_S = 0; for (int i=0; i<nsurf_; i++) { max_S = fabs(S[i*nsurf_+i])>max_S ? fabs(S[i*nsurf_+i]) : max_S; } for (int i=0; i<nsurf_; i++) { S[i*nsurf_+i] = S[i*nsurf_+i]>EPS*max_S*4 ? 1.0/S[i*nsurf_+i] : 0.0; } RealVec V = transpose(VT, nsurf_, nsurf_); matrix_UC2E_U[level] = transpose(U, nsurf_, nsurf_); gemm(nsurf_, nsurf_, nsurf_, &V[0], &S[0], &(matrix_UC2E_V[level][0])); matrix_DC2E_U[level] = VT; gemm(nsurf_, nsurf_, nsurf_, &U[0], &S[0], &(matrix_DC2E_V[level][0])); } } template <> void Fmm<complex_t>::precompute_check2equiv() { real_t c[3] = {0, 0, 0}; int& nsurf_ = this->nsurf; #pragma omp parallel for for (int level=0; level<=this->depth; ++level) { // compute kernel matrix RealVec up_check_surf = surface(this->p, this->r0, level, c, 2.95); RealVec up_equiv_surf = surface(this->p, this->r0, level, c, 1.05); ComplexVec matrix_c2e(nsurf_*nsurf_); // UC2UE this->kernel_matrix(up_check_surf, up_equiv_surf, matrix_c2e); // svd RealVec S(nsurf_*nsurf_); // singular values ComplexVec U(nsurf_*nsurf_), VH(nsurf_*nsurf_); svd(nsurf_, nsurf_, &matrix_c2e[0], &S[0], &U[0], &VH[0]); // pseudo-inverse real_t max_S = 0; for (int i=0; i<nsurf_; i++) { max_S = fabs(S[i*nsurf_+i])>max_S ? fabs(S[i*nsurf_+i]) : max_S; } for (int i=0; i<nsurf_; i++) { S[i*nsurf_+i] = S[i*nsurf_+i]>EPS*max_S*4 ? 1.0/S[i*nsurf_+i] : 0.0; } ComplexVec S_(nsurf_*nsurf_); for (size_t i=0; i<S_.size(); i++) { // convert S to complex type S_[i] = S[i]; } ComplexVec V = conjugate_transpose(VH, nsurf_, nsurf_); ComplexVec UH = conjugate_transpose(U, nsurf_, nsurf_); matrix_UC2E_U[level] = UH; gemm(nsurf_, nsurf_, nsurf_, &V[0], &S_[0], &(matrix_UC2E_V[level][0])); matrix_DC2E_U[level] = transpose(V, nsurf_, nsurf_); ComplexVec UHT = transpose(UH, nsurf_, nsurf_); gemm(nsurf_, nsurf_, nsurf_, &UHT[0], &S_[0], &(matrix_DC2E_V[level][0])); } } //! member function specialization for real type template <> void Fmm<real_t>::precompute_M2L(std::ofstream& file) { int n1 = this->p * 2; int& nconv_ = this->nconv; int& nfreq_ = this->nfreq; int fft_size = 2 * nfreq_ * NCHILD * NCHILD; std::vector<RealVec> matrix_M2L_Helper(REL_COORD[M2L_Helper_Type].size(), RealVec(2*nfreq_)); std::vector<AlignedVec> matrix_M2L(REL_COORD[M2L_Type].size(), AlignedVec(fft_size)); // create fft plan RealVec fftw_in(nconv_); RealVec fftw_out(2*nfreq_); int dim[3] = {n1, n1, n1}; fft_plan plan = fft_plan_dft_r2c(3, dim, fftw_in.data(), reinterpret_cast<fft_complex*>(fftw_out.data()), FFTW_ESTIMATE); RealVec trg_coord(3,0); for (int l=1; l<this->depth+1; ++l) { // compute M2L kernel matrix, perform DFT #pragma omp parallel for for (size_t i=0; i<REL_COORD[M2L_Helper_Type].size(); ++i) { real_t coord[3]; for (int d=0; d<3; d++) { coord[d] = REL_COORD[M2L_Helper_Type][i][d] * this->r0 * powf(0.5, l-1); // relative coords } RealVec conv_coord = convolution_grid(this->p, this->r0, l, coord); // convolution grid RealVec conv_value(nconv_); // potentials on convolution grid this->kernel_matrix(conv_coord, trg_coord, conv_value); fft_execute_dft_r2c(plan, conv_value.data(), reinterpret_cast<fft_complex*>(matrix_M2L_Helper[i].data())); } // convert M2L_Helper to M2L and reorder data layout to improve locality #pragma omp parallel for for (size_t i=0; i<REL_COORD[M2L_Type].size(); ++i) { for (int j=0; j<NCHILD*NCHILD; j++) { // loop over child's relative positions int child_rel_idx = M2L_INDEX_MAP[i][j]; if (child_rel_idx != -1) { for (int k=0; k<nfreq_; k++) { // loop over frequencies int new_idx = k*(2*NCHILD*NCHILD) + 2*j; matrix_M2L[i][new_idx+0] = matrix_M2L_Helper[child_rel_idx][k*2+0] / nconv_; // real matrix_M2L[i][new_idx+1] = matrix_M2L_Helper[child_rel_idx][k*2+1] / nconv_; // imag } } } } // write to file for(auto& vec : matrix_M2L) { file.write(reinterpret_cast<char*>(vec.data()), fft_size*sizeof(real_t)); } } // destroy fftw plan fft_destroy_plan(plan); } //! member function specialization for complex type template <> void Fmm<complex_t>::precompute_M2L(std::ofstream& file) { int n1 = this->p * 2; int& nconv_ = this->nconv; int& nfreq_ = this->nfreq; int fft_size = 2 * nfreq_ * NCHILD * NCHILD; std::vector<RealVec> matrix_M2L_Helper(REL_COORD[M2L_Helper_Type].size(), RealVec(2*nfreq_)); std::vector<AlignedVec> matrix_M2L(REL_COORD[M2L_Type].size(), AlignedVec(fft_size)); // create fft plan RealVec fftw_in(nconv_); RealVec fftw_out(2*nfreq_); int dim[3] = {n1, n1, n1}; fft_plan plan = fft_plan_dft(3, dim, reinterpret_cast<fft_complex*>(fftw_in.data()), reinterpret_cast<fft_complex*>(fftw_out.data()), FFTW_FORWARD, FFTW_ESTIMATE); RealVec trg_coord(3,0); for (int l=1; l<this->depth+1; ++l) { // compute M2L kernel matrix, perform DFT #pragma omp parallel for for (size_t i=0; i<REL_COORD[M2L_Helper_Type].size(); ++i) { real_t coord[3]; for (int d=0; d<3; d++) { coord[d] = REL_COORD[M2L_Helper_Type][i][d] * this->r0 * powf(0.5, l-1); // relative coords } RealVec conv_coord = convolution_grid(this->p, this->r0, l, coord); // convolution grid ComplexVec conv_value(nconv_); // potentials on convolution grid this->kernel_matrix(conv_coord, trg_coord, conv_value); fft_execute_dft(plan, reinterpret_cast<fft_complex*>(conv_value.data()), reinterpret_cast<fft_complex*>(matrix_M2L_Helper[i].data())); } // convert M2L_Helper to M2L and reorder data layout to improve locality #pragma omp parallel for for (size_t i=0; i<REL_COORD[M2L_Type].size(); ++i) { for (int j=0; j<NCHILD*NCHILD; j++) { // loop over child's relative positions int child_rel_idx = M2L_INDEX_MAP[i][j]; if (child_rel_idx != -1) { for (int k=0; k<nfreq_; k++) { // loop over frequencies int new_idx = k*(2*NCHILD*NCHILD) + 2*j; matrix_M2L[i][new_idx+0] = matrix_M2L_Helper[child_rel_idx][k*2+0] / nconv_; // real matrix_M2L[i][new_idx+1] = matrix_M2L_Helper[child_rel_idx][k*2+1] / nconv_; // imag } } } } // write to file for(auto& vec : matrix_M2L) { file.write(reinterpret_cast<char*>(vec.data()), fft_size*sizeof(real_t)); } } // destroy fftw plan fft_destroy_plan(plan); } template <> void Fmm<real_t>::fft_up_equiv(std::vector<size_t>& fft_offset, RealVec& all_up_equiv, AlignedVec& fft_in) { int& nsurf_ = this->nsurf; int& nconv_ = this->nconv; int& nfreq_ = this->nfreq; int n1 = this->p * 2; auto map = generate_surf2conv_up(p); size_t fft_size = 2 * NCHILD * nfreq_; AlignedVec fftw_in(nconv_ * NCHILD); AlignedVec fftw_out(fft_size); int dim[3] = {n1, n1, n1}; fft_plan plan = fft_plan_many_dft_r2c(3, dim, NCHILD, (real_t*)&fftw_in[0], nullptr, 1, nconv_, (fft_complex*)(&fftw_out[0]), nullptr, 1, nfreq_, FFTW_ESTIMATE); #pragma omp parallel for for (size_t node_idx=0; node_idx<fft_offset.size(); node_idx++) { RealVec buffer(fft_size, 0); RealVec equiv_t(NCHILD*nconv_, 0.); real_t* up_equiv = &all_up_equiv[fft_offset[node_idx]]; // offset ptr of node's 8 child's up_equiv in all_up_equiv, size=8*nsurf_ real_t* up_equiv_f = &fft_in[fft_size*node_idx]; // offset ptr of node_idx in fft_in vector, size=fftsize for (int k=0; k<nsurf_; k++) { size_t idx = map[k]; for (int j=0; j<NCHILD; j++) equiv_t[idx+j*nconv_] = up_equiv[j*nsurf_+k]; } fft_execute_dft_r2c(plan, &equiv_t[0], (fft_complex*)&buffer[0]); for (int k=0; k<nfreq_; k++) { for (int j=0; j<NCHILD; j++) { up_equiv_f[2*(NCHILD*k+j)+0] = buffer[2*(nfreq_*j+k)+0]; up_equiv_f[2*(NCHILD*k+j)+1] = buffer[2*(nfreq_*j+k)+1]; } } } fft_destroy_plan(plan); } template <> void Fmm<complex_t>::fft_up_equiv(std::vector<size_t>& fft_offset, ComplexVec& all_up_equiv, AlignedVec& fft_in) { int& nsurf_ = this->nsurf; int& nconv_ = this->nconv; int& nfreq_ = this->nfreq; int n1 = this->p * 2; auto map = generate_surf2conv_up(p); size_t fft_size = 2 * NCHILD * nfreq_; ComplexVec fftw_in(nconv_ * NCHILD); AlignedVec fftw_out(fft_size); int dim[3] = {n1, n1, n1}; fft_plan plan = fft_plan_many_dft(3, dim, NCHILD, reinterpret_cast<fft_complex*>(&fftw_in[0]), nullptr, 1, nconv_, (fft_complex*)(&fftw_out[0]), nullptr, 1, nfreq_, FFTW_FORWARD, FFTW_ESTIMATE); #pragma omp parallel for for (size_t node_idx=0; node_idx<fft_offset.size(); node_idx++) { RealVec buffer(fft_size, 0); ComplexVec equiv_t(NCHILD*nconv_, complex_t(0.,0.)); complex_t* up_equiv = &all_up_equiv[fft_offset[node_idx]]; // offset ptr of node's 8 child's up_equiv in all_up_equiv, size=8*nsurf_ real_t* up_equiv_f = &fft_in[fft_size*node_idx]; // offset ptr of node_idx in fft_in vector, size=fftsize for (int k=0; k<nsurf_; k++) { size_t idx = map[k]; for (int j=0; j<NCHILD; j++) equiv_t[idx+j*nconv_] = up_equiv[j*nsurf_+k]; } fft_execute_dft(plan, reinterpret_cast<fft_complex*>(&equiv_t[0]), (fft_complex*)&buffer[0]); for (int k=0; k<nfreq_; k++) { for (int j=0; j<NCHILD; j++) { up_equiv_f[2*(NCHILD*k+j)+0] = buffer[2*(nfreq_*j+k)+0]; up_equiv_f[2*(NCHILD*k+j)+1] = buffer[2*(nfreq_*j+k)+1]; } } } fft_destroy_plan(plan); } template <> void Fmm<real_t>::ifft_dn_check(std::vector<size_t>& ifft_offset, AlignedVec& fft_out, RealVec& all_dn_equiv) { int& nsurf_ = this->nsurf; int& nconv_ = this->nconv; int& nfreq_ = this->nfreq; int n1 = this->p * 2; auto map = generate_surf2conv_dn(p); size_t fft_size = 2 * NCHILD * nfreq_; AlignedVec fftw_in(fft_size); AlignedVec fftw_out(nconv_ * NCHILD); int dim[3] = {n1, n1, n1}; fft_plan plan = fft_plan_many_dft_c2r(3, dim, NCHILD, (fft_complex*)(&fftw_in[0]), nullptr, 1, nfreq_, (real_t*)(&fftw_out[0]), nullptr, 1, nconv_, FFTW_ESTIMATE); #pragma omp parallel for for (size_t node_idx=0; node_idx<ifft_offset.size(); node_idx++) { RealVec buffer0(fft_size, 0); RealVec buffer1(fft_size, 0); real_t* dn_check_f = &fft_out[fft_size*node_idx]; // offset ptr for node_idx in fft_out vector, size=fftsize real_t* dn_equiv = &all_dn_equiv[ifft_offset[node_idx]]; // offset ptr for node_idx's child's dn_equiv in all_dn_equiv, size=numChilds * nsurf_ for (int k=0; k<nfreq_; k++) for (int j=0; j<NCHILD; j++) { buffer0[2*(nfreq_*j+k)+0] = dn_check_f[2*(NCHILD*k+j)+0]; buffer0[2*(nfreq_*j+k)+1] = dn_check_f[2*(NCHILD*k+j)+1]; } fft_execute_dft_c2r(plan, (fft_complex*)&buffer0[0], (real_t*)(&buffer1[0])); for (int k=0; k<nsurf_; k++) { size_t idx = map[k]; for (int j=0; j<NCHILD; j++) dn_equiv[nsurf_*j+k] += buffer1[idx+j*nconv_]; } } fft_destroy_plan(plan); } template <> void Fmm<complex_t>::ifft_dn_check(std::vector<size_t>& ifft_offset, AlignedVec& fft_out, ComplexVec& all_dn_equiv) { int& nsurf_ = this->nsurf; int& nconv_ = this->nconv; int& nfreq_ = this->nfreq; int n1 = this->p * 2; auto map = generate_surf2conv_dn(p); size_t fft_size = 2 * NCHILD * nfreq_; AlignedVec fftw_in(fft_size); ComplexVec fftw_out(nconv_*NCHILD); int dim[3] = {n1, n1, n1}; fft_plan plan = fft_plan_many_dft(3, dim, NCHILD, (fft_complex*)(&fftw_in[0]), nullptr, 1, nfreq_, reinterpret_cast<fft_complex*>(&fftw_out[0]), nullptr, 1, nconv_, FFTW_BACKWARD, FFTW_ESTIMATE); #pragma omp parallel for for (size_t node_idx=0; node_idx<ifft_offset.size(); node_idx++) { RealVec buffer0(fft_size, 0); ComplexVec buffer1(NCHILD*nconv_, 0); real_t* dn_check_f = &fft_out[fft_size*node_idx]; complex_t* dn_equiv = &all_dn_equiv[ifft_offset[node_idx]]; for (int k=0; k<nfreq_; k++) for (int j=0; j<NCHILD; j++) { buffer0[2*(nfreq_*j+k)+0] = dn_check_f[2*(NCHILD*k+j)+0]; buffer0[2*(nfreq_*j+k)+1] = dn_check_f[2*(NCHILD*k+j)+1]; } fft_execute_dft(plan, (fft_complex*)&buffer0[0], reinterpret_cast<fft_complex*>(&buffer1[0])); for (int k=0; k<nsurf_; k++) { size_t idx = map[k]; for (int j=0; j<NCHILD; j++) dn_equiv[nsurf_*j+k]+=buffer1[idx+j*nconv_]; } } fft_destroy_plan(plan); } } // end namespace #endif
innerProd.c
/* The MIT License (MIT) Copyright (c) 2017 Tim Warburton, Noel Chalmers, Jesse Chan, Ali Karakus 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. */ extern "C" void FUNC(innerProd)( const dlong & Nblocks, const dlong & N, const dlong & offset, const dfloat * __restrict__ cpu_a, const dfloat * __restrict__ cpu_b, dfloat * __restrict__ cpu_ab){ dfloat ab = 0; #ifdef __NEKRS__OMP__ #pragma omp parallel for reduction(+:ab) #endif for(int i=0;i<N;++i){ const dfloat ai = cpu_a[i+offset]; const dfloat bi = cpu_b[i]; ab += ai*bi; } cpu_ab[0] = ab; }
interpolate_op.h
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve. 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. */ #pragma once #include <string> #include <vector> #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/operators/math/math_function.h" namespace paddle { namespace operators { template <typename T, size_t D, int MajorType = Eigen::RowMajor, typename IndexType = Eigen::DenseIndex> using EigenTensor = framework::EigenTensor<T, D, MajorType, IndexType>; using Tensor = framework::Tensor; template <typename T> static void NearestNeighborInterpolate(const Tensor& input, Tensor* output, const float ratio_h, const float ratio_w, const int n, const int c, const int out_h, const int out_w, const bool align_corners) { auto input_t = EigenTensor<T, 4>::From(input); auto output_t = EigenTensor<T, 4>::From(*output); for (int k = 0; k < out_h; k++) { // loop for images int in_k = (align_corners) ? static_cast<int>(ratio_h * k + 0.5) : static_cast<int>(ratio_h * k); for (int l = 0; l < out_w; l++) { int in_l = (align_corners) ? static_cast<int>(ratio_w * l + 0.5) : static_cast<int>(ratio_w * l); for (int i = 0; i < n; i++) { // loop for batches for (int j = 0; j < c; j++) { // loop for channels output_t(i, j, k, l) = input_t(i, j, in_k, in_l); } } } } } template <typename T> static void BilinearInterpolation(const Tensor& input, Tensor* output, const float ratio_h, const float ratio_w, const int in_h, const int in_w, const int n, const int c, const int out_h, const int out_w, const bool align_corners, const bool align_mode) { auto input_t = EigenTensor<T, 4>::From(input); auto output_t = EigenTensor<T, 4>::From(*output); bool align_flag = (align_mode == 0 && !align_corners); std::vector<int> vy_n, vy_s; std::vector<float> vd_n, vd_s; vy_n.reserve(out_h); vy_s.reserve(out_h); vd_n.reserve(out_h); vd_s.reserve(out_h); #ifdef PADDLE_WITH_MKLML #pragma omp parallel for #endif for (int k = 0; k < out_h; k++) { int y_n = align_flag ? static_cast<int>(ratio_h * (k + 0.5) - 0.5) : static_cast<int>(ratio_h * k); y_n = (y_n > 0) ? y_n : 0; int y_s = (y_n + 1) < (in_h - 1) ? (y_n + 1) : (in_h - 1); float idx_src_y = ratio_h * (k + 0.5) - 0.5; idx_src_y = (idx_src_y > 0) ? idx_src_y : 0; float d_n = align_flag ? idx_src_y - y_n : ratio_h * k - y_n; float d_s = 1.f - d_n; { vy_n[k] = y_n; vy_s[k] = y_s; vd_n[k] = d_n; vd_s[k] = d_s; } } std::vector<int> vx_w, vx_e; std::vector<float> vd_w, vd_e; vx_w.reserve(out_w); vx_e.reserve(out_w); vd_w.reserve(out_w); vd_e.reserve(out_w); #ifdef PADDLE_WITH_MKLML #pragma omp parallel for #endif for (int l = 0; l < out_w; l++) { int x_w = (align_mode == 0 && !align_corners) ? static_cast<int>(ratio_w * (l + 0.5) - 0.5) : static_cast<int>(ratio_w * l); x_w = (x_w > 0) ? x_w : 0; int x_e = (x_w + 1) < (in_w - 1) ? (x_w + 1) : (in_w - 1); float idx_src_x = ratio_w * (l + 0.5) - 0.5; idx_src_x = (idx_src_x > 0) ? idx_src_x : 0; float d_w = align_flag ? idx_src_x - x_w : ratio_w * l - x_w; float d_e = 1.f - d_w; { vx_w[l] = x_w; vx_e[l] = x_e; vd_w[l] = d_w; vd_e[l] = d_e; } } #ifdef PADDLE_WITH_MKLML #pragma omp parallel for collapse(4) #endif for (int i = 0; i < n; i++) { // loop for batches for (int j = 0; j < c; j++) { // loop for channels for (int k = 0; k < out_h; k++) { // loop for images for (int l = 0; l < out_w; l++) { // bilinear interpolation T out_t = input_t(i, j, vy_n[k], vx_w[l]) * vd_s[k] * vd_e[l] + input_t(i, j, vy_s[k], vx_w[l]) * vd_n[k] * vd_e[l] + input_t(i, j, vy_n[k], vx_e[l]) * vd_s[k] * vd_w[l] + input_t(i, j, vy_s[k], vx_e[l]) * vd_n[k] * vd_w[l]; output_t(i, j, k, l) = out_t; } } } } } template <typename T> static void TrilinearInterpolation( const Tensor& input, Tensor* output, const float ratio_d, const float ratio_h, const float ratio_w, const int in_d, const int in_h, const int in_w, const int n, const int c, const int out_d, const int out_h, const int out_w, const bool align_corners, const bool align_mode) { auto input_t = EigenTensor<T, 5>::From(input); auto output_t = EigenTensor<T, 5>::From(*output); bool align_flag = (align_mode == 0 && !align_corners); std::vector<int> vt_f, vt_b; std::vector<float> vd_f, vd_b; vt_f.reserve(out_d); vt_b.reserve(out_d); vd_f.reserve(out_d); vd_b.reserve(out_d); #ifdef PADDLE_WITH_MKLML #pragma omp parallel for #endif for (int j = 0; j < out_d; j++) { int t_f = align_flag ? static_cast<int>(ratio_d * (j + 0.5) - 0.5) : static_cast<int>(ratio_d * j); t_f = (t_f > 0) ? t_f : 0; int t_b = (t_f + 1) < (in_d - 1) ? (t_f + 1) : (in_d - 1); float idx_src_t = ratio_d * (j + 0.5) - 0.5; idx_src_t = (idx_src_t > 0) ? idx_src_t : 0; float d_f = align_flag ? idx_src_t - t_f : ratio_d * j - t_f; float d_b = 1.f - d_f; { vt_f[j] = t_f; vt_b[j] = t_b; vd_f[j] = d_f; vd_b[j] = d_b; } } std::vector<int> vy_n, vy_s; std::vector<float> vd_n, vd_s; vy_n.reserve(out_h); vy_s.reserve(out_h); vd_n.reserve(out_h); vd_s.reserve(out_h); #ifdef PADDLE_WITH_MKLML #pragma omp parallel for #endif for (int k = 0; k < out_h; k++) { int y_n = align_flag ? static_cast<int>(ratio_h * (k + 0.5) - 0.5) : static_cast<int>(ratio_h * k); y_n = (y_n > 0) ? y_n : 0; int y_s = (y_n + 1) < (in_h - 1) ? (y_n + 1) : (in_h - 1); float idx_src_y = ratio_h * (k + 0.5) - 0.5; idx_src_y = (idx_src_y > 0) ? idx_src_y : 0; float d_n = align_flag ? idx_src_y - y_n : ratio_h * k - y_n; float d_s = 1.f - d_n; { vy_n[k] = y_n; vy_s[k] = y_s; vd_n[k] = d_n; vd_s[k] = d_s; } } std::vector<int> vx_w, vx_e; std::vector<float> vd_w, vd_e; vx_w.reserve(out_w); vx_e.reserve(out_w); vd_w.reserve(out_w); vd_e.reserve(out_w); #ifdef PADDLE_WITH_MKLML #pragma omp parallel for #endif for (int l = 0; l < out_w; l++) { int x_w = (align_mode == 0 && !align_corners) ? static_cast<int>(ratio_w * (l + 0.5) - 0.5) : static_cast<int>(ratio_w * l); x_w = (x_w > 0) ? x_w : 0; int x_e = (x_w + 1) < (in_w - 1) ? (x_w + 1) : (in_w - 1); float idx_src_x = ratio_w * (l + 0.5) - 0.5; idx_src_x = (idx_src_x > 0) ? idx_src_x : 0; float d_w = align_flag ? idx_src_x - x_w : ratio_w * l - x_w; float d_e = 1.f - d_w; { vx_w[l] = x_w; vx_e[l] = x_e; vd_w[l] = d_w; vd_e[l] = d_e; } } #ifdef PADDLE_WITH_MKLML #pragma omp parallel for collapse(5) #endif for (int b = 0; b < n; b++) { // loop for batches for (int i = 0; i < c; i++) { // loop for channels for (int j = 0; j < out_d; j++) { // loop for D, H, W for (int k = 0; k < out_h; k++) { for (int l = 0; l < out_w; l++) { // trilinear interpolation T out_t = input_t(b, i, vt_f[j], vy_n[k], vx_w[l]) * vd_b[j] * vd_s[k] * vd_e[l] + input_t(b, i, vt_f[j], vy_n[k], vx_e[l]) * vd_b[j] * vd_s[k] * vd_w[l] + input_t(b, i, vt_f[j], vy_s[k], vx_w[l]) * vd_b[j] * vd_n[k] * vd_e[l] + input_t(b, i, vt_f[j], vy_s[k], vx_e[l]) * vd_b[j] * vd_n[k] * vd_w[l] + input_t(b, i, vt_b[j], vy_n[k], vx_w[l]) * vd_f[j] * vd_s[k] * vd_e[l] + input_t(b, i, vt_b[j], vy_n[k], vx_e[l]) * vd_f[j] * vd_s[k] * vd_w[l] + input_t(b, i, vt_b[j], vy_s[k], vx_w[l]) * vd_f[j] * vd_n[k] * vd_e[l] + input_t(b, i, vt_b[j], vy_s[k], vx_e[l]) * vd_f[j] * vd_n[k] * vd_w[l]; output_t(b, i, j, k, l) = out_t; } } } } } } template <typename T> static void NearestNeighborInterpolateGrad( const Tensor& output_grad, Tensor* input_grad, const float ratio_h, const float ratio_w, const int n, const int c, const int out_h, const int out_w, const bool align_corners) { auto input_grad_t = EigenTensor<T, 4>::From(*input_grad); auto output_grad_t = EigenTensor<T, 4>::From(output_grad); for (int k = 0; k < out_h; k++) { // loop for images int in_k = (align_corners) ? static_cast<int>(ratio_h * k + 0.5) : static_cast<int>(ratio_h * k); for (int l = 0; l < out_w; l++) { int in_l = (align_corners) ? static_cast<int>(ratio_w * l + 0.5) : static_cast<int>(ratio_w * l); for (int i = 0; i < n; i++) { // loop for batches for (int j = 0; j < c; j++) { // loop for channels input_grad_t(i, j, in_k, in_l) += output_grad_t(i, j, k, l); } } } } } template <typename T> static void BilinearInterpolationGrad(const Tensor& output_grad, Tensor* input_grad, const float ratio_h, const float ratio_w, const int in_h, const int in_w, const int n, const int c, const int out_h, const int out_w, const bool align_corners, const int align_mode) { auto input_grad_t = EigenTensor<T, 4>::From(*input_grad); auto output_grad_t = EigenTensor<T, 4>::From(output_grad); bool align_flag = (align_mode == 0 && !align_corners); for (int k = 0; k < out_h; k++) { // loop for images int y_n = align_flag ? static_cast<int>(ratio_h * (k + 0.5) - 0.5) : static_cast<int>(ratio_h * k); y_n = (y_n > 0) ? y_n : 0; int y_s = (y_n + 1) < (in_h - 1) ? (y_n + 1) : (in_h - 1); float idx_src_y = ratio_h * (k + 0.5) - 0.5; idx_src_y = (idx_src_y > 0) ? idx_src_y : 0; float d_n = align_flag ? idx_src_y - y_n : ratio_h * k - y_n; float d_s = 1.f - d_n; for (int l = 0; l < out_w; l++) { int x_w = align_flag ? static_cast<int>(ratio_w * (l + 0.5) - 0.5) : static_cast<int>(ratio_w * l); x_w = (x_w > 0) ? x_w : 0; int x_e = (x_w + 1) < (in_w - 1) ? (x_w + 1) : (in_w - 1); float idx_src_x = ratio_w * (l + 0.5) - 0.5; idx_src_x = (idx_src_x > 0) ? idx_src_x : 0; float d_w = align_flag ? idx_src_x - x_w : ratio_w * l - x_w; float d_e = 1.f - d_w; for (int i = 0; i < n; i++) { // loop for batches for (int j = 0; j < c; j++) { // loop for channels // bilinear interpolation grad const T grad = output_grad_t(i, j, k, l); input_grad_t(i, j, y_n, x_w) += static_cast<T>(grad * d_s * d_e); input_grad_t(i, j, y_s, x_w) += static_cast<T>(grad * d_n * d_e); input_grad_t(i, j, y_n, x_e) += static_cast<T>(grad * d_s * d_w); input_grad_t(i, j, y_s, x_e) += static_cast<T>(grad * d_n * d_w); } } } } } template <typename T> static void TrilinearInterpolationGrad( const Tensor& output_grad, Tensor* input_grad, const float ratio_d, const float ratio_h, const float ratio_w, const int in_d, const int in_h, const int in_w, const int n, const int c, const int out_d, const int out_h, const int out_w, const bool align_corners, const int align_mode) { auto input_grad_t = EigenTensor<T, 5>::From(*input_grad); auto output_grad_t = EigenTensor<T, 5>::From(output_grad); bool align_flag = (align_mode == 0 && !align_corners); for (int j = 0; j < out_d; j++) { // loop for D int t_f = align_flag ? static_cast<int>(ratio_d * (j + 0.5) - 0.5) : static_cast<int>(ratio_d * j); t_f = (t_f > 0) ? t_f : 0; int t_b = (t_f + 1) < (in_d - 1) ? (t_f + 1) : (in_d - 1); float idx_src_t = ratio_d * (j + 0.5) - 0.5; idx_src_t = (idx_src_t > 0) ? idx_src_t : 0; float d_f = align_flag ? idx_src_t - t_f : ratio_d * j - t_f; float d_b = 1.f - d_f; for (int k = 0; k < out_h; k++) { // loop for H int y_n = align_flag ? static_cast<int>(ratio_h * (k + 0.5) - 0.5) : static_cast<int>(ratio_h * k); y_n = (y_n > 0) ? y_n : 0; int y_s = (y_n + 1) < (in_h - 1) ? (y_n + 1) : (in_h - 1); float idx_src_y = ratio_h * (k + 0.5) - 0.5; idx_src_y = (idx_src_y > 0) ? idx_src_y : 0; float d_n = align_flag ? idx_src_y - y_n : ratio_h * k - y_n; float d_s = 1.f - d_n; for (int l = 0; l < out_w; l++) { // loop for W int x_w = align_flag ? static_cast<int>(ratio_w * (l + 0.5) - 0.5) : static_cast<int>(ratio_w * l); x_w = (x_w > 0) ? x_w : 0; int x_e = (x_w + 1) < (in_w - 1) ? (x_w + 1) : (in_w - 1); float idx_src_x = ratio_w * (l + 0.5) - 0.5; idx_src_x = (idx_src_x > 0) ? idx_src_x : 0; float d_w = align_flag ? idx_src_x - x_w : ratio_w * l - x_w; float d_e = 1.f - d_w; for (int b = 0; b < n; b++) { // loop for batches for (int i = 0; i < c; i++) { // loop for channels // trilinear interpolation grad const T grad = output_grad_t(b, i, j, k, l); input_grad_t(b, i, t_f, y_n, x_w) += static_cast<T>(grad * d_b * d_s * d_e); input_grad_t(b, i, t_f, y_n, x_e) += static_cast<T>(grad * d_b * d_s * d_w); input_grad_t(b, i, t_f, y_s, x_w) += static_cast<T>(grad * d_b * d_n * d_e); input_grad_t(b, i, t_f, y_s, x_e) += static_cast<T>(grad * d_b * d_n * d_w); input_grad_t(b, i, t_b, y_n, x_w) += static_cast<T>(grad * d_f * d_s * d_e); input_grad_t(b, i, t_b, y_n, x_e) += static_cast<T>(grad * d_f * d_s * d_w); input_grad_t(b, i, t_b, y_s, x_w) += static_cast<T>(grad * d_f * d_n * d_e); input_grad_t(b, i, t_b, y_s, x_e) += static_cast<T>(grad * d_f * d_n * d_w); } } } } } } template <typename T> static void Interpolate2DCPUFwd(const framework::ExecutionContext& ctx, const Tensor& input, Tensor* output) { const int n = input.dims()[0]; const int c = input.dims()[1]; const int in_h = input.dims()[2]; const int in_w = input.dims()[3]; auto interp_method = ctx.Attr<std::string>("interp_method"); bool align_corners = ctx.Attr<bool>("align_corners"); int align_mode = ctx.Attr<int>("align_mode"); int out_h = ctx.Attr<int>("out_h"); int out_w = ctx.Attr<int>("out_w"); float scale = ctx.Attr<float>("scale"); if (scale > 0) { out_h = static_cast<int>(in_h * scale); out_w = static_cast<int>(in_w * scale); } auto out_size = ctx.Input<Tensor>("OutSize"); if (out_size != nullptr) { auto out_size_data = out_size->data<int>(); out_h = out_size_data[0]; out_w = out_size_data[1]; } output->mutable_data<T>({n, c, out_h, out_w}, ctx.GetPlace()); if (in_h == out_h && in_w == out_w) { framework::TensorCopy(input, ctx.GetPlace(), output); return; } float ratio_h = 0.f; float ratio_w = 0.f; if (out_h > 1) { ratio_h = (align_corners) ? static_cast<float>(in_h - 1) / (out_h - 1) : static_cast<float>(in_h) / out_h; } if (out_w > 1) { ratio_w = (align_corners) ? static_cast<float>(in_w - 1) / (out_w - 1) : static_cast<float>(in_w) / out_w; } if ("bilinear" == interp_method) { BilinearInterpolation<T>(input, output, ratio_h, ratio_w, in_h, in_w, n, c, out_h, out_w, align_corners, align_mode); } else if ("nearest" == interp_method) { NearestNeighborInterpolate<T>(input, output, ratio_h, ratio_w, n, c, out_h, out_w, align_corners); } } template <typename T> static void Interpolate3DCPUFwd(const framework::ExecutionContext& ctx, const Tensor& input, Tensor* output) { const int n = input.dims()[0]; const int c = input.dims()[1]; const int in_d = input.dims()[2]; const int in_h = input.dims()[3]; const int in_w = input.dims()[4]; auto interp_method = ctx.Attr<std::string>("interp_method"); bool align_corners = ctx.Attr<bool>("align_corners"); int align_mode = ctx.Attr<int>("align_mode"); int out_d = ctx.Attr<int>("out_d"); int out_h = ctx.Attr<int>("out_h"); int out_w = ctx.Attr<int>("out_w"); float scale = ctx.Attr<float>("scale"); if (scale > 0) { out_d = static_cast<int>(in_d * scale); out_h = static_cast<int>(in_h * scale); out_w = static_cast<int>(in_w * scale); } auto out_size = ctx.Input<Tensor>("OutSize"); if (out_size != nullptr) { auto out_size_data = out_size->data<int>(); out_d = out_size_data[0]; out_h = out_size_data[1]; out_w = out_size_data[2]; } output->mutable_data<T>({n, c, out_d, out_h, out_w}, ctx.GetPlace()); if (in_d == out_d && in_h == out_h && in_w == out_w) { framework::TensorCopy(input, ctx.GetPlace(), output); return; } float ratio_d = 0.f; float ratio_h = 0.f; float ratio_w = 0.f; if (out_d > 1) { ratio_d = (align_corners) ? static_cast<float>(in_d - 1) / (out_d - 1) : static_cast<float>(in_d) / out_d; } if (out_h > 1) { ratio_h = (align_corners) ? static_cast<float>(in_h - 1) / (out_h - 1) : static_cast<float>(in_h) / out_h; } if (out_w > 1) { ratio_w = (align_corners) ? static_cast<float>(in_w - 1) / (out_w - 1) : static_cast<float>(in_w) / out_w; } if ("trilinear" == interp_method) { TrilinearInterpolation<T>(input, output, ratio_d, ratio_h, ratio_w, in_d, in_h, in_w, n, c, out_d, out_h, out_w, align_corners, align_mode); } } template <typename T> static void Interpolate2DCPUBwd(const framework::ExecutionContext& ctx, Tensor* input_grad, const Tensor& output_grad) { auto* input = ctx.Input<Tensor>("X"); const int n = input->dims()[0]; const int c = input->dims()[1]; const int in_h = input->dims()[2]; const int in_w = input->dims()[3]; auto interp_method = ctx.Attr<std::string>("interp_method"); bool align_corners = ctx.Attr<bool>("align_corners"); int align_mode = ctx.Attr<int>("align_mode"); int out_h = ctx.Attr<int>("out_h"); int out_w = ctx.Attr<int>("out_w"); float scale = ctx.Attr<float>("scale"); if (scale > 0) { out_h = static_cast<int>(in_h * scale); out_w = static_cast<int>(in_w * scale); } auto out_size = ctx.Input<Tensor>("OutSize"); if (out_size != nullptr) { auto out_size_data = out_size->data<int>(); out_h = out_size_data[0]; out_w = out_size_data[1]; } input_grad->mutable_data<T>({n, c, in_h, in_w}, ctx.GetPlace()); auto& device_ctx = ctx.template device_context<platform::CPUDeviceContext>(); math::SetConstant<platform::CPUDeviceContext, T> zero; zero(device_ctx, input_grad, static_cast<T>(0.0)); if (in_h == out_h && in_w == out_w) { framework::TensorCopy(output_grad, ctx.GetPlace(), input_grad); return; } float ratio_h = 0.f; float ratio_w = 0.f; if (out_h > 1) { ratio_h = (align_corners) ? static_cast<float>(in_h - 1) / (out_h - 1) : static_cast<float>(in_h) / out_h; } if (out_w > 1) { ratio_w = (align_corners) ? static_cast<float>(in_w - 1) / (out_w - 1) : static_cast<float>(in_w) / out_w; } if ("bilinear" == interp_method) { BilinearInterpolationGrad<T>(output_grad, input_grad, ratio_h, ratio_w, in_h, in_w, n, c, out_h, out_w, align_corners, align_mode); } else if ("nearest" == interp_method) { NearestNeighborInterpolateGrad<T>(output_grad, input_grad, ratio_h, ratio_w, n, c, out_h, out_w, align_corners); } } template <typename T> static void Interpolate3DCPUBwd(const framework::ExecutionContext& ctx, Tensor* input_grad, const Tensor output_grad) { auto* input = ctx.Input<Tensor>("X"); const int n = input->dims()[0]; const int c = input->dims()[1]; const int in_d = input->dims()[2]; const int in_h = input->dims()[3]; const int in_w = input->dims()[4]; auto interp_method = ctx.Attr<std::string>("interp_method"); bool align_corners = ctx.Attr<bool>("align_corners"); int align_mode = ctx.Attr<int>("align_mode"); int out_d = ctx.Attr<int>("out_d"); int out_h = ctx.Attr<int>("out_h"); int out_w = ctx.Attr<int>("out_w"); float scale = ctx.Attr<float>("scale"); if (scale > 0) { out_d = static_cast<int>(in_d * scale); out_h = static_cast<int>(in_h * scale); out_w = static_cast<int>(in_w * scale); } auto out_size = ctx.Input<Tensor>("OutSize"); if (out_size != nullptr) { auto out_size_data = out_size->data<int>(); out_d = out_size_data[0]; out_h = out_size_data[1]; out_w = out_size_data[2]; } input_grad->mutable_data<T>({n, c, in_d, in_h, in_w}, ctx.GetPlace()); auto& device_ctx = ctx.template device_context<platform::CPUDeviceContext>(); math::SetConstant<platform::CPUDeviceContext, T> zero; zero(device_ctx, input_grad, static_cast<T>(0.0)); if (in_d == out_d && in_h == out_h && in_w == out_w) { framework::TensorCopy(output_grad, ctx.GetPlace(), input_grad); return; } float ratio_d = 0.f; float ratio_h = 0.f; float ratio_w = 0.f; if (out_d > 1) { ratio_d = (align_corners) ? static_cast<float>(in_d - 1) / (out_d - 1) : static_cast<float>(in_d) / out_d; } if (out_h > 1) { ratio_h = (align_corners) ? static_cast<float>(in_h - 1) / (out_h - 1) : static_cast<float>(in_h) / out_h; } if (out_w > 1) { ratio_w = (align_corners) ? static_cast<float>(in_w - 1) / (out_w - 1) : static_cast<float>(in_w) / out_w; } if ("trilinear" == interp_method) { TrilinearInterpolationGrad<T>(output_grad, input_grad, ratio_d, ratio_h, ratio_w, in_d, in_h, in_w, n, c, out_d, out_h, out_w, align_corners, align_mode); } } template <typename T> class InterpolateKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& ctx) const override { auto* input = ctx.Input<Tensor>("X"); auto* output = ctx.Output<Tensor>("Out"); auto input_dims = input->dims(); if (input_dims.size() == 4) { // 2D interpolation Interpolate2DCPUFwd<T>(ctx, *input, output); } else if (input_dims.size() == 5) { // 3D interpolation Interpolate3DCPUFwd<T>(ctx, *input, output); } } }; template <typename T> class InterpolateGradKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& ctx) const override { auto* input_grad = ctx.Output<Tensor>(framework::GradVarName("X")); auto* output_grad = ctx.Input<Tensor>(framework::GradVarName("Out")); auto output_grad_dims = output_grad->dims(); if (output_grad_dims.size() == 4) { // 2D interpolation grad Interpolate2DCPUBwd<T>(ctx, input_grad, *output_grad); } else if (output_grad_dims.size() == 5) { // 3D interpolation grad Interpolate3DCPUBwd<T>(ctx, input_grad, *output_grad); } } }; } // namespace operators } // namespace paddle
LAGraph_Sort3.c
//------------------------------------------------------------------------------ // LAGraph_Sort3: sort a 3-by-n list of integers, using A[0:2][ ] as the key //------------------------------------------------------------------------------ // LAGraph, (c) 2021 by The LAGraph Contributors, All Rights Reserved. // SPDX-License-Identifier: BSD-2-Clause // See additional acknowledgments in the LICENSE file, // or contact permission@sei.cmu.edu for the full terms. // Contributed by Timothy A. Davis, Texas A&M University //------------------------------------------------------------------------------ // A parallel mergesort of an array of 3-by-n integers. Each key // consists of three integers. #define LG_FREE_ALL LAGraph_Free ((void **) &W, NULL) ; #include "LG_internal.h" //------------------------------------------------------------------------------ // prototype only needed for LAGraph_Sort3 //------------------------------------------------------------------------------ void LG_msort_3b_create_merge_tasks ( // output: int64_t *LG_RESTRICT L_task, // L_task [t0...t0+ntasks-1] computed int64_t *LG_RESTRICT L_len, // L_len [t0...t0+ntasks-1] computed int64_t *LG_RESTRICT R_task, // R_task [t0...t0+ntasks-1] computed int64_t *LG_RESTRICT R_len, // R_len [t0...t0+ntasks-1] computed int64_t *LG_RESTRICT S_task, // S_task [t0...t0+ntasks-1] computed // input: const int t0, // first task tid to create const int ntasks, // # of tasks to create const int64_t pS_start, // merge into S [pS_start...] const int64_t *LG_RESTRICT L_0, // Left = L [pL_start...pL_end-1] const int64_t *LG_RESTRICT L_1, const int64_t *LG_RESTRICT L_2, const int64_t pL_start, const int64_t pL_end, const int64_t *LG_RESTRICT R_0, // Right = R [pR_start...pR_end-1] const int64_t *LG_RESTRICT R_1, const int64_t *LG_RESTRICT R_2, const int64_t pR_start, const int64_t pR_end ) ; //------------------------------------------------------------------------------ // LG_msort_3b_binary_search: binary search for the pivot //------------------------------------------------------------------------------ // The Pivot value is Y [pivot], and a binary search for the Pivot is made in // the array X [p_pstart...p_end-1], which is sorted in non-decreasing order on // input. The return value is pleft, where // // X [p_start ... pleft-1] <= Pivot and // X [pleft ... p_end-1] >= Pivot holds. // // pleft is returned in the range p_start to p_end. If pleft is p_start, then // the Pivot is smaller than all entries in X [p_start...p_end-1], and the left // list X [p_start...pleft-1] is empty. If pleft is p_end, then the Pivot is // larger than all entries in X [p_start...p_end-1], and the right list X // [pleft...p_end-1] is empty. static int64_t LG_msort_3b_binary_search // return pleft ( const int64_t *LG_RESTRICT Y_0, // Pivot is Y [pivot] const int64_t *LG_RESTRICT Y_1, const int64_t *LG_RESTRICT Y_2, const int64_t pivot, const int64_t *LG_RESTRICT X_0, // search in X [p_start..p_end_-1] const int64_t *LG_RESTRICT X_1, const int64_t *LG_RESTRICT X_2, const int64_t p_start, const int64_t p_end ) { //-------------------------------------------------------------------------- // find where the Pivot appears in X //-------------------------------------------------------------------------- // binary search of X [p_start...p_end-1] for the Pivot int64_t pleft = p_start ; int64_t pright = p_end - 1 ; while (pleft < pright) { int64_t pmiddle = (pleft + pright) >> 1 ; // less = (X [pmiddle] < Pivot) bool less = LG_lt_3 (X_0, X_1, X_2, pmiddle, Y_0, Y_1, Y_2, pivot) ; pleft = less ? (pmiddle+1) : pleft ; pright = less ? pright : pmiddle ; } // binary search is narrowed down to a single item // or it has found the list is empty: ASSERT (pleft == pright || pleft == pright + 1) ; // If found is true then X [pleft == pright] == Pivot. If duplicates // appear then X [pleft] is any one of the entries equal to the Pivot // in the list. If found is false then // X [p_start ... pleft-1] < Pivot and // X [pleft+1 ... p_end-1] > Pivot holds. // The value X [pleft] may be either < or > Pivot. bool found = (pleft == pright) && LG_eq_3 (X_0, X_1, X_2, pleft, Y_0, Y_1, Y_2, pivot) ; // Modify pleft and pright: if (!found && (pleft == pright)) { if (LG_lt_3 (X_0, X_1, X_2, pleft, Y_0, Y_1, Y_2, pivot)) { pleft++ ; } else { // pright++ ; // (not needed) } } //-------------------------------------------------------------------------- // return result //-------------------------------------------------------------------------- // If found is false then // X [p_start ... pleft-1] < Pivot and // X [pleft ... p_end-1] > Pivot holds, // and pleft-1 == pright // If X has no duplicates, then whether or not Pivot is found, // X [p_start ... pleft-1] < Pivot and // X [pleft ... p_end-1] >= Pivot holds. // If X has duplicates, then whether or not Pivot is found, // X [p_start ... pleft-1] <= Pivot and // X [pleft ... p_end-1] >= Pivot holds. return (pleft) ; } //------------------------------------------------------------------------------ // LG_msort_3b_create_merge_tasks //------------------------------------------------------------------------------ // Recursively constructs ntasks tasks to merge two arrays, Left and Right, // into Sresult, where Left is L [pL_start...pL_end-1], Right is R // [pR_start...pR_end-1], and Sresult is S [pS_start...pS_start+total_work-1], // and where total_work is the total size of Left and Right. // // Task tid will merge L [L_task [tid] ... L_task [tid] + L_len [tid] - 1] and // R [R_task [tid] ... R_task [tid] + R_len [tid] -1] into the merged output // array S [S_task [tid] ... ]. The task tids created are t0 to // t0+ntasks-1. void LG_msort_3b_create_merge_tasks ( // output: int64_t *LG_RESTRICT L_task, // L_task [t0...t0+ntasks-1] computed int64_t *LG_RESTRICT L_len, // L_len [t0...t0+ntasks-1] computed int64_t *LG_RESTRICT R_task, // R_task [t0...t0+ntasks-1] computed int64_t *LG_RESTRICT R_len, // R_len [t0...t0+ntasks-1] computed int64_t *LG_RESTRICT S_task, // S_task [t0...t0+ntasks-1] computed // input: const int t0, // first task tid to create const int ntasks, // # of tasks to create const int64_t pS_start, // merge into S [pS_start...] const int64_t *LG_RESTRICT L_0, // Left = L [pL_start...pL_end-1] const int64_t *LG_RESTRICT L_1, const int64_t *LG_RESTRICT L_2, const int64_t pL_start, const int64_t pL_end, const int64_t *LG_RESTRICT R_0, // Right = R [pR_start...pR_end-1] const int64_t *LG_RESTRICT R_1, const int64_t *LG_RESTRICT R_2, const int64_t pR_start, const int64_t pR_end ) { //-------------------------------------------------------------------------- // get problem size //-------------------------------------------------------------------------- int64_t nleft = pL_end - pL_start ; // size of Left array int64_t nright = pR_end - pR_start ; // size of Right array int64_t total_work = nleft + nright ; // total work to do ASSERT (ntasks >= 1) ; ASSERT (total_work > 0) ; //-------------------------------------------------------------------------- // create the tasks //-------------------------------------------------------------------------- if (ntasks == 1) { //---------------------------------------------------------------------- // a single task will merge all of Left and Right into Sresult //---------------------------------------------------------------------- L_task [t0] = pL_start ; L_len [t0] = nleft ; R_task [t0] = pR_start ; R_len [t0] = nright ; S_task [t0] = pS_start ; } else { //---------------------------------------------------------------------- // partition the Left and Right arrays for multiple merge tasks //---------------------------------------------------------------------- int64_t pleft, pright ; if (nleft >= nright) { // split Left in half, and search for its pivot in Right pleft = (pL_end + pL_start) >> 1 ; pright = LG_msort_3b_binary_search ( L_0, L_1, L_2, pleft, R_0, R_1, R_2, pR_start, pR_end) ; } else { // split Right in half, and search for its pivot in Left pright = (pR_end + pR_start) >> 1 ; pleft = LG_msort_3b_binary_search ( R_0, R_1, R_2, pright, L_0, L_1, L_2, pL_start, pL_end) ; } //---------------------------------------------------------------------- // partition the tasks according to the work of each partition //---------------------------------------------------------------------- // work0 is the total work in the first partition int64_t work0 = (pleft - pL_start) + (pright - pR_start) ; int ntasks0 = (int) round ((double) ntasks * (((double) work0) / ((double) total_work))) ; // ensure at least one task is assigned to each partition ntasks0 = LAGRAPH_MAX (ntasks0, 1) ; ntasks0 = LAGRAPH_MIN (ntasks0, ntasks-1) ; int ntasks1 = ntasks - ntasks0 ; //---------------------------------------------------------------------- // assign ntasks0 to the first half //---------------------------------------------------------------------- // ntasks0 tasks merge L [pL_start...pleft-1] and R [pR_start..pright-1] // into the result S [pS_start...work0-1]. LG_msort_3b_create_merge_tasks ( L_task, L_len, R_task, R_len, S_task, t0, ntasks0, pS_start, L_0, L_1, L_2, pL_start, pleft, R_0, R_1, R_2, pR_start, pright) ; //---------------------------------------------------------------------- // assign ntasks1 to the second half //---------------------------------------------------------------------- // ntasks1 tasks merge L [pleft...pL_end-1] and R [pright...pR_end-1] // into the result S [pS_start+work0...pS_start+total_work]. int t1 = t0 + ntasks0 ; // first task id of the second set of tasks int64_t pS_start1 = pS_start + work0 ; // 2nd set starts here in S LG_msort_3b_create_merge_tasks ( L_task, L_len, R_task, R_len, S_task, t1, ntasks1, pS_start1, L_0, L_1, L_2, pleft, pL_end, R_0, R_1, R_2, pright, pR_end) ; } } //------------------------------------------------------------------------------ // LG_msort_3b_merge: merge two sorted lists via a single thread //------------------------------------------------------------------------------ // merge Left [0..nleft-1] and Right [0..nright-1] into S [0..nleft+nright-1] */ static void LG_msort_3b_merge ( int64_t *LG_RESTRICT S_0, // output of length nleft + nright int64_t *LG_RESTRICT S_1, int64_t *LG_RESTRICT S_2, const int64_t *LG_RESTRICT Left_0, // left input of length nleft const int64_t *LG_RESTRICT Left_1, const int64_t *LG_RESTRICT Left_2, const int64_t nleft, const int64_t *LG_RESTRICT Right_0, // right input of length nright const int64_t *LG_RESTRICT Right_1, const int64_t *LG_RESTRICT Right_2, const int64_t nright ) { int64_t p, pleft, pright ; // merge the two inputs, Left and Right, while both inputs exist for (p = 0, pleft = 0, pright = 0 ; pleft < nleft && pright < nright ; p++) { if (LG_lt_3 (Left_0, Left_1, Left_2, pleft, Right_0, Right_1, Right_2, pright)) { // S [p] = Left [pleft++] S_0 [p] = Left_0 [pleft] ; S_1 [p] = Left_1 [pleft] ; S_2 [p] = Left_2 [pleft] ; pleft++ ; } else { // S [p] = Right [pright++] S_0 [p] = Right_0 [pright] ; S_1 [p] = Right_1 [pright] ; S_2 [p] = Right_2 [pright] ; pright++ ; } } // either input is exhausted; copy the remaining list into S if (pleft < nleft) { int64_t nremaining = (nleft - pleft) ; memcpy (S_0 + p, Left_0 + pleft, nremaining * sizeof (int64_t)) ; memcpy (S_1 + p, Left_1 + pleft, nremaining * sizeof (int64_t)) ; memcpy (S_2 + p, Left_2 + pleft, nremaining * sizeof (int64_t)) ; } else if (pright < nright) { int64_t nremaining = (nright - pright) ; memcpy (S_0 + p, Right_0 + pright, nremaining * sizeof (int64_t)) ; memcpy (S_1 + p, Right_1 + pright, nremaining * sizeof (int64_t)) ; memcpy (S_2 + p, Right_2 + pright, nremaining * sizeof (int64_t)) ; } } //------------------------------------------------------------------------------ // LAGraph_Sort3: parallel mergesort //------------------------------------------------------------------------------ int LAGraph_Sort3 ( // input/output: int64_t *A_0, // size n array int64_t *A_1, // size n array int64_t *A_2, // size n array // input: const int64_t n, char *msg ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- LG_CLEAR_MSG ; int64_t *LG_RESTRICT W = NULL ; LG_ASSERT (A_0 != NULL, GrB_NULL_POINTER) ; LG_ASSERT (A_1 != NULL, GrB_NULL_POINTER) ; LG_ASSERT (A_2 != NULL, GrB_NULL_POINTER) ; //-------------------------------------------------------------------------- // handle small problems with a single thread //-------------------------------------------------------------------------- int nthreads = LG_nthreads_outer * LG_nthreads_inner ; // # threads to use if (nthreads <= 1 || n <= LG_BASECASE) { // sequential quicksort LG_qsort_3 (A_0, A_1, A_2, n) ; return (GrB_SUCCESS) ; } //-------------------------------------------------------------------------- // determine # of tasks //-------------------------------------------------------------------------- // determine the number of levels to create, which must always be an // even number. The # of levels is chosen to ensure that the # of leaves // of the task tree is between 4*nthreads and 16*nthreads. // 2 to 4 threads: 4 levels, 16 qsort leaves // 5 to 16 threads: 6 levels, 64 qsort leaves // 17 to 64 threads: 8 levels, 256 qsort leaves // 65 to 256 threads: 10 levels, 1024 qsort leaves // 256 to 1024 threads: 12 levels, 4096 qsort leaves // ... int k = (int) (2 + 2 * ceil (log2 ((double) nthreads) / 2)) ; int ntasks = 1 << k ; //-------------------------------------------------------------------------- // allocate workspace //-------------------------------------------------------------------------- LG_TRY (LAGraph_Malloc ((void **) &W, 3*n + 6*ntasks + 1, sizeof (int64_t), msg)) ; int64_t *T = W ; int64_t *LG_RESTRICT W_0 = T ; T += n ; int64_t *LG_RESTRICT W_1 = T ; T += n ; int64_t *LG_RESTRICT W_2 = T ; T += n ; int64_t *LG_RESTRICT L_task = T ; T += ntasks ; int64_t *LG_RESTRICT L_len = T ; T += ntasks ; int64_t *LG_RESTRICT R_task = T ; T += ntasks ; int64_t *LG_RESTRICT R_len = T ; T += ntasks ; int64_t *LG_RESTRICT S_task = T ; T += ntasks ; int64_t *LG_RESTRICT Slice = T ; T += (ntasks+1) ; //-------------------------------------------------------------------------- // partition and sort the leaves //-------------------------------------------------------------------------- LG_eslice (Slice, n, ntasks) ; int tid ; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (tid = 0 ; tid < ntasks ; tid++) { int64_t leaf = Slice [tid] ; int64_t leafsize = Slice [tid+1] - leaf ; LG_qsort_3 (A_0 + leaf, A_1 + leaf, A_2 + leaf, leafsize) ; } //-------------------------------------------------------------------------- // merge each level //-------------------------------------------------------------------------- int nt = 1 ; for ( ; k >= 2 ; k -= 2) { //---------------------------------------------------------------------- // merge level k into level k-1, from A into W //---------------------------------------------------------------------- // this could be done in parallel if ntasks was large for (int tid = 0 ; tid < ntasks ; tid += 2*nt) { // create 2*nt tasks to merge two A sublists into one W sublist LG_msort_3b_create_merge_tasks ( L_task, L_len, R_task, R_len, S_task, tid, 2*nt, Slice [tid], A_0, A_1, A_2, Slice [tid], Slice [tid+nt], A_0, A_1, A_2, Slice [tid+nt], Slice [tid+2*nt]) ; } #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (tid = 0 ; tid < ntasks ; tid++) { // merge A [pL...pL+nL-1] and A [pR...pR+nR-1] into W [pS..] int64_t pL = L_task [tid], nL = L_len [tid] ; int64_t pR = R_task [tid], nR = R_len [tid] ; int64_t pS = S_task [tid] ; LG_msort_3b_merge ( W_0 + pS, W_1 + pS, W_2 + pS, A_0 + pL, A_1 + pL, A_2 + pL, nL, A_0 + pR, A_1 + pR, A_2 + pR, nR) ; } nt = 2*nt ; //---------------------------------------------------------------------- // merge level k-1 into level k-2, from W into A //---------------------------------------------------------------------- // this could be done in parallel if ntasks was large for (int tid = 0 ; tid < ntasks ; tid += 2*nt) { // create 2*nt tasks to merge two W sublists into one A sublist LG_msort_3b_create_merge_tasks ( L_task, L_len, R_task, R_len, S_task, tid, 2*nt, Slice [tid], W_0, W_1, W_2, Slice [tid], Slice [tid+nt], W_0, W_1, W_2, Slice [tid+nt], Slice [tid+2*nt]) ; } #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (tid = 0 ; tid < ntasks ; tid++) { // merge A [pL...pL+nL-1] and A [pR...pR+nR-1] into W [pS..] int64_t pL = L_task [tid], nL = L_len [tid] ; int64_t pR = R_task [tid], nR = R_len [tid] ; int64_t pS = S_task [tid] ; LG_msort_3b_merge ( A_0 + pS, A_1 + pS, A_2 + pS, W_0 + pL, W_1 + pL, W_2 + pL, nL, W_0 + pR, W_1 + pR, W_2 + pR, nR) ; } nt = 2*nt ; } //-------------------------------------------------------------------------- // free workspace and return result //-------------------------------------------------------------------------- LG_FREE_ALL ; return (GrB_SUCCESS) ; }
mSortParaDebug.c
#include<stdlib.h> #include<stdio.h> #include<string.h> #include "omp.h" #define MAX_SIZE 10000//number of elements // function to generate an array void generate_list(int * x, int n) { int i,j = MAX_SIZE; for (i = 0; i < n; i++){ x[i] = j; j--; } } // merge function void merge(int * X, int n, int * tmp) { int i = 0; int j = n/2; int ti = 0; while (i<n/2 && j<n) { if (X[i] < X[j]) { tmp[ti] = X[i]; ti++; i++; } else { tmp[ti] = X[j]; ti++; j++; } } while (i<n/2) { /* finish up lower half */ tmp[ti] = X[i]; ti++; i++; } while (j<n) { /* finish up upper half */ tmp[ti] = X[j]; ti++; j++; } memcpy(X, tmp, n*sizeof(int)); } void mergeSortSeq(int arr[], int size, int temp[]){ if (size < 2){ return; } // Sort first and second halves mergeSortSeq(arr, size/2, temp); mergeSortSeq(arr+size/2, size-size/2, temp); merge(arr, size,temp); } void mergeSortPara(int arr[], int size, int temp[] , int threads){ printf("MergeSortPara ID:%d\n", omp_get_thread_num()); if (threads > 1){ // Sort first and second halves #pragma omp task mergeSortPara(arr, size/2, temp, threads/2); #pragma omp task mergeSortPara((arr+size/2), (size-size/2), (temp+size/2) , (threads-threads/2)); #pragma omp taskwait merge(arr, size, temp); }else if (threads == 1){ printf("MergeSortSeq ID:%d\n", omp_get_thread_num()); mergeSortSeq(arr,size,temp); } } void printArray(int A[], int size){ int i; for (i=0; i < size; i++) printf("%d ", A[i]); printf("\n"); } //function to check if array is sorted to be called after merge Sort int isSorted(int a[], int size){ int i,r = 0; for(i=0;i<size-1;i++){ if(a[i]>a[i+1]){ r = 1; printf("a[%d]=%d,a[%d]=%d \n",i,a[i],i+1,a[i+1]); break; } } return r; } int main(int argc , char * argv[]){ int threads; int *data = malloc(MAX_SIZE*sizeof(int)); int *temp = malloc(MAX_SIZE*sizeof(int)); int n = MAX_SIZE; double start,stop; printf("Given array is \n"); generate_list(data, n); printArray(data, n); threads = omp_get_num_threads(); printf("Before parallel zone: No of threads: %d ID:%d \n",threads,omp_get_thread_num()); start = omp_get_wtime(); #pragma omp parallel { threads = omp_get_num_threads(); printf("Threads: %d ID:%d \n",threads,omp_get_thread_num()); #pragma omp single { printf("single ID:%d\n",omp_get_thread_num()); mergeSortPara(data, n, temp ,threads); } } stop = omp_get_wtime(); printf("\nSorted array is \n"); printArray(data, n); int r = isSorted(data,n); if(r != 0){ printf("O array não está ordenado"); } printf("\nMergeSort Time: %f\n",(stop-start)); free(temp); free(data); return 0; }
libperf_thread.c
/** * Copyright (C) NVIDIA 2021. ALL RIGHTS RESERVED. * * See file LICENSE for terms. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <ucs/debug/log.h> #include <ucs/arch/bitops.h> #include <ucs/sys/module.h> #include <ucs/sys/string.h> #include <tools/perf/lib/libperf_int.h> #include <string.h> #include <unistd.h> #if _OPENMP # include <omp.h> static ucs_status_t ucx_perf_thread_run_test(void* arg) { ucx_perf_thread_context_t* tctx = (ucx_perf_thread_context_t*) arg; /* a single thread context */ ucx_perf_result_t* result = &tctx->result; ucx_perf_context_t* perf = &tctx->perf; ucx_perf_params_t* params = &perf->params; ucs_status_t status; /* new threads need explicit device association */ status = perf->send_allocator->init(perf); if (status != UCS_OK) { goto out; } if (perf->send_allocator != perf->recv_allocator) { status = perf->recv_allocator->init(perf); if (status != UCS_OK) { goto out; } } if (params->warmup_iter > 0) { ucx_perf_set_warmup(perf, params); status = ucx_perf_funcs[params->api].run(perf); ucx_perf_funcs[params->api].barrier(perf); if (UCS_OK != status) { goto out; } ucx_perf_test_prepare_new_run(perf, params); } /* Run test */ #pragma omp barrier status = ucx_perf_funcs[params->api].run(perf); ucx_perf_funcs[params->api].barrier(perf); if (UCS_OK != status) { goto out; } ucx_perf_calc_result(perf, result); out: return status; } static void ucx_perf_thread_report_aggregated_results(ucx_perf_context_t *perf) { ucx_perf_thread_context_t* tctx = perf->ucp.tctx; /* all the thread contexts on perf */ unsigned i, thread_count = perf->params.thread_count; double lat_sum_total_avegare = 0.0; ucx_perf_result_t agg_result; agg_result.iters = tctx[0].result.iters; agg_result.bytes = tctx[0].result.bytes; agg_result.elapsed_time = tctx[0].result.elapsed_time; agg_result.bandwidth.total_average = 0.0; agg_result.bandwidth.percentile = 0.0; /* Undefined since used only for latency calculations */ agg_result.latency.total_average = 0.0; agg_result.msgrate.total_average = 0.0; agg_result.msgrate.percentile = 0.0; /* Undefined since used only for latency calculations */ /* when running with multiple threads, the moment average value is * undefined since we don't capture the values of the last iteration */ agg_result.msgrate.moment_average = 0.0; agg_result.bandwidth.moment_average = 0.0; agg_result.latency.moment_average = 0.0; agg_result.latency.percentile = 0.0; /* in case of multiple threads, we have to aggregate the results so that the * final output of the result would show the performance numbers that were * collected from all the threads. * BW and message rate values will be the sum of their values from all * the threads, while the latency value is the average latency from the * threads. */ for (i = 0; i < thread_count; i++) { agg_result.bandwidth.total_average += tctx[i].result.bandwidth.total_average; agg_result.msgrate.total_average += tctx[i].result.msgrate.total_average; lat_sum_total_avegare += tctx[i].result.latency.total_average; } agg_result.latency.total_average = lat_sum_total_avegare / thread_count; rte_call(perf, report, &agg_result, perf->params.report_arg, "", 1, 1); } ucs_status_t ucx_perf_thread_spawn(ucx_perf_context_t *perf, ucx_perf_result_t* result) { ucx_perf_thread_context_t* tctx = perf->ucp.tctx; /* all the thread contexts on perf */ int ti, thread_count = perf->params.thread_count; ucs_status_t* statuses; ucs_status_t status; omp_set_num_threads(thread_count); statuses = calloc(thread_count, sizeof(ucs_status_t)); if (statuses == NULL) { status = UCS_ERR_NO_MEMORY; goto out; } #pragma omp parallel private(ti) { ti = omp_get_thread_num(); tctx[ti].status = ucx_perf_thread_run_test((void*)&tctx[ti]); } status = UCS_OK; for (ti = 0; ti < thread_count; ti++) { if (UCS_OK != tctx[ti].status) { ucs_error("Thread %d failed to run test: %s", tctx[ti].tid, ucs_status_string(tctx[ti].status)); status = tctx[ti].status; } } ucx_perf_thread_report_aggregated_results(perf); free(statuses); out: return status; } #else ucs_status_t ucx_perf_thread_spawn(ucx_perf_context_t *perf, ucx_perf_result_t* result) { ucs_error("Invalid test parameter (thread mode requested without OpenMP capabilities)"); return UCS_ERR_INVALID_PARAM; } #endif /* _OPENMP */
GB_bitmap_assign_M_col_template.c
//------------------------------------------------------------------------------ // GB_bitmap_assign_M_col_template: traverse M for GB_COL_ASSIGN //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // M is a (C->vlen)-by-1 hypersparse or sparse matrix, for // GrB_Row_assign (if C is CSR) or GrB_Col_assign (if C is CSC). // C is bitmap/full. M is sparse/hyper, and can be jumbled. { const int64_t *restrict kfirst_Mslice = M_ek_slicing ; const int64_t *restrict klast_Mslice = M_ek_slicing + M_ntasks ; const int64_t *restrict pstart_Mslice = M_ek_slicing + M_ntasks * 2 ; int64_t jC = J [0] ; int tid ; #pragma omp parallel for num_threads(M_nthreads) schedule(dynamic,1) \ reduction(+:cnvals) for (tid = 0 ; tid < M_ntasks ; tid++) { int64_t kfirst = kfirst_Mslice [tid] ; int64_t klast = klast_Mslice [tid] ; int64_t task_cnvals = 0 ; //---------------------------------------------------------------------- // traverse over M (:,kfirst:klast) //---------------------------------------------------------------------- for (int64_t k = kfirst ; k <= klast ; k++) { //------------------------------------------------------------------ // find the part of M(:,k) for this task //------------------------------------------------------------------ ASSERT (k == 0) ; ASSERT (GBH (Mh, k) == 0) ; int64_t pM_start, pM_end ; GB_get_pA (&pM_start, &pM_end, tid, k, kfirst, klast, pstart_Mslice, Mp, mvlen) ; //------------------------------------------------------------------ // traverse over M(:,0), the kth vector of M //------------------------------------------------------------------ // for col_assign: M is a single vector, jC = J [0] for (int64_t pM = pM_start ; pM < pM_end ; pM++) { bool mij = GB_mcast (Mx, pM, msize) ; if (mij) { int64_t iC = Mi [pM] ; int64_t pC = iC + jC * cvlen ; GB_MASK_WORK (pC) ; } } } cnvals += task_cnvals ; } }
ioc-ummap-bandwidth-mpi.c
//mpicc ioc-ummap-bandwidth-mpi.c -I$HOME/test-rdma/usr2/include -lioc-client -lummap-io -L$HOME/test-rdma/usr2/lib -Wl,-rpath,$HOME/test-rdma/usr2/lib -o ioc-ummap-bandwidth-mpi #include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdbool.h> #include <ioc-client.h> #include <time.h> #include <mpi.h> #include <ummap/ummap.h> #include <omp.h> const size_t total_size = 4UL*1024UL*1024UL*1024UL; const size_t ref_repeat = 10; static inline double timespec_diff(struct timespec *a, struct timespec *b) { struct timespec result; result.tv_sec = a->tv_sec - b->tv_sec; result.tv_nsec = a->tv_nsec - b->tv_nsec; if (result.tv_nsec < 0) { --result.tv_sec; result.tv_nsec += 1000000000L; } return (double)result.tv_sec + (double)result.tv_nsec / (double)1e9; } void make_ummap_read(ioc_client_t * client, char * buffer0, size_t size, size_t seg_size, size_t repeat) { //get MPI rank int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); size_t threads = omp_get_max_threads(); //calc base size_t base = rank * size; //ummap ummap_driver_t * driver = ummap_driver_create_ioc(client, 10, 20, rank == 0); ummap_policy_t * policy = ummap_policy_create_fifo(2 * threads * seg_size, true); int flags = 0; if (seg_size <= 131072) flags |= UMMAP_THREAD_UNSAFE; char * buffer = ummap(NULL, size, seg_size, base, PROT_READ|PROT_WRITE, flags, driver, policy, NULL); //access size_t r; size_t offset; size_t sum = 0; for (r = 0 ; r < repeat ; r++) { #pragma omp parallel for for (offset = 0 ; offset < size ; offset +=seg_size) sum+=buffer[offset]; } //unmap umunmap(buffer, false); } void make_ummap_write(ioc_client_t * client, char * buffer0, size_t size, size_t seg_size, size_t repeat) { //get MPI rank int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); size_t threads = omp_get_max_threads(); //calc base size_t base = rank * size; //ummap ummap_driver_t * driver = ummap_driver_create_ioc(client, 10, 20, rank == 0); ummap_policy_t * policy = ummap_policy_create_fifo(2 * threads * seg_size, true); int flags = 0; if (seg_size <= 131072) flags |= UMMAP_THREAD_UNSAFE; char * buffer = ummap(NULL, size, seg_size, base, PROT_READ|PROT_WRITE, UMMAP_NO_FIRST_READ|flags, driver, policy, NULL); //access size_t r; size_t offset; for (r = 0 ; r < repeat ; r++) { ummap_skip_first_read(buffer); #pragma omp parallel for for (offset = 0 ; offset < size ; offset += seg_size) buffer[offset]++; } //unmap umunmap(buffer, false); } void make_write(ioc_client_t * client, char * buffer, size_t size, size_t seg_size, size_t repeat) { //get MPI rank int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); //do size_t r; size_t offset; size_t base = rank * size; for (r = 0 ; r < repeat ; r++) for (offset = 0 ; offset < size ; offset += seg_size) ioc_client_obj_write(client, 10, 20, buffer, seg_size, base + offset); } void make_read(ioc_client_t * client, char * buffer, size_t size, size_t seg_size, size_t repeat) { //get MPI rank int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); //do size_t r; size_t offset; size_t base = rank * size; for (r = 0 ; r < repeat ; r++) for (offset = 0 ; offset < size ; offset += seg_size) ioc_client_obj_read(client, 10, 20, buffer, seg_size, base + offset); } double calc_bandwidth(ioc_client_t * client, char * buffer, size_t size, size_t seg_size, size_t repeat, void(*op)(ioc_client_t * client, char * buffer, size_t size, size_t seg_size, size_t repeat)) { //wait all MPI_Barrier(MPI_COMM_WORLD); //start struct timespec start, stop; clock_gettime(CLOCK_MONOTONIC, &start); //call to all op(client, buffer, size, seg_size, repeat); //wait all MPI_Barrier(MPI_COMM_WORLD); //stop clock_gettime(CLOCK_MONOTONIC, &stop); //compute time double t = timespec_diff(&stop, &start); //calc bandwidth double bw = (double)repeat * (double)total_size / 1024.0 / 1024.0 / 1024.0 / t; //ok return return bw; } int main(int argc, char ** argv) { //check args if (argc < 2) { fprintf(stderr, "%s {ioc_server_ip}\n", argv[0]); return EXIT_FAILURE; } //init MPI MPI_Init(&argc, &argv); //init ummapio ummap_init(); //get MPI infos int rank; int world; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &world); //connect to server ioc_client_t * client = ioc_client_init(argv[1], "8556"); //cal size size_t size = total_size / world; //allocate buffer char * buffer = malloc(size); memset(buffer, 0, size); //to ensure object is created, make a first round trip //calc_bandwidth(client, buffer, size, 8*1024*1024, ref_repeat, make_read); //calc_bandwidth(client, buffer, size, 8*1024*1024, ref_repeat, make_write); calc_bandwidth(client, buffer, size, 8*1024*1024, ref_repeat, make_ummap_read); calc_bandwidth(client, buffer, size, 8*1024*1024, ref_repeat, make_ummap_write); //header if (rank == 0) { printf("#total_size=%f GB\n", (double)total_size/1024.0/1024.0/1024.0); printf("#world_size=%d\n", world); printf("#seg_size (bytes) read (GB/s) twrite(GB/s)\n"); } //loop on all size size_t seg_size = 16 * 1024 * 1024; for ( ; seg_size >= 4096 ; seg_size /= 2) { //calc repeat size_t repeat = ref_repeat; //if (seg_size > 256*1024) // repeat *= 2; //measure read //double read_bw = calc_bandwidth(client, buffer, size, seg_size, repeat, make_read); //double write_bw = calc_bandwidth(client, buffer, size, seg_size, repeat, make_write); double read_bw = calc_bandwidth(client, buffer, size, seg_size, repeat, make_ummap_read); double write_bw = calc_bandwidth(client, buffer, size, seg_size, repeat, make_ummap_write); //print if (rank == 0) printf("%zu %f %f\n", seg_size, read_bw, write_bw); } //close connection ioc_client_fini(client); //fini ummap ummap_finalize(); //fin i mpi MPI_Finalize(); //ok return EXIT_SUCCESS; }
GB_binop__rminus_fp64.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 Generated/ folder, do not edit it (auto-generated). #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__rminus_fp64) // A.*B function (eWiseMult): GB (_AemultB) // A.*B function (eWiseMult): GB (_AemultB_02__rminus_fp64) // A.*B function (eWiseMult): GB (_AemultB_03__rminus_fp64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__rminus_fp64) // A*D function (colscale): GB (_AxD__rminus_fp64) // D*A function (rowscale): GB (_DxB__rminus_fp64) // C+=B function (dense accum): GB (_Cdense_accumB__rminus_fp64) // C+=b function (dense accum): GB (_Cdense_accumb__rminus_fp64) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__rminus_fp64) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__rminus_fp64) // C=scalar+B GB (_bind1st__rminus_fp64) // C=scalar+B' GB (_bind1st_tran__rminus_fp64) // C=A+scalar GB (_bind2nd__rminus_fp64) // C=A'+scalar GB (_bind2nd_tran__rminus_fp64) // C type: double // A type: double // B,b type: double // BinaryOp: cij = (bij - aij) #define GB_ATYPE \ double #define GB_BTYPE \ double #define GB_CTYPE \ double // 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) \ double aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ double bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ double 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, i, j) \ z = (y - x) ; // 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_RMINUS || GxB_NO_FP64 || GxB_NO_RMINUS_FP64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB (_Cdense_ewise3_accum__rminus_fp64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__rminus_fp64) ( 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__rminus_fp64) ( 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__rminus_fp64) ( 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 double double bwork = (*((double *) 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__rminus_fp64) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else double *restrict Cx = (double *) 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__rminus_fp64) ( 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 double *restrict Cx = (double *) 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__rminus_fp64) ( 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 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) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__rminus_fp64) ( 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_01_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__rminus_fp64) ( 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_03__rminus_fp64) ( 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_03_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__rminus_fp64) ( 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__rminus_fp64) ( 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 anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else double *Cx = (double *) Cx_output ; double x = (*((double *) x_input)) ; double *Bx = (double *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; double bij = Bx [p] ; Cx [p] = (bij - x) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__rminus_fp64) ( 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 ; double *Cx = (double *) Cx_output ; double *Ax = (double *) Ax_input ; double y = (*((double *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; double aij = Ax [p] ; Cx [p] = (y - aij) ; } 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) \ { \ double aij = Ax [pA] ; \ Cx [pC] = (aij - x) ; \ } GrB_Info GB (_bind1st_tran__rminus_fp64) ( 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 \ double #if GB_DISABLE return (GrB_NO_VALUE) ; #else double x = (*((const double *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ double } //------------------------------------------------------------------------------ // 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) \ { \ double aij = Ax [pA] ; \ Cx [pC] = (y - aij) ; \ } GrB_Info GB (_bind2nd_tran__rminus_fp64) ( 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 double y = (*((const double *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
task_codegen.c
// RUN: %clang_cc1 -no-opaque-pointers -verify -triple x86_64-apple-darwin10 -fopenmp -fopenmp-version=50 -x c -emit-llvm %s -o - | FileCheck %s // RUN: %clang_cc1 -no-opaque-pointers -fopenmp -fopenmp-version=50 -x c -triple x86_64-apple-darwin10 -emit-pch -o %t %s // RUN: %clang_cc1 -no-opaque-pointers -fopenmp -fopenmp-version=50 -x c -triple x86_64-apple-darwin10 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s // RUN: %clang_cc1 -no-opaque-pointers -verify -triple x86_64-apple-darwin10 -fopenmp-simd -fopenmp-version=50 -x c -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s // RUN: %clang_cc1 -no-opaque-pointers -fopenmp-simd -fopenmp-version=50 -x c -triple x86_64-apple-darwin10 -emit-pch -o %t %s // RUN: %clang_cc1 -no-opaque-pointers -fopenmp-simd -fopenmp-version=50 -x c -triple x86_64-apple-darwin10 -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY0 %s // SIMD-ONLY0-NOT: {{__kmpc|__tgt}} // expected-no-diagnostics #ifndef HEADER #define HEADER typedef void *omp_depend_t; typedef __UINTPTR_TYPE__ omp_event_handle_t; void foo(void); // CHECK-LABEL: @main int main(void) { omp_depend_t d, x; omp_event_handle_t evt; int a, *b; // CHECK: [[D_ADDR:%.+]] = alloca i8*, // CHECK: [[X_ADDR:%.+]] = alloca i8*, // CHECK: [[EVT_ADDR:%.+]] = alloca i64, // CHECK: [[A_ADDR:%.+]] = alloca i32, // CHECK: [[DEPOBJ_SIZE_ADDR:%.+]] = alloca i64, // CHECK: [[DEPOBJ_SIZE_ADDR1:%.+]] = alloca i64, // CHECK: = alloca i64, // CHECK: [[DEP_COUNTER_ADDR:%.+]] = alloca i64, // CHECK: [[GTID:%.+]] = call i32 @__kmpc_global_thread_num( // CHECK: [[ALLOC:%.+]] = call i8* @__kmpc_omp_task_alloc(%struct.ident_t* @{{.+}}, i32 [[GTID]], i32 65, i64 48, i64 0, i32 (i32, i8*)* bitcast (i32 (i32, [[PRIVATES_TY:%.+]]*)* [[TASK_ENTRY:@.+]] to i32 (i32, i8*)*)) // CHECK: [[EVT_VAL:%.+]] = call i8* @__kmpc_task_allow_completion_event(%struct.ident_t* @{{.+}}, i32 [[GTID]], i8* [[ALLOC]]) // CHECK: [[CAST_EVT_VAL:%.+]] = ptrtoint i8* [[EVT_VAL]] to i64 // CHECK: store i64 [[CAST_EVT_VAL]], i64* [[EVT_ADDR]], align 8 // CHECK: [[DATA:%.+]] = bitcast i8* [[ALLOC]] to [[PRIVATES_TY]]* // CHECK: [[D_ADDR_CAST:%.+]] = bitcast i8** [[D_ADDR]] to %struct.kmp_depend_info** // CHECK: [[D_DEP:%.+]] = load %struct.kmp_depend_info*, %struct.kmp_depend_info** [[D_ADDR_CAST]], align 8 // CHECK: [[D_DEP_BASE:%.+]] = getelementptr %struct.kmp_depend_info, %struct.kmp_depend_info* [[D_DEP]], i{{.+}} -1 // CHECK: [[D_DEP_BASE_SIZE:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[D_DEP_BASE]], i{{.+}} 0, i{{.+}} 0 // CHECK: [[SIZE1:%.+]] = load i64, i64* [[D_DEP_BASE_SIZE]], align 8 // CHECK-DAG: store i64 0, i64* [[DEPOBJ_SIZE_ADDR]], align 8 // CHECK: [[SZ:%.+]] = load i64, i64* [[DEPOBJ_SIZE_ADDR]], align 8 // CHECK: [[SIZE:%.+]] = add nuw i64 [[SZ]], [[SIZE1]] // CHECK: store i64 [[SIZE]], i64* [[DEPOBJ_SIZE_ADDR]], align 8 // CHECK: [[X_ADDR_CAST:%.+]] = bitcast i8** [[X_ADDR]] to %struct.kmp_depend_info** // CHECK: [[X_DEP:%.+]] = load %struct.kmp_depend_info*, %struct.kmp_depend_info** [[X_ADDR_CAST]], align 8 // CHECK: [[X_DEP_BASE:%.+]] = getelementptr %struct.kmp_depend_info, %struct.kmp_depend_info* [[X_DEP]], i{{.+}} -1 // CHECK: [[X_DEP_BASE_SIZE:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[X_DEP_BASE]], i{{.+}} 0, i{{.+}} 0 // CHECK: [[SIZE2:%.+]] = load i64, i64* [[X_DEP_BASE_SIZE]], align 8 // CHECK-DAG: store i64 0, i64* [[DEPOBJ_SIZE_ADDR1]], align 8 // CHECK: [[SZ:%.+]] = load i64, i64* [[DEPOBJ_SIZE_ADDR1]], align 8 // CHECK: [[SIZE3:%.+]] = add nuw i64 [[SZ]], [[SIZE2]] // CHECK: store i64 [[SIZE3]], i64* [[DEPOBJ_SIZE_ADDR1]], align 8 // CHECK: [[SZ:%.+]] = load i64, i64* [[DEPOBJ_SIZE_ADDR]], align 8 // CHECK: [[SZ1:%.+]] = load i64, i64* [[DEPOBJ_SIZE_ADDR1]], align 8 // CHECK: [[SIZE1:%.+]] = add nuw i64 0, [[SZ]] // CHECK: [[SIZE2:%.+]] = add nuw i64 [[SIZE1]], [[SZ1]] // CHECK: [[SIZE:%.+]] = add nuw i64 [[SIZE2]], 2 // CHECK: [[SV:%.+]] = call i8* @llvm.stacksave() // CHECK: store i8* [[SV]], i8** [[SV_ADDR:%.+]], align 8 // CHECK: [[VLA:%.+]] = alloca %struct.kmp_depend_info, i64 [[SIZE]], // CHECK: [[SIZE32:%.+]] = trunc i64 [[SIZE]] to i32 // CHECK: [[VLA0:%.+]] = getelementptr %struct.kmp_depend_info, %struct.kmp_depend_info* [[VLA]], i64 0 // CHECK: [[BASE_ADDR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[VLA0]], i{{.+}} 0, i{{.+}} 0 // CHECK: [[A_ADDR_CAST:%.+]] = ptrtoint i32* [[A_ADDR]] to i64 // CHECK: store i64 [[A_ADDR_CAST]], i64* [[BASE_ADDR]], align 16 // CHECK: [[SIZE_ADDR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[VLA0]], i{{.+}} 0, i{{.+}} 1 // CHECK: store i64 4, i64* [[SIZE_ADDR]], align 8 // CHECK: [[FLAGS_ADDR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[VLA0]], i{{.+}} 0, i{{.+}} 2 // CHECK: store i8 1, i8* [[FLAGS_ADDR]], align 1 // CHECK: [[A:%.+]] = load i32, i32* [[A_ADDR]], align 4 // CHECK: [[A_CAST:%.+]] = sext i32 [[A]] to i64 // CHECK: [[SZ1:%.+]] = mul nuw i64 24, [[A_CAST]] // CHECK: [[A:%.+]] = load i32, i32* [[A_ADDR]], align 4 // CHECK: [[A_CAST:%.+]] = sext i32 [[A]] to i64 // CHECK: [[SZ:%.+]] = mul nuw i64 [[SZ1]], [[A_CAST]] // CHECK: [[VLA1:%.+]] = getelementptr %struct.kmp_depend_info, %struct.kmp_depend_info* [[VLA]], i64 1 // CHECK: [[BASE_ADDR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[VLA1]], i{{.+}} 0, i{{.+}} 0 // CHECK: [[B_ADDR_CAST:%.+]] = ptrtoint i32** %{{.+}} to i64 // CHECK: store i64 [[B_ADDR_CAST]], i64* [[BASE_ADDR]], align 8 // CHECK: [[SIZE_ADDR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[VLA1]], i{{.+}} 0, i{{.+}} 1 // CHECK: store i64 [[SZ]], i64* [[SIZE_ADDR]], align 8 // CHECK: [[FLAGS_ADDR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[VLA1]], i{{.+}} 0, i{{.+}} 2 // CHECK: store i8 1, i8* [[FLAGS_ADDR]], align 8 // CHECK: store i64 2, i64* [[DEP_COUNTER_ADDR]], align 8 // CHECK: [[D_ADDR_CAST:%.+]] = bitcast i8** [[D_ADDR]] to %struct.kmp_depend_info** // CHECK: [[BC:%.+]] = load %struct.kmp_depend_info*, %struct.kmp_depend_info** [[D_ADDR_CAST]], align 8 // CHECK: [[PREV:%.+]] = getelementptr %struct.kmp_depend_info, %struct.kmp_depend_info* [[BC]], i64 -1 // CHECK: [[SIZE_ADDR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[PREV]], i{{.+}} 0, i{{.+}} 0 // CHECK: [[SIZE:%.+]] = load i64, i64* [[SIZE_ADDR]], align 8 // CHECK: [[BYTES:%.+]] = mul nuw i64 24, [[SIZE]] // CHECK: [[POS:%.+]] = load i64, i64* [[DEP_COUNTER_ADDR]], align 8 // CHECK: [[VLA_D:%.+]] = getelementptr %struct.kmp_depend_info, %struct.kmp_depend_info* [[VLA]], i64 [[POS]] // CHECK: [[DEST:%.+]] = bitcast %struct.kmp_depend_info* [[VLA_D]] to i8* // CHECK: [[SRC:%.+]] = bitcast %struct.kmp_depend_info* [[BC]] to i8* // CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* align {{.+}} [[DEST]], i8* align {{.+}} [[SRC]], i64 [[BYTES]], i1 false) // CHECK: [[ADD:%.+]] = add nuw i64 [[POS]], [[SIZE]] // CHECK: store i64 [[ADD]], i64* [[DEP_COUNTER_ADDR]], align 8 // CHECK: [[X_ADDR_CAST:%.+]] = bitcast i8** [[X_ADDR]] to %struct.kmp_depend_info** // CHECK: [[BC:%.+]] = load %struct.kmp_depend_info*, %struct.kmp_depend_info** [[X_ADDR_CAST]], align 8 // CHECK: [[PREV:%.+]] = getelementptr %struct.kmp_depend_info, %struct.kmp_depend_info* [[BC]], i64 -1 // CHECK: [[SIZE_ADDR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[PREV]], i{{.+}} 0, i{{.+}} 0 // CHECK: [[SIZE:%.+]] = load i64, i64* [[SIZE_ADDR]], align 8 // CHECK: [[BYTES:%.+]] = mul nuw i64 24, [[SIZE]] // CHECK: [[POS:%.+]] = load i64, i64* [[DEP_COUNTER_ADDR]], align 8 // CHECK: [[VLA_X:%.+]] = getelementptr %struct.kmp_depend_info, %struct.kmp_depend_info* [[VLA]], i64 [[POS]] // CHECK: [[DEST:%.+]] = bitcast %struct.kmp_depend_info* [[VLA_X]] to i8* // CHECK: [[SRC:%.+]] = bitcast %struct.kmp_depend_info* [[BC]] to i8* // CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* align {{.+}} [[DEST]], i8* align {{.+}} [[SRC]], i64 [[BYTES]], i1 false) // CHECK: [[ADD:%.+]] = add nuw i64 [[POS]], [[SIZE]] // CHECK: store i64 [[ADD]], i64* [[DEP_COUNTER_ADDR]], align 8 // CHECK: [[BC:%.+]] = bitcast %struct.kmp_depend_info* [[VLA]] to i8* // CHECK: call i32 @__kmpc_omp_task_with_deps(%struct.ident_t* @{{.+}}, i32 [[GTID]], i8* [[ALLOC]], i32 [[SIZE32]], i8* [[BC]], i32 0, i8* null) // CHECK: [[SV:%.+]] = load i8*, i8** [[SV_ADDR]], align 8 // CHECK: call void @llvm.stackrestore(i8* [[SV]]) #pragma omp task depend(in: a, ([3][a][a])&b) depend(depobj: d, x) detach(evt) { #pragma omp taskgroup { #pragma omp task foo(); } } // CHECK: ret i32 0 return 0; } // CHECK: call void @__kmpc_taskgroup( // CHECK: call i8* @__kmpc_omp_task_alloc( // CHECK: call i32 @__kmpc_omp_task( // CHECK: call void @__kmpc_end_taskgroup( // CHECK-LINE: @bar void bar(void) { int **a; // CHECK: call void @__kmpc_for_static_init_4( #pragma omp for for (int i = 0; i < 10; ++i) // CHECK: [[BUF:%.+]] = call i8* @__kmpc_omp_task_alloc(%struct.ident_t* @{{.+}}, i32 %{{.+}}, i32 1, i64 48, // CHECK: [[BC_BUF:%.+]] = bitcast i8* [[BUF]] to [[TT_WITH_PRIVS:%.+]]* // CHECK: [[PRIVS:%.+]] = getelementptr inbounds [[TT_WITH_PRIVS]], [[TT_WITH_PRIVS]]* [[BC_BUF]], i32 0, i32 1 // CHECK: [[I_PRIV:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}} [[PRIVS]], i32 0, i32 0 // CHECK: [[I:%.+]] = load i32, i32* [[I_ADDR:%.+]], // CHECK: store i32 %{{.+}}, i32* [[I_PRIV]], // NELEMS = 1 * ((i - 0 + 2 - 1) / 2); // CHECK: [[END:%.+]] = load i32, i32* [[I_ADDR]], // CHECK: [[EB_SUB:%.+]] = sub i32 [[END]], 0 // CHECK: [[EB_SUB_2_ADD:%.+]] = add i32 [[EB_SUB]], 2 // CHECK: [[EB_SUB_2_ADD_1_SUB:%.+]] = sub i32 [[EB_SUB_2_ADD]], 1 // CHECK: [[EB_SUB_2_ADD_1_SUB_2_DIV:%.+]] = udiv i32 [[EB_SUB_2_ADD_1_SUB]], 2 // CHECK: [[ELEMS:%.+]] = zext i32 [[EB_SUB_2_ADD_1_SUB_2_DIV]] to i64 // CHECK: [[NELEMS:%.+]] = mul nuw i64 [[ELEMS]], 1 // ITERATOR_TOTAL = NELEMS + 0; // CHECK: [[ITERATOR_TOTAL:%.+]] = add nuw i64 0, [[NELEMS]] // NELEMS = ITERATOR_TOTAL + non-iterator-deps (=0) // CHECK: [[TOTAL:%.+]] = add nuw i64 [[ITERATOR_TOTAL]], 0 // %struct.kmp_depend_info DEPS[TOTAL]; // CHECK: [[DEPS:%.+]] = alloca %struct.kmp_depend_info, i64 [[TOTAL]], // CHECK: [[NDEPS:%.+]] = trunc i64 [[TOTAL]] to i32 // i64 DEP_COUNTER = 0; // CHECK: store i64 0, i64* [[DEP_COUNTER_ADDR:%.+]], // NELEMS = ((i - 0 + 2 - 1) / 2); // CHECK: [[END:%.+]] = load i32, i32* [[I_ADDR]], // CHECK: [[EB_SUB:%.+]] = sub i32 [[END]], 0 // CHECK: [[EB_SUB_2_ADD:%.+]] = add i32 [[EB_SUB]], 2 // CHECK: [[EB_SUB_2_ADD_1_SUB:%.+]] = sub i32 [[EB_SUB_2_ADD]], 1 // CHECK: [[ELEMS:%.+]] = udiv i32 [[EB_SUB_2_ADD_1_SUB]], 2 // i32 COUNTER = 0; // CHECK: store i32 0, i32* [[COUNTER_ADDR:%.+]], // CHECK: br label %[[CONT:.+]] // Loop. // CHECK: [[CONT]]: // CHECK: [[COUNTER:%.+]] = load i32, i32* [[COUNTER_ADDR]], // CHECK: [[CMP:%.+]] = icmp ult i32 [[COUNTER]], [[ELEMS]] // CHECK: br i1 [[CMP]], label %[[BODY:.+]], label %[[EXIT:.+]] // CHECK: [[BODY]]: // k = 0 + 2*COUNTER; // CHECK: [[COUNTER:%.+]] = load i32, i32* [[COUNTER_ADDR]], // CHECK: [[C2_MUL:%.+]] = mul i32 [[COUNTER]], 2 // CHECK: [[C2_MUL_0_ADD:%.+]] = add i32 0, [[C2_MUL]] // CHECK: store i32 [[C2_MUL_0_ADD]], i32* [[K_ADDR:%.+]], // &a[k][i] // CHECK: [[A:%.+]] = load i32**, i32*** [[A_ADDR:%.+]], // CHECK: [[K:%.+]] = load i32, i32* [[K_ADDR]], // CHECK: [[IDX:%.+]] = zext i32 [[K]] to i64 // CHECK: [[AK_ADDR:%.+]] = getelementptr inbounds i32*, i32** [[A]], i64 [[IDX]] // CHECK: [[AK:%.+]] = load i32*, i32** [[AK_ADDR]], // CHECK: [[I:%.+]] = load i32, i32* [[I_ADDR]], // CHECK: [[IDX:%.+]] = sext i32 [[I]] to i64 // CHECK: [[AKI_ADDR:%.+]] = getelementptr inbounds i32, i32* [[AK]], i64 [[IDX]] // DEPS[DEP_COUNTER].base_addr = &a[k][i]; // CHECK: [[DEP_COUNTER:%.+]] = load i64, i64* [[DEP_COUNTER_ADDR]], // CHECK: [[DEPS_DC:%.+]] = getelementptr %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEPS]], i64 [[DEP_COUNTER]] // CHECK: [[DEPS_DC_BASE_ADDR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEPS_DC]], i{{.+}} 0, i{{.+}} 0 // CHECK: [[AKI_INT:%.+]] = ptrtoint i32* [[AKI_ADDR]] to i64 // CHECK: store i64 [[AKI_INT]], i64* [[DEPS_DC_BASE_ADDR]], // DEPS[DEP_COUNTER].size = sizeof(a[k][i]); // CHECK: [[DEPS_DC_SIZE:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEPS_DC]], i{{.+}} 0, i{{.+}} 1 // CHECK: store i64 4, i64* [[DEPS_DC_SIZE]], // DEPS[DEP_COUNTER].flags = in; // CHECK: [[DEPS_DC_FLAGS:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEPS_DC]], i{{.+}} 0, i{{.+}} 2 // CHECK: store i8 1, i8* [[DEPS_DC_FLAGS]], // DEP_COUNTER = DEP_COUNTER + 1; // CHECK: [[DEP_COUNTER:%.+]] = load i64, i64* [[DEP_COUNTER_ADDR]], // CHECK: [[INC:%.+]] = add nuw i64 [[DEP_COUNTER]], 1 // CHECK: store i64 [[INC]], i64* [[DEP_COUNTER_ADDR]], // COUNTER = COUNTER + 1; // CHECK: [[COUNTER:%.+]] = load i32, i32* [[COUNTER_ADDR]], // CHECK: [[INC:%.+]] = add i32 [[COUNTER]], 1 // CHECK: store i32 [[INC]], i32* [[COUNTER_ADDR]], // CHECK: br label %[[CONT]] // CHECK: [[EXIT]]: // CHECK: [[DEP_BEGIN:%.+]] = bitcast %struct.kmp_depend_info* [[DEPS]] to i8* // CHECK: = call i32 @__kmpc_omp_task_with_deps(%struct.ident_t* @{{.+}}, i32 %{{.+}}, i8* [[BUF]], i32 [[NDEPS]], i8* [[DEP_BEGIN]], i32 0, i8* null) #pragma omp task depend(iterator(unsigned k=0:i:2), in: a[k][i]) ++i; } #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-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/artifact.h" #include "MagickCore/attribute.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/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite-private.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/fx.h" #include "MagickCore/gem.h" #include "MagickCore/gem-private.h" #include "MagickCore/geometry.h" #include "MagickCore/histogram.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resample.h" #include "MagickCore/resample-private.h" #include "MagickCore/resource_.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/threshold.h" #include "MagickCore/token.h" #include "MagickCore/xml-tree.h" #include "MagickCore/xml-tree-private.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 appropriately. % % The format of the AutoGammaImage method is: % % MagickBooleanType AutoGammaImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image to auto-level % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType AutoGammaImage(Image *image, ExceptionInfo *exception) { double gamma, log_mean, mean, sans; MagickStatusType status; ssize_t i; log_mean=log(0.5); if (image->channel_mask == DefaultChannels) { /* Apply gamma correction equally across all given channels. */ (void) GetImageMean(image,&mean,&sans,exception); gamma=log(mean*QuantumScale)/log_mean; return(LevelImage(image,0.0,(double) QuantumRange,gamma,exception)); } /* Auto-gamma each channel separately. */ status=MagickTrue; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { ChannelType channel_mask; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; channel_mask=SetImageChannelMask(image,(ChannelType) (1UL << i)); status=GetImageMean(image,&mean,&sans,exception); gamma=log(mean*QuantumScale)/log_mean; status&=LevelImage(image,0.0,(double) QuantumRange,gamma,exception); (void) SetImageChannelMask(image,channel_mask); if (status == MagickFalse) break; } 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,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image to auto-level % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType AutoLevelImage(Image *image, ExceptionInfo *exception) { return(MinMaxStretchImage(image,0.0,0.0,1.0,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % 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,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o brightness: the brightness percent (-100 .. 100). % % o contrast: the contrast percent (-100 .. 100). % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType BrightnessContrastImage(Image *image, const double brightness,const double contrast,ExceptionInfo *exception) { #define BrightnessContastImageTag "BrightnessContast/Image" double alpha, coefficients[2], intercept, 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=FunctionImage(image,PolynomialFunction,2,coefficients,exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C L A H E I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CLAHEImage() is a variant of adaptive histogram equalization in which the % contrast amplification is limited, so as to reduce this problem of noise % amplification. % % Adapted from implementation by Karel Zuiderveld, karel@cv.ruu.nl in % "Graphics Gems IV", Academic Press, 1994. % % The format of the CLAHEImage method is: % % MagickBooleanType CLAHEImage(Image *image,const size_t width, % const size_t height,const size_t number_bins,const double clip_limit, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width: the width of the tile divisions to use in horizontal direction. % % o height: the height of the tile divisions to use in vertical direction. % % o number_bins: number of bins for histogram ("dynamic range"). % % o clip_limit: contrast limit for localised changes in contrast. A limit % less than 1 results in standard non-contrast limited AHE. % % o exception: return any errors or warnings in this structure. % */ typedef struct _RangeInfo { unsigned short min, max; } RangeInfo; static void ClipCLAHEHistogram(const double clip_limit,const size_t number_bins, size_t *histogram) { #define NumberCLAHEGrays (65536) ssize_t i; size_t cumulative_excess, previous_excess, step; ssize_t excess; /* Compute total number of excess pixels. */ cumulative_excess=0; for (i=0; i < (ssize_t) number_bins; i++) { excess=(ssize_t) histogram[i]-(ssize_t) clip_limit; if (excess > 0) cumulative_excess+=excess; } /* Clip histogram and redistribute excess pixels across all bins. */ step=cumulative_excess/number_bins; excess=(ssize_t) (clip_limit-step); for (i=0; i < (ssize_t) number_bins; i++) { if ((double) histogram[i] > clip_limit) histogram[i]=(size_t) clip_limit; else if ((ssize_t) histogram[i] > excess) { cumulative_excess-=histogram[i]-excess; histogram[i]=(size_t) clip_limit; } else { cumulative_excess-=step; histogram[i]+=step; } } /* Redistribute remaining excess. */ do { size_t *p; size_t *q; previous_excess=cumulative_excess; p=histogram; q=histogram+number_bins; while ((cumulative_excess != 0) && (p < q)) { step=number_bins/cumulative_excess; if (step < 1) step=1; for (p=histogram; (p < q) && (cumulative_excess != 0); p+=step) if ((double) *p < clip_limit) { (*p)++; cumulative_excess--; } p++; } } while ((cumulative_excess != 0) && (cumulative_excess < previous_excess)); } static void GenerateCLAHEHistogram(const RectangleInfo *clahe_info, const RectangleInfo *tile_info,const size_t number_bins, const unsigned short *lut,const unsigned short *pixels,size_t *histogram) { const unsigned short *p; ssize_t i; /* Classify the pixels into a gray histogram. */ for (i=0; i < (ssize_t) number_bins; i++) histogram[i]=0L; p=pixels; for (i=0; i < (ssize_t) tile_info->height; i++) { const unsigned short *q; q=p+tile_info->width; while (p < q) histogram[lut[*p++]]++; q+=clahe_info->width; p=q-tile_info->width; } } static void InterpolateCLAHE(const RectangleInfo *clahe_info,const size_t *Q12, const size_t *Q22,const size_t *Q11,const size_t *Q21, const RectangleInfo *tile,const unsigned short *lut,unsigned short *pixels) { ssize_t y; unsigned short intensity; /* Bilinear interpolate four tiles to eliminate boundary artifacts. */ for (y=(ssize_t) tile->height; y > 0; y--) { ssize_t x; for (x=(ssize_t) tile->width; x > 0; x--) { intensity=lut[*pixels]; *pixels++=(unsigned short) (PerceptibleReciprocal((double) tile->width* tile->height)*(y*((double) x*Q12[intensity]+(tile->width-x)* Q22[intensity])+(tile->height-y)*((double) x*Q11[intensity]+ (tile->width-x)*Q21[intensity]))); } pixels+=(clahe_info->width-tile->width); } } static void GenerateCLAHELut(const RangeInfo *range_info, const size_t number_bins,unsigned short *lut) { ssize_t i; unsigned short delta; /* Scale input image [intensity min,max] to [0,number_bins-1]. */ delta=(unsigned short) ((range_info->max-range_info->min)/number_bins+1); for (i=(ssize_t) range_info->min; i <= (ssize_t) range_info->max; i++) lut[i]=(unsigned short) ((i-range_info->min)/delta); } static void MapCLAHEHistogram(const RangeInfo *range_info, const size_t number_bins,const size_t number_pixels,size_t *histogram) { double scale, sum; ssize_t i; /* Rescale histogram to range [min-intensity .. max-intensity]. */ scale=(double) (range_info->max-range_info->min)/number_pixels; sum=0.0; for (i=0; i < (ssize_t) number_bins; i++) { sum+=histogram[i]; histogram[i]=(size_t) (range_info->min+scale*sum); if (histogram[i] > range_info->max) histogram[i]=range_info->max; } } static MagickBooleanType CLAHE(const RectangleInfo *clahe_info, const RectangleInfo *tile_info,const RangeInfo *range_info, const size_t number_bins,const double clip_limit,unsigned short *pixels) { MemoryInfo *tile_cache; unsigned short *p; size_t limit, *tiles; ssize_t y; unsigned short *lut; /* Constrast limited adapted histogram equalization. */ if (clip_limit == 1.0) return(MagickTrue); tile_cache=AcquireVirtualMemory((size_t) clahe_info->x*number_bins, clahe_info->y*sizeof(*tiles)); if (tile_cache == (MemoryInfo *) NULL) return(MagickFalse); lut=(unsigned short *) AcquireQuantumMemory(NumberCLAHEGrays,sizeof(*lut)); if (lut == (unsigned short *) NULL) { tile_cache=RelinquishVirtualMemory(tile_cache); return(MagickFalse); } tiles=(size_t *) GetVirtualMemoryBlob(tile_cache); limit=(size_t) (clip_limit*(tile_info->width*tile_info->height)/number_bins); if (limit < 1UL) limit=1UL; /* Generate greylevel mappings for each tile. */ GenerateCLAHELut(range_info,number_bins,lut); p=pixels; for (y=0; y < (ssize_t) clahe_info->y; y++) { ssize_t x; for (x=0; x < (ssize_t) clahe_info->x; x++) { size_t *histogram; histogram=tiles+(number_bins*(y*clahe_info->x+x)); GenerateCLAHEHistogram(clahe_info,tile_info,number_bins,lut,p,histogram); ClipCLAHEHistogram((double) limit,number_bins,histogram); MapCLAHEHistogram(range_info,number_bins,tile_info->width* tile_info->height,histogram); p+=tile_info->width; } p+=clahe_info->width*(tile_info->height-1); } /* Interpolate greylevel mappings to get CLAHE image. */ p=pixels; for (y=0; y <= (ssize_t) clahe_info->y; y++) { OffsetInfo offset; RectangleInfo tile; ssize_t x; tile.height=tile_info->height; tile.y=y-1; offset.y=tile.y+1; if (y == 0) { /* Top row. */ tile.height=tile_info->height >> 1; tile.y=0; offset.y=0; } else if (y == (ssize_t) clahe_info->y) { /* Bottom row. */ tile.height=(tile_info->height+1) >> 1; tile.y=clahe_info->y-1; offset.y=tile.y; } for (x=0; x <= (ssize_t) clahe_info->x; x++) { tile.width=tile_info->width; tile.x=x-1; offset.x=tile.x+1; if (x == 0) { /* Left column. */ tile.width=tile_info->width >> 1; tile.x=0; offset.x=0; } else if (x == (ssize_t) clahe_info->x) { /* Right column. */ tile.width=(tile_info->width+1) >> 1; tile.x=clahe_info->x-1; offset.x=tile.x; } InterpolateCLAHE(clahe_info, tiles+(number_bins*(tile.y*clahe_info->x+tile.x)), /* Q12 */ tiles+(number_bins*(tile.y*clahe_info->x+offset.x)), /* Q22 */ tiles+(number_bins*(offset.y*clahe_info->x+tile.x)), /* Q11 */ tiles+(number_bins*(offset.y*clahe_info->x+offset.x)), /* Q21 */ &tile,lut,p); p+=tile.width; } p+=clahe_info->width*(tile.height-1); } lut=(unsigned short *) RelinquishMagickMemory(lut); tile_cache=RelinquishVirtualMemory(tile_cache); return(MagickTrue); } MagickExport MagickBooleanType CLAHEImage(Image *image,const size_t width, const size_t height,const size_t number_bins,const double clip_limit, ExceptionInfo *exception) { #define CLAHEImageTag "CLAHE/Image" CacheView *image_view; ColorspaceType colorspace; MagickBooleanType status; MagickOffsetType progress; MemoryInfo *pixel_cache; RangeInfo range_info; RectangleInfo clahe_info, tile_info; size_t n; ssize_t y; unsigned short *pixels; /* Configure CLAHE parameters. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); range_info.min=0; range_info.max=NumberCLAHEGrays-1; tile_info.width=width; if (tile_info.width == 0) tile_info.width=image->columns >> 3; tile_info.height=height; if (tile_info.height == 0) tile_info.height=image->rows >> 3; tile_info.x=0; if ((image->columns % tile_info.width) != 0) tile_info.x=(ssize_t) tile_info.width-(image->columns % tile_info.width); tile_info.y=0; if ((image->rows % tile_info.height) != 0) tile_info.y=(ssize_t) tile_info.height-(image->rows % tile_info.height); clahe_info.width=image->columns+tile_info.x; clahe_info.height=image->rows+tile_info.y; clahe_info.x=(ssize_t) clahe_info.width/tile_info.width; clahe_info.y=(ssize_t) clahe_info.height/tile_info.height; pixel_cache=AcquireVirtualMemory(clahe_info.width,clahe_info.height* sizeof(*pixels)); if (pixel_cache == (MemoryInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); pixels=(unsigned short *) GetVirtualMemoryBlob(pixel_cache); colorspace=image->colorspace; if (TransformImageColorspace(image,LabColorspace,exception) == MagickFalse) { pixel_cache=RelinquishVirtualMemory(pixel_cache); return(MagickFalse); } /* Initialize CLAHE pixels. */ image_view=AcquireVirtualCacheView(image,exception); progress=0; status=MagickTrue; n=0; for (y=0; y < (ssize_t) clahe_info.height; y++) { const Quantum *magick_restrict p; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-(tile_info.x >> 1),y- (tile_info.y >> 1),clahe_info.width,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) clahe_info.width; x++) { pixels[n++]=ScaleQuantumToShort(p[0]); p+=GetPixelChannels(image); } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; progress++; proceed=SetImageProgress(image,CLAHEImageTag,progress,2* GetPixelChannels(image)); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); status=CLAHE(&clahe_info,&tile_info,&range_info,number_bins == 0 ? (size_t) 128 : MagickMin(number_bins,256),clip_limit,pixels); if (status == MagickFalse) (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); /* Push CLAHE pixels to CLAHE image. */ image_view=AcquireAuthenticCacheView(image,exception); n=clahe_info.width*(tile_info.y >> 1); for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } n+=tile_info.x >> 1; for (x=0; x < (ssize_t) image->columns; x++) { q[0]=ScaleShortToQuantum(pixels[n++]); q+=GetPixelChannels(image); } n+=(clahe_info.width-image->columns-(tile_info.x >> 1)); if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; progress++; proceed=SetImageProgress(image,CLAHEImageTag,progress,2* GetPixelChannels(image)); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); pixel_cache=RelinquishVirtualMemory(pixel_cache); if (TransformImageColorspace(image,colorspace,exception) == MagickFalse) status=MagickFalse; 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, % const PixelInterpolateMethod method,ExceptionInfo *exception) % % 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 method: the pixel interpolation method. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ClutImage(Image *image,const Image *clut_image, const PixelInterpolateMethod method,ExceptionInfo *exception) { #define ClutImageTag "Clut/Image" CacheView *clut_view, *image_view; MagickBooleanType status; MagickOffsetType progress; PixelInfo *clut_map; 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,exception) == MagickFalse) return(MagickFalse); if ((IsGrayColorspace(image->colorspace) != MagickFalse) && (IsGrayColorspace(clut_image->colorspace) == MagickFalse)) (void) SetImageColorspace(image,sRGBColorspace,exception); clut_map=(PixelInfo *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*clut_map)); if (clut_map == (PixelInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); /* Clut image. */ status=MagickTrue; progress=0; adjust=(ssize_t) (clut_image->interpolate == IntegerInterpolatePixel ? 0 : 1); clut_view=AcquireVirtualCacheView(clut_image,exception); for (i=0; i <= (ssize_t) MaxMap; i++) { GetPixelInfo(clut_image,clut_map+i); status=InterpolatePixelInfo(clut_image,clut_view,method, (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++) { PixelInfo pixel; Quantum *magick_restrict q; 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++) { PixelTrait traits; GetPixelInfoPixel(image,q,&pixel); traits=GetPixelChannelTraits(image,RedPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.red=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.red))].red; traits=GetPixelChannelTraits(image,GreenPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.green=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.green))].green; traits=GetPixelChannelTraits(image,BluePixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.blue=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.blue))].blue; traits=GetPixelChannelTraits(image,BlackPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.black=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.black))].black; traits=GetPixelChannelTraits(image,AlphaPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.alpha=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.alpha))].alpha; SetPixelViaPixelInfo(image,&pixel,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_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,ClutImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); clut_map=(PixelInfo *) RelinquishMagickMemory(clut_map); if ((clut_image->alpha_trait != UndefinedPixelTrait) && ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)) (void) SetImageAlphaChannel(image,ActivateAlphaChannel,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,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o color_correction_collection: the color correction collection in XML. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ColorDecisionListImage(Image *image, const char *color_correction_collection,ExceptionInfo *exception) { #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[MagickPathExtent]; ColorCorrection color_correction; const char *content, *p; MagickBooleanType status; MagickOffsetType progress; PixelInfo *cdl_map; 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,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++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,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++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,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++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,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; (void) GetNextToken(p,&p,MagickPathExtent,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=(PixelInfo *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*cdl_map)); if (cdl_map == (PixelInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); for (i=0; i <= (ssize_t) MaxMap; i++) { cdl_map[i].red=(double) ScaleMapToQuantum((double) (MaxMap*(pow(color_correction.red.slope*i/MaxMap+ color_correction.red.offset,color_correction.red.power)))); cdl_map[i].green=(double) ScaleMapToQuantum((double) (MaxMap*(pow(color_correction.green.slope*i/MaxMap+ color_correction.green.offset,color_correction.green.power)))); cdl_map[i].blue=(double) ScaleMapToQuantum((double) (MaxMap*(pow(color_correction.blue.slope*i/MaxMap+ color_correction.blue.offset,color_correction.blue.power)))); } if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Apply transfer function to colormap. */ double luma; luma=0.21267f*image->colormap[i].red+0.71526*image->colormap[i].green+ 0.07217f*image->colormap[i].blue; image->colormap[i].red=luma+color_correction.saturation*cdl_map[ ScaleQuantumToMap(ClampToQuantum(image->colormap[i].red))].red-luma; image->colormap[i].green=luma+color_correction.saturation*cdl_map[ ScaleQuantumToMap(ClampToQuantum(image->colormap[i].green))].green-luma; image->colormap[i].blue=luma+color_correction.saturation*cdl_map[ ScaleQuantumToMap(ClampToQuantum(image->colormap[i].blue))].blue-luma; } /* Apply transfer function to 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++) { double luma; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { luma=0.21267f*GetPixelRed(image,q)+0.71526*GetPixelGreen(image,q)+ 0.07217f*GetPixelBlue(image,q); SetPixelRed(image,ClampToQuantum(luma+color_correction.saturation* (cdl_map[ScaleQuantumToMap(GetPixelRed(image,q))].red-luma)),q); SetPixelGreen(image,ClampToQuantum(luma+color_correction.saturation* (cdl_map[ScaleQuantumToMap(GetPixelGreen(image,q))].green-luma)),q); SetPixelBlue(image,ClampToQuantum(luma+color_correction.saturation* (cdl_map[ScaleQuantumToMap(GetPixelBlue(image,q))].blue-luma)),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_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,ColorDecisionListCorrectImageTag, progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); cdl_map=(PixelInfo *) RelinquishMagickMemory(cdl_map); 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,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o sharpen: Increase or decrease image contrast. % % o exception: return any errors or warnings in this structure. % */ static void Contrast(const int sign,double *red,double *green,double *blue) { double brightness, hue, saturation; /* Enhance contrast: dark color become darker, light color become lighter. */ assert(red != (double *) NULL); assert(green != (double *) NULL); assert(blue != (double *) 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,ExceptionInfo *exception) { #define ContrastImageTag "Contrast/Image" CacheView *image_view; int sign; MagickBooleanType status; MagickOffsetType progress; ssize_t i; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateContrastImage(image,sharpen,exception) != MagickFalse) return(MagickTrue); #endif 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++) { double blue, green, red; red=(double) image->colormap[i].red; green=(double) image->colormap[i].green; blue=(double) image->colormap[i].blue; Contrast(sign,&red,&green,&blue); image->colormap[i].red=(MagickRealType) red; image->colormap[i].green=(MagickRealType) green; image->colormap[i].blue=(MagickRealType) blue; } } /* Contrast enhance 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++) { double blue, green, red; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { red=(double) GetPixelRed(image,q); green=(double) GetPixelGreen(image,q); blue=(double) GetPixelBlue(image,q); Contrast(sign,&red,&green,&blue); SetPixelRed(image,ClampToQuantum(red),q); SetPixelGreen(image,ClampToQuantum(green),q); SetPixelBlue(image,ClampToQuantum(blue),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_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,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,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % 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.). % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ContrastStretchImage(Image *image, const double black_point,const double white_point,ExceptionInfo *exception) { #define MaxRange(color) ((double) ScaleQuantumToMap((Quantum) (color))) #define ContrastStretchImageTag "ContrastStretch/Image" CacheView *image_view; double *black, *histogram, *stretch_map, *white; ImageType type; MagickBooleanType status; MagickOffsetType progress; 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); type=IdentifyImageType(image,exception); if (IsGrayImageType(type) != MagickFalse) (void) SetImageColorspace(image,GRAYColorspace,exception); black=(double *) AcquireQuantumMemory(MaxPixelChannels,sizeof(*black)); white=(double *) AcquireQuantumMemory(MaxPixelChannels,sizeof(*white)); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels* sizeof(*histogram)); stretch_map=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels* sizeof(*stretch_map)); if ((black == (double *) NULL) || (white == (double *) NULL) || (histogram == (double *) NULL) || (stretch_map == (double *) NULL)) { if (stretch_map != (double *) NULL) stretch_map=(double *) RelinquishMagickMemory(stretch_map); if (histogram != (double *) NULL) histogram=(double *) RelinquishMagickMemory(histogram); if (white != (double *) NULL) white=(double *) RelinquishMagickMemory(white); if (black != (double *) NULL) black=(double *) RelinquishMagickMemory(black); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } /* Form histogram. */ status=MagickTrue; (void) memset(histogram,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *magick_restrict p; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double pixel; pixel=GetPixelIntensity(image,p); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { if (image->channel_mask != DefaultChannels) pixel=(double) p[i]; histogram[GetPixelChannels(image)*ScaleQuantumToMap( ClampToQuantum(pixel))+i]++; } p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Find the histogram boundaries by locating the black/white levels. */ for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; ssize_t j; black[i]=0.0; white[i]=MaxRange(QuantumRange); intensity=0.0; for (j=0; j <= (ssize_t) MaxMap; j++) { intensity+=histogram[GetPixelChannels(image)*j+i]; if (intensity > black_point) break; } black[i]=(double) j; intensity=0.0; for (j=(ssize_t) MaxMap; j != 0; j--) { intensity+=histogram[GetPixelChannels(image)*j+i]; if (intensity > ((double) image->columns*image->rows-white_point)) break; } white[i]=(double) j; } histogram=(double *) RelinquishMagickMemory(histogram); /* Stretch the histogram to create the stretched image mapping. */ (void) memset(stretch_map,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*stretch_map)); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { ssize_t j; for (j=0; j <= (ssize_t) MaxMap; j++) { double gamma; gamma=PerceptibleReciprocal(white[i]-black[i]); if (j < (ssize_t) black[i]) stretch_map[GetPixelChannels(image)*j+i]=0.0; else if (j > (ssize_t) white[i]) stretch_map[GetPixelChannels(image)*j+i]=(double) QuantumRange; else if (black[i] != white[i]) stretch_map[GetPixelChannels(image)*j+i]=(double) ScaleMapToQuantum( (double) (MaxMap*gamma*(j-black[i]))); } } if (image->storage_class == PseudoClass) { ssize_t j; /* Stretch-contrast colormap. */ for (j=0; j < (ssize_t) image->colors; j++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,RedPixelChannel); image->colormap[j].red=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+i]; } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,GreenPixelChannel); image->colormap[j].green=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+i]; } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,BluePixelChannel); image->colormap[j].blue=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+i]; } if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,AlphaPixelChannel); image->colormap[j].alpha=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+i]; } } } /* Stretch-contrast 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++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if (black[j] == white[j]) continue; q[j]=ClampToQuantum(stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(q[j])+j]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_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,ContrastStretchImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); stretch_map=(double *) RelinquishMagickMemory(stretch_map); white=(double *) RelinquishMagickMemory(white); black=(double *) RelinquishMagickMemory(black); 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 EnhanceImageTag "Enhance/Image" #define EnhancePixel(weight) \ mean=QuantumScale*((double) GetPixelRed(image,r)+pixel.red)/2.0; \ distance=QuantumScale*((double) GetPixelRed(image,r)-pixel.red); \ distance_squared=(4.0+mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelGreen(image,r)+pixel.green)/2.0; \ distance=QuantumScale*((double) GetPixelGreen(image,r)-pixel.green); \ distance_squared+=(7.0-mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelBlue(image,r)+pixel.blue)/2.0; \ distance=QuantumScale*((double) GetPixelBlue(image,r)-pixel.blue); \ distance_squared+=(5.0-mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelBlack(image,r)+pixel.black)/2.0; \ distance=QuantumScale*((double) GetPixelBlack(image,r)-pixel.black); \ distance_squared+=(5.0-mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelAlpha(image,r)+pixel.alpha)/2.0; \ distance=QuantumScale*((double) GetPixelAlpha(image,r)-pixel.alpha); \ distance_squared+=(5.0-mean)*distance*distance; \ if (distance_squared < 0.069) \ { \ aggregate.red+=(weight)*GetPixelRed(image,r); \ aggregate.green+=(weight)*GetPixelGreen(image,r); \ aggregate.blue+=(weight)*GetPixelBlue(image,r); \ aggregate.black+=(weight)*GetPixelBlack(image,r); \ aggregate.alpha+=(weight)*GetPixelAlpha(image,r); \ total_weight+=(weight); \ } \ r+=GetPixelChannels(image); CacheView *enhance_view, *image_view; Image *enhance_image; MagickBooleanType status; MagickOffsetType progress; 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); enhance_image=CloneImage(image,0,0,MagickTrue, exception); if (enhance_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(enhance_image,DirectClass,exception) == MagickFalse) { enhance_image=DestroyImage(enhance_image); return((Image *) NULL); } /* Enhance image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(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++) { PixelInfo pixel; const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; ssize_t center; 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 Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } center=(ssize_t) GetPixelChannels(image)*(2*(image->columns+4)+2); GetPixelInfo(image,&pixel); for (x=0; x < (ssize_t) image->columns; x++) { double distance, distance_squared, mean, total_weight; PixelInfo aggregate; const Quantum *magick_restrict r; GetPixelInfo(image,&aggregate); total_weight=0.0; GetPixelInfoPixel(image,p+center,&pixel); r=p; EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0); EnhancePixel(8.0); EnhancePixel(5.0); r=p+GetPixelChannels(image)*(image->columns+4); EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0); EnhancePixel(20.0); EnhancePixel(8.0); r=p+2*GetPixelChannels(image)*(image->columns+4); EnhancePixel(10.0); EnhancePixel(40.0); EnhancePixel(80.0); EnhancePixel(40.0); EnhancePixel(10.0); r=p+3*GetPixelChannels(image)*(image->columns+4); EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0); EnhancePixel(20.0); EnhancePixel(8.0); r=p+4*GetPixelChannels(image)*(image->columns+4); EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0); EnhancePixel(8.0); EnhancePixel(5.0); if (total_weight > MagickEpsilon) { pixel.red=((aggregate.red+total_weight/2.0)/total_weight); pixel.green=((aggregate.green+total_weight/2.0)/total_weight); pixel.blue=((aggregate.blue+total_weight/2.0)/total_weight); pixel.black=((aggregate.black+total_weight/2.0)/total_weight); pixel.alpha=((aggregate.alpha+total_weight/2.0)/total_weight); } SetPixelViaPixelInfo(enhance_image,&pixel,q); p+=GetPixelChannels(image); q+=GetPixelChannels(enhance_image); } if (SyncCacheViewAuthenticPixels(enhance_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,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,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType EqualizeImage(Image *image, ExceptionInfo *exception) { #define EqualizeImageTag "Equalize/Image" CacheView *image_view; double black[CompositePixelChannel+1], *equalize_map, *histogram, *map, white[CompositePixelChannel+1]; MagickBooleanType status; MagickOffsetType progress; ssize_t i; ssize_t y; /* Allocate and initialize histogram arrays. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateEqualizeImage(image,exception) != MagickFalse) return(MagickTrue); #endif if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); equalize_map=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels* sizeof(*equalize_map)); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels* sizeof(*histogram)); map=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels*sizeof(*map)); if ((equalize_map == (double *) NULL) || (histogram == (double *) NULL) || (map == (double *) NULL)) { if (map != (double *) NULL) map=(double *) RelinquishMagickMemory(map); if (histogram != (double *) NULL) histogram=(double *) RelinquishMagickMemory(histogram); if (equalize_map != (double *) NULL) equalize_map=(double *) RelinquishMagickMemory(equalize_map); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } /* Form histogram. */ status=MagickTrue; (void) memset(histogram,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *magick_restrict p; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; intensity=(double) p[i]; if ((image->channel_mask & SyncChannels) != 0) intensity=GetPixelIntensity(image,p); histogram[GetPixelChannels(image)*ScaleQuantumToMap( ClampToQuantum(intensity))+i]++; } p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Integrate the histogram to get the equalization map. */ for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; ssize_t j; intensity=0.0; for (j=0; j <= (ssize_t) MaxMap; j++) { intensity+=histogram[GetPixelChannels(image)*j+i]; map[GetPixelChannels(image)*j+i]=intensity; } } (void) memset(equalize_map,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*equalize_map)); (void) memset(black,0,sizeof(*black)); (void) memset(white,0,sizeof(*white)); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { ssize_t j; black[i]=map[i]; white[i]=map[GetPixelChannels(image)*MaxMap+i]; if (black[i] != white[i]) for (j=0; j <= (ssize_t) MaxMap; j++) equalize_map[GetPixelChannels(image)*j+i]=(double) ScaleMapToQuantum((double) ((MaxMap*(map[ GetPixelChannels(image)*j+i]-black[i]))/(white[i]-black[i]))); } histogram=(double *) RelinquishMagickMemory(histogram); map=(double *) RelinquishMagickMemory(map); if (image->storage_class == PseudoClass) { ssize_t j; /* Equalize colormap. */ for (j=0; j < (ssize_t) image->colors; j++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel = GetPixelChannelChannel(image, RedPixelChannel); if (black[channel] != white[channel]) image->colormap[j].red=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+ channel]; } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel = GetPixelChannelChannel(image, GreenPixelChannel); if (black[channel] != white[channel]) image->colormap[j].green=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+ channel]; } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel = GetPixelChannelChannel(image, BluePixelChannel); if (black[channel] != white[channel]) image->colormap[j].blue=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+ channel]; } if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel = GetPixelChannelChannel(image, AlphaPixelChannel); if (black[channel] != white[channel]) image->colormap[j].alpha=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+ channel]; } } } /* Equalize image. */ 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++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if (((traits & UpdatePixelTrait) == 0) || (black[j] == white[j])) continue; q[j]=ClampToQuantum(equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(q[j])+j]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_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,EqualizeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); equalize_map=(double *) 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 double gamma, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % 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 double gamma, ExceptionInfo *exception) { #define GammaImageTag "Gamma/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; Quantum *gamma_map; 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]=ScaleMapToQuantum((double) (MaxMap*pow((double) i/ MaxMap,PerceptibleReciprocal(gamma)))); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Gamma-correct colormap. */ if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].red))]; if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].green))]; if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].blue))]; if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].alpha))]; } /* Gamma-correct 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++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=gamma_map[ScaleQuantumToMap(ClampToQuantum((MagickRealType) q[j]))]; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_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,GammaImageTag,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 image to grayscale. % % The format of the GrayscaleImage method is: % % MagickBooleanType GrayscaleImage(Image *image, % const PixelIntensityMethod method ,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o method: the pixel intensity method. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GrayscaleImage(Image *image, const PixelIntensityMethod method,ExceptionInfo *exception) { #define GrayscaleImageTag "Grayscale/Image" CacheView *image_view; 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,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateGrayscaleImage(image,method,exception) != MagickFalse) { image->intensity=method; image->type=GrayscaleType; if ((method == Rec601LuminancePixelIntensityMethod) || (method == Rec709LuminancePixelIntensityMethod)) return(SetImageColorspace(image,LinearGRAYColorspace,exception)); return(SetImageColorspace(image,GRAYColorspace,exception)); } #endif /* Grayscale 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++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType blue, green, red, intensity; red=(MagickRealType) GetPixelRed(image,q); green=(MagickRealType) GetPixelGreen(image,q); blue=(MagickRealType) GetPixelBlue(image,q); 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); 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(image,ClampToQuantum(intensity),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_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,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,exception)); return(SetImageColorspace(image,GRAYColorspace,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % 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, % ExceptionInfo *exception) % % 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 exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType HaldClutImage(Image *image, const Image *hald_image,ExceptionInfo *exception) { #define HaldClutImageTag "Clut/Image" typedef struct _HaldInfo { double x, y, z; } HaldInfo; CacheView *hald_view, *image_view; double width; MagickBooleanType status; MagickOffsetType progress; PixelInfo 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,exception) == MagickFalse) return(MagickFalse); if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); /* 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; GetPixelInfo(hald_image,&zero); hald_view=AcquireVirtualCacheView(hald_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 *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double area, offset; HaldInfo point; PixelInfo pixel, pixel1, pixel2, pixel3, pixel4; point.x=QuantumScale*(level-1.0)*GetPixelRed(image,q); point.y=QuantumScale*(level-1.0)*GetPixelGreen(image,q); point.z=QuantumScale*(level-1.0)*GetPixelBlue(image,q); offset=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); pixel1=zero; status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, fmod(offset,width),floor(offset/width),&pixel1,exception); if (status == MagickFalse) break; pixel2=zero; status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, fmod(offset+level,width),floor((offset+level)/width),&pixel2,exception); if (status == MagickFalse) break; pixel3=zero; area=point.y; if (hald_image->interpolate == NearestInterpolatePixel) area=(point.y < 0.5) ? 0.0 : 1.0; CompositePixelInfoAreaBlend(&pixel1,pixel1.alpha,&pixel2,pixel2.alpha, area,&pixel3); offset+=cube_size; status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, fmod(offset,width),floor(offset/width),&pixel1,exception); if (status == MagickFalse) break; status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, fmod(offset+level,width),floor((offset+level)/width),&pixel2,exception); if (status == MagickFalse) break; pixel4=zero; CompositePixelInfoAreaBlend(&pixel1,pixel1.alpha,&pixel2,pixel2.alpha, area,&pixel4); pixel=zero; area=point.z; if (hald_image->interpolate == NearestInterpolatePixel) area=(point.z < 0.5)? 0.0 : 1.0; CompositePixelInfoAreaBlend(&pixel3,pixel3.alpha,&pixel4,pixel4.alpha, area,&pixel); if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) SetPixelRed(image,ClampToQuantum(pixel.red),q); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) SetPixelGreen(image,ClampToQuantum(pixel.green),q); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) SetPixelBlue(image,ClampToQuantum(pixel.blue),q); if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) && (image->colorspace == CMYKColorspace)) SetPixelBlack(image,ClampToQuantum(pixel.black),q); if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) && (image->alpha_trait != UndefinedPixelTrait)) SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_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,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 % LevelizeImage() below. % % Gamma specifies a gamma correction to apply to the image. % % The format of the LevelImage method is: % % MagickBooleanType LevelImage(Image *image,const double black_point, % const double white_point,const double gamma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_point: The level to map zero (black) to. % % o white_point: The level to map QuantumRange (white) to. % % o exception: return any errors or warnings in this structure. % */ static inline double LevelPixel(const double black_point, const double white_point,const double gamma,const double pixel) { double level_pixel, scale; scale=PerceptibleReciprocal(white_point-black_point); level_pixel=QuantumRange*gamma_pow(scale*((double) pixel-black_point), PerceptibleReciprocal(gamma)); return(level_pixel); } MagickExport MagickBooleanType LevelImage(Image *image,const double black_point, const double white_point,const double gamma,ExceptionInfo *exception) { #define LevelImageTag "Level/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; 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 ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(double) ClampToQuantum(LevelPixel(black_point, white_point,gamma,image->colormap[i].red)); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(double) ClampToQuantum(LevelPixel(black_point, white_point,gamma,image->colormap[i].green)); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(double) ClampToQuantum(LevelPixel(black_point, white_point,gamma,image->colormap[i].blue)); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(double) ClampToQuantum(LevelPixel(black_point, white_point,gamma,image->colormap[i].alpha)); } /* Level 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++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=ClampToQuantum(LevelPixel(black_point,white_point,gamma, (double) q[j])); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_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,LevelImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); (void) ClampImage(image,exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L e v e l i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LevelizeImage() 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. % % LevelizeImage() 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 to 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 LevelizeImage method is: % % MagickBooleanType LevelizeImage(Image *image,const double black_point, % const double white_point,const double gamma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % 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. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType LevelizeImage(Image *image, const double black_point,const double white_point,const double gamma, ExceptionInfo *exception) { #define LevelizeImageTag "Levelize/Image" #define LevelizeValue(x) ClampToQuantum(((MagickRealType) gamma_pow((double) \ (QuantumScale*(x)),gamma))*(white_point-black_point)+black_point) CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; 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 ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(double) LevelizeValue(image->colormap[i].red); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(double) LevelizeValue( image->colormap[i].green); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(double) LevelizeValue(image->colormap[i].blue); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(double) LevelizeValue( image->colormap[i].alpha); } /* Level 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++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=LevelizeValue(q[j]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_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,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 % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LevelImageColors() 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 % appropriately. This effectivally maps a greyscale gradient into the given % color gradient. % % The format of the LevelImageColors method is: % % MagickBooleanType LevelImageColors(Image *image, % const PixelInfo *black_color,const PixelInfo *white_color, % const MagickBooleanType invert,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % 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) % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType LevelImageColors(Image *image, const PixelInfo *black_color,const PixelInfo *white_color, const MagickBooleanType invert,ExceptionInfo *exception) { ChannelType channel_mask; 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,exception); status=MagickTrue; if (invert == MagickFalse) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,RedChannel); status&=LevelImage(image,black_color->red,white_color->red,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,GreenChannel); status&=LevelImage(image,black_color->green,white_color->green,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,BlueChannel); status&=LevelImage(image,black_color->blue,white_color->blue,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) && (image->colorspace == CMYKColorspace)) { channel_mask=SetImageChannelMask(image,BlackChannel); status&=LevelImage(image,black_color->black,white_color->black,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) && (image->alpha_trait != UndefinedPixelTrait)) { channel_mask=SetImageChannelMask(image,AlphaChannel); status&=LevelImage(image,black_color->alpha,white_color->alpha,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } } else { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,RedChannel); status&=LevelizeImage(image,black_color->red,white_color->red,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,GreenChannel); status&=LevelizeImage(image,black_color->green,white_color->green,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,BlueChannel); status&=LevelizeImage(image,black_color->blue,white_color->blue,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) && (image->colorspace == CMYKColorspace)) { channel_mask=SetImageChannelMask(image,BlackChannel); status&=LevelizeImage(image,black_color->black,white_color->black,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) && (image->alpha_trait != UndefinedPixelTrait)) { channel_mask=SetImageChannelMask(image,AlphaChannel); status&=LevelizeImage(image,black_color->alpha,white_color->alpha,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } } return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % 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, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_point: the black point. % % o white_point: the white point. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType LinearStretchImage(Image *image, const double black_point,const double white_point,ExceptionInfo *exception) { #define LinearStretchImageTag "LinearStretch/Image" CacheView *image_view; double *histogram, intensity; MagickBooleanType status; ssize_t black, white, y; /* Allocate histogram and linear map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*histogram)); if (histogram == (double *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); /* Form histogram. */ (void) memset(histogram,0,(MaxMap+1)*sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *magick_restrict p; ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { intensity=GetPixelIntensity(image,p); histogram[ScaleQuantumToMap(ClampToQuantum(intensity))]++; p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* 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=(double *) RelinquishMagickMemory(histogram); status=LevelImage(image,(double) ScaleMapToQuantum((MagickRealType) black), (double) ScaleMapToQuantum((MagickRealType) white),1.0,exception); 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, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o modulate: Define the percent change in brightness, saturation, and hue. % % o exception: return any errors or warnings in this structure. % */ static inline void ModulateHCL(const double percent_hue, const double percent_chroma,const double percent_luma,double *red, double *green,double *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,double *red, double *green,double *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,double *red, double *green,double *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,double *red, double *green,double *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,double *red, double *green,double *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,double *red, double *green,double *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,double *red, double *green,double *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, const IlluminantType illuminant,double *red,double *green,double *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToLCHab(*red,*green,*blue,illuminant,&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,illuminant,red,green,blue); } static inline void ModulateLCHuv(const double percent_luma, const double percent_chroma,const double percent_hue, const IlluminantType illuminant,double *red,double *green,double *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToLCHuv(*red,*green,*blue,illuminant,&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,illuminant,red,green,blue); } MagickExport MagickBooleanType ModulateImage(Image *image,const char *modulate, ExceptionInfo *exception) { #define ModulateImageTag "Modulate/Image" CacheView *image_view; ColorspaceType colorspace = UndefinedColorspace; const char *artifact; double percent_brightness, percent_hue, percent_saturation; GeometryInfo geometry_info; IlluminantType illuminant = D65Illuminant; MagickBooleanType status; MagickOffsetType progress; MagickStatusType flags; 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,exception); 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; artifact=GetImageArtifact(image,"modulate:colorspace"); if (artifact != (const char *) NULL) { colorspace=(ColorspaceType) ParseCommandOption(MagickColorspaceOptions, MagickFalse,artifact); if ((ssize_t) illuminant < 0) colorspace=UndefinedColorspace; } artifact=GetImageArtifact(image,"color:illuminant"); if (artifact != (const char *) NULL) { illuminant=(IlluminantType) ParseCommandOption(MagickIlluminantOptions, MagickFalse,artifact); if ((ssize_t) illuminant < 0) illuminant=UndefinedIlluminant; } if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { double blue, green, red; /* Modulate image colormap. */ red=(double) image->colormap[i].red; green=(double) image->colormap[i].green; blue=(double) 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 LCHColorspace: case LCHabColorspace: { ModulateLCHab(percent_brightness,percent_saturation,percent_hue, illuminant,&red,&green,&blue); break; } case LCHuvColorspace: { ModulateLCHuv(percent_brightness,percent_saturation,percent_hue, illuminant,&red,&green,&blue); break; } } image->colormap[i].red=red; image->colormap[i].green=green; image->colormap[i].blue=blue; } /* Modulate image. */ #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateModulateImage(image,percent_brightness,percent_hue, percent_saturation,colorspace,exception) != MagickFalse) return(MagickTrue); #endif 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++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double blue, green, red; red=(double) GetPixelRed(image,q); green=(double) GetPixelGreen(image,q); blue=(double) GetPixelBlue(image,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, illuminant,&red,&green,&blue); break; } case LCHColorspace: case LCHuvColorspace: { ModulateLCHuv(percent_brightness,percent_saturation,percent_hue, illuminant,&red,&green,&blue); break; } } SetPixelRed(image,ClampToQuantum(red),q); SetPixelGreen(image,ClampToQuantum(green),q); SetPixelBlue(image,ClampToQuantum(blue),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_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,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 NegateImage method is: % % MagickBooleanType NegateImage(Image *image, % const MagickBooleanType grayscale,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o grayscale: If MagickTrue, only negate grayscale pixels within the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType NegateImage(Image *image, const MagickBooleanType grayscale,ExceptionInfo *exception) { #define NegateImageTag "Negate/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; 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) for (i=0; i < (ssize_t) image->colors; i++) { /* Negate colormap. */ if (grayscale != MagickFalse) if ((image->colormap[i].red != image->colormap[i].green) || (image->colormap[i].green != image->colormap[i].blue)) continue; if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=QuantumRange-image->colormap[i].red; if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=QuantumRange-image->colormap[i].green; if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=QuantumRange-image->colormap[i].blue; } /* Negate image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); if( grayscale != MagickFalse ) { for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { ssize_t j; if (IsPixelGray(image,q) == MagickFalse) { q+=GetPixelChannels(image); continue; } for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=QuantumRange-q[j]; } q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; progress++; 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++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=QuantumRange-q[j]; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_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,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,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType NormalizeImage(Image *image, ExceptionInfo *exception) { double black_point, white_point; black_point=(double) image->columns*image->rows*0.0015; white_point=(double) image->columns*image->rows*0.9995; return(ContrastStretchImage(image,black_point,white_point,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % 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, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % 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. % % o exception: return any errors or warnings in this structure. % */ /* ImageMagick 6 has a version of this function which uses 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 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 double contrast,const double midpoint, ExceptionInfo *exception) { #define SigmoidalContrastImageTag "SigmoidalContrast/Image" #define ScaledSig(x) ( ClampToQuantum(QuantumRange* \ ScaledSigmoidal(contrast,QuantumScale*midpoint,QuantumScale*(x))) ) #define InverseScaledSig(x) ( ClampToQuantum(QuantumRange* \ InverseScaledSigmoidal(contrast,QuantumScale*midpoint,QuantumScale*(x))) ) CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Convenience macros. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); /* Side effect: may clamp values unless contrast<MagickEpsilon, in which case nothing is done. */ if (contrast < MagickEpsilon) return(MagickTrue); /* Sigmoidal-contrast enhance colormap. */ if (image->storage_class == PseudoClass) { ssize_t i; if( sharpen != MagickFalse ) for (i=0; i < (ssize_t) image->colors; i++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(MagickRealType) ScaledSig( image->colormap[i].red); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(MagickRealType) ScaledSig( image->colormap[i].green); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(MagickRealType) ScaledSig( image->colormap[i].blue); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(MagickRealType) ScaledSig( image->colormap[i].alpha); } else for (i=0; i < (ssize_t) image->colors; i++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(MagickRealType) InverseScaledSig( image->colormap[i].red); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(MagickRealType) InverseScaledSig( image->colormap[i].green); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(MagickRealType) InverseScaledSig( image->colormap[i].blue); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(MagickRealType) InverseScaledSig( image->colormap[i].alpha); } } /* Sigmoidal-contrast enhance 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++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (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++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if( sharpen != MagickFalse ) q[i]=ScaledSig(q[i]); else q[i]=InverseScaledSig(q[i]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_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,SigmoidalContrastImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W h i t e B a l a n c e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WhiteBalanceImage() applies white balancing to an image according to a % grayworld assumption in the LAB colorspace. % % The format of the WhiteBalanceImage method is: % % MagickBooleanType WhiteBalanceImage(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image to auto-level % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType WhiteBalanceImage(Image *image, ExceptionInfo *exception) { #define WhiteBalanceImageTag "WhiteBalance/Image" CacheView *image_view; const char *artifact; double a_mean, b_mean; MagickOffsetType progress; MagickStatusType status; ssize_t y; /* White balance image. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); status=TransformImageColorspace(image,LabColorspace,exception); a_mean=0.0; b_mean=0.0; image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *magick_restrict p; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { a_mean+=QuantumScale*GetPixela(image,p)-0.5; b_mean+=QuantumScale*GetPixelb(image,p)-0.5; p+=GetPixelChannels(image); } } a_mean/=((double) image->columns*image->rows); b_mean/=((double) image->columns*image->rows); 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++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double a, b; /* Scale the chroma distance shifted according to amount of luminance. */ a=(double) GetPixela(image,q)-1.1*GetPixelL(image,q)*a_mean; b=(double) GetPixelb(image,q)-1.1*GetPixelL(image,q)*b_mean; SetPixela(image,ClampToQuantum(a),q); SetPixelb(image,ClampToQuantum(b),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_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,WhiteBalanceImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); artifact=GetImageArtifact(image,"white-balance:vibrance"); if (artifact != (const char *) NULL) { ChannelType channel_mask; double black_point; GeometryInfo geometry_info; MagickStatusType flags; /* Level the a & b channels. */ flags=ParseGeometry(artifact,&geometry_info); black_point=geometry_info.rho; if ((flags & PercentValue) != 0) black_point*=(double) (QuantumRange/100.0); channel_mask=SetImageChannelMask(image,(ChannelType) (aChannel | bChannel)); status&=LevelImage(image,black_point,(double) QuantumRange-black_point, 1.0,exception); (void) SetImageChannelMask(image,channel_mask); } status&=TransformImageColorspace(image,sRGBColorspace,exception); return(status != 0 ? MagickTrue : MagickFalse); }
hd_joint_probability_generator_inl.h
/* * * Copyright (c) 2014, Nicola Pezzotti (Delft 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: * 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. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the Delft University of Technology. * 4. Neither the name of the Delft 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 NICOLA PEZZOTTI ''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 NICOLA PEZZOTTI 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 HD_JOINT_PROBABILITY_GENERATOR_INL #define HD_JOINT_PROBABILITY_GENERATOR_INL #include "hdi/dimensionality_reduction/hd_joint_probability_generator.h" #include "hdi/utils/math_utils.h" #include "hdi/utils/log_helper_functions.h" #include "hdi/utils/scoped_timers.h" #include "hdi/dimensionality_reduction/knn_utils.h" #include <random> #include <chrono> #include <unordered_set> #include <numeric> #include <thread> #if defined(_OPENMP) #include "omp.h" #endif #ifdef HNSWLIB_FOUND #ifdef _MSC_VER #if (_MSC_VER >= 1910) #include "hnswlib/hnswlib.h" #include "hnswlib/space_l2.h" #define HNSWLIB_SUPPORTED #endif //__cplusplus >=201103 #else // _MSC_VER #include "hnswlib/hnswlib.h" #include "hnswlib/space_l2.h" #define HNSWLIB_SUPPORTED #endif #endif // HNSWLIB_FOUND #ifdef __USE_ANNOY__ #ifndef WIN32 #define isnan std::isnan #endif #include "annoylib.h" #include "kissrandom.h" #ifndef WIN32 #undef isnan #endif #endif // __USE_ANNOY__ #ifdef __USE_GCD__ #include <dispatch/dispatch.h> #endif // __USE_GCD__ #pragma warning( push ) #pragma warning( disable : 4267) #pragma warning( push ) #pragma warning( disable : 4291) #pragma warning( push ) #pragma warning( disable : 4996) #pragma warning( push ) #pragma warning( disable : 4018) #pragma warning( push ) #pragma warning( disable : 4244) #pragma warning( pop ) #pragma warning( pop ) #pragma warning( pop ) #pragma warning( pop ) #pragma warning( pop ) namespace hdi { namespace dr { ///////////////////////////////////////////////////////////////////////// template <typename scalar, typename sparse_scalar_matrix> HDJointProbabilityGenerator<scalar, sparse_scalar_matrix>::Parameters::Parameters() : _perplexity(30), _perplexity_multiplier(3), _num_trees(4), _num_checks(1024), _aknn_algorithm(hdi::dr::KNN_ANNOY), _aknn_metric(hdi::dr::KNN_METRIC_EUCLIDEAN), _aknn_algorithmP1(16), // default parameter for HNSW _aknn_algorithmP2(200) // default parameter for HNSW {} ///////////////////////////////////////////////////////////////////////// template <typename scalar, typename sparse_scalar_matrix> HDJointProbabilityGenerator<scalar, sparse_scalar_matrix>::Statistics::Statistics() : _total_time(0), _trees_construction_time(0), _aknn_time(0), _distribution_time(0) {} template <typename scalar, typename sparse_scalar_matrix> void HDJointProbabilityGenerator<scalar, sparse_scalar_matrix>::Statistics::reset() { _total_time = 0; _trees_construction_time = 0; _aknn_time = 0; _distribution_time = 0; } template <typename scalar, typename sparse_scalar_matrix> void HDJointProbabilityGenerator<scalar, sparse_scalar_matrix>::Statistics::log(utils::AbstractLog* logger)const { utils::secureLog(logger, "\n-------- HD Joint Probability Generator Statistics -----------"); utils::secureLogValue(logger, "Total time", _total_time); utils::secureLogValue(logger, "\tTrees construction time", _trees_construction_time, true, 1); utils::secureLogValue(logger, "\tAKNN time", _aknn_time, true, 3); utils::secureLogValue(logger, "\tDistributions time", _distribution_time, true, 2); utils::secureLog(logger, "--------------------------------------------------------------\n"); } ///////////////////////////////////////////////////////////////////////// template <typename scalar, typename sparse_scalar_matrix> HDJointProbabilityGenerator<scalar, sparse_scalar_matrix>::HDJointProbabilityGenerator() : _logger(nullptr) { } template <typename scalar, typename sparse_scalar_matrix> void HDJointProbabilityGenerator<scalar, sparse_scalar_matrix>::computeJointProbabilityDistribution(scalar_type* high_dimensional_data, unsigned int num_dim, unsigned int num_dps, sparse_scalar_matrix& distribution, Parameters params) { utils::ScopedTimer<scalar_type, utils::Seconds> timer(_statistics._total_time); hdi::utils::secureLog(_logger, "Computing the HD joint probability distribution..."); distribution.resize(num_dps); std::vector<scalar_type> distances_squared; std::vector<int> indices; computeHighDimensionalDistances(high_dimensional_data, num_dim, num_dps, distances_squared, indices, params); computeGaussianDistributions(distances_squared, indices, distribution, params); symmetrize(distribution); } template <typename scalar, typename sparse_scalar_matrix> void HDJointProbabilityGenerator<scalar, sparse_scalar_matrix>::computeProbabilityDistributions(scalar_type* high_dimensional_data, unsigned int num_dim, unsigned int num_dps, sparse_scalar_matrix& distribution, Parameters params) { utils::ScopedTimer<scalar_type, utils::Seconds> timer(_statistics._total_time); hdi::utils::secureLog(_logger, "Computing the HD joint probability distribution..."); distribution.resize(num_dps); std::vector<scalar_type> distances_squared; std::vector<int> indices; computeHighDimensionalDistances(high_dimensional_data, num_dim, num_dps, distances_squared, indices, params); computeGaussianDistributions(distances_squared, indices, distribution, params); } template <typename scalar, typename sparse_scalar_matrix> void HDJointProbabilityGenerator<scalar, sparse_scalar_matrix>::computeProbabilityDistributions(scalar_type* high_dimensional_data, unsigned int num_dim, unsigned int num_dps, std::vector<scalar_type>& probabilities, std::vector<int>& indices, Parameters params) { utils::ScopedTimer<scalar_type, utils::Seconds> timer(_statistics._total_time); hdi::utils::secureLog(_logger, "Computing the HD joint probability distribution..."); std::vector<scalar_type> distances_squared; computeHighDimensionalDistances(high_dimensional_data, num_dim, num_dps, distances_squared, indices, params); computeGaussianDistributions(distances_squared, indices, probabilities, params); } template <typename scalar, typename sparse_scalar_matrix> void HDJointProbabilityGenerator<scalar, sparse_scalar_matrix>::computeHighDimensionalDistances(scalar_type* high_dimensional_data, unsigned int num_dim, unsigned int num_dps, std::vector<scalar_type>& distances_squared, std::vector<int>& indices, Parameters& params) { // Fallback to ANNOY if others are not supported #ifndef HNSWLIB_SUPPORTED if (params._aknn_algorithm == hdi::dr::KNN_HNSW) { hdi::utils::secureLog(_logger, "HNSW not available, falling back to ANNOY"); params._aknn_algorithm = hdi::dr::KNN_ANNOY; } #endif // HNSWLIB_SUPPORTED #ifndef __USE_ANNOY__ if (params._aknn_algorithm == hdi::dr::KNN_ANNOY) { params._aknn_algorithm = hdi::dr::KNN_HNSW; } #endif // __USE_ANNOY__ if (params._aknn_algorithm == hdi::dr::KNN_HNSW) { #ifdef HNSWLIB_SUPPORTED hdi::utils::secureLog(_logger, "Computing approximated knn with HNSWLIB..."); hnswlib::SpaceInterface<float> *space = NULL; switch (params._aknn_metric) { case hdi::dr::KNN_METRIC_EUCLIDEAN: space = new hnswlib::L2Space(num_dim); break; case hdi::dr::KNN_METRIC_INNER_PRODUCT: space = new hnswlib::InnerProductSpace(num_dim); break; default: space = new hnswlib::L2Space(num_dim); break; } hnswlib::HierarchicalNSW<scalar> appr_alg(space, num_dps, params._aknn_algorithmP1, params._aknn_algorithmP2, 0); { utils::ScopedTimer<scalar_type, utils::Seconds> timer(_statistics._trees_construction_time); appr_alg.addPoint((void*)high_dimensional_data, (std::size_t) 0); unsigned num_threads = std::thread::hardware_concurrency(); hnswlib::ParallelFor(1, num_dps, num_threads, [&](size_t i, size_t threadId) { appr_alg.addPoint((void*)(high_dimensional_data + (i*num_dim)), (hnswlib::labeltype) i); }); } const unsigned int nn = params._perplexity*params._perplexity_multiplier + 1; distances_squared.resize(num_dps*nn); indices.resize(num_dps*nn); { utils::ScopedTimer<scalar_type, utils::Seconds> timer(_statistics._aknn_time); #pragma omp parallel for for (int i = 0; i < num_dps; ++i) { auto top_candidates = appr_alg.searchKnn(high_dimensional_data + (i*num_dim), (hnswlib::labeltype)nn); while (top_candidates.size() > nn) { top_candidates.pop(); } auto *distances_offset = distances_squared.data() + (i*nn); auto indices_offset = indices.data() + (i*nn); int j = 0; while (top_candidates.size() > 0) { auto rez = top_candidates.top(); distances_offset[nn - j - 1] = rez.first; indices_offset[nn - j - 1] = appr_alg.getExternalLabel(rez.second); top_candidates.pop(); ++j; } } } #endif // HNSWLIB_SUPPORTED } else if (params._aknn_algorithm == hdi::dr::KNN_ANNOY) { #ifdef __USE_ANNOY__ int k = (int)params._perplexity * params._perplexity_multiplier + 1; int search_k = k * params._num_trees; distances_squared.resize(num_dps * k); indices.resize(num_dps * k); AnnoyIndexInterface<int, double>* tree = NULL; switch (params._aknn_metric) { case hdi::dr::KNN_METRIC_EUCLIDEAN: hdi::utils::secureLog(_logger, "Computing approximated knn with Annoy using Euclidean distances ..."); tree = new AnnoyIndex<int, double, Euclidean, Kiss32Random,AnnoyIndexSingleThreadedBuildPolicy>(num_dim); break; case hdi::dr::KNN_METRIC_COSINE: hdi::utils::secureLog(_logger, "Computing approximated knn with Annoy using Cosine distances ..."); tree = new AnnoyIndex<int, double, Angular, Kiss32Random, AnnoyIndexSingleThreadedBuildPolicy>(num_dim); break; case hdi::dr::KNN_METRIC_MANHATTAN: hdi::utils::secureLog(_logger, "Computing approximated knn with Annoy using Manhattan distances ..."); tree = new AnnoyIndex<int, double, Manhattan, Kiss32Random, AnnoyIndexSingleThreadedBuildPolicy>(num_dim); break; //case hdi::dr::KNN_METRIC_HAMMING: // hdi::utils::secureLog(_logger, "Computing approximated knn with Annoy using Euclidean distances ..."); // tree = new AnnoyIndex<int, double, Hamming, Kiss32Random>(num_dim); // break; case hdi::dr::KNN_METRIC_DOT: hdi::utils::secureLog(_logger, "Computing approximated knn with Annoy using Dot product distances ..."); tree = new AnnoyIndex<int, double, DotProduct, Kiss32Random, AnnoyIndexSingleThreadedBuildPolicy>(num_dim); break; default: hdi::utils::secureLog(_logger, "Computing approximated knn with Annoy using Euclidean distances ..."); tree = new AnnoyIndex<int, double, Euclidean, Kiss32Random, AnnoyIndexSingleThreadedBuildPolicy>(num_dim); break; } { utils::ScopedTimer<scalar_type, utils::Seconds> timer(_statistics._trees_construction_time); for (int i = 0; i < num_dps; ++i) { double* vec = new double[num_dim]; for (int z = 0; z < num_dim; ++z) { vec[z] = high_dimensional_data[i * num_dim + z]; } tree->add_item(i, vec); } tree->build(params._num_trees); // Sample check if it returns enough neighbors std::vector<int> closest; std::vector<double> closest_distances; for (int n = 0; n < 100; n++) { tree->get_nns_by_item(n, k, search_k, &closest, &closest_distances); unsigned int neighbors_count = closest.size(); if (neighbors_count < k) { printf("Requesting %d neighbors, but ANNOY returned only %u. Please increase search_k\n", k, neighbors_count); return; } } } hdi::utils::secureLog(_logger, "Done building tree. Beginning nearest neighbor search... "); { utils::ScopedTimer<scalar_type, utils::Seconds> timer(_statistics._aknn_time); #pragma omp parallel for for (int n = 0; n < num_dps; n++) { // Find nearest neighbors std::vector<int> closest; std::vector<double> closest_distances; tree->get_nns_by_item(n, k, search_k, &closest, &closest_distances); // Copy current row for (unsigned int m = 0; m < k; m++) { indices[n * k + m] = closest[m]; distances_squared[n * k + m] = closest_distances[m] * closest_distances[m]; } } } delete tree; #endif // __USE_ANNOY__ } } template <typename scalar, typename sparse_scalar_matrix> void HDJointProbabilityGenerator<scalar, sparse_scalar_matrix>::computeGaussianDistributions(const std::vector<scalar_type>& distances_squared, const std::vector<int>& indices, int nn, sparse_scalar_matrix& distribution, Parameters& params) { utils::ScopedTimer<scalar_type, utils::Seconds> timer(_statistics._distribution_time); utils::secureLog(_logger, "Computing joint-probability distribution..."); const int n = distribution.size(); #ifdef __USE_GCD__ __block scalar_vector_type temp_vector(distances_squared.size(), 0); #else scalar_vector_type temp_vector(distances_squared.size(), 0); #endif //__USE_GCD__ #ifdef __USE_GCD__ std::cout << "GCD dispatch, hd_joint_probability_generator 193.\n"; dispatch_apply(n, dispatch_get_global_queue(0, 0), ^ (size_t j) { #else #pragma omp parallel for for (int j = 0; j < n; ++j) { #endif //__USE_GCD__ const auto sigma = utils::computeGaussianDistributionWithFixedPerplexity<scalar_vector_type>( distances_squared.begin() + j * nn, //check squared distances_squared.begin() + (j + 1)*nn, temp_vector.begin() + j * nn, temp_vector.begin() + (j + 1)*nn, params._perplexity, 200, 1e-5, 0 ); } #ifdef __USE_GCD__ ); #endif for (int j = 0; j < n; ++j) { for (int k = 1; k < nn; ++k) { const unsigned int i = j * nn + k; // if items do not have all the same number of neighbors this is indicated by -1 if (indices[i] == -1) continue; distribution[j][indices[i]] = temp_vector[i]; } } } template <typename scalar, typename sparse_scalar_matrix> void HDJointProbabilityGenerator<scalar, sparse_scalar_matrix>::computeGaussianDistributions(const std::vector<scalar_type>& distances_squared, const std::vector<int>& indices, sparse_scalar_matrix& distribution, Parameters& params) { utils::ScopedTimer<scalar_type, utils::Seconds> timer(_statistics._distribution_time); utils::secureLog(_logger, "Computing joint-probability distribution..."); const int n = distribution.size(); const unsigned int nn = params._perplexity*params._perplexity_multiplier + 1; #ifdef __USE_GCD__ __block scalar_vector_type temp_vector(distances_squared.size(), 0); #else scalar_vector_type temp_vector(distances_squared.size(), 0); #endif //__USE_GCD__ #ifdef __USE_GCD__ std::cout << "GCD dispatch, hd_joint_probability_generator 193.\n"; dispatch_apply(n, dispatch_get_global_queue(0, 0), ^ (size_t j) { #else #pragma omp parallel for for (int j = 0; j < n; ++j) { #endif //__USE_GCD__ const auto sigma = utils::computeGaussianDistributionWithFixedPerplexity<scalar_vector_type>( distances_squared.begin() + j * nn, //check squared distances_squared.begin() + (j + 1)*nn, temp_vector.begin() + j * nn, temp_vector.begin() + (j + 1)*nn, params._perplexity, 200, 1e-5, 0 ); } #ifdef __USE_GCD__ ); #endif for (int j = 0; j < n; ++j) { for (int k = 1; k < nn; ++k) { const unsigned int i = j * nn + k; distribution[j][indices[i]] = temp_vector[i]; } } } template <typename scalar, typename sparse_scalar_matrix> void HDJointProbabilityGenerator<scalar, sparse_scalar_matrix>::computeGaussianDistributions(const std::vector<scalar_type>& distances_squared, const std::vector<int>& indices, std::vector<scalar_type>& probabilities, Parameters& params) { utils::ScopedTimer<scalar_type, utils::Seconds> timer(_statistics._distribution_time); utils::secureLog(_logger, "Computing joint-probability distribution..."); const unsigned int nn = params._perplexity*params._perplexity_multiplier + 1; const int n = indices.size() / nn; #ifdef __USE_GCD__ std::cout << "GCD dispatch, hd_joint_probability_generator 232.\n"; dispatch_apply(n, dispatch_get_global_queue(0, 0), ^ (size_t j) { #else #pragma omp parallel for for (int j = 0; j < n; ++j) { #endif //__USE_GCD__ const auto sigma = utils::computeGaussianDistributionWithFixedPerplexity<scalar_vector_type>( distances_squared.begin() + j * nn, //check squared distances_squared.begin() + (j + 1)*nn, probabilities.begin() + j * nn, probabilities.begin() + (j + 1)*nn, params._perplexity, 200, 1e-5, 0 ); } #ifdef __USE_GCD__ ); #endif } template <typename scalar, typename sparse_scalar_matrix> void HDJointProbabilityGenerator<scalar, sparse_scalar_matrix>::symmetrize(sparse_scalar_matrix& distribution) { const int n = distribution.size(); for (int j = 0; j < n; ++j) { for (auto& e : distribution[j]) { const unsigned int i = e.first; scalar new_val = (distribution[j][i] + distribution[i][j])*0.5; distribution[j][i] = new_val; distribution[i][j] = new_val; } } } template <typename scalar, typename sparse_scalar_matrix> void HDJointProbabilityGenerator<scalar, sparse_scalar_matrix>::computeProbabilityDistributionsFromDistanceMatrix(const std::vector<scalar_type>& squared_distance_matrix, unsigned int num_dps, sparse_scalar_matrix& distribution, Parameters params) { utils::ScopedTimer<scalar_type, utils::Seconds> timer(_statistics._distribution_time); utils::secureLog(_logger, "Computing joint-probability distribution..."); const int n = num_dps; const unsigned int nn = num_dps; #ifdef __USE_GCD__ __block scalar_vector_type temp_vector(num_dps*num_dps, 0); #else scalar_vector_type temp_vector(num_dps*num_dps, 0); #endif //__USE_GCD__ distribution.clear(); distribution.resize(n); #ifdef __USE_GCD__ std::cout << "GCD dispatch, hd_joint_probability_generator 193.\n"; dispatch_apply(n, dispatch_get_global_queue(0, 0), ^ (size_t j) { #else #pragma omp parallel for for (int j = 0; j < n; ++j) { #endif //__USE_GCD__ const auto sigma = utils::computeGaussianDistributionWithFixedPerplexity<scalar_vector_type>( squared_distance_matrix.begin() + j * nn, //check squared squared_distance_matrix.begin() + (j + 1)*nn, temp_vector.begin() + j * nn, temp_vector.begin() + (j + 1)*nn, params._perplexity, 200, 1e-5, j ); } #ifdef __USE_GCD__ ); #endif for (int j = 0; j < n; ++j) { for (int k = 0; k < nn; ++k) { const unsigned int i = j * nn + k; distribution[j][k] = temp_vector[i]; } } } ///////////////////////////////////////////////////////////////////////////////////7 } } #endif
threads1.c
#include <stdio.h> #include <omp.h> void* thread_function(); int contador_global = 0; int main(int argc, char* argv[]) { unsigned int num_threads = omp_get_thread_num(); if (argc >= 2) { num_threads = atoi(argv[1]); } printf("Executing with %d threads.\n", num_threads); #pragma omp parallel for for (unsigned int i = 0; i < num_threads; ++i) { thread_function(num_threads); } #pragma omp single printf("%d", contador_global); return 0; } void* thread_function(unsigned int num_threads) { for (int i = 0; i < num_threads * 1000; ++i) { #pragma omp critical contador_global++; } }
3rd_compress.h
// compress.c de/compressors into a single-file header // - rlyeh, public domain // // current file format: // header : [1<<block_size:8][1<<excess:8] // chunk : [len:32] [fmt:4|lvl:4] [data:X] // // @todo: new format // header : [1<<block_size:8][1<<excess:8] // chunk : [len:32][fmt|lvl:8][data:X][fmt|lvl:8][crc:32] // // @todo: endianness // @todo: 0(store),1..(6)..9,10..15(uber) // @todo: expose new/del ctx (workmem) // @todo: compressed file seeking #ifndef COMPRESS_H #define COMPRESS_H #define COMPRESS_VERSION "v1.1.0" #include <stdio.h> #ifndef REALLOC #define REALLOC realloc #endif // compressor type [0..15]: high nibble // compression level/flags [0..15]: low hibble // compressor_type << 4 + compression_level = 1 byte enum { RAW = 0, PPP = (1<<4), ULZ = (2<<4), LZ4X = (3<<4), CRSH = (4<<4), DEFL = (5<<4), LZP1 = (6<<4), LZMA = (7<<4), BALZ = (8<<4), LZW3 = (9<<4), LZSS = (10<<4), BCM = (11<<4), NUM_PACKESSORS = 13 }; // mem de/encoder unsigned mem_bounds(unsigned inlen, unsigned compressor); unsigned mem_encode(const void *in, unsigned inlen, void *out, unsigned outlen, unsigned compressor); unsigned mem_excess(unsigned compressor); unsigned mem_decode(const void *in, unsigned inlen, void *out, unsigned outlen); // file de/encoder unsigned file_encode(FILE* in, FILE* out, FILE *logfile, unsigned cnum, unsigned *clist); unsigned file_decode(FILE* in, FILE* out, FILE *logfile); #endif // COMPRESS_H #ifdef COMPRESS_C #pragma once #define RAW_C #define PPP_C #define ULZ_C #define LZ4X_C #define CRUSH_C #define DEFLATE_C #define LZP1_C #define LZMA_C #define BALZ_C #define LZRW3A_C #define LZSS_C #define BCM_C #endif //#line 1 "amalgamated_balz.c" // balz.cpp is written and placed in the public domain by Ilya Muravyov // additional code by @r-lyeh (public domain) unsigned balz_encode(const void *in, unsigned inlen, void *out, unsigned outlen, unsigned flags /*[0..1]*/); unsigned balz_decode(const void *in, unsigned inlen, void *out, unsigned outlen); unsigned balz_bounds(unsigned inlen, unsigned flags); unsigned balz_excess(unsigned flags); #ifdef BALZ_C #pragma once #define _CRT_SECURE_NO_WARNINGS #define _CRT_DISABLE_PERFCRIT_LOCKS #include <stdlib.h> #include <string.h> #include <stdint.h> typedef struct mfile { uint8_t *begin, *seek, *end; } mfile; int minit(mfile *f, const void *ptr, int len) { f->begin = f->seek = f->end = (uint8_t*)ptr; f->end += len; return 0; } int mread(mfile *m, void *buf, int len) { if( len >= (m->end - m->seek) ) len = (m->end - m->seek); memcpy(buf,m->seek,len); m->seek += len; return len; } int mwrite(mfile *m, const void *buf, int len) { if( len >= (m->end - m->seek) ) len = (m->end - m->seek); memcpy(m->seek,buf,len); m->seek += len; return len; } int mtell(mfile *m) { return m->seek - m->begin; } int mavail(mfile *m) { return m->end - m->seek; } int mputc(mfile *m, int i) { uint8_t ch = i; return mwrite(m, &ch, 1); } int mgetc(mfile *m) { if( mavail(m) <= 0 ) return -1; uint8_t ch; mread(m, &ch, 1); return ch; } typedef struct Counter { uint16_t p1; uint16_t p2; } Counter; void CounterCtor(Counter *c) { c->p1 = 1<<15; c->p2 = 1<<15; } uint32_t CounterP(const Counter *c) { return c->p1+c->p2; } void CounterUpdate0(Counter *c) { c->p1-=c->p1>>3; c->p2-=c->p2>>6; } void CounterUpdate1(Counter *c) { c->p1+=(c->p1^65535)>>3; c->p2+=(c->p2^65535)>>6; } typedef struct Encoder { uint32_t code; uint32_t low; uint32_t high; mfile *in, *out; } Encoder; void EncoderCtor(Encoder *e, mfile *in, mfile *out) { e->code = e->low = 0; e->high = -1; e->in = in; e->out = out; } void EncoderEncode(Encoder *e, int bit, Counter *c) { const uint32_t mid=e->low+((((uint64_t)e->high-e->low)*(CounterP(c)<<15))>>32); if (bit) { e->high=mid; CounterUpdate1(c); } else { e->low=mid+1; CounterUpdate0(c); } while ((e->low^e->high)<(1<<24)) { mputc(e->out, e->low>>24); e->low<<=8; e->high=(e->high<<8)|255; } } void EncoderFlush(Encoder *e) { for (int i=0; i<4; ++i) { mputc(e->out, e->low>>24); e->low<<=8; } } void EncoderInit(Encoder *e) { for (int i=0; i<4; ++i) e->code=(e->code<<8)|mgetc(e->in); } int EncoderDecode(Encoder *e, Counter *c) { const uint32_t mid=e->low+((((uint64_t)e->high-e->low)*(CounterP(c)<<15))>>32); const int bit=(e->code<=mid); if (bit) { e->high=mid; CounterUpdate1(c); } else { e->low=mid+1; CounterUpdate0(c); } while ((e->low^e->high)<(1<<24)) { e->code=(e->code<<8)|mgetc(e->in); e->low<<=8; e->high=(e->high<<8)|255; } return bit; } enum { BALZ_TAB_BITS=7 }; enum { BALZ_TAB_SIZE=1<<BALZ_TAB_BITS }; enum { BALZ_TAB_MASK=BALZ_TAB_SIZE-1 }; typedef struct CM { Encoder encoder; Counter counter1[256][512]; Counter counter2[256][BALZ_TAB_SIZE]; } CM; void CMCtor(CM *cm, mfile *in, mfile *out) { EncoderCtor(&cm->encoder, in, out); for( int i = 0; i < 256; ++i) for( int j = 0; j < 512; ++j) CounterCtor(&cm->counter1[i][j]); for( int i = 0; i < 256; ++i) for( int j = 0; j < BALZ_TAB_SIZE; ++j) CounterCtor(&cm->counter2[i][j]); } void CMInit(CM *cm) { EncoderInit(&cm->encoder); } void CMEncode(CM *cm, int t, int c1) { int ctx=1; while (ctx<512) { const int bit=((t&256)!=0); t+=t; EncoderEncode(&cm->encoder, bit, &cm->counter1[c1][ctx]); ctx+=ctx+bit; } } void CMEncodeIdx(CM *cm, int x, int c2) { int ctx=1; while (ctx<BALZ_TAB_SIZE) { const int bit=((x&(BALZ_TAB_SIZE>>1))!=0); x+=x; EncoderEncode(&cm->encoder, bit, &cm->counter2[c2][ctx]); ctx+=ctx+bit; } } int CMDecode(CM *cm, int c1) { int ctx=1; while (ctx<512) ctx+=ctx+EncoderDecode(&cm->encoder, &cm->counter1[c1][ctx]); return ctx-512; } int CMDecodeIdx(CM *cm, int c2) { int ctx=1; while (ctx<BALZ_TAB_SIZE) ctx+=ctx+EncoderDecode(&cm->encoder, &cm->counter2[c2][ctx]); return ctx-BALZ_TAB_SIZE; } enum { BALZ_MIN_MATCH=3 }; enum { BALZ_MAX_MATCH=255+BALZ_MIN_MATCH }; enum { BALZ_BUF_BITS=25 }; enum { BALZ_BUF_SIZE=1<<BALZ_BUF_BITS }; enum { BALZ_BUF_MASK=BALZ_BUF_SIZE-1 }; uint8_t buf[BALZ_BUF_SIZE]; uint32_t tab[1<<16][BALZ_TAB_SIZE]; int cnt[1<<16]; void balz_init() { size_t buflen = sizeof(uint8_t) * BALZ_BUF_SIZE; memset(buf, 0, buflen); size_t cntlen = sizeof(int) * (1<<16); memset(cnt, 0, cntlen); for(int i = 0; i < (1<<16); ++i) for(int j = 0; j < BALZ_TAB_SIZE; ++j) tab[i][j] = 0; } // E8E9 preprocessor to improve compression of x86 (EXE and DLL) files. // The preprocessor replaces relative CALL and JMP addresses with absolute addresses, // which improves compression because an address may appear multiple times. // Many other compressors use this technique. #define e8e9_transform(FWD,n) do { \ const int end=n-8; \ int p=0; \ while((*((int*)&buf[p])!=0x4550)&&(++p<end)); /* unaligned */ \ while (p<end) { \ if ((buf[p++]&254)==0xe8) { \ int *addr=(int*)&buf[p]; /* unaligned */ \ if (FWD) { \ if ((*addr>=-p)&&(*addr<(n-p))) \ *addr+=p; \ else if ((*addr>0)&&(*addr<n)) \ *addr-=n; \ } else { \ if (*addr<0) { \ if ((*addr+p)>=0) \ *addr+=n; \ } \ else if (*addr<n) \ *addr-=p; \ } \ p+=4; \ } \ } \ } while(0) static inline uint32_t get_hash(int p) { return (((*(uint32_t*)(&buf[p]))&0xffffff) *2654435769UL)&~BALZ_BUF_MASK; // Little-endian+unaligned } static inline int get_pts(int len, int x) { return len>=BALZ_MIN_MATCH?(len<<BALZ_TAB_BITS)-x:((BALZ_MIN_MATCH-1)<<BALZ_TAB_BITS)-8; } int get_pts_at(int p, int n) { const int c2=*(uint16_t*)&buf[p-2]; // unaligned const uint32_t hash=get_hash(p); int len=BALZ_MIN_MATCH-1; int idx=BALZ_TAB_SIZE; int max_match=n-p; if (max_match>BALZ_MAX_MATCH) max_match=BALZ_MAX_MATCH; for (int x=0; x<BALZ_TAB_SIZE; ++x) { const uint32_t d=tab[c2][(cnt[c2]-x)&BALZ_TAB_MASK]; if (!d) break; if ((d&~BALZ_BUF_MASK)!=hash) continue; const int s=d&BALZ_BUF_MASK; if ((buf[s+len]!=buf[p+len])||(buf[s]!=buf[p])) continue; int l=0; while (++l<max_match) if (buf[s+l]!=buf[p+l]) break; if (l>len) { idx=x; len=l; if (l==max_match) break; } } return get_pts(len, idx); } int balz_compress(const uint8_t *in, unsigned inlen, uint8_t *out, unsigned outlen, unsigned is_max) { balz_init(); *out++ = (inlen >> 24) & 255; *out++ = (inlen >> 16) & 255; *out++ = (inlen >> 8) & 255; *out++ = (inlen >> 0) & 255; outlen -= 4; mfile inf, outf; minit(&inf, in, inlen); minit(&outf, out, outlen); CM cm; CMCtor(&cm, &inf, &outf); int best_idx[BALZ_MAX_MATCH+1]; int n; while ((n=mread(&inf, buf, BALZ_BUF_SIZE))>0) { //e8e9_transform(1,n); memset(tab, 0, sizeof(tab)); int p=0; while ((p<2)&&(p<n)) CMEncode(&cm, buf[p++], 0); while (p<n) { const int c2=*(uint16_t*)&buf[p-2]; // unaligned const uint32_t hash=get_hash(p); int len=BALZ_MIN_MATCH-1; int idx=BALZ_TAB_SIZE; int max_match=n-p; if (max_match>BALZ_MAX_MATCH) max_match=BALZ_MAX_MATCH; for (int x=0; x<BALZ_TAB_SIZE; ++x) { const uint32_t d=tab[c2][(cnt[c2]-x)&BALZ_TAB_MASK]; if (!d) break; if ((d&~BALZ_BUF_MASK)!=hash) continue; const int s=d&BALZ_BUF_MASK; if ((buf[s+len]!=buf[p+len])||(buf[s]!=buf[p])) continue; int l=0; while (++l<max_match) if (buf[s+l]!=buf[p+l]) break; if (l>len) { for (int i=l; i>len; --i) best_idx[i]=x; idx=x; len=l; if (l==max_match) break; } } if ((is_max)&&(len>=BALZ_MIN_MATCH)) { int sum=get_pts(len, idx)+get_pts_at(p+len, n); if (sum<get_pts(len+BALZ_MAX_MATCH, 0)) { const int lookahead=len; for (int i=1; i<lookahead; ++i) { const int tmp=get_pts(i, best_idx[i])+get_pts_at(p+i, n); if (tmp>sum) { sum=tmp; len=i; } } idx=best_idx[len]; } } tab[c2][++cnt[c2]&BALZ_TAB_MASK]=hash|p; if (len>=BALZ_MIN_MATCH) { CMEncode(&cm, (256-BALZ_MIN_MATCH)+len, buf[p-1]); CMEncodeIdx(&cm, idx, buf[p-2]); p+=len; } else { CMEncode(&cm, buf[p], buf[p-1]); ++p; } } } EncoderFlush(&cm.encoder); if ( (inf.seek - inf.begin) != inlen) { return 0; // size mismatch error } return (int)(outf.seek - outf.begin) + 4; } int balz_decompress(const uint8_t *in, unsigned inlen, uint8_t *out, unsigned outlen) { balz_init(); uint32_t flen32 = 0; flen32 |= ((uint32_t)*in++) << 24; flen32 |= ((uint32_t)*in++) << 16; flen32 |= ((uint32_t)*in++) << 8; flen32 |= ((uint32_t)*in++) << 0; outlen = flen32; int flen = flen32; inlen -= 4; mfile inf, outf; minit(&inf, in, inlen); minit(&outf, out, outlen); CM cm; CMCtor(&cm, &inf, &outf); CMInit(&cm); #define balz_src_avail ((int)(inf.end - inf.seek)) #define balz_dst_avail ((int)(outf.end - outf.seek)) #define balz_dst_written ((int)(outf.seek - outf.begin)) while(/*(balz_src_avail > 0) &&*/ (balz_dst_written != flen)) { int p=0; while ((p<2) && ((p+balz_dst_written)<flen)) { const int t=CMDecode(&cm, 0); if (t>=256) { return 0; // corrupt file error } buf[p++]=t; } while ((p < BALZ_BUF_SIZE) && (p+balz_dst_written<flen)) { // (balz_src_avail > 0)) { const int tmp=p; const int c2=*(uint16_t*)(&buf[p-2]); // unaligned const int t=CMDecode(&cm, buf[p-1]); if (t>=256) { int len=t-256; int s=tab[c2][(cnt[c2]-CMDecodeIdx(&cm, buf[p-2]))&BALZ_TAB_MASK]; buf[p++]=buf[s++]; buf[p++]=buf[s++]; buf[p++]=buf[s++]; while (len--) buf[p++]=buf[s++]; } else buf[p++]=t; tab[c2][++cnt[c2]&BALZ_TAB_MASK]=tmp; } //e8e9_transform(0,p); mwrite(&outf, buf, p); } return (int)(outf.seek - outf.begin); } unsigned balz_encode(const void *in, unsigned inlen, void *out, unsigned outlen, unsigned flags /*[0..1]*/) { unsigned level = flags > 0 ? 1 : 0; return (unsigned)balz_compress((const uint8_t *)in, inlen, (uint8_t*)out, outlen, level); } unsigned balz_decode(const void *in, unsigned inlen, void *out, unsigned outlen) { return (unsigned)balz_decompress((const uint8_t *)in, inlen, (uint8_t*)out, outlen); } unsigned balz_bounds(unsigned inlen, unsigned flags) { return (unsigned)(inlen * 1.1) + 16; // @todo: check src } unsigned balz_excess(unsigned flags) { return (unsigned)0; } #endif // BALZ_C #ifdef BALZ_DEMO #pragma once #include <string.h> int main() { const char *longcopy = "Hello world! Hello world! Hello world! Hello world!"; int level=1; char out[128]; unsigned outlen = balz_encode(longcopy, strlen(longcopy)+1, out, 128, level); printf("%s %d->%d\n", outlen ? "ok" : "fail", (int)strlen(longcopy)+1, (int)outlen); char redo[128]; unsigned unpacked = balz_decode(out, outlen, redo, 128); printf("%d->%d %s\n", (int)outlen, (int)unpacked, redo); } #define main main__ #endif // BALZ_DEMO //#line 1 "amalgamated_bcm_bwt.c" #ifndef BCM_C // do nothing #elif defined BCM_NO_ENCODER // dummy int bcm_divbwt(const unsigned char *T, unsigned char *U, int *A, int n) { return -1; } #else /* * divsufsort.h for libdivsufsort-lite * Copyright (c) 2003-2008 Yuta Mori All Rights Reserved. * * 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. */ #ifndef _DIVSUFSORT_H #define _DIVSUFSORT_H 1 #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /*- Prototypes -*/ /** * Constructs the suffix array of a given string. * @param T[0..n-1] The input string. * @param SA[0..n-1] The output array of suffixes. * @param n The length of the given string. * @return 0 if no error occurred, -1 or -2 otherwise. */ int bcm_divsufsort(const unsigned char *T, int *SA, int n); /** * Constructs the burrows-wheeler transformed string of a given string. * @param T[0..n-1] The input string. * @param U[0..n-1] The output string. (can be T) * @param A[0..n-1] The temporary array. (can be NULL) * @param n The length of the given string. * @return The primary index if no error occurred, -1 or -2 otherwise. */ int bcm_divbwt(const unsigned char *T, unsigned char *U, int *A, int n); #ifdef __cplusplus } /* extern "C" */ #endif /* __cplusplus */ #endif /* _DIVSUFSORT_H */ /* * divsufsort.c for libdivsufsort-lite * Copyright (c) 2003-2008 Yuta Mori All Rights Reserved. * * 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 <assert.h> #include <stdio.h> #include <stdlib.h> #ifdef _OPENMP # include <omp.h> #endif //#include "bcm_divsufsort.h" /*- Constants -*/ #define INLINE __inline #if defined(ALPHABET_SIZE) && (ALPHABET_SIZE < 1) # undef ALPHABET_SIZE #endif #if !defined(ALPHABET_SIZE) # define ALPHABET_SIZE (256) #endif #define BUCKET_A_SIZE (ALPHABET_SIZE) #define BUCKET_B_SIZE (ALPHABET_SIZE * ALPHABET_SIZE) #if defined(SS_INSERTIONSORT_THRESHOLD) # if SS_INSERTIONSORT_THRESHOLD < 1 # undef SS_INSERTIONSORT_THRESHOLD # define SS_INSERTIONSORT_THRESHOLD (1) # endif #else # define SS_INSERTIONSORT_THRESHOLD (8) #endif #if defined(SS_BLOCKSIZE) # if SS_BLOCKSIZE < 0 # undef SS_BLOCKSIZE # define SS_BLOCKSIZE (0) # elif 32768 <= SS_BLOCKSIZE # undef SS_BLOCKSIZE # define SS_BLOCKSIZE (32767) # endif #else # define SS_BLOCKSIZE (1024) #endif /* minstacksize = log(SS_BLOCKSIZE) / log(3) * 2 */ #if SS_BLOCKSIZE == 0 # define SS_MISORT_STACKSIZE (96) #elif SS_BLOCKSIZE <= 4096 # define SS_MISORT_STACKSIZE (16) #else # define SS_MISORT_STACKSIZE (24) #endif #define SS_SMERGE_STACKSIZE (32) #define TR_INSERTIONSORT_THRESHOLD (8) #define TR_STACKSIZE (64) /*- Macros -*/ #ifndef SWAP # define SWAP(_a, _b) do { t = (_a); (_a) = (_b); (_b) = t; } while(0) #endif /* SWAP */ #ifndef MIN # define MIN(_a, _b) (((_a) < (_b)) ? (_a) : (_b)) #endif /* MIN */ #ifndef MAX # define MAX(_a, _b) (((_a) > (_b)) ? (_a) : (_b)) #endif /* MAX */ #define STACK_PUSH(_a, _b, _c, _d)\ do {\ assert(ssize < STACK_SIZE);\ stack[ssize].a = (_a), stack[ssize].b = (_b),\ stack[ssize].c = (_c), stack[ssize++].d = (_d);\ } while(0) #define STACK_PUSH5(_a, _b, _c, _d, _e)\ do {\ assert(ssize < STACK_SIZE);\ stack[ssize].a = (_a), stack[ssize].b = (_b),\ stack[ssize].c = (_c), stack[ssize].d = (_d), stack[ssize++].e = (_e);\ } while(0) #define STACK_POP(_a, _b, _c, _d)\ do {\ assert(0 <= ssize);\ if(ssize == 0) { return; }\ (_a) = stack[--ssize].a, (_b) = stack[ssize].b,\ (_c) = stack[ssize].c, (_d) = stack[ssize].d;\ } while(0) #define STACK_POP5(_a, _b, _c, _d, _e)\ do {\ assert(0 <= ssize);\ if(ssize == 0) { return; }\ (_a) = stack[--ssize].a, (_b) = stack[ssize].b,\ (_c) = stack[ssize].c, (_d) = stack[ssize].d, (_e) = stack[ssize].e;\ } while(0) #define BUCKET_A(_c0) bucket_A[(_c0)] #if ALPHABET_SIZE == 256 #define BUCKET_B(_c0, _c1) (bucket_B[((_c1) << 8) | (_c0)]) #define BUCKET_BSTAR(_c0, _c1) (bucket_B[((_c0) << 8) | (_c1)]) #else #define BUCKET_B(_c0, _c1) (bucket_B[(_c1) * ALPHABET_SIZE + (_c0)]) #define BUCKET_BSTAR(_c0, _c1) (bucket_B[(_c0) * ALPHABET_SIZE + (_c1)]) #endif /*- Private Functions -*/ static const int lg_table[256]= { -1,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7 }; #if (SS_BLOCKSIZE == 0) || (SS_INSERTIONSORT_THRESHOLD < SS_BLOCKSIZE) static INLINE int ss_ilg(int n) { #if SS_BLOCKSIZE == 0 return (n & 0xffff0000) ? ((n & 0xff000000) ? 24 + lg_table[(n >> 24) & 0xff] : 16 + lg_table[(n >> 16) & 0xff]) : ((n & 0x0000ff00) ? 8 + lg_table[(n >> 8) & 0xff] : 0 + lg_table[(n >> 0) & 0xff]); #elif SS_BLOCKSIZE < 256 return lg_table[n]; #else return (n & 0xff00) ? 8 + lg_table[(n >> 8) & 0xff] : 0 + lg_table[(n >> 0) & 0xff]; #endif } #endif /* (SS_BLOCKSIZE == 0) || (SS_INSERTIONSORT_THRESHOLD < SS_BLOCKSIZE) */ #if SS_BLOCKSIZE != 0 static const int sqq_table[256] = { 0, 16, 22, 27, 32, 35, 39, 42, 45, 48, 50, 53, 55, 57, 59, 61, 64, 65, 67, 69, 71, 73, 75, 76, 78, 80, 81, 83, 84, 86, 87, 89, 90, 91, 93, 94, 96, 97, 98, 99, 101, 102, 103, 104, 106, 107, 108, 109, 110, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 128, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 144, 145, 146, 147, 148, 149, 150, 150, 151, 152, 153, 154, 155, 155, 156, 157, 158, 159, 160, 160, 161, 162, 163, 163, 164, 165, 166, 167, 167, 168, 169, 170, 170, 171, 172, 173, 173, 174, 175, 176, 176, 177, 178, 178, 179, 180, 181, 181, 182, 183, 183, 184, 185, 185, 186, 187, 187, 188, 189, 189, 190, 191, 192, 192, 193, 193, 194, 195, 195, 196, 197, 197, 198, 199, 199, 200, 201, 201, 202, 203, 203, 204, 204, 205, 206, 206, 207, 208, 208, 209, 209, 210, 211, 211, 212, 212, 213, 214, 214, 215, 215, 216, 217, 217, 218, 218, 219, 219, 220, 221, 221, 222, 222, 223, 224, 224, 225, 225, 226, 226, 227, 227, 228, 229, 229, 230, 230, 231, 231, 232, 232, 233, 234, 234, 235, 235, 236, 236, 237, 237, 238, 238, 239, 240, 240, 241, 241, 242, 242, 243, 243, 244, 244, 245, 245, 246, 246, 247, 247, 248, 248, 249, 249, 250, 250, 251, 251, 252, 252, 253, 253, 254, 254, 255 }; static INLINE int ss_isqrt(int x) { int y, e; if(x >= (SS_BLOCKSIZE * SS_BLOCKSIZE)) { return SS_BLOCKSIZE; } e = (x & 0xffff0000) ? ((x & 0xff000000) ? 24 + lg_table[(x >> 24) & 0xff] : 16 + lg_table[(x >> 16) & 0xff]) : ((x & 0x0000ff00) ? 8 + lg_table[(x >> 8) & 0xff] : 0 + lg_table[(x >> 0) & 0xff]); if(e >= 16) { y = sqq_table[x >> ((e - 6) - (e & 1))] << ((e >> 1) - 7); if(e >= 24) { y = (y + 1 + x / y) >> 1; } y = (y + 1 + x / y) >> 1; } else if(e >= 8) { y = (sqq_table[x >> ((e - 6) - (e & 1))] >> (7 - (e >> 1))) + 1; } else { return sqq_table[x] >> 4; } return (x < (y * y)) ? y - 1 : y; } #endif /* SS_BLOCKSIZE != 0 */ /*---------------------------------------------------------------------------*/ /* Compares two suffixes. */ static INLINE int ss_compare(const unsigned char *T, const int *p1, const int *p2, int depth) { const unsigned char *U1, *U2, *U1n, *U2n; for(U1 = T + depth + *p1, U2 = T + depth + *p2, U1n = T + *(p1 + 1) + 2, U2n = T + *(p2 + 1) + 2; (U1 < U1n) && (U2 < U2n) && (*U1 == *U2); ++U1, ++U2) { } return U1 < U1n ? (U2 < U2n ? *U1 - *U2 : 1) : (U2 < U2n ? -1 : 0); } /*---------------------------------------------------------------------------*/ #if (SS_BLOCKSIZE != 1) && (SS_INSERTIONSORT_THRESHOLD != 1) /* Insertionsort for small size groups */ static void ss_insertionsort(const unsigned char *T, const int *PA, int *first, int *last, int depth) { int *i, *j; int t; int r; for(i = last - 2; first <= i; --i) { for(t = *i, j = i + 1; 0 < (r = ss_compare(T, PA + t, PA + *j, depth));) { do { *(j - 1) = *j; } while((++j < last) && (*j < 0)); if(last <= j) { break; } } if(r == 0) { *j = ~*j; } *(j - 1) = t; } } #endif /* (SS_BLOCKSIZE != 1) && (SS_INSERTIONSORT_THRESHOLD != 1) */ /*---------------------------------------------------------------------------*/ #if (SS_BLOCKSIZE == 0) || (SS_INSERTIONSORT_THRESHOLD < SS_BLOCKSIZE) static INLINE void ss_fixdown(const unsigned char *Td, const int *PA, int *SA, int i, int size) { int j, k; int v; int c, d, e; for(v = SA[i], c = Td[PA[v]]; (j = 2 * i + 1) < size; SA[i] = SA[k], i = k) { d = Td[PA[SA[k = j++]]]; if(d < (e = Td[PA[SA[j]]])) { k = j; d = e; } if(d <= c) { break; } } SA[i] = v; } /* Simple top-down heapsort. */ static void ss_heapsort(const unsigned char *Td, const int *PA, int *SA, int size) { int i, m; int t; m = size; if((size % 2) == 0) { m--; if(Td[PA[SA[m / 2]]] < Td[PA[SA[m]]]) { SWAP(SA[m], SA[m / 2]); } } for(i = m / 2 - 1; 0 <= i; --i) { ss_fixdown(Td, PA, SA, i, m); } if((size % 2) == 0) { SWAP(SA[0], SA[m]); ss_fixdown(Td, PA, SA, 0, m); } for(i = m - 1; 0 < i; --i) { t = SA[0], SA[0] = SA[i]; ss_fixdown(Td, PA, SA, 0, i); SA[i] = t; } } /*---------------------------------------------------------------------------*/ /* Returns the median of three elements. */ static INLINE int * ss_median3(const unsigned char *Td, const int *PA, int *v1, int *v2, int *v3) { int *t; if(Td[PA[*v1]] > Td[PA[*v2]]) { SWAP(v1, v2); } if(Td[PA[*v2]] > Td[PA[*v3]]) { if(Td[PA[*v1]] > Td[PA[*v3]]) { return v1; } else { return v3; } } return v2; } /* Returns the median of five elements. */ static INLINE int * ss_median5(const unsigned char *Td, const int *PA, int *v1, int *v2, int *v3, int *v4, int *v5) { int *t; if(Td[PA[*v2]] > Td[PA[*v3]]) { SWAP(v2, v3); } if(Td[PA[*v4]] > Td[PA[*v5]]) { SWAP(v4, v5); } if(Td[PA[*v2]] > Td[PA[*v4]]) { SWAP(v2, v4); SWAP(v3, v5); } if(Td[PA[*v1]] > Td[PA[*v3]]) { SWAP(v1, v3); } if(Td[PA[*v1]] > Td[PA[*v4]]) { SWAP(v1, v4); SWAP(v3, v5); } if(Td[PA[*v3]] > Td[PA[*v4]]) { return v4; } return v3; } /* Returns the pivot element. */ static INLINE int * ss_pivot(const unsigned char *Td, const int *PA, int *first, int *last) { int *middle; int t; t = last - first; middle = first + t / 2; if(t <= 512) { if(t <= 32) { return ss_median3(Td, PA, first, middle, last - 1); } else { t >>= 2; return ss_median5(Td, PA, first, first + t, middle, last - 1 - t, last - 1); } } t >>= 3; first = ss_median3(Td, PA, first, first + t, first + (t << 1)); middle = ss_median3(Td, PA, middle - t, middle, middle + t); last = ss_median3(Td, PA, last - 1 - (t << 1), last - 1 - t, last - 1); return ss_median3(Td, PA, first, middle, last); } /*---------------------------------------------------------------------------*/ /* Binary partition for substrings. */ static INLINE int * ss_partition(const int *PA, int *first, int *last, int depth) { int *a, *b; int t; for(a = first - 1, b = last;;) { for(; (++a < b) && ((PA[*a] + depth) >= (PA[*a + 1] + 1));) { *a = ~*a; } for(; (a < --b) && ((PA[*b] + depth) < (PA[*b + 1] + 1));) { } if(b <= a) { break; } t = ~*b; *b = *a; *a = t; } if(first < a) { *first = ~*first; } return a; } /* Multikey introsort for medium size groups. */ static void ss_mintrosort(const unsigned char *T, const int *PA, int *first, int *last, int depth) { #define STACK_SIZE SS_MISORT_STACKSIZE struct { int *a, *b, c; int d; } stack[STACK_SIZE]; const unsigned char *Td; int *a, *b, *c, *d, *e, *f; int s, t; int ssize; int limit; int v, x = 0; for(ssize = 0, limit = ss_ilg(last - first);;) { if((last - first) <= SS_INSERTIONSORT_THRESHOLD) { #if 1 < SS_INSERTIONSORT_THRESHOLD if(1 < (last - first)) { ss_insertionsort(T, PA, first, last, depth); } #endif STACK_POP(first, last, depth, limit); continue; } Td = T + depth; if(limit-- == 0) { ss_heapsort(Td, PA, first, last - first); } if(limit < 0) { for(a = first + 1, v = Td[PA[*first]]; a < last; ++a) { if((x = Td[PA[*a]]) != v) { if(1 < (a - first)) { break; } v = x; first = a; } } if(Td[PA[*first] - 1] < v) { first = ss_partition(PA, first, a, depth); } if((a - first) <= (last - a)) { if(1 < (a - first)) { STACK_PUSH(a, last, depth, -1); last = a, depth += 1, limit = ss_ilg(a - first); } else { first = a, limit = -1; } } else { if(1 < (last - a)) { STACK_PUSH(first, a, depth + 1, ss_ilg(a - first)); first = a, limit = -1; } else { last = a, depth += 1, limit = ss_ilg(a - first); } } continue; } /* choose pivot */ a = ss_pivot(Td, PA, first, last); v = Td[PA[*a]]; SWAP(*first, *a); /* partition */ for(b = first; (++b < last) && ((x = Td[PA[*b]]) == v);) { } if(((a = b) < last) && (x < v)) { for(; (++b < last) && ((x = Td[PA[*b]]) <= v);) { if(x == v) { SWAP(*b, *a); ++a; } } } for(c = last; (b < --c) && ((x = Td[PA[*c]]) == v);) { } if((b < (d = c)) && (x > v)) { for(; (b < --c) && ((x = Td[PA[*c]]) >= v);) { if(x == v) { SWAP(*c, *d); --d; } } } for(; b < c;) { SWAP(*b, *c); for(; (++b < c) && ((x = Td[PA[*b]]) <= v);) { if(x == v) { SWAP(*b, *a); ++a; } } for(; (b < --c) && ((x = Td[PA[*c]]) >= v);) { if(x == v) { SWAP(*c, *d); --d; } } } if(a <= d) { c = b - 1; if((s = a - first) > (t = b - a)) { s = t; } for(e = first, f = b - s; 0 < s; --s, ++e, ++f) { SWAP(*e, *f); } if((s = d - c) > (t = last - d - 1)) { s = t; } for(e = b, f = last - s; 0 < s; --s, ++e, ++f) { SWAP(*e, *f); } a = first + (b - a), c = last - (d - c); b = (v <= Td[PA[*a] - 1]) ? a : ss_partition(PA, a, c, depth); if((a - first) <= (last - c)) { if((last - c) <= (c - b)) { STACK_PUSH(b, c, depth + 1, ss_ilg(c - b)); STACK_PUSH(c, last, depth, limit); last = a; } else if((a - first) <= (c - b)) { STACK_PUSH(c, last, depth, limit); STACK_PUSH(b, c, depth + 1, ss_ilg(c - b)); last = a; } else { STACK_PUSH(c, last, depth, limit); STACK_PUSH(first, a, depth, limit); first = b, last = c, depth += 1, limit = ss_ilg(c - b); } } else { if((a - first) <= (c - b)) { STACK_PUSH(b, c, depth + 1, ss_ilg(c - b)); STACK_PUSH(first, a, depth, limit); first = c; } else if((last - c) <= (c - b)) { STACK_PUSH(first, a, depth, limit); STACK_PUSH(b, c, depth + 1, ss_ilg(c - b)); first = c; } else { STACK_PUSH(first, a, depth, limit); STACK_PUSH(c, last, depth, limit); first = b, last = c, depth += 1, limit = ss_ilg(c - b); } } } else { limit += 1; if(Td[PA[*first] - 1] < v) { first = ss_partition(PA, first, last, depth); limit = ss_ilg(last - first); } depth += 1; } } #undef STACK_SIZE } #endif /* (SS_BLOCKSIZE == 0) || (SS_INSERTIONSORT_THRESHOLD < SS_BLOCKSIZE) */ /*---------------------------------------------------------------------------*/ #if SS_BLOCKSIZE != 0 static INLINE void ss_blockswap(int *a, int *b, int n) { int t; for(; 0 < n; --n, ++a, ++b) { t = *a, *a = *b, *b = t; } } static INLINE void ss_rotate(int *first, int *middle, int *last) { int *a, *b, t; int l, r; l = middle - first, r = last - middle; for(; (0 < l) && (0 < r);) { if(l == r) { ss_blockswap(first, middle, l); break; } if(l < r) { a = last - 1, b = middle - 1; t = *a; do { *a-- = *b, *b-- = *a; if(b < first) { *a = t; last = a; if((r -= l + 1) <= l) { break; } a -= 1, b = middle - 1; t = *a; } } while(1); } else { a = first, b = middle; t = *a; do { *a++ = *b, *b++ = *a; if(last <= b) { *a = t; first = a + 1; if((l -= r + 1) <= r) { break; } a += 1, b = middle; t = *a; } } while(1); } } } /*---------------------------------------------------------------------------*/ static void ss_inplacemerge(const unsigned char *T, const int *PA, int *first, int *middle, int *last, int depth) { const int *p; int *a, *b; int len, half; int q, r; int x; for(;;) { if(*(last - 1) < 0) { x = 1; p = PA + ~*(last - 1); } else { x = 0; p = PA + *(last - 1); } for(a = first, len = middle - first, half = len >> 1, r = -1; 0 < len; len = half, half >>= 1) { b = a + half; q = ss_compare(T, PA + ((0 <= *b) ? *b : ~*b), p, depth); if(q < 0) { a = b + 1; half -= (len & 1) ^ 1; } else { r = q; } } if(a < middle) { if(r == 0) { *a = ~*a; } ss_rotate(a, middle, last); last -= middle - a; middle = a; if(first == middle) { break; } } --last; if(x != 0) { while(*--last < 0) { } } if(middle == last) { break; } } } /*---------------------------------------------------------------------------*/ /* Merge-forward with internal buffer. */ static void ss_mergeforward(const unsigned char *T, const int *PA, int *first, int *middle, int *last, int *buf, int depth) { int *a, *b, *c, *bufend; int t; int r; bufend = buf + (middle - first) - 1; ss_blockswap(buf, first, middle - first); for(t = *(a = first), b = buf, c = middle;;) { r = ss_compare(T, PA + *b, PA + *c, depth); if(r < 0) { do { *a++ = *b; if(bufend <= b) { *bufend = t; return; } *b++ = *a; } while(*b < 0); } else if(r > 0) { do { *a++ = *c, *c++ = *a; if(last <= c) { while(b < bufend) { *a++ = *b, *b++ = *a; } *a = *b, *b = t; return; } } while(*c < 0); } else { *c = ~*c; do { *a++ = *b; if(bufend <= b) { *bufend = t; return; } *b++ = *a; } while(*b < 0); do { *a++ = *c, *c++ = *a; if(last <= c) { while(b < bufend) { *a++ = *b, *b++ = *a; } *a = *b, *b = t; return; } } while(*c < 0); } } } /* Merge-backward with internal buffer. */ static void ss_mergebackward(const unsigned char *T, const int *PA, int *first, int *middle, int *last, int *buf, int depth) { const int *p1, *p2; int *a, *b, *c, *bufend; int t; int r; int x; bufend = buf + (last - middle) - 1; ss_blockswap(buf, middle, last - middle); x = 0; if(*bufend < 0) { p1 = PA + ~*bufend; x |= 1; } else { p1 = PA + *bufend; } if(*(middle - 1) < 0) { p2 = PA + ~*(middle - 1); x |= 2; } else { p2 = PA + *(middle - 1); } for(t = *(a = last - 1), b = bufend, c = middle - 1;;) { r = ss_compare(T, p1, p2, depth); if(0 < r) { if(x & 1) { do { *a-- = *b, *b-- = *a; } while(*b < 0); x ^= 1; } *a-- = *b; if(b <= buf) { *buf = t; break; } *b-- = *a; if(*b < 0) { p1 = PA + ~*b; x |= 1; } else { p1 = PA + *b; } } else if(r < 0) { if(x & 2) { do { *a-- = *c, *c-- = *a; } while(*c < 0); x ^= 2; } *a-- = *c, *c-- = *a; if(c < first) { while(buf < b) { *a-- = *b, *b-- = *a; } *a = *b, *b = t; break; } if(*c < 0) { p2 = PA + ~*c; x |= 2; } else { p2 = PA + *c; } } else { if(x & 1) { do { *a-- = *b, *b-- = *a; } while(*b < 0); x ^= 1; } *a-- = ~*b; if(b <= buf) { *buf = t; break; } *b-- = *a; if(x & 2) { do { *a-- = *c, *c-- = *a; } while(*c < 0); x ^= 2; } *a-- = *c, *c-- = *a; if(c < first) { while(buf < b) { *a-- = *b, *b-- = *a; } *a = *b, *b = t; break; } if(*b < 0) { p1 = PA + ~*b; x |= 1; } else { p1 = PA + *b; } if(*c < 0) { p2 = PA + ~*c; x |= 2; } else { p2 = PA + *c; } } } } /* D&C based merge. */ static void ss_swapmerge(const unsigned char *T, const int *PA, int *first, int *middle, int *last, int *buf, int bufsize, int depth) { #define STACK_SIZE SS_SMERGE_STACKSIZE #define GETIDX(a) ((0 <= (a)) ? (a) : (~(a))) #define MERGE_CHECK(a, b, c)\ do {\ if(((c) & 1) ||\ (((c) & 2) && (ss_compare(T, PA + GETIDX(*((a) - 1)), PA + *(a), depth) == 0))) {\ *(a) = ~*(a);\ }\ if(((c) & 4) && ((ss_compare(T, PA + GETIDX(*((b) - 1)), PA + *(b), depth) == 0))) {\ *(b) = ~*(b);\ }\ } while(0) struct { int *a, *b, *c; int d; } stack[STACK_SIZE]; int *l, *r, *lm, *rm; int m, len, half; int ssize; int check, next; for(check = 0, ssize = 0;;) { if((last - middle) <= bufsize) { if((first < middle) && (middle < last)) { ss_mergebackward(T, PA, first, middle, last, buf, depth); } MERGE_CHECK(first, last, check); STACK_POP(first, middle, last, check); continue; } if((middle - first) <= bufsize) { if(first < middle) { ss_mergeforward(T, PA, first, middle, last, buf, depth); } MERGE_CHECK(first, last, check); STACK_POP(first, middle, last, check); continue; } for(m = 0, len = MIN(middle - first, last - middle), half = len >> 1; 0 < len; len = half, half >>= 1) { if(ss_compare(T, PA + GETIDX(*(middle + m + half)), PA + GETIDX(*(middle - m - half - 1)), depth) < 0) { m += half + 1; half -= (len & 1) ^ 1; } } if(0 < m) { lm = middle - m, rm = middle + m; ss_blockswap(lm, middle, m); l = r = middle, next = 0; if(rm < last) { if(*rm < 0) { *rm = ~*rm; if(first < lm) { for(; *--l < 0;) { } next |= 4; } next |= 1; } else if(first < lm) { for(; *r < 0; ++r) { } next |= 2; } } if((l - first) <= (last - r)) { STACK_PUSH(r, rm, last, (next & 3) | (check & 4)); middle = lm, last = l, check = (check & 3) | (next & 4); } else { if((next & 2) && (r == middle)) { next ^= 6; } STACK_PUSH(first, lm, l, (check & 3) | (next & 4)); first = r, middle = rm, check = (next & 3) | (check & 4); } } else { if(ss_compare(T, PA + GETIDX(*(middle - 1)), PA + *middle, depth) == 0) { *middle = ~*middle; } MERGE_CHECK(first, last, check); STACK_POP(first, middle, last, check); } } #undef STACK_SIZE } #endif /* SS_BLOCKSIZE != 0 */ /*---------------------------------------------------------------------------*/ /* Substring sort */ static void sssort(const unsigned char *T, const int *PA, int *first, int *last, int *buf, int bufsize, int depth, int n, int lastsuffix) { int *a; #if SS_BLOCKSIZE != 0 int *b, *middle, *curbuf; int j, k, curbufsize, limit; #endif int i; if(lastsuffix != 0) { ++first; } #if SS_BLOCKSIZE == 0 ss_mintrosort(T, PA, first, last, depth); #else if((bufsize < SS_BLOCKSIZE) && (bufsize < (last - first)) && (bufsize < (limit = ss_isqrt(last - first)))) { if(SS_BLOCKSIZE < limit) { limit = SS_BLOCKSIZE; } buf = middle = last - limit, bufsize = limit; } else { middle = last, limit = 0; } for(a = first, i = 0; SS_BLOCKSIZE < (middle - a); a += SS_BLOCKSIZE, ++i) { #if SS_INSERTIONSORT_THRESHOLD < SS_BLOCKSIZE ss_mintrosort(T, PA, a, a + SS_BLOCKSIZE, depth); #elif 1 < SS_BLOCKSIZE ss_insertionsort(T, PA, a, a + SS_BLOCKSIZE, depth); #endif curbufsize = last - (a + SS_BLOCKSIZE); curbuf = a + SS_BLOCKSIZE; if(curbufsize <= bufsize) { curbufsize = bufsize, curbuf = buf; } for(b = a, k = SS_BLOCKSIZE, j = i; j & 1; b -= k, k <<= 1, j >>= 1) { ss_swapmerge(T, PA, b - k, b, b + k, curbuf, curbufsize, depth); } } #if SS_INSERTIONSORT_THRESHOLD < SS_BLOCKSIZE ss_mintrosort(T, PA, a, middle, depth); #elif 1 < SS_BLOCKSIZE ss_insertionsort(T, PA, a, middle, depth); #endif for(k = SS_BLOCKSIZE; i != 0; k <<= 1, i >>= 1) { if(i & 1) { ss_swapmerge(T, PA, a - k, a, middle, buf, bufsize, depth); a -= k; } } if(limit != 0) { #if SS_INSERTIONSORT_THRESHOLD < SS_BLOCKSIZE ss_mintrosort(T, PA, middle, last, depth); #elif 1 < SS_BLOCKSIZE ss_insertionsort(T, PA, middle, last, depth); #endif ss_inplacemerge(T, PA, first, middle, last, depth); } #endif if(lastsuffix != 0) { /* Insert last type B* suffix. */ int PAi[2]; PAi[0] = PA[*(first - 1)], PAi[1] = n - 2; for(a = first, i = *(first - 1); (a < last) && ((*a < 0) || (0 < ss_compare(T, &(PAi[0]), PA + *a, depth))); ++a) { *(a - 1) = *a; } *(a - 1) = i; } } /*---------------------------------------------------------------------------*/ static INLINE int tr_ilg(int n) { return (n & 0xffff0000) ? ((n & 0xff000000) ? 24 + lg_table[(n >> 24) & 0xff] : 16 + lg_table[(n >> 16) & 0xff]) : ((n & 0x0000ff00) ? 8 + lg_table[(n >> 8) & 0xff] : 0 + lg_table[(n >> 0) & 0xff]); } /*---------------------------------------------------------------------------*/ /* Simple insertionsort for small size groups. */ static void tr_insertionsort(const int *ISAd, int *first, int *last) { int *a, *b; int t, r; for(a = first + 1; a < last; ++a) { for(t = *a, b = a - 1; 0 > (r = ISAd[t] - ISAd[*b]);) { do { *(b + 1) = *b; } while((first <= --b) && (*b < 0)); if(b < first) { break; } } if(r == 0) { *b = ~*b; } *(b + 1) = t; } } /*---------------------------------------------------------------------------*/ static INLINE void tr_fixdown(const int *ISAd, int *SA, int i, int size) { int j, k; int v; int c, d, e; for(v = SA[i], c = ISAd[v]; (j = 2 * i + 1) < size; SA[i] = SA[k], i = k) { d = ISAd[SA[k = j++]]; if(d < (e = ISAd[SA[j]])) { k = j; d = e; } if(d <= c) { break; } } SA[i] = v; } /* Simple top-down heapsort. */ static void tr_heapsort(const int *ISAd, int *SA, int size) { int i, m; int t; m = size; if((size % 2) == 0) { m--; if(ISAd[SA[m / 2]] < ISAd[SA[m]]) { SWAP(SA[m], SA[m / 2]); } } for(i = m / 2 - 1; 0 <= i; --i) { tr_fixdown(ISAd, SA, i, m); } if((size % 2) == 0) { SWAP(SA[0], SA[m]); tr_fixdown(ISAd, SA, 0, m); } for(i = m - 1; 0 < i; --i) { t = SA[0], SA[0] = SA[i]; tr_fixdown(ISAd, SA, 0, i); SA[i] = t; } } /*---------------------------------------------------------------------------*/ /* Returns the median of three elements. */ static INLINE int * tr_median3(const int *ISAd, int *v1, int *v2, int *v3) { int *t; if(ISAd[*v1] > ISAd[*v2]) { SWAP(v1, v2); } if(ISAd[*v2] > ISAd[*v3]) { if(ISAd[*v1] > ISAd[*v3]) { return v1; } else { return v3; } } return v2; } /* Returns the median of five elements. */ static INLINE int * tr_median5(const int *ISAd, int *v1, int *v2, int *v3, int *v4, int *v5) { int *t; if(ISAd[*v2] > ISAd[*v3]) { SWAP(v2, v3); } if(ISAd[*v4] > ISAd[*v5]) { SWAP(v4, v5); } if(ISAd[*v2] > ISAd[*v4]) { SWAP(v2, v4); SWAP(v3, v5); } if(ISAd[*v1] > ISAd[*v3]) { SWAP(v1, v3); } if(ISAd[*v1] > ISAd[*v4]) { SWAP(v1, v4); SWAP(v3, v5); } if(ISAd[*v3] > ISAd[*v4]) { return v4; } return v3; } /* Returns the pivot element. */ static INLINE int * tr_pivot(const int *ISAd, int *first, int *last) { int *middle; int t; t = last - first; middle = first + t / 2; if(t <= 512) { if(t <= 32) { return tr_median3(ISAd, first, middle, last - 1); } else { t >>= 2; return tr_median5(ISAd, first, first + t, middle, last - 1 - t, last - 1); } } t >>= 3; first = tr_median3(ISAd, first, first + t, first + (t << 1)); middle = tr_median3(ISAd, middle - t, middle, middle + t); last = tr_median3(ISAd, last - 1 - (t << 1), last - 1 - t, last - 1); return tr_median3(ISAd, first, middle, last); } /*---------------------------------------------------------------------------*/ typedef struct _trbudget_t trbudget_t; struct _trbudget_t { int chance; int remain; int incval; int count; }; static INLINE void trbudget_init(trbudget_t *budget, int chance, int incval) { budget->chance = chance; budget->remain = budget->incval = incval; } static INLINE int trbudget_check(trbudget_t *budget, int size) { if(size <= budget->remain) { budget->remain -= size; return 1; } if(budget->chance == 0) { budget->count += size; return 0; } budget->remain += budget->incval - size; budget->chance -= 1; return 1; } /*---------------------------------------------------------------------------*/ static INLINE void tr_partition(const int *ISAd, int *first, int *middle, int *last, int **pa, int **pb, int v) { int *a, *b, *c, *d, *e, *f; int t, s; int x = 0; for(b = middle - 1; (++b < last) && ((x = ISAd[*b]) == v);) { } if(((a = b) < last) && (x < v)) { for(; (++b < last) && ((x = ISAd[*b]) <= v);) { if(x == v) { SWAP(*b, *a); ++a; } } } for(c = last; (b < --c) && ((x = ISAd[*c]) == v);) { } if((b < (d = c)) && (x > v)) { for(; (b < --c) && ((x = ISAd[*c]) >= v);) { if(x == v) { SWAP(*c, *d); --d; } } } for(; b < c;) { SWAP(*b, *c); for(; (++b < c) && ((x = ISAd[*b]) <= v);) { if(x == v) { SWAP(*b, *a); ++a; } } for(; (b < --c) && ((x = ISAd[*c]) >= v);) { if(x == v) { SWAP(*c, *d); --d; } } } if(a <= d) { c = b - 1; if((s = a - first) > (t = b - a)) { s = t; } for(e = first, f = b - s; 0 < s; --s, ++e, ++f) { SWAP(*e, *f); } if((s = d - c) > (t = last - d - 1)) { s = t; } for(e = b, f = last - s; 0 < s; --s, ++e, ++f) { SWAP(*e, *f); } first += (b - a), last -= (d - c); } *pa = first, *pb = last; } static void tr_copy(int *ISA, const int *SA, int *first, int *a, int *b, int *last, int depth) { /* sort suffixes of middle partition by using sorted order of suffixes of left and right partition. */ int *c, *d, *e; int s, v; v = b - SA - 1; for(c = first, d = a - 1; c <= d; ++c) { if((0 <= (s = *c - depth)) && (ISA[s] == v)) { *++d = s; ISA[s] = d - SA; } } for(c = last - 1, e = d + 1, d = b; e < d; --c) { if((0 <= (s = *c - depth)) && (ISA[s] == v)) { *--d = s; ISA[s] = d - SA; } } } static void tr_partialcopy(int *ISA, const int *SA, int *first, int *a, int *b, int *last, int depth) { int *c, *d, *e; int s, v; int rank, lastrank, newrank = -1; v = b - SA - 1; lastrank = -1; for(c = first, d = a - 1; c <= d; ++c) { if((0 <= (s = *c - depth)) && (ISA[s] == v)) { *++d = s; rank = ISA[s + depth]; if(lastrank != rank) { lastrank = rank; newrank = d - SA; } ISA[s] = newrank; } } lastrank = -1; for(e = d; first <= e; --e) { rank = ISA[*e]; if(lastrank != rank) { lastrank = rank; newrank = e - SA; } if(newrank != rank) { ISA[*e] = newrank; } } lastrank = -1; for(c = last - 1, e = d + 1, d = b; e < d; --c) { if((0 <= (s = *c - depth)) && (ISA[s] == v)) { *--d = s; rank = ISA[s + depth]; if(lastrank != rank) { lastrank = rank; newrank = d - SA; } ISA[s] = newrank; } } } static void tr_introsort(int *ISA, const int *ISAd, int *SA, int *first, int *last, trbudget_t *budget) { #define STACK_SIZE TR_STACKSIZE struct { const int *a; int *b, *c; int d, e; }stack[STACK_SIZE]; int *a, *b, *c; int t; int v, x = 0; int incr = ISAd - ISA; int limit, next; int ssize, trlink = -1; for(ssize = 0, limit = tr_ilg(last - first);;) { if(limit < 0) { if(limit == -1) { /* tandem repeat partition */ tr_partition(ISAd - incr, first, first, last, &a, &b, last - SA - 1); /* update ranks */ if(a < last) { for(c = first, v = a - SA - 1; c < a; ++c) { ISA[*c] = v; } } if(b < last) { for(c = a, v = b - SA - 1; c < b; ++c) { ISA[*c] = v; } } /* push */ if(1 < (b - a)) { STACK_PUSH5(NULL, a, b, 0, 0); STACK_PUSH5(ISAd - incr, first, last, -2, trlink); trlink = ssize - 2; } if((a - first) <= (last - b)) { if(1 < (a - first)) { STACK_PUSH5(ISAd, b, last, tr_ilg(last - b), trlink); last = a, limit = tr_ilg(a - first); } else if(1 < (last - b)) { first = b, limit = tr_ilg(last - b); } else { STACK_POP5(ISAd, first, last, limit, trlink); } } else { if(1 < (last - b)) { STACK_PUSH5(ISAd, first, a, tr_ilg(a - first), trlink); first = b, limit = tr_ilg(last - b); } else if(1 < (a - first)) { last = a, limit = tr_ilg(a - first); } else { STACK_POP5(ISAd, first, last, limit, trlink); } } } else if(limit == -2) { /* tandem repeat copy */ a = stack[--ssize].b, b = stack[ssize].c; if(stack[ssize].d == 0) { tr_copy(ISA, SA, first, a, b, last, ISAd - ISA); } else { if(0 <= trlink) { stack[trlink].d = -1; } tr_partialcopy(ISA, SA, first, a, b, last, ISAd - ISA); } STACK_POP5(ISAd, first, last, limit, trlink); } else { /* sorted partition */ if(0 <= *first) { a = first; do { ISA[*a] = a - SA; } while((++a < last) && (0 <= *a)); first = a; } if(first < last) { a = first; do { *a = ~*a; } while(*++a < 0); next = (ISA[*a] != ISAd[*a]) ? tr_ilg(a - first + 1) : -1; if(++a < last) { for(b = first, v = a - SA - 1; b < a; ++b) { ISA[*b] = v; } } /* push */ if(trbudget_check(budget, a - first)) { if((a - first) <= (last - a)) { STACK_PUSH5(ISAd, a, last, -3, trlink); ISAd += incr, last = a, limit = next; } else { if(1 < (last - a)) { STACK_PUSH5(ISAd + incr, first, a, next, trlink); first = a, limit = -3; } else { ISAd += incr, last = a, limit = next; } } } else { if(0 <= trlink) { stack[trlink].d = -1; } if(1 < (last - a)) { first = a, limit = -3; } else { STACK_POP5(ISAd, first, last, limit, trlink); } } } else { STACK_POP5(ISAd, first, last, limit, trlink); } } continue; } if((last - first) <= TR_INSERTIONSORT_THRESHOLD) { tr_insertionsort(ISAd, first, last); limit = -3; continue; } if(limit-- == 0) { tr_heapsort(ISAd, first, last - first); for(a = last - 1; first < a; a = b) { for(x = ISAd[*a], b = a - 1; (first <= b) && (ISAd[*b] == x); --b) { *b = ~*b; } } limit = -3; continue; } /* choose pivot */ a = tr_pivot(ISAd, first, last); SWAP(*first, *a); v = ISAd[*first]; /* partition */ tr_partition(ISAd, first, first + 1, last, &a, &b, v); if((last - first) != (b - a)) { next = (ISA[*a] != v) ? tr_ilg(b - a) : -1; /* update ranks */ for(c = first, v = a - SA - 1; c < a; ++c) { ISA[*c] = v; } if(b < last) { for(c = a, v = b - SA - 1; c < b; ++c) { ISA[*c] = v; } } /* push */ if((1 < (b - a)) && (trbudget_check(budget, b - a))) { if((a - first) <= (last - b)) { if((last - b) <= (b - a)) { if(1 < (a - first)) { STACK_PUSH5(ISAd + incr, a, b, next, trlink); STACK_PUSH5(ISAd, b, last, limit, trlink); last = a; } else if(1 < (last - b)) { STACK_PUSH5(ISAd + incr, a, b, next, trlink); first = b; } else { ISAd += incr, first = a, last = b, limit = next; } } else if((a - first) <= (b - a)) { if(1 < (a - first)) { STACK_PUSH5(ISAd, b, last, limit, trlink); STACK_PUSH5(ISAd + incr, a, b, next, trlink); last = a; } else { STACK_PUSH5(ISAd, b, last, limit, trlink); ISAd += incr, first = a, last = b, limit = next; } } else { STACK_PUSH5(ISAd, b, last, limit, trlink); STACK_PUSH5(ISAd, first, a, limit, trlink); ISAd += incr, first = a, last = b, limit = next; } } else { if((a - first) <= (b - a)) { if(1 < (last - b)) { STACK_PUSH5(ISAd + incr, a, b, next, trlink); STACK_PUSH5(ISAd, first, a, limit, trlink); first = b; } else if(1 < (a - first)) { STACK_PUSH5(ISAd + incr, a, b, next, trlink); last = a; } else { ISAd += incr, first = a, last = b, limit = next; } } else if((last - b) <= (b - a)) { if(1 < (last - b)) { STACK_PUSH5(ISAd, first, a, limit, trlink); STACK_PUSH5(ISAd + incr, a, b, next, trlink); first = b; } else { STACK_PUSH5(ISAd, first, a, limit, trlink); ISAd += incr, first = a, last = b, limit = next; } } else { STACK_PUSH5(ISAd, first, a, limit, trlink); STACK_PUSH5(ISAd, b, last, limit, trlink); ISAd += incr, first = a, last = b, limit = next; } } } else { if((1 < (b - a)) && (0 <= trlink)) { stack[trlink].d = -1; } if((a - first) <= (last - b)) { if(1 < (a - first)) { STACK_PUSH5(ISAd, b, last, limit, trlink); last = a; } else if(1 < (last - b)) { first = b; } else { STACK_POP5(ISAd, first, last, limit, trlink); } } else { if(1 < (last - b)) { STACK_PUSH5(ISAd, first, a, limit, trlink); first = b; } else if(1 < (a - first)) { last = a; } else { STACK_POP5(ISAd, first, last, limit, trlink); } } } } else { if(trbudget_check(budget, last - first)) { limit = tr_ilg(last - first), ISAd += incr; } else { if(0 <= trlink) { stack[trlink].d = -1; } STACK_POP5(ISAd, first, last, limit, trlink); } } } #undef STACK_SIZE } /*---------------------------------------------------------------------------*/ /* Tandem repeat sort */ static void trsort(int *ISA, int *SA, int n, int depth) { int *ISAd; int *first, *last; trbudget_t budget; int t, skip, unsorted; trbudget_init(&budget, tr_ilg(n) * 2 / 3, n); /* trbudget_init(&budget, tr_ilg(n) * 3 / 4, n); */ for(ISAd = ISA + depth; -n < *SA; ISAd += ISAd - ISA) { first = SA; skip = 0; unsorted = 0; do { if((t = *first) < 0) { first -= t; skip += t; } else { if(skip != 0) { *(first + skip) = skip; skip = 0; } last = SA + ISA[t] + 1; if(1 < (last - first)) { budget.count = 0; tr_introsort(ISA, ISAd, SA, first, last, &budget); if(budget.count != 0) { unsorted += budget.count; } else { skip = first - last; } } else if((last - first) == 1) { skip = -1; } first = last; } } while(first < (SA + n)); if(skip != 0) { *(first + skip) = skip; } if(unsorted == 0) { break; } } } /*---------------------------------------------------------------------------*/ /* Sorts suffixes of type B*. */ static int sort_typeBstar(const unsigned char *T, int *SA, int *bucket_A, int *bucket_B, int n) { int *PAb, *ISAb, *buf; #ifdef _OPENMP int *curbuf; int l; #endif int i, j, k, t, m, bufsize; int c0, c1; #ifdef _OPENMP int d0, d1; int tmp; #endif /* Initialize bucket arrays. */ for(i = 0; i < BUCKET_A_SIZE; ++i) { bucket_A[i] = 0; } for(i = 0; i < BUCKET_B_SIZE; ++i) { bucket_B[i] = 0; } /* Count the number of occurrences of the first one or two characters of each type A, B and B* suffix. Moreover, store the beginning position of all type B* suffixes into the array SA. */ for(i = n - 1, m = n, c0 = T[n - 1]; 0 <= i;) { /* type A suffix. */ do { ++BUCKET_A(c1 = c0); } while((0 <= --i) && ((c0 = T[i]) >= c1)); if(0 <= i) { /* type B* suffix. */ ++BUCKET_BSTAR(c0, c1); SA[--m] = i; /* type B suffix. */ for(--i, c1 = c0; (0 <= i) && ((c0 = T[i]) <= c1); --i, c1 = c0) { ++BUCKET_B(c0, c1); } } } m = n - m; /* note: A type B* suffix is lexicographically smaller than a type B suffix that begins with the same first two characters. */ /* Calculate the index of start/end point of each bucket. */ for(c0 = 0, i = 0, j = 0; c0 < ALPHABET_SIZE; ++c0) { t = i + BUCKET_A(c0); BUCKET_A(c0) = i + j; /* start point */ i = t + BUCKET_B(c0, c0); for(c1 = c0 + 1; c1 < ALPHABET_SIZE; ++c1) { j += BUCKET_BSTAR(c0, c1); BUCKET_BSTAR(c0, c1) = j; /* end point */ i += BUCKET_B(c0, c1); } } if(0 < m) { /* Sort the type B* suffixes by their first two characters. */ PAb = SA + n - m; ISAb = SA + m; for(i = m - 2; 0 <= i; --i) { t = PAb[i], c0 = T[t], c1 = T[t + 1]; SA[--BUCKET_BSTAR(c0, c1)] = i; } t = PAb[m - 1], c0 = T[t], c1 = T[t + 1]; SA[--BUCKET_BSTAR(c0, c1)] = m - 1; /* Sort the type B* substrings using sssort. */ #ifdef _OPENMP tmp = omp_get_max_threads(); buf = SA + m, bufsize = (n - (2 * m)) / tmp; c0 = ALPHABET_SIZE - 2, c1 = ALPHABET_SIZE - 1, j = m; #pragma omp parallel default(shared) private(curbuf, k, l, d0, d1, tmp) { tmp = omp_get_thread_num(); curbuf = buf + tmp * bufsize; k = 0; for(;;) { #pragma omp critical(sssort_lock) { if(0 < (l = j)) { d0 = c0, d1 = c1; do { k = BUCKET_BSTAR(d0, d1); if(--d1 <= d0) { d1 = ALPHABET_SIZE - 1; if(--d0 < 0) { break; } } } while(((l - k) <= 1) && (0 < (l = k))); c0 = d0, c1 = d1, j = k; } } if(l == 0) { break; } sssort(T, PAb, SA + k, SA + l, curbuf, bufsize, 2, n, *(SA + k) == (m - 1)); } } #else buf = SA + m, bufsize = n - (2 * m); for(c0 = ALPHABET_SIZE - 2, j = m; 0 < j; --c0) { for(c1 = ALPHABET_SIZE - 1; c0 < c1; j = i, --c1) { i = BUCKET_BSTAR(c0, c1); if(1 < (j - i)) { sssort(T, PAb, SA + i, SA + j, buf, bufsize, 2, n, *(SA + i) == (m - 1)); } } } #endif /* Compute ranks of type B* substrings. */ for(i = m - 1; 0 <= i; --i) { if(0 <= SA[i]) { j = i; do { ISAb[SA[i]] = i; } while((0 <= --i) && (0 <= SA[i])); SA[i + 1] = i - j; if(i <= 0) { break; } } j = i; do { ISAb[SA[i] = ~SA[i]] = j; } while(SA[--i] < 0); ISAb[SA[i]] = j; } /* Construct the inverse suffix array of type B* suffixes using trsort. */ trsort(ISAb, SA, m, 1); /* Set the sorted order of tyoe B* suffixes. */ for(i = n - 1, j = m, c0 = T[n - 1]; 0 <= i;) { for(--i, c1 = c0; (0 <= i) && ((c0 = T[i]) >= c1); --i, c1 = c0) { } if(0 <= i) { t = i; for(--i, c1 = c0; (0 <= i) && ((c0 = T[i]) <= c1); --i, c1 = c0) { } SA[ISAb[--j]] = ((t == 0) || (1 < (t - i))) ? t : ~t; } } /* Calculate the index of start/end point of each bucket. */ BUCKET_B(ALPHABET_SIZE - 1, ALPHABET_SIZE - 1) = n; /* end point */ for(c0 = ALPHABET_SIZE - 2, k = m - 1; 0 <= c0; --c0) { i = BUCKET_A(c0 + 1) - 1; for(c1 = ALPHABET_SIZE - 1; c0 < c1; --c1) { t = i - BUCKET_B(c0, c1); BUCKET_B(c0, c1) = i; /* end point */ /* Move all type B* suffixes to the correct position. */ for(i = t, j = BUCKET_BSTAR(c0, c1); j <= k; --i, --k) { SA[i] = SA[k]; } } BUCKET_BSTAR(c0, c0 + 1) = i - BUCKET_B(c0, c0) + 1; /* start point */ BUCKET_B(c0, c0) = i; /* end point */ } } return m; } /* Constructs the suffix array by using the sorted order of type B* suffixes. */ static void construct_SA(const unsigned char *T, int *SA, int *bucket_A, int *bucket_B, int n, int m) { int *i, *j, *k; int s; int c0, c1, c2; if(0 < m) { /* Construct the sorted order of type B suffixes by using the sorted order of type B* suffixes. */ for(c1 = ALPHABET_SIZE - 2; 0 <= c1; --c1) { /* Scan the suffix array from right to left. */ for(i = SA + BUCKET_BSTAR(c1, c1 + 1), j = SA + BUCKET_A(c1 + 1) - 1, k = NULL, c2 = -1; i <= j; --j) { if(0 < (s = *j)) { assert(T[s] == c1); assert(((s + 1) < n) && (T[s] <= T[s + 1])); assert(T[s - 1] <= T[s]); *j = ~s; c0 = T[--s]; if((0 < s) && (T[s - 1] > c0)) { s = ~s; } if(c0 != c2) { if(0 <= c2) { BUCKET_B(c2, c1) = k - SA; } k = SA + BUCKET_B(c2 = c0, c1); } assert(k < j); *k-- = s; } else { assert(((s == 0) && (T[s] == c1)) || (s < 0)); *j = ~s; } } } } /* Construct the suffix array by using the sorted order of type B suffixes. */ k = SA + BUCKET_A(c2 = T[n - 1]); *k++ = (T[n - 2] < c2) ? ~(n - 1) : (n - 1); /* Scan the suffix array from left to right. */ for(i = SA, j = SA + n; i < j; ++i) { if(0 < (s = *i)) { assert(T[s - 1] >= T[s]); c0 = T[--s]; if((s == 0) || (T[s - 1] < c0)) { s = ~s; } if(c0 != c2) { BUCKET_A(c2) = k - SA; k = SA + BUCKET_A(c2 = c0); } assert(i < k); *k++ = s; } else { assert(s < 0); *i = ~s; } } } /* Constructs the burrows-wheeler transformed string directly by using the sorted order of type B* suffixes. */ static int construct_BWT(const unsigned char *T, int *SA, int *bucket_A, int *bucket_B, int n, int m) { int *i, *j, *k, *orig; int s; int c0, c1, c2; if(0 < m) { /* Construct the sorted order of type B suffixes by using the sorted order of type B* suffixes. */ for(c1 = ALPHABET_SIZE - 2; 0 <= c1; --c1) { /* Scan the suffix array from right to left. */ for(i = SA + BUCKET_BSTAR(c1, c1 + 1), j = SA + BUCKET_A(c1 + 1) - 1, k = NULL, c2 = -1; i <= j; --j) { if(0 < (s = *j)) { assert(T[s] == c1); assert(((s + 1) < n) && (T[s] <= T[s + 1])); assert(T[s - 1] <= T[s]); c0 = T[--s]; *j = ~((int)c0); if((0 < s) && (T[s - 1] > c0)) { s = ~s; } if(c0 != c2) { if(0 <= c2) { BUCKET_B(c2, c1) = k - SA; } k = SA + BUCKET_B(c2 = c0, c1); } assert(k < j); *k-- = s; } else if(s != 0) { *j = ~s; #ifndef NDEBUG } else { assert(T[s] == c1); #endif } } } } /* Construct the BWTed string by using the sorted order of type B suffixes. */ k = SA + BUCKET_A(c2 = T[n - 1]); *k++ = (T[n - 2] < c2) ? ~((int)T[n - 2]) : (n - 1); /* Scan the suffix array from left to right. */ for(i = SA, j = SA + n, orig = SA; i < j; ++i) { if(0 < (s = *i)) { assert(T[s - 1] >= T[s]); c0 = T[--s]; *i = c0; if((0 < s) && (T[s - 1] < c0)) { s = ~((int)T[s - 1]); } if(c0 != c2) { BUCKET_A(c2) = k - SA; k = SA + BUCKET_A(c2 = c0); } assert(i < k); *k++ = s; } else if(s != 0) { *i = ~s; } else { orig = i; } } return orig - SA; } /*---------------------------------------------------------------------------*/ /*- Function -*/ int bcm_divsufsort(const unsigned char *T, int *SA, int n) { int *bucket_A, *bucket_B; int m; int err = 0; /* Check arguments. */ if((T == NULL) || (SA == NULL) || (n < 0)) { return -1; } else if(n == 0) { return 0; } else if(n == 1) { SA[0] = 0; return 0; } else if(n == 2) { m = (T[0] < T[1]); SA[m ^ 1] = 0, SA[m] = 1; return 0; } bucket_A = (int *)malloc(BUCKET_A_SIZE * sizeof(int)); bucket_B = (int *)malloc(BUCKET_B_SIZE * sizeof(int)); /* Suffixsort. */ if((bucket_A != NULL) && (bucket_B != NULL)) { m = sort_typeBstar(T, SA, bucket_A, bucket_B, n); construct_SA(T, SA, bucket_A, bucket_B, n, m); } else { err = -2; } free(bucket_B); free(bucket_A); return err; } int bcm_divbwt(const unsigned char *T, unsigned char *U, int *A, int n) { int *B; int *bucket_A, *bucket_B; int m, pidx, i; /* Check arguments. */ if((T == NULL) || (U == NULL) || (n < 0)) { return -1; } else if(n <= 1) { if(n == 1) { U[0] = T[0]; } return n; } if((B = A) == NULL) { B = (int *)malloc((size_t)(n + 1) * sizeof(int)); } bucket_A = (int *)malloc(BUCKET_A_SIZE * sizeof(int)); bucket_B = (int *)malloc(BUCKET_B_SIZE * sizeof(int)); /* Burrows-Wheeler Transform. */ if((B != NULL) && (bucket_A != NULL) && (bucket_B != NULL)) { m = sort_typeBstar(T, B, bucket_A, bucket_B, n); pidx = construct_BWT(T, B, bucket_A, bucket_B, n, m); /* Copy to output string. */ U[0] = T[n - 1]; for(i = 0; i < pidx; ++i) { U[i + 1] = (unsigned char)B[i]; } for(i += 1; i < n; ++i) { U[i] = (unsigned char)B[i]; } pidx += 1; } else { pidx = -2; } free(bucket_B); free(bucket_A); if(A == NULL) { free(B); } return pidx; } #endif // BCM_C //#line 1 "amalgamated_bcm.c" // BCM 1.40 - A BWT-based file compressor // Written and placed in the public domain by Ilya Muravyov (UNLICENSE) // Additional code by @r-lyeh (UNLICENSE) // // Notes: // - BCM decoder has no dependencies. // - BCM encoder requires libdivsufsort, which is MIT licensed. // - #define BCM_NO_ENCODER if you want to exclude libdivsufsort from linkage. unsigned bcm_encode(const void *in, unsigned inlen, void *out, unsigned outlen, unsigned flags/*[0..(4)..9]*/); unsigned bcm_decode(const void *in, unsigned inlen, void *out, unsigned outlen); unsigned bcm_bounds(unsigned inlen, unsigned flags); unsigned bcm_excess(unsigned flags); // --- #ifdef BCM_C #pragma once #include <stdbool.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #if INTPTR_MAX >= INT64_MAX #define BCM_64BITS 1 #else #define BCM_64BITS 0 #endif #ifndef BCM_REALLOC #define BCM_REALLOC REALLOC #endif # if defined _MSC_VER && !defined __thread #define __thread __declspec(thread) #elif defined __TINYC__ && !defined __thread #define __thread __declspec(thread) #endif #ifndef BALZ_C typedef struct mfile { uint8_t *begin, *seek, *end; } mfile; int minit(mfile *f, const void *ptr, int len) { f->begin = f->seek = f->end = (uint8_t*)ptr; f->end += len; return 0; } int mread(mfile *m, void *buf, int len) { if( len >= (m->end - m->seek) ) len = (m->end - m->seek); memcpy(buf,m->seek,len); m->seek += len; return len; } int mwrite(mfile *m, const void *buf, int len) { if( len >= (m->end - m->seek) ) len = (m->end - m->seek); memcpy(m->seek,buf,len); m->seek += len; return len; } int mtell(mfile *m) { return m->seek - m->begin; } int mavail(mfile *m) { return m->end - m->seek; } int mputc(mfile *m, int i) { uint8_t ch = i; return mwrite(m, &ch, 1); } int mgetc(mfile *m) { if( mavail(m) <= 0 ) return -1; uint8_t ch; mread(m, &ch, 1); return ch; } #endif int bcm_divbwt(const unsigned char *T, unsigned char *U, int *A, int n); // Globals static __thread mfile* g_in; static __thread mfile* g_out; typedef struct bcmEncode { uint32_t low; uint32_t high; uint32_t code; } bcmEncoder; void bcmeCtor(bcmEncoder *e) { e->low=0; e->high=0xFFFFFFFF; e->code=0; } void bcmeFlush(bcmEncoder *e) { for (int i=0; i<4; ++i) { mputc(g_out, e->low>>24); e->low<<=8; } } void bcmeInit(bcmEncoder *e) { for (int i=0; i<4; ++i) e->code=(e->code<<8)+mgetc(g_in); } void bcmeEncodeDirectBits(bcmEncoder *e, int N, uint32_t x) { for (uint32_t i=1<<(N-1); i!=0; i>>=1) { if (x&i) e->high=e->low+((e->high-e->low)>>1); else e->low+=((e->high-e->low)>>1)+1; if ((e->low^e->high)<(1<<24)) { mputc(g_out, e->low>>24); e->low<<=8; e->high=(e->high<<8)+255; } } } void bcmeEncodeBit1(bcmEncoder *e, uint32_t p) { #if BCM_64BITS e->high=e->low+(((uint64_t)(e->high-e->low)*p)>>18); #else e->high=e->low+(((uint64_t)(e->high-e->low)*(p<<(32-18)))>>32); #endif while ((e->low^e->high)<(1<<24)) { mputc(g_out, e->low>>24); e->low<<=8; e->high=(e->high<<8)+255; } } void bcmeEncodeBit0(bcmEncoder *e, uint32_t p) { #if BCM_64BITS e->low+=(((uint64_t)(e->high-e->low)*p)>>18)+1; #else e->low+=(((uint64_t)(e->high-e->low)*(p<<(32-18)))>>32)+1; #endif while ((e->low^e->high)<(1<<24)) { mputc(g_out, e->low>>24); e->low<<=8; e->high=(e->high<<8)+255; } } uint32_t bcmeDecodeDirectBits(bcmEncoder *e, int N) { uint32_t x=0; for (int i=0; i<N; ++i) { const uint32_t mid=e->low+((e->high-e->low)>>1); if (e->code<=mid) { e->high=mid; x+=x+1; } else { e->low=mid+1; x+=x; } if ((e->low^e->high)<(1<<24)) { e->low<<=8; e->high=(e->high<<8)+255; e->code=(e->code<<8)+mgetc(g_in); } } return x; } int bcmeDecodeBit(bcmEncoder *e, uint32_t p) { #if BCM_64BITS const uint32_t mid=e->low+(((uint64_t)(e->high-e->low)*p)>>18); #else const uint32_t mid=e->low+(((uint64_t)(e->high-e->low)*(p<<(32-18)))>>32); #endif const int bit=(e->code<=mid); if (bit) e->high=mid; else e->low=mid+1; while ((e->low^e->high)<(1<<24)) { e->low<<=8; e->high=(e->high<<8)+255; e->code=(e->code<<8)+mgetc(g_in); } return bit; } #define BCM_COUNTER_TEMPLATE(RATE) \ typedef struct bcmCounter##RATE { uint16_t p; } bcmCounter##RATE; \ void bcmCounter##RATE##Ctor(bcmCounter##RATE *c) { c->p=1<<15; /* 0.5 */ } \ void bcmCounter##RATE##UpdateBit0(bcmCounter##RATE *c) { c->p-=c->p>>RATE; } \ void bcmCounter##RATE##UpdateBit1(bcmCounter##RATE *c) { c->p+=(c->p^0xFFFF)>>RATE; } BCM_COUNTER_TEMPLATE(2); BCM_COUNTER_TEMPLATE(4); BCM_COUNTER_TEMPLATE(6); typedef struct bcmCM { bcmEncoder enc; bcmCounter2 counter0[256]; bcmCounter4 counter1[256][256]; bcmCounter6 counter2[2][256][17]; int c1; int c2; int run; } bcmCM; void bcmCMCtor(bcmCM *c) { bcmeCtor(&c->enc); for(int i = 0; i < 256; ++i) { bcmCounter2Ctor(&c->counter0[i]); for(int j = 0; j < 256; ++j) { bcmCounter4Ctor(&c->counter1[i][j]); } for(int k = 0; k < 17; ++k) { bcmCounter6Ctor(&c->counter2[0][i][k]); bcmCounter6Ctor(&c->counter2[1][i][k]); } } c->c1=0; c->c2=0; c->run=0; for (int i=0; i<2; ++i) { for (int j=0; j<256; ++j) { for (int k=0; k<17; ++k) c->counter2[i][j][k].p=(k<<12)-(k==16); } } } void bcmCMEncode(bcmCM *c, int ch) { if (c->c1==c->c2) ++c->run; else c->run=0; const int f=(c->run>2); int ctx=1; while (ctx<256) { const int p0=c->counter0[ctx].p; const int p1=c->counter1[c->c1][ctx].p; const int p2=c->counter1[c->c2][ctx].p; const int p=(((p0+p1)*7)+p2+p2)>>4; const int j=p>>12; const int x1=c->counter2[f][ctx][j].p; const int x2=c->counter2[f][ctx][j+1].p; const int ssep=x1+(((x2-x1)*(p&4095))>>12); if (ch&128) { bcmeEncodeBit1(&c->enc, (ssep*3)+p); bcmCounter2UpdateBit1(&c->counter0[ctx]); bcmCounter4UpdateBit1(&c->counter1[c->c1][ctx]); bcmCounter6UpdateBit1(&c->counter2[f][ctx][j]); bcmCounter6UpdateBit1(&c->counter2[f][ctx][j+1]); ctx+=ctx+1; } else { bcmeEncodeBit0(&c->enc, (ssep*3)+p); bcmCounter2UpdateBit0(&c->counter0[ctx]); bcmCounter4UpdateBit0(&c->counter1[c->c1][ctx]); bcmCounter6UpdateBit0(&c->counter2[f][ctx][j]); bcmCounter6UpdateBit0(&c->counter2[f][ctx][j+1]); ctx+=ctx; } ch+=ch; } c->c2=c->c1; c->c1=ctx-256; } int bcmCMDecode(bcmCM *c) { if (c->c1==c->c2) ++c->run; else c->run=0; const int f=(c->run>2); int ctx=1; while (ctx<256) { const int p0=c->counter0[ctx].p; const int p1=c->counter1[c->c1][ctx].p; const int p2=c->counter1[c->c2][ctx].p; const int p=(((p0+p1)*7)+p2+p2)>>4; const int j=p>>12; const int x1=c->counter2[f][ctx][j].p; const int x2=c->counter2[f][ctx][j+1].p; const int ssep=x1+(((x2-x1)*(p&4095))>>12); if (bcmeDecodeBit(&c->enc, (ssep*3)+p)) { bcmCounter2UpdateBit1(&c->counter0[ctx]); bcmCounter4UpdateBit1(&c->counter1[c->c1][ctx]); bcmCounter6UpdateBit1(&c->counter2[f][ctx][j]); bcmCounter6UpdateBit1(&c->counter2[f][ctx][j+1]); ctx+=ctx+1; } else { bcmCounter2UpdateBit0(&c->counter0[ctx]); bcmCounter4UpdateBit0(&c->counter1[c->c1][ctx]); bcmCounter6UpdateBit0(&c->counter2[f][ctx][j]); bcmCounter6UpdateBit0(&c->counter2[f][ctx][j+1]); ctx+=ctx; } } c->c2=c->c1; return c->c1=ctx-256; } unsigned bcm_encode(const void *in, unsigned inlen, void *out, unsigned outlen, unsigned level) { mfile infile; minit(&infile, in, inlen); g_in = &infile; mfile outfile; minit(&outfile, out, outlen); g_out = &outfile; bcmCM cm; bcmCMCtor(&cm); const int config_tab[10]= { 1<<19, // -0 - 512KiB, @rlyeh: originally was: 0 1<<20, // -1 - 1 MB 1<<22, // -2 - 4 MB 1<<23, // -3 - 8 MB 0x00FFFFFF, // -4 - ~16 MB (Default) 1<<25, // -5 - 32 MB 1<<26, // -6 - 64 MB 1<<27, // -7 - 128 MB 1<<28, // -8 - 256 MB 0x7FFFFFFF, // -9 - ~2 GB }; int block_size=config_tab[level]; int64_t file_size = (int64_t)inlen; if (file_size>0 && block_size>file_size) block_size=(int)(file_size); uint8_t* buf=(uint8_t*)BCM_REALLOC(0, sizeof(uint8_t) * block_size); int* ptr=(int*)BCM_REALLOC(0, sizeof(int) * block_size); int n; while ((n=mread(g_in, buf, block_size))>0) { const int idx=bcm_divbwt(buf, buf, ptr, n); if (idx<1) return 0; // divbwt() failed bcmeEncodeDirectBits(&cm.enc, 32, n); bcmeEncodeDirectBits(&cm.enc, 32, idx); for (int i=0; i<n; ++i) bcmCMEncode(&cm, buf[i]); } bcmeEncodeDirectBits(&cm.enc, 32, 0); // EOF // bcmeEncodeDirectBits(&cm.enc, 32, crc32); bcmeFlush(&cm.enc); BCM_REALLOC(buf, 0); // free BCM_REALLOC(ptr, 0); // free return mtell(g_out); } unsigned bcm_decode(const void *in, unsigned inlen, void *out, unsigned outlen) { mfile infile; minit(&infile, in, inlen); g_in = &infile; mfile outfile; minit(&outfile, out, outlen); g_out = &outfile; bcmCM cm; bcmCMCtor(&cm); bcmeInit(&cm.enc); int block_size=0; uint8_t* buf=NULL; uint32_t* ptr=NULL; int n; while ((n=bcmeDecodeDirectBits(&cm.enc, 32))>0) { if (block_size==0) { if ((block_size=n)>=(1<<24)) // 5*N buf=(uint8_t*)BCM_REALLOC(0, sizeof(uint8_t) * block_size); ptr=(uint32_t*)BCM_REALLOC(0, sizeof(uint32_t) * block_size); } const int idx=bcmeDecodeDirectBits(&cm.enc, 32); if (n>block_size || idx<1 || idx>n) return 0; // corrupt input // Inverse BW-transform if (n>=(1<<24)) // 5*N { int t[257]={0}; for (int i=0; i<n; ++i) ++t[(buf[i]=bcmCMDecode(&cm))+1]; for (int i=1; i<256; ++i) t[i]+=t[i-1]; for (int i=0; i<n; ++i) ptr[t[buf[i]]++]=i+(i>=idx); for (int p=idx; p;) { p=ptr[p-1]; const int c=buf[p-(p>=idx)]; mputc(g_out, c); } } else // 4*N { int t[257]={0}; for (int i=0; i<n; ++i) ++t[(ptr[i]=bcmCMDecode(&cm))+1]; for (int i=1; i<256; ++i) t[i]+=t[i-1]; for (int i=0; i<n; ++i) ptr[t[ptr[i]&255]++]|=(i+(i>=idx))<<8; for (int p=idx; p;) { p=ptr[p-1]>>8; const int c=ptr[p-(p>=idx)]&255; mputc(g_out, c); } } } // if (bcmeDecodeDirectBits(&cm.enc, 32)!=crc32) return 0; // crc error BCM_REALLOC(buf, 0); // free BCM_REALLOC(ptr, 0); // free return mtell(g_out); } unsigned bcm_bounds(unsigned inlen, unsigned flags) { return (unsigned)(inlen * 2); // @todo: check src } unsigned bcm_excess(unsigned flags) { return (unsigned)0; } #endif // BCM_C //#line 1 "amalgamated_crush.c" // crush.cpp // Written and placed in the public domain by Ilya Muravyov // Additional code by @r-lyeh (public domain). @todo: honor unused args inlen/outlen unsigned crush_encode(const void* in, unsigned inlen, void* out, unsigned outlen, unsigned flags); // [0..(4)..10] unsigned crush_decode(const void* in, unsigned inlen, void* out, unsigned outlen); unsigned crush_bounds(unsigned inlen, unsigned flags); unsigned crush_excess(unsigned flags); #ifdef CRUSH_C #pragma once #ifdef _MSC_VER #define _CRT_SECECURE_NO_WARNINGS #define _CRT_DISABLE_PERFCRIT_LOCKS #endif #include <stdint.h> #include <stdlib.h> // Bit I/O // typedef struct bits { const uint8_t* g_inbuf; uint8_t* g_outbuf; int g_inbuf_pos; int g_outbuf_pos; int bit_buf; int bit_count; } bits; void bits_init(bits *b, const uint8_t* inbuf, uint8_t* outbuf) { b->bit_count=b->bit_buf=b->g_inbuf_pos=b->g_outbuf_pos=0; b->g_inbuf = inbuf; b->g_outbuf = outbuf; } void bits_put(bits *b, int n, int x) { b->bit_buf|=x<<b->bit_count; b->bit_count+=n; while (b->bit_count>=8) { b->g_outbuf[b->g_outbuf_pos++] = b->bit_buf; b->bit_buf>>=8; b->bit_count-=8; } } void bits_flush(bits *b) { bits_put(b, 7, 0); b->bit_count=b->bit_buf=0; } int bits_get(bits *b, int n) { while (b->bit_count<n) { b->bit_buf|=b->g_inbuf[b->g_inbuf_pos++]<<b->bit_count; b->bit_count+=8; } const int x=b->bit_buf&((1<<n)-1); b->bit_buf>>=n; b->bit_count-=n; return x; } // LZ77 // enum { W_BITS=21 }; // Window size (17..23) enum { W_SIZE=1<<W_BITS }; enum { W_MASK=W_SIZE-1 }; enum { SLOT_BITS=4 }; enum { NUM_SLOTS=1<<SLOT_BITS }; enum { A_BITS=2 }; // 1 xx enum { B_BITS=2 }; // 01 xx enum { C_BITS=2 }; // 001 xx enum { D_BITS=3 }; // 0001 xxx enum { E_BITS=5 }; // 00001 xxxxx enum { F_BITS=9 }; // 00000 xxxxxxxxx enum { A=1<<A_BITS }; enum { B=(1<<B_BITS)+A }; enum { C=(1<<C_BITS)+B }; enum { D=(1<<D_BITS)+C }; enum { E=(1<<E_BITS)+D }; enum { F=(1<<F_BITS)+E }; enum { MIN_MATCH=3 }; enum { MAX_MATCH=(F-1)+MIN_MATCH }; enum { TOO_FAR=1<<16 }; enum { HASH1_LEN=MIN_MATCH }; enum { HASH2_LEN=MIN_MATCH+1 }; enum { HASH1_BITS=21 }; enum { HASH2_BITS=24 }; enum { HASH1_SIZE=1<<HASH1_BITS }; enum { HASH2_SIZE=1<<HASH2_BITS }; enum { HASH1_MASK=HASH1_SIZE-1 }; enum { HASH2_MASK=HASH2_SIZE-1 }; enum { HASH1_SHIFT=(HASH1_BITS+(HASH1_LEN-1))/HASH1_LEN }; enum { HASH2_SHIFT=(HASH2_BITS+(HASH2_LEN-1))/HASH2_LEN }; static inline int update_hash1(int h, int c) { return ((h<<HASH1_SHIFT)+c)&HASH1_MASK; } static inline int update_hash2(int h, int c) { return ((h<<HASH2_SHIFT)+c)&HASH2_MASK; } static inline int get_min(int a, int b) { return a<b?a:b; } static inline int get_max(int a, int b) { return a>b?a:b; } static inline int get_penalty(int a, int b) { int p=0; while (a>b) { a>>=3; ++p; } return p; } static size_t crush_compress(const uint8_t* buf, size_t size, uint8_t* outbuf, size_t outlen, size_t level) { static int head[HASH1_SIZE+HASH2_SIZE]; static int prev[W_SIZE]; //const int max_chain[]={4, 256, 1<<12}; // original [0fast..2uber] const int max_chain[11] = { 0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 1<<12 }; //[0fastest..10uber] const int max_level = sizeof(max_chain)/sizeof(max_chain[0]); level = level > max_level ? max_level : level; bits bits; { for (int i=0; i<HASH1_SIZE+HASH2_SIZE; ++i) head[i]=-1; int h1=0; int h2=0; for (int i=0; i<HASH1_LEN; ++i) h1=update_hash1(h1, buf[i]); for (int i=0; i<HASH2_LEN; ++i) h2=update_hash2(h2, buf[i]); bits_init(&bits, NULL, outbuf); size_t p=0; while (p<size) { int len=MIN_MATCH-1; int offset=W_SIZE; const int max_match=get_min(MAX_MATCH, size-p); const int limit=get_max(p-W_SIZE, 0); if (head[h1]>=limit) { int s=head[h1]; if (buf[s]==buf[p]) { int l=0; while (++l<max_match) if (buf[s+l]!=buf[p+l]) break; if (l>len) { len=l; offset=p-s; } } } if (len<MAX_MATCH) { int chain_len=max_chain[level]; int s=head[h2+HASH1_SIZE]; while ((chain_len--!=0)&&(s>=limit)) { if ((buf[s+len]==buf[p+len])&&(buf[s]==buf[p])) { int l=0; while (++l<max_match) if (buf[s+l]!=buf[p+l]) break; if (l>len+get_penalty((p-s)>>4, offset)) { len=l; offset=p-s; } if (l==max_match) break; } s=prev[s&W_MASK]; } } if ((len==MIN_MATCH)&&(offset>TOO_FAR)) len=0; if ((level>=2)&&(len>=MIN_MATCH)&&(len<max_match)) { const int next_p=p+1; const int max_lazy=get_min(len+4, max_match); int chain_len=max_chain[level]; int s=head[update_hash2(h2, buf[next_p+(HASH2_LEN-1)])+HASH1_SIZE]; while ((chain_len--!=0)&&(s>=limit)) { if ((buf[s+len]==buf[next_p+len])&&(buf[s]==buf[next_p])) { int l=0; while (++l<max_lazy) if (buf[s+l]!=buf[next_p+l]) break; if (l>len+get_penalty(next_p-s, offset)) { len=0; break; } if (l==max_lazy) break; } s=prev[s&W_MASK]; } } if (len>=MIN_MATCH) // Match { bits_put(&bits, 1, 1); const int l=len-MIN_MATCH; if (l<A) { bits_put(&bits, 1, 1); // 1 bits_put(&bits, A_BITS, l); } else if (l<B) { bits_put(&bits, 2, 1<<1); // 01 bits_put(&bits, B_BITS, l-A); } else if (l<C) { bits_put(&bits, 3, 1<<2); // 001 bits_put(&bits, C_BITS, l-B); } else if (l<D) { bits_put(&bits, 4, 1<<3); // 0001 bits_put(&bits, D_BITS, l-C); } else if (l<E) { bits_put(&bits, 5, 1<<4); // 00001 bits_put(&bits, E_BITS, l-D); } else { bits_put(&bits, 5, 0); // 00000 bits_put(&bits, F_BITS, l-E); } --offset; int log=W_BITS-NUM_SLOTS; while (offset>=(2<<log)) ++log; bits_put(&bits, SLOT_BITS, log-(W_BITS-NUM_SLOTS)); if (log>(W_BITS-NUM_SLOTS)) bits_put(&bits, log, offset-(1<<log)); else bits_put(&bits, W_BITS-(NUM_SLOTS-1), offset); } else // Literal { len=1; bits_put(&bits, 9, buf[p]<<1); // 0 xxxxxxxx } while (len--!=0) // Insert new strings { head[h1]=p; prev[p&W_MASK]=head[h2+HASH1_SIZE]; head[h2+HASH1_SIZE]=p; ++p; h1=update_hash1(h1, buf[p+(HASH1_LEN-1)]); h2=update_hash2(h2, buf[p+(HASH2_LEN-1)]); } } bits_flush(&bits); } return bits.g_outbuf_pos; } static size_t crush_decompress(const uint8_t* inbuf, size_t inlen, uint8_t* outbuf, size_t outsize) { if (inlen<1) { //fprintf(stderr, "Corrupted stream: size=%d\n", (int)inlen); return 0; } bits bits; bits_init(&bits, inbuf, NULL); int p=0; while (bits.g_inbuf_pos<(int)inlen) { if (bits_get(&bits, 1)) { int len; /**/ if (bits_get(&bits, 1)) len=bits_get(&bits, A_BITS); else if (bits_get(&bits, 1)) len=bits_get(&bits, B_BITS)+A; else if (bits_get(&bits, 1)) len=bits_get(&bits, C_BITS)+B; else if (bits_get(&bits, 1)) len=bits_get(&bits, D_BITS)+C; else if (bits_get(&bits, 1)) len=bits_get(&bits, E_BITS)+D; else len=bits_get(&bits, F_BITS)+E; const int log=bits_get(&bits, SLOT_BITS)+(W_BITS-NUM_SLOTS); int s=~(log>(W_BITS-NUM_SLOTS) ?bits_get(&bits, log)+(1<<log) :bits_get(&bits, W_BITS-(NUM_SLOTS-1)))+p; if (s<0) { //fprintf(stderr, "Corrupted stream: s=%d p=%d inlen=%d\n", s, p, (int)inlen); return 0; } outbuf[p++]=outbuf[s++]; outbuf[p++]=outbuf[s++]; outbuf[p++]=outbuf[s++]; while (len--!=0) outbuf[p++]=outbuf[s++]; } else outbuf[p++]=bits_get(&bits, 8); } return p; } unsigned crush_encode(const void* in, unsigned inlen, void* out, unsigned outlen, unsigned flags) { unsigned level = flags > 10 ? 10 : flags < 0 ? 0 : flags; return crush_compress((const uint8_t*)in, (size_t)inlen, (uint8_t*)out, (size_t)outlen, (size_t)level); } unsigned crush_decode(const void* in, unsigned inlen, void* out, unsigned outlen) { return crush_decompress((const uint8_t*)in, (size_t)inlen, (uint8_t*)out, (size_t)outlen); } unsigned crush_bounds(unsigned inlen, unsigned flags) { return (unsigned)(inlen * 1.1) + 16; // @todo: check src } unsigned crush_excess(unsigned flags) { return (unsigned)0; } #endif // CRUSH_C #ifdef CRUSH_DEMO #pragma once int main() { const char *longcopy = "Hello world! Hello world! Hello world! Hello world!"; int level = 1; char out[128]; size_t outlen = crush_encode(longcopy, strlen(longcopy)+1, out, 128, level ); printf("%s %d->%d\n", outlen ? "ok" : "fail", (int)strlen(longcopy)+1, (int)outlen); char redo[128]; size_t unpacked = crush_decode(out, outlen, redo, 128); printf("%d->%d %s\n", (int)outlen, (int)unpacked, redo); } #define main main__ #endif // CRUSH_DEMO //#line 1 "amalgamated_deflate.c" // miniz.c v1.15 r4 - public domain de/inflate. See "unlicense" statement at http://unlicense.org/ // Rich Geldreich <richgel99@gmail.com>, last updated Oct. 13, 2013. Then stripped down by @r-lyeh. // Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt unsigned deflate_encode(const void *in, unsigned inlen, void *out, unsigned outlen, unsigned flags); // [0..(6)..9][10 (uber)] unsigned deflate_decode(const void *in, unsigned inlen, void *out, unsigned outlen); unsigned deflate_bounds(unsigned inlen, unsigned flags); unsigned deflate_excess(unsigned flags); #ifdef DEFLATE_C #pragma once #include <assert.h> // assert() #include <stdint.h> // types #include <stdlib.h> // realloc() #include <string.h> // Set to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. #ifndef MINIZ_USE_UNALIGNED_LOADS_AND_STORES #if defined(_M_X64) || defined(_M_IX86) #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #else #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 #endif #endif // Set to 1 if the processor is little endian. #ifndef MINIZ_LITTLE_ENDIAN #if defined(_M_X64) || defined(_M_IX86) || __BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__ #define MINIZ_LITTLE_ENDIAN 1 #else #define MINIZ_LITTLE_ENDIAN 0 #endif #endif // Set to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions). #ifndef MINIZ_HAS_64BIT_REGISTERS #if UINTPTR_MAX > 0xffffffff // defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__) #define MINIZ_HAS_64BIT_REGISTERS 1 #else #define MINIZ_HAS_64BIT_REGISTERS 0 #endif #endif // ------------------- Types and macros typedef uint32_t mz_uint; // An attempt to work around MSVC's spammy "warning C4127: conditional expression is constant" message. #ifdef _MSC_VER #define MZ_MACRO_END while (0, 0) #else #define MZ_MACRO_END while (0) #endif #define MZ_ASSERT(x) assert(x) #define MZ_MAX(a,b) (((a)>(b))?(a):(b)) #define MZ_MIN(a,b) (((a)<(b))?(a):(b)) #define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN #define MZ_READ_LE16(p) *((const uint16_t *)(p)) #define MZ_READ_LE32(p) *((const uint32_t *)(p)) #else #define MZ_READ_LE16(p) ((uint32_t)(((const uint8_t *)(p))[0]) | ((uint32_t)(((const uint8_t *)(p))[1]) << 8U)) #define MZ_READ_LE32(p) ((uint32_t)(((const uint8_t *)(p))[0]) | ((uint32_t)(((const uint8_t *)(p))[1]) << 8U) | ((uint32_t)(((const uint8_t *)(p))[2]) << 16U) | ((uint32_t)(((const uint8_t *)(p))[3]) << 24U)) #endif // Return status. typedef enum { TINFL_STATUS_BAD_PARAM = -3, TINFL_STATUS_ADLER32_MISMATCH = -2, TINFL_STATUS_FAILED = -1, TINFL_STATUS_DONE = 0, TINFL_STATUS_NEEDS_MORE_INPUT = 1, TINFL_STATUS_HAS_MORE_OUTPUT = 2 } tinfl_status; struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor; // ------------------- Low-level Decompression (completely independent from all compression API's) // Decompression flags used by tinfl_decompress(). // TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. // TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. // TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). // TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. enum { TINFL_FLAG_PARSE_ZLIB_HEADER = 1, TINFL_FLAG_HAS_MORE_INPUT = 2, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, TINFL_FLAG_COMPUTE_ADLER32 = 8 }; #define TINFL_MEMCPY memcpy #define TINFL_MEMSET memset #define TINFL_CR_BEGIN switch(r->m_state) { case 0: #define TINFL_CR_RETURN(state_index, result) do { status = result; r->m_state = state_index; /*printf("L%d\n", __LINE__);*/ goto common_exit; case state_index:; } MZ_MACRO_END #define TINFL_CR_RETURN_FOREVER(state_index, result) do { for ( ; ; ) { TINFL_CR_RETURN(state_index, result); } } MZ_MACRO_END #define TINFL_CR_FINISH } // TODO: If the caller has indicated that there's no more input, and we attempt to read beyond the input buf, then something is wrong with the input because the inflator never // reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of the stream with 0's in this scenario. #define TINFL_GET_BYTE(state_index, c) do { \ if (pIn_buf_cur >= pIn_buf_end) { \ for ( ; ; ) { \ if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \ TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \ if (pIn_buf_cur < pIn_buf_end) { \ c = *pIn_buf_cur++; \ break; \ } \ } else { \ c = 0; \ break; \ } \ } \ } else c = *pIn_buf_cur++; } MZ_MACRO_END #define TINFL_NEED_BITS(state_index, n) do { mz_uint c; TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; } while (num_bits < (mz_uint)(n)) #define TINFL_SKIP_BITS(state_index, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END #define TINFL_GET_BITS(state_index, b, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } b = bit_buf & ((1 << (n)) - 1); bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END // TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2. // It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a // Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the // bit buffer contains >=15 bits (deflate's max. Huffman code size). #define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ do { \ temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ if (temp >= 0) { \ code_len = temp >> 9; \ if ((code_len) && (num_bits >= code_len)) \ break; \ } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \ code_len = TINFL_FAST_LOOKUP_BITS; \ do { \ temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ } while ((temp < 0) && (num_bits >= (code_len + 1))); if (temp >= 0) break; \ } TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; \ } while (num_bits < 15); // TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read // beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully // decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32. // The slow path is only executed at the very end of the input buffer. #define TINFL_HUFF_DECODE(state_index, sym, pHuff) do { \ int temp; mz_uint code_len, c; \ if (num_bits < 15) { \ if ((pIn_buf_end - pIn_buf_cur) < 2) { \ TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ } else { \ bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); pIn_buf_cur += 2; num_bits += 16; \ } \ } \ if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \ code_len = temp >> 9, temp &= 511; \ else { \ code_len = TINFL_FAST_LOOKUP_BITS; do { temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; } while (temp < 0); \ } sym = temp; bit_buf >>= code_len; num_bits -= code_len; } MZ_MACRO_END // Internal/private bits follow. enum { TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19, TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS }; typedef struct { uint8_t m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; int16_t m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; } tinfl_huff_table; #if MINIZ_HAS_64BIT_REGISTERS typedef uint64_t tinfl_bit_buf_t; #define TINFL_BITBUF_SIZE (64) #else typedef uint32_t tinfl_bit_buf_t; #define TINFL_BITBUF_SIZE (32) #endif struct tinfl_decompressor_tag { uint32_t m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; tinfl_bit_buf_t m_bit_buf; size_t m_dist_from_out_buf_start; tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; uint8_t m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; }; tinfl_status tinfl_decompress(tinfl_decompressor *r, const uint8_t *pIn_buf_next, size_t *pIn_buf_size, uint8_t *pOut_buf_start, uint8_t *pOut_buf_next, size_t *pOut_buf_size, const uint32_t decomp_flags) { static const int s_length_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 }; static const int s_length_extra[31]= { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; static const int s_dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; static const int s_dist_extra[32] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; static const uint8_t s_length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; static const int s_min_table_sizes[3] = { 257, 1, 4 }; tinfl_status status = TINFL_STATUS_FAILED; uint32_t num_bits, dist, counter, num_extra; tinfl_bit_buf_t bit_buf; const uint8_t *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size; uint8_t *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size; size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; // Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter). if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) { *pIn_buf_size = *pOut_buf_size = 0; return TINFL_STATUS_BAD_PARAM; } num_bits = r->m_num_bits; bit_buf = r->m_bit_buf; dist = r->m_dist; counter = r->m_counter; num_extra = r->m_num_extra; dist_from_out_buf_start = r->m_dist_from_out_buf_start; TINFL_CR_BEGIN bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1; if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { TINFL_GET_BYTE(1, r->m_zhdr0); TINFL_GET_BYTE(2, r->m_zhdr1); counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1U << (8U + (r->m_zhdr0 >> 4))))); if (counter) { TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); } } do { TINFL_GET_BITS(3, r->m_final, 3); r->m_type = r->m_final >> 1; if (r->m_type == 0) { TINFL_SKIP_BITS(5, num_bits & 7); for (counter = 0; counter < 4; ++counter) { if (num_bits) TINFL_GET_BITS(6, r->m_raw_header[counter], 8); else TINFL_GET_BYTE(7, r->m_raw_header[counter]); } if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); } while ((counter) && (num_bits)) { TINFL_GET_BITS(51, dist, 8); while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = (uint8_t)dist; counter--; } while (counter) { size_t n; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); } while (pIn_buf_cur >= pIn_buf_end) { if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT); } else { TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED); } } n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter); TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (mz_uint)n; } } else if (r->m_type == 3) { TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); } else { if (r->m_type == 1) { uint8_t *p = r->m_tables[0].m_code_size; mz_uint i; r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32); for ( i = 0; i <= 143; ++i) *p++ = 8; for ( ; i <= 255; ++i) *p++ = 9; for ( ; i <= 279; ++i) *p++ = 7; for ( ; i <= 287; ++i) *p++ = 8; } else { for (counter = 0; counter < 3; counter++) { TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); r->m_table_sizes[counter] += s_min_table_sizes[counter]; } MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); for (counter = 0; counter < r->m_table_sizes[2]; counter++) { mz_uint s; TINFL_GET_BITS(14, s, 3); r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (uint8_t)s; } r->m_table_sizes[2] = 19; } for ( ; (int)r->m_type >= 0; r->m_type--) { int tree_next, tree_cur; tinfl_huff_table *pTable; mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; pTable = &r->m_tables[r->m_type]; MZ_CLEAR_OBJ(total_syms); MZ_CLEAR_OBJ(pTable->m_look_up); MZ_CLEAR_OBJ(pTable->m_tree); for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pTable->m_code_size[i]]++; used_syms = 0, total = 0; next_code[0] = next_code[1] = 0; for (i = 1; i <= 15; ++i) { used_syms += total_syms[i]; next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); } if ((65536 != total) && (used_syms > 1)) { TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); } for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) { mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; if (!code_size) continue; cur_code = next_code[code_size]++; for (l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1); if (code_size <= TINFL_FAST_LOOKUP_BITS) { int16_t k = (int16_t)((code_size << 9) | sym_index); while (rev_code < TINFL_FAST_LOOKUP_SIZE) { pTable->m_look_up[rev_code] = k; rev_code += (1 << code_size); } continue; } if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) { pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (int16_t)tree_next; tree_cur = tree_next; tree_next -= 2; } rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) { tree_cur -= ((rev_code >>= 1) & 1); if (!pTable->m_tree[-tree_cur - 1]) { pTable->m_tree[-tree_cur - 1] = (int16_t)tree_next; tree_cur = tree_next; tree_next -= 2; } else tree_cur = pTable->m_tree[-tree_cur - 1]; } tree_cur -= ((rev_code >>= 1) & 1); pTable->m_tree[-tree_cur - 1] = (int16_t)sym_index; } if (r->m_type == 2) { for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]); ) { mz_uint s; TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); if (dist < 16) { r->m_len_codes[counter++] = (uint8_t)dist; continue; } if ((dist == 16) && (!counter)) { TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); } num_extra = "\02\03\07"[dist - 16]; TINFL_GET_BITS(18, s, num_extra); s += "\03\03\013"[dist - 16]; TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); counter += s; } if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) { TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); } TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); } } for ( ; ; ) { uint8_t *pSrc; for ( ; ; ) { if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) { TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]); if (counter >= 256) break; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = (uint8_t)counter; } else { int sym2; mz_uint code_len; #if MINIZ_HAS_64BIT_REGISTERS if (num_bits < 30) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); pIn_buf_cur += 4; num_bits += 32; } #else if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } #endif if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) code_len = sym2 >> 9; else { code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); } counter = sym2; bit_buf >>= code_len; num_bits -= code_len; if (counter & 256) break; #if !MINIZ_HAS_64BIT_REGISTERS if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } #endif if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) code_len = sym2 >> 9; else { code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); } bit_buf >>= code_len; num_bits -= code_len; pOut_buf_cur[0] = (uint8_t)counter; if (sym2 & 256) { pOut_buf_cur++; counter = sym2; break; } pOut_buf_cur[1] = (uint8_t)sym2; pOut_buf_cur += 2; } } if ((counter &= 511) == 256) break; num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257]; if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(25, extra_bits, num_extra); counter += extra_bits; } TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]); num_extra = s_dist_extra[dist]; dist = s_dist_base[dist]; if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(27, extra_bits, num_extra); dist += extra_bits; } dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) { TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); } pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) { while (counter--) { while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask]; } continue; } #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES else if ((counter >= 9) && (counter <= dist)) { const uint8_t *pSrc_end = pSrc + (counter & ~7); do { ((uint32_t *)pOut_buf_cur)[0] = ((const uint32_t *)pSrc)[0]; ((uint32_t *)pOut_buf_cur)[1] = ((const uint32_t *)pSrc)[1]; pOut_buf_cur += 8; } while ((pSrc += 8) < pSrc_end); if ((counter &= 7) < 3) { if (counter) { pOut_buf_cur[0] = pSrc[0]; if (counter > 1) pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur += counter; } continue; } } #endif do { pOut_buf_cur[0] = pSrc[0]; pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur[2] = pSrc[2]; pOut_buf_cur += 3; pSrc += 3; } while ((int)(counter -= 3) > 2); if ((int)counter > 0) { pOut_buf_cur[0] = pSrc[0]; if ((int)counter > 1) pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur += counter; } } } } while (!(r->m_final & 1)); if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { TINFL_SKIP_BITS(32, num_bits & 7); for (counter = 0; counter < 4; ++counter) { mz_uint s; if (num_bits) TINFL_GET_BITS(41, s, 8); else TINFL_GET_BYTE(42, s); r->m_z_adler32 = (r->m_z_adler32 << 8) | s; } } TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); TINFL_CR_FINISH common_exit: r->m_num_bits = num_bits; r->m_bit_buf = bit_buf; r->m_dist = dist; r->m_counter = counter; r->m_num_extra = num_extra; r->m_dist_from_out_buf_start = dist_from_out_buf_start; *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next; if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) { const uint8_t *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size; uint32_t i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552; while (buf_len) { for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1; s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; } r->m_check_adler32 = (s2 << 16) + s1; if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) status = TINFL_STATUS_ADLER32_MISMATCH; } return status; } // end of inflate.c // begin of deflate.c // Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently). #define TDEFL_LESS_MEMORY 0 #ifndef MZ_REALLOC #define MZ_REALLOC REALLOC #endif #ifndef MZ_FORCEINLINE #ifdef _MSC_VER #define MZ_FORCEINLINE __forceinline #elif defined(__GNUC__) #define MZ_FORCEINLINE inline __attribute__((__always_inline__)) #else #define MZ_FORCEINLINE inline #endif #endif // ------------------- Types and macros typedef int32_t mz_bool; #define MZ_FALSE (0) #define MZ_TRUE (1) // ------------------- Low-level Compression API Definitions // tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search): // TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression). enum { TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF }; // TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. // TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers). // TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing. // TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory). // TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) // TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. // TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. // TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. // The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK). enum { TDEFL_WRITE_ZLIB_HEADER = 0x01000, TDEFL_COMPUTE_ADLER32 = 0x02000, TDEFL_GREEDY_PARSING_FLAG = 0x04000, TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, TDEFL_RLE_MATCHES = 0x10000, TDEFL_FILTER_MATCHES = 0x20000, TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 }; // Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. typedef mz_bool (*tdefl_callback)(const void* pBuf, int len, void *pUser); enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 }; // TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes). #if TDEFL_LESS_MEMORY enum { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; #else enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; #endif // The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions. typedef enum { TDEFL_STATUS_BAD_PARAM = -2, TDEFL_STATUS_PUT_BUF_FAILED = -1, TDEFL_STATUS_OKAY = 0, TDEFL_STATUS_DONE = 1, } tdefl_status; // Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums typedef enum { TDEFL_NO_FLUSH = 0, TDEFL_SYNC_FLUSH = 2, TDEFL_FULL_FLUSH = 3, TDEFL_FINISH = 4 } tdefl_flush; // tdefl's compression state structure. typedef struct { char *m_outbuffer[3]; // start,seek,end mz_uint m_flags, m_max_probes[2]; int m_greedy_parsing; mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; uint8_t *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; tdefl_status m_prev_return_status; const void *m_pIn_buf; void *m_pOut_buf; size_t *m_pIn_buf_size, *m_pOut_buf_size; tdefl_flush m_flush; const uint8_t *m_pSrc; size_t m_src_buf_left, m_out_buf_ofs; uint8_t m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; uint16_t m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; uint16_t m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; uint8_t m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; uint8_t m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; uint16_t m_next[TDEFL_LZ_DICT_SIZE]; uint16_t m_hash[TDEFL_LZ_HASH_SIZE]; uint8_t m_output_buf[TDEFL_OUT_BUF_SIZE]; } tdefl_compressor; // ------------------- zlib-style API's // mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL. uint32_t mz_adler32(uint32_t adler, const unsigned char *ptr, size_t buf_len) { uint32_t i, s1 = (adler & 0xffff), s2 = (adler >> 16); size_t block_len = buf_len % 5552; if (!ptr) return 1; // MZ_ADLER32_INIT; while (buf_len) { for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1; s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; } return (s2 << 16) + s1; } // ------------------- Low-level Compression (independent from all decompression API's) // Purposely making these tables static for faster init and thread safety. static const uint16_t s_tdefl_len_sym[256] = { 257,258,259,260,261,262,263,264,265,265,266,266,267,267,268,268,269,269,269,269,270,270,270,270,271,271,271,271,272,272,272,272, 273,273,273,273,273,273,273,273,274,274,274,274,274,274,274,274,275,275,275,275,275,275,275,275,276,276,276,276,276,276,276,276, 277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278, 279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280, 281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281, 282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282, 283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283, 284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,285 }; static const uint8_t s_tdefl_len_extra[256] = { 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,0 }; static const uint8_t s_tdefl_small_dist_sym[512] = { 0,1,2,3,4,4,5,5,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11, 11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13, 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,14,14,14,14, 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14, 14,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15, 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,16,16,16,16,16, 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,17,17,17,17,17,17, 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17, 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17, 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17 }; static const uint8_t s_tdefl_small_dist_extra[512] = { 0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5, 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7 }; static const uint8_t s_tdefl_large_dist_sym[128] = { 0,0,18,19,20,20,21,21,22,22,22,22,23,23,23,23,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,26,26, 26,26,26,26,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28, 28,28,28,28,28,28,28,28,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29 }; static const uint8_t s_tdefl_large_dist_extra[128] = { 0,0,8,8,9,9,9,9,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12, 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13, 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13 }; // Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values. typedef struct { uint16_t m_key, m_sym_index; } tdefl_sym_freq; static tdefl_sym_freq* tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq* pSyms0, tdefl_sym_freq* pSyms1) { uint32_t total_passes = 2, pass_shift, pass, i, hist[256 * 2]; tdefl_sym_freq* pCur_syms = pSyms0, *pNew_syms = pSyms1; MZ_CLEAR_OBJ(hist); for (i = 0; i < num_syms; i++) { mz_uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ((freq >> 8) & 0xFF)]++; } while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) total_passes--; for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) { const uint32_t* pHist = &hist[pass << 8]; mz_uint offsets[256], cur_ofs = 0; for (i = 0; i < 256; i++) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; } for (i = 0; i < num_syms; i++) pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i]; { tdefl_sym_freq* t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t; } } return pCur_syms; } // tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996. static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) { int root, leaf, next, avbl, used, dpth; if (n==0) return; else if (n==1) { A[0].m_key = 1; return; } A[0].m_key += A[1].m_key; root = 0; leaf = 2; for (next=1; next < n-1; next++) { if (leaf>=n || A[root].m_key<A[leaf].m_key) { A[next].m_key = A[root].m_key; A[root++].m_key = (uint16_t)next; } else A[next].m_key = A[leaf++].m_key; if (leaf>=n || (root<next && A[root].m_key<A[leaf].m_key)) { A[next].m_key = (uint16_t)(A[next].m_key + A[root].m_key); A[root++].m_key = (uint16_t)next; } else A[next].m_key = (uint16_t)(A[next].m_key + A[leaf++].m_key); } A[n-2].m_key = 0; for (next=n-3; next>=0; next--) A[next].m_key = A[A[next].m_key].m_key+1; avbl = 1; used = dpth = 0; root = n-2; next = n-1; while (avbl>0) { while (root>=0 && (int)A[root].m_key==dpth) { used++; root--; } while (avbl>used) { A[next--].m_key = (uint16_t)(dpth); avbl--; } avbl = 2*used; dpth++; used = 0; } } // Limits canonical Huffman code table's max code size. enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 }; static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size) { int i; uint32_t total = 0; if (code_list_len <= 1) return; for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) pNum_codes[max_code_size] += pNum_codes[i]; for (i = max_code_size; i > 0; i--) total += (((uint32_t)pNum_codes[i]) << (max_code_size - i)); while (total != (1UL << max_code_size)) { pNum_codes[max_code_size]--; for (i = max_code_size - 1; i > 0; i--) if (pNum_codes[i]) { pNum_codes[i]--; pNum_codes[i + 1] += 2; break; } total--; } } static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table) { int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; MZ_CLEAR_OBJ(num_codes); if (static_table) { for (i = 0; i < table_len; i++) num_codes[d->m_huff_code_sizes[table_num][i]]++; } else { tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms; int num_used_syms = 0; const uint16_t *pSym_count = &d->m_huff_count[table_num][0]; for (i = 0; i < table_len; i++) if (pSym_count[i]) { syms0[num_used_syms].m_key = (uint16_t)pSym_count[i]; syms0[num_used_syms++].m_sym_index = (uint16_t)i; } pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); tdefl_calculate_minimum_redundancy(pSyms, num_used_syms); for (i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++; tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit); MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); MZ_CLEAR_OBJ(d->m_huff_codes[table_num]); for (i = 1, j = num_used_syms; i <= code_size_limit; i++) for (l = num_codes[i]; l > 0; l--) d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (uint8_t)(i); } next_code[1] = 0; for (j = 0, i = 2; i <= code_size_limit; i++) next_code[i] = j = ((j + num_codes[i - 1]) << 1); for (i = 0; i < table_len; i++) { mz_uint rev_code = 0, code, code_size; if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue; code = next_code[code_size]++; for (l = code_size; l > 0; l--, code >>= 1) rev_code = (rev_code << 1) | (code & 1); d->m_huff_codes[table_num][i] = (uint16_t)rev_code; } } #define TDEFL_PUT_BITS(b, l) do { \ mz_uint bits = b; mz_uint len = l; MZ_ASSERT(bits <= ((1U << len) - 1U)); \ d->m_bit_buffer |= (bits << d->m_bits_in); d->m_bits_in += len; \ while (d->m_bits_in >= 8) { \ if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ *d->m_pOutput_buf++ = (uint8_t)(d->m_bit_buffer); \ d->m_bit_buffer >>= 8; \ d->m_bits_in -= 8; \ } \ } MZ_MACRO_END #define TDEFL_RLE_PREV_CODE_SIZE() { if (rle_repeat_count) { \ if (rle_repeat_count < 3) { \ d->m_huff_count[2][prev_code_size] = (uint16_t)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ while (rle_repeat_count--) packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ } else { \ d->m_huff_count[2][16] = (uint16_t)(d->m_huff_count[2][16] + 1); packed_code_sizes[num_packed_code_sizes++] = 16; packed_code_sizes[num_packed_code_sizes++] = (uint8_t)(rle_repeat_count - 3); \ } rle_repeat_count = 0; } } #define TDEFL_RLE_ZERO_CODE_SIZE() { if (rle_z_count) { \ if (rle_z_count < 3) { \ d->m_huff_count[2][0] = (uint16_t)(d->m_huff_count[2][0] + rle_z_count); while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \ } else if (rle_z_count <= 10) { \ d->m_huff_count[2][17] = (uint16_t)(d->m_huff_count[2][17] + 1); packed_code_sizes[num_packed_code_sizes++] = 17; packed_code_sizes[num_packed_code_sizes++] = (uint8_t)(rle_z_count - 3); \ } else { \ d->m_huff_count[2][18] = (uint16_t)(d->m_huff_count[2][18] + 1); packed_code_sizes[num_packed_code_sizes++] = 18; packed_code_sizes[num_packed_code_sizes++] = (uint8_t)(rle_z_count - 11); \ } rle_z_count = 0; } } static uint8_t s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; static void tdefl_start_dynamic_block(tdefl_compressor *d) { int num_lit_codes, num_dist_codes, num_bit_lengths; mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index; uint8_t code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF; d->m_huff_count[0][256] = 1; tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE); tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE); for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) if (d->m_huff_code_sizes[0][num_lit_codes - 1]) break; for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) if (d->m_huff_code_sizes[1][num_dist_codes - 1]) break; memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes); total_code_sizes_to_pack = num_lit_codes + num_dist_codes; num_packed_code_sizes = 0; rle_z_count = 0; rle_repeat_count = 0; memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); for (i = 0; i < total_code_sizes_to_pack; i++) { uint8_t code_size = code_sizes_to_pack[i]; if (!code_size) { TDEFL_RLE_PREV_CODE_SIZE(); if (++rle_z_count == 138) { TDEFL_RLE_ZERO_CODE_SIZE(); } } else { TDEFL_RLE_ZERO_CODE_SIZE(); if (code_size != prev_code_size) { TDEFL_RLE_PREV_CODE_SIZE(); d->m_huff_count[2][code_size] = (uint16_t)(d->m_huff_count[2][code_size] + 1); packed_code_sizes[num_packed_code_sizes++] = code_size; } else if (++rle_repeat_count == 6) { TDEFL_RLE_PREV_CODE_SIZE(); } } prev_code_size = code_size; } if (rle_repeat_count) { TDEFL_RLE_PREV_CODE_SIZE(); } else { TDEFL_RLE_ZERO_CODE_SIZE(); } tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE); TDEFL_PUT_BITS(2, 2); TDEFL_PUT_BITS(num_lit_codes - 257, 5); TDEFL_PUT_BITS(num_dist_codes - 1, 5); for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) if (d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) break; num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); TDEFL_PUT_BITS(num_bit_lengths - 4, 4); for (i = 0; (int)i < num_bit_lengths; i++) TDEFL_PUT_BITS(d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3); for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes; ) { mz_uint code = packed_code_sizes[packed_code_sizes_index++]; MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2); TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]); if (code >= 16) TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]); } } static void tdefl_start_static_block(tdefl_compressor *d) { mz_uint i; uint8_t *p = &d->m_huff_code_sizes[0][0]; for (i = 0; i <= 143; ++i) *p++ = 8; for ( ; i <= 255; ++i) *p++ = 9; for ( ; i <= 279; ++i) *p++ = 7; for ( ; i <= 287; ++i) *p++ = 8; memset(d->m_huff_code_sizes[1], 5, 32); tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE); tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE); TDEFL_PUT_BITS(1, 2); } static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF }; #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) { mz_uint flags; uint8_t *pLZ_codes; uint8_t *pOutput_buf = d->m_pOutput_buf; uint8_t *pLZ_code_buf_end = d->m_pLZ_code_buf; uint64_t bit_buffer = d->m_bit_buffer; mz_uint bits_in = d->m_bits_in; #define TDEFL_PUT_BITS_FAST(b, l) { bit_buffer |= (((uint64_t)(b)) << bits_in); bits_in += (l); } flags = 1; for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1) { if (flags == 1) flags = *pLZ_codes++ | 0x100; if (flags & 1) { mz_uint s0, s1, n0, n1, sym, num_extra_bits; mz_uint match_len = pLZ_codes[0], match_dist = *(const uint16_t *)(pLZ_codes + 1); pLZ_codes += 3; MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); // This sequence coaxes MSVC into using cmov's vs. jmp's. s0 = s_tdefl_small_dist_sym[match_dist & 511]; n0 = s_tdefl_small_dist_extra[match_dist & 511]; s1 = s_tdefl_large_dist_sym[match_dist >> 8]; n1 = s_tdefl_large_dist_extra[match_dist >> 8]; sym = (match_dist < 512) ? s0 : s1; num_extra_bits = (match_dist < 512) ? n0 : n1; MZ_ASSERT(d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); } else { mz_uint lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); } } } if (pOutput_buf >= d->m_pOutput_buf_end) return MZ_FALSE; *(uint64_t*)pOutput_buf = bit_buffer; pOutput_buf += (bits_in >> 3); bit_buffer >>= (bits_in & ~7); bits_in &= 7; } #undef TDEFL_PUT_BITS_FAST d->m_pOutput_buf = pOutput_buf; d->m_bits_in = 0; d->m_bit_buffer = 0; while (bits_in) { uint32_t n = MZ_MIN(bits_in, 16); TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n); bit_buffer >>= n; bits_in -= n; } TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); return (d->m_pOutput_buf < d->m_pOutput_buf_end); } #else static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) { mz_uint flags; uint8_t *pLZ_codes; flags = 1; for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1) { if (flags == 1) flags = *pLZ_codes++ | 0x100; if (flags & 1) { mz_uint sym, num_extra_bits; mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); pLZ_codes += 3; MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); if (match_dist < 512) { sym = s_tdefl_small_dist_sym[match_dist]; num_extra_bits = s_tdefl_small_dist_extra[match_dist]; } else { sym = s_tdefl_large_dist_sym[match_dist >> 8]; num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; } MZ_ASSERT(d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); } else { mz_uint lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); } } TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); return (d->m_pOutput_buf < d->m_pOutput_buf_end); } #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) { if (static_block) tdefl_start_static_block(d); else tdefl_start_dynamic_block(d); return tdefl_compress_lz_codes(d); } static int tdefl_flush_block(tdefl_compressor *d, int flush) { mz_uint saved_bit_buf, saved_bits_in; uint8_t *pSaved_output_buf; mz_bool comp_block_succeeded = MZ_FALSE; int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; uint8_t *pOutput_buf_start = ((d->m_outbuffer[0] == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((uint8_t *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf; d->m_pOutput_buf = pOutput_buf_start; d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16; MZ_ASSERT(!d->m_output_flush_remaining); d->m_output_flush_ofs = 0; d->m_output_flush_remaining = 0; *d->m_pLZ_flags = (uint8_t)(*d->m_pLZ_flags >> d->m_num_flags_left); d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) { TDEFL_PUT_BITS(0x78, 8); TDEFL_PUT_BITS(0x01, 8); } TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1); pSaved_output_buf = d->m_pOutput_buf; saved_bit_buf = d->m_bit_buffer; saved_bits_in = d->m_bits_in; if (!use_raw_block) comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48)); // If the block gets expanded, forget the current contents of the output buffer and send a raw block instead. if ( ((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) && ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size) ) { mz_uint i; d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; TDEFL_PUT_BITS(0, 2); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) { TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16); } for (i = 0; i < d->m_total_lz_bytes; ++i) { TDEFL_PUT_BITS(d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8); } } // Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes. else if (!comp_block_succeeded) { d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; tdefl_compress_block(d, MZ_TRUE); } if (flush) { if (flush == TDEFL_FINISH) { if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) { mz_uint i, a = d->m_adler32; for (i = 0; i < 4; i++) { TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); a <<= 8; } } } else { mz_uint i, z = 0; TDEFL_PUT_BITS(0, 3); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, z ^= 0xFFFF) { TDEFL_PUT_BITS(z & 0xFFFF, 16); } } } MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end); memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; d->m_total_lz_bytes = 0; d->m_block_index++; if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) { if (d->m_outbuffer[0]) { *d->m_pIn_buf_size = d->m_pSrc - (const uint8_t *)d->m_pIn_buf; uintptr_t capacity = (uintptr_t)d->m_outbuffer[2] - (uintptr_t)d->m_outbuffer[1]; if( n > capacity ) return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); memcpy(d->m_outbuffer[1], d->m_output_buf, n); d->m_outbuffer[1] += n; } else if (pOutput_buf_start == d->m_output_buf) { int bytes_to_copy = (int)MZ_MIN((size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs)); memcpy((uint8_t *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy); d->m_out_buf_ofs += bytes_to_copy; if ((n -= bytes_to_copy) != 0) { d->m_output_flush_ofs = bytes_to_copy; d->m_output_flush_remaining = n; } } else { d->m_out_buf_ofs += n; } } return d->m_output_flush_remaining; } #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES #define TDEFL_READ_UNALIGNED_WORD(p) *(const uint16_t*)(p) static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) { mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; const uint16_t *s = (const uint16_t*)(d->m_dict + pos), *p, *q; uint16_t c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD(s); MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; for ( ; ; ) { for ( ; ; ) { if (--num_probes_left == 0) return; #define TDEFL_PROBE \ next_probe_pos = d->m_next[probe_pos]; \ if ((!next_probe_pos) || ((dist = (uint16_t)(lookahead_pos - next_probe_pos)) > max_dist)) return; \ probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) break; TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; } if (!dist) break; q = (const uint16_t*)(d->m_dict + probe_pos); if (TDEFL_READ_UNALIGNED_WORD(q) != s01) continue; p = s; probe_len = 32; do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0) ); if (!probe_len) { *pMatch_dist = dist; *pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN); break; } else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const uint8_t*)p == *(const uint8_t*)q)) > match_len) { *pMatch_dist = dist; if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) break; c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]); } } } #else static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) { mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; const uint8_t *s = d->m_dict + pos, *p, *q; uint8_t c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1]; MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; for ( ; ; ) { for ( ; ; ) { if (--num_probes_left == 0) return; #define TDEFL_PROBE \ next_probe_pos = d->m_next[probe_pos]; \ if ((!next_probe_pos) || ((dist = (uint16_t)(lookahead_pos - next_probe_pos)) > max_dist)) return; \ probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) break; TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; } if (!dist) break; p = s; q = d->m_dict + probe_pos; for (probe_len = 0; probe_len < max_match_len; probe_len++) if (*p++ != *q++) break; if (probe_len > match_len) { *pMatch_dist = dist; if ((*pMatch_len = match_len = probe_len) == max_match_len) return; c0 = d->m_dict[pos + match_len]; c1 = d->m_dict[pos + match_len - 1]; } } } #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN static mz_bool tdefl_compress_fast(tdefl_compressor *d) { // Faster, minimally featured LZRW1-style match+parse loop with better register utilization. Intended for applications where raw throughput is valued more highly than ratio. mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left; uint8_t *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) { const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size); d->m_src_buf_left -= num_bytes_to_process; lookahead_size += num_bytes_to_process; while (num_bytes_to_process) { uint32_t n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); memcpy(d->m_dict + dst_pos, d->m_pSrc, n); if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); d->m_pSrc += n; dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; num_bytes_to_process -= n; } dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) break; while (lookahead_size >= 4) { mz_uint cur_match_dist, cur_match_len = 1; uint8_t *pCur_dict = d->m_dict + cur_pos; mz_uint first_trigram = (*(const uint32_t *)pCur_dict) & 0xFFFFFF; mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK; mz_uint probe_pos = d->m_hash[hash]; d->m_hash[hash] = (uint16_t)lookahead_pos; if (((cur_match_dist = (uint16_t)(lookahead_pos - probe_pos)) <= dict_size) && ((*(const uint32_t *)(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) { const uint16_t *p = (const uint16_t *)pCur_dict; const uint16_t *q = (const uint16_t *)(d->m_dict + probe_pos); uint32_t probe_len = 32; do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0) ); cur_match_len = ((mz_uint)(p - (const uint16_t *)pCur_dict) * 2) + (mz_uint)(*(const uint8_t *)p == *(const uint8_t *)q); if (!probe_len) cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U))) { cur_match_len = 1; *pLZ_code_buf++ = (uint8_t)first_trigram; *pLZ_flags = (uint8_t)(*pLZ_flags >> 1); d->m_huff_count[0][(uint8_t)first_trigram]++; } else { uint32_t s0, s1; cur_match_len = MZ_MIN(cur_match_len, lookahead_size); MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); cur_match_dist--; pLZ_code_buf[0] = (uint8_t)(cur_match_len - TDEFL_MIN_MATCH_LEN); *(uint16_t *)(&pLZ_code_buf[1]) = (uint16_t)cur_match_dist; pLZ_code_buf += 3; *pLZ_flags = (uint8_t)((*pLZ_flags >> 1) | 0x80); s0 = s_tdefl_small_dist_sym[cur_match_dist & 511]; s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8]; d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++; } } else { *pLZ_code_buf++ = (uint8_t)first_trigram; *pLZ_flags = (uint8_t)(*pLZ_flags >> 1); d->m_huff_count[0][(uint8_t)first_trigram]++; } if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } total_lz_bytes += cur_match_len; lookahead_pos += cur_match_len; dict_size = MZ_MIN(dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE); cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK; MZ_ASSERT(lookahead_size >= cur_match_len); lookahead_size -= cur_match_len; if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { int n; d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; } } while (lookahead_size) { uint8_t lit = d->m_dict[cur_pos]; total_lz_bytes++; *pLZ_code_buf++ = lit; *pLZ_flags = (uint8_t)(*pLZ_flags >> 1); if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } d->m_huff_count[0][lit]++; lookahead_pos++; dict_size = MZ_MIN(dict_size + 1, TDEFL_LZ_DICT_SIZE); cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; lookahead_size--; if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { int n; d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; } } } d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; return MZ_TRUE; } #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, uint8_t lit) { d->m_total_lz_bytes++; *d->m_pLZ_code_buf++ = lit; *d->m_pLZ_flags = (uint8_t)(*d->m_pLZ_flags >> 1); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } d->m_huff_count[0][lit]++; } static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) { uint32_t s0, s1; MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE)); d->m_total_lz_bytes += match_len; d->m_pLZ_code_buf[0] = (uint8_t)(match_len - TDEFL_MIN_MATCH_LEN); match_dist -= 1; d->m_pLZ_code_buf[1] = (uint8_t)(match_dist & 0xFF); d->m_pLZ_code_buf[2] = (uint8_t)(match_dist >> 8); d->m_pLZ_code_buf += 3; *d->m_pLZ_flags = (uint8_t)((*d->m_pLZ_flags >> 1) | 0x80); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } s0 = s_tdefl_small_dist_sym[match_dist & 511]; s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127]; d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; if (match_len >= TDEFL_MIN_MATCH_LEN) d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; } static mz_bool tdefl_compress_normal(tdefl_compressor *d) { const uint8_t *pSrc = d->m_pSrc; size_t src_buf_left = d->m_src_buf_left; tdefl_flush flush = d->m_flush; while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) { mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; // Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN. if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) { mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2; mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]; mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size); const uint8_t *pSrc_end = pSrc + num_bytes_to_process; src_buf_left -= num_bytes_to_process; d->m_lookahead_size += num_bytes_to_process; while (pSrc != pSrc_end) { uint8_t c = *pSrc++; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (uint16_t)(ins_pos); dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; ins_pos++; } } else { while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) { uint8_t c = *pSrc++; mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; src_buf_left--; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) { mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (uint16_t)(ins_pos); } } } d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) break; // Simple lazy/greedy parsing state machine. len_to_move = 1; cur_match_dist = 0; cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) { if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) { uint8_t c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; cur_match_len = 0; while (cur_match_len < d->m_lookahead_size) { if (d->m_dict[cur_pos + cur_match_len] != c) break; cur_match_len++; } if (cur_match_len < TDEFL_MIN_MATCH_LEN) cur_match_len = 0; else cur_match_dist = 1; } } else { tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len); } if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) { cur_match_dist = cur_match_len = 0; } if (d->m_saved_match_len) { if (cur_match_len > d->m_saved_match_len) { tdefl_record_literal(d, (uint8_t)d->m_saved_lit); if (cur_match_len >= 128) { tdefl_record_match(d, cur_match_len, cur_match_dist); d->m_saved_match_len = 0; len_to_move = cur_match_len; } else { d->m_saved_lit = d->m_dict[cur_pos]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; } } else { tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist); len_to_move = d->m_saved_match_len - 1; d->m_saved_match_len = 0; } } else if (!cur_match_dist) tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]); else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128)) { tdefl_record_match(d, cur_match_len, cur_match_dist); len_to_move = cur_match_len; } else { d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; } // Move the lookahead forward by len_to_move bytes. d->m_lookahead_pos += len_to_move; MZ_ASSERT(d->m_lookahead_size >= len_to_move); d->m_lookahead_size -= len_to_move; d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, TDEFL_LZ_DICT_SIZE); // Check if it's time to flush the current LZ codes to the internal output buffer. if ( (d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || ( (d->m_total_lz_bytes > 31*1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) ) { int n; d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; } } d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; return MZ_TRUE; } static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) { if (d->m_pIn_buf_size) { *d->m_pIn_buf_size = d->m_pSrc - (const uint8_t *)d->m_pIn_buf; } if (d->m_pOut_buf_size) { size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining); memcpy((uint8_t *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n); d->m_output_flush_ofs += (mz_uint)n; d->m_output_flush_remaining -= (mz_uint)n; d->m_out_buf_ofs += n; *d->m_pOut_buf_size = d->m_out_buf_ofs; } return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY; } tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush) { if (!d) { if (pIn_buf_size) *pIn_buf_size = 0; if (pOut_buf_size) *pOut_buf_size = 0; return TDEFL_STATUS_BAD_PARAM; } d->m_pIn_buf = pIn_buf; d->m_pIn_buf_size = pIn_buf_size; d->m_pOut_buf = pOut_buf; d->m_pOut_buf_size = pOut_buf_size; d->m_pSrc = (const uint8_t *)(pIn_buf); d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; d->m_out_buf_ofs = 0; d->m_flush = flush; if ( ((d->m_outbuffer[0] != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) || (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf) ) { if (pIn_buf_size) *pIn_buf_size = 0; if (pOut_buf_size) *pOut_buf_size = 0; return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); } d->m_wants_to_finish |= (flush == TDEFL_FINISH); if ((d->m_output_flush_remaining) || (d->m_finished)) return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0)) { if (!tdefl_compress_fast(d)) return d->m_prev_return_status; } else #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN { if (!tdefl_compress_normal(d)) return d->m_prev_return_status; } if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf)) d->m_adler32 = (uint32_t)mz_adler32(d->m_adler32, (const uint8_t *)pIn_buf, d->m_pSrc - (const uint8_t *)pIn_buf); if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining)) { if (tdefl_flush_block(d, flush) < 0) return d->m_prev_return_status; d->m_finished = (flush == TDEFL_FINISH); if (flush == TDEFL_FULL_FLUSH) { MZ_CLEAR_OBJ(d->m_hash); MZ_CLEAR_OBJ(d->m_next); d->m_dict_size = 0; } } return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); } tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush) { MZ_ASSERT(d->m_outbuffer[0]); MZ_ASSERT(d->m_outbuffer[1]); MZ_ASSERT(d->m_outbuffer[2]); return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush); } tdefl_status tdefl_init(tdefl_compressor *d, void *out, size_t outlen, int flags) { #if 0 d->m_putbuf_callback = putbuf_callback; d->m_pPut_buf_user = pPut_buf_user; d->m_flags = (mz_uint)(flags); d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_OBJ(d->m_hash); d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_pOutput_buf = d->m_output_buf; d->m_pOutput_buf_end = d->m_output_buf; d->m_prev_return_status = TDEFL_STATUS_OKAY; d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; d->m_adler32 = 1; d->m_pIn_buf = NULL; d->m_pOut_buf = NULL; d->m_pIn_buf_size = NULL; d->m_pOut_buf_size = NULL; d->m_flush = TDEFL_NO_FLUSH; d->m_pSrc = NULL; d->m_src_buf_left = 0; d->m_out_buf_ofs = 0; memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); #else tdefl_compressor zero = {0}; *d = zero; // invalidated TDEFL_NONDETERMINISTIC_PARSING_FLAG option here d->m_outbuffer[0] = d->m_outbuffer[1] = (char*)out; d->m_outbuffer[2] = d->m_outbuffer[0] + outlen; d->m_flags = (mz_uint)(flags); d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_pOutput_buf = d->m_output_buf; d->m_pOutput_buf_end = d->m_output_buf; d->m_prev_return_status = TDEFL_STATUS_OKAY; d->m_adler32 = 1; d->m_flush = TDEFL_NO_FLUSH; //memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); //memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); #endif return TDEFL_STATUS_OKAY; } // end of deflate.c unsigned deflate_decode(const void *in, unsigned inlen_, void *out, unsigned outlen_) { size_t inlen = inlen_, outlen = outlen_; tinfl_decompressor decomp = {0}; tinfl_status status; // tinfl_init(&decomp); status = tinfl_decompress(&decomp, (const uint8_t*)in, &inlen, (uint8_t*)out, (uint8_t*)out, &outlen, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); return (unsigned)((status != TINFL_STATUS_DONE) ? 0 : outlen); } unsigned deflate_encode(const void *in, unsigned inlen, void *out, unsigned outlen, unsigned flags /*[0..9|10]*/) { size_t bytes = 0; if(in && inlen && out && outlen) { int level = flags > 10 ? 10 : flags < 0 ? 0 : flags; const mz_uint tdefl_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; mz_uint comp_flags = tdefl_num_probes[level % 12] | (level <= 3 ? TDEFL_GREEDY_PARSING_FLAG : 0);// | TDEFL_WRITE_ZLIB_HEADER ); tdefl_compressor *pComp = (tdefl_compressor*)MZ_REALLOC(0,sizeof(tdefl_compressor)); if (!pComp) return MZ_FALSE; if(tdefl_init(pComp, out, outlen, (int)comp_flags) == TDEFL_STATUS_OKAY) { if(tdefl_compress_buffer(pComp, in, inlen, TDEFL_FINISH) == TDEFL_STATUS_DONE) { bytes = pComp->m_outbuffer[1] - pComp->m_outbuffer[0]; } } MZ_REALLOC(pComp, 0); } return (unsigned)bytes; } unsigned deflate_bounds(unsigned inlen, unsigned flags) { return (unsigned)MZ_MAX(128 + (inlen * 110) / 100, 128 + inlen + ((inlen / (31 * 1024)) + 1) * 5); } unsigned deflate_excess(unsigned flags) { return (unsigned)0; } #endif // DEFLATE_C #ifdef DEFLATE_DEMO #pragma once int main() { const char *longcopy = "Hello world! Hello world! Hello world! Hello world!"; int level=1; char out[128]; unsigned outlen = deflate_encode(longcopy, strlen(longcopy)+1, out, 128, level); printf("%s %d->%d\n", outlen ? "ok" : "fail", (int)strlen(longcopy)+1, (int)outlen); char redo[128]; unsigned unpacked = deflate_decode(out, outlen, redo, 128); printf("%d->%d %s\n", (int)outlen, (int)unpacked, redo); } #define main main__ #endif // DEFLATE_DEMO //#line 1 "amalgamated_lz4x.c" // LZ4X - An optimized LZ4 compressor // Written and placed in the public domain by Ilya Muravyov (UNLICENSED) // MemBased by @r-lyeh. @todo: thread-safe unsigned lz4x_encode(const void *in, unsigned inlen, void *out, unsigned outlen, unsigned flags); //[1(fastest)..(6)..15(uber)] unsigned lz4x_decode(const void *in, unsigned inlen, void *out, unsigned outlen); unsigned lz4x_bounds(unsigned inlen, unsigned flags); unsigned lz4x_excess(unsigned flags); #ifdef LZ4X_C #pragma once #define _CRT_SECURE_NO_WARNINGS #define _CRT_DISABLE_PERFCRIT_LOCKS #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <time.h> #include <stdbool.h> #ifndef LZ4X_REALLOC #define LZ4X_REALLOC REALLOC #endif #define LZ4X_BLOCK_SIZE (8<<20) // 8 MB #define LZ4X_PADDING_LITERALS 5 #define LZ4X_WINDOW_BITS 16 #define LZ4X_WINDOW_SIZE (1<<LZ4X_WINDOW_BITS) #define LZ4X_WINDOW_MASK (LZ4X_WINDOW_SIZE-1) #define LZ4X_MIN_MATCH 4 #define LZ4X_EXCESS (16+(LZ4X_BLOCK_SIZE/255)) #define LZ4X_MIN(a, b) (((a)<(b))?(a):(b)) #define LZ4X_MAX(a, b) (((a)>(b))?(a):(b)) #define LZ4X_LOAD_16(p) (*(const uint16_t*)(p)) #define LZ4X_LOAD_32(p) (*(const uint32_t*)(p)) #define LZ4X_STORE_16(p, x) (*(uint16_t*)(p)=(x)) #define LZ4X_COPY_32(d, s) (*(uint32_t*)(d)=LZ4X_LOAD_32(s)) #define LZ4X_HASH_BITS 18 #define LZ4X_HASH_SIZE (1<<LZ4X_HASH_BITS) #define LZ4X_NIL (-1) #define LZ4X_HASH_32(p) ((LZ4X_LOAD_32(p)*0x9E3779B9)>>(32-LZ4X_HASH_BITS)) #define lz4x_wild_copy(d,s,n) do { \ LZ4X_COPY_32(d, s); \ LZ4X_COPY_32(d+4, s+4); \ for (int i_=8; i_<n; i_+=8) { \ LZ4X_COPY_32(d+i_, s+i_); \ LZ4X_COPY_32(d+4+i_, s+4+i_); \ } \ } while(0) int lz4x_compress_optimal(const uint8_t *in, size_t inlen, uint8_t *out, size_t outlen) { static int head[LZ4X_HASH_SIZE]; static int nodes[LZ4X_WINDOW_SIZE][2]; struct lz4x_path { int cum; int len; int dist; } *path; //path[LZ4X_BLOCK_SIZE+1]; path = (struct lz4x_path*)LZ4X_REALLOC(0, sizeof(path[0]) * (inlen+1)); int n = (int)inlen; // Pass 1: Find all matches for (int i=0; i<LZ4X_HASH_SIZE; ++i) head[i]=LZ4X_NIL; for (int p=0; p<n; ++p) { int best_len=0; int dist=0; const int max_match=(n-LZ4X_PADDING_LITERALS)-p; if (max_match>=LZ4X_MAX(12-LZ4X_PADDING_LITERALS, LZ4X_MIN_MATCH)) { const int limit=LZ4X_MAX(p-LZ4X_WINDOW_SIZE, LZ4X_NIL); int* left=&nodes[p&LZ4X_WINDOW_MASK][1]; int* right=&nodes[p&LZ4X_WINDOW_MASK][0]; int left_len=0; int right_len=0; const uint32_t h=LZ4X_HASH_32(&in[p]); int s=head[h]; head[h]=p; while (s>limit) { int len=LZ4X_MIN(left_len, right_len); if (in[s+len]==in[p+len]) { while (++len<max_match && in[s+len]==in[p+len]); if (len>best_len) { best_len=len; dist=p-s; if (len==max_match || len>=(1<<16)) break; } } if (in[s+len]<in[p+len]) // in/out out/in ? { *right=s; right=&nodes[s&LZ4X_WINDOW_MASK][1]; s=*right; right_len=len; } else { *left=s; left=&nodes[s&LZ4X_WINDOW_MASK][0]; s=*left; left_len=len; } } *left=LZ4X_NIL; *right=LZ4X_NIL; } path[p].len=best_len; path[p].dist=dist; } // Pass 2: Build the shortest path path[n].cum=0; int count=15; for (int p=n-1; p>0; --p) { int c0=path[p+1].cum+1; if (--count==0) { count=255; ++c0; } int len=path[p].len; if (len>=LZ4X_MIN_MATCH) { int c1=1<<30; const int j=LZ4X_MAX(len-255, LZ4X_MIN_MATCH); for (int i=len; i>=j; --i) { int tmp=path[p+i].cum+3; if (i>=(15+LZ4X_MIN_MATCH)) tmp+=1+((i-(15+LZ4X_MIN_MATCH))/255); if (tmp<c1) { c1=tmp; len=i; } } if (c1<=c0) { path[p].cum=c1; path[p].len=len; count=15; } else { path[p].cum=c0; path[p].len=0; } } else path[p].cum=c0; } // Pass 3: Output the codes int op=0; int pp=0; int p=0; while (p<n) { if (path[p].len>=LZ4X_MIN_MATCH) { int len=path[p].len-LZ4X_MIN_MATCH; const int nib=LZ4X_MIN(len, 15); if (pp!=p) { const int run=p-pp; if (run>=15) { out[op++]=(15<<4)+nib; int j=run-15; for (; j>=255; j-=255) out[op++]=255; out[op++]=j; } else out[op++]=(run<<4)+nib; lz4x_wild_copy(&out[op], &in[pp], run); op+=run; } else out[op++]=nib; LZ4X_STORE_16(&out[op], path[p].dist); op+=2; if (len>=15) { len-=15; for (; len>=255; len-=255) out[op++]=255; out[op++]=len; } p+=path[p].len; pp=p; } else ++p; } if (pp!=p) { const int run=p-pp; if (run>=15) { out[op++]=15<<4; int j=run-15; for (; j>=255; j-=255) out[op++]=255; out[op++]=j; } else out[op++]=run<<4; lz4x_wild_copy(&out[op], &in[pp], run); op+=run; } LZ4X_REALLOC(path, 0); const int comp_len=op; return comp_len; } int lz4x_compress(const uint8_t *in, size_t inlen, uint8_t *out, size_t outlen, unsigned max_chain) { static int head[LZ4X_HASH_SIZE]; static int tail[LZ4X_WINDOW_SIZE]; int n = (int)inlen; for (int i=0; i<LZ4X_HASH_SIZE; ++i) head[i]=LZ4X_NIL; int op=0; int pp=0; int p=0; while (p<n) { int best_len=0; int dist=0; const int max_match=(n-LZ4X_PADDING_LITERALS)-p; if (max_match>=LZ4X_MAX(12-LZ4X_PADDING_LITERALS, LZ4X_MIN_MATCH)) { const int limit=LZ4X_MAX(p-LZ4X_WINDOW_SIZE, LZ4X_NIL); int chain_len=max_chain; int s=head[LZ4X_HASH_32(&in[p])]; while (s>limit) { if (in[s+best_len]==in[p+best_len] && LZ4X_LOAD_32(&in[s])==LZ4X_LOAD_32(&in[p])) { int len=LZ4X_MIN_MATCH; while (len<max_match && in[s+len]==in[p+len]) ++len; if (len>best_len) { best_len=len; dist=p-s; if (len==max_match) break; } } if (--chain_len<=0) break; s=tail[s&LZ4X_WINDOW_MASK]; } } if (best_len>=LZ4X_MIN_MATCH) { int len=best_len-LZ4X_MIN_MATCH; const int nib=LZ4X_MIN(len, 15); if (pp!=p) { const int run=p-pp; if (run>=15) { out[op++]=(15<<4)+nib; int j=run-15; for (; j>=255; j-=255) out[op++]=255; out[op++]=j; } else out[op++]=(run<<4)+nib; lz4x_wild_copy(&out[op], &in[pp], run); op+=run; } else out[op++]=nib; LZ4X_STORE_16(&out[op], dist); op+=2; if (len>=15) { len-=15; for (; len>=255; len-=255) out[op++]=255; out[op++]=len; } pp=p+best_len; while (p<pp) { const uint32_t h=LZ4X_HASH_32(&in[p]); // out? tail[p&LZ4X_WINDOW_MASK]=head[h]; head[h]=p++; } } else { const uint32_t h=LZ4X_HASH_32(&in[p]); // out? tail[p&LZ4X_WINDOW_MASK]=head[h]; head[h]=p++; } } if (pp!=p) { const int run=p-pp; if (run>=15) { out[op++]=15<<4; int j=run-15; for (; j>=255; j-=255) out[op++]=255; out[op++]=j; } else out[op++]=run<<4; lz4x_wild_copy(&out[op], &in[pp], run); op+=run; } const int comp_len=op; return comp_len; } int lz4x_decompress(const uint8_t *in, size_t inlen, uint8_t *out, size_t outlen) { int n = (int)inlen; int p=0; int ip=0; const int ip_end=ip+n; for (;;) { const int token=in[ip++]; if (token>=16) { int run=token>>4; if (run==15) { for (;;) { const int c=in[ip++]; run+=c; if (c!=255) break; } } if ((p+run)>outlen) return 0; // -1 lz4x_wild_copy(&out[p], &in[ip], run); p+=run; ip+=run; if (ip>=ip_end) break; } int s=p-LZ4X_LOAD_16(&in[ip]); ip+=2; if (s<0) return 0; // -1 int len=(token&15)+LZ4X_MIN_MATCH; if (len==(15+LZ4X_MIN_MATCH)) { for (;;) { const int c=in[ip++]; len+=c; if (c!=255) break; } } if ((p+len)>outlen) return 0; // -1 if ((p-s)>=4) { lz4x_wild_copy(&out[p], &out[s], len); p+=len; } else { while (len--!=0) out[p++]=out[s++]; } } return p; } unsigned lz4x_encode(const void *in, unsigned inlen, void *out, unsigned outlen, unsigned flags/*[1..15*/) { unsigned level = (unsigned)(flags > 15 ? 15 : flags < 1 ? 1 : flags); if(level >= 15) return lz4x_compress_optimal((const uint8_t*)in, inlen, (uint8_t*)out, outlen); return (unsigned)lz4x_compress((const uint8_t*)in, inlen, (uint8_t*)out, outlen, level); } unsigned lz4x_decode(const void *in, unsigned inlen, void *out, unsigned outlen) { return (unsigned)lz4x_decompress((const uint8_t*)in, (size_t)inlen, (uint8_t*)out, (size_t)outlen); } unsigned lz4x_bounds(unsigned inlen, unsigned flags) { return (unsigned)(inlen + (inlen/255) + 16); } unsigned lz4x_excess(unsigned flags) { // return (unsigned)(16+(LZ4X_BLOCK_SIZE/255)); // 32912.5, same as LZ4X_EXCESS return (unsigned)(16); // ok? } #endif // LZ4X_C #ifdef LZ4X_DEMO #pragma once int main() { const char *longcopy = "Hello world! Hello world! Hello world! Hello world!"; int level=1; char out[128]; unsigned outlen = lz4x_encode(longcopy, strlen(longcopy)+1, out, 128, level); printf("%s %d->%d\n", outlen ? "ok" : "fail", (int)strlen(longcopy)+1, (int)outlen); char redo[128]; unsigned unpacked = lz4x_decode(out, outlen, redo, 128); printf("%d->%d %s\n", (int)outlen, (int)unpacked, redo); } #define main main__ #endif // LZ4X_DEMO //#line 1 "amalgamated_lzma.c" // LzFind.c -- Match finder for LZ algorithms 2009-04-22 : Igor Pavlov : Public domain // LzmaDec.c -- LZMA Decoder 2009-09-20 : Igor Pavlov : Public domain // LzmaEnc.c -- LZMA Encoder 2009-11-24 : Igor Pavlov : Public domain // Additional code by @r-lyeh, public domain. TOC: glue.h+lzfind.h/c+lzmaenc.h/c+lzmadec.h/c+glue.c unsigned lzma_encode(const void *in, unsigned inlen, void *out, unsigned outlen, unsigned flags); // [0..(7)..9] unsigned lzma_decode(const void *in, unsigned inlen, void *out, unsigned outlen); unsigned lzma_bounds(unsigned inlen, unsigned flags); unsigned lzma_excess(unsigned flags); #ifdef LZMA_C #pragma once // glue.h #ifndef LZMA_REALLOC #define LZMA_REALLOC REALLOC #endif #define LZMA_MALLOC(s) LZMA_REALLOC(0, s) #define LZMA_FREE(p) LZMA_REALLOC(p, 0) #define _FILE_OFFSET_BITS 64 #include <errno.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #ifndef max #define max(x,y) ((x) >= (y) ? (x) : (y)) #endif #ifndef min #define min(x,y) ((x) <= (y) ? (x) : (y)) #endif #ifdef _WIN32 //#include <io.h> #else //#include <unistd.h> #endif /* #define SHOW_STAT */ /* #define SHOW_STAT2 */ typedef int State; enum { min_dictionary_bits = 12, min_dictionary_size = 1 << min_dictionary_bits, max_dictionary_bits = 29, max_dictionary_size = 1 << max_dictionary_bits, max_dictionary_bits_c = 27, /* kDicLogSizeMaxCompress */ max_dictionary_size_c = 1 << max_dictionary_bits_c, literal_context_bits = 3, literal_pos_state_bits = 0, /* not used */ pos_state_bits = 2, len_low_bits = 3, len_mid_bits = 3, len_high_bits = 8, len_low_symbols = 1 << len_low_bits, len_mid_symbols = 1 << len_mid_bits, len_high_symbols = 1 << len_high_bits, max_len_symbols = len_low_symbols + len_mid_symbols + len_high_symbols, min_match_len = 2, /* must be 2 */ max_match_len = min_match_len + max_len_symbols - 1, /* 273 */ min_match_len_limit = 5 }; enum { SZ_OK = 0, SZ_ERROR_READ = 8, SZ_ERROR_WRITE = 9, }; // io interface static int readblock( const int fd, uint8_t *buf,int size ); static int writeblock( const int fd, const uint8_t *buf, int size ); /* LzFind.h -- Match finder for LZ algorithms 2009-04-22 : Igor Pavlov : Public domain */ typedef uint32_t CLzRef; typedef struct { uint8_t *bufferBase; uint8_t *buffer; CLzRef *hash; CLzRef *son; uint32_t pos; uint32_t posLimit; uint32_t streamPos; uint32_t lenLimit; uint32_t cyclicBufferPos; uint32_t cyclicBufferSize; /* it must be = (historySize + 1) */ uint32_t matchMaxLen; uint32_t hashMask; uint32_t cutValue; uint32_t blockSize; uint32_t keepSizeBefore; uint32_t keepSizeAfter; uint32_t numHashBytes; uint32_t historySize; uint32_t hashSizeSum; uint32_t numSons; int infd; int result; uint32_t crc; bool btMode; bool streamEndWasReached; } CMatchFinder; /* Conditions: historySize <= 3 GB keepAddBufferBefore + matchMaxLen + keepAddBufferAfter < 511MB */ int Mf_Init(CMatchFinder *p, const int ifd, const int mc, uint32_t historySize, uint32_t keepAddBufferBefore, uint32_t matchMaxLen, uint32_t keepAddBufferAfter); void Mf_Free(CMatchFinder *p); /* Conditions: Mf_GetNumAvailableBytes_Func must be called before each Mf_GetMatchLen_Func. Mf_GetPointerToCurrentPos_Func's result must be used only before any other function */ typedef uint32_t (*Mf_GetMatches_Func)(void *object, uint32_t *distances); typedef void (*Mf_Skip_Func)(void *object, uint32_t); typedef struct _IMatchFinder { Mf_GetMatches_Func GetMatches; Mf_Skip_Func Skip; } IMatchFinder; void Mf_CreateVTable(CMatchFinder *p, IMatchFinder *vTable); static inline uint32_t Mf_GetNumAvailableBytes(CMatchFinder *p) { return p->streamPos - p->pos; } static inline uint8_t Mf_GetIndexByte(CMatchFinder *p, int index) { return p->buffer[index]; } static inline uint8_t * Mf_GetPointerToCurrentPos(CMatchFinder *p) { return p->buffer; } /* LzFind.c -- Match finder for LZ algorithms 2009-04-22 : Igor Pavlov : Public domain */ static uint32_t crc32[256]; /* Table of CRCs of all 8-bit messages. */ static inline void CRC32_init(void) { for( unsigned n = 0; n < 256; ++n ) { unsigned c = n; for( int k = 0; k < 8; ++k ) { if( c & 1 ) c = 0xEDB88320U ^ ( c >> 1 ); else c >>= 1; } crc32[n] = c; } } static inline void CRC32_update_buf(uint32_t* const crc, const uint8_t* const buffer, const int size) { uint32_t c = *crc; for( int i = 0; i < size; ++i ) c = crc32[(c^buffer[i])&0xFF] ^ ( c >> 8 ); *crc = c; } #define kHash2Size (1 << 10) #define kHash3Size (1 << 16) #define kHash4Size (1 << 20) #define kFix3HashSize (kHash2Size) #define kFix4HashSize (kHash2Size + kHash3Size) #define HASH2_CALC hashValue = cur[0] | ((uint32_t)cur[1] << 8); #define HASH3_CALC { \ uint32_t temp = crc32[cur[0]] ^ cur[1]; \ hash2Value = temp & (kHash2Size - 1); \ hashValue = (temp ^ ((uint32_t)cur[2] << 8)) & p->hashMask; } #define HASH4_CALC { \ uint32_t temp = crc32[cur[0]] ^ cur[1]; \ hash2Value = temp & (kHash2Size - 1); \ hash3Value = (temp ^ ((uint32_t)cur[2] << 8)) & (kHash3Size - 1); \ hashValue = (temp ^ ((uint32_t)cur[2] << 8) ^ (crc32[cur[3]] << 5)) & p->hashMask; } #define kEmptyHashValue 0 #define kMaxValForNormalize ((uint32_t)0xFFFFFFFF) #define kNormalizeStepMin (1 << 10) /* it must be power of 2 */ #define kNormalizeMask (~(kNormalizeStepMin - 1)) #define kStartMaxLen 3 static void Mf_ReadBlock(CMatchFinder *p) { if (p->streamEndWasReached || p->result != SZ_OK) return; for (;;) { uint8_t * const dest = p->buffer + (p->streamPos - p->pos); const int size = (p->bufferBase + p->blockSize - dest); int rd; if (size == 0) return; rd = readblock( p->infd, dest, size ); if (rd != size && errno) { p->result = SZ_ERROR_READ; return; } if (rd == 0) { p->streamEndWasReached = true; return; } CRC32_update_buf( &p->crc, dest, rd ); p->streamPos += rd; if (p->streamPos - p->pos > p->keepSizeAfter) return; } } static void Mf_CheckAndMoveAndRead(CMatchFinder *p) { if ((uint32_t)(p->bufferBase + p->blockSize - p->buffer) <= p->keepSizeAfter) { memmove(p->bufferBase, p->buffer - p->keepSizeBefore, p->streamPos - p->pos + p->keepSizeBefore); p->buffer = p->bufferBase + p->keepSizeBefore; } Mf_ReadBlock(p); } void Mf_Free(CMatchFinder *p) { LZMA_FREE(p->hash); p->hash = 0; LZMA_FREE(p->bufferBase); p->bufferBase = 0; } static CLzRef* AllocRefs(uint32_t num) { uint32_t sizeInBytes = num * sizeof(CLzRef); if (sizeInBytes / sizeof(CLzRef) != num) return 0; return (CLzRef *)LZMA_MALLOC(sizeInBytes); } static void Mf_SetLimits(CMatchFinder *p) { uint32_t limit = kMaxValForNormalize - p->pos; uint32_t limit2 = p->cyclicBufferSize - p->cyclicBufferPos; if (limit2 < limit) limit = limit2; limit2 = p->streamPos - p->pos; if (limit2 <= p->keepSizeAfter) { if (limit2 > 0) limit2 = 1; } else limit2 -= p->keepSizeAfter; if (limit2 < limit) limit = limit2; { uint32_t lenLimit = p->streamPos - p->pos; if (lenLimit > p->matchMaxLen) lenLimit = p->matchMaxLen; p->lenLimit = lenLimit; } p->posLimit = p->pos + limit; } int Mf_Init(CMatchFinder *p, const int ifd, const int mc, uint32_t historySize, uint32_t keepAddBufferBefore, uint32_t matchMaxLen, uint32_t keepAddBufferAfter) { const uint32_t sizeReserv = ( historySize >> 1 ) + (keepAddBufferBefore + matchMaxLen + keepAddBufferAfter) / 2 + (1 << 19); p->hash = 0; p->cutValue = mc; p->infd = ifd; p->btMode = true; p->numHashBytes = 4; p->crc = 0xFFFFFFFFU; p->keepSizeBefore = historySize + keepAddBufferBefore + 1; p->keepSizeAfter = matchMaxLen + keepAddBufferAfter; /* we need one additional byte, since we use MoveBlock after pos++ and before dictionary using */ /* keepSizeBefore + keepSizeAfter + sizeReserv must be < 4G) */ p->blockSize = p->keepSizeBefore + p->keepSizeAfter + sizeReserv; p->buffer = p->bufferBase = (uint8_t *)LZMA_MALLOC(p->blockSize); if( p->bufferBase ) { uint32_t newCyclicBufferSize = historySize + 1; uint32_t hs; p->matchMaxLen = matchMaxLen; { if (p->numHashBytes == 2) hs = (1 << 16) - 1; else { hs = historySize - 1; hs |= (hs >> 1); hs |= (hs >> 2); hs |= (hs >> 4); hs |= (hs >> 8); hs >>= 1; hs |= 0xFFFF; /* don't change it! It's required for Deflate */ if (hs > (1 << 24)) { if (p->numHashBytes == 3) hs = (1 << 24) - 1; else hs >>= 1; } } p->hashMask = hs; hs++; if (p->numHashBytes > 2) hs += kHash2Size; if (p->numHashBytes > 3) hs += kHash3Size; if (p->numHashBytes > 4) hs += kHash4Size; } { uint32_t newSize; p->historySize = historySize; p->hashSizeSum = hs; p->cyclicBufferSize = newCyclicBufferSize; p->numSons = (p->btMode ? newCyclicBufferSize * 2 : newCyclicBufferSize); newSize = p->hashSizeSum + p->numSons; p->hash = AllocRefs(newSize); if (p->hash != 0) { uint32_t i; p->son = p->hash + p->hashSizeSum; for (i = 0; i < p->hashSizeSum; i++) p->hash[i] = kEmptyHashValue; p->cyclicBufferPos = 0; p->pos = p->streamPos = p->cyclicBufferSize; p->result = SZ_OK; p->streamEndWasReached = false; Mf_ReadBlock(p); Mf_SetLimits(p); return 1; } } } Mf_Free(p); return 0; } static void Mf_Normalize3(uint32_t subValue, CLzRef *items, uint32_t numItems) { uint32_t i; for (i = 0; i < numItems; i++) { uint32_t value = items[i]; if (value <= subValue) value = kEmptyHashValue; else value -= subValue; items[i] = value; } } static void Mf_Normalize(CMatchFinder *p) { uint32_t subValue = (p->pos - p->historySize - 1) & kNormalizeMask; Mf_Normalize3(subValue, p->hash, p->hashSizeSum + p->numSons); p->posLimit -= subValue; p->pos -= subValue; p->streamPos -= subValue; } static void Mf_CheckLimits(CMatchFinder *p) { if (p->pos == kMaxValForNormalize) Mf_Normalize(p); if (!p->streamEndWasReached && p->keepSizeAfter == p->streamPos - p->pos) Mf_CheckAndMoveAndRead(p); if (p->cyclicBufferPos == p->cyclicBufferSize) p->cyclicBufferPos = 0; Mf_SetLimits(p); } static uint32_t * Hc_GetMatchesSpec(uint32_t lenLimit, uint32_t curMatch, uint32_t pos, const uint8_t *cur, CLzRef *son, uint32_t _cyclicBufferPos, uint32_t _cyclicBufferSize, uint32_t cutValue, uint32_t *distances, uint32_t maxLen) { son[_cyclicBufferPos] = curMatch; for (;;) { uint32_t delta = pos - curMatch; if (cutValue-- == 0 || delta >= _cyclicBufferSize) return distances; { const uint8_t *pb = cur - delta; curMatch = son[_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)]; if (pb[maxLen] == cur[maxLen] && *pb == *cur) { uint32_t len = 0; while (++len != lenLimit) if (pb[len] != cur[len]) break; if (maxLen < len) { *distances++ = maxLen = len; *distances++ = delta - 1; if (len == lenLimit) return distances; } } } } } static uint32_t * GetMatchesSpec1( uint32_t lenLimit, uint32_t curMatch, uint32_t pos, const uint8_t *cur, CLzRef *son, uint32_t _cyclicBufferPos, uint32_t _cyclicBufferSize, uint32_t cutValue, uint32_t *distances, uint32_t maxLen ) { CLzRef *ptr0 = son + (_cyclicBufferPos << 1) + 1; CLzRef *ptr1 = son + (_cyclicBufferPos << 1); uint32_t len0 = 0, len1 = 0; for (;;) { uint32_t delta = pos - curMatch; if (cutValue-- == 0 || delta >= _cyclicBufferSize) { *ptr0 = *ptr1 = kEmptyHashValue; return distances; } { CLzRef *pair = son + ((_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1); const uint8_t *pb = cur - delta; uint32_t len = (len0 < len1 ? len0 : len1); if (pb[len] == cur[len]) { if (++len != lenLimit && pb[len] == cur[len]) while (++len != lenLimit) if (pb[len] != cur[len]) break; if (maxLen < len) { *distances++ = maxLen = len; *distances++ = delta - 1; if (len == lenLimit) { *ptr1 = pair[0]; *ptr0 = pair[1]; return distances; } } } if (pb[len] < cur[len]) { *ptr1 = curMatch; ptr1 = pair + 1; curMatch = *ptr1; len1 = len; } else { *ptr0 = curMatch; ptr0 = pair; curMatch = *ptr0; len0 = len; } } } } static void SkipMatchesSpec(uint32_t lenLimit, uint32_t curMatch, uint32_t pos, const uint8_t *cur, CLzRef *son, uint32_t _cyclicBufferPos, uint32_t _cyclicBufferSize, uint32_t cutValue) { CLzRef *ptr0 = son + (_cyclicBufferPos << 1) + 1; CLzRef *ptr1 = son + (_cyclicBufferPos << 1); uint32_t len0 = 0, len1 = 0; for (;;) { uint32_t delta = pos - curMatch; if (cutValue-- == 0 || delta >= _cyclicBufferSize) { *ptr0 = *ptr1 = kEmptyHashValue; return; } { CLzRef *pair = son + ((_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1); const uint8_t *pb = cur - delta; uint32_t len = (len0 < len1 ? len0 : len1); if (pb[len] == cur[len]) { while (++len != lenLimit) if (pb[len] != cur[len]) break; { if (len == lenLimit) { *ptr1 = pair[0]; *ptr0 = pair[1]; return; } } } if (pb[len] < cur[len]) { *ptr1 = curMatch; ptr1 = pair + 1; curMatch = *ptr1; len1 = len; } else { *ptr0 = curMatch; ptr0 = pair; curMatch = *ptr0; len0 = len; } } } } #define MOVE_POS \ ++p->cyclicBufferPos; \ p->buffer++; \ if (++p->pos == p->posLimit) Mf_CheckLimits(p); #define MOVE_POS_RET MOVE_POS return offset; static void Mf_MovePos(CMatchFinder *p) { MOVE_POS; } #define GET_MATCHES_HEADER2(minLen, ret_op) \ uint32_t lenLimit; uint32_t hashValue; const uint8_t *cur; uint32_t curMatch; \ lenLimit = p->lenLimit; { if (lenLimit < minLen) { Mf_MovePos(p); ret_op; }} \ cur = p->buffer; #define GET_MATCHES_HEADER(minLen) GET_MATCHES_HEADER2(minLen, return 0) #define SKIP_HEADER(minLen) GET_MATCHES_HEADER2(minLen, continue) #define MF_PARAMS(p) p->pos, p->buffer, p->son, p->cyclicBufferPos, p->cyclicBufferSize, p->cutValue #define GET_MATCHES_FOOTER(offset, maxLen) \ offset = (uint32_t)(GetMatchesSpec1(lenLimit, curMatch, MF_PARAMS(p), \ distances + offset, maxLen) - distances); MOVE_POS_RET; #define SKIP_FOOTER \ SkipMatchesSpec(lenLimit, curMatch, MF_PARAMS(p)); MOVE_POS; static uint32_t Bt2_MatchFinder_GetMatches(CMatchFinder *p, uint32_t *distances) { uint32_t offset; GET_MATCHES_HEADER(2) HASH2_CALC; curMatch = p->hash[hashValue]; p->hash[hashValue] = p->pos; offset = 0; GET_MATCHES_FOOTER(offset, 1) } static uint32_t Bt3_MatchFinder_GetMatches(CMatchFinder *p, uint32_t *distances) { uint32_t hash2Value, delta2, maxLen, offset; GET_MATCHES_HEADER(3) HASH3_CALC; delta2 = p->pos - p->hash[hash2Value]; curMatch = p->hash[kFix3HashSize + hashValue]; p->hash[hash2Value] = p->hash[kFix3HashSize + hashValue] = p->pos; maxLen = 2; offset = 0; if (delta2 < p->cyclicBufferSize && *(cur - delta2) == *cur) { for (; maxLen != lenLimit; maxLen++) if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen]) break; distances[0] = maxLen; distances[1] = delta2 - 1; offset = 2; if (maxLen == lenLimit) { SkipMatchesSpec(lenLimit, curMatch, MF_PARAMS(p)); MOVE_POS_RET; } } GET_MATCHES_FOOTER(offset, maxLen) } static uint32_t Bt4_MatchFinder_GetMatches(CMatchFinder *p, uint32_t *distances) { uint32_t hash2Value, hash3Value, delta2, delta3, maxLen, offset; GET_MATCHES_HEADER(4) HASH4_CALC; delta2 = p->pos - p->hash[ hash2Value]; delta3 = p->pos - p->hash[kFix3HashSize + hash3Value]; curMatch = p->hash[kFix4HashSize + hashValue]; p->hash[ hash2Value] = p->hash[kFix3HashSize + hash3Value] = p->hash[kFix4HashSize + hashValue] = p->pos; maxLen = 1; offset = 0; if (delta2 < p->cyclicBufferSize && *(cur - delta2) == *cur) { distances[0] = maxLen = 2; distances[1] = delta2 - 1; offset = 2; } if (delta2 != delta3 && delta3 < p->cyclicBufferSize && *(cur - delta3) == *cur) { maxLen = 3; distances[offset + 1] = delta3 - 1; offset += 2; delta2 = delta3; } if (offset != 0) { for (; maxLen != lenLimit; maxLen++) if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen]) break; distances[offset - 2] = maxLen; if (maxLen == lenLimit) { SkipMatchesSpec(lenLimit, curMatch, MF_PARAMS(p)); MOVE_POS_RET; } } if (maxLen < 3) maxLen = 3; GET_MATCHES_FOOTER(offset, maxLen) } static uint32_t Hc4_MatchFinder_GetMatches(CMatchFinder *p, uint32_t *distances) { uint32_t hash2Value, hash3Value, delta2, delta3, maxLen, offset; GET_MATCHES_HEADER(4) HASH4_CALC; delta2 = p->pos - p->hash[ hash2Value]; delta3 = p->pos - p->hash[kFix3HashSize + hash3Value]; curMatch = p->hash[kFix4HashSize + hashValue]; p->hash[ hash2Value] = p->hash[kFix3HashSize + hash3Value] = p->hash[kFix4HashSize + hashValue] = p->pos; maxLen = 1; offset = 0; if (delta2 < p->cyclicBufferSize && *(cur - delta2) == *cur) { distances[0] = maxLen = 2; distances[1] = delta2 - 1; offset = 2; } if (delta2 != delta3 && delta3 < p->cyclicBufferSize && *(cur - delta3) == *cur) { maxLen = 3; distances[offset + 1] = delta3 - 1; offset += 2; delta2 = delta3; } if (offset != 0) { for (; maxLen != lenLimit; maxLen++) if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen]) break; distances[offset - 2] = maxLen; if (maxLen == lenLimit) { p->son[p->cyclicBufferPos] = curMatch; MOVE_POS_RET; } } if (maxLen < 3) maxLen = 3; offset = (uint32_t)(Hc_GetMatchesSpec(lenLimit, curMatch, MF_PARAMS(p), distances + offset, maxLen) - (distances)); MOVE_POS_RET } static void Bt2_MatchFinder_Skip(CMatchFinder *p, uint32_t num) { do { SKIP_HEADER(2) HASH2_CALC; curMatch = p->hash[hashValue]; p->hash[hashValue] = p->pos; SKIP_FOOTER } while (--num != 0); } static void Bt3_MatchFinder_Skip(CMatchFinder *p, uint32_t num) { do { uint32_t hash2Value; SKIP_HEADER(3) HASH3_CALC; curMatch = p->hash[kFix3HashSize + hashValue]; p->hash[hash2Value] = p->hash[kFix3HashSize + hashValue] = p->pos; SKIP_FOOTER } while (--num != 0); } static void Bt4_MatchFinder_Skip(CMatchFinder *p, uint32_t num) { do { uint32_t hash2Value, hash3Value; SKIP_HEADER(4) HASH4_CALC; curMatch = p->hash[kFix4HashSize + hashValue]; p->hash[ hash2Value] = p->hash[kFix3HashSize + hash3Value] = p->pos; p->hash[kFix4HashSize + hashValue] = p->pos; SKIP_FOOTER } while (--num != 0); } static void Hc4_MatchFinder_Skip(CMatchFinder *p, uint32_t num) { do { uint32_t hash2Value, hash3Value; SKIP_HEADER(4) HASH4_CALC; curMatch = p->hash[kFix4HashSize + hashValue]; p->hash[ hash2Value] = p->hash[kFix3HashSize + hash3Value] = p->hash[kFix4HashSize + hashValue] = p->pos; p->son[p->cyclicBufferPos] = curMatch; MOVE_POS } while (--num != 0); } void Mf_CreateVTable(CMatchFinder *p, IMatchFinder *vTable) { if (!p->btMode) { vTable->GetMatches = (Mf_GetMatches_Func)Hc4_MatchFinder_GetMatches; vTable->Skip = (Mf_Skip_Func)Hc4_MatchFinder_Skip; } else if (p->numHashBytes == 2) { vTable->GetMatches = (Mf_GetMatches_Func)Bt2_MatchFinder_GetMatches; vTable->Skip = (Mf_Skip_Func)Bt2_MatchFinder_Skip; } else if (p->numHashBytes == 3) { vTable->GetMatches = (Mf_GetMatches_Func)Bt3_MatchFinder_GetMatches; vTable->Skip = (Mf_Skip_Func)Bt3_MatchFinder_Skip; } else { vTable->GetMatches = (Mf_GetMatches_Func)Bt4_MatchFinder_GetMatches; vTable->Skip = (Mf_Skip_Func)Bt4_MatchFinder_Skip; } } /* LzmaEnc.h -- LZMA Encoder 2009-02-07 : Igor Pavlov : Public domain */ /* ---------- CLzmaEncHandle Interface ---------- */ /* LzmaEnc_* functions can return the following exit codes: Returns: SZ_OK - OK SZ_ERROR_WRITE - Write callback error. */ typedef void * CLzmaEncHandle; CLzmaEncHandle LzmaEnc_Init( const int dict_size, const int match_len_limit, const int infd, const int outfd ); void LzmaEnc_Free(CLzmaEncHandle p); int LzmaEnc_Encode(CLzmaEncHandle p); /* LzmaEnc.c -- LZMA Encoder 2009-11-24 : Igor Pavlov : Public domain */ #ifdef SHOW_STAT static int ttt = 0; #endif static int verbosity = 0; enum { Fh_size = 6, // file header size Ft_size = 20, // file trailer size /* 0-3 CRC32 of the uncompressed data */ /* 4-11 size of the uncompressed data */ /* 12-19 member size including header and trailer */ }; typedef uint8_t File_trailer[Ft_size]; static inline void Ft_set_data_crc( File_trailer data, unsigned crc ) { for( int i = 0; i <= 3; ++i ) { data[i] = (uint8_t)crc; crc >>= 8; } } static inline void Ft_set_data_size( File_trailer data, unsigned long long sz ) { for( int i = 4; i <= 11; ++i ) { data[i] = (uint8_t)sz; sz >>= 8; } } static inline void Ft_set_member_size( File_trailer data, unsigned long long sz ) { for( int i = 12; i <= 19; ++i ) { data[i] = (uint8_t)sz; sz >>= 8; } } #define kNumTopBits 24 #define kTopValue ((uint32_t)1 << kNumTopBits) #define kNumBitModelTotalBits 11 #define kBitModelTotal (1 << kNumBitModelTotalBits) #define kNumMoveBits 5 #define kProbInitValue (kBitModelTotal >> 1) #define kNumMoveReducingBits 4 #define kNumBitPriceShiftBits 4 #define kNumLogBits (9 + (int)sizeof(uint32_t) / 2) #define kDicLogSizeMaxCompress ((kNumLogBits - 1) * 2 + 7) static void LzmaEnc_FastPosInit(uint8_t *g_FastPos) { int c = 2, slotFast; g_FastPos[0] = 0; g_FastPos[1] = 1; for (slotFast = 2; slotFast < kNumLogBits * 2; slotFast++) { uint32_t k = (1 << ((slotFast >> 1) - 1)); uint32_t j; for (j = 0; j < k; j++, c++) g_FastPos[c] = (uint8_t)slotFast; } } #define BSR2_RET(pos, res) { uint32_t i = 6 + ((kNumLogBits - 1) & \ (0 - (((((uint32_t)1 << (kNumLogBits + 6)) - 1) - pos) >> 31))); \ res = p->g_FastPos[pos >> i] + (i * 2); } /* #define BSR2_RET(pos, res) { res = (pos < (1 << (kNumLogBits + 6))) ? \ p->g_FastPos[pos >> 6] + 12 : \ p->g_FastPos[pos >> (6 + kNumLogBits - 1)] + (6 + (kNumLogBits - 1)) * 2; } */ #define GetPosSlot1(pos) p->g_FastPos[pos] #define GetPosSlot2(pos, res) { BSR2_RET(pos, res); } #define GetPosSlot(pos, res) { if (pos < kNumFullDistances) res = p->g_FastPos[pos]; else BSR2_RET(pos, res); } #define LZMA_NUM_REPS 4 typedef struct { uint32_t price; State state; uint32_t posPrev2; uint32_t backPrev2; uint32_t posPrev; uint32_t backPrev; uint32_t backs[LZMA_NUM_REPS]; bool prev1IsChar; bool prev2; } COptimal; #define kNumOpts (1 << 12) #define kNumLenToPosStates 4 #define kNumPosSlotBits 6 #define kDicLogSizeMin 0 #define kDicLogSizeMax 32 #define kDistTableSizeMax (kDicLogSizeMax * 2) #define kNumAlignBits 4 #define kAlignTableSize (1 << kNumAlignBits) #define kAlignMask (kAlignTableSize - 1) #define kStartPosModelIndex 4 #define kEndPosModelIndex 14 #define kNumPosModels (kEndPosModelIndex - kStartPosModelIndex) #define kNumFullDistances (1 << (kEndPosModelIndex >> 1)) #define LZMA_LC_MAX 8 #define LZMA_LP_MAX 4 #define LZMA_PB_MAX 4 #define LZMA_NUM_PB_STATES_MAX (1 << LZMA_PB_MAX) #define kLenNumLowBits 3 #define kLenNumLowSymbols (1 << kLenNumLowBits) #define kLenNumMidBits 3 #define kLenNumMidSymbols (1 << kLenNumMidBits) #define kLenNumHighBits 8 #define kLenNumHighSymbols (1 << kLenNumHighBits) #define kLenNumSymbolsTotal (kLenNumLowSymbols + kLenNumMidSymbols + kLenNumHighSymbols) #define LZMA_MATCH_LEN_MIN 2 #define LZMA_MATCH_LEN_MAX (LZMA_MATCH_LEN_MIN + kLenNumSymbolsTotal - 1) #define kNumStates 12 typedef struct { int choice; int choice2; int low[LZMA_NUM_PB_STATES_MAX << kLenNumLowBits]; int mid[LZMA_NUM_PB_STATES_MAX << kLenNumMidBits]; int high[kLenNumHighSymbols]; } CLenEnc; typedef struct { CLenEnc p; uint32_t prices[LZMA_NUM_PB_STATES_MAX][kLenNumSymbolsTotal]; uint32_t tableSize; uint32_t counters[LZMA_NUM_PB_STATES_MAX]; } CLenPriceEnc; typedef struct { uint64_t low; uint64_t processed; uint8_t *bufBase; uint8_t *buf; uint8_t *bufLim; uint32_t range; uint32_t cacheSize; int outfd; int res; uint8_t cache; } CRangeEnc; typedef struct { uint64_t nowPos64; int *litProbs; IMatchFinder matchFinder; CMatchFinder matchFinderBase; uint32_t optimumEndIndex; uint32_t optimumCurrentIndex; uint32_t longestMatchLength; uint32_t numPairs; uint32_t numAvail; COptimal opt[kNumOpts]; uint8_t g_FastPos[1 << kNumLogBits]; uint32_t ProbPrices[kBitModelTotal >> kNumMoveReducingBits]; uint32_t matches[LZMA_MATCH_LEN_MAX * 2 + 2 + 1]; uint32_t numFastBytes; uint32_t additionalOffset; uint32_t reps[LZMA_NUM_REPS]; State state; uint32_t posSlotPrices[kNumLenToPosStates][kDistTableSizeMax]; uint32_t distancesPrices[kNumLenToPosStates][kNumFullDistances]; uint32_t alignPrices[kAlignTableSize]; uint32_t alignPriceCount; uint32_t distTableSize; unsigned lc, lp, pb; unsigned lpMask, pbMask; int isMatch[kNumStates][LZMA_NUM_PB_STATES_MAX]; int isRep[kNumStates]; int isRepG0[kNumStates]; int isRepG1[kNumStates]; int isRepG2[kNumStates]; int isRep0Long[kNumStates][LZMA_NUM_PB_STATES_MAX]; int posSlotEncoder[kNumLenToPosStates][1 << kNumPosSlotBits]; int posEncoders[kNumFullDistances - kEndPosModelIndex]; int posAlignEncoder[1 << kNumAlignBits]; CLenPriceEnc lenEnc; CLenPriceEnc repLenEnc; CRangeEnc rc; uint32_t matchPriceCount; int result; uint32_t dictSize; bool fastMode; bool finished; } CLzmaEnc; static const int kLiteralNextStates[kNumStates] = {0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 4, 5}; static const int kMatchNextStates[kNumStates] = {7, 7, 7, 7, 7, 7, 7, 10, 10, 10, 10, 10}; static const int kRepNextStates[kNumStates] = {8, 8, 8, 8, 8, 8, 8, 11, 11, 11, 11, 11}; static const int kShortRepNextStates[kNumStates]= {9, 9, 9, 9, 9, 9, 9, 11, 11, 11, 11, 11}; #define IsCharState(s) ((s) < 7) #define GetLenToPosState(len) (((len) < kNumLenToPosStates + 1) ? (len) - 2 : kNumLenToPosStates - 1) #define kInfinityPrice (1 << 30) #define RC_BUF_SIZE (1 << 16) static int RangeEnc_Init( CRangeEnc *p, const int outfd ) { p->low = 0; p->processed = 0; p->range = 0xFFFFFFFF; p->cacheSize = 1; p->outfd = outfd; p->res = SZ_OK; p->cache = 0; p->buf = p->bufBase = (uint8_t *)LZMA_MALLOC( RC_BUF_SIZE ); if( !p->bufBase ) return 0; p->bufLim = p->bufBase + RC_BUF_SIZE; return 1; } static void RangeEnc_Free(CRangeEnc *p) { LZMA_FREE(p->bufBase); p->bufBase = 0; } static void RangeEnc_FlushStream(CRangeEnc *p) { int num; if (p->res != SZ_OK) return; num = p->buf - p->bufBase; if (num != writeblock(p->outfd, p->bufBase, num)) p->res = SZ_ERROR_WRITE; p->processed += num; p->buf = p->bufBase; } static void RangeEnc_ShiftLow(CRangeEnc *p) { if ((uint32_t)p->low < (uint32_t)0xFF000000 || (int)(p->low >> 32) != 0) { uint8_t temp = p->cache; do { uint8_t *buf = p->buf; *buf++ = (uint8_t)(temp + (uint8_t)(p->low >> 32)); p->buf = buf; if (buf == p->bufLim) RangeEnc_FlushStream(p); temp = 0xFF; } while (--p->cacheSize != 0); p->cache = (uint8_t)((uint32_t)p->low >> 24); } p->cacheSize++; p->low = (uint32_t)p->low << 8; } static void RangeEnc_FlushData(CRangeEnc *p) { int i; for (i = 0; i < 5; i++) RangeEnc_ShiftLow(p); } static void RangeEnc_EncodeDirectBits(CRangeEnc *p, uint32_t value, int numBits) { do { p->range >>= 1; p->low += p->range & (0 - ((value >> --numBits) & 1)); if (p->range < kTopValue) { p->range <<= 8; RangeEnc_ShiftLow(p); } } while (numBits != 0); } static void RangeEnc_EncodeBit(CRangeEnc *p, int *prob, uint32_t symbol) { uint32_t ttt = *prob; uint32_t newBound = (p->range >> kNumBitModelTotalBits) * ttt; if (symbol == 0) { p->range = newBound; ttt += (kBitModelTotal - ttt) >> kNumMoveBits; } else { p->low += newBound; p->range -= newBound; ttt -= ttt >> kNumMoveBits; } *prob = (int)ttt; if (p->range < kTopValue) { p->range <<= 8; RangeEnc_ShiftLow(p); } } static void LitEnc_Encode(CRangeEnc *p, int *probs, uint32_t symbol) { symbol |= 0x100; do { RangeEnc_EncodeBit(p, probs + (symbol >> 8), (symbol >> 7) & 1); symbol <<= 1; } while (symbol < 0x10000); } static void LitEnc_EncodeMatched(CRangeEnc *p, int *probs, uint32_t symbol, uint32_t matchByte) { uint32_t offs = 0x100; symbol |= 0x100; do { matchByte <<= 1; RangeEnc_EncodeBit(p, probs + (offs + (matchByte & offs) + (symbol >> 8)), (symbol >> 7) & 1); symbol <<= 1; offs &= ~(matchByte ^ symbol); } while (symbol < 0x10000); } static void LzmaEnc_InitPriceTables(uint32_t *ProbPrices) { uint32_t i; for (i = (1 << kNumMoveReducingBits) / 2; i < kBitModelTotal; i += (1 << kNumMoveReducingBits)) { const int kCyclesBits = kNumBitPriceShiftBits; uint32_t w = i; uint32_t bitCount = 0; int j; for (j = 0; j < kCyclesBits; j++) { w = w * w; bitCount <<= 1; while (w >= ((uint32_t)1 << 16)) { w >>= 1; bitCount++; } } ProbPrices[i >> kNumMoveReducingBits] = ((kNumBitModelTotalBits << kCyclesBits) - 15 - bitCount); } } #define GET_PRICE(prob, symbol) \ p->ProbPrices[((prob) ^ (((-(int)(symbol))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits]; #define GET_PRICEa(prob, symbol) \ ProbPrices[((prob) ^ ((-((int)(symbol))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits]; #define GET_PRICE_0(prob) p->ProbPrices[(prob) >> kNumMoveReducingBits] #define GET_PRICE_1(prob) p->ProbPrices[((prob) ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits] #define GET_PRICE_0a(prob) ProbPrices[(prob) >> kNumMoveReducingBits] #define GET_PRICE_1a(prob) ProbPrices[((prob) ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits] static uint32_t LitEnc_GetPrice(const int *probs, uint32_t symbol, uint32_t *ProbPrices) { uint32_t price = 0; symbol |= 0x100; do { price += GET_PRICEa(probs[symbol >> 8], (symbol >> 7) & 1); symbol <<= 1; } while (symbol < 0x10000); return price; } static uint32_t LitEnc_GetPriceMatched(const int *probs, uint32_t symbol, uint32_t matchByte, uint32_t *ProbPrices) { uint32_t price = 0; uint32_t offs = 0x100; symbol |= 0x100; do { matchByte <<= 1; price += GET_PRICEa(probs[offs + (matchByte & offs) + (symbol >> 8)], (symbol >> 7) & 1); symbol <<= 1; offs &= ~(matchByte ^ symbol); } while (symbol < 0x10000); return price; } static void RcTree_Encode(CRangeEnc *rc, int *probs, int numBitLevels, uint32_t symbol) { uint32_t m = 1; int i; for (i = numBitLevels; i != 0;) { uint32_t bit; i--; bit = (symbol >> i) & 1; RangeEnc_EncodeBit(rc, probs + m, bit); m = (m << 1) | bit; } } static void RcTree_ReverseEncode(CRangeEnc *rc, int *probs, int numBitLevels, uint32_t symbol) { uint32_t m = 1; int i; for (i = 0; i < numBitLevels; i++) { uint32_t bit = symbol & 1; RangeEnc_EncodeBit(rc, probs + m, bit); m = (m << 1) | bit; symbol >>= 1; } } static uint32_t RcTree_GetPrice(const int *probs, int numBitLevels, uint32_t symbol, uint32_t *ProbPrices) { uint32_t price = 0; symbol |= (1 << numBitLevels); while (symbol != 1) { price += GET_PRICEa(probs[symbol >> 1], symbol & 1); symbol >>= 1; } return price; } static uint32_t RcTree_ReverseGetPrice(const int *probs, int numBitLevels, uint32_t symbol, uint32_t *ProbPrices) { uint32_t price = 0; uint32_t m = 1; int i; for (i = numBitLevels; i != 0; i--) { uint32_t bit = symbol & 1; symbol >>= 1; price += GET_PRICEa(probs[m], bit); m = (m << 1) | bit; } return price; } static void LenEnc_Init(CLenEnc *p) { unsigned i; p->choice = p->choice2 = kProbInitValue; for (i = 0; i < (LZMA_NUM_PB_STATES_MAX << kLenNumLowBits); i++) p->low[i] = kProbInitValue; for (i = 0; i < (LZMA_NUM_PB_STATES_MAX << kLenNumMidBits); i++) p->mid[i] = kProbInitValue; for (i = 0; i < kLenNumHighSymbols; i++) p->high[i] = kProbInitValue; } static void LenEnc_Encode(CLenEnc *p, CRangeEnc *rc, uint32_t symbol, uint32_t posState) { if (symbol < kLenNumLowSymbols) { RangeEnc_EncodeBit(rc, &p->choice, 0); RcTree_Encode(rc, p->low + (posState << kLenNumLowBits), kLenNumLowBits, symbol); } else { RangeEnc_EncodeBit(rc, &p->choice, 1); if (symbol < kLenNumLowSymbols + kLenNumMidSymbols) { RangeEnc_EncodeBit(rc, &p->choice2, 0); RcTree_Encode(rc, p->mid + (posState << kLenNumMidBits), kLenNumMidBits, symbol - kLenNumLowSymbols); } else { RangeEnc_EncodeBit(rc, &p->choice2, 1); RcTree_Encode(rc, p->high, kLenNumHighBits, symbol - kLenNumLowSymbols - kLenNumMidSymbols); } } } static void LenEnc_SetPrices(CLenEnc *p, uint32_t posState, uint32_t numSymbols, uint32_t *prices, uint32_t *ProbPrices) { uint32_t a0 = GET_PRICE_0a(p->choice); uint32_t a1 = GET_PRICE_1a(p->choice); uint32_t b0 = a1 + GET_PRICE_0a(p->choice2); uint32_t b1 = a1 + GET_PRICE_1a(p->choice2); uint32_t i = 0; for (i = 0; i < kLenNumLowSymbols; i++) { if (i >= numSymbols) return; prices[i] = a0 + RcTree_GetPrice(p->low + (posState << kLenNumLowBits), kLenNumLowBits, i, ProbPrices); } for (; i < kLenNumLowSymbols + kLenNumMidSymbols; i++) { if (i >= numSymbols) return; prices[i] = b0 + RcTree_GetPrice(p->mid + (posState << kLenNumMidBits), kLenNumMidBits, i - kLenNumLowSymbols, ProbPrices); } for (; i < numSymbols; i++) prices[i] = b1 + RcTree_GetPrice(p->high, kLenNumHighBits, i - kLenNumLowSymbols - kLenNumMidSymbols, ProbPrices); } static void LenPriceEnc_UpdateTable(CLenPriceEnc *p, uint32_t posState, uint32_t *ProbPrices) { LenEnc_SetPrices(&p->p, posState, p->tableSize, p->prices[posState], ProbPrices); p->counters[posState] = p->tableSize; } static void LenPriceEnc_UpdateTables(CLenPriceEnc *p, uint32_t numPosStates, uint32_t *ProbPrices) { uint32_t posState; for (posState = 0; posState < numPosStates; posState++) LenPriceEnc_UpdateTable(p, posState, ProbPrices); } static void LenEnc_Encode2(CLenPriceEnc *p, CRangeEnc *rc, uint32_t symbol, uint32_t posState, bool updatePrice, uint32_t *ProbPrices) { LenEnc_Encode(&p->p, rc, symbol, posState); if (updatePrice) if (--p->counters[posState] == 0) LenPriceEnc_UpdateTable(p, posState, ProbPrices); } static void MovePos(CLzmaEnc *p, uint32_t num) { #ifdef SHOW_STAT ttt += num; printf("\n MovePos %d", num); #endif if (num != 0) { p->additionalOffset += num; p->matchFinder.Skip(&p->matchFinderBase, num); } } static uint32_t ReadMatchDistances(CLzmaEnc *p, uint32_t *numDistancePairsRes) { uint32_t lenRes = 0, numPairs; p->numAvail = Mf_GetNumAvailableBytes(&p->matchFinderBase); numPairs = p->matchFinder.GetMatches(&p->matchFinderBase, p->matches); #ifdef SHOW_STAT printf("\n i = %d numPairs = %d ", ttt, numPairs / 2); ttt++; { uint32_t i; for (i = 0; i < numPairs; i += 2) printf("%2d %6d | ", p->matches[i], p->matches[i + 1]); } #endif if (numPairs > 0) { lenRes = p->matches[numPairs - 2]; if (lenRes == p->numFastBytes) { const uint8_t *pby = Mf_GetPointerToCurrentPos(&p->matchFinderBase) - 1; uint32_t distance = p->matches[numPairs - 1] + 1; uint32_t numAvail = p->numAvail; if (numAvail > LZMA_MATCH_LEN_MAX) numAvail = LZMA_MATCH_LEN_MAX; { const uint8_t *pby2 = pby - distance; for (; lenRes < numAvail && pby[lenRes] == pby2[lenRes]; lenRes++) ; } } } p->additionalOffset++; *numDistancePairsRes = numPairs; return lenRes; } #define MakeAsChar(p) (p)->backPrev = (uint32_t)(-1); (p)->prev1IsChar = false; #define MakeAsShortRep(p) (p)->backPrev = 0; (p)->prev1IsChar = false; #define IsShortRep(p) ((p)->backPrev == 0) static uint32_t GetRepLen1Price(CLzmaEnc *p, State state, uint32_t posState) { return GET_PRICE_0(p->isRepG0[state]) + GET_PRICE_0(p->isRep0Long[state][posState]); } static uint32_t GetPureRepPrice(CLzmaEnc *p, uint32_t repIndex, State state, uint32_t posState) { uint32_t price; if (repIndex == 0) { price = GET_PRICE_0(p->isRepG0[state]); price += GET_PRICE_1(p->isRep0Long[state][posState]); } else { price = GET_PRICE_1(p->isRepG0[state]); if (repIndex == 1) price += GET_PRICE_0(p->isRepG1[state]); else { price += GET_PRICE_1(p->isRepG1[state]); price += GET_PRICE(p->isRepG2[state], repIndex - 2); } } return price; } static uint32_t GetRepPrice(CLzmaEnc *p, uint32_t repIndex, uint32_t len, State state, uint32_t posState) { return p->repLenEnc.prices[posState][len - LZMA_MATCH_LEN_MIN] + GetPureRepPrice(p, repIndex, state, posState); } static uint32_t Backward(CLzmaEnc *p, uint32_t *backRes, uint32_t cur) { uint32_t posMem = p->opt[cur].posPrev; uint32_t backMem = p->opt[cur].backPrev; p->optimumEndIndex = cur; do { if (p->opt[cur].prev1IsChar) { MakeAsChar(&p->opt[posMem]) p->opt[posMem].posPrev = posMem - 1; if (p->opt[cur].prev2) { p->opt[posMem - 1].prev1IsChar = false; p->opt[posMem - 1].posPrev = p->opt[cur].posPrev2; p->opt[posMem - 1].backPrev = p->opt[cur].backPrev2; } } { uint32_t posPrev = posMem; uint32_t backCur = backMem; backMem = p->opt[posPrev].backPrev; posMem = p->opt[posPrev].posPrev; p->opt[posPrev].backPrev = backCur; p->opt[posPrev].posPrev = cur; cur = posPrev; } } while (cur != 0); *backRes = p->opt[0].backPrev; p->optimumCurrentIndex = p->opt[0].posPrev; return p->optimumCurrentIndex; } #define LIT_PROBS(pos, prevByte) (p->litProbs + ((((pos) & p->lpMask) << p->lc) + ((prevByte) >> (8 - p->lc))) * 0x300) static uint32_t GetOptimum(CLzmaEnc *p, uint32_t position, uint32_t *backRes) { uint32_t numAvail, mainLen, numPairs, repMaxIndex, i, posState, lenEnd, len, cur; uint32_t matchPrice, repMatchPrice, normalMatchPrice; uint32_t reps[LZMA_NUM_REPS], repLens[LZMA_NUM_REPS]; uint32_t *matches; const uint8_t *data; uint8_t curByte, matchByte; if (p->optimumEndIndex != p->optimumCurrentIndex) { const COptimal *opt = &p->opt[p->optimumCurrentIndex]; uint32_t lenRes = opt->posPrev - p->optimumCurrentIndex; *backRes = opt->backPrev; p->optimumCurrentIndex = opt->posPrev; return lenRes; } p->optimumCurrentIndex = p->optimumEndIndex = 0; if (p->additionalOffset == 0) mainLen = ReadMatchDistances(p, &numPairs); else { mainLen = p->longestMatchLength; numPairs = p->numPairs; } numAvail = p->numAvail; if (numAvail < 2) { *backRes = (uint32_t)(-1); return 1; } if (numAvail > LZMA_MATCH_LEN_MAX) numAvail = LZMA_MATCH_LEN_MAX; data = Mf_GetPointerToCurrentPos(&p->matchFinderBase) - 1; repMaxIndex = 0; for (i = 0; i < LZMA_NUM_REPS; i++) { uint32_t lenTest; const uint8_t *data2; reps[i] = p->reps[i]; data2 = data - (reps[i] + 1); if (data[0] != data2[0] || data[1] != data2[1]) { repLens[i] = 0; continue; } for (lenTest = 2; lenTest < numAvail && data[lenTest] == data2[lenTest]; lenTest++) ; repLens[i] = lenTest; if (lenTest > repLens[repMaxIndex]) repMaxIndex = i; } if (repLens[repMaxIndex] >= p->numFastBytes) { uint32_t lenRes; *backRes = repMaxIndex; lenRes = repLens[repMaxIndex]; MovePos(p, lenRes - 1); return lenRes; } matches = p->matches; if (mainLen >= p->numFastBytes) { *backRes = matches[numPairs - 1] + LZMA_NUM_REPS; MovePos(p, mainLen - 1); return mainLen; } curByte = *data; matchByte = *(data - (reps[0] + 1)); if (mainLen < 2 && curByte != matchByte && repLens[repMaxIndex] < 2) { *backRes = (uint32_t)-1; return 1; } p->opt[0].state = p->state; posState = (position & p->pbMask); { const int *probs = LIT_PROBS(position, *(data - 1)); p->opt[1].price = GET_PRICE_0(p->isMatch[p->state][posState]) + (!IsCharState(p->state) ? LitEnc_GetPriceMatched(probs, curByte, matchByte, p->ProbPrices) : LitEnc_GetPrice(probs, curByte, p->ProbPrices)); } MakeAsChar(&p->opt[1]); matchPrice = GET_PRICE_1(p->isMatch[p->state][posState]); repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[p->state]); if (matchByte == curByte) { uint32_t shortRepPrice = repMatchPrice + GetRepLen1Price(p, p->state, posState); if (shortRepPrice < p->opt[1].price) { p->opt[1].price = shortRepPrice; MakeAsShortRep(&p->opt[1]); } } lenEnd = ((mainLen >= repLens[repMaxIndex]) ? mainLen : repLens[repMaxIndex]); if (lenEnd < 2) { *backRes = p->opt[1].backPrev; return 1; } p->opt[1].posPrev = 0; for (i = 0; i < LZMA_NUM_REPS; i++) p->opt[0].backs[i] = reps[i]; len = lenEnd; do p->opt[len--].price = kInfinityPrice; while (len >= 2); for (i = 0; i < LZMA_NUM_REPS; i++) { uint32_t repLen = repLens[i]; uint32_t price; if (repLen < 2) continue; price = repMatchPrice + GetPureRepPrice(p, i, p->state, posState); do { uint32_t curAndLenPrice = price + p->repLenEnc.prices[posState][repLen - 2]; COptimal *opt = &p->opt[repLen]; if (curAndLenPrice < opt->price) { opt->price = curAndLenPrice; opt->posPrev = 0; opt->backPrev = i; opt->prev1IsChar = false; } } while (--repLen >= 2); } normalMatchPrice = matchPrice + GET_PRICE_0(p->isRep[p->state]); len = ((repLens[0] >= 2) ? repLens[0] + 1 : 2); if (len <= mainLen) { uint32_t offs = 0; while (len > matches[offs]) offs += 2; for (; ; len++) { COptimal *opt; uint32_t distance = matches[offs + 1]; uint32_t curAndLenPrice = normalMatchPrice + p->lenEnc.prices[posState][len - LZMA_MATCH_LEN_MIN]; uint32_t lenToPosState = GetLenToPosState(len); if (distance < kNumFullDistances) curAndLenPrice += p->distancesPrices[lenToPosState][distance]; else { uint32_t slot; GetPosSlot2(distance, slot); curAndLenPrice += p->alignPrices[distance & kAlignMask] + p->posSlotPrices[lenToPosState][slot]; } opt = &p->opt[len]; if (curAndLenPrice < opt->price) { opt->price = curAndLenPrice; opt->posPrev = 0; opt->backPrev = distance + LZMA_NUM_REPS; opt->prev1IsChar = false; } if (len == matches[offs]) { offs += 2; if (offs == numPairs) break; } } } cur = 0; #ifdef SHOW_STAT2 if (position >= 0) { unsigned i; printf("\n pos = %4X", position); for (i = cur; i <= lenEnd; i++) printf("\nprice[%4X] = %d", position - cur + i, p->opt[i].price); } #endif for (;;) { uint32_t numAvailFull, newLen, numPairs, posPrev, state, posState, startLen; uint32_t curPrice, curAnd1Price, matchPrice, repMatchPrice; bool nextIsChar; uint8_t curByte, matchByte; const uint8_t *data; COptimal *curOpt; COptimal *nextOpt; cur++; if (cur == lenEnd) return Backward(p, backRes, cur); newLen = ReadMatchDistances(p, &numPairs); if (newLen >= p->numFastBytes) { p->numPairs = numPairs; p->longestMatchLength = newLen; return Backward(p, backRes, cur); } position++; curOpt = &p->opt[cur]; posPrev = curOpt->posPrev; if (curOpt->prev1IsChar) { posPrev--; if (curOpt->prev2) { state = p->opt[curOpt->posPrev2].state; if (curOpt->backPrev2 < LZMA_NUM_REPS) state = kRepNextStates[state]; else state = kMatchNextStates[state]; } else state = p->opt[posPrev].state; state = kLiteralNextStates[state]; } else state = p->opt[posPrev].state; if (posPrev == cur - 1) { if (IsShortRep(curOpt)) state = kShortRepNextStates[state]; else state = kLiteralNextStates[state]; } else { uint32_t pos; const COptimal *prevOpt; if (curOpt->prev1IsChar && curOpt->prev2) { posPrev = curOpt->posPrev2; pos = curOpt->backPrev2; state = kRepNextStates[state]; } else { pos = curOpt->backPrev; if (pos < LZMA_NUM_REPS) state = kRepNextStates[state]; else state = kMatchNextStates[state]; } prevOpt = &p->opt[posPrev]; if (pos < LZMA_NUM_REPS) { uint32_t i; reps[0] = prevOpt->backs[pos]; for (i = 1; i <= pos; i++) reps[i] = prevOpt->backs[i - 1]; for (; i < LZMA_NUM_REPS; i++) reps[i] = prevOpt->backs[i]; } else { uint32_t i; reps[0] = (pos - LZMA_NUM_REPS); for (i = 1; i < LZMA_NUM_REPS; i++) reps[i] = prevOpt->backs[i - 1]; } } curOpt->state = state; curOpt->backs[0] = reps[0]; curOpt->backs[1] = reps[1]; curOpt->backs[2] = reps[2]; curOpt->backs[3] = reps[3]; curPrice = curOpt->price; nextIsChar = false; data = Mf_GetPointerToCurrentPos(&p->matchFinderBase) - 1; curByte = *data; matchByte = *(data - (reps[0] + 1)); posState = (position & p->pbMask); curAnd1Price = curPrice + GET_PRICE_0(p->isMatch[state][posState]); { const int *probs = LIT_PROBS(position, *(data - 1)); curAnd1Price += (!IsCharState(state) ? LitEnc_GetPriceMatched(probs, curByte, matchByte, p->ProbPrices) : LitEnc_GetPrice(probs, curByte, p->ProbPrices)); } nextOpt = &p->opt[cur + 1]; if (curAnd1Price < nextOpt->price) { nextOpt->price = curAnd1Price; nextOpt->posPrev = cur; MakeAsChar(nextOpt); nextIsChar = true; } matchPrice = curPrice + GET_PRICE_1(p->isMatch[state][posState]); repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[state]); if (matchByte == curByte && !(nextOpt->posPrev < cur && nextOpt->backPrev == 0)) { uint32_t shortRepPrice = repMatchPrice + GetRepLen1Price(p, state, posState); if (shortRepPrice <= nextOpt->price) { nextOpt->price = shortRepPrice; nextOpt->posPrev = cur; MakeAsShortRep(nextOpt); nextIsChar = true; } } numAvailFull = p->numAvail; { uint32_t temp = kNumOpts - 1 - cur; if (temp < numAvailFull) numAvailFull = temp; } if (numAvailFull < 2) continue; numAvail = (numAvailFull <= p->numFastBytes ? numAvailFull : p->numFastBytes); if (!nextIsChar && matchByte != curByte) /* speed optimization */ { /* try Literal + rep0 */ uint32_t temp; uint32_t lenTest2; const uint8_t *data2 = data - (reps[0] + 1); uint32_t limit = p->numFastBytes + 1; if (limit > numAvailFull) limit = numAvailFull; for (temp = 1; temp < limit && data[temp] == data2[temp]; temp++) ; lenTest2 = temp - 1; if (lenTest2 >= 2) { State state2 = kLiteralNextStates[state]; uint32_t posStateNext = (position + 1) & p->pbMask; uint32_t nextRepMatchPrice = curAnd1Price + GET_PRICE_1(p->isMatch[state2][posStateNext]) + GET_PRICE_1(p->isRep[state2]); /* for (; lenTest2 >= 2; lenTest2--) */ { uint32_t curAndLenPrice; COptimal *opt; uint32_t offset = cur + 1 + lenTest2; while (lenEnd < offset) p->opt[++lenEnd].price = kInfinityPrice; curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext); opt = &p->opt[offset]; if (curAndLenPrice < opt->price) { opt->price = curAndLenPrice; opt->posPrev = cur + 1; opt->backPrev = 0; opt->prev1IsChar = true; opt->prev2 = false; } } } } startLen = 2; /* speed optimization */ { uint32_t repIndex; for (repIndex = 0; repIndex < LZMA_NUM_REPS; repIndex++) { uint32_t lenTest; uint32_t lenTestTemp; uint32_t price; const uint8_t *data2 = data - (reps[repIndex] + 1); if (data[0] != data2[0] || data[1] != data2[1]) continue; for (lenTest = 2; lenTest < numAvail && data[lenTest] == data2[lenTest]; lenTest++) ; while (lenEnd < cur + lenTest) p->opt[++lenEnd].price = kInfinityPrice; lenTestTemp = lenTest; price = repMatchPrice + GetPureRepPrice(p, repIndex, state, posState); do { uint32_t curAndLenPrice = price + p->repLenEnc.prices[posState][lenTest - 2]; COptimal *opt = &p->opt[cur + lenTest]; if (curAndLenPrice < opt->price) { opt->price = curAndLenPrice; opt->posPrev = cur; opt->backPrev = repIndex; opt->prev1IsChar = false; } } while (--lenTest >= 2); lenTest = lenTestTemp; if (repIndex == 0) startLen = lenTest + 1; /* if (_maxMode) */ { uint32_t lenTest2 = lenTest + 1; uint32_t limit = lenTest2 + p->numFastBytes; uint32_t nextRepMatchPrice; if (limit > numAvailFull) limit = numAvailFull; for (; lenTest2 < limit && data[lenTest2] == data2[lenTest2]; lenTest2++) ; lenTest2 -= lenTest + 1; if (lenTest2 >= 2) { State state2 = kRepNextStates[state]; uint32_t posStateNext = (position + lenTest) & p->pbMask; uint32_t curAndLenCharPrice = price + p->repLenEnc.prices[posState][lenTest - 2] + GET_PRICE_0(p->isMatch[state2][posStateNext]) + LitEnc_GetPriceMatched(LIT_PROBS(position + lenTest, data[lenTest - 1]), data[lenTest], data2[lenTest], p->ProbPrices); state2 = kLiteralNextStates[state2]; posStateNext = (position + lenTest + 1) & p->pbMask; nextRepMatchPrice = curAndLenCharPrice + GET_PRICE_1(p->isMatch[state2][posStateNext]) + GET_PRICE_1(p->isRep[state2]); /* for (; lenTest2 >= 2; lenTest2--) */ { uint32_t curAndLenPrice; COptimal *opt; uint32_t offset = cur + lenTest + 1 + lenTest2; while (lenEnd < offset) p->opt[++lenEnd].price = kInfinityPrice; curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext); opt = &p->opt[offset]; if (curAndLenPrice < opt->price) { opt->price = curAndLenPrice; opt->posPrev = cur + lenTest + 1; opt->backPrev = 0; opt->prev1IsChar = true; opt->prev2 = true; opt->posPrev2 = cur; opt->backPrev2 = repIndex; } } } } } } /* for (uint32_t lenTest = 2; lenTest <= newLen; lenTest++) */ if (newLen > numAvail) { newLen = numAvail; for (numPairs = 0; newLen > matches[numPairs]; numPairs += 2) ; matches[numPairs] = newLen; numPairs += 2; } if (newLen >= startLen) { uint32_t normalMatchPrice = matchPrice + GET_PRICE_0(p->isRep[state]); uint32_t offs, curBack, posSlot; uint32_t lenTest; while (lenEnd < cur + newLen) p->opt[++lenEnd].price = kInfinityPrice; offs = 0; while (startLen > matches[offs]) offs += 2; curBack = matches[offs + 1]; GetPosSlot2(curBack, posSlot); for (lenTest = /*2*/ startLen; ; lenTest++) { uint32_t curAndLenPrice = normalMatchPrice + p->lenEnc.prices[posState][lenTest - LZMA_MATCH_LEN_MIN]; uint32_t lenToPosState = GetLenToPosState(lenTest); COptimal *opt; if (curBack < kNumFullDistances) curAndLenPrice += p->distancesPrices[lenToPosState][curBack]; else curAndLenPrice += p->posSlotPrices[lenToPosState][posSlot] + p->alignPrices[curBack & kAlignMask]; opt = &p->opt[cur + lenTest]; if (curAndLenPrice < opt->price) { opt->price = curAndLenPrice; opt->posPrev = cur; opt->backPrev = curBack + LZMA_NUM_REPS; opt->prev1IsChar = false; } if (/*_maxMode && */lenTest == matches[offs]) { /* Try Match + Literal + Rep0 */ const uint8_t *data2 = data - (curBack + 1); uint32_t lenTest2 = lenTest + 1; uint32_t limit = lenTest2 + p->numFastBytes; uint32_t nextRepMatchPrice; if (limit > numAvailFull) limit = numAvailFull; for (; lenTest2 < limit && data[lenTest2] == data2[lenTest2]; lenTest2++) ; lenTest2 -= lenTest + 1; if (lenTest2 >= 2) { State state2 = kMatchNextStates[state]; uint32_t posStateNext = (position + lenTest) & p->pbMask; uint32_t curAndLenCharPrice = curAndLenPrice + GET_PRICE_0(p->isMatch[state2][posStateNext]) + LitEnc_GetPriceMatched(LIT_PROBS(position + lenTest, data[lenTest - 1]), data[lenTest], data2[lenTest], p->ProbPrices); state2 = kLiteralNextStates[state2]; posStateNext = (posStateNext + 1) & p->pbMask; nextRepMatchPrice = curAndLenCharPrice + GET_PRICE_1(p->isMatch[state2][posStateNext]) + GET_PRICE_1(p->isRep[state2]); /* for (; lenTest2 >= 2; lenTest2--) */ { uint32_t offset = cur + lenTest + 1 + lenTest2; uint32_t curAndLenPrice; COptimal *opt; while (lenEnd < offset) p->opt[++lenEnd].price = kInfinityPrice; curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext); opt = &p->opt[offset]; if (curAndLenPrice < opt->price) { opt->price = curAndLenPrice; opt->posPrev = cur + lenTest + 1; opt->backPrev = 0; opt->prev1IsChar = true; opt->prev2 = true; opt->posPrev2 = cur; opt->backPrev2 = curBack + LZMA_NUM_REPS; } } } offs += 2; if (offs == numPairs) break; curBack = matches[offs + 1]; if (curBack >= kNumFullDistances) GetPosSlot2(curBack, posSlot); } } } } } #define ChangePair(smallDist, bigDist) (((bigDist) >> 7) > (smallDist)) static uint32_t GetOptimumFast(CLzmaEnc *p, uint32_t *backRes) { uint32_t numAvail, mainLen, mainDist, numPairs, repIndex, repLen, i; const uint8_t *data; const uint32_t *matches; if (p->additionalOffset == 0) mainLen = ReadMatchDistances(p, &numPairs); else { mainLen = p->longestMatchLength; numPairs = p->numPairs; } numAvail = p->numAvail; *backRes = (uint32_t)-1; if (numAvail < 2) return 1; if (numAvail > LZMA_MATCH_LEN_MAX) numAvail = LZMA_MATCH_LEN_MAX; data = Mf_GetPointerToCurrentPos(&p->matchFinderBase) - 1; repLen = repIndex = 0; for (i = 0; i < LZMA_NUM_REPS; i++) { uint32_t len; const uint8_t *data2 = data - (p->reps[i] + 1); if (data[0] != data2[0] || data[1] != data2[1]) continue; for (len = 2; len < numAvail && data[len] == data2[len]; len++) ; if (len >= p->numFastBytes) { *backRes = i; MovePos(p, len - 1); return len; } if (len > repLen) { repIndex = i; repLen = len; } } matches = p->matches; if (mainLen >= p->numFastBytes) { *backRes = matches[numPairs - 1] + LZMA_NUM_REPS; MovePos(p, mainLen - 1); return mainLen; } mainDist = 0; /* for GCC */ if (mainLen >= 2) { mainDist = matches[numPairs - 1]; while (numPairs > 2 && mainLen == matches[numPairs - 4] + 1) { if (!ChangePair(matches[numPairs - 3], mainDist)) break; numPairs -= 2; mainLen = matches[numPairs - 2]; mainDist = matches[numPairs - 1]; } if (mainLen == 2 && mainDist >= 0x80) mainLen = 1; } if (repLen >= 2 && ( (repLen + 1 >= mainLen) || (repLen + 2 >= mainLen && mainDist >= (1 << 9)) || (repLen + 3 >= mainLen && mainDist >= (1 << 15)))) { *backRes = repIndex; MovePos(p, repLen - 1); return repLen; } if (mainLen < 2 || numAvail <= 2) return 1; p->longestMatchLength = ReadMatchDistances(p, &p->numPairs); if (p->longestMatchLength >= 2) { uint32_t newDistance = matches[p->numPairs - 1]; if ((p->longestMatchLength >= mainLen && newDistance < mainDist) || (p->longestMatchLength == mainLen + 1 && !ChangePair(mainDist, newDistance)) || (p->longestMatchLength > mainLen + 1) || (p->longestMatchLength + 1 >= mainLen && mainLen >= 3 && ChangePair(newDistance, mainDist))) return 1; } data = Mf_GetPointerToCurrentPos(&p->matchFinderBase) - 1; for (i = 0; i < LZMA_NUM_REPS; i++) { uint32_t len, limit; const uint8_t *data2 = data - (p->reps[i] + 1); if (data[0] != data2[0] || data[1] != data2[1]) continue; limit = mainLen - 1; for (len = 2; len < limit && data[len] == data2[len]; len++) ; if (len >= limit) return 1; } *backRes = mainDist + LZMA_NUM_REPS; MovePos(p, mainLen - 2); return mainLen; } static void LZe_full_flush(CLzmaEnc *p, uint32_t posState) { const uint32_t len = LZMA_MATCH_LEN_MIN; File_trailer trailer; RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 1); RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 0); p->state = kMatchNextStates[p->state]; LenEnc_Encode2(&p->lenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices); RcTree_Encode(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], kNumPosSlotBits, (1 << kNumPosSlotBits) - 1); RangeEnc_EncodeDirectBits(&p->rc, (((uint32_t)1 << 30) - 1) >> kNumAlignBits, 30 - kNumAlignBits); RcTree_ReverseEncode(&p->rc, p->posAlignEncoder, kNumAlignBits, kAlignMask); RangeEnc_FlushData(&p->rc); RangeEnc_FlushStream(&p->rc); Ft_set_data_crc( trailer, p->matchFinderBase.crc ^ 0xFFFFFFFFU ); Ft_set_data_size( trailer, p->nowPos64 ); Ft_set_member_size( trailer, p->rc.processed + Fh_size + Ft_size ); if( writeblock( p->rc.outfd, trailer, Ft_size ) != Ft_size ) p->rc.res = SZ_ERROR_WRITE; if( verbosity >= 1 ) { unsigned long long in_size = p->nowPos64; unsigned long long out_size = p->rc.processed + Fh_size + Ft_size; if( in_size == 0 || out_size == 0 ) fputs( " no data compressed.\n", stderr ); else fprintf( stderr, "%6.3f:1, %5.2f%% ratio, %5.2f%% saved, " "%llu in, %llu out.\n", (double)in_size / out_size, ( 100.0 * out_size ) / in_size, 100.0 - ( ( 100.0 * out_size ) / in_size ), in_size, out_size ); } } static int CheckErrors(CLzmaEnc *p) { if (p->result != SZ_OK) return p->result; if (p->rc.res != SZ_OK) p->result = SZ_ERROR_WRITE; if (p->matchFinderBase.result != SZ_OK) p->result = SZ_ERROR_READ; if (p->result != SZ_OK) p->finished = true; return p->result; } static int Flush(CLzmaEnc *p, uint32_t nowPos) { /* ReleaseMFStream(); */ p->finished = true; LZe_full_flush(p, nowPos & p->pbMask); return CheckErrors(p); } static void FillAlignPrices(CLzmaEnc *p) { uint32_t i; for (i = 0; i < kAlignTableSize; i++) p->alignPrices[i] = RcTree_ReverseGetPrice(p->posAlignEncoder, kNumAlignBits, i, p->ProbPrices); p->alignPriceCount = 0; } static void FillDistancesPrices(CLzmaEnc *p) { uint32_t tempPrices[kNumFullDistances]; uint32_t i, lenToPosState; for (i = kStartPosModelIndex; i < kNumFullDistances; i++) { uint32_t posSlot = GetPosSlot1(i); uint32_t footerBits = ((posSlot >> 1) - 1); uint32_t base = ((2 | (posSlot & 1)) << footerBits); tempPrices[i] = RcTree_ReverseGetPrice(p->posEncoders + base - posSlot - 1, footerBits, i - base, p->ProbPrices); } for (lenToPosState = 0; lenToPosState < kNumLenToPosStates; lenToPosState++) { uint32_t posSlot; const int *encoder = p->posSlotEncoder[lenToPosState]; uint32_t *posSlotPrices = p->posSlotPrices[lenToPosState]; for (posSlot = 0; posSlot < p->distTableSize; posSlot++) posSlotPrices[posSlot] = RcTree_GetPrice(encoder, kNumPosSlotBits, posSlot, p->ProbPrices); for (posSlot = kEndPosModelIndex; posSlot < p->distTableSize; posSlot++) posSlotPrices[posSlot] += ((((posSlot >> 1) - 1) - kNumAlignBits) << kNumBitPriceShiftBits); { uint32_t *distancesPrices = p->distancesPrices[lenToPosState]; uint32_t i; for (i = 0; i < kStartPosModelIndex; i++) distancesPrices[i] = posSlotPrices[i]; for (; i < kNumFullDistances; i++) distancesPrices[i] = posSlotPrices[GetPosSlot1(i)] + tempPrices[i]; } } p->matchPriceCount = 0; } static int LzmaEnc_CodeOneBlock(CLzmaEnc *p) { uint32_t nowPos32, startPos32; if (p->finished) return p->result; if( CheckErrors(p) != 0 ) return p->result; nowPos32 = (uint32_t)p->nowPos64; startPos32 = nowPos32; if (p->nowPos64 == 0) { uint32_t numPairs; uint8_t curByte; if (Mf_GetNumAvailableBytes(&p->matchFinderBase) == 0) return Flush(p, nowPos32); ReadMatchDistances(p, &numPairs); RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][0], 0); p->state = kLiteralNextStates[p->state]; curByte = Mf_GetIndexByte(&p->matchFinderBase, 0 - p->additionalOffset); LitEnc_Encode(&p->rc, p->litProbs, curByte); p->additionalOffset--; nowPos32++; } if (Mf_GetNumAvailableBytes(&p->matchFinderBase) != 0) for (;;) { uint32_t pos, len, posState; if (p->fastMode) len = GetOptimumFast(p, &pos); else len = GetOptimum(p, nowPos32, &pos); #ifdef SHOW_STAT2 printf("\n pos = %4X, len = %d pos = %d", nowPos32, len, pos); #endif posState = nowPos32 & p->pbMask; if (len == 1 && pos == (uint32_t)-1) { uint8_t curByte; int *probs; const uint8_t *data; RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 0); data = Mf_GetPointerToCurrentPos(&p->matchFinderBase) - p->additionalOffset; curByte = *data; probs = LIT_PROBS(nowPos32, *(data - 1)); if (IsCharState(p->state)) LitEnc_Encode(&p->rc, probs, curByte); else LitEnc_EncodeMatched(&p->rc, probs, curByte, *(data - p->reps[0] - 1)); p->state = kLiteralNextStates[p->state]; } else { RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 1); if (pos < LZMA_NUM_REPS) { RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 1); if (pos == 0) { RangeEnc_EncodeBit(&p->rc, &p->isRepG0[p->state], 0); RangeEnc_EncodeBit(&p->rc, &p->isRep0Long[p->state][posState], ((len == 1) ? 0 : 1)); } else { uint32_t distance = p->reps[pos]; RangeEnc_EncodeBit(&p->rc, &p->isRepG0[p->state], 1); if (pos == 1) RangeEnc_EncodeBit(&p->rc, &p->isRepG1[p->state], 0); else { RangeEnc_EncodeBit(&p->rc, &p->isRepG1[p->state], 1); RangeEnc_EncodeBit(&p->rc, &p->isRepG2[p->state], pos - 2); if (pos == 3) p->reps[3] = p->reps[2]; p->reps[2] = p->reps[1]; } p->reps[1] = p->reps[0]; p->reps[0] = distance; } if (len == 1) p->state = kShortRepNextStates[p->state]; else { LenEnc_Encode2(&p->repLenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices); p->state = kRepNextStates[p->state]; } } else { uint32_t posSlot; RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 0); p->state = kMatchNextStates[p->state]; LenEnc_Encode2(&p->lenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices); pos -= LZMA_NUM_REPS; GetPosSlot(pos, posSlot); RcTree_Encode(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], kNumPosSlotBits, posSlot); if (posSlot >= kStartPosModelIndex) { uint32_t footerBits = ((posSlot >> 1) - 1); uint32_t base = ((2 | (posSlot & 1)) << footerBits); uint32_t posReduced = pos - base; if (posSlot < kEndPosModelIndex) RcTree_ReverseEncode(&p->rc, p->posEncoders + base - posSlot - 1, footerBits, posReduced); else { RangeEnc_EncodeDirectBits(&p->rc, posReduced >> kNumAlignBits, footerBits - kNumAlignBits); RcTree_ReverseEncode(&p->rc, p->posAlignEncoder, kNumAlignBits, posReduced & kAlignMask); p->alignPriceCount++; } } p->reps[3] = p->reps[2]; p->reps[2] = p->reps[1]; p->reps[1] = p->reps[0]; p->reps[0] = pos; p->matchPriceCount++; } } p->additionalOffset -= len; nowPos32 += len; if (p->additionalOffset == 0) { uint32_t processed; if (!p->fastMode) { if (p->matchPriceCount >= (1 << 7)) FillDistancesPrices(p); if (p->alignPriceCount >= kAlignTableSize) FillAlignPrices(p); } if (Mf_GetNumAvailableBytes(&p->matchFinderBase) == 0) break; processed = nowPos32 - startPos32; if (processed >= (1 << 15)) { p->nowPos64 += nowPos32 - startPos32; return CheckErrors(p); } } } p->nowPos64 += nowPos32 - startPos32; return Flush(p, nowPos32); } CLzmaEncHandle LzmaEnc_Init( const int dict_size, const int match_len_limit, const int infd, const int outfd ) { int i; const uint32_t beforeSize = kNumOpts; CLzmaEnc * const p = (CLzmaEnc *)LZMA_MALLOC(sizeof(CLzmaEnc)); if( !p ) return 0; p->nowPos64 = 0; p->dictSize = dict_size; p->numFastBytes = match_len_limit; p->lc = literal_context_bits; p->lp = 0; p->pb = pos_state_bits; p->optimumEndIndex = 0; p->optimumCurrentIndex = 0; p->additionalOffset = 0; p->state = 0; p->result = SZ_OK; p->fastMode = false; p->finished = false; if (!Mf_Init(&p->matchFinderBase, infd, 16 + ( match_len_limit / 2 ), p->dictSize, beforeSize, p->numFastBytes, LZMA_MATCH_LEN_MAX)) { LZMA_FREE( p ); return 0; } Mf_CreateVTable(&p->matchFinderBase, &p->matchFinder); LzmaEnc_FastPosInit(p->g_FastPos); LzmaEnc_InitPriceTables(p->ProbPrices); for (i = 0; i < kDicLogSizeMaxCompress; i++) if (p->dictSize <= ((uint32_t)1 << i)) break; p->distTableSize = i * 2; if( !RangeEnc_Init( &p->rc, outfd ) ) { LZMA_FREE( p ); return 0; } p->litProbs = (int *)LZMA_MALLOC((0x300 << (p->lc + p->lp)) * sizeof(int)); if( !p->litProbs ) { LZMA_FREE( p ); return 0; } for (i = 0 ; i < LZMA_NUM_REPS; i++) p->reps[i] = 0; for (i = 0; i < kNumStates; i++) { int j; for (j = 0; j < LZMA_NUM_PB_STATES_MAX; j++) { p->isMatch[i][j] = kProbInitValue; p->isRep0Long[i][j] = kProbInitValue; } p->isRep[i] = kProbInitValue; p->isRepG0[i] = kProbInitValue; p->isRepG1[i] = kProbInitValue; p->isRepG2[i] = kProbInitValue; } { const int num = 0x300 << (p->lp + p->lc); for (i = 0; i < num; i++) p->litProbs[i] = kProbInitValue; } for (i = 0; i < kNumLenToPosStates; i++) { int *probs = p->posSlotEncoder[i]; uint32_t j; for (j = 0; j < (1 << kNumPosSlotBits); j++) probs[j] = kProbInitValue; } for (i = 0; i < kNumFullDistances - kEndPosModelIndex; i++) p->posEncoders[i] = kProbInitValue; LenEnc_Init(&p->lenEnc.p); LenEnc_Init(&p->repLenEnc.p); for (i = 0; i < (1 << kNumAlignBits); i++) p->posAlignEncoder[i] = kProbInitValue; p->pbMask = (1 << p->pb) - 1; p->lpMask = (1 << p->lp) - 1; if (!p->fastMode) { FillDistancesPrices(p); FillAlignPrices(p); } p->lenEnc.tableSize = p->repLenEnc.tableSize = p->numFastBytes + 1 - LZMA_MATCH_LEN_MIN; LenPriceEnc_UpdateTables(&p->lenEnc, 1 << p->pb, p->ProbPrices); LenPriceEnc_UpdateTables(&p->repLenEnc, 1 << p->pb, p->ProbPrices); return p; } void LzmaEnc_Free(CLzmaEncHandle pp) { CLzmaEnc *p = (CLzmaEnc *)pp; Mf_Free(&p->matchFinderBase); LZMA_FREE(p->litProbs); p->litProbs = 0; RangeEnc_Free(&p->rc); LZMA_FREE(p); } int LzmaEnc_Encode(CLzmaEncHandle pp) { int res = SZ_OK; CLzmaEnc *p = (CLzmaEnc *)pp; for (;;) { res = LzmaEnc_CodeOneBlock(p); if( res != SZ_OK || p->finished ) break; } return res; } /* LzmaDec.h -- LZMA Decoder 2009-02-07 : Igor Pavlov : Public domain */ /* ---------- LZMA Properties ---------- */ #define LZMA_PROPS_SIZE 5 /* ---------- LZMA Decoder state ---------- */ /* LZMA_REQUIRED_INPUT_MAX = number of required input bytes for worst case. Num bits = log2((2^11 / 31) ^ 22) + 26 < 134 + 26 = 160; */ #define LZMA_REQUIRED_INPUT_MAX 20 typedef struct { int *probs; uint8_t *dic; const uint8_t *buf; uint32_t range, code; uint32_t dicPos; uint32_t dicBufSize; uint32_t processedPos; uint32_t checkDicSize; unsigned lc, lp, pb; State state; uint32_t reps[4]; unsigned remainLen; uint32_t numProbs; unsigned tempBufSize; bool needFlush; uint8_t tempBuf[LZMA_REQUIRED_INPUT_MAX]; } CLzmaDec; /* There are two types of LZMA streams: 0) Stream with end mark. That end mark adds about 6 bytes to compressed size. 1) Stream without end mark. You must know exact uncompressed size to decompress such stream. */ typedef enum { LZMA_FINISH_ANY, /* finish at any point */ LZMA_FINISH_END /* block must be finished at the end */ } ELzmaFinishMode; /* ELzmaFinishMode has meaning only if the decoding reaches output limit !!! You must use LZMA_FINISH_END, when you know that current output buffer covers last bytes of block. In other cases you must use LZMA_FINISH_ANY. If LZMA decoder sees end marker before reaching output limit, it returns SZ_OK, and output value of destLen will be less than output buffer size limit. You can check status result also. You can use multiple checks to test data integrity after full decompression: 1) Check Result and "status" variable. 2) Check that output(destLen) = uncompressedSize, if you know real uncompressedSize. 3) Check that output(srcLen) = compressedSize, if you know real compressedSize. You must use correct finish mode in that case. */ typedef enum { LZMA_STATUS_NOT_SPECIFIED, /* use main error code instead */ LZMA_STATUS_FINISHED_WITH_MARK, /* stream was finished with end mark. */ LZMA_STATUS_NOT_FINISHED, /* stream was not finished */ LZMA_STATUS_NEEDS_MORE_INPUT, /* you must provide more input bytes */ LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK /* there is probability that stream was finished without end mark */ } ELzmaStatus; /* ELzmaStatus is used only as output value for function call */ static bool LzmaDec_Init(CLzmaDec *p, const uint8_t *raw_props); static void LzmaDec_Free(CLzmaDec *p); /* ---------- Buffer Interface ---------- */ /* It's zlib-like interface. finishMode: It has meaning only if the decoding reaches output limit (*destLen). LZMA_FINISH_ANY - Decode just destLen bytes. LZMA_FINISH_END - Stream must be finished after (*destLen). */ static bool LzmaDec_DecodeToBuf( CLzmaDec *p, uint8_t *dest, uint32_t *destLen, const uint8_t *src, uint32_t *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status ); /* LzmaDec.c -- LZMA Decoder 2009-09-20 : Igor Pavlov : Public domain */ #define kNumTopBits 24 #define kTopValue ((uint32_t)1 << kNumTopBits) #define kNumBitModelTotalBits 11 #define kBitModelTotal (1 << kNumBitModelTotalBits) #define kNumMoveBits 5 #define RC_INIT_SIZE 5 #define NORMALIZE if (range < kTopValue) { range <<= 8; code = (code << 8) | (*buf++); } #define IF_BIT_0(p) ttt = *(p); NORMALIZE; bound = (range >> kNumBitModelTotalBits) * ttt; if (code < bound) #define UPDATE_0(p) range = bound; *(p) = (int)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits)); #define UPDATE_1(p) range -= bound; code -= bound; *(p) = (int)(ttt - (ttt >> kNumMoveBits)); #define GET_BIT2(p, i, A0, A1) IF_BIT_0(p) \ { UPDATE_0(p); i = (i + i); A0; } else \ { UPDATE_1(p); i = (i + i) + 1; A1; } #define GET_BIT(p, i) GET_BIT2(p, i, ; , ;) #define TREE_GET_BIT(probs, i) { GET_BIT((probs + i), i); } #define TREE_DECODE(probs, limit, i) \ { i = 1; do { TREE_GET_BIT(probs, i); } while (i < limit); i -= limit; } /* #define _LZMA_SIZE_OPT */ #ifdef _LZMA_SIZE_OPT #define TREE_6_DECODE(probs, i) TREE_DECODE(probs, (1 << 6), i) #else #define TREE_6_DECODE(probs, i) \ { i = 1; \ TREE_GET_BIT(probs, i); \ TREE_GET_BIT(probs, i); \ TREE_GET_BIT(probs, i); \ TREE_GET_BIT(probs, i); \ TREE_GET_BIT(probs, i); \ TREE_GET_BIT(probs, i); \ i -= 0x40; } #endif #define NORMALIZE_CHECK if (range < kTopValue) { if (buf >= bufLimit) return DUMMY_ERROR; range <<= 8; code = (code << 8) | (*buf++); } #define IF_BIT_0_CHECK(p) ttt = *(p); NORMALIZE_CHECK; bound = (range >> kNumBitModelTotalBits) * ttt; if (code < bound) #define UPDATE_0_CHECK range = bound; #define UPDATE_1_CHECK range -= bound; code -= bound; #define GET_BIT2_CHECK(p, i, A0, A1) IF_BIT_0_CHECK(p) \ { UPDATE_0_CHECK; i = (i + i); A0; } else \ { UPDATE_1_CHECK; i = (i + i) + 1; A1; } #define GET_BIT_CHECK(p, i) GET_BIT2_CHECK(p, i, ; , ;) #define TREE_DECODE_CHECK(probs, limit, i) \ { i = 1; do { GET_BIT_CHECK(probs + i, i) } while (i < limit); i -= limit; } #define kNumPosBitsMax 4 #define kNumPosStatesMax (1 << kNumPosBitsMax) #define kLenNumLowBits 3 #define kLenNumLowSymbols (1 << kLenNumLowBits) #define kLenNumMidBits 3 #define kLenNumMidSymbols (1 << kLenNumMidBits) #define kLenNumHighBits 8 #define kLenNumHighSymbols (1 << kLenNumHighBits) #define LenChoice 0 #define LenChoice2 (LenChoice + 1) #define LenLow (LenChoice2 + 1) #define LenMid (LenLow + (kNumPosStatesMax << kLenNumLowBits)) #define LenHigh (LenMid + (kNumPosStatesMax << kLenNumMidBits)) #define kNumLenProbs (LenHigh + kLenNumHighSymbols) #define kNumStates 12 #define kNumLitStates 7 #define kStartPosModelIndex 4 #define kEndPosModelIndex 14 #define kNumFullDistances (1 << (kEndPosModelIndex >> 1)) #define kNumPosSlotBits 6 #define kNumLenToPosStates 4 #define kNumAlignBits 4 #define kAlignTableSize (1 << kNumAlignBits) #define kMatchMinLen 2 #define kMatchSpecLenStart (kMatchMinLen + kLenNumLowSymbols + kLenNumMidSymbols + kLenNumHighSymbols) #define IsMatch 0 #define IsRep (IsMatch + (kNumStates << kNumPosBitsMax)) #define IsRepG0 (IsRep + kNumStates) #define IsRepG1 (IsRepG0 + kNumStates) #define IsRepG2 (IsRepG1 + kNumStates) #define IsRep0Long (IsRepG2 + kNumStates) #define PosSlot (IsRep0Long + (kNumStates << kNumPosBitsMax)) #define SpecPos (PosSlot + (kNumLenToPosStates << kNumPosSlotBits)) #define Align (SpecPos + kNumFullDistances - kEndPosModelIndex) #define LenCoder (Align + kAlignTableSize) #define RepLenCoder (LenCoder + kNumLenProbs) #define Literal (RepLenCoder + kNumLenProbs) #define LZMA_BASE_SIZE 1846 #define LZMA_LIT_SIZE 768 #define LzmaProps_GetNumProbs(p) ((uint32_t)LZMA_BASE_SIZE + (LZMA_LIT_SIZE << ((p)->lc + (p)->lp))) #if Literal != LZMA_BASE_SIZE StopCompilingDueBUG #endif /* First LZMA-symbol is always decoded. And it decodes new LZMA-symbols while (buf < bufLimit), but "buf" is without last normalization Out: Result: true - OK false - Error p->remainLen: < kMatchSpecLenStart : normal remain = kMatchSpecLenStart : finished = kMatchSpecLenStart + 1 : Flush marker = kMatchSpecLenStart + 2 : State Init Marker */ static bool LzmaDec_DecodeReal(CLzmaDec *p, uint32_t limit, const uint8_t *bufLimit) { int *probs = p->probs; State state = p->state; uint32_t rep0 = p->reps[0], rep1 = p->reps[1], rep2 = p->reps[2], rep3 = p->reps[3]; unsigned pbMask = ((unsigned)1 << (p->pb)) - 1; unsigned lpMask = ((unsigned)1 << (p->lp)) - 1; const unsigned lc = p->lc; uint8_t *dic = p->dic; const uint32_t dicBufSize = p->dicBufSize; uint32_t dicPos = p->dicPos; uint32_t processedPos = p->processedPos; uint32_t checkDicSize = p->checkDicSize; unsigned len = 0; const uint8_t *buf = p->buf; uint32_t range = p->range; uint32_t code = p->code; do { int *prob; uint32_t bound; unsigned ttt; unsigned posState = processedPos & pbMask; prob = probs + IsMatch + (state << kNumPosBitsMax) + posState; IF_BIT_0(prob) { unsigned symbol; UPDATE_0(prob); prob = probs + Literal; if (checkDicSize != 0 || processedPos != 0) prob += (LZMA_LIT_SIZE * (((processedPos & lpMask) << lc) + (dic[(dicPos == 0 ? dicBufSize : dicPos) - 1] >> (8 - lc)))); if (state < kNumLitStates) { state -= (state < 4) ? state : 3; symbol = 1; do { GET_BIT(prob + symbol, symbol) } while (symbol < 0x100); } else { unsigned matchByte = p->dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)]; unsigned offs = 0x100; state -= (state < 10) ? 3 : 6; symbol = 1; do { unsigned bit; int *probLit; matchByte <<= 1; bit = (matchByte & offs); probLit = prob + offs + bit + symbol; GET_BIT2(probLit, symbol, offs &= ~bit, offs &= bit) } while (symbol < 0x100); } dic[dicPos++] = (uint8_t)symbol; processedPos++; continue; } else { UPDATE_1(prob); prob = probs + IsRep + state; IF_BIT_0(prob) { UPDATE_0(prob); state += kNumStates; prob = probs + LenCoder; } else { UPDATE_1(prob); if (checkDicSize == 0 && processedPos == 0) return false; prob = probs + IsRepG0 + state; IF_BIT_0(prob) { UPDATE_0(prob); prob = probs + IsRep0Long + (state << kNumPosBitsMax) + posState; IF_BIT_0(prob) { UPDATE_0(prob); dic[dicPos] = dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)]; dicPos++; processedPos++; state = state < kNumLitStates ? 9 : 11; continue; } UPDATE_1(prob); } else { uint32_t distance; UPDATE_1(prob); prob = probs + IsRepG1 + state; IF_BIT_0(prob) { UPDATE_0(prob); distance = rep1; } else { UPDATE_1(prob); prob = probs + IsRepG2 + state; IF_BIT_0(prob) { UPDATE_0(prob); distance = rep2; } else { UPDATE_1(prob); distance = rep3; rep3 = rep2; } rep2 = rep1; } rep1 = rep0; rep0 = distance; } state = state < kNumLitStates ? 8 : 11; prob = probs + RepLenCoder; } { unsigned limit, offset; int *probLen = prob + LenChoice; IF_BIT_0(probLen) { UPDATE_0(probLen); probLen = prob + LenLow + (posState << kLenNumLowBits); offset = 0; limit = (1 << kLenNumLowBits); } else { UPDATE_1(probLen); probLen = prob + LenChoice2; IF_BIT_0(probLen) { UPDATE_0(probLen); probLen = prob + LenMid + (posState << kLenNumMidBits); offset = kLenNumLowSymbols; limit = (1 << kLenNumMidBits); } else { UPDATE_1(probLen); probLen = prob + LenHigh; offset = kLenNumLowSymbols + kLenNumMidSymbols; limit = (1 << kLenNumHighBits); } } TREE_DECODE(probLen, limit, len); len += offset; } if (state >= kNumStates) { uint32_t distance; prob = probs + PosSlot + ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) << kNumPosSlotBits); TREE_6_DECODE(prob, distance); if (distance >= kStartPosModelIndex) { unsigned posSlot = (unsigned)distance; int numDirectBits = (int)(((distance >> 1) - 1)); distance = (2 | (distance & 1)); if (posSlot < kEndPosModelIndex) { distance <<= numDirectBits; prob = probs + SpecPos + distance - posSlot - 1; { uint32_t mask = 1; unsigned i = 1; do { GET_BIT2(prob + i, i, ; , distance |= mask); mask <<= 1; } while (--numDirectBits != 0); } } else { numDirectBits -= kNumAlignBits; do { NORMALIZE range >>= 1; { uint32_t t; code -= range; t = (0 - ((uint32_t)code >> 31)); /* (uint32_t)((int)code >> 31) */ distance = (distance << 1) + (t + 1); code += range & t; } /* distance <<= 1; if (code >= range) { code -= range; distance |= 1; } */ } while (--numDirectBits != 0); prob = probs + Align; distance <<= kNumAlignBits; { unsigned i = 1; GET_BIT2(prob + i, i, ; , distance |= 1); GET_BIT2(prob + i, i, ; , distance |= 2); GET_BIT2(prob + i, i, ; , distance |= 4); GET_BIT2(prob + i, i, ; , distance |= 8); } if (distance == (uint32_t)0xFFFFFFFF) { len += kMatchSpecLenStart; state -= kNumStates; break; } } } rep3 = rep2; rep2 = rep1; rep1 = rep0; rep0 = distance + 1; if (checkDicSize == 0) { if (distance >= processedPos) return false; } else if (distance >= checkDicSize) return false; state = (state < kNumStates + kNumLitStates) ? kNumLitStates : kNumLitStates + 3; } len += kMatchMinLen; if (limit == dicPos) return false; { uint32_t rem = limit - dicPos; unsigned curLen = ((rem < len) ? (unsigned)rem : len); uint32_t pos = (dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0); processedPos += curLen; len -= curLen; if (pos + curLen <= dicBufSize) { uint8_t *dest = dic + dicPos; ptrdiff_t src = (ptrdiff_t)pos - (ptrdiff_t)dicPos; const uint8_t *lim = dest + curLen; dicPos += curLen; do *(dest) = (uint8_t)*(dest + src); while (++dest != lim); } else { do { dic[dicPos++] = dic[pos]; if (++pos == dicBufSize) pos = 0; } while (--curLen != 0); } } } } while (dicPos < limit && buf < bufLimit); NORMALIZE; p->buf = buf; p->range = range; p->code = code; p->remainLen = len; p->dicPos = dicPos; p->processedPos = processedPos; p->reps[0] = rep0; p->reps[1] = rep1; p->reps[2] = rep2; p->reps[3] = rep3; p->state = state; return true; } static void LzmaDec_WriteRem(CLzmaDec *p, uint32_t limit) { if (p->remainLen != 0 && p->remainLen < kMatchSpecLenStart) { uint8_t *dic = p->dic; uint32_t dicPos = p->dicPos; const uint32_t dicBufSize = p->dicBufSize; unsigned len = p->remainLen; uint32_t rep0 = p->reps[0]; if (limit - dicPos < len) len = (unsigned)(limit - dicPos); if (p->checkDicSize == 0 && dicBufSize - p->processedPos <= len) p->checkDicSize = dicBufSize; p->processedPos += len; p->remainLen -= len; while (len-- != 0) { dic[dicPos] = dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)]; dicPos++; } p->dicPos = dicPos; } } static int LzmaDec_DecodeReal2(CLzmaDec *p, uint32_t limit, const uint8_t *bufLimit) { const uint32_t dicBufSize = p->dicBufSize; do { uint32_t limit2 = limit; if (p->checkDicSize == 0) { uint32_t rem = dicBufSize - p->processedPos; if (limit - p->dicPos > rem) limit2 = p->dicPos + rem; } if( !LzmaDec_DecodeReal(p, limit2, bufLimit) ) return false; if (p->processedPos >= dicBufSize) p->checkDicSize = dicBufSize; LzmaDec_WriteRem(p, limit); } while (p->dicPos < limit && p->buf < bufLimit && p->remainLen < kMatchSpecLenStart); if (p->remainLen > kMatchSpecLenStart) { p->remainLen = kMatchSpecLenStart; } return true; } typedef enum { DUMMY_ERROR, /* unexpected end of input stream */ DUMMY_LIT, DUMMY_MATCH, DUMMY_REP } ELzmaDummy; static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const uint8_t *buf, uint32_t inSize) { uint32_t range = p->range; uint32_t code = p->code; const uint8_t *bufLimit = buf + inSize; int *probs = p->probs; State state = p->state; ELzmaDummy res; { int *prob; uint32_t bound; unsigned ttt; unsigned posState = (p->processedPos) & ((1 << p->pb) - 1); prob = probs + IsMatch + (state << kNumPosBitsMax) + posState; IF_BIT_0_CHECK(prob) { UPDATE_0_CHECK /* if (bufLimit - buf >= 7) return DUMMY_LIT; */ prob = probs + Literal; if (p->checkDicSize != 0 || p->processedPos != 0) prob += (LZMA_LIT_SIZE * ((((p->processedPos) & ((1 << (p->lp)) - 1)) << p->lc) + (p->dic[(p->dicPos == 0 ? p->dicBufSize : p->dicPos) - 1] >> (8 - p->lc)))); if (state < kNumLitStates) { unsigned symbol = 1; do { GET_BIT_CHECK(prob + symbol, symbol) } while (symbol < 0x100); } else { unsigned matchByte = p->dic[p->dicPos - p->reps[0] + ((p->dicPos < p->reps[0]) ? p->dicBufSize : 0)]; unsigned offs = 0x100; unsigned symbol = 1; do { unsigned bit; int *probLit; matchByte <<= 1; bit = (matchByte & offs); probLit = prob + offs + bit + symbol; GET_BIT2_CHECK(probLit, symbol, offs &= ~bit, offs &= bit) } while (symbol < 0x100); } res = DUMMY_LIT; } else { unsigned len; UPDATE_1_CHECK; prob = probs + IsRep + state; IF_BIT_0_CHECK(prob) { UPDATE_0_CHECK; state = 0; prob = probs + LenCoder; res = DUMMY_MATCH; } else { UPDATE_1_CHECK; res = DUMMY_REP; prob = probs + IsRepG0 + state; IF_BIT_0_CHECK(prob) { UPDATE_0_CHECK; prob = probs + IsRep0Long + (state << kNumPosBitsMax) + posState; IF_BIT_0_CHECK(prob) { UPDATE_0_CHECK; NORMALIZE_CHECK; return DUMMY_REP; } else { UPDATE_1_CHECK; } } else { UPDATE_1_CHECK; prob = probs + IsRepG1 + state; IF_BIT_0_CHECK(prob) { UPDATE_0_CHECK; } else { UPDATE_1_CHECK; prob = probs + IsRepG2 + state; IF_BIT_0_CHECK(prob) { UPDATE_0_CHECK; } else { UPDATE_1_CHECK; } } } state = kNumStates; prob = probs + RepLenCoder; } { unsigned limit, offset; int *probLen = prob + LenChoice; IF_BIT_0_CHECK(probLen) { UPDATE_0_CHECK; probLen = prob + LenLow + (posState << kLenNumLowBits); offset = 0; limit = 1 << kLenNumLowBits; } else { UPDATE_1_CHECK; probLen = prob + LenChoice2; IF_BIT_0_CHECK(probLen) { UPDATE_0_CHECK; probLen = prob + LenMid + (posState << kLenNumMidBits); offset = kLenNumLowSymbols; limit = 1 << kLenNumMidBits; } else { UPDATE_1_CHECK; probLen = prob + LenHigh; offset = kLenNumLowSymbols + kLenNumMidSymbols; limit = 1 << kLenNumHighBits; } } TREE_DECODE_CHECK(probLen, limit, len); len += offset; } if (state < 4) { unsigned posSlot; prob = probs + PosSlot + ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) << kNumPosSlotBits); TREE_DECODE_CHECK(prob, 1 << kNumPosSlotBits, posSlot); if (posSlot >= kStartPosModelIndex) { int numDirectBits = ((posSlot >> 1) - 1); /* if (bufLimit - buf >= 8) return DUMMY_MATCH; */ if (posSlot < kEndPosModelIndex) { prob = probs + SpecPos + ((2 | (posSlot & 1)) << numDirectBits) - posSlot - 1; } else { numDirectBits -= kNumAlignBits; do { NORMALIZE_CHECK range >>= 1; code -= range & (((code - range) >> 31) - 1); /* if (code >= range) code -= range; */ } while (--numDirectBits != 0); prob = probs + Align; numDirectBits = kNumAlignBits; } { unsigned i = 1; do { GET_BIT_CHECK(prob + i, i); } while (--numDirectBits != 0); } } } } } NORMALIZE_CHECK; return res; } static void LzmaDec_InitRc(CLzmaDec *p, const uint8_t *data) { p->code = ((uint32_t)data[1] << 24) | ((uint32_t)data[2] << 16) | ((uint32_t)data[3] << 8) | ((uint32_t)data[4]); p->range = 0xFFFFFFFF; p->needFlush = false; } static bool LzmaDec_DecodeToDic(CLzmaDec *p, uint32_t dicLimit, const uint8_t *src, uint32_t *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status) { uint32_t inSize = *srcLen; (*srcLen) = 0; LzmaDec_WriteRem(p, dicLimit); *status = LZMA_STATUS_NOT_SPECIFIED; while (p->remainLen != kMatchSpecLenStart) { int checkEndMarkNow; if( p->needFlush ) { for (; inSize > 0 && p->tempBufSize < RC_INIT_SIZE; (*srcLen)++, inSize--) p->tempBuf[p->tempBufSize++] = *src++; if (p->tempBufSize < RC_INIT_SIZE) { *status = LZMA_STATUS_NEEDS_MORE_INPUT; return true; } if (p->tempBuf[0] != 0) return false; LzmaDec_InitRc(p, p->tempBuf); p->tempBufSize = 0; } checkEndMarkNow = 0; if (p->dicPos >= dicLimit) { if (p->remainLen == 0 && p->code == 0) { *status = LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK; return true; } if (finishMode == LZMA_FINISH_ANY) { *status = LZMA_STATUS_NOT_FINISHED; return true; } if (p->remainLen != 0) { *status = LZMA_STATUS_NOT_FINISHED; return false; } checkEndMarkNow = 1; } if (p->tempBufSize == 0) { uint32_t processed; const uint8_t *bufLimit; if (inSize < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow) { int dummyRes = LzmaDec_TryDummy(p, src, inSize); if (dummyRes == DUMMY_ERROR) { memcpy(p->tempBuf, src, inSize); p->tempBufSize = (unsigned)inSize; (*srcLen) += inSize; *status = LZMA_STATUS_NEEDS_MORE_INPUT; return true; } if (checkEndMarkNow && dummyRes != DUMMY_MATCH) { *status = LZMA_STATUS_NOT_FINISHED; return false; } bufLimit = src; } else bufLimit = src + inSize - LZMA_REQUIRED_INPUT_MAX; p->buf = src; if( !LzmaDec_DecodeReal2(p, dicLimit, bufLimit) ) return false; processed = (uint32_t)(p->buf - src); (*srcLen) += processed; src += processed; inSize -= processed; } else { unsigned rem = p->tempBufSize, lookAhead = 0; while (rem < LZMA_REQUIRED_INPUT_MAX && lookAhead < inSize) p->tempBuf[rem++] = src[lookAhead++]; p->tempBufSize = rem; if (rem < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow) { int dummyRes = LzmaDec_TryDummy(p, p->tempBuf, rem); if (dummyRes == DUMMY_ERROR) { (*srcLen) += lookAhead; *status = LZMA_STATUS_NEEDS_MORE_INPUT; return true; } if (checkEndMarkNow && dummyRes != DUMMY_MATCH) { *status = LZMA_STATUS_NOT_FINISHED; return false; } } p->buf = p->tempBuf; if( !LzmaDec_DecodeReal2(p, dicLimit, p->buf) ) return false; lookAhead -= (rem - (unsigned)(p->buf - p->tempBuf)); (*srcLen) += lookAhead; src += lookAhead; inSize -= lookAhead; p->tempBufSize = 0; } } if (p->code == 0) *status = LZMA_STATUS_FINISHED_WITH_MARK; return (p->code == 0); } static bool LzmaDec_DecodeToBuf( CLzmaDec *p, uint8_t *dest, uint32_t *destLen, const uint8_t *src, uint32_t *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status ) { uint32_t outSize = *destLen; uint32_t inSize = *srcLen; *srcLen = *destLen = 0; for (;;) { uint32_t inSizeCur = inSize, outSizeCur, dicPos; ELzmaFinishMode curFinishMode; bool res; if (p->dicPos == p->dicBufSize) p->dicPos = 0; dicPos = p->dicPos; if (outSize > p->dicBufSize - dicPos) { outSizeCur = p->dicBufSize; curFinishMode = LZMA_FINISH_ANY; } else { outSizeCur = dicPos + outSize; curFinishMode = finishMode; } res = LzmaDec_DecodeToDic(p, outSizeCur, src, &inSizeCur, curFinishMode, status); src += inSizeCur; inSize -= inSizeCur; *srcLen += inSizeCur; outSizeCur = p->dicPos - dicPos; memcpy(dest, p->dic + dicPos, outSizeCur); dest += outSizeCur; outSize -= outSizeCur; *destLen += outSizeCur; if( !res ) return false; if (outSizeCur == 0 || outSize == 0) return true; } } static void LzmaDec_Free(CLzmaDec *p) { LZMA_FREE( p->dic ); LZMA_FREE( p->probs ); } static bool LzmaDec_Init(CLzmaDec *p, const uint8_t *raw_props) { uint32_t i; uint8_t d = raw_props[0]; p->lc = d % 9; d /= 9; p->pb = d / 5; p->lp = d % 5; p->dicBufSize = raw_props[1] | ((uint32_t)raw_props[2] << 8) | ((uint32_t)raw_props[3] << 16) | ((uint32_t)raw_props[4] << 24); if (p->dicBufSize < min_dictionary_size) p->dicBufSize = min_dictionary_size; p->numProbs = LzmaProps_GetNumProbs(p); p->probs = (int *)LZMA_MALLOC(p->numProbs * sizeof(int)); if( !p->probs ) return false; p->dic = (uint8_t *)LZMA_MALLOC(p->dicBufSize); if (p->dic == 0) { LZMA_FREE( p->probs ); return false; } p->dicPos = 0; p->needFlush = true; p->remainLen = 0; p->tempBufSize = 0; p->processedPos = 0; p->checkDicSize = 0; for( i = 0; i < p->numProbs; ++i ) p->probs[i] = kBitModelTotal >> 1; p->reps[0] = p->reps[1] = p->reps[2] = p->reps[3] = 1; p->state = 0; return true; } // glue.c static #ifdef _MSC_VER __declspec(thread) #else __thread #endif struct { uint8_t *begin, *seek, *end; } memfd[2]; /* Returns the number of bytes really read. If (returned value < size) and (errno == 0), means EOF was reached. */ static int readblock( const int fd, uint8_t * buf, int size ) { int avail = (memfd[fd].end - memfd[fd].seek); if( size > avail ) size = avail; memcpy(buf, memfd[fd].seek, size); memfd[fd].seek += size; errno = 0; return size; } /* Returns the number of bytes really written. If (returned value < size), it is always an error. */ static int writeblock( const int fd, const uint8_t *buf, int size ) { int avail = (memfd[fd].end - memfd[fd].seek); if( size > avail ) size = avail; memcpy(memfd[fd].seek, buf, size); memfd[fd].seek += size; errno = 0; return size; } // Customized compression modes. // Lower modes are optimized for low-mem devices. Uber modes A-B-C require *lots of RAM*. static const struct lzma_options { int dictionary_size; /* [4 KiB .. 512 MiB] */ int match_len_limit; /* [5 .. 273] */ } lzma_mappings[] = { // lowmem+fastest modes { 1 << 12, 5 }, // 0 - 39973598 lzma 39.97% c:13.635s d:2.909s { 1 << 16, 6 }, // 1 - 34979790 lzma 34.98% c:19.151s d:2.427s { 1 << 19, 7 }, // 2 - 32881806 lzma 32.88% c:25.592s d:1.907s { 1 << 20, 8 }, // 3 - 31908622 lzma 31.91% c:32.189s d:1.827s { 3 << 19, 10 }, // 4 - 30704458 lzma 30.70% c:40.736s d:1.747s { 1 << 21, 16 }, // 5 - 28807777 lzma 28.81% c:55.690s d:1.645s { 3 << 20, 20 }, // 6 - 28100304 lzma 28.10% c:63.734s d:1.614s { 1 << 22, 28 }, // 7 - 27594705 lzma 27.59% c:72.234s d:1.604s { 1 << 23, 36 }, // 8 - 27051139 lzma 27.05% c:79.418s d:1.586s { 1 << 24, 68 }, // 9 - 26702913 lzma 26.70% c:87.800s d:1.573s { 3 << 23, 132 }, // A - 26667550 lzma 26.67% c:89.020s d:1.581s { 1 << 25, 273 }, // B - 26656366 lzma 26.66% c:89.586s d:1.607s { 1 << 26, 273 }, // C - 26656366 lzma 26.66% c:90.004s d:1.586s // himem+slowest modes }; unsigned lzma_encode(const void *in, unsigned inlen, void *out, unsigned outlen, unsigned flags /*[0..9]*/) { uint8_t level = (uint8_t)(flags > 9 ? 9 : flags < 0 ? 0 : flags); int i = 0; memfd[i].begin = memfd[i].seek = memfd[i].end = (uint8_t*)in; memfd[i].end += inlen; int o = 1; memfd[o].begin = memfd[o].seek = memfd[o].end = (uint8_t*)out; memfd[o].end += outlen; writeblock(o, &level, 1); // write 1-byte header struct lzma_options encoder_options = lzma_mappings[level]; CLzmaEncHandle handle = LzmaEnc_Init( encoder_options.dictionary_size, encoder_options.match_len_limit, i, o ); int ok = SZ_OK == LzmaEnc_Encode(handle); LzmaEnc_Free(handle); return ok ? (int)(memfd[o].seek - memfd[o].begin) : 0; } unsigned lzma_decode(const void *in_, unsigned inlen, void *out, unsigned outlen) { const uint8_t *in = (const uint8_t*)in_; // parse 1-byte header uint8_t level = *in++; --inlen; // -d{N}: set dictionary size - [12, 30], default: 23 (8MB) // -fb{N}: set number of fast bytes - [5, 273], default: 128 // -mc{N}: set number of cycles for match finder // -lc{N}: set number of literal context bits - [0, 8], default: 3 // -lp{N}: set number of literal pos bits - [0, 4], default: 0 // -pb{N}: set number of pos bits - [0, 4], default: 2 // -mf{MF_ID}: set Match Finder: [bt2, bt3, bt4, hc4], default: bt4 #pragma pack(push,1) struct { uint8_t d /*d=lc/pb/lp*/; uint32_t dsize; uint64_t rawsize; } props = {0}; #pragma pack(pop) props.d = 0x5D; props.dsize = lzma_mappings[level].dictionary_size; CLzmaDec dec; ELzmaStatus status; LzmaDec_Init(&dec, &props.d); uint32_t srcLen = (uint32_t)inlen, destLen = (uint32_t)outlen; bool ok = LzmaDec_DecodeToBuf(&dec, (uint8_t*)out, &destLen, in, &srcLen, LZMA_FINISH_ANY, &status); LzmaDec_Free(&dec); return (unsigned)(ok ? destLen : 0); } unsigned lzma_bounds(unsigned inlen, unsigned flags) { return (unsigned)(inlen * 1.1) + 16; // @todo: check src } unsigned lzma_excess(unsigned flags) { return (unsigned)(0); } #endif // LZMA_C #ifdef LZMA_DEMO #pragma once int main() { const char *longcopy = "Hello world! Hello world! Hello world! Hello world!"; int level = 1; char out[128]; unsigned outlen = lzma_encode(longcopy, strlen(longcopy)+1, out, 128, level ); printf("%s %d->%d\n", outlen ? "ok" : "fail", (int)strlen(longcopy)+1, (int)outlen); char redo[128]; unsigned unpacked = lzma_decode(out, outlen, redo, 128); printf("%d->%d %s\n", (int)outlen, (int)unpacked, redo); } #define main main__ #endif // LZMA_DEMO //#line 1 "amalgamated_lzp1.c" /*********** Direct port of the old lzp1.c code to a single file header. This is not the best way to make fast compressors on modern hardware and this is by no means a modern competitive compressor. Also, zlib licensed is not strictly public domain, but pretty close terms :o) ----------- Copyright (c) 2019, @r-lyeh Copyright (c) 1998-2012, Charles Bloom This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. *******************/ unsigned lzp1_encode(const void* in, unsigned inlen, void* out, unsigned outlen, unsigned flags); unsigned lzp1_decode(const void* in, unsigned inlen, void* out, unsigned outlen); unsigned lzp1_bounds(unsigned inlen, unsigned flags); unsigned lzp1_excess(unsigned flags); #ifdef LZP1_C #pragma once #include <stdint.h> #define LZP1_BOUNDS(sz) ((sz)+((sz)/8)+256) #define LZP1_EXCESS 256 #define LZP1_HASH_SIZE (1<<16) #define LZP1_HASH(x,y,z) ((x ^ (y << 7) ^ (z<<11)) & 0xFFFF) static int lzp1_encode_(const uint8_t *raw,int rawLen,uint8_t * comp,int compLen) { uint8_t const *table[LZP1_HASH_SIZE]; for(int ix=0;ix<LZP1_HASH_SIZE;ix++) table[ix] = raw; uint8_t *cp,*controlp; const uint8_t *rp,*endrp,*mp; int ix,control,controlb,ml; uint8_t literal; /** do the LZP **/ rp = raw; endrp = raw + rawLen; cp = comp; // store excess *cp++ = rawLen & 255; // seed four *cp++ = *rp++; *cp++ = *rp++; *cp++ = *rp++; *cp++ = *rp++; control = 0; controlp = cp++; controlb = 8; /** the control-byte entry macro **/ #define ENC_SHIFT_CONTROL(bit) if ( 0 ) ; else { control += control + bit; if ( --controlb == 0 ) { *controlp = (uint8_t)control; controlp = cp++; control = 0; controlb = 8; } } while(rp < endrp) { ix = LZP1_HASH(rp[-1],rp[-2],rp[-3]); mp = table[ix]; table[ix] = rp; if ( *mp != *rp ) { literal = *rp++; ix = LZP1_HASH(rp[-1],rp[-2],rp[-3]); mp = table[ix]; table[ix] = rp; if ( *mp != *rp ) { ENC_SHIFT_CONTROL(0); //flag two literals : 0 *cp++ = literal; *cp++ = *rp++; // pass a literal } else { ENC_SHIFT_CONTROL(1); //flag literal then a match : 10 ENC_SHIFT_CONTROL(0); *cp++ = literal; goto encode_match; } } else { ENC_SHIFT_CONTROL(1); //flag a match with no literals : 11 ENC_SHIFT_CONTROL(1); encode_match: mp++; rp++; if ( *mp != *rp ) { ENC_SHIFT_CONTROL(0); } else { mp++; rp++; ENC_SHIFT_CONTROL(1); if ( *mp == *rp ) { mp++; rp++; if ( *mp == *rp ) { mp++; rp++; if ( *mp == *rp ) { mp++; rp++; // flag more than 3 ENC_SHIFT_CONTROL(1); ENC_SHIFT_CONTROL(1); if ( *mp == *rp ) { mp++; rp++; if ( *mp == *rp ) { mp++; rp++; if ( *mp == *rp ) { mp++; rp++; if ( *mp == *rp ) { mp++; rp++; if ( *mp == *rp ) { mp++; rp++; if ( *mp == *rp ) { mp++; rp++; if ( *mp == *rp ) { mp++; rp++; // flag 11 or more ENC_SHIFT_CONTROL(1); ENC_SHIFT_CONTROL(1); ENC_SHIFT_CONTROL(1); ml = 0; while(rp < endrp && *mp == *rp ) { mp++; rp++; ml++; } while( ml >= 0xFF ) { *cp++ = 0xFF; ml -= 0xFF; } *cp++ = (uint8_t)ml; } else { // match 10 ENC_SHIFT_CONTROL(1); ENC_SHIFT_CONTROL(1); ENC_SHIFT_CONTROL(0); } } else { // match 9 ENC_SHIFT_CONTROL(1); ENC_SHIFT_CONTROL(0); ENC_SHIFT_CONTROL(1); } } else { // match 8 ENC_SHIFT_CONTROL(1); ENC_SHIFT_CONTROL(0); ENC_SHIFT_CONTROL(0); } } else { // match 7 ENC_SHIFT_CONTROL(0); ENC_SHIFT_CONTROL(1); ENC_SHIFT_CONTROL(1); } } else { // match 6 ENC_SHIFT_CONTROL(0); ENC_SHIFT_CONTROL(1); ENC_SHIFT_CONTROL(0); } } else { // match 5 ENC_SHIFT_CONTROL(0); ENC_SHIFT_CONTROL(0); ENC_SHIFT_CONTROL(1); } } else { // match 4 ENC_SHIFT_CONTROL(0); ENC_SHIFT_CONTROL(0); ENC_SHIFT_CONTROL(0); } } else { // match 3 ENC_SHIFT_CONTROL(1); ENC_SHIFT_CONTROL(0); } } else { // match 2 ENC_SHIFT_CONTROL(0); ENC_SHIFT_CONTROL(1); } } else { //match 1 ENC_SHIFT_CONTROL(0); ENC_SHIFT_CONTROL(0); } } } } //flush the control while( controlb > 0 ) { control += control; controlb--; } *controlp = (uint8_t)control; return (int)(cp - comp); } static int lzp1_decode_(const uint8_t * comp,int compLen,uint8_t * raw,int rawLen) { uint8_t const *table[LZP1_HASH_SIZE]; for(int ix=0;ix<LZP1_HASH_SIZE;ix++) table[ix] = raw; const uint8_t *cp,*mp,*endcp; uint8_t *rp,*endrp; int ix,control,controlb,ml; int bit; rp = raw; endrp = raw + rawLen; cp = comp; endcp = comp + compLen; uint8_t excess = *cp++; compLen--; *rp++ = *cp++; *rp++ = *cp++; *rp++ = *cp++; *rp++ = *cp++; control = *cp++; controlb = 8; #define DEC_GET_CONTROL(getbit) if ( 0 ) ; else { getbit = control & 0x80; control += control;if ( --controlb == 0 ) { control = *cp++; controlb = 8; } } while(cp<endcp) { DEC_GET_CONTROL(bit); if ( ! bit ) { // two literals table[ LZP1_HASH(rp[-1],rp[-2],rp[-3]) ] = rp; *rp++ = *cp++; table[ LZP1_HASH(rp[-1],rp[-2],rp[-3]) ] = rp; *rp++ = *cp++; } else { DEC_GET_CONTROL(bit); if ( ! bit ) { //10 : literal then match table[ LZP1_HASH(rp[-1],rp[-2],rp[-3]) ] = rp; *rp++ = *cp++; } // match ix = LZP1_HASH(rp[-1],rp[-2],rp[-3]); mp = table[ix]; table[ix] = rp; *rp++ = *mp++; // read 1 bit DEC_GET_CONTROL(bit); if ( bit ) { *rp++ = *mp++; // read 2 bits to get length DEC_GET_CONTROL(bit); if ( bit ) { *rp++ = *mp++; *rp++ = *mp++; DEC_GET_CONTROL(bit); if ( bit ) { *rp++ = *mp++; //read 3 more bits DEC_GET_CONTROL(bit); if ( bit ) { *rp++ = *mp++; *rp++ = *mp++; *rp++ = *mp++; *rp++ = *mp++; DEC_GET_CONTROL(bit); if ( bit ) { DEC_GET_CONTROL(bit); if ( bit ) { // 111 *rp++ = *mp++; *rp++ = *mp++; *rp++ = *mp++; do { int l; l = ml = *cp++; while(l--) *rp++ = *mp++; } while( ml == 0xFF ); } else { // 110 *rp++ = *mp++; *rp++ = *mp++; } } else { DEC_GET_CONTROL(bit); if ( bit ) { // 101 *rp++ = *mp++; } else { // 100 } } } else { DEC_GET_CONTROL(bit); if ( bit ) { DEC_GET_CONTROL(bit); if ( bit ) { // 011 *rp++ = *mp++; *rp++ = *mp++; *rp++ = *mp++; } else { // 010 *rp++ = *mp++; *rp++ = *mp++; } } else { DEC_GET_CONTROL(bit); if ( bit ) { // 001 *rp++ = *mp++; } else { // 000 } } } } } else { DEC_GET_CONTROL(bit); if ( bit ) { *rp++ = *mp++; } } } } } return (((int)(rp - raw) >> 8) << 8) | excess; } unsigned lzp1_encode(const void* in, unsigned inlen, void* out, unsigned outlen, unsigned flags) { return (unsigned)lzp1_encode_((const uint8_t*)in, (int)inlen, (uint8_t*)out, (int)outlen); } unsigned lzp1_decode(const void* in, unsigned inlen, void* out, unsigned outlen) { return (unsigned)lzp1_decode_((const uint8_t*)in, (int)inlen, (uint8_t*)out, (int)outlen); } unsigned lzp1_bounds(unsigned inlen, unsigned flags) { return (unsigned)LZP1_BOUNDS(inlen); } unsigned lzp1_excess(unsigned flags) { return (unsigned)LZP1_EXCESS; } #endif // LZP1_C #ifdef LZP1_DEMO #pragma once int main(int argc, char** argv) { const char *longcopy = "Hello world! Hello world! Hello world! Hello world!"; char out[128]; int outlen = lzp1_encode(longcopy, strlen(longcopy)+1, out, 128); printf("%s %d->%d\n", outlen ? "ok" : "fail", (int)strlen(longcopy)+1, outlen); char redo[128 + 256]; int unpacked = lzp1_decode(out, outlen, redo, 128); printf("%d->%d %s\n", outlen, unpacked, redo); } #define main main__ #endif // LZP1_DEMO //#line 1 "amalgamated_lzrw3a.c" // Author : Ross Williams. Date : 15-Jul-1991. Release : 1. // Modified by @r-lyeh. // // This file contains an implementation of the LZRW3-A data compression // algorithm in the C programming language. // 1 Algorithm is free of patent problems. The algorithm has not been // patented (nor will it be) and is of the LZ77 class which is fairly // clear of patents. // 2 This implementation in C is in the public domain. unsigned lzrw3a_encode(const void* in, unsigned inlen, void* out, unsigned outlen, unsigned flags); unsigned lzrw3a_decode(const void* in, unsigned inlen, void* out, unsigned outlen); unsigned lzrw3a_bounds(unsigned inlen, unsigned flags); unsigned lzrw3a_excess(unsigned flags); #ifdef LZRW3A_C #pragma once #include <string.h> #include <stdint.h> #define MEM_REQ ( HASH_TABLE_LENGTH*sizeof(uint8_t *) + 16 ) // 16 = ALIGNMENT_FUDGE #define FLAG_BYTES 4 #define FLAG_PACKESS 0 #define FLAG_COPY 1 #define ALIGN_UP(X) ((((uintptr_t)X)+3)&~3) #define MAX_RAW_ITEM (18) #define MAX_RAW_GROUP (16*MAX_RAW_ITEM) #define MAX_CMP_GROUP (2+16*2) #define HASH_TABLE_LENGTH (4096) #define HASH_TABLE_DEPTH_BITS (3) #define PARTITION_LENGTH_BITS (12-HASH_TABLE_DEPTH_BITS) #define PARTITION_LENGTH (1<<PARTITION_LENGTH_BITS) #define HASH_TABLE_DEPTH (1<<HASH_TABLE_DEPTH_BITS ) #define HASH_MASK (PARTITION_LENGTH-1) #define DEPTH_MASK (HASH_TABLE_DEPTH-1) #define START_STRING_18 ((uint8_t *) "123456789012345678") #define HASH(PTR) ( \ (((40543*(((*(PTR))<<8)^((*((PTR)+1))<<4)^(*((PTR)+2))))>>4) & HASH_MASK) \ << HASH_TABLE_DEPTH_BITS \ ) #define UPDATE_P(P_BASE,NEWPTR) \ {(P_BASE)[cycle++]=(NEWPTR); cycle&=DEPTH_MASK;} #define UPDATE_I(I_BASE,NEWPTR) \ {hash[(I_BASE)+cycle++]=(NEWPTR); cycle&=DEPTH_MASK;} #define ANY_HASH_INDEX (0) static void lzrw3a_compress(uint8_t* p_wrk_mem, uint8_t* p_src_first, uint32_t src_len, uint8_t* p_dst_first, size_t* p_dst_len) { uint8_t* p_src = p_src_first; uint8_t* p_dst = p_dst_first; uint8_t* p_src_post = p_src_first + src_len; uint8_t* p_dst_post = p_dst_first + src_len; uint8_t* p_src_max1 = p_src_first + src_len - MAX_RAW_ITEM; uint8_t* p_src_max16 = p_src_first + src_len - MAX_RAW_ITEM * 16; #define TOPWORD 0xFFFF0000 uint8_t* p_control; uint32_t control = TOPWORD; uint8_t** hash = (uint8_t**)ALIGN_UP(p_wrk_mem); uint8_t** p_h1 = 0; uint8_t** p_h2 = 0; unsigned cycle = 0; *p_dst++ = FLAG_PACKESS; {unsigned i; for (i = 2; i <= FLAG_BYTES; i++) *p_dst++ = 0; } p_control = p_dst; p_dst += 2; {unsigned i; uint8_t** p_h = hash; #define ZH *p_h++=START_STRING_18 for (i = 0; i < 256; i++) { ZH; ZH; ZH; ZH; ZH; ZH; ZH; ZH; ZH; ZH; ZH; ZH; ZH; ZH; ZH; ZH; } } while (1) { uint8_t* p_ziv; unsigned unroll; unsigned index; uint8_t** p_h0; register unsigned d; register unsigned bestlen; register unsigned bestpos; if (p_dst > p_dst_post) goto overrun; unroll = 16; if (p_src > p_src_max16) { unroll = 1; if (p_src > p_src_max1) { if (p_src == p_src_post) break; else { p_h0 = &hash[ANY_HASH_INDEX]; goto literal; } } } begin_unrolled_loop: p_ziv = p_src; index = HASH(p_src); p_h0 = &hash[index]; bestlen = 0; bestpos = 0; for (d = 0; d < HASH_TABLE_DEPTH; d++) { register uint8_t* s = p_src; register uint8_t* p = p_h0[d]; register unsigned len; if (s[bestlen] == p[bestlen]) { #define PS *p++!=*s++ PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || s++; len = s - p_src - 1; if (len > bestlen) { bestpos = d; bestlen = len; } } } if (bestlen < 3) { literal: *p_dst++ = *p_src++; control &= 0xFFFEFFFF; if (p_h2 != 0) { UPDATE_P(p_h2, p_ziv - 2); } p_h2 = p_h1; p_h1 = p_h0; } else { index += bestpos; *p_dst++ = ((index & 0xF00) >> 4) | (bestlen - 3); *p_dst++ = index & 0xFF; p_src += bestlen; if (p_h1 != 0) { if (p_h2 != 0) { UPDATE_P(p_h2, p_ziv - 2); p_h2 = 0; } UPDATE_P(p_h1, p_ziv - 1); p_h1 = 0; } UPDATE_P(p_h0, p_ziv); } control >>= 1; if (--unroll) goto begin_unrolled_loop; if ((control & TOPWORD) == 0) { *p_control++ = control & 0xFF; *p_control = (control >> 8) & 0xFF; p_control = p_dst; p_dst += 2; control = TOPWORD; } } while (control & TOPWORD) control >>= 1; *p_control++ = control & 0xFF; *p_control++ = (control >> 8) & 0xFF; if (p_control == p_dst) p_dst -= 2; *p_dst_len = p_dst - p_dst_first; return; overrun: *p_dst_first = FLAG_COPY; memcpy(p_dst_first + FLAG_BYTES, p_src_first, src_len); *p_dst_len = src_len + FLAG_BYTES; } static void lzrw3a_decompress(uint8_t* p_wrk_mem, uint8_t* p_src_first, uint32_t src_len, uint8_t* p_dst_first, size_t* p_dst_len) { register uint8_t* p_src = p_src_first + FLAG_BYTES; register uint8_t* p_dst = p_dst_first; uint8_t* p_src_post = p_src_first + src_len; uint8_t* p_src_max16 = p_src_first + src_len - (MAX_CMP_GROUP - 2); uint8_t** hash = (uint8_t**)ALIGN_UP(p_wrk_mem); register uint32_t control = 1; register unsigned literals = 0; unsigned cycle = 0; if (*p_src_first == FLAG_COPY) { memcpy(p_dst_first, p_src_first + FLAG_BYTES, src_len - FLAG_BYTES); *p_dst_len = src_len - FLAG_BYTES; return; } {unsigned i; uint8_t** p_h = hash; #define ZJ *p_h++=START_STRING_18 for (i = 0; i < 256; i++) { ZJ; ZJ; ZJ; ZJ; ZJ; ZJ; ZJ; ZJ; ZJ; ZJ; ZJ; ZJ; ZJ; ZJ; ZJ; ZJ; } } while (p_src != p_src_post) { register unsigned unroll; if (control == 1) { control = 0x10000 | *p_src++; control |= (*p_src++) << 8; } unroll = p_src <= p_src_max16 ? 16 : 1; while (unroll--) { if (control & 1) { register uint8_t* p; register unsigned lenmt; register uint8_t* p_ziv = p_dst; register unsigned index; lenmt = *p_src++; index = ((lenmt & 0xF0) << 4) | *p_src++; p = hash[index]; lenmt &= 0xF; *p_dst++ = *p++; *p_dst++ = *p++; *p_dst++ = *p++; while (lenmt--) *p_dst++ = *p++; if (literals > 0) { register uint8_t* r = p_ziv - literals;; UPDATE_I(HASH(r), r); if (literals == 2) { r++; UPDATE_I(HASH(r), r); } literals = 0; } UPDATE_I(index & (~DEPTH_MASK), p_ziv); } else { *p_dst++ = *p_src++; if (++literals == 3) { register uint8_t* p = p_dst - 3; UPDATE_I(HASH(p), p); literals = 2; } } control >>= 1; } } *p_dst_len = p_dst - p_dst_first; } unsigned lzrw3a_encode(const void* in, unsigned inlen, void* out, unsigned outlen, unsigned flags) { uint8_t workmem[MEM_REQ]; size_t outlen_ = outlen; lzrw3a_compress(workmem, (uint8_t*)in, inlen, (uint8_t*)out, &outlen_); return (unsigned)outlen_; } unsigned lzrw3a_decode(const void* in, unsigned inlen, void* out, unsigned outlen) { uint8_t workmem[MEM_REQ]; size_t outlen_ = outlen; lzrw3a_decompress(workmem, (uint8_t*)in, inlen, (uint8_t*)out, &outlen_); return (unsigned)outlen_; } unsigned lzrw3a_bounds(unsigned inlen, unsigned flags) { return (unsigned)(inlen * 1.1) + 16; // @todo: check src } unsigned lzrw3a_excess(unsigned flags) { return (unsigned)0; } #endif // LZRW3A_C #ifdef LZRW3A_DEMO #pragma once #include <stdio.h> int main() { const char* longcopy = "Hello world! Hello world! Hello world! Hello world!"; int level = 1; char out[128]; size_t outlen = lzrw3a_encode(longcopy, strlen(longcopy) + 1, out, 128, level); printf("%s %d->%d\n", outlen ? "ok" : "fail", (int)strlen(longcopy) + 1, (int)outlen); char redo[128]; size_t unpacked = lzrw3a_decode(out, outlen, redo, 128); printf("%d->%d %s\n", (int)outlen, (int)unpacked, redo); } #define main main__ #endif // LZRW3A_DEMO //#line 1 "amalgamated_lzss.c" /************************************************************** LZSS.C -- A Data Compression Program *************************************************************** 4/ 6/1989 Haruhiko Okumura 30/12/2019 @r-lyeh Use, distribute, and modify this program freely. **************************************************************/ unsigned lzss_encode(const void *in, unsigned inlen, void *out, unsigned outlen, unsigned flags); unsigned lzss_decode(const void *in, unsigned inlen, void *out, unsigned outlen); unsigned lzss_bounds(unsigned bytes, unsigned flags); unsigned lzss_excess(unsigned flags); #ifdef LZSS_C #pragma once #include <stdlib.h> #include <string.h> #include <ctype.h> #define N 4096 /* size of ring buffer */ #define F 18 /* upper limit for match_length */ #define THRESHOLD 2 /* encode string into position and length if match_length is greater than this */ #define NIL N /* index for root of binary search trees */ /* of longest match. These are set by the InsertNode() procedure. */ static int match_position; static int match_length; static void InsertNode(unsigned char* text_buf, int* lson, int* rson, int* dad, int r) /* Inserts string of length F, text_buf[r..r+F-1], into one of the trees (text_buf[r]'th tree) and returns the longest-match position and length via the global variables match_position and match_length. If match_length = F, then removes the old node in favor of the new one, because the old one will be deleted sooner. Note r plays double role, as tree node and position in buffer. */ { int i, p, cmp; unsigned char *key; cmp = 1; key = &text_buf[r]; p = N + 1 + key[0]; rson[r] = lson[r] = NIL; match_length = 0; for ( ; ; ) { if (cmp >= 0) { if (rson[p] != NIL) p = rson[p]; else { rson[p] = r; dad[r] = p; return; } } else { if (lson[p] != NIL) p = lson[p]; else { lson[p] = r; dad[r] = p; return; } } for (i = 1; i < F; i++) if ((cmp = key[i] - text_buf[p + i]) != 0) break; if (i > match_length) { match_position = p; if ((match_length = i) >= F) break; } } dad[r] = dad[p]; lson[r] = lson[p]; rson[r] = rson[p]; dad[lson[p]] = r; dad[rson[p]] = r; if (rson[dad[p]] == p) rson[dad[p]] = r; else lson[dad[p]] = r; dad[p] = NIL; /* remove p */ } static void DeleteNode(int* lson, int* rson, int* dad, int p) /* deletes node p from tree */ { int q; if (dad[p] == NIL) return; /* not in tree */ if (rson[p] == NIL) q = lson[p]; else if (lson[p] == NIL) q = rson[p]; else { q = lson[p]; if (rson[q] != NIL) { do { q = rson[q]; } while (rson[q] != NIL); rson[dad[q]] = lson[q]; dad[lson[q]] = dad[q]; lson[q] = lson[p]; dad[lson[p]] = q; } rson[q] = rson[p]; dad[rson[p]] = q; } dad[q] = dad[p]; if (rson[dad[p]] == p) rson[dad[p]] = q; else lson[dad[p]] = q; dad[p] = NIL; } #define _get(c) \ if (! ilen) {\ c = -1; /*EOF;*/ \ break;\ }\ c = *istr;\ ++istr;\ --ilen #define _put(c) \ *ostr = c;\ ++ostr;\ --olen size_t LzssEncode(const char* istr, size_t ilen, char* ostr, size_t olen) { int i, c, len, r, s, last_match_length, code_buf_ptr; unsigned char code_buf[17], mask; size_t codesize = 0; int lson[N + 1], rson[N + 257], dad[N + 1]; /* left & right children & parents -- These constitute binary search trees. */ unsigned char text_buf[N + F - 1]; /* ring buffer of size N, with extra F-1 bytes to facilitate string comparison */ match_position = 0; match_length = 0; if (ilen == 0) return 0; /* initialize trees */ /* For i = 0 to N - 1, rson[i] and lson[i] will be the right and left children of node i. These nodes need not be initialized. Also, dad[i] is the parent of node i. These are initialized to NIL (= N), which stands for 'not used.' For i = 0 to 255, rson[N + i + 1] is the root of the tree for strings that begin with character i. These are initialized to NIL. Note there are 256 trees. */ for (i = N + 1; i <= N + 256; i++) rson[i] = NIL; for (i = 0; i < N; i++) dad[i] = NIL; code_buf[0] = 0; /* code_buf[1..16] saves eight units of code, and code_buf[0] works as eight flags, "1" representing that the unit is an unencoded letter (1 byte), "0" a position-and-length pair (2 bytes). Thus, eight units require at most 16 bytes of code. */ code_buf_ptr = mask = 1; s = 0; r = N - F; for (i = s; i < r; i++) text_buf[i] = 0; /* Clear the buffer with any character that will appear often. */ for (len = 0; len < F && ilen; len++) { _get(c); text_buf[r + len] = c; /* Read F bytes into the last F bytes of the buffer */ } for (i = 1; i <= F; i++) InsertNode(text_buf, lson, rson, dad, r - i); /* Insert the F strings, each of which begins with one or more 'space' characters. Note the order in which these strings are inserted. This way, degenerate trees will be less likely to occur. */ InsertNode(text_buf, lson, rson, dad, r); /* Finally, insert the whole string just read. The global variables match_length and match_position are set. */ do { if (match_length > len) match_length = len; /* match_length may be spuriously long near the end of text. */ if (match_length <= THRESHOLD) { match_length = 1; /* Not long enough match. Send one byte. */ code_buf[0] |= mask; /* 'send one byte' flag */ code_buf[code_buf_ptr++] = text_buf[r]; /* Send uncoded. */ } else { code_buf[code_buf_ptr++] = (unsigned char) match_position; code_buf[code_buf_ptr++] = (unsigned char) (((match_position >> 4) & 0xf0) | (match_length - (THRESHOLD + 1))); /* Send position and length pair. Note match_length > THRESHOLD. */ } if ((mask <<= 1) == 0) { /* Shift mask left one bit. */ for (i = 0; i < code_buf_ptr; i++) { /* Send at most 8 units of */ _put(code_buf[i]); /* code together */ } codesize += code_buf_ptr; code_buf[0] = 0; code_buf_ptr = mask = 1; } last_match_length = match_length; for (i = 0; i < last_match_length && ilen; i++) { _get(c); DeleteNode(lson, rson, dad, s); /* Delete old strings and */ text_buf[s] = c; /* read new bytes */ if (s < F - 1) text_buf[s + N] = c; /* If the position is near the end of buffer, extend the buffer to make string comparison easier. */ s = (s + 1) & (N - 1); r = (r + 1) & (N - 1); /* Since this is a ring buffer, increment the position modulo N. */ InsertNode(text_buf, lson, rson, dad, r); /* Register the string in text_buf[r..r+F-1] */ } while (i++ < last_match_length) { /* After the end of text, */ DeleteNode(lson, rson, dad, s); /* no need to read, but */ s = (s + 1) & (N - 1); r = (r + 1) & (N - 1); if (--len) InsertNode(text_buf, lson, rson, dad, r); /* buffer may not be empty. */ } } while (len > 0); /* until length of string to be processed is zero */ if (code_buf_ptr > 1) { /* Send remaining code. */ for (i = 0; i < code_buf_ptr; i++) { _put(code_buf[i]); } codesize += code_buf_ptr; } return codesize; } #undef _put #define _put(c) \ *ostr++ = c; size_t LzssDecode(const unsigned char* istr, size_t ilen, char *ostr, size_t olen) /* Just the reverse of Encode(). */ { unsigned char text_buf[N + F - 1]; /* ring buffer of size N, with extra F-1 bytes to facilitate string comparison */ int i, j, k, r, c; unsigned int flags; int limit = ilen; char *obak = ostr; for (i = 0; i < N - F; i++) text_buf[i] = 0; r = N - F; flags = 0; for ( ; ; ) { if (((flags >>= 1) & 256) == 0) { _get(c); flags = c | 0xff00; /* uses higher byte cleverly */ } /* to count eight */ if (flags & 1) { _get(c); _put(c); text_buf[r++] = c; r &= (N - 1); } else { _get(i); _get(j); i |= ((j & 0xf0) << 4); j = (j & 0x0f) + THRESHOLD; for (k = 0; k <= j; k++) { c = text_buf[(i + k) & (N - 1)]; _put(c); text_buf[r++] = c; r &= (N - 1); } } } return (size_t)(ostr - obak); } #undef _get #undef _put #undef N #undef F #undef THRESHOLD #undef NIL unsigned lzss_encode(const void *in, unsigned inlen, void *out, unsigned outlen, unsigned flags) { size_t rc = LzssEncode((const char*)in, (size_t)inlen, (char*)out, (size_t)outlen); return (unsigned)rc; } unsigned lzss_decode(const void *in, unsigned inlen, void *out, unsigned outlen) { size_t rc = LzssDecode((const unsigned char*)in, (size_t)inlen, (char*)out, (size_t)outlen); return (unsigned)rc; } unsigned lzss_bounds(unsigned bytes, unsigned flags) { return (unsigned)(bytes * 1.5) + 16; // @todo: check src } unsigned lzss_excess(unsigned flags) { return (unsigned)0; } #endif // LZSS_C #ifdef LZSS_DEMO #pragma once #include <stdio.h> int main() { const char *longcopy = "Hello world! Hello world! Hello world! Hello world!"; int level=1; char out[128]; size_t outlen = lzss_encode(longcopy, strlen(longcopy)+1, out, 128, level); printf("%s %d->%d\n", outlen ? "ok" : "fail", (int)strlen(longcopy)+1, (int)outlen); char redo[128]; size_t unpacked = lzss_decode(out, outlen, redo, 128); printf("%d->%d %s\n", (int)outlen, (int)unpacked, redo); } #define main main__ #endif // LZSS_DEMO //#line 1 "amalgamated_ppp.c" // pred.c -- Original code by Dave Rand's rendition of the predictor algorithm. // Updated by: Ian Donaldson, Carsten Bormann. Additional modifications by @r-lyeh. // // There are no license fees or costs associated with using the Predictor algorithm. // Use the following code at your own risk. unsigned ppp_encode(const void *in, unsigned inlen, void *out, unsigned outlen, unsigned flags); unsigned ppp_decode(const void *in, unsigned inlen, void *out, unsigned outlen); unsigned ppp_bounds(unsigned inlen, unsigned flags); unsigned ppp_excess(unsigned flags); #ifdef PPP_C #pragma once #include <stdio.h> #include <stdlib.h> #include <string.h> /* The following hash code is the heart of the algorithm: * It builds a sliding hash sum of the previous 3-and-a-bit * characters which will be used to index the guess table. * A better hash function would result in additional compression, * at the expense of time. */ // original. enwik8: 61.730.508 c:0.729s d:0.453s //#define PPP_HASH_TYPE unsigned short //#define PPP_HASH_TABLE (65536) //#define PPP_HASH(x) Hash = (Hash << 4) ^ (x) // // improved. enwik8: 58.769.363 c:0.772s d:0.490s #define PPP_HASH_TYPE unsigned int #define PPP_HASH_TABLE (1<<18) // 256K #define PPP_HASH(x) Hash = ((Hash * 160) ^ (x)) & (PPP_HASH_TABLE-1) // see: https://encode.su/threads/1025-PREDICTOR-algorithm static int ppp_compress(const unsigned char *source, int slen, unsigned char *dest, int dlen) { PPP_HASH_TYPE Hash = 0; unsigned char GuessTable[PPP_HASH_TABLE] = {0}; unsigned char *orgdest = dest; while (slen) { unsigned char *flagdest = dest++, flags = 0; /* All guess wrong initially */ for (int bitmask=1, i=0; i < 8 && slen; i++, bitmask <<= 1) { if (GuessTable[Hash] != *source) { GuessTable[Hash] = *source; *dest++ = *source; /* Guess wrong, output char */ } else { flags |= bitmask; /* Guess was right - don't output */ } PPP_HASH(*source++);slen--; } *flagdest = flags; } return(dest - orgdest); } static int ppp_decompress(const unsigned char *source, int slen, unsigned char *dest, int dlen) { int final = 1; PPP_HASH_TYPE Hash = 0; unsigned char GuessTable[PPP_HASH_TABLE] = {0}; unsigned char *orgdest = dest; while (slen >= 9) { unsigned char flags = *source++; for (int i=0, bitmask = 1; i < 8; i++, bitmask <<= 1) { if (!(flags & bitmask)) { GuessTable[Hash] = *source; /* Guess wrong */ *dest = *source++; /* Read from source */ slen--; } else { *dest = GuessTable[Hash]; /* Guess correct */ } PPP_HASH(*dest++); } slen--; } while (final && slen > 0) { unsigned char flags = *source++; slen--; for (int i=0, bitmask = 1; i < 8; i++, bitmask <<= 1) { if (!(flags & bitmask)) { if (!slen) break; /* we seem to be really done -- cabo */ GuessTable[Hash] = *source; /* Guess wrong */ *dest = *source++; /* Read from source */ slen--; } else { *dest = GuessTable[Hash]; /* Guess correct */ } PPP_HASH(*dest++); } } return (dest - orgdest); // len } unsigned ppp_encode(const void *in, unsigned inlen, void *out, unsigned outlen, unsigned flags) { return (unsigned)ppp_compress((const unsigned char *)in, (int)inlen, (unsigned char *)out, (int)outlen); } unsigned ppp_decode(const void *in, unsigned inlen, void *out, unsigned outlen) { return (unsigned)ppp_decompress((const unsigned char *)in, (int)inlen, (unsigned char *)out, (int)outlen); } unsigned ppp_bounds(unsigned inlen, unsigned flags) { return (unsigned)(inlen/8*9+9); } unsigned ppp_excess(unsigned flags) { return (unsigned)0; } #endif // PPP_C #ifdef PPP_DEMO #pragma once #include <stdio.h> int main() { const char *longcopy = "Hello world! Hello world! Hello world! Hello world!"; int level = 0; char out[128]; unsigned outlen = ppp_encode(longcopy, strlen(longcopy)+1, out, 128, level); printf("%s %d->%d\n", outlen ? "ok" : "fail", (int)strlen(longcopy)+1, (int)outlen); char redo[128]; unsigned unpacked = ppp_decode(out, outlen, redo, 128); printf("%d->%d %s\n", outlen, unpacked, redo); } #define main main__ #endif // PPP_DEMO //#line 1 "amalgamated_raw.c" // raw memcpy de/encoder // - rlyeh, public domain #ifndef RAW_H #define RAW_H unsigned raw_encode(const void *in, unsigned inlen, void *out, unsigned outcap, unsigned flags); unsigned raw_decode(const void *in, unsigned inlen, void *out, unsigned outcap); unsigned raw_bounds(unsigned bytes, unsigned flags); unsigned raw_excess(unsigned flags); #endif #ifdef RAW_C #pragma once #include <string.h> unsigned raw_encode(const void *in, unsigned inlen, void *out, unsigned outcap, unsigned flags) { return memcpy(out, in, inlen), inlen; } unsigned raw_decode(const void *in, unsigned inlen, void *out, unsigned outcap) { return memcpy(out, in, inlen), inlen; } unsigned raw_bounds(unsigned bytes, unsigned flags) { return (unsigned)bytes; } unsigned raw_excess(unsigned flags) { return (unsigned)0; } #endif //#line 1 "amalgamated_ulz.c" // ULZ.HPP - An ultra-fast LZ77 compressor // Original C++ code written and placed in the public domain by Ilya Muravyov (UNLICENSED) // Modified by r-lyeh (UNLICENSED) unsigned ulz_encode(const void *in, unsigned inlen, void *out, unsigned outlen, unsigned flags); // [0..(6)..9] unsigned ulz_decode(const void *in, unsigned inlen, void *out, unsigned outlen); unsigned ulz_bounds(unsigned inlen, unsigned flags); unsigned ulz_excess(unsigned flags); #ifdef ULZ_C #pragma once #include <stdlib.h> #include <stdint.h> #ifndef ULZ_REALLOC #define ULZ_REALLOC REALLOC #endif enum { ULZ_EXCESS=16, ULZ_WINDOW_BITS=17, // Hard-coded ULZ_WINDOW_SIZE=1<<ULZ_WINDOW_BITS, ULZ_WINDOW_MASK=ULZ_WINDOW_SIZE-1, ULZ_MIN_MATCH=4, ULZ_HASH_BITS=19, ULZ_HASH_SIZE=1<<ULZ_HASH_BITS, ULZ_NIL=-1, }; typedef struct ULZ_WORKMEM { int HashTable[ULZ_HASH_SIZE]; int Prev[ULZ_WINDOW_SIZE]; } ULZ_WORKMEM; // Utils static inline uint16_t UnalignedLoad16(const void* p) { return *(const uint16_t*)(p); } static inline uint32_t UnalignedLoad32(const void* p) { return *(const uint32_t*)(p); } static inline void UnalignedStore16(void* p, uint16_t x) { *(uint16_t*)(p)=x; } static inline void UnalignedCopy64(void* d, const void* s) { *(uint64_t*)(d)=*(const uint64_t*)(s); } static inline void WildCopy(uint8_t* d, const uint8_t* s, int n) { UnalignedCopy64(d, s); for (int i=8; i<n; i+=8) UnalignedCopy64(d+i, s+i); } static inline uint32_t Hash32(const void* p) { return (UnalignedLoad32(p)*0x9E3779B9)>>(32-ULZ_HASH_BITS); } static inline void EncodeMod(uint8_t** p, uint32_t x) { while (x>=128) { x-=128; *(*p)++=128+(x&127); x>>=7; } *(*p)++=x; } static inline uint32_t DecodeMod(const uint8_t** p) { uint32_t x=0; for (int i=0; i<=21; i+=7) { const uint32_t c=*(*p)++; x+=c<<i; if (c<128) break; } return x; } // LZ77 static int UlzCompressFast(const uint8_t* in, int inlen, uint8_t* out, int outlen) { ULZ_WORKMEM *u =(ULZ_WORKMEM*)ULZ_REALLOC(0, sizeof(ULZ_WORKMEM)); for (int i=0; i<ULZ_HASH_SIZE; ++i) u->HashTable[i]=ULZ_NIL; uint8_t* op=out; int anchor=0; int p=0; while (p<inlen) { int best_len=0; int dist=0; const int max_match=inlen-p; if (max_match>=ULZ_MIN_MATCH) { const int limit=(p-ULZ_WINDOW_SIZE) > ULZ_NIL ? (p-ULZ_WINDOW_SIZE) : ULZ_NIL; const uint32_t h=Hash32(&in[p]); int s=u->HashTable[h]; u->HashTable[h]=p; if (s>limit && UnalignedLoad32(&in[s])==UnalignedLoad32(&in[p])) { int len=ULZ_MIN_MATCH; while (len<max_match && in[s+len]==in[p+len]) ++len; best_len=len; dist=p-s; } } if (best_len==ULZ_MIN_MATCH && (p-anchor)>=(7+128)) best_len=0; if (best_len>=ULZ_MIN_MATCH) { const int len=best_len-ULZ_MIN_MATCH; const int token=((dist>>12)&16)+(len < 15 ? len : 15); if (anchor!=p) { const int run=p-anchor; if (run>=7) { *op++=(7<<5)+token; EncodeMod(&op, run-7); } else *op++=(run<<5)+token; WildCopy(op, &in[anchor], run); op+=run; } else *op++=token; if (len>=15) EncodeMod(&op, len-15); UnalignedStore16(op, dist); op+=2; anchor=p+best_len; ++p; u->HashTable[Hash32(&in[p])]=p++; u->HashTable[Hash32(&in[p])]=p++; u->HashTable[Hash32(&in[p])]=p++; p=anchor; } else ++p; } if (anchor!=p) { const int run=p-anchor; if (run>=7) { *op++=7<<5; EncodeMod(&op, run-7); } else *op++=run<<5; WildCopy(op, &in[anchor], run); op+=run; } ULZ_REALLOC(u, 0); return op-out; } static int UlzCompress(const uint8_t* in, int inlen, uint8_t* out, int outlen, int level) { if (level<1 || level>9) return 0; const int max_chain=(level<9)?1<<level:1<<13; ULZ_WORKMEM *u = (ULZ_WORKMEM*)ULZ_REALLOC(0, sizeof(ULZ_WORKMEM)); for (int i=0; i<ULZ_HASH_SIZE; ++i) u->HashTable[i]=ULZ_NIL; uint8_t* op=out; int anchor=0; int p=0; while (p<inlen) { int best_len=0; int dist=0; const int max_match=inlen-p; if (max_match>=ULZ_MIN_MATCH) { const int limit=(p-ULZ_WINDOW_SIZE) > ULZ_NIL ? (p-ULZ_WINDOW_SIZE) : ULZ_NIL; int chainlen=max_chain; int s=u->HashTable[Hash32(&in[p])]; while (s>limit) { if (in[s+best_len]==in[p+best_len] && UnalignedLoad32(&in[s])==UnalignedLoad32(&in[p])) { int len=ULZ_MIN_MATCH; while (len<max_match && in[s+len]==in[p+len]) ++len; if (len>best_len) { best_len=len; dist=p-s; if (len==max_match) break; } } if (--chainlen==0) break; s=u->Prev[s&ULZ_WINDOW_MASK]; } } if (best_len==ULZ_MIN_MATCH && (p-anchor)>=(7+128)) best_len=0; if (level>=5 && best_len>=ULZ_MIN_MATCH && best_len<max_match && (p-anchor)!=6) { const int x=p+1; const int target_len=best_len+1; const int limit=(x-ULZ_WINDOW_SIZE) > ULZ_NIL ? (x-ULZ_WINDOW_SIZE) : ULZ_NIL; int chainlen=max_chain; int s=u->HashTable[Hash32(&in[x])]; while (s>limit) { if (in[s+best_len]==in[x+best_len] && UnalignedLoad32(&in[s])==UnalignedLoad32(&in[x])) { int len=ULZ_MIN_MATCH; while (len<target_len && in[s+len]==in[x+len]) ++len; if (len==target_len) { best_len=0; break; } } if (--chainlen==0) break; s=u->Prev[s&ULZ_WINDOW_MASK]; } } if (best_len>=ULZ_MIN_MATCH) { const int len=best_len-ULZ_MIN_MATCH; const int token=((dist>>12)&16)+(len < 15 ? len : 15); if (anchor!=p) { const int run=p-anchor; if (run>=7) { *op++=(7<<5)+token; EncodeMod(&op, run-7); } else *op++=(run<<5)+token; WildCopy(op, &in[anchor], run); op+=run; } else *op++=token; if (len>=15) EncodeMod(&op, len-15); UnalignedStore16(op, dist); op+=2; while (best_len--!=0) { const uint32_t h=Hash32(&in[p]); u->Prev[p&ULZ_WINDOW_MASK]=u->HashTable[h]; u->HashTable[h]=p++; } anchor=p; } else { const uint32_t h=Hash32(&in[p]); u->Prev[p&ULZ_WINDOW_MASK]=u->HashTable[h]; u->HashTable[h]=p++; } } if (anchor!=p) { const int run=p-anchor; if (run>=7) { *op++=7<<5; EncodeMod(&op, run-7); } else *op++=run<<5; WildCopy(op, &in[anchor], run); op+=run; } ULZ_REALLOC(u, 0); return op-out; } static int UlzDecompress(const uint8_t* in, int inlen, uint8_t* out, int outlen) { uint8_t* op=out; const uint8_t* ip=in; const uint8_t* ip_end=ip+inlen; const uint8_t* op_end=op+outlen; while (ip<ip_end) { const int token=*ip++; if (token>=32) { int run=token>>5; if (run==7) run+=DecodeMod(&ip); if ((op_end-op)<run || (ip_end-ip)<run) // Overrun check return 0; WildCopy(op, ip, run); op+=run; ip+=run; if (ip>=ip_end) break; } int len=(token&15)+ULZ_MIN_MATCH; if (len==(15+ULZ_MIN_MATCH)) len+=DecodeMod(&ip); if ((op_end-op)<len) // Overrun check return 0; const int dist=((token&16)<<12)+UnalignedLoad16(ip); ip+=2; uint8_t* cp=op-dist; if ((op-out)<dist) // Range check return 0; if (dist>=8) { WildCopy(op, cp, len); op+=len; } else { *op++=*cp++; *op++=*cp++; *op++=*cp++; *op++=*cp++; while (len--!=4) *op++=*cp++; } } return (ip==ip_end)?op-out:0; } unsigned ulz_encode(const void *in, unsigned inlen, void *out, unsigned outlen, unsigned flags) { int level = flags > 9 ? 9 : flags < 0 ? 0 : flags; // [0..(6)..9] int rc = level ? UlzCompress((uint8_t *)in, (int)inlen, (uint8_t *)out, (int)outlen, level) : UlzCompressFast((uint8_t *)in, (int)inlen, (uint8_t *)out, (int)outlen); return (unsigned)rc; } unsigned ulz_decode(const void *in, unsigned inlen, void *out, unsigned outlen) { return (unsigned)UlzDecompress((uint8_t *)in, (int)inlen, (uint8_t *)out, (int)outlen); } unsigned ulz_bounds(unsigned inlen, unsigned flags) { return (unsigned)(inlen + inlen/255 + 16); } unsigned ulz_excess(unsigned flags) { return (unsigned)(ULZ_EXCESS); } #endif // ULZ_C #ifdef ULZ_DEMO #pragma once #include <stdio.h> int main() { const char *longcopy = "Hello world! Hello world! Hello world! Hello world!"; int level=1; char out[128]; size_t outlen = ulz_encode(longcopy, strlen(longcopy)+1, out, 128, level); printf("%s %d->%d\n", outlen ? "ok" : "fail", (int)strlen(longcopy)+1, (int)outlen); char redo[128]; size_t unpacked = ulz_decode(out, outlen, redo, 128); printf("%d->%d %s\n", (int)outlen, (int)unpacked, redo); } #define main main__ #endif // ULZ_DEMO //#line 1 "amalgamated_pack.c" #ifdef COMPRESS_C #pragma once #include <stdio.h> #ifdef _MSC_VER # define ftello64 _ftelli64 #elif !defined __GNUC__ # define ftello64 ftell #endif #include <stdlib.h> #include <stdint.h> #include <time.h> static struct compressor { // id of compressor unsigned enumerator; // name of compressor const char name1, *name4, *name; // returns worst case compression estimation for selected flags unsigned (*bounds)(unsigned bytes, unsigned flags); // returns number of bytes written. 0 if error. unsigned (*encode)(const void *in, unsigned inlen, void *out, unsigned outcap, unsigned flags); // returns number of excess bytes that will be overwritten when decoding. unsigned (*excess)(unsigned flags); // returns number of bytes written. 0 if error. unsigned (*decode)(const void *in, unsigned inlen, void *out, unsigned outcap); } list[] = { { RAW, '0', "raw", "raw", raw_bounds, raw_encode, raw_excess, raw_decode }, { PPP, 'p', "ppp", "ppp", ppp_bounds, ppp_encode, ppp_excess, ppp_decode }, { ULZ, 'u', "ulz", "ulz", ulz_bounds, ulz_encode, ulz_excess, ulz_decode }, { LZ4X, '4', "lz4x", "lz4x", lz4x_bounds, lz4x_encode, lz4x_excess, lz4x_decode }, { CRSH, 'c', "crsh", "crush", crush_bounds, crush_encode, crush_excess, crush_decode }, { DEFL, 'd', "defl", "deflate", deflate_bounds, deflate_encode, deflate_excess, deflate_decode }, { LZP1, '1', "lzp1", "lzp1", lzp1_bounds, lzp1_encode, lzp1_excess, lzp1_decode }, { LZMA, 'm', "lzma", "lzma", lzma_bounds, lzma_encode, lzma_excess, lzma_decode }, { BALZ, 'b', "balz", "balz", balz_bounds, balz_encode, balz_excess, balz_decode }, { LZW3, 'w', "lzw3", "lzrw3a", lzrw3a_bounds, lzrw3a_encode, lzrw3a_excess, lzrw3a_decode }, { LZSS, 's', "lzss", "lzss", lzss_bounds, lzss_encode, lzss_excess, lzss_decode }, { BCM, 'B', "bcm", "bcm", bcm_bounds, bcm_encode, bcm_excess, bcm_decode }, }; char *arc_nameof(unsigned flags) { static __thread char buf[16]; snprintf(buf, 16, "%4s.%c", list[(flags>>4)&0x0F].name4, "0123456789ABCDEF"[flags&0xF]); return buf; } unsigned mem_encode(const void *in, unsigned inlen, void *out, unsigned outlen, unsigned compressor) { *(uint8_t*)out = compressor & 0xff; unsigned ret = list[(compressor >> 4) % NUM_PACKESSORS].encode(in, inlen, (uint8_t*)out+1, outlen-1, compressor & 0x0F); return ret ? ret+1 : 0; } unsigned mem_decode(const void *in, unsigned inlen, void *out, unsigned outlen) { unsigned compressor = *(uint8_t*)in; return list[(compressor >> 4) % NUM_PACKESSORS].decode((uint8_t*)in+1, inlen-1, out, outlen); } unsigned mem_bounds(unsigned inlen, unsigned compressor) { return 1 + list[(compressor >> 4) % NUM_PACKESSORS].bounds(inlen, compressor & 0x0F); } unsigned mem_excess(unsigned compressor) { return list[(compressor >> 4) % NUM_PACKESSORS].excess(compressor & 0x0F); } // --- // file options static uint8_t COMPRESS_FILE_BLOCK_SIZE = 23; // 2<<(BS+12) = { 8K..256M } static uint8_t COMPRESS_FILE_BLOCK_EXCESS = 0; // 16<<BE = 16, 256, 4K, 64K (16 for ulz, 256 for lpz1) // xx yy zzzz : 8 bits // xx : reserved (default = 0x11) // yy : block excess [00..03] = 16<<X = { 16, 256, 4K, 64K } // zzzz : block size [00..15] = 2<<(X+13) = { 8K..256M } unsigned file_encode(FILE* in, FILE* out, FILE *logfile, unsigned cnum, unsigned *clist) { // multi encoder #if 0 // uint8_t MAGIC = 0x11 << 6 | ((COMPRESS_FILE_BLOCK_EXCESS&3) << 4) | ((COMPRESS_FILE_BLOCK_SIZE-12)&15); // EXCESS = 16ull << ((MAGIC >> 4) & 3); // BLSIZE = 1ull << ((MAGIC & 15) + 13); #else if( fwrite(&COMPRESS_FILE_BLOCK_SIZE, 1,1, out) < 1) return 0; if( fwrite(&COMPRESS_FILE_BLOCK_EXCESS, 1,1, out) < 1) return 0; uint64_t BS_BYTES = 1ull << COMPRESS_FILE_BLOCK_SIZE; uint64_t BE_BYTES = 1ull << COMPRESS_FILE_BLOCK_EXCESS; #endif uint64_t total_in = 0, total_out = 0; uint8_t *inbuf, *outbuf[2]; inbuf=(uint8_t*)REALLOC(0, BS_BYTES+BE_BYTES); outbuf[0]=(uint8_t*)REALLOC(0, BS_BYTES*1.1+BE_BYTES); outbuf[1]=(uint8_t*)(cnum > 1 ? REALLOC(0, BS_BYTES*1.1+BE_BYTES) : 0); enum { BLOCK_PREVIEW_CHARS = 8 }; char best_compressors_history[BLOCK_PREVIEW_CHARS+1] = {0}, best_compressors_index = BLOCK_PREVIEW_CHARS-1; uint8_t best = 0; clock_t tm = {0}; double enctime = 0; if( logfile ) tm = clock(); { for( uint32_t inlen; (inlen=fread(inbuf, 1, BS_BYTES, in)) > 0 ; ) { uint32_t outlen[2] = {0}; best = clist[0]; for(unsigned i = 0; i < cnum; ++i) { unsigned compr = clist[i] >> 4; unsigned flags = clist[i] & 15; if(logfile) fprintf(logfile, "\r%11lld -> %11lld %4s.%c %s", (int64_t)(total_in+inlen), (int64_t)outlen[0], list[compr].name4, "0123456789ABCDEF"[flags], best_compressors_history); outlen[!!i] = list[compr].encode(inbuf, (unsigned)inlen, outbuf[!!i], BS_BYTES, flags); if(!outlen[!!i]) goto fail; if( i && outlen[1] < outlen[0]) { best = clist[i]; outlen[0] = outlen[1]; uint8_t *swap = outbuf[0]; outbuf[0] = outbuf[1]; outbuf[1] = swap; } if(logfile) fprintf(logfile, "\r%11lld -> %11lld %4s.%c %s", (int64_t)(total_in+inlen), (int64_t)outlen[0], list[compr].name4, "0123456789ABCDEF"[flags], best_compressors_history); } uint64_t final = 4 + 1 + outlen[0]; // sizeof(outlen[0]) + sizeof(compressor) + compr data double ratio = final * 100.0 / (inlen ? inlen : 1); if(!(ratio < 97 /* && ((outlen[0] - inlen) >= 64*1024) */ )) best = 0; unsigned compr = best >> 4; unsigned flags = best & 15; if( compr ) { uint8_t packer = (compr << 4) | flags; // store block length + compressor + compr data if( fwrite(&outlen[0], 1, 4, out) != 4 ) goto fail; if( fwrite(&packer, 1, 1, out) != 1 ) goto fail; if( fwrite(outbuf[0], 1, outlen[0], out) != outlen[0] ) goto fail; } else { uint8_t packer = 0; // store block length + no-compressor + raw data if( fwrite(&inlen, 1, 4, out) != 4 ) goto fail; if( fwrite(&packer, 1, 1, out) != 1 ) goto fail; if( fwrite(inbuf, 1, inlen, out) != inlen ) goto fail; } total_in += inlen; total_out += 4 + 1 + (best ? outlen[0] : inlen); best_compressors_index = (best_compressors_index+1) % BLOCK_PREVIEW_CHARS; best_compressors_history[best_compressors_index] = list[compr].name1; best_compressors_history[best_compressors_index+1] = 0; } } if( logfile ) enctime = (clock() - tm) / (double)CLOCKS_PER_SEC; if( logfile ) { double ratio = (total_out - 4 - 1) * 100.0 / (total_in ? total_in : 1); fprintf(logfile, "\r%11lld -> %11lld %4s.%c %5.*f%% c:%.*fs ", total_in, total_out - 4 - 1, list[best>>4].name4, "0123456789ABCDEF"[best&15], ratio >= 100 ? 1 : 2, ratio, enctime > 99 ? 1 : enctime > 9 ? 2 : 3, enctime); } pass: goto next; fail: total_out = 0; next: REALLOC( outbuf[1], 0 ); REALLOC( outbuf[0], 0 ); REALLOC( inbuf, 0 ); return (unsigned)total_out; } unsigned file_decode(FILE* in, FILE* out, FILE *logfile) { // multi decoder uint8_t block8; if( fread(&block8, 1,1, in ) < 1 ) return 0; uint8_t excess8; if( fread(&excess8, 1,1, in ) < 1 ) return 0; uint64_t BLOCK_SIZE = 1ull << block8; uint64_t EXCESS = 1ull << excess8; unsigned total = 0, outlen; uint8_t* inbuf=(uint8_t*)REALLOC(0, BLOCK_SIZE+EXCESS); uint8_t* outbuf=(uint8_t*)REALLOC(0, BLOCK_SIZE+EXCESS); clock_t tm = {0}; double dectime = 0; if(logfile) tm = clock(); { for(uint32_t inlen=0, loop=0;fread(&inlen, 1, sizeof(inlen), in)>0;++loop) { if (inlen>(BLOCK_SIZE+EXCESS)) goto fail; uint8_t packer; if( fread(&packer, 1,sizeof(packer), in) <= 0 ) goto fail; if(packer) { // read compressed if (fread(inbuf, 1, inlen, in)!=inlen) goto fail; // decompress uint8_t compressor = packer >> 4; outlen=list[compressor % NUM_PACKESSORS].decode(inbuf, (unsigned)inlen, outbuf, BLOCK_SIZE); if (!outlen) goto fail; } else { // read raw if (fread(outbuf, 1, inlen, in)!=inlen) goto fail; outlen=inlen; } if (fwrite(outbuf, 1, outlen, out) != outlen) { perror("fwrite() failed"); goto fail; } total += outlen; if( logfile ) fprintf(logfile, "%c\b", "\\|/-"[loop&3] ); } } if( logfile ) dectime = (clock() - tm) / (double)CLOCKS_PER_SEC; if( logfile ) fprintf(logfile, "d:%.*fs ", dectime > 99 ? 1 : dectime > 9 ? 2 : 3, dectime ); pass: goto next; fail: total = 0; next: REALLOC( outbuf, 0 ); REALLOC( inbuf, 0 ); return total; } #endif // COMPRESS_C
rawSHA1_ng_fmt_plug.c
// // Alternative SSE2 optimised raw SHA-1 implementation for John The Ripper. // // This plugin requires -msse4 in CFLAGS. // // Copyright (C) 2012 Tavis Ormandy <taviso@cmpxchg8b.com> // Copyright (c) 2015 magnum (AVX2/AVX512 support) // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This 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 // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the // Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, // Boston, MA 02110-1301, USA. // #include "arch.h" #if defined(SIMD_COEF_32) && (SIMD_COEF_32 < 16 || ARCH_BITS >= 64) && !_MSC_VER && !__ARM_NEON #if FMT_EXTERNS_H extern struct fmt_main fmt_sha1_ng; #elif FMT_REGISTERS_H john_register_one(&fmt_sha1_ng); #else #include "misc.h" #if !defined(DEBUG) && !defined(WITH_ASAN) // These compilers claim to be __GNUC__ but warn on gcc pragmas. #if __GNUC__ && !__INTEL_COMPILER && !__clang__ && !__llvm__ && !_MSC_VER #pragma GCC optimize 3 #pragma GCC optimize "-fprefetch-loop-arrays" #endif #endif #ifndef _GNU_SOURCE #define _GNU_SOURCE 1 #endif #include <string.h> #if !FAST_FORMATS_OMP #undef _OPENMP #elif _OPENMP #include <omp.h> #endif #include "stdbool.h" #include "stdint.h" #if SIMD_COEF_32 > 8 #include "int128.h" #endif #include "pseudo_intrinsics.h" #include "stdint.h" #include "params.h" #include "formats.h" #include "memory.h" #include "sha.h" #include "johnswap.h" #include "aligned.h" #include "rawSHA1_common.h" #include "memdbg.h" #define VWIDTH SIMD_COEF_32 #define SHA1_BLOCK_SIZE 64 #define SHA1_BLOCK_WORDS 16 #define SHA1_DIGEST_SIZE 20 #define SHA1_DIGEST_WORDS 5 #define SHA1_PARALLEL_HASH 512 // This must be a multiple of max VWIDTH. #ifdef __MIC__ #ifndef OMP_SCALE #define OMP_SCALE 128 #endif #else #ifndef OMP_SCALE #define OMP_SCALE 2048 // Multiplier to hide OMP overhead #endif #endif #define X(X0, X2, X8, X13) do { \ X0 = vxor(X0, X8); \ X0 = vxor(X0, X13); \ X0 = vxor(X0, X2); \ X0 = vroti_epi32(X0, 1); \ } while (false) #define R1(W, A, B, C, D, E) do { \ E = vadd_epi32(E, K); \ E = vadd_epi32(E, vcmov(C, D, B)); \ E = vadd_epi32(E, W); \ B = vroti_epi32(B, 30); \ E = vadd_epi32(E, vroti_epi32(A, 5)); \ } while (false) #define R2(W, A, B, C, D, E) do { \ E = vadd_epi32(E, K); \ E = vadd_epi32(E, vxor(vxor(B, C), D)); \ E = vadd_epi32(E, W); \ B = vroti_epi32(B, 30); \ E = vadd_epi32(E, vroti_epi32(A, 5)); \ } while (false) #define R4(W, A, B, C, D, E) do { \ E = vadd_epi32(E, K); \ E = vadd_epi32(E, vxor(vxor(B, C), D)); \ E = vadd_epi32(E, W); \ E = vadd_epi32(E, vroti_epi32(A, 5)); \ } while (false) #if !VCMOV_EMULATED #define R3(W, A, B, C, D, E) do { \ E = vadd_epi32(E, K); \ E = vadd_epi32(E, vcmov(D, B, vxor(C, B))); \ E = vadd_epi32(E, W); \ B = vroti_epi32(B, 30); \ E = vadd_epi32(E, vroti_epi32(A, 5)); \ } while (false) #else #define R3(W, A, B, C, D, E) do { \ E = vadd_epi32(E, K); \ E = vadd_epi32(E, vor(vand(D, B), vand(vor(D, B), C))); \ E = vadd_epi32(E, W); \ B = vroti_epi32(B, 30); \ E = vadd_epi32(E, vroti_epi32(A, 5)); \ } while (false) #endif #if SIMD_COEF_32 == 4 // Not used for AVX2 and better, which has gather instructions. #define _MM_TRANSPOSE4_EPI32(R0, R1, R2, R3) do {\ vtype T0, T1, T2, T3; \ T0 = vunpacklo_epi32(R0, R1); \ T1 = vunpacklo_epi32(R2, R3); \ T2 = vunpackhi_epi32(R0, R1); \ T3 = vunpackhi_epi32(R2, R3); \ R0 = vunpacklo_epi64(T0, T1); \ R1 = vunpackhi_epi64(T0, T1); \ R2 = vunpacklo_epi64(T2, T3); \ R3 = vunpackhi_epi64(T2, T3); \ } while (false) #endif // M and N contain the first and last 128bits of a 512bit SHA-1 message block // respectively. The remaining 256bits are always zero, and so are not stored // here to avoid the load overhead. // For AVX2, we have half a block and for AVX512/MIC we actually have a full // block. static uint32_t (*M)[VWIDTH]; static uint32_t *N; // MD contains the state of the SHA-1 A register at R75 for each of the input // messages. static uint32_t *MD; /* unused static inline uint32_t __attribute__((const)) rotateright(uint32_t value, uint8_t count) { register uint32_t result; asm("ror %%cl, %0" : "=r" (result) : "0" (value), "c" (count)); return result; } */ static inline uint32_t __attribute__((const)) rotateleft(uint32_t value, uint8_t count) { register uint32_t result; #if (__MINGW32__ || __MINGW64__) && __STRICT_ANSI__ result = _rotl(value, count); //((value<<count)|((ARCH_WORD_32)value>>(32-count))); #elif __i386__ || __x86_64__ asm("rol %%cl, %0" : "=r" (result) : "0" (value), "c" (count)); #else // assume count <= 32 result = (value << count) | (value >> (32 - count)); #endif return result; } // GCC < 4.3 does not have __builtin_bswap32(), provide an alternative. #if !__INTEL_COMPILER && GCC_VERSION < 40300 #define __builtin_bswap32 bswap32 static inline uint32_t __attribute__((const)) bswap32(uint32_t value) { register uint32_t result; #if (__MINGW32__ || __MINGW64__) && __STRICT_ANSI__ result = _byteswap_ulong(value); #elif __i386 || __x86_64__ asm("bswap %0" : "=r" (result) : "0" (value)); #else result = (value << 24) | ((value << 8) & 0xFF0000) | (value >> 24) | ((value >> 8) & 0xFF00); #endif return result; } #endif static void sha1_fmt_init(struct fmt_main *self) { #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; #endif M = mem_calloc_align(self->params.max_keys_per_crypt, sizeof(*M), MEM_ALIGN_CACHE); N = mem_calloc_align(self->params.max_keys_per_crypt, sizeof(*N), MEM_ALIGN_CACHE); MD = mem_calloc_align(self->params.max_keys_per_crypt, sizeof(*MD), MEM_ALIGN_CACHE); } static void done(void) { MEM_FREE(MD); MEM_FREE(N); MEM_FREE(M); } static void *sha1_fmt_binary(char *ciphertext) { // Static buffer storing the binary representation of ciphertext. static union { uint32_t w[SHA1_DIGEST_WORDS]; vtype v; } result; uint32_t a75; // Convert ascii representation into binary. memcpy(result.w, rawsha1_common_get_binary(ciphertext), 20); // One preprocessing step, if we calculate E80 rol 2 here, we // can compare it against A75 and save 5 rounds in crypt_all(). a75 = rotateleft(__builtin_bswap32(result.w[4]) - 0xC3D2E1F0, 2); // Fill the vector with it, so we can do a vectorized compare result.v = vset1_epi32(a75); return result.w; } // This function is called when John wants us to buffer a crypt() operation // on the specified key. We also preprocess it for SHA-1 as we load it. // // This implementation is hardcoded to only accept passwords under 15 // characters. This is because we can create a new message block in just two // MOVDQA instructions (we need 15 instead of 16 because we must append a bit // to the message). For AVX2 it's 31 characters and for AVX-512+ it's 125. // // This routine assumes that key is not on an unmapped page boundary, but // doesn't require it to be 16 byte aligned (although that would be nice). static void sha1_fmt_set_key(char *key, int index) { vtype Z = vsetzero(); vtype X = vloadu(key); vtype B; // First, find the length of the key by scanning for a zero byte. #if (__AVX512F__ && !__AVX512BW__) || __MIC__ || __ALTIVEC__ || __ARM_NEON uint32_t len = strlen(key); #else // FIXME: even uint64_t won't be long enough for AVX-1024 uint64_t mask = vcmpeq_epi8_mask(X, Z); uint32_t len = __builtin_ctzl(mask); #endif // Create a lookup tables to find correct masks for each supported input // length. It would be nice if we could use bit shifts to produce these // dynamically, but they require an immediate operand. #if VWIDTH > 8 // FIXME: a problem with using int128 here is it won't work at // all for 32-bit builds - but that may be academic. #define XX ((((uint128_t)0xFFFFFFFFFFFFFFFFULL)<<64) + 0xFFFFFFFFFFFFFFFFULL) #define YY ((uint128_t)0x80) #define ZZ ((uint128_t)0x0) static const JTR_ALIGN(MEM_ALIGN_SIMD) uint128_t kTrailingBitTable[][4] = { {YY<< 0, ZZ, ZZ, ZZ}, {YY<< 8, ZZ, ZZ, ZZ}, {YY<< 16, ZZ, ZZ, ZZ}, {YY<< 24, ZZ, ZZ, ZZ}, {YY<< 32, ZZ, ZZ, ZZ}, {YY<< 40, ZZ, ZZ, ZZ}, {YY<< 48, ZZ, ZZ, ZZ}, {YY<< 56, ZZ, ZZ, ZZ}, {YY<< 64, ZZ, ZZ, ZZ}, {YY<< 72, ZZ, ZZ, ZZ}, {YY<< 80, ZZ, ZZ, ZZ}, {YY<< 88, ZZ, ZZ, ZZ}, {YY<< 96, ZZ, ZZ, ZZ}, {YY<<104, ZZ, ZZ, ZZ}, {YY<<112, ZZ, ZZ, ZZ}, {YY<<120, ZZ, ZZ, ZZ}, {ZZ, YY<< 0, ZZ, ZZ}, {ZZ, YY<< 8, ZZ, ZZ}, {ZZ, YY<< 16, ZZ, ZZ}, {ZZ, YY<< 24, ZZ, ZZ}, {ZZ, YY<< 32, ZZ, ZZ}, {ZZ, YY<< 40, ZZ, ZZ}, {ZZ, YY<< 48, ZZ, ZZ}, {ZZ, YY<< 56, ZZ, ZZ}, {ZZ, YY<< 64, ZZ, ZZ}, {ZZ, YY<< 72, ZZ, ZZ}, {ZZ, YY<< 80, ZZ, ZZ}, {ZZ, YY<< 88, ZZ, ZZ}, {ZZ, YY<< 96, ZZ, ZZ}, {ZZ, YY<<104, ZZ, ZZ}, {ZZ, YY<<112, ZZ, ZZ}, {ZZ, YY<<120, ZZ, ZZ}, {ZZ, ZZ, YY<< 0, ZZ}, {ZZ, ZZ, YY<< 8, ZZ}, {ZZ, ZZ, YY<< 16, ZZ}, {ZZ, ZZ, YY<< 24, ZZ}, {ZZ, ZZ, YY<< 32, ZZ}, {ZZ, ZZ, YY<< 40, ZZ}, {ZZ, ZZ, YY<< 48, ZZ}, {ZZ, ZZ, YY<< 56, ZZ}, {ZZ, ZZ, YY<< 64, ZZ}, {ZZ, ZZ, YY<< 72, ZZ}, {ZZ, ZZ, YY<< 80, ZZ}, {ZZ, ZZ, YY<< 88, ZZ}, {ZZ, ZZ, YY<< 96, ZZ}, {ZZ, ZZ, YY<<104, ZZ}, {ZZ, ZZ, YY<<112, ZZ}, {ZZ, ZZ, YY<<120, ZZ}, {ZZ, ZZ, ZZ, YY<< 0}, {ZZ, ZZ, ZZ, YY<< 8}, {ZZ, ZZ, ZZ, YY<< 16}, {ZZ, ZZ, ZZ, YY<< 24}, {ZZ, ZZ, ZZ, YY<< 32}, {ZZ, ZZ, ZZ, YY<< 40}, {ZZ, ZZ, ZZ, YY<< 48}, {ZZ, ZZ, ZZ, YY<< 56}, {ZZ, ZZ, ZZ, YY<< 64}, {ZZ, ZZ, ZZ, YY<< 72}, {ZZ, ZZ, ZZ, YY<< 80}, {ZZ, ZZ, ZZ, YY<< 88}, {ZZ, ZZ, ZZ, YY<< 96}, {ZZ, ZZ, ZZ, YY<<104}, {ZZ, ZZ, ZZ, YY<<112}, {ZZ, ZZ, ZZ, YY<<120} }; static const JTR_ALIGN(MEM_ALIGN_SIMD) uint128_t kUsedBytesTable[][4] = { {XX<< 0, XX, XX, XX}, {XX<< 8, XX, XX, XX}, {XX<< 16, XX, XX, XX}, {XX<< 24, XX, XX, XX}, {XX<< 32, XX, XX, XX}, {XX<< 40, XX, XX, XX}, {XX<< 48, XX, XX, XX}, {XX<< 56, XX, XX, XX}, {XX<< 64, XX, XX, XX}, {XX<< 72, XX, XX, XX}, {XX<< 80, XX, XX, XX}, {XX<< 88, XX, XX, XX}, {XX<< 96, XX, XX, XX}, {XX<<104, XX, XX, XX}, {XX<<112, XX, XX, XX}, {XX<<120, XX, XX, XX}, {ZZ, XX<< 0, XX, XX}, {ZZ, XX<< 8, XX, XX}, {ZZ, XX<< 16, XX, XX}, {ZZ, XX<< 24, XX, XX}, {ZZ, XX<< 32, XX, XX}, {ZZ, XX<< 40, XX, XX}, {ZZ, XX<< 48, XX, XX}, {ZZ, XX<< 56, XX, XX}, {ZZ, XX<< 64, XX, XX}, {ZZ, XX<< 72, XX, XX}, {ZZ, XX<< 80, XX, XX}, {ZZ, XX<< 88, XX, XX}, {ZZ, XX<< 96, XX, XX}, {ZZ, XX<<104, XX, XX}, {ZZ, XX<<112, XX, XX}, {ZZ, XX<<120, XX, XX}, {ZZ, ZZ, XX<< 0, XX}, {ZZ, ZZ, XX<< 8, XX}, {ZZ, ZZ, XX<< 16, XX}, {ZZ, ZZ, XX<< 24, XX}, {ZZ, ZZ, XX<< 32, XX}, {ZZ, ZZ, XX<< 40, XX}, {ZZ, ZZ, XX<< 48, XX}, {ZZ, ZZ, XX<< 56, XX}, {ZZ, ZZ, XX<< 64, XX}, {ZZ, ZZ, XX<< 72, XX}, {ZZ, ZZ, XX<< 80, XX}, {ZZ, ZZ, XX<< 88, XX}, {ZZ, ZZ, XX<< 96, XX}, {ZZ, ZZ, XX<<104, XX}, {ZZ, ZZ, XX<<112, XX}, {ZZ, ZZ, XX<<120, XX}, {ZZ, ZZ, ZZ, XX<< 0}, {ZZ, ZZ, ZZ, XX<< 8}, {ZZ, ZZ, ZZ, XX<< 16}, {ZZ, ZZ, ZZ, XX<< 24}, {ZZ, ZZ, ZZ, XX<< 32}, {ZZ, ZZ, ZZ, XX<< 40}, {ZZ, ZZ, ZZ, XX<< 48}, {ZZ, ZZ, ZZ, XX<< 56}, {ZZ, ZZ, ZZ, XX<< 64}, {ZZ, ZZ, ZZ, XX<< 72}, {ZZ, ZZ, ZZ, XX<< 80}, {ZZ, ZZ, ZZ, XX<< 88}, {ZZ, ZZ, ZZ, XX<< 96}, {ZZ, ZZ, ZZ, XX<<104}, {ZZ, ZZ, ZZ, XX<<112}, {ZZ, ZZ, ZZ, XX<<120} }; #elif VWIDTH > 4 static const JTR_ALIGN(MEM_ALIGN_SIMD) uint32_t kTrailingBitTable[][8] = { { 0x00000080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00008000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00800000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x80000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00008000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00800000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x80000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00008000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00800000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x80000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000080, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00008000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00800000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x80000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000080, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00008000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00800000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x80000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000080, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00008000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00800000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x80000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000080, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00008000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00800000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x80000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000080 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00008000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00800000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x80000000 }, }; static const JTR_ALIGN(MEM_ALIGN_SIMD) uint32_t kUsedBytesTable[][8] = { { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0xFFFFFF00, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0xFFFF0000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0xFFFFFF00, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0xFFFF0000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0xFFFFFF00, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0xFFFF0000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0xFFFFFF00, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0xFFFF0000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFFFF00, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFF0000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFFFF00, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFF0000, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFFFF00, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFF0000, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFF000000, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFFFF00 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFF0000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFF000000 }, }; #else static const JTR_ALIGN(MEM_ALIGN_SIMD) uint32_t kTrailingBitTable[][4] = { { 0x00000080, 0x00000000, 0x00000000, 0x00000000 }, { 0x00008000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00800000, 0x00000000, 0x00000000, 0x00000000 }, { 0x80000000, 0x00000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000080, 0x00000000, 0x00000000 }, { 0x00000000, 0x00008000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00800000, 0x00000000, 0x00000000 }, { 0x00000000, 0x80000000, 0x00000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000080, 0x00000000 }, { 0x00000000, 0x00000000, 0x00008000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00800000, 0x00000000 }, { 0x00000000, 0x00000000, 0x80000000, 0x00000000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00000080 }, { 0x00000000, 0x00000000, 0x00000000, 0x00008000 }, { 0x00000000, 0x00000000, 0x00000000, 0x00800000 }, { 0x00000000, 0x00000000, 0x00000000, 0x80000000 }, }; static const JTR_ALIGN(MEM_ALIGN_SIMD) uint32_t kUsedBytesTable[][4] = { { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0xFFFFFF00, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0xFFFF0000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0xFFFFFF00, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0xFFFF0000, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0xFF000000, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0xFFFFFF00, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0xFFFF0000, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0xFF000000, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0xFFFFFFFF }, { 0x00000000, 0x00000000, 0x00000000, 0xFFFFFF00 }, { 0x00000000, 0x00000000, 0x00000000, 0xFFFF0000 }, { 0x00000000, 0x00000000, 0x00000000, 0xFF000000 }, }; #endif N[index] = len; // Zero out the rest of the DQWORD in X by making a suitable mask. Z = vload(kUsedBytesTable[len]); // Find the correct position for the trailing bit required by SHA-1. B = vload(kTrailingBitTable[len]); // Now we have this: // B = 00 00 00 00 00 80 00 00 00 00 00 00 00 00 00 // Z = 00 00 00 00 00 ff ff ff ff ff ff ff ff ff ff // X = 41 41 41 41 41 00 12 34 56 78 12 34 56 78 9A // <---------------> <------------------------> // key bytes w/nul junk from stack. // Use PANDN to apply the mask, then POR to append the trailing bit // required by SHA-1, which leaves us with this: // X = 41 41 41 41 41 80 00 00 00 00 00 00 00 00 00 X = vor(vandnot(Z, X), B); // SHA-1 requires us to byte swap all the 32bit words in the message, which // we do here. // X = 40 41 42 44 45 80 00 00 00 00 00 00 00 00 00 // What we have. // X = 44 42 41 40 00 00 80 45 00 00 00 00 00 00 00 // What we want. vswap32(X); // Store the result into the message buffer. vstore(&M[index], X); return; } static char *sha1_fmt_get_key(int index) { static uint32_t key[VWIDTH + 1]; int i; // This function is not hot, we can do this slowly. First, restore // endianness. for (i = 0; i < SIMD_COEF_32; i++) key[i] = __builtin_bswap32(M[index][i]); // Skip backwards until we hit the trailing bit, then remove it. memset(strrchr((char*)(key), 0x80), 0x00, 1); return (char*) key; } static int sha1_fmt_crypt_all(int *pcount, struct db_salt *salt) { uint32_t i; // Fetch crypt count from john. const int32_t count = *pcount; // To reduce the overhead of multiple function calls, we buffer lots of // passwords, and then hash them in multiples of VWIDTH all at once. #ifdef _OPENMP #pragma omp parallel for #endif for (i = 0; i < count; i += VWIDTH) { vtype W[SHA1_BLOCK_WORDS]; vtype A, B, C, D, E; vtype K; #if __AVX512F__ || __MIC__ const vtype indices = vset_epi32(15<<4,14<<4,13<<4,12<<4, 11<<4,10<<4, 9<<4, 8<<4, 7<<4, 6<<4, 5<<4, 4<<4, 3<<4, 2<<4, 1<<4, 0<<4); #elif __AVX2__ const vtype indices = vset_epi32( 7<<3, 6<<3, 5<<3, 4<<3, 3<<3, 2<<3, 1<<3, 0<<3); #endif #if __AVX2__ || __MIC__ // Gather the message right into place. uint32_t j; for (j = 0; j < VWIDTH; ++j) W[j] = vgather_epi32(&M[i][j], indices, sizeof(uint32_t)); #else // AVX has no gather instructions, so load and transpose. W[0] = vload(&M[i + 0]); W[1] = vload(&M[i + 1]); W[2] = vload(&M[i + 2]); W[3] = vload(&M[i + 3]); _MM_TRANSPOSE4_EPI32(W[0], W[1], W[2], W[3]); #endif A = vset1_epi32(0x67452301); B = vset1_epi32(0xEFCDAB89); C = vset1_epi32(0x98BADCFE); D = vset1_epi32(0x10325476); E = vset1_epi32(0xC3D2E1F0); K = vset1_epi32(0x5A827999); R1(W[0], A, B, C, D, E); R1(W[1], E, A, B, C, D); R1(W[2], D, E, A, B, C); #if VWIDTH > 4 R1(W[3], C, D, E, A, B); R1(W[4], B, C, D, E, A); R1(W[5], A, B, C, D, E); // 5 R1(W[6], E, A, B, C, D); #else R1(W[3], C, D, E, A, B); W[4] = vsetzero(); R1(W[4], B, C, D, E, A); W[5] = vsetzero(); R1(W[5], A, B, C, D, E); W[6] = vsetzero(); // 5 R1(W[6], E, A, B, C, D); W[7] = vsetzero(); #endif #if VWIDTH > 8 R1(W[7], D, E, A, B, C); R1(W[8], C, D, E, A, B); R1(W[9], B, C, D, E, A); R1(W[10], A, B, C, D, E); // 10 R1(W[11], E, A, B, C, D); R1(W[12], D, E, A, B, C); R1(W[13], C, D, E, A, B); R1(W[14], B, C, D, E, A); #else R1(W[7], D, E, A, B, C); W[8] = vsetzero(); R1(W[8], C, D, E, A, B); W[9] = vsetzero(); R1(W[9], B, C, D, E, A); W[10] = vsetzero(); R1(W[10], A, B, C, D, E); W[11] = vsetzero(); // 10 R1(W[11], E, A, B, C, D); W[12] = vsetzero(); R1(W[12], D, E, A, B, C); W[13] = vsetzero(); R1(W[13], C, D, E, A, B); W[14] = vsetzero(); R1(W[14], B, C, D, E, A); #endif // Fetch the message lengths, multiply 8 (to get the length in bits). W[15] = vslli_epi32(vload(&N[i]), 3); R1(W[15], A, B, C, D, E); // 15 X(W[0], W[2], W[8], W[13]); R1(W[0], E, A, B, C, D); X(W[1], W[3], W[9], W[14]); R1(W[1], D, E, A, B, C); X(W[2], W[4], W[10], W[15]); R1(W[2], C, D, E, A, B); X(W[3], W[5], W[11], W[0]); R1(W[3], B, C, D, E, A); K = vset1_epi32(0x6ED9EBA1); X(W[4], W[6], W[12], W[1]); R2(W[4], A, B, C, D, E); // 20 X(W[5], W[7], W[13], W[2]); R2(W[5], E, A, B, C, D); X(W[6], W[8], W[14], W[3]); R2(W[6], D, E, A, B, C); X(W[7], W[9], W[15], W[4]); R2(W[7], C, D, E, A, B); X(W[8], W[10], W[0], W[5]); R2(W[8], B, C, D, E, A); X(W[9], W[11], W[1], W[6]); R2(W[9], A, B, C, D, E); // 25 X(W[10], W[12], W[2], W[7]); R2(W[10], E, A, B, C, D); X(W[11], W[13], W[3], W[8]); R2(W[11], D, E, A, B, C); X(W[12], W[14], W[4], W[9]); R2(W[12], C, D, E, A, B); X(W[13], W[15], W[5], W[10]); R2(W[13], B, C, D, E, A); X(W[14], W[0], W[6], W[11]); R2(W[14], A, B, C, D, E); // 30 X(W[15], W[1], W[7], W[12]); R2(W[15], E, A, B, C, D); X(W[0], W[2], W[8], W[13]); R2(W[0], D, E, A, B, C); X(W[1], W[3], W[9], W[14]); R2(W[1], C, D, E, A, B); X(W[2], W[4], W[10], W[15]); R2(W[2], B, C, D, E, A); X(W[3], W[5], W[11], W[0]); R2(W[3], A, B, C, D, E); // 35 X(W[4], W[6], W[12], W[1]); R2(W[4], E, A, B, C, D); X(W[5], W[7], W[13], W[2]); R2(W[5], D, E, A, B, C); X(W[6], W[8], W[14], W[3]); R2(W[6], C, D, E, A, B); X(W[7], W[9], W[15], W[4]); R2(W[7], B, C, D, E, A); K = vset1_epi32(0x8F1BBCDC); X(W[8], W[10], W[0], W[5]); R3(W[8], A, B, C, D, E); // 40 X(W[9], W[11], W[1], W[6]); R3(W[9], E, A, B, C, D); X(W[10], W[12], W[2], W[7]); R3(W[10], D, E, A, B, C); X(W[11], W[13], W[3], W[8]); R3(W[11], C, D, E, A, B); X(W[12], W[14], W[4], W[9]); R3(W[12], B, C, D, E, A); X(W[13], W[15], W[5], W[10]); R3(W[13], A, B, C, D, E); // 45 X(W[14], W[0], W[6], W[11]); R3(W[14], E, A, B, C, D); X(W[15], W[1], W[7], W[12]); R3(W[15], D, E, A, B, C); X(W[0], W[2], W[8], W[13]); R3(W[0], C, D, E, A, B); X(W[1], W[3], W[9], W[14]); R3(W[1], B, C, D, E, A); X(W[2], W[4], W[10], W[15]); R3(W[2], A, B, C, D, E); // 50 X(W[3], W[5], W[11], W[0]); R3(W[3], E, A, B, C, D); X(W[4], W[6], W[12], W[1]); R3(W[4], D, E, A, B, C); X(W[5], W[7], W[13], W[2]); R3(W[5], C, D, E, A, B); X(W[6], W[8], W[14], W[3]); R3(W[6], B, C, D, E, A); X(W[7], W[9], W[15], W[4]); R3(W[7], A, B, C, D, E); // 55 X(W[8], W[10], W[0], W[5]); R3(W[8], E, A, B, C, D); X(W[9], W[11], W[1], W[6]); R3(W[9], D, E, A, B, C); X(W[10], W[12], W[2], W[7]); R3(W[10], C, D, E, A, B); X(W[11], W[13], W[3], W[8]); R3(W[11], B, C, D, E, A); K = vset1_epi32(0xCA62C1D6); X(W[12], W[14], W[4], W[9]); R2(W[12], A, B, C, D, E); // 60 X(W[13], W[15], W[5], W[10]); R2(W[13], E, A, B, C, D); X(W[14], W[0], W[6], W[11]); R2(W[14], D, E, A, B, C); X(W[15], W[1], W[7], W[12]); R2(W[15], C, D, E, A, B); X(W[0], W[2], W[8], W[13]); R2(W[0], B, C, D, E, A); X(W[1], W[3], W[9], W[14]); R2(W[1], A, B, C, D, E); // 65 X(W[2], W[4], W[10], W[15]); R2(W[2], E, A, B, C, D); X(W[3], W[5], W[11], W[0]); R2(W[3], D, E, A, B, C); X(W[4], W[6], W[12], W[1]); R2(W[4], C, D, E, A, B); X(W[5], W[7], W[13], W[2]); R2(W[5], B, C, D, E, A); X(W[6], W[8], W[14], W[3]); R2(W[6], A, B, C, D, E); // 70 X(W[7], W[9], W[15], W[4]); R2(W[7], E, A, B, C, D); X(W[8], W[10], W[0], W[5]); R2(W[8], D, E, A, B, C); X(W[9], W[11], W[1], W[6]); R2(W[9], C, D, E, A, B); X(W[10], W[12], W[2], W[7]); R2(W[10], B, C, D, E, A); X(W[11], W[13], W[3], W[8]); R4(W[11], A, B, C, D, E); // 75 // A75 has an interesting property, it is the first word that's (almost) // part of the final MD (E79 ror 2). The common case will be that this // doesn't match, so we stop here and save 5 rounds. // // Note that I'm using E due to displacement caused by vectorization, // this is A in standard SHA-1. vstore(&MD[i], E); } return count; } static int sha1_fmt_cmp_all(void *binary, int count) { uint32_t M; uint32_t i; vtype B; // This function is hot, we need to do this quickly. We use PCMP to find // out if any of the dwords in A75 matched E in the input hash. // First, Load the target hash into an XMM register B = vloadu(binary); M = 0; #ifdef _OPENMP #pragma omp parallel for reduction(|:M) #endif // We can test for matches 4/8 at a time. As the common case will be that // there is no match, we can avoid testing it after every compare, reducing // the number of branches. // // It's hard to convince GCC that it's safe to unroll this loop, so I've // manually unrolled it a little bit. for (i = 0; i < count; i += 64) { uint32_t R = 0; #if __AVX512F__ || __MIC__ R |= vanyeq_epi32(B, vload(&MD[i + 0])); R |= vanyeq_epi32(B, vload(&MD[i + 16])); R |= vanyeq_epi32(B, vload(&MD[i + 32])); R |= vanyeq_epi32(B, vload(&MD[i + 48])); #elif __AVX2__ R |= vanyeq_epi32(B, vload(&MD[i + 0])); R |= vanyeq_epi32(B, vload(&MD[i + 8])); R |= vanyeq_epi32(B, vload(&MD[i + 16])); R |= vanyeq_epi32(B, vload(&MD[i + 24])); R |= vanyeq_epi32(B, vload(&MD[i + 32])); R |= vanyeq_epi32(B, vload(&MD[i + 40])); R |= vanyeq_epi32(B, vload(&MD[i + 48])); R |= vanyeq_epi32(B, vload(&MD[i + 56])); #else R |= vanyeq_epi32(B, vload(&MD[i + 0])); R |= vanyeq_epi32(B, vload(&MD[i + 4])); R |= vanyeq_epi32(B, vload(&MD[i + 8])); R |= vanyeq_epi32(B, vload(&MD[i + 12])); R |= vanyeq_epi32(B, vload(&MD[i + 16])); R |= vanyeq_epi32(B, vload(&MD[i + 20])); R |= vanyeq_epi32(B, vload(&MD[i + 24])); R |= vanyeq_epi32(B, vload(&MD[i + 28])); R |= vanyeq_epi32(B, vload(&MD[i + 32])); R |= vanyeq_epi32(B, vload(&MD[i + 36])); R |= vanyeq_epi32(B, vload(&MD[i + 40])); R |= vanyeq_epi32(B, vload(&MD[i + 44])); R |= vanyeq_epi32(B, vload(&MD[i + 48])); R |= vanyeq_epi32(B, vload(&MD[i + 52])); R |= vanyeq_epi32(B, vload(&MD[i + 56])); R |= vanyeq_epi32(B, vload(&MD[i + 60])); #endif M |= R; } return M; } static inline int sha1_fmt_get_hash(int index) { return MD[index]; } static int sha1_fmt_get_hash0(int index) { return sha1_fmt_get_hash(index) & PH_MASK_0; } static int sha1_fmt_get_hash1(int index) { return sha1_fmt_get_hash(index) & PH_MASK_1; } static int sha1_fmt_get_hash2(int index) { return sha1_fmt_get_hash(index) & PH_MASK_2; } static int sha1_fmt_get_hash3(int index) { return sha1_fmt_get_hash(index) & PH_MASK_3; } static int sha1_fmt_get_hash4(int index) { return sha1_fmt_get_hash(index) & PH_MASK_4; } static int sha1_fmt_get_hash5(int index) { return sha1_fmt_get_hash(index) & PH_MASK_5; } static int sha1_fmt_get_hash6(int index) { return sha1_fmt_get_hash(index) & PH_MASK_6; } static inline int sha1_fmt_get_binary(void *binary) { return *(uint32_t*)(binary); } static int sha1_fmt_binary0(void *binary) { return sha1_fmt_get_binary(binary) & PH_MASK_0; } static int sha1_fmt_binary1(void *binary) { return sha1_fmt_get_binary(binary) & PH_MASK_1; } static int sha1_fmt_binary2(void *binary) { return sha1_fmt_get_binary(binary) & PH_MASK_2; } static int sha1_fmt_binary3(void *binary) { return sha1_fmt_get_binary(binary) & PH_MASK_3; } static int sha1_fmt_binary4(void *binary) { return sha1_fmt_get_binary(binary) & PH_MASK_4; } static int sha1_fmt_binary5(void *binary) { return sha1_fmt_get_binary(binary) & PH_MASK_5; } static int sha1_fmt_binary6(void *binary) { return sha1_fmt_get_binary(binary) & PH_MASK_6; } static int sha1_fmt_cmp_one(void *binary, int index) { // We can quickly check if it will be worth doing a full comparison here, // this lets us turn up SHA1_PARALLEL_HASH without too much overhead when a // partial match occurs. return sha1_fmt_get_binary(binary) == sha1_fmt_get_hash(index); } // This function is not hot, and will only be called for around 1:2^32 random // crypts. Use a real SHA-1 implementation to verify the result exactly. This // routine is only called by John when cmp_one succeeds. static int sha1_fmt_cmp_exact(char *source, int index) { uint32_t full_sha1_digest[SHA1_DIGEST_WORDS]; SHA_CTX ctx; char *key; // Fetch the original input to hash. key = sha1_fmt_get_key(index); SHA1_Init(&ctx); SHA1_Update(&ctx, key, strlen(key)); SHA1_Final((unsigned char*)(full_sha1_digest), &ctx); // Compare result. return !memcmp(rawsha1_common_get_binary(source), full_sha1_digest, sizeof(full_sha1_digest)); } struct fmt_main fmt_sha1_ng = { .params = { .label = "Raw-SHA1-ng", #if VWIDTH == 16 .format_name = "(pwlen <= 55)", #if __MIC__ .algorithm_name = "SHA1 512/512 MIC 16x", #else .algorithm_name = "SHA1 512/512 AVX512 16x", #endif #elif VWIDTH == 8 .format_name = "(pwlen <= 31)", .algorithm_name = "SHA1 256/256 AVX2 8x", #else .format_name = "(pwlen <= 15)", .algorithm_name = "SHA1 128/128 " #if __ALTIVEC__ "AltiVec" #elif __ARM_NEON "NEON" #elif __XOP__ "XOP" #elif __AVX__ "AVX" #elif __SSE4_1__ "SSE4.1" #else "SSE2" #endif " 4x", #endif .benchmark_comment = "", .benchmark_length = -1, #if VWIDTH * 4 - 1 > 55 .plaintext_length = 55, #else .plaintext_length = sizeof(vtype) - 1, #endif .binary_size = sizeof(vtype), .binary_align = VWIDTH * 4, .salt_size = 0, .salt_align = 1, .min_keys_per_crypt = VWIDTH, .max_keys_per_crypt = SHA1_PARALLEL_HASH, .flags = #ifdef _OPENMP FMT_OMP | FMT_OMP_BAD | #endif FMT_CASE | FMT_8_BIT | FMT_SPLIT_UNIFIES_CASE, .tunable_cost_name = { NULL }, .tests = rawsha1_common_tests, }, .methods = { .init = sha1_fmt_init, .done = done, .reset = fmt_default_reset, .prepare = rawsha1_common_prepare, .valid = rawsha1_common_valid, .split = rawsha1_common_split, .binary = sha1_fmt_binary, .salt = fmt_default_salt, .tunable_cost_value = { NULL }, .source = fmt_default_source, .salt_hash = fmt_default_salt_hash, .set_salt = fmt_default_set_salt, .set_key = sha1_fmt_set_key, .get_key = sha1_fmt_get_key, .clear_keys = fmt_default_clear_keys, .crypt_all = sha1_fmt_crypt_all, .get_hash = { [0] = sha1_fmt_get_hash0, [1] = sha1_fmt_get_hash1, [2] = sha1_fmt_get_hash2, [3] = sha1_fmt_get_hash3, [4] = sha1_fmt_get_hash4, [5] = sha1_fmt_get_hash5, [6] = sha1_fmt_get_hash6, }, .binary_hash = { [0] = sha1_fmt_binary0, [1] = sha1_fmt_binary1, [2] = sha1_fmt_binary2, [3] = sha1_fmt_binary3, [4] = sha1_fmt_binary4, [5] = sha1_fmt_binary5, [6] = sha1_fmt_binary6, }, .cmp_all = sha1_fmt_cmp_all, .cmp_one = sha1_fmt_cmp_one, .cmp_exact = sha1_fmt_cmp_exact }, }; #endif /* plugin stanza */ #endif /* defined(SIMD_COEF_32) && (SIMD_COEF_32 < 16 || ARCH_BITS >= 64) && !_MSC_VER */
threadpool.h
/* Copyright 2015 The TensorFlow Authors. 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. ==============================================================================*/ /* Modifications Copyright (c) Microsoft. */ #pragma once #include <string> #include <vector> #include <functional> #include <memory> #include "core/common/common.h" #include "core/platform/env.h" #include <functional> #include <memory> // ORT thread pool overview // ------------------------ // // The ORT thread pool implementation is split into two layers. This // file provides the high-level component. See the accompanying // comments in EigenNonBlockingThreadPool.h for the low-level // component. // // threadpool.h defines the user-facing functions for use in // operators. The main abstraction are parallel loops // (ThreadPool::TryParallelFor*), although we also support scheduling // of asynchronous tasks (ThreadPool::Schedule), and the construction // of multi-loop parallel sections (ThreadPool::ParallelSection). // // This high level API is accessed via static methods on the // ThreadPool class. These methods map the operations onto one of // three low-level implementations: (#1) direct execution of the // operations if there is no thread pool configured, (#2) execution of // the operations using the modified Eigen threadpool, (#3) execution // of the operations using OpenMP. Option #1 enables execution in // simple settings without needing threads. Option #2 is the // preferred approach for use in settings with parallelism. // // The high-level part of the thread pool is responsible for: // // - Exposing the desired degree of parallelism to user code, and to // libraries such as MLAS. This lets the libraries tailor the // extent to which they parallelize work. // // - Handling trivial cases (such as directly running parallel loops // with only a single iteration, or with no iterations at all). // // - Deciding how to divide work efficiently between the threads // available. // // The ThreadPool::TryParallelFor methods do this based on cost // estimates supplied by the caller, and are designed to support // loops with small amounts of work per iteration. The loop body is // supplied as a function taking a [start,end) range of iterations // to execute (avoiding the need for per-iteration std::function // calls, or a reliance upon inlining to avoid those calls). // // ThreadPool::TrySimpleParallelFor uses a simpler single-iteration // API based on the assumption that the caller has divided work to // an appropriate granularity. // // - When used with the Eigen-based thread pool, the implementation of // all of the loops maps down onto // ThreadPool::ParallelForFixedBlockSizeScheduling. This method // takes the degree of parallelism (d_of_p) and work distribution // block size (from the cost-based heuristics), and creates a set of // tasks in the underlying thread pool (via // ThreadPool::RunInParallel). // // These tasks then run a loop which picks off batches of iterations // from the user's code. The distribution of these batches is // handled dynmamically via LoopCounter::ClaimIterations. This // dynamic balancing behavior helps make performance robust to any // variability in the execution time across iterations, and to // situations such as multiple loops running concurrently on the // same thread pool. // // - When running a series of loops inside a parallel section, the // LoopCounter also helps obtain affinity between these loops (i.e., // iteration X of one loop will tend to run on the same thread that // ran iteration X of prior loops). This locality helps improve hit // rates in per-core caches across the series of short loops used in // operators like GRU. // // There are some known areas for exploration here: // // - The cost-based heuristics were developed prior to recent changes // to the thread pool. The heuristics seem to work well, but we // should revisit the tuning periodically. // // - Can we unify the APIs for the different kinds of parallel loop? // // In particular, we may be able to replace the current use of // TryBatchParallelFor with appropriate costs for each call site, // and then use TryParallelFor. This would allow for more dynamic // re-balancing of work between threads than the current // ThreadPool::PartitionWork function provides. // // - Given the extensive modifications to original Eigen code, should // we separate that out as a new class and remove the dependence on // other Eigen components. // This file use PIMPL to avoid having eigen headers here namespace Eigen { class Allocator; class ThreadPoolInterface; } // namespace Eigen namespace onnxruntime { struct TensorOpCost { double bytes_loaded; double bytes_stored; double compute_cycles; }; namespace concurrency { template <typename Environment> class ThreadPoolTempl; class ExtendedThreadPoolInterface; class LoopCounter; class ThreadPoolParallelSection; class ThreadPool { public: #ifdef _WIN32 using NAME_CHAR_TYPE = wchar_t; #else using NAME_CHAR_TYPE = char; #endif // Constructs a pool for running with with "degree_of_parallelism" threads with // specified "name". env->StartThread() is used to create individual threads // with the given ThreadOptions. If "low_latency_hint" is true the thread pool // implementation may use it as a hint that lower latency is preferred at the // cost of higher CPU usage, e.g. by letting one or more idle threads spin // wait. Conversely, if the threadpool is used to schedule high-latency // operations like I/O the hint should be set to false. // // REQUIRES: degree_of_parallelism > 0 ThreadPool(Env* env, const ThreadOptions& thread_options, const NAME_CHAR_TYPE* name, int degree_of_parallelism, bool low_latency_hint); // Waits until all scheduled work has finished and then destroy the // set of threads. ~ThreadPool(); // Start and end a multi-loop parallel section. Parallel loops can // be executed directly (without using this API), but entering a // parallel section allows the runtime system to amortize loop // entry/exit costs over multiple loops, and allows it to promote // affinity between corresponding iterations of different loops. // // Multi-loop sections would typically be used in cases where a // series of loops executes without much code in between them, and // where it is impractical to refactor code into a single loop. For // instance: // // { // onnxruntime::concurrency::ThreadPoool::ParallelSection ps(tp); // for (int x = 0; x < seq_len; x++) { // TrySimpleParallelFor(tp, 16, [&]() { ... }); // } // } // // The parallel section is entered via the constructor of // ThreadPool::ParallelSection, and exited via the destructor. // Currently, thread-local state is used to track whether or not the // current thread is inside a parallel section. In contrast to // handling parallel section objects explicitly in user code, this // approach allows code such as MLAS to operate with/without the use // of parallel sections. // // Parallel sections are only implemented with the Eigen threadpool. // They have no effect when using OpenMP. // // Parallel sections may not be nested, and may not be used inside // parallel loops. class ParallelSection { public: explicit ParallelSection(ThreadPool *tp); ~ParallelSection(); private: friend class ThreadPool; // Owning reference for the underlying ThreadPoolParallelSection // which implements the thread management. We use an explicit // deleter here so that the definition of // ThreadPoolParallelSection does not need to be available at this // point to avoid a dependence on the Eigen headers. std::unique_ptr<ThreadPoolParallelSection, void(*)(ThreadPoolParallelSection*)> ps_{nullptr, [](ThreadPoolParallelSection*){}}; #ifndef _OPENMP ThreadPool *tp_; #endif ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(ParallelSection); // Non-owning reference to the current thread's paralel section // (or nullptr outside parallel sections). static thread_local ParallelSection *current_parallel_section; static_assert(std::is_trivially_destructible<decltype(current_parallel_section)>::value, "Per-thread state should be trivially destructible"); }; // Schedules fn() for execution in the pool of threads. The function may run // synchronously if it cannot be enqueued. This will occur if the thread pool's // degree-of-parallelism is 1, but it may also occur for implementation-dependent // reasons such as if queues used for buffering work are full. static void Schedule(ThreadPool* tp, std::function<void()> fn) { if (tp) { tp->Schedule(fn); } else { fn(); } } // ParallelFor shards the "total" units of work assuming each unit of work // having roughly "cost_per_unit" cost, in cycles. Each unit of work is // indexed 0, 1, ..., total - 1. Each shard contains 1 or more units of work // and the total cost of each shard is roughly the same. // // "cost_per_unit" is an estimate of the number of CPU cycles (or nanoseconds // if not CPU-bound) to complete a unit of work. Overestimating creates too // many shards and CPU time will be dominated by per-shard overhead, such as // Context creation. Underestimating may not fully make use of the specified // parallelism, and may also cause inefficiencies due to load balancing // issues and stragglers. static void TryParallelFor(ThreadPool* tp, std::ptrdiff_t total, double cost_per_unit, const std::function<void(std::ptrdiff_t first, std::ptrdiff_t last)>& fn) { TryParallelFor(tp, total, TensorOpCost{0, 0, static_cast<double>(cost_per_unit)}, fn); } static void TryParallelFor(ThreadPool* tp, std::ptrdiff_t total, const TensorOpCost& cost_per_unit, const std::function<void(std::ptrdiff_t first, std::ptrdiff_t last)>& fn); // Directly schedule the 'total' tasks to the underlying threadpool, without // cutting them by halves inline static void TrySimpleParallelFor(ThreadPool* tp, std::ptrdiff_t total, const std::function<void(std::ptrdiff_t)>& fn) { #ifdef _OPENMP ORT_UNUSED_PARAMETER(tp); #pragma omp parallel for for (std::ptrdiff_t i = 0; i < total; ++i) { fn(i); } #else if (tp != nullptr) { tp->SimpleParallelFor(total, fn); } else { for (std::ptrdiff_t i = 0; i < total; ++i) { // In many cases, fn can be inlined here. fn(i); } } #endif } /** * Tries to call the given function in parallel, with calls split into (num_batches) batches. *\param num_batches If it is zero, it will be replaced to the value of DegreeOfParallelism(). *\param fn A std::function or STL style functor with signature of "void f(std::ptrdiff_t);" * Pitfall: Caller should cap `num_batches` to a reasonable value based on the cost of `fn` and the value of `total`. *For example, if fn is as simple as: int sum=0; fn = [&](int i){sum +=i;} and `total` is 100, then num_batches should *be just 1. * * ``` **/ template <typename F> inline static void TryBatchParallelFor(ThreadPool* tp, std::ptrdiff_t total, F&& fn, std::ptrdiff_t num_batches) { #ifdef _OPENMP ORT_UNUSED_PARAMETER(tp); ORT_UNUSED_PARAMETER(num_batches); #pragma omp parallel for for (std::ptrdiff_t i = 0; i < total; ++i) { fn(i); } #else if (tp == nullptr) { for (std::ptrdiff_t i = 0; i < total; ++i) { // In many cases, fn can be inlined here. fn(i); } return; } if (total <= 0) return; if (total == 1) { fn(0); return; } if (num_batches <= 0) { num_batches = std::min<std::ptrdiff_t>(total, DegreeOfParallelism(tp)); } if (num_batches <= 1) { for (int i = 0; i < total; i++) { fn(i); } return; } tp->SimpleParallelFor(num_batches, [&](std::ptrdiff_t batch_index) { auto work = PartitionWork(batch_index, num_batches, total); for (std::ptrdiff_t i = work.start; i < work.end; i++) { fn(i); } }); #endif } struct WorkInfo { std::ptrdiff_t start; std::ptrdiff_t end; }; /** Calculate the start and end offsets for a batch. @remarks Based on MlasPartitionWork */ static WorkInfo PartitionWork(std::ptrdiff_t batch_idx, std::ptrdiff_t num_batches, std::ptrdiff_t total_work) { const std::ptrdiff_t work_per_batch = total_work / num_batches; const std::ptrdiff_t work_per_batch_extra = total_work % num_batches; WorkInfo info; if (batch_idx < work_per_batch_extra) { info.start = (work_per_batch + 1) * batch_idx; info.end = info.start + work_per_batch + 1; } else { info.start = work_per_batch * batch_idx + work_per_batch_extra; info.end = info.start + work_per_batch; } return info; } //...................................................................... // // The following static methods take into account whether OpenMP is // enabled/disabled, and if the thread pool pointer is nullptr // during sequential execution. // Provide a hint to the caller for whether or not to parallelize // work. This lets a caller switch to a sequential version of an // algorithm rather than using calls via the ParallelFor functions. static bool ShouldParallelize(const ThreadPool* tp); // Return the degree of parallelism that code should assume when using the thread pool. // It decouples the degree of parallelism for use with the thread pool from // the implementation choice of whether this matches the number of threads created in // the pool. // // Currently, a loop with degree-of-parallelism N is supported by a pool of N-1 threads // working in combination with the thread initiating the loop. static int DegreeOfParallelism(const ThreadPool* tp); ORT_DISALLOW_COPY_AND_ASSIGNMENT(ThreadPool); // StartProfiling and StopProfiling are not to be consumed as public-facing API static void StartProfiling(concurrency::ThreadPool* tp); static std::string StopProfiling(concurrency::ThreadPool* tp); private: friend class LoopCounter; // Returns the number of threads created in the pool. This may be different from the // value returned by DegreeOfParallelism to code using the pool. int NumThreads() const; // Returns current thread id between 0 and NumThreads() - 1, if called from a // thread in the pool. Returns -1 otherwise. int CurrentThreadId() const; // Run fn with up to n degree-of-parallelism enlisting the thread pool for // help. The degree-of-parallelism includes the caller, and so if n==1 // then the function will run directly in the caller. The fork-join // synchronization is handled in the thread pool, and so any state captured // by fn() is safe from concurrent access once RunWithHelp returns. void RunInParallel(std::function<void(unsigned idx)> fn, unsigned n, std::ptrdiff_t block_size, std::ptrdiff_t); // Divides the work represented by the range [0, total) into k shards. // Calls fn(i*block_size, (i+1)*block_size) from the ith shard (0 <= i < k). // Each shard may be executed on a different thread in parallel, depending on // the number of threads available in the pool. // When (i+1)*block_size > total, fn(i*block_size, total) is called instead. // Requires 0 < block_size <= total. void ParallelForFixedBlockSizeScheduling(std::ptrdiff_t total, std::ptrdiff_t block_size, const std::function<void(std::ptrdiff_t, std::ptrdiff_t)>& fn); // Return whether or not the calling thread should run a loop of // num_iterations divided in chunks of block_size in parallel. If not, // the caller should run the loop sequentially. bool ShouldParallelizeLoop(const std::ptrdiff_t num_iterations, const std::ptrdiff_t block_size = 1) const; // Internal (non-static) parallel loop methods. Unlike the public static methods, // these will not handle the cases of OpenMP builds. or builds without a threadpool. void ParallelFor(std::ptrdiff_t total, double cost_per_unit, const std::function<void(std::ptrdiff_t first, std::ptrdiff_t last)>& fn); void ParallelFor(std::ptrdiff_t total, const TensorOpCost& cost_per_unit, const std::function<void(std::ptrdiff_t first, std::ptrdiff_t)>& fn); void SimpleParallelFor(std::ptrdiff_t total, const std::function<void(std::ptrdiff_t)>& fn); void Schedule(std::function<void()> fn); void StartProfiling(); std::string StopProfiling(); ThreadOptions thread_options_; // If a thread pool is created with degree_of_parallelism != 1 then an underlying // EigenThreadPool is used to create OS threads and handle work distribution to them. // If degree_of_parallelism == 1 then underlying_threadpool_ is left as nullptr // and parallel work is run directly by the caller. ExtendedThreadPoolInterface* underlying_threadpool_ = nullptr; // If used, underlying_threadpool_ is instantiated and owned by the ThreadPool. std::unique_ptr<ThreadPoolTempl<Env> > extended_eigen_threadpool_; }; } // namespace concurrency } // namespace onnxruntime
GB_unop__one_uint8_uint8.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 Generated/ folder, do not edit it (auto-generated). #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__one_uint8_uint8) // op(A') function: GB (_unop_tran__one_uint8_uint8) // C type: uint8_t // A type: uint8_t // cast: ; // unaryop: cij = 1 #define GB_ATYPE \ uint8_t #define GB_CTYPE \ uint8_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ ; #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = 1 ; // casting #define GB_CAST(z, aij) \ ; ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ ; ; \ /* Cx [pC] = op (cast (aij)) */ \ ; ; \ Cx [pC] = 1 ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ONE || GxB_NO_UINT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__one_uint8_uint8) ( uint8_t *Cx, // Cx and Ax may be aliased const uint8_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 ; // TODO: if OP is ONE and uniform-valued matrices are exploited, then // do this in O(1) time if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (uint8_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { ; ; ; ; Cx [p] = 1 ; } #endif } 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 ; ; ; ; ; Cx [p] = 1 ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__one_uint8_uint8) ( 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
GB_binop__times_fp64.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__times_fp64) // A.*B function (eWiseMult): GB (_AemultB_08__times_fp64) // A.*B function (eWiseMult): GB (_AemultB_02__times_fp64) // A.*B function (eWiseMult): GB (_AemultB_04__times_fp64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__times_fp64) // A*D function (colscale): GB (_AxD__times_fp64) // D*A function (rowscale): GB (_DxB__times_fp64) // C+=B function (dense accum): GB (_Cdense_accumB__times_fp64) // C+=b function (dense accum): GB (_Cdense_accumb__times_fp64) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__times_fp64) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__times_fp64) // C=scalar+B GB (_bind1st__times_fp64) // C=scalar+B' GB (_bind1st_tran__times_fp64) // C=A+scalar GB (_bind2nd__times_fp64) // C=A'+scalar GB (_bind2nd_tran__times_fp64) // C type: double // A type: double // A pattern? 0 // B type: double // B pattern? 0 // BinaryOp: cij = (aij * bij) #define GB_ATYPE \ double #define GB_BTYPE \ double #define GB_CTYPE \ double // 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) \ double 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) \ double 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) \ double 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 = (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_TIMES || GxB_NO_FP64 || GxB_NO_TIMES_FP64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB (_Cdense_ewise3_accum__times_fp64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__times_fp64) ( 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__times_fp64) ( 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__times_fp64) ( 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 double double bwork = (*((double *) 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__times_fp64) ( 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 double *restrict Cx = (double *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__times_fp64) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else double *restrict Cx = (double *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__times_fp64) ( 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) ; double alpha_scalar ; double beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((double *) alpha_scalar_in)) ; beta_scalar = (*((double *) 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__times_fp64) ( 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__times_fp64) ( 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__times_fp64) ( 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__times_fp64) ( 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__times_fp64) ( 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 double *Cx = (double *) Cx_output ; double x = (*((double *) x_input)) ; double *Bx = (double *) 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 ; double bij = GBX (Bx, p, false) ; Cx [p] = (x * bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__times_fp64) ( 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 ; double *Cx = (double *) Cx_output ; double *Ax = (double *) Ax_input ; double y = (*((double *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; double aij = GBX (Ax, p, false) ; Cx [p] = (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) \ { \ double aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x * aij) ; \ } GrB_Info GB (_bind1st_tran__times_fp64) ( 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 \ double #if GB_DISABLE return (GrB_NO_VALUE) ; #else double x = (*((const double *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ double } //------------------------------------------------------------------------------ // 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) \ { \ double aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij * y) ; \ } GrB_Info GB (_bind2nd_tran__times_fp64) ( 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 double y = (*((const double *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
radix_hash_map.h
#pragma once #include <new> #include <malloc.h> #include "omp.h" #include <util/search_util.h> inline uint32_t get_log_size(int x) { int cnt = 0; for (; x > 0; cnt++) { x >>= 1; } return cnt; } inline uint32_t get_part_size(int i) { return i == 0 ? 0 : 1 << (get_log_size(i) - 1); } class RadixFilter { BoolArray<uint64_t> psum_occupied_bool_; graph_t *g_; int radix_val_; public: explicit RadixFilter(graph_t *g) : g_(g), radix_val_(-1) {} void Construct(int u) { auto deg = g_->num_edges[u + 1] - g_->num_edges[u]; // if (deg > 0) { // assume deg > 0 // 1: Histogram. constexpr int heuristic_factor = 16; auto partition_size = get_part_size(deg) * heuristic_factor; radix_val_ = partition_size - 1; psum_occupied_bool_ = BoolArray<uint64_t>(partition_size); auto radix_val = partition_size - 1; for (auto j = g_->num_edges[u]; j < g_->num_edges[u + 1]; j++) { auto v = g_->adj[j]; auto bucket_id = v & radix_val; psum_occupied_bool_.set(bucket_id); } // } } bool PossibleExist(int v) { auto bucket_id = v & radix_val_; return psum_occupied_bool_.get(bucket_id); } }; class RadixSet { vector<int> psum_arr_; BoolArray<uint64_t> psum_occupied_bool_; vector<int> tmp_; vector<int> hash_table_; graph_t *g_; public: explicit RadixSet(graph_t *g) : g_(g) { psum_arr_.reserve(1024 * 1204 * 2); hash_table_.reserve(1024 * 1204 * 2); } void Construct(int u) { auto deg = g_->num_edges[u + 1] - g_->num_edges[u]; if (deg > 0) { // 1: Histogram. constexpr int heuristic_factor = 16; auto partition_size = get_part_size(deg) * heuristic_factor; psum_arr_.resize(partition_size + 1); memset(&psum_arr_.front(), 0, psum_arr_.size() * sizeof(int)); hash_table_.resize(deg); psum_occupied_bool_ = BoolArray<uint64_t>(psum_arr_.size()); auto radix_val = partition_size - 1; for (auto j = g_->num_edges[u]; j < g_->num_edges[u + 1]; j++) { auto v = g_->adj[j]; auto bucket_id = v & radix_val; psum_arr_[bucket_id + 1]++; psum_occupied_bool_.set(bucket_id); } // 2: PrefixSum. for (auto i = 0u; i < partition_size; i++) { psum_arr_[i + 1] += psum_arr_[i]; } // 3: Scatter. tmp_.resize(psum_arr_.size()); memcpy(&tmp_.front(), &psum_arr_.front(), sizeof(int) * psum_arr_.size()); for (auto j = g_->num_edges[u]; j < g_->num_edges[u + 1]; j++) { auto v = g_->adj[j]; auto bucket_id = v & radix_val; hash_table_[tmp_[bucket_id]++] = v; } } else { psum_arr_.clear(); } } bool Exist(int v) { // if (psum_arr_.empty())return false; // Assume not zero deg. auto partition_size = psum_arr_.size() - 1; auto radix_val = partition_size - 1; auto bucket_id = v & radix_val; if (psum_occupied_bool_.get(bucket_id)) { for (auto j = psum_arr_[bucket_id]; j < psum_arr_[bucket_id + 1]; j++) { if (hash_table_[j] == v) { return true; } } } return false; } }; class RadixHashMap { public: using hash_entry_t = pair<int, eid_t>; private: graph_t *g_; int size_; vector<vector<int>> psum_arr_arr_; // key (v) and eid for (u,v) vector<vector<pair<int, eid_t>>> hash_table_arr_; public: explicit RadixHashMap(graph_t *g) : g_(g), size_(g_->n), psum_arr_arr_(size_), hash_table_arr_(size_) { // Construct in Parallel #pragma omp parallel { ParallelPopulate(); #pragma omp for for (auto u = 0; u < size_; u++) { Construct(u); } } } void Construct(int u) { // 1: Histogram. auto &psum_arr = psum_arr_arr_[u]; if (psum_arr.empty())return; auto &hash_table = hash_table_arr_[u]; auto partition_size = psum_arr.size() - 1; auto radix_val = partition_size - 1; for (auto j = g_->num_edges[u]; j < g_->num_edges[u + 1]; j++) { auto v = g_->adj[j]; auto bucket_id = v & radix_val; // assert(bucket_id < psum_arr.size()); psum_arr[bucket_id + 1]++; } // 2: PrefixSum. for (auto i = 0u; i < partition_size; i++) { psum_arr[i + 1] += psum_arr[i]; } // 3: Scatter. auto tmp = psum_arr; for (auto j = g_->num_edges[u]; j < g_->num_edges[u + 1]; j++) { auto v = g_->adj[j]; auto bucket_id = v & radix_val; hash_table[tmp[bucket_id]++] = make_pair(v, g_->eid[j]); } } void find_u_psum_table_size(int u, vector<int> *&psum_arr_ptr, vector<hash_entry_t> *&hash_table_ptr, uint32_t &radix_val) { psum_arr_ptr = &psum_arr_arr_[u]; hash_table_ptr = &hash_table_arr_[u]; auto partition_size = psum_arr_ptr->size() - 1; radix_val = partition_size - 1; } // Assume `psum_arr` is not empty. eid_t *get(vector<int> *psum_arr_ptr, vector<hash_entry_t> *hash_table_ptr, uint32_t radix_val, int v) { auto &psum_arr = *psum_arr_ptr; auto &hash_table = *hash_table_ptr; auto bucket_id = v & radix_val; for (auto j = psum_arr[bucket_id]; j < psum_arr[bucket_id + 1]; j++) { if (hash_table[j].first == v) { return &hash_table[j].second; } } return nullptr; } eid_t *get(int u, int v) { auto &psum_arr = psum_arr_arr_[u]; if (psum_arr.empty())return nullptr; auto &hash_table = hash_table_arr_[u]; auto partition_size = psum_arr.size() - 1; auto radix_val = partition_size - 1; auto bucket_id = v & radix_val; for (auto j = psum_arr[bucket_id]; j < psum_arr[bucket_id + 1]; j++) { if (hash_table[j].first == v) { return &hash_table[j].second; } } return nullptr; } void ParallelPopulate() { #pragma omp for for (auto u = 0; u < size_; u++) { auto deg = g_->num_edges[u + 1] - g_->num_edges[u]; if (deg > 0) { auto partition_size = get_part_size(deg); psum_arr_arr_[u] = vector<int>(partition_size + 1, 0); } } #pragma omp for for (auto i = 0; i < size_; i++) { hash_table_arr_[i] = vector<hash_entry_t>(g_->num_edges[i + 1] - g_->num_edges[i]); } } void ManuallyFree() { Timer free_timer; #pragma omp parallel { #pragma omp for for (auto i = 0; i < size_; i++) { vector<int> tmp; psum_arr_arr_[i].swap(tmp); } #pragma omp for for (auto i = 0; i < size_; i++) { vector<hash_entry_t> tmp; hash_table_arr_[i].swap(tmp); } } log_info("Free radix hash map cost: %.6lfs", free_timer.elapsed()); } ~RadixHashMap() { ManuallyFree(); } };
ike_fmt_plug.c
/* PSK cracker patch for JtR. Hacked together during March of 2012 by * Dhiru Kholia <dhiru.kholia at gmail.com> . * * This software is Copyright (c) 2012, Dhiru Kholia <dhiru.kholia at gmail.com> * and it is hereby released to the general public under GPL * * The IKE Scanner (ike-scan) is Copyright (C) 2003-2007 Roy Hills, * NTA Monitor Ltd. * * This program 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 * of the License, or (at your option) any later version. * * This program 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 this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library, and distribute linked combinations including the two. * * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. * * If this license is unacceptable to you, I may be willing to negotiate * alternative licenses (contact ike-scan@nta-monitor.com). * * You are encouraged to send comments, improvements or suggestions to * me at ike-scan@nta-monitor.com. * * psk-crack.c -- IKE Aggressive Mode Pre-Shared Key cracker for ike-scan * * Author: Roy Hills * Date: 8 July 2004 * * July, 2012, JimF small changes made, many more should be done. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_ike; #elif FMT_REGISTERS_H john_register_one(&fmt_ike); #else #include <string.h> #include <assert.h> #include <errno.h> #include "arch.h" #include "misc.h" #include "common.h" #include "formats.h" #include "params.h" #include "options.h" #include "ike-crack.h" #ifdef _OPENMP #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 16 #endif static int omp_t = 1; #endif #include "memdbg.h" #define FORMAT_LABEL "IKE" #define FORMAT_NAME "PSK" #define FORMAT_TAG "$ike$*" #define FORMAT_TAG_LEN (sizeof(FORMAT_TAG)-1) #define ALGORITHM_NAME "HMAC MD5/SHA1 32/" ARCH_BITS_STR #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define PLAINTEXT_LENGTH 32 #define BINARY_SIZE 20 /* SHA1 */ #define BINARY_SIZE_SMALLER 16 /* MD5 */ #define SALT_SIZE sizeof(psk_entry) #define BINARY_ALIGN sizeof(uint32_t) #define SALT_ALIGN sizeof(size_t) #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 16 static struct fmt_tests ike_tests[] = { {"$ike$*0*5c7916ddf8db4d233b3b36005bb3ccc115a73807e11a897be943fd4a2d0f942624cb00588d8b3a0a26502b73e639df217ef6c4cb90f96b0a3c3ef2f62ed025b4a705df9de65e33e380c1ba5fa23bf1f9911bbf388d0844256fa0131fc5cf8acb396936ba3295b4637b039d93f58db90a3a1cf1ef5051103bacf6e1a3334f9f89*fde8c68c5f324c7dbcbadde1d757af6962c63496c009f77cad647f2997fd4295e50821453a6dc2f6279fd7fef68768584d9cee0da6e68a534a097ce206bf77ecc798310206f3f82d92d02c885794e0a430ceb2d6b43c2aff45a6e14c6558382df0692ff65c2724eef750764ee456f31424a5ebd9e115d826bbb9722111aa4e01*b2a3c7aa4be95e85*756e3fa11c1b102c*00000001000000010000002c01010001000000240101000080010001800200018003000180040002800b0001000c000400007080*01000000ac100202*251d7ace920b17cb34f9d561bca46d037b337d19*e045819a64edbf022620bff3efdb935216584cc4*b9c594fa3fca6bb30a85c4208a8df348", "abc123"}, {"$ike$*0*9bdee7aa341cf1a6c19bc0191106b5056537ce6b837cd70678ea5a3ccb606b56dee4548feb67f24fd6f4d5f58967a9ff3c674d9d79e4195b7def5aac147c9fe9abdc2f8ba2eca58f4c863fedc7a8c8e1ad6e1551b1e44bf9a0e258561a5db1c2ca1e8b5dfda1b012012b6fdf24ecd07da6b10d76ab3b58d07b30b4f9da26aee4*c9b7ef0610a22b3e1c88b1a01ce4d4110edf6baa122ed1285eb2184cd75d30a11520a725c2d263de5a157f77f953880732f3b14521836d7f3585cb0ce3fcadf81c541dde2680bd81953cf88e8f8096c173470694ca7414fff9df0cdcdbb9d4f70ef1d6347293b507cfad965e2d2c1fa07326353e9a493d93284970040344fb11*3506592130312567*6c362583ce7a2a26*00000001000000010000002c01010001000000240101000080010001800200028003000180040002800b0001000c000400007080*01000000ac100202*84943233f42a0b5a9b33c327162fe0efee2545e4*76f451dce3fea6402b67f3fddae561ebdb4a6efe*f63f237b3c0f1fe57a5b852203cfd27cbf0c78d4", "abc123"}, {NULL} }; static psk_entry *cur_salt; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static uint32_t (*crypt_out)[BINARY_SIZE / sizeof(uint32_t)]; static void init(struct fmt_main *self) { #if defined (_OPENMP) 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; #endif saved_key = mem_calloc(sizeof(*saved_key), self->params.max_keys_per_crypt); crypt_out = mem_calloc(sizeof(*crypt_out), self->params.max_keys_per_crypt); } static void done(void) { MEM_FREE(crypt_out); MEM_FREE(saved_key); } static int valid(char *ciphertext, struct fmt_main *self) { char *ptr, *ctcopy, *keeptr; if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN)) return 0; if (!(ctcopy = strdup(ciphertext))) return 0; keeptr = ctcopy; ctcopy += FORMAT_TAG_LEN; /* skip leading '$ike$*' */ if (*ctcopy != '0' && *ctcopy != '1') goto error; /* skip '*0' */ ctcopy += 1; if (*ctcopy != '*') goto error; ctcopy += 1; if (!(ptr = strtokm(ctcopy, "*"))) goto error; if (strlen(ptr) > MAXLEN) goto error; if (!ishexlc(ptr)) goto error; if (!(ptr = strtokm(NULL, "*"))) goto error; if (strlen(ptr) > MAXLEN) goto error; if (!ishexlc(ptr)) goto error; if (!(ptr = strtokm(NULL, "*"))) goto error; if (strlen(ptr) > MAXLEN) goto error; if (!ishexlc(ptr)) goto error; if (!(ptr = strtokm(NULL, "*"))) goto error; if (strlen(ptr) > MAXLEN) goto error; if (!ishexlc(ptr)) goto error; if (!(ptr = strtokm(NULL, "*"))) goto error; if (strlen(ptr) > MAXLEN) goto error; if (!ishexlc(ptr)) goto error; if (!(ptr = strtokm(NULL, "*"))) goto error; if (strlen(ptr) > MAXLEN) goto error; if (!ishexlc(ptr)) goto error; if (!(ptr = strtokm(NULL, "*"))) goto error; if (strlen(ptr) > MAXLEN) goto error; if (!ishexlc(ptr)) goto error; if (!(ptr = strtokm(NULL, "*"))) goto error; if (strlen(ptr) > MAXLEN) goto error; if (!ishexlc(ptr)) goto error; if (!(ptr = strtokm(NULL, "*"))) goto error; if (strlen(ptr) != 32 && strlen(ptr) != 40) // md5 or sha1 length. goto error; if (!ishexlc(ptr)) goto error; MEM_FREE(keeptr); return 1; error: MEM_FREE(keeptr); return 0; } static void *get_salt(char *ciphertext) { static psk_entry cs; cs.isnortel = atoi(&ciphertext[FORMAT_TAG_LEN]); load_psk_params(&ciphertext[FORMAT_TAG_LEN+2], NULL, &cs); return (void *)&cs; } 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_SMALLER; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } return out; } static void set_salt(void *salt) { cur_salt = (psk_entry *)salt; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for #endif for (index = 0; index < count; index++) { compute_hash(cur_salt, saved_key[index], (unsigned char*)crypt_out[index]); } return count; } static int cmp_all(void *binary, int count) { int index = 0; for (; index < count; index++) if (*((uint32_t*)binary) == crypt_out[index][0]) return 1; return 0; } static int cmp_one(void *binary, int index) { return (*((uint32_t*)binary) == crypt_out[index][0]); } static int cmp_exact(char *source, int index) { void *binary = get_binary(source); return !memcmp(binary, crypt_out[index], BINARY_SIZE_SMALLER); } static void ike_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]; } /* * For ike, the hash algorithm used for hmac * is returned as the first "tunable cost": * 1: MD5 * 2: SHA1 * * However, the there is almost no difference in speed, * so if the different hash types for HMAC shouldn't be reported, * just define IKE_REPORT_TUNABLE_COSTS to be 0 instead of 1. */ #define IKE_REPORT_TUNABLE_COSTS 1 #if IKE_REPORT_TUNABLE_COSTS static unsigned int tunable_cost_hmac_hash_type(void *salt) { psk_entry *my_salt; my_salt = salt; return (unsigned int) my_salt->hash_type; } #endif struct fmt_main fmt_ike = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE_SMALLER, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_HUGE_INPUT, { #if IKE_REPORT_TUNABLE_COSTS "hash algorithm used for hmac [1:MD5 2:SHA1]", #else NULL #endif }, { FORMAT_TAG }, ike_tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, fmt_default_split, get_binary, get_salt, { #if IKE_REPORT_TUNABLE_COSTS tunable_cost_hmac_hash_type, #else NULL #endif }, fmt_default_source, { fmt_default_binary_hash }, fmt_default_salt_hash, NULL, set_salt, ike_set_key, get_key, fmt_default_clear_keys, crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
hadvuv.h
#ifndef HADVUV_H #define HADVUV_H ElementType advectionDriver(const Storage3D field, const int64_t i, const int64_t j, const int64_t k, const ElementType uavg, const ElementType vavg, const ElementType eddlat, const ElementType eddlon) { ElementType result_x = 0.0; ElementType result_y = 0.0; if (uavg > 0) { result_x = uavg * (ElementType(-1.0) / ElementType(6.0) * field(i - 2, j, k) + field(i - 1, j, k) + ElementType(-0.5) * field(i, j, k) + ElementType(-1.0) / ElementType(3.0) * field(i + 1, j, k)); } else { result_x = -uavg * (ElementType(-1.0) / ElementType(3.0) * field(i - 1, j, k) + ElementType(-0.5) * field(i, j, k) + field(i + 1, j, k) + ElementType(-1.0) / ElementType(6.0) * field(i + 2, j, k)); } if (vavg > 0) { result_y = vavg * (ElementType(-1.0) / ElementType(6.0) * field(i, j - 2, k) + field(i, j - 1, k) + ElementType(-0.5) * field(i, j, k) + ElementType(-1.0) / ElementType(3.0) * field(i, j + 1, k)); } else { result_y = -vavg * (ElementType(-1.0) / ElementType(3.0) * field(i, j - 1, k) + ElementType(-0.5) * field(i, j, k) + field(i, j + 1, k) + ElementType(-1.0) / ElementType(6.0) * field(i, j + 2, k)); } return eddlat * result_x + eddlon * result_y; } void hadvuv(Storage3D& uout, Storage3D& vout, const Storage3D& uin, const Storage3D& vin, const Storage1D& acrlat0, const Storage1D& acrlat1, const Storage1D& tgrlatda0, const Storage1D& tgrlatda1, Storage3D& uatupos, Storage3D& vatupos, Storage3D& uatvpos, Storage3D& vatvpos, Storage3D& uavg, Storage3D& vavg, Storage3D& ures, Storage3D& vres, const ElementType eddlat, const ElementType eddlon) { for (int64_t k = 0; k < domain_height; ++k) { for (int64_t i = 0; i < domain_size; ++i) { for (int64_t j = 0; j < domain_size; ++j) { uatupos(i, j, k) = (ElementType(1.0) / ElementType(3.0)) * (uin(i - 1, j, k) + uin(i, j, k) + uin(i + 1, j, k)); vatupos(i, j, k) = ElementType(0.25) * (vin(i + 1, j, k) + vin(i + 1, j - 1, k) + vin(i, j, k) + vin(i, j - 1, k)); } } } for (int64_t k = 0; k < domain_height; ++k) { for (int64_t i = 0; i < domain_size; ++i) { for (int64_t j = 0; j < domain_size; ++j) { uavg(i, j, k) = acrlat0(j) * uatupos(i, j, k); vavg(i, j, k) = EARTH_RADIUS_RECIP * vatupos(i, j, k); } } } for (int64_t k = 0; k < domain_height; ++k) { for (int64_t i = 0; i < domain_size; ++i) { for (int64_t j = 0; j < domain_size; ++j) { ures(i, j, k) = advectionDriver(uin, i, j, k, uavg(i, j, k), vavg(i, j, k), eddlat, eddlon); } } } for (int64_t k = 0; k < domain_height; ++k) { for (int64_t i = 0; i < domain_size; ++i) { for (int64_t j = 0; j < domain_size; ++j) { uout(i, j, k) = ures(i, j, k) + tgrlatda0(j) * uin(i, j, k) * vatupos(i, j, k); } } } for (int64_t k = 0; k < domain_height; ++k) { for (int64_t i = 0; i < domain_size; ++i) { for (int64_t j = 0; j < domain_size; ++j) { uatvpos(i, j, k) = ElementType(0.25) * (uin(i - 1, j, k) + uin(i, j, k) + uin(i, j + 1, k) + uin(i - 1, j + 1, k)); vatvpos(i, j, k) = ElementType(1.0) / ElementType(3.0) * (vin(i, j - 1, k) + vin(i, j, k) + vin(i, j + 1, k)); } } } for (int64_t k = 0; k < domain_height; ++k) { for (int64_t i = 0; i < domain_size; ++i) { for (int64_t j = 0; j < domain_size; ++j) { uavg(i, j, k) = acrlat1(j) * uatvpos(i, j, k); vavg(i, j, k) = EARTH_RADIUS_RECIP * vatvpos(i, j, k); } } } for (int64_t k = 0; k < domain_height; ++k) { for (int64_t i = 0; i < domain_size; ++i) { for (int64_t j = 0; j < domain_size; ++j) { vres(i, j, k) = advectionDriver(vin, i, j, k, uavg(i, j, k), vavg(i, j, k), eddlat, eddlon); } } } for (int64_t k = 0; k < domain_height; ++k) { for (int64_t i = 0; i < domain_size; ++i) { for (int64_t j = 0; j < domain_size; ++j) { vout(i, j, k) = vres(i, j, k) - tgrlatda1(j) * uatvpos(i, j, k) * uatvpos(i, j, k); } } } } void hadvuv_partialfusion(Storage3D& uout, Storage3D& vout, const Storage3D& uin, const Storage3D& vin, const Storage1D& acrlat0, const Storage1D& acrlat1, const Storage1D& tgrlatda0, const Storage1D& tgrlatda1, Storage3D& uatupos, Storage3D& vatupos, Storage3D& uatvpos, Storage3D& vatvpos, Storage3D& uavg, Storage3D& vavg, Storage3D& ures, Storage3D& vres, const ElementType eddlat, const ElementType eddlon) { for (int64_t k = 0; k < domain_height; ++k) { for (int64_t i = 0; i < domain_size; ++i) { for (int64_t j = 0; j < domain_size; ++j) { auto _uatupos = (ElementType(1.0) / ElementType(3.0)) * (uin(i - 1, j, k) + uin(i, j, k) + uin(i + 1, j, k)); auto _vatupos = ElementType(0.25) * (vin(i + 1, j, k) + vin(i + 1, j - 1, k) + vin(i, j, k) + vin(i, j - 1, k)); auto _uavg = acrlat0(j) * _uatupos; auto _vavg = EARTH_RADIUS_RECIP * _vatupos; auto _ures = advectionDriver(uin, i, j, k, _uavg, _vavg, eddlat, eddlon); uout(i, j, k) = _ures + tgrlatda0(j) * uin(i, j, k) * _vatupos; } } } for (int64_t k = 0; k < domain_height; ++k) { for (int64_t i = 0; i < domain_size; ++i) { for (int64_t j = 0; j < domain_size; ++j) { auto _uatvpos = ElementType(0.25) * (uin(i - 1, j, k) + uin(i, j, k) + uin(i, j + 1, k) + uin(i - 1, j + 1, k)); auto _vatvpos = ElementType(1.0) / ElementType(3.0) * (vin(i, j - 1, k) + vin(i, j, k) + vin(i, j + 1, k)); auto _uavg = acrlat1(j) * _uatvpos; auto _vavg = EARTH_RADIUS_RECIP * _vatvpos; auto _vres = advectionDriver(vin, i, j, k, _uavg, _vavg, eddlat, eddlon); vout(i, j, k) = _vres - tgrlatda1(j) * _uatvpos * _uatvpos; } } } } void hadvuv_fullfusion(Storage3D& uout, Storage3D& vout, const Storage3D& uin, const Storage3D& vin, const Storage1D& acrlat0, const Storage1D& acrlat1, const Storage1D& tgrlatda0, const Storage1D& tgrlatda1, Storage3D& uatupos, Storage3D& vatupos, Storage3D& uatvpos, Storage3D& vatvpos, Storage3D& uavg, Storage3D& vavg, Storage3D& ures, Storage3D& vres, const ElementType eddlat, const ElementType eddlon) { for (int64_t k = 0; k < domain_height; ++k) { for (int64_t i = 0; i < domain_size; ++i) { for (int64_t j = 0; j < domain_size; ++j) { auto _uatupos = (ElementType(1.0) / ElementType(3.0)) * (uin(i - 1, j, k) + uin(i, j, k) + uin(i + 1, j, k)); auto _vatupos = ElementType(0.25) * (vin(i + 1, j, k) + vin(i + 1, j - 1, k) + vin(i, j, k) + vin(i, j - 1, k)); auto _uavg = acrlat0(j) * _uatupos; auto _vavg = EARTH_RADIUS_RECIP * _vatupos; auto _ures = advectionDriver(uin, i, j, k, _uavg, _vavg, eddlat, eddlon); uout(i, j, k) = _ures + tgrlatda0(j) * uin(i, j, k) * _vatupos; auto _uatvpos = ElementType(0.25) * (uin(i - 1, j, k) + uin(i, j, k) + uin(i, j + 1, k) + uin(i - 1, j + 1, k)); auto _vatvpos = ElementType(1.0) / ElementType(3.0) * (vin(i, j - 1, k) + vin(i, j, k) + vin(i, j + 1, k)); _uavg = acrlat1(j) * _uatvpos; _vavg = EARTH_RADIUS_RECIP * _vatvpos; auto _vres = advectionDriver(vin, i, j, k, _uavg, _vavg, eddlat, eddlon); vout(i, j, k) = _vres - tgrlatda1(j) * _uatvpos * _uatvpos; } } } } void hadvuv_openmp(Storage3D& uout, Storage3D& vout, const Storage3D& uin, const Storage3D& vin, const Storage1D& acrlat0, const Storage1D& acrlat1, const Storage1D& tgrlatda0, const Storage1D& tgrlatda1, Storage3D& uatupos, Storage3D& vatupos, Storage3D& uatvpos, Storage3D& vatvpos, Storage3D& uavg, Storage3D& vavg, Storage3D& ures, Storage3D& vres, const ElementType eddlat, const ElementType eddlon) { #pragma omp parallel for for (int64_t k = 0; k < domain_height; ++k) { for (int64_t i = 0; i < domain_size; ++i) { for (int64_t j = 0; j < domain_size; ++j) { auto _uatupos = (ElementType(1.0) / ElementType(3.0)) * (uin(i - 1, j, k) + uin(i, j, k) + uin(i + 1, j, k)); auto _vatupos = ElementType(0.25) * (vin(i + 1, j, k) + vin(i + 1, j - 1, k) + vin(i, j, k) + vin(i, j - 1, k)); auto _uavg = acrlat0(j) * _uatupos; auto _vavg = EARTH_RADIUS_RECIP * _vatupos; auto _ures = advectionDriver(uin, i, j, k, _uavg, _vavg, eddlat, eddlon); uout(i, j, k) = _ures + tgrlatda0(j) * uin(i, j, k) * _vatupos; auto _uatvpos = ElementType(0.25) * (uin(i - 1, j, k) + uin(i, j, k) + uin(i, j + 1, k) + uin(i - 1, j + 1, k)); auto _vatvpos = ElementType(1.0) / ElementType(3.0) * (vin(i, j - 1, k) + vin(i, j, k) + vin(i, j + 1, k)); _uavg = acrlat1(j) * _uatvpos; _vavg = EARTH_RADIUS_RECIP * _vatvpos; auto _vres = advectionDriver(vin, i, j, k, _uavg, _vavg, eddlat, eddlon); vout(i, j, k) = _vres - tgrlatda1(j) * _uatvpos * _uatvpos; } } } } #endif // HADVUV_H
assignment.h
/* Portions Copyright 2019-2021 Xuesong Zhou and Peiheng Li, Cafer Avci * If you help write or modify the code, please also list your names here. * The reason of having Copyright info here is to ensure all the modified version, as a whole, under the GPL * and further prevent a violation of the GPL. * * More about "How to use GNU licenses for your own software" * http://www.gnu.org/licenses/gpl-howto.html */ // Peiheng, 02/03/21, remove them later after adopting better casting #pragma warning(disable : 4305 4267 4018) // stop warning: "conversion from 'int' to 'float', possible loss of data" #pragma warning(disable: 4244) #ifdef _WIN32 #include "pch.h" #endif #include "config.h" #include "utils.h" #include "DTA.h" #include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include <string> #include <cstring> #include <cstdio> #include <ctime> #include <cmath> #include <algorithm> #include <functional> #include <stack> #include <list> #include <vector> #include <map> #include <omp.h> using std::max; using std::min; using std::cout; using std::endl; using std::string; using std::vector; using std::map; using std::ifstream; using std::ofstream; using std::istringstream; void g_reset_and_update_link_volume_based_on_columns(int number_of_links, int iteration_index, bool b_self_reducing_path_volume, bool b_sensitivity_analysis_flag) { // record numbers if (b_sensitivity_analysis_flag) { // for (int i = 0; i < number_of_links; ++i) // { // for (int tau = 0; tau < assignment.g_number_of_demand_periods; ++tau) // { //// g_link_vector[i].VDF_period[tau].link_volume_per_iteration_map[iteration_index] = g_link_vector[i].PCE_volume_per_period[tau] + g_link_vector[i].VDF_period[tau].preload; // // used in travel time calculation // } // } } // reset the link volume for (int i = 0; i < number_of_links; ++i) { for (int tau = 0; tau < assignment.g_number_of_demand_periods; ++tau) { // used in travel time calculation g_link_vector[i].PCE_volume_per_period[tau] = 0; g_link_vector[i].person_volume_per_period[tau] = 0; for (int at = 0; at < assignment.g_AgentTypeVector.size(); ++at) g_link_vector[i].person_volume_per_period_per_at[tau][at] = 0; } for (int at = 0; at < assignment.g_AgentTypeVector.size(); ++at) for (int og = 0; og < assignment.g_number_of_analysis_districts; ++og) { g_link_vector[i].person_volume_per_district_per_at[og][at] = 0; } } if (iteration_index >= 0) { for (int at = 0; at < assignment.g_AgentTypeVector.size(); ++at) //m { std::map<int, CColumnPath>::iterator it; int zone_size = g_zone_vector.size(); int tau_size = assignment.g_DemandPeriodVector.size(); float link_volume_contributed_by_path_volume; int link_seq_no; double PCE_ratio = 1; double OCC_ratio = 1; int nl; std::map<int, CColumnPath>::iterator it_begin; std::map<int, CColumnPath>::iterator it_end; int column_vector_size; CColumnVector* p_column_pool; for (int orig = 0; orig < zone_size; ++orig) // o { int from_zone_sindex = g_zone_vector[orig].sindex; if (from_zone_sindex == -1) continue; int analysis_district_id = assignment.g_zone_seq_no_to_analysis_distrct_id_mapping[orig]; for (int dest = 0; dest < zone_size; ++dest) //d { int to_zone_sindex = g_zone_vector[dest].sindex; if (to_zone_sindex == -1) continue; for (int tau = 0; tau < tau_size; ++tau) //tau { p_column_pool = &(assignment.g_column_pool[from_zone_sindex][to_zone_sindex][at][tau]); if (p_column_pool->od_volume > 0) { column_vector_size = p_column_pool->path_node_sequence_map.size(); it_begin = p_column_pool->path_node_sequence_map.begin(); it_end = p_column_pool->path_node_sequence_map.end(); for (it = it_begin; it != it_end; ++it) { link_volume_contributed_by_path_volume = it->second.path_volume; // assign all OD flow to this first path // add path volume to link volume for (nl = 0; nl < it->second.m_link_size; ++nl) // arc a { link_seq_no = it->second.path_link_vector[nl]; // MSA updating for the existing column pools // if iteration_index = 0; then update no flow discount is used (for the column pool case) PCE_ratio = g_link_vector[link_seq_no].VDF_period[tau].pce[at]; // updated on 08/16/2021 for link dependent and agent type dependent pce factor mainly for trucks OCC_ratio = g_link_vector[link_seq_no].VDF_period[tau].occ[at]; // updated on 08/16/2021 for link dependent and agent type dependent pce factor mainly for trucks #pragma omp critical { g_link_vector[link_seq_no].PCE_volume_per_period[tau] += link_volume_contributed_by_path_volume * PCE_ratio; g_link_vector[link_seq_no].person_volume_per_period[tau] += link_volume_contributed_by_path_volume * OCC_ratio; g_link_vector[link_seq_no].person_volume_per_period_per_at[tau][at] += link_volume_contributed_by_path_volume * OCC_ratio; // pure volume, not consider PCE g_link_vector[link_seq_no].person_volume_per_district_per_at[analysis_district_id][at] += link_volume_contributed_by_path_volume * OCC_ratio; // pure volume, not consider PCE } } // this self-deducting action does not agents with fixed routing policies. if (!p_column_pool->bfixed_route && b_self_reducing_path_volume) { //after link volumn "tally", self-deducting the path volume by 1/(k+1) (i.e. keep k/(k+1) ratio of previous flow) so that the following shortes path will be receiving 1/(k+1) flow it->second.path_volume = it->second.path_volume * (double(iteration_index) / double(iteration_index + 1)); } } } } } } } } } double update_link_travel_time_and_cost(int inner_iteration_number) { if (assignment.assignment_mode == 2) { //compute the time-dependent delay from simulation //for (int l = 0; l < g_link_vector.size(); l++) //{ // float volume = assignment.m_LinkCumulativeDepartureVector[l][assignment.g_number_of_simulation_intervals - 1]; // link flow rates // float waiting_time_count = 0; //for (int tt = 0; tt < assignment.g_number_of_simulation_intervals; tt++) //{ // waiting_time_count += assignment.m_link_TD_waiting_time[l][tt/number_of_simu_intervals_in_min]; // tally total waiting cou //} //for (int tau = 0; tau < assignment.g_DemandPeriodVector.size(); tau++) //{ // float travel_time = g_link_vector[l].free_flow_travel_time_in_min + waiting_time_count* number_of_seconds_per_interval / max(1, volume) / 60; // g_link_vector[l].travel_time_per_period[tau] = travel_time; //} } #pragma omp parallel for for (int i = 0; i < g_link_vector.size(); ++i) { // step 1: travel time based on VDF g_link_vector[i].calculate_dynamic_VDFunction(inner_iteration_number, false, g_link_vector[i].vdf_type); for (int tau = 0; tau < assignment.g_DemandPeriodVector.size(); ++tau) { for (int at = 0; at < assignment.g_AgentTypeVector.size(); ++at) { float PCE_agent_type = assignment.g_AgentTypeVector[at].PCE; // step 2: marginal cost for SO g_link_vector[i].calculate_marginal_cost_for_agent_type(tau, at, PCE_agent_type); //if (g_debug_level >= 3 && assignment.assignment_mode >= 2 && assignment.g_pFileDebugLog != NULL) // fprintf(assignment.g_pFileDebugLog, "Update link cost: link %d->%d: tau = %d, at = %d, travel_marginal = %.3f\n", // g_node_vector[g_link_vector[l].from_node_seq_no].node_id, // g_node_vector[g_link_vector[l].to_node_seq_no].node_id, // tau, at, // g_link_vector[l].travel_marginal_cost_per_period[tau][at]); } } } double total_network_travel_time = 0; for (int i = 0; i < g_link_vector.size(); ++i) { for (int tau = 0; tau < assignment.g_DemandPeriodVector.size(); ++tau) { total_network_travel_time += g_link_vector[i].VDF_period[tau].avg_travel_time * g_link_vector[i].VDF_period[tau].link_volume; } } return total_network_travel_time; } // changes here are also for odmes, don't need to implement the changes in this function for now double g_reset_and_update_link_volume_based_on_ODME_columns(int number_of_links, int iteration_no, double& system_gap) { float total_gap = 0; float sub_total_gap_link_count = 0; float sub_total_system_gap_count = 0; system_gap = 0; float sub_total_gap_P_count = 0; float sub_total_gap_A_count = 0; double total_system_travel_cost = 0; double total_system_travel_time = 0; double total_system_demand = 0; double total_system_UE_gap = 0; // reset the link volume for (int i = 0; i < number_of_links; ++i) { for (int tau = 0; tau < assignment.g_number_of_demand_periods; ++tau) { // used in travel time calculation g_link_vector[i].PCE_volume_per_period[tau] = 0; g_link_vector[i].person_volume_per_period[tau] = 0; for (int at = 0; at < assignment.g_AgentTypeVector.size(); ++at) g_link_vector[i].person_volume_per_period_per_at[tau][at] = 0; } for (int at = 0; at < assignment.g_AgentTypeVector.size(); ++at) for (int og = 0; og < assignment.g_number_of_analysis_districts; ++og) { g_link_vector[i].person_volume_per_district_per_at[og][at] = 0; } } // reset the estimated production and attraction for (int orig = 0; orig < g_zone_vector.size(); ++orig) // o { g_zone_vector[orig].est_attraction = 0; g_zone_vector[orig].est_production = 0; } for (int at = 0; at < assignment.g_AgentTypeVector.size(); ++at) //m { int zone_size = g_zone_vector.size(); int tau_size = assignment.g_DemandPeriodVector.size(); float PCE_ratio = assignment.g_AgentTypeVector[at].PCE; float OCC_ratio = assignment.g_AgentTypeVector[at].OCC; #pragma omp parallel for for (int orig = 0; orig < zone_size; ++orig) // o { int from_zone_sindex = g_zone_vector[orig].sindex; if (from_zone_sindex == -1) continue; int analysis_district_id = assignment.g_zone_seq_no_to_analysis_distrct_id_mapping[orig]; std::map<int, CColumnPath>::iterator it; float link_volume_contributed_by_path_volume; int nl; std::map<int, CColumnPath>::iterator it_begin; std::map<int, CColumnPath>::iterator it_end; int column_vector_size; CColumnVector* p_column_pool; for (int dest = 0; dest < zone_size; ++dest) //d { int to_zone_sindex = g_zone_vector[dest].sindex; if (to_zone_sindex == -1) continue; for (int tau = 0; tau < tau_size; ++tau) //tau { p_column_pool = &(assignment.g_column_pool[from_zone_sindex][to_zone_sindex][at][tau]); if (p_column_pool->od_volume > 0) { // continuous: type 0 column_vector_size = p_column_pool->path_node_sequence_map.size(); it_begin = p_column_pool->path_node_sequence_map.begin(); it_end = p_column_pool->path_node_sequence_map.end(); double least_cost = 999999; int least_cost_path_seq_no = -1; int least_cost_path_node_sum_index = -1; int path_seq_count = 0; double path_toll = 0; double path_gradient_cost = 0; double path_distance = 0; double path_travel_time = 0; int link_seq_no; double link_travel_time; double total_switched_out_path_volume = 0; double step_size = 0; double previous_path_volume = 0; least_cost = 999999; path_seq_count = 0; it_begin = p_column_pool->path_node_sequence_map.begin(); it_end = p_column_pool->path_node_sequence_map.end(); for (it = it_begin; it != it_end; ++it) { total_system_demand += it->second.path_volume; path_toll = 0; path_gradient_cost = 0; path_distance = 0; path_travel_time = 0; for (int nl = 0; nl < it->second.m_link_size; ++nl) // arc a { link_seq_no = it->second.path_link_vector[nl]; link_travel_time = g_link_vector[link_seq_no].travel_time_per_period[tau]; path_travel_time += link_travel_time; } it->second.path_toll = path_toll; it->second.path_travel_time = path_travel_time; total_system_travel_time += (it->second.path_travel_time * it->second.path_volume); if (column_vector_size == 1) // only one path { break; } if (path_travel_time < least_cost) { least_cost = path_travel_time; least_cost_path_seq_no = it->second.path_seq_no; least_cost_path_node_sum_index = it->first; } #pragma omp critical { total_system_travel_cost += (it->second.path_travel_time * it->second.path_volume); } } // end for each path if (column_vector_size >= 2) { // step 2: calculate gradient cost difference for each column path total_switched_out_path_volume = 0; for (it = it_begin; it != it_end; ++it) { if (it->second.path_seq_no != least_cost_path_seq_no) //for non-least cost path { it->second.UE_gap = it->second.path_travel_time - least_cost; it->second.UE_relative_gap = (it->second.path_travel_time - least_cost) / max(0.0001, least_cost); #pragma omp critical { total_system_UE_gap += (it->second.UE_gap * it->second.path_volume); } } } } // end for each path for (it = it_begin; it != it_end; ++it) // path k { link_volume_contributed_by_path_volume = it->second.path_volume; // assign all OD flow to this first path #pragma omp critical { g_zone_vector[orig].est_production += it->second.path_volume; g_zone_vector[dest].est_attraction += it->second.path_volume; } // add path volume to link volume for (nl = 0; nl < it->second.m_link_size; ++nl) // arc a { link_seq_no = it->second.path_link_vector[nl]; // MSA updating for the existing column pools // if iteration_index = 0; then update no flow discount is used (for the column pool case) #pragma omp critical { g_link_vector[link_seq_no].PCE_volume_per_period[tau] += link_volume_contributed_by_path_volume * PCE_ratio; g_link_vector[link_seq_no].person_volume_per_period[tau] += link_volume_contributed_by_path_volume * OCC_ratio; g_link_vector[link_seq_no].person_volume_per_period_per_at[tau][at] += link_volume_contributed_by_path_volume; // pure volume, not consider PCE g_link_vector[link_seq_no].person_volume_per_district_per_at[analysis_district_id][at] += link_volume_contributed_by_path_volume; // pure volume, not consider PCE } } } } } } } } int total_link_count = 0; // calcualte deviation for each measurement type for (int i = 0; i < number_of_links; ++i) { g_link_vector[i].calculate_dynamic_VDFunction(iteration_no, false, g_link_vector[i].vdf_type); for (int tau = 0; tau < assignment.g_DemandPeriodVector.size(); ++tau) //tau { if (assignment.g_DemandPeriodVector[tau].number_of_demand_files == 0) continue; if (g_link_vector[i].VDF_period[tau].obs_count >= 1) // with data { g_link_vector[i].VDF_period[tau].est_count_dev = g_link_vector[i].PCE_volume_per_period[tau] + g_link_vector[i].VDF_period[tau].preload - g_link_vector[i].VDF_period[tau].obs_count; if (dtalog.debug_level() == 2) { dtalog.output() << "link " << g_node_vector[g_link_vector[i].from_node_seq_no].node_id << "->" << g_node_vector[g_link_vector[i].to_node_seq_no].node_id << "obs:, " << g_link_vector[i].VDF_period[tau].obs_count << "est:, " << g_link_vector[i].PCE_volume_per_period[tau] << "dev:," << g_link_vector[i].VDF_period[tau].est_count_dev << endl; } if (g_link_vector[i].VDF_period[tau].upper_bound_flag == 0) { total_gap += abs(g_link_vector[i].VDF_period[tau].est_count_dev); sub_total_gap_link_count += fabs(g_link_vector[i].VDF_period[tau].est_count_dev / g_link_vector[i].VDF_period[tau].obs_count); sub_total_system_gap_count += g_link_vector[i].VDF_period[tau].est_count_dev / g_link_vector[i].VDF_period[tau].obs_count; } else { // upper bound constraints if (g_link_vector[i].VDF_period[tau].est_count_dev > 0) { total_gap += abs(g_link_vector[i].VDF_period[tau].est_count_dev); sub_total_gap_link_count += fabs(g_link_vector[i].VDF_period[tau].est_count_dev / g_link_vector[i].VDF_period[tau].obs_count); sub_total_system_gap_count += g_link_vector[i].VDF_period[tau].est_count_dev / g_link_vector[i].VDF_period[tau].obs_count; } } total_link_count += 1; } } } //for (int orig = 0; orig < g_zone_vector.size(); ++orig) // o //{ // if (g_zone_vector[orig].obs_attraction >= 1) // with observation // { // g_zone_vector[orig].est_attraction_dev = g_zone_vector[orig].est_attraction - g_zone_vector[orig].obs_attraction; // if (dtalog.debug_level() == 2) // { // dtalog.output() << "zone " << g_zone_vector[orig].zone_id << "A: obs:" << g_zone_vector[orig].obs_attraction // << ",est:," << g_zone_vector[orig].est_attraction << ",dev:," << g_zone_vector[orig].est_attraction_dev << endl; // } // total_gap += abs(g_zone_vector[orig].est_attraction_dev); // sub_total_gap_A_count += g_zone_vector[orig].est_attraction_dev / g_zone_vector[orig].obs_attraction; // } // if (g_zone_vector[orig].obs_production >= 1) // with observation // { // g_zone_vector[orig].est_production_dev = g_zone_vector[orig].est_production - g_zone_vector[orig].obs_production; // if (dtalog.debug_level() == 2) // { // dtalog.output() << "zone " << g_zone_vector[orig].zone_id << "P: obs:" << g_zone_vector[orig].obs_production // << ",est:," << g_zone_vector[orig].est_production << ",dev:," << g_zone_vector[orig].est_production_dev << endl; // } // total_gap += abs(g_zone_vector[orig].est_production_dev); // sub_total_gap_P_count += g_zone_vector[orig].est_production_dev / g_zone_vector[orig].obs_production; // } //} dtalog.output() << "ODME #" << iteration_no << ", link MAE= " << total_gap / max(1, total_link_count) << ",link_MAPE: " << (sub_total_gap_link_count) / max(1, total_link_count) * 100 << "%,system_MPE: " << (sub_total_system_gap_count) / max(1, total_link_count) * 100 << "%,avg_tt = " << total_system_travel_time / max(0.1, total_system_demand) << "(min) " << ",UE gap =" << total_system_UE_gap / max(0.00001, total_system_demand) << "(min)" << " = (" << total_system_UE_gap / max(0.00001, total_system_travel_time) * 100 << " %)" << endl; double gap = sub_total_gap_link_count / max(1, total_link_count); system_gap = sub_total_system_gap_count / max(1, total_link_count); return gap; } void g_update_gradient_cost_and_assigned_flow_in_column_pool(Assignment& assignment, int inner_iteration_number, bool b_sensitivity_analysis_flag) { double total_system_cost_gap = 0; float total_relative_gap = 0; double total_system_travel_cost = 0; double total_system_travel_time = 0; double total_system_demand = 0; // we can have a recursive formulat to reupdate the current link volume by a factor of k/(k+1), // and use the newly generated path flow to add the additional 1/(k+1) g_reset_and_update_link_volume_based_on_columns(g_link_vector.size(), inner_iteration_number, false, b_sensitivity_analysis_flag); if (b_sensitivity_analysis_flag == true) // check estimation counts { for (int i = 0; i < g_link_vector.size(); ++i) { for (int tau = 0; tau < assignment.g_number_of_demand_periods; ++tau) { if (g_link_vector[i].VDF_period[tau].obs_count >= 1) // with data { g_link_vector[i].VDF_period[tau].est_count_dev = g_link_vector[i].PCE_volume_per_period[tau] + g_link_vector[i].VDF_period[tau].preload - g_link_vector[i].VDF_period[tau].obs_count; } } } } // step 4: based on newly calculated path volumn, update volume based travel time, and update volume based resource balance, update gradie update_link_travel_time_and_cost(inner_iteration_number); // step 0 // assignment.summary_file << ",iteration,key,o,d,at,tau,volume,"<< endl; //step 1: calculate shortest path at inner iteration of column flow updating //#pragma omp parallel for for (int orig = 0; orig < g_zone_vector.size(); ++orig) // o { CColumnVector* p_column_pool; std::map<int, CColumnPath>::iterator it, it_begin, it_end; int column_vector_size; double least_gradient_cost = 999999; int least_gradient_cost_path_seq_no = -1; int least_gradient_cost_path_node_sum_index = -1; int path_seq_count = 0; double path_toll = 0; double path_gradient_cost = 0; double path_distance = 0; double path_travel_time = 0; int link_seq_no; double link_travel_time; double total_switched_out_path_volume = 0; double step_size = 0; double previous_path_volume = 0; int from_zone_sindex = g_zone_vector[orig].sindex; if (from_zone_sindex == -1) continue; for (int dest = 0; dest < g_zone_vector.size(); ++dest) //d { int to_zone_sindex = g_zone_vector[dest].sindex; if (to_zone_sindex == -1) continue; for (int at = 0; at < assignment.g_AgentTypeVector.size(); ++at) //m { for (int tau = 0; tau < assignment.g_DemandPeriodVector.size(); ++tau) //tau { p_column_pool = &(assignment.g_column_pool[from_zone_sindex][to_zone_sindex][at][tau]); if (p_column_pool->od_volume > 0) { double diff = p_column_pool->od_volume - p_column_pool->prev_od_volume; if (b_sensitivity_analysis_flag && inner_iteration_number >= 1) { if (diff < -0.0001 || diff > 0.0001) { int idebug = 1; } if (inner_iteration_number >= 1) diff = p_column_pool->od_volume - p_column_pool->od_volume_per_iteration_map[inner_iteration_number - 1]; if (diff < -0.0001 || diff > 0.0001) { int idebug = 1; } } if (b_sensitivity_analysis_flag) { if (g_zone_vector[orig].zone_id == 6 && g_zone_vector[dest].zone_id == 2) { int idebug = 1; } } p_column_pool->prev_od_volume = p_column_pool->od_volume; column_vector_size = p_column_pool->path_node_sequence_map.size(); if (b_sensitivity_analysis_flag) { p_column_pool->od_volume_per_iteration_map[inner_iteration_number] = p_column_pool->od_volume; } // scan through the map with different node sum for different paths /// step 1: update gradient cost for each column path least_gradient_cost = 999999; least_gradient_cost_path_seq_no = -1; least_gradient_cost_path_node_sum_index = -1; path_seq_count = 0; it_begin = p_column_pool->path_node_sequence_map.begin(); it_end = p_column_pool->path_node_sequence_map.end(); bool least_path_passing_improvement_flag = false; for (it = it_begin; it != it_end; ++it) { path_toll = 0; path_gradient_cost = 0; path_distance = 0; path_travel_time = 0; for (int nl = 0; nl < it->second.m_link_size; ++nl) // arc a { link_seq_no = it->second.path_link_vector[nl]; path_toll += g_link_vector[link_seq_no].VDF_period[tau].toll[at]; path_distance += g_link_vector[link_seq_no].link_distance_VDF; link_travel_time = g_link_vector[link_seq_no].travel_time_per_period[tau]; path_travel_time += link_travel_time; path_gradient_cost += g_link_vector[link_seq_no].get_generalized_first_order_gradient_cost_of_second_order_loss_for_agent_type(tau, at); } it->second.path_toll = path_toll; it->second.path_travel_time = path_travel_time; it->second.path_gradient_cost = path_gradient_cost; if (b_sensitivity_analysis_flag == false) it->second.path_time_per_iteration_map[inner_iteration_number] = path_travel_time; else // SA mode it->second.path_time_per_iteration_SA_map[inner_iteration_number] = path_travel_time; #pragma omp critical { total_system_travel_time += (it->second.path_travel_time * it->second.path_volume); total_system_demand += it->second.path_volume; if (column_vector_size == 1) // only one path { total_system_travel_cost += (it->second.path_gradient_cost * it->second.path_volume); } } if (path_gradient_cost < least_gradient_cost) { least_gradient_cost = path_gradient_cost; least_gradient_cost_path_seq_no = it->second.path_seq_no; least_gradient_cost_path_node_sum_index = it->first; if (it->second.network_design_flag) { least_path_passing_improvement_flag = 1; } } } if (column_vector_size >= 2) { // step 2: calculate gradient cost difference for each column path total_switched_out_path_volume = 0; for (it = it_begin; it != it_end; ++it) { if (it->second.path_seq_no != least_gradient_cost_path_seq_no) //for non-least cost path { it->second.path_gradient_cost_difference = it->second.path_gradient_cost - least_gradient_cost; //if(it->second.path_gradient_cost_difference >0.0001f) { it->second.path_gradient_cost_relative_difference = it->second.path_gradient_cost_difference / max(0.0001, least_gradient_cost); } #pragma omp critical { total_system_cost_gap += (it->second.path_gradient_cost_difference * it->second.path_volume); total_system_travel_cost += (it->second.path_gradient_cost * it->second.path_volume); } if (b_sensitivity_analysis_flag == true) // SA stages { //float est_count_dev = 0; //bool network_design_flag = false; //for (int nl = 0; nl < it->second.m_link_size; ++nl) // arc a //{ // // step 3.3 link flow gradient // link_seq_no = it->second.path_link_vector[nl]; // //if (g_link_vector[link_seq_no].tmc_corridor_name .size() > 0) // // network_design_flag = true; // if (g_link_vector[link_seq_no].VDF_period[tau].obs_count >= 1) // { // path_gradient_cost += g_link_vector[link_seq_no].VDF_period[tau].est_count_dev; // est_count_dev += g_link_vector[link_seq_no].VDF_period[tau].est_count_dev; // //if (g_link_vector[link_seq_no].VDF_period[tau].network_design_flag==0 && g_link_vector[link_seq_no].VDF_period[tau].est_count_dev < 0) // if under-report traffic // //{ // // double weight_on_count = 0.0; // // it->second.path_gradient_cost_relative_difference -= weight_on_count* g_link_vector[link_seq_no].VDF_period[tau].est_count_dev; // //} // } //} //step_size = 0.00; //if (least_path_passing_improvement_flag) //{ // if(network_design_flag == false) step_size = 0.05; // small changes //} // step_size = 1.0 / (inner_iteration_number + 2) * p_column_pool->od_volume; //if (network_design_flag) //{ // // step_size = 1.0 / (inner_iteration_number + 2) * p_column_pool->od_volume; // assignment.summary_file << "," << inner_iteration_number // << "," << orig // << "-" << dest // << "-" << at // << "-" << tau // << "," << orig // << "," << dest // << "," << at // << "," << tau // << "," << p_column_pool->od_volume // << "," << step_size * it->second.path_gradient_cost_relative_difference // << endl; //} } else { // column updating step size step_size = 1.0 / (inner_iteration_number + 2) * p_column_pool->od_volume; } previous_path_volume = it->second.path_volume; //b double flow_shift = step_size * max(0.0000, it->second.path_gradient_cost_relative_difference); //c, must be positive if (it->second.path_gradient_cost_relative_difference > 3 * 60) // difference more than 3 hours { flow_shift = it->second.path_volume; //switch out } if (flow_shift > it->second.path_volume) { flow_shift = it->second.path_volume; } if (flow_shift >= 0.000001) { int idebug = 1; } //recall that it->second.path_gradient_cost_difference >=0 // step 3.1: shift flow from nonshortest path to shortest path it->second.path_volume = max(0.0, it->second.path_volume - flow_shift); //d // //we use min(step_size to ensure a path is not switching more than 1/n proportion of flow it->second.path_switch_volume = (previous_path_volume - it->second.path_volume); // d-b // should be nonnegative total_switched_out_path_volume += (previous_path_volume - it->second.path_volume); if (fabs(total_switched_out_path_volume) > 0.00001) { int idebug = 1; } } } //step 3.2 consider least cost path, receive all volume shifted from non-shortest path if (least_gradient_cost_path_seq_no != -1 && p_column_pool->path_node_sequence_map.find(least_gradient_cost_path_node_sum_index) != p_column_pool->path_node_sequence_map.end()) { if (least_gradient_cost_path_node_sum_index < 100) { int i_debug = 1; } p_column_pool->path_node_sequence_map[least_gradient_cost_path_node_sum_index].path_volume += total_switched_out_path_volume; if (b_sensitivity_analysis_flag == false) p_column_pool->path_node_sequence_map[least_gradient_cost_path_node_sum_index].path_volume_per_iteration_map[inner_iteration_number] = p_column_pool->path_node_sequence_map[least_gradient_cost_path_node_sum_index].path_volume; else p_column_pool->path_node_sequence_map[least_gradient_cost_path_node_sum_index].path_volume_per_iteration_SA_map[inner_iteration_number] = p_column_pool->path_node_sequence_map[least_gradient_cost_path_node_sum_index].path_volume; #pragma omp critical { total_system_travel_cost += (p_column_pool->path_node_sequence_map[least_gradient_cost_path_node_sum_index].path_gradient_cost * p_column_pool->path_node_sequence_map[least_gradient_cost_path_node_sum_index].path_volume); } } } // record path flow for all paths( including shortst path and non_shortest path) for (it = it_begin; it != it_end; ++it) { if (b_sensitivity_analysis_flag == false) it->second.path_volume_per_iteration_map[inner_iteration_number] = it->second.path_volume; else //SA mode it->second.path_volume_per_iteration_SA_map[inner_iteration_number] = it->second.path_volume; } } } } } } double avg_travel_time = total_system_travel_time / max(0.001, total_system_demand); dtalog.output() << "column updating: iteration= " << inner_iteration_number << ", avg travel time = " << avg_travel_time << "(min), optimization obj = " << total_system_cost_gap << ",Relative_gap=" << total_system_cost_gap * 100.0 / max(0.00001, total_system_travel_cost) << " %" << endl; string stage_str; stage_str = "column updating"; if (b_sensitivity_analysis_flag) stage_str = "sensitivity analaysis"; assignment.summary_file2 << stage_str.c_str() << ",iteration," << inner_iteration_number << ",total_system_demand," << total_system_demand << ",avg travel time," << avg_travel_time << ",optimization obj," << total_system_cost_gap << ",relative_gap," << total_system_cost_gap * 100.0 / max(0.00001, total_system_travel_cost) << "," << endl; } void g_classification_in_column_pool(Assignment& assignment) { int impact_OD_counts = 0; int impact_OD_counts_detour = 0; //#pragma omp parallel for for (int orig = 0; orig < g_zone_vector.size(); ++orig) // o { CColumnVector* p_column_pool; std::map<int, CColumnPath>::iterator it, it_begin, it_end; int column_vector_size; int from_zone_sindex = g_zone_vector[orig].sindex; if (from_zone_sindex == -1) continue; int link_seq_no; for (int dest = 0; dest < g_zone_vector.size(); ++dest) //d { int to_zone_sindex = g_zone_vector[dest].sindex; if (to_zone_sindex == -1) continue; for (int at = 0; at < assignment.g_AgentTypeVector.size(); ++at) //m { for (int tau = 0; tau < assignment.g_DemandPeriodVector.size(); ++tau) //tau { p_column_pool = &(assignment.g_column_pool[from_zone_sindex][to_zone_sindex][at][tau]); if (p_column_pool->od_volume > 0) { if (g_zone_vector[orig].zone_id == 6 && g_zone_vector[dest].zone_id == 2) { int idebug = 1; } column_vector_size = p_column_pool->path_node_sequence_map.size(); // scan through the map with different node sum for different paths /// step 1: update gradient cost for each column path it_begin = p_column_pool->path_node_sequence_map.begin(); it_end = p_column_pool->path_node_sequence_map.end(); bool least_path_passing_improvement_flag = false; // scan all paths in this OD pair int path_count = 0; int network_design_path_count = 0; for (it = it_begin; it != it_end; ++it) { for (int nl = 0; nl < it->second.m_link_size; ++nl) // arc a { link_seq_no = it->second.path_link_vector[nl]; if (g_link_vector[link_seq_no].VDF_period[tau].network_design_flag != 0) // screening condition 1: passing through the network design location { it->second.network_design_flag = 1; // to be revised: passing through work zone, and with signal timing enhancemnets } } if (it->second.network_design_flag) network_design_path_count++; path_count++; } if (network_design_path_count >= 1) { if (network_design_path_count == path_count) { p_column_pool->OD_network_design_flag = 1; impact_OD_counts++; } else { p_column_pool->OD_network_design_flag = 2; // more than 2 alterantive paths with respect to the newtork design location impact_OD_counts_detour++; } } if (p_column_pool->OD_network_design_flag == 2) // { // scan all paths in this OD pair again // mark alternative paths for (it = it_begin; it != it_end; ++it) { if (it->second.network_design_flag == 0) { it->second.network_design_detour_mode = 2; // detour } else { it->second.network_design_detour_mode = 1; // main passing path } } } } } // for each tau }// for each agent type mode } // for each d } string stage_str; stage_str = "classification"; // assignment.summary_file2 << stage_str.c_str() << ",impact_OD_counts," << impact_OD_counts << // ",impact_OD_counts_with_detour," << impact_OD_counts_detour << endl; } void g_column_pool_optimization(Assignment& assignment, int column_updating_iterations, bool sensitivity_analysis_flag = false) { // column_updating_iterations is internal numbers of column updating for (int n = 0; n < column_updating_iterations; ++n) { g_update_gradient_cost_and_assigned_flow_in_column_pool(assignment, n, sensitivity_analysis_flag); if (dtalog.debug_level() >= 3) { for (int i = 0; i < g_link_vector.size(); ++i) { dtalog.output() << "link: " << g_node_vector[g_link_vector[i].from_node_seq_no].node_id << "-->" << g_node_vector[g_link_vector[i].to_node_seq_no].node_id << ", " << "flow count:" << g_link_vector[i].PCE_volume_per_period[0] << endl; } } } } void g_column_pool_route_scheduling(Assignment& assignment, int inner_iteration_number) { //step 1: calculate shortest path at inner iteration of column flow updating #pragma omp parallel for for (int orig = 0; orig < g_zone_vector.size(); ++orig) // o { CColumnVector* p_column_pool; std::map<int, CColumnPath>::iterator it, it_begin, it_end; int column_vector_size; int path_seq_count = 0; double path_toll = 0; double path_gradient_cost = 0; double path_distance = 0; double path_travel_time = 0; int link_seq_no; int from_zone_sindex = g_zone_vector[orig].sindex; if (from_zone_sindex == -1) continue; for (int dest = 0; dest < g_zone_vector.size(); ++dest) //d { int to_zone_sindex = g_zone_vector[dest].sindex; if (to_zone_sindex == -1) continue; for (int at = 0; at < assignment.g_AgentTypeVector.size(); ++at) //m { for (int tau = 0; tau < assignment.g_DemandPeriodVector.size(); ++tau) //tau { p_column_pool = &(assignment.g_column_pool[from_zone_sindex][to_zone_sindex][at][tau]); if (p_column_pool->od_volume > 0) { if (assignment.g_AgentTypeVector[at].real_time_information == 1) // case of VMS { column_vector_size = p_column_pool->path_node_sequence_map.size(); // scan through the map with different node sum for different paths path_seq_count = 0; it_begin = p_column_pool->path_node_sequence_map.begin(); it_end = p_column_pool->path_node_sequence_map.end(); //test condition 1: passing through information zone bool b_passing_information_zone = false; int new_orig_zone_id = 0; std::vector <int> link_seq_vector; //test condition 2: passing through capacity impact area bool b_passing_capacity_impact_area = false; for (it = it_begin; it != it_end; ++it) // scan each first-stage original path { if (it->second.path_volume < 0.00001) continue; for (int nl = 0; nl < it->second.m_link_size; ++nl) // arc a { link_seq_no = it->second.path_link_vector[nl]; CLink* p_current_link = &(g_link_vector[link_seq_no]); if (b_passing_information_zone == false && assignment.node_seq_no_2_info_zone_id_mapping.find(p_current_link->to_node_seq_no) != assignment.node_seq_no_2_info_zone_id_mapping.end()) // this node been defined as zone { int zone_id = assignment.node_seq_no_2_info_zone_id_mapping[p_current_link->to_node_seq_no]; int zone_no = assignment.g_zoneid_to_zone_seq_no_mapping[zone_id]; if (assignment.zone_seq_no_2_info_mapping.find(zone_no) != assignment.zone_seq_no_2_info_mapping.end()) // as information zone { b_passing_information_zone = true; new_orig_zone_id = zone_id; // zone id to zone no. for (int nl2 = 0; nl2 <= nl; ++nl2) // arc a { // copy the existing link sequence up to the downstream node id corresponding to the info zone link_seq_no = it->second.path_link_vector[nl2]; link_seq_vector.push_back(link_seq_no); } } } if (p_current_link->capacity_reduction_map.find(tau) != p_current_link->capacity_reduction_map.end()) { b_passing_capacity_impact_area = true; } } if (b_passing_capacity_impact_area == true && b_passing_information_zone == true) { CColumnVector* p_2_stage_column_pool; int info_orig = assignment.g_zoneid_to_zone_seq_no_mapping[new_orig_zone_id]; int from_zone_sindex = g_zone_vector[info_orig].sindex; if (from_zone_sindex == -1) continue; int to_zone_sindex = g_zone_vector[dest].sindex; if (to_zone_sindex == -1) continue; //step 2: fetch the related column pool from the information node/zone p_2_stage_column_pool = &(assignment.g_column_pool[from_zone_sindex][to_zone_sindex][at][tau]); // we come from info_orig but going to the same destination with same at, and assignment period tau // scan through the map with different node sum for different continuous paths std::map<int, CColumnPath>::iterator it2, it_begin2, it_end2; it_begin2 = p_2_stage_column_pool->path_node_sequence_map.begin(); it_end2 = p_2_stage_column_pool->path_node_sequence_map.end(); for (it2 = it_begin2; it2 != it_end2; ++it2) // we can still have k-path from the info zone to to final destination so we need to random select one { for (int nl = 1; nl < it2->second.m_link_size; ++nl) // arc a // exclude virtual link at the end; { link_seq_vector.push_back(it2->second.path_link_vector[nl]); } break; // only connect with the first available second stage path } if (it->second.path_link_vector != NULL) { // copy the updated path (stage1 + stage 2) back to the path link vector delete it->second.path_link_vector; it->second.path_link_vector = new int[link_seq_vector.size()]; for (int l = 0; l < link_seq_vector.size(); l++) { it->second.path_link_vector[l] = link_seq_vector[l]; } it->second.m_link_size = link_seq_vector.size(); // copy the updated path (stage1 + stage 2) back to the path node vector delete it->second.path_node_vector; it->second.path_node_vector = new int[link_seq_vector.size() + 1]; // first node it->second.path_node_vector[0] = g_link_vector[link_seq_vector[0]].from_node_seq_no; // remaining nodes to the end of path for (int l = 0; l < link_seq_vector.size(); l++) { it->second.path_node_vector[l + 1] = g_link_vector[link_seq_vector[l]].to_node_seq_no; } it->second.m_node_size = link_seq_vector.size() + 1; } p_2_stage_column_pool->od_volume += it->second.path_volume;// carry over the switching path flow to the second path volume count p_2_stage_column_pool->information_type = 1; it2->second.path_volume += it->second.path_volume;// carry over the switching path flow to the second path volume count } // two conditions satisified } //end of scanning for the first stage path in the column pool } // agent type is real time agent type } // with positve OD volume } // tau } //agent type } //dest } // orig dtalog.output() << " updating"; } void g_rt_info_column_generation(Assignment* p_assignment, float current_time_in_min, int recording_flag = 0) { //dtalog.output() << "Begin the computing of " << g_NetworkForRTSP_vector.size() << " RTSP networks in CPU." << endl; clock_t start_t0, end_t0, total_t0; start_t0 = clock(); #pragma omp parallel for // step 3: C++ open mp automatically create n threads., each thread has its own computing thread on a cpu core for (int blk = 0; blk < g_NetworkForRTSP_vector.size(); ++blk) { NetworkForSP* pNetwork = g_NetworkForRTSP_vector[blk]; if (assignment.g_DemandPeriodVector[pNetwork->m_tau].starting_time_slot_no * MIN_PER_TIMESLOT > current_time_in_min) // RT network is for a later time interval continue; pNetwork->optimal_backward_label_correcting_from_destination(blk, p_assignment, current_time_in_min, pNetwork->m_RT_dest_zone, pNetwork->m_RT_dest_node, -1, recording_flag); } end_t0 = clock(); total_t0 = (end_t0 - start_t0); int second = total_t0 / 1000.0; int min = second / 60; int sec = second - min * 60; //dtalog.output() << "CPU Running Time for RT shortest path: " << min << " min " << sec << " sec" << endl; assignment.summary_file << ", RT shortest path at time =," << current_time_in_min << "min" << endl; } void g_column_pool_activity_scheduling(Assignment& assignment, int inner_iteration_number) { //step 1: calculate shortest path at inner iteration of column flow updating for (int orig = 0; orig < g_zone_vector.size(); ++orig) // o { int from_zone_sindex = g_zone_vector[orig].sindex; if (from_zone_sindex == -1) continue; CColumnVector* p_column_pool; int path_seq_count = 0; double path_toll = 0; double path_gradient_cost = 0; double path_distance = 0; double path_travel_time = 0; for (int dest = 0; dest < g_zone_vector.size(); ++dest) //d { int to_zone_sindex = g_zone_vector[dest].sindex; if (to_zone_sindex == -1) continue; for (int at = 0; at < assignment.g_AgentTypeVector.size(); ++at) //m { for (int tau = 0; tau < assignment.g_DemandPeriodVector.size(); ++tau) //tau { p_column_pool = &(assignment.g_column_pool[from_zone_sindex][to_zone_sindex][at][tau]); if (p_column_pool->od_volume > 0) { if (p_column_pool->activity_zone_no_vector.size()) // case of activity zones { p_column_pool->path_node_sequence_map.clear(); // remove existing single OD pair based routes std::vector <int> link_seq_vector; // for each origin and detination pair in activity zone no to perform routing continuously for (int az = 0; az < p_column_pool->activity_zone_no_vector.size() - 1; az++) // key step: go through each activty OD pair { // 0 will the origin // last one will destination int aat = p_column_pool->activity_agent_type_no_vector[az]; CColumnVector* p_2_stage_column_pool; int activity_orig = p_column_pool->activity_zone_no_vector[az]; int activity_dest = p_column_pool->activity_zone_no_vector[az + 1]; int from_zone_sindex = g_zone_vector[activity_orig].sindex; if (from_zone_sindex == -1) continue; int to_zone_sindex = g_zone_vector[activity_dest].sindex; if (to_zone_sindex == -1) continue; //step 2: fetch the related column pool from the information node/zone p_2_stage_column_pool = &(assignment.g_column_pool[from_zone_sindex][to_zone_sindex][aat][tau]); // we come from info_orig but going to the same destination with same at, and assignment period tau // scan through the map with different node sum for different continuous paths std::map<int, CColumnPath>::iterator it2, it_begin2, it_end2; it_begin2 = p_2_stage_column_pool->path_node_sequence_map.begin(); it_end2 = p_2_stage_column_pool->path_node_sequence_map.end(); for (it2 = it_begin2; it2 != it_end2; ++it2) // we can still have k-path from the info zone to to final destination so we need to random select one { for (int nl = 1; nl < it2->second.m_link_size - 1; ++nl) // arc a // exclude virtual link in the beginning and at the end; { link_seq_vector.push_back(it2->second.path_link_vector[nl]); } break; // only connect with the first available second stage path } } if (link_seq_vector.size() == 0) { int i_debug = 1; continue; } int node_sum = 0; for (int l = 0; l < link_seq_vector.size(); l++) { node_sum += link_seq_vector[l]; } // add this unique path // later we can add k activity paths int path_count = p_column_pool->path_node_sequence_map.size(); p_column_pool->path_node_sequence_map[node_sum].path_seq_no = path_count; p_column_pool->path_node_sequence_map[node_sum].path_volume = p_column_pool->od_volume; p_column_pool->path_node_sequence_map[node_sum].path_toll = 0; p_column_pool->path_node_sequence_map[node_sum].path_link_vector = new int[link_seq_vector.size()]; p_column_pool->path_node_sequence_map[node_sum].path_node_vector = new int[link_seq_vector.size() + 1]; for (int l = 0; l < link_seq_vector.size(); l++) { p_column_pool->path_node_sequence_map[node_sum].path_link_vector[l] = link_seq_vector[l]; p_column_pool->path_node_sequence_map[node_sum].path_link_STL_vector.push_back(link_seq_vector[l]); } p_column_pool->path_node_sequence_map[node_sum].m_link_size = link_seq_vector.size(); // copy the updated path (stage1 + stage 2) back to the path node vector // first node p_column_pool->path_node_sequence_map[node_sum].path_node_vector[0] = g_link_vector[link_seq_vector[0]].from_node_seq_no; // remaining nodes to the end of path for (int l = 0; l < link_seq_vector.size(); l++) { p_column_pool->path_node_sequence_map[node_sum].path_node_vector[l + 1] = g_link_vector[link_seq_vector[l]].to_node_seq_no; } p_column_pool->path_node_sequence_map[node_sum].m_node_size = link_seq_vector.size() + 1; } //end of conditions for activity chain } // with positve OD volume } // tau } //agent type } //dest } // orig dtalog.output() << " updating"; }
chetrs.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 -> c, 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_chetrf. * ******************************************************************************* * * @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 Hermitian matrix A, * as computed by plasma_chetrf. * * @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_cgbtrf. * * @param[in] ldt * The leading dimension of the array T. * * @param[in] ipiv * The pivot indices used for chetrf; 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 cgbtrf; 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_chetrs * @sa plasma_chetrs * @sa plasma_dsytrs * @sa plasma_ssytrs * @sa plasma_chetrf * ******************************************************************************/ int plasma_chetrs(plasma_enum_t uplo, int n, int nrhs, plasma_complex32_t *pA, int lda, int *ipiv, plasma_complex32_t *pT, int ldt, int *ipiv2, plasma_complex32_t *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, PlasmaComplexFloat, 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 cgetrf 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(PlasmaComplexFloat, 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(PlasmaComplexFloat, 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(PlasmaComplexFloat, 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_ctr2desc(pA, lda, A, &sequence, &request); plasma_omp_cpb2desc(pT, ldt, T, &sequence, &request); plasma_omp_cge2desc(pB, ldb, B, &sequence, &request); } #pragma omp parallel #pragma omp master { // Call the tile async function. plasma_omp_chetrs(uplo, A, ipiv, T, ipiv2, B, &sequence, &request); } #pragma omp parallel #pragma omp master { // Translate back to LAPACK layout. plasma_omp_cdesc2ge(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_chetrs(). * 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^H*U or A = L*L^H, computed by plasma_cpotrf. * * @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_chetrs * @sa plasma_omp_chetrs * @sa plasma_omp_chetrs * @sa plasma_omp_dsytrs * @sa plasma_omp_ssytrs * @sa plasma_omp_chetrf * ******************************************************************************/ void plasma_omp_chetrs(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_pcgeswp(PlasmaRowwise, B, ipiv, 1, sequence, request); #pragma omp taskwait plasma_pctrsm(PlasmaLeft, PlasmaLower, PlasmaNoTrans, PlasmaUnit, 1.0, vA, vB, sequence, request); } // solve with band matrix T #pragma omp taskwait plasma_pctbsm(PlasmaLeft, PlasmaLower, PlasmaNoTrans, PlasmaUnit, 1.0, T, B, ipiv2, sequence, request); plasma_pctbsm(PlasmaLeft, PlasmaUpper, PlasmaNoTrans, PlasmaNonUnit, 1.0, T, B, ipiv2, sequence, request); // backward-substitution with L^H if (A.m > A.nb) { plasma_pctrsm(PlasmaLeft, PlasmaLower, PlasmaConjTrans, PlasmaUnit, 1.0, vA, vB, sequence, request); #pragma omp taskwait plasma_pcgeswp(PlasmaRowwise, B, ipiv, -1, sequence, request); } } else { // TODO: upper } }
QuadtreeCartesianEuclid.h
/* * Quadtree.h * * Created on: 21.05.2014 * Author: Moritz v. Looz (moritz.looz-corswarem@kit.edu) */ #ifndef QUADTREECARTESIANEUCLID_H_ #define QUADTREECARTESIANEUCLID_H_ #include <vector> #include <memory> #include <cmath> #include <omp.h> #include <functional> #include "QuadNodeCartesianEuclid.h" namespace NetworKit { template <class T> class QuadtreeCartesianEuclid { friend class QuadTreeCartesianEuclidGTest; public: /** * @param maxR Radius of the managed area. Must be smaller than 1. * @param theoreticalSplit If true, split cells to get the same area in each child cell. Default is false * @param alpha dispersion Parameter of the point distribution. Only has an effect if theoretical split is true * @param capacity How many points can inhabit a leaf cell before it is split up? * */ QuadtreeCartesianEuclid(Point<double> lower = Point<double>({0.0, 0.0}), Point<double> upper = Point<double>({1.0, 1.0}), bool theoreticalSplit=false, count capacity=1000) { assert(lower.getDimensions() == upper.getDimensions()); root = QuadNodeCartesianEuclid<T>(lower, upper, capacity, theoreticalSplit); this->lower = lower; this->upper = upper; } QuadtreeCartesianEuclid(const vector<Point<double> > &positions, const vector<T> &content, bool theoreticalSplit=false, count capacity=1000) { const count n = positions.size(); assert(content.size() == n); assert(n > 0); this->dimension = positions[0].getDimensions(); vector<double> lowerValue(dimension); vector<double> upperValue(dimension); for (index d = 0; d < dimension; d++) { lowerValue[d] = positions[0].at(d); upperValue[d] = positions[0].at(d); } for (Point<double> pos : positions) { assert(pos.getDimensions() == dimension); for (index d = 0; d < dimension; d++) { if (pos[d] < lowerValue[d]) lowerValue[d] = pos[d]; if (pos[d] > upperValue[d]) upperValue[d] = pos[d]; } } //the upper limit is open, so it needs to be above the points for (index d = 0; d < dimension; d++) { upperValue[d] = std::nextafter(upperValue[d], std::numeric_limits<double>::max()); } this->lower = Point<double>(lowerValue); this->upper = Point<double>(upperValue); root = QuadNodeCartesianEuclid<T>(lower, upper, capacity, theoreticalSplit); for (index i = 0; i < n; i++) { assert(content[i] < n); root.addContent(content[i], positions[i]); } } /** * @param newcomer content to be added at point x * @param angle angular coordinate of x * @param R radial coordinate of x */ void addContent(T newcomer, Point<double> pos) { root.addContent(newcomer, pos); } /** * @param newcomer content to be removed at point x * @param angle angular coordinate of x * @param R radial coordinate of x */ bool removeContent(T toRemove, Point<double> pos) { return root.removeContent(toRemove, pos); } /** * Get all elements, regardless of position * * @return vector<T> of elements */ vector<T> getElements() const { return root.getElements(); } void extractCoordinates(vector<Point<double> > &posContainer) const { root.getCoordinates(posContainer); } void getElementsInEuclideanCircle(const Point<double> circleCenter, const double radius, vector<T> &circleDenizens) const { root.getElementsInEuclideanCircle(circleCenter, radius, circleDenizens); } template<typename L> count getElementsProbabilistically(Point<double> euQuery, L prob, vector<T> &circleDenizens) { return root.getElementsProbabilistically(euQuery, prob, circleDenizens); } void recount() { root.recount(); } count size() const { return root.size(); } count height() const { return root.height(); } count countLeaves() const { return root.countLeaves(); } index indexSubtree(index nextID) { return root.indexSubtree(nextID); } index getCellID(Point<double> pos) const { return root.getCellID(pos); } void reindex() { #pragma omp parallel { #pragma omp single nowait { root.reindex(0); } } } /** * trims the vectors used to hold the content in the leaf cells. Reduces memory usage, makes changes slower */ void trim() { root.trim(); } private: QuadNodeCartesianEuclid<T> root; Point<double> lower; Point<double> upper; count dimension; }; } #endif /* QUADTREE_H_ */
3d7pt.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 * 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, 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]); double ****A = (double ****) malloc(sizeof(double***)*2); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][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] = 4; tile_size[3] = 256; 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; const double alpha = 0.0876; const double beta = 0.0765; // 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); } } } #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,12);t1++) { lbp=max(ceild(t1,2),ceild(24*t1-Nt+3,24)); ubp=min(floord(Nt+Nz-4,24),floord(12*t1+Nz+9,24)); #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(24*t2-Nz,4)),3*t1);t3<=min(min(min(floord(Nt+Ny-4,4),floord(12*t1+Ny+21,4)),floord(24*t2+Ny+20,4)),floord(24*t1-24*t2+Nz+Ny+19,4));t3++) { for (t4=max(max(max(0,ceild(3*t1-63,64)),ceild(24*t2-Nz-252,256)),ceild(4*t3-Ny-252,256));t4<=min(min(min(min(floord(4*t3+Nx,256),floord(Nt+Nx-4,256)),floord(12*t1+Nx+21,256)),floord(24*t2+Nx+20,256)),floord(24*t1-24*t2+Nz+Nx+19,256));t4++) { for (t5=max(max(max(max(max(0,12*t1),24*t1-24*t2+1),24*t2-Nz+2),4*t3-Ny+2),256*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,12*t1+23),24*t2+22),4*t3+2),256*t4+254),24*t1-24*t2+Nz+21);t5++) { for (t6=max(max(24*t2,t5+1),-24*t1+24*t2+2*t5-23);t6<=min(min(24*t2+23,-24*t1+24*t2+2*t5),t5+Nz-2);t6++) { for (t7=max(4*t3,t5+1);t7<=min(4*t3+3,t5+Ny-2);t7++) { lbv=max(256*t4,t5+1); ubv=min(256*t4+255,t5+Nx-2); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = ((alpha * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)]) + (beta * (((((A[ t5 % 2][ (-t5+t6) - 1][ (-t5+t7)][ (-t5+t8)] + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) - 1][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) - 1]) + A[ t5 % 2][ (-t5+t6) + 1][ (-t5+t7)][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) + 1][ (-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, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays (Causing performance degradation /* 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]); */ return 0; }
blackscholes.c
// Copyright (c) 2007 Intel Corp. // Black-Scholes // Analytical method for calculating European Options // // // Reference Source: Options, Futures, and Other Derivatives, 3rd Edition, Prentice // Hall, John C. Hull, #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #define DEFINE_PROFILE_DATA_HERE #include <parsec_profiler.h> #ifdef ENABLE_PARSEC_HOOKS #include <hooks.h> #endif // Multi-threaded pthreads header #ifdef ENABLE_THREADS // Add the following line so that icc 9.0 is compatible with pthread lib. #define __thread __threadp MAIN_ENV #undef __thread #endif // Multi-threaded OpenMP header #ifdef ENABLE_OPENMP #include <omp.h> #endif #ifdef ENABLE_TBB #include "tbb/blocked_range.h" #include "tbb/parallel_for.h" #include "tbb/task_scheduler_init.h" #include "tbb/tick_count.h" using namespace std; using namespace tbb; #endif //ENABLE_TBB // Multi-threaded header for Windows #ifdef WIN32 #pragma warning(disable : 4305) #pragma warning(disable : 4244) #include <windows.h> #endif //Precision to use for calculations #define fptype float #define NUM_RUNS 100 typedef struct OptionData_ { fptype s; // spot price fptype strike; // strike price fptype r; // risk-free interest rate fptype divq; // dividend rate fptype v; // volatility fptype t; // time to maturity or option expiration in years // (1yr = 1.0, 6mos = 0.5, 3mos = 0.25, ..., etc) char OptionType; // Option type. "P"=PUT, "C"=CALL fptype divs; // dividend vals (not used in this test) fptype DGrefval; // DerivaGem Reference Value } OptionData; OptionData *data; fptype *prices; int numOptions; int * otype; fptype * sptprice; fptype * strike; fptype * rate; fptype * volatility; fptype * otime; int numError = 0; int nThreads; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // Cumulative Normal Distribution Function // See Hull, Section 11.8, P.243-244 #define inv_sqrt_2xPI 0.39894228040143270286 fptype CNDF ( fptype InputX ) { int sign; fptype OutputX; fptype xInput; fptype xNPrimeofX; fptype expValues; fptype xK2; fptype xK2_2, xK2_3; fptype xK2_4, xK2_5; fptype xLocal, xLocal_1; fptype xLocal_2, xLocal_3; // Check for negative value of InputX if (InputX < 0.0) { InputX = -InputX; sign = 1; } else sign = 0; xInput = InputX; // Compute NPrimeX term common to both four & six decimal accuracy calcs expValues = exp(-0.5f * InputX * InputX); xNPrimeofX = expValues; xNPrimeofX = xNPrimeofX * inv_sqrt_2xPI; xK2 = 0.2316419 * xInput; xK2 = 1.0 + xK2; xK2 = 1.0 / xK2; xK2_2 = xK2 * xK2; xK2_3 = xK2_2 * xK2; xK2_4 = xK2_3 * xK2; xK2_5 = xK2_4 * xK2; xLocal_1 = xK2 * 0.319381530; xLocal_2 = xK2_2 * (-0.356563782); xLocal_3 = xK2_3 * 1.781477937; xLocal_2 = xLocal_2 + xLocal_3; xLocal_3 = xK2_4 * (-1.821255978); xLocal_2 = xLocal_2 + xLocal_3; xLocal_3 = xK2_5 * 1.330274429; xLocal_2 = xLocal_2 + xLocal_3; xLocal_1 = xLocal_2 + xLocal_1; xLocal = xLocal_1 * xNPrimeofX; xLocal = 1.0 - xLocal; OutputX = xLocal; if (sign) { OutputX = 1.0 - OutputX; } return OutputX; } ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// fptype BlkSchlsEqEuroNoDiv( fptype sptprice, fptype strike, fptype rate, fptype volatility, fptype time, int otype, float timet ) { fptype OptionPrice; // local private working variables for the calculation fptype xStockPrice; fptype xStrikePrice; fptype xRiskFreeRate; fptype xVolatility; fptype xTime; fptype xSqrtTime; fptype logValues; fptype xLogTerm; fptype xD1; fptype xD2; fptype xPowerTerm; fptype xDen; fptype d1; fptype d2; fptype FutureValueX; fptype NofXd1; fptype NofXd2; fptype NegNofXd1; fptype NegNofXd2; xStockPrice = sptprice; xStrikePrice = strike; xRiskFreeRate = rate; xVolatility = volatility; xTime = time; xSqrtTime = sqrt(xTime); logValues = log( sptprice / strike ); xLogTerm = logValues; xPowerTerm = xVolatility * xVolatility; xPowerTerm = xPowerTerm * 0.5; xD1 = xRiskFreeRate + xPowerTerm; xD1 = xD1 * xTime; xD1 = xD1 + xLogTerm; xDen = xVolatility * xSqrtTime; xD1 = xD1 / xDen; xD2 = xD1 - xDen; d1 = xD1; d2 = xD2; NofXd1 = CNDF( d1 ); NofXd2 = CNDF( d2 ); FutureValueX = strike * ( exp( -(rate)*(time) ) ); if (otype == 0) { OptionPrice = (sptprice * NofXd1) - (FutureValueX * NofXd2); } else { NegNofXd1 = (1.0 - NofXd1); NegNofXd2 = (1.0 - NofXd2); OptionPrice = (FutureValueX * NegNofXd2) - (sptprice * NegNofXd1); } return OptionPrice; } #ifdef ENABLE_TBB struct mainWork { mainWork() {} mainWork(mainWork &w, tbb::split) {} void operator()(const tbb::blocked_range<int> &range) const { fptype price; int begin = range.begin(); int end = range.end(); for (int i=begin; i!=end; i++) { /* Calling main function to calculate option value based on * Black & Scholes's equation. */ price = BlkSchlsEqEuroNoDiv( sptprice[i], strike[i], rate[i], volatility[i], otime[i], otype[i], 0); prices[i] = price; #ifdef ERR_CHK fptype priceDelta = data[i].DGrefval - price; if( fabs(priceDelta) >= 1e-5 ){ fprintf(stderr,"Error on %d. Computed=%.5f, Ref=%.5f, Delta=%.5f\n", i, price, data[i].DGrefval, priceDelta); numError ++; } #endif } } }; #endif // ENABLE_TBB ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// #ifdef ENABLE_TBB int bs_thread(void *tid_ptr) { int j; tbb::affinity_partitioner a; mainWork doall; for (j=0; j<NUM_RUNS; j++) { tbb::parallel_for(tbb::blocked_range<int>(0, numOptions), doall, a); } return 0; } #else // !ENABLE_TBB #ifdef WIN32 DWORD WINAPI bs_thread(LPVOID tid_ptr){ #else int bs_thread(void *tid_ptr) { #endif PROFILER_TIMER_INIT(0); int i, j; fptype price; fptype priceDelta; int tid = *(int *)tid_ptr; int start = tid * (numOptions / nThreads); int end = start + (numOptions / nThreads); for (j=0; j<NUM_RUNS; j++) { #ifdef ENABLE_OPENMP #pragma omp parallel for private(i, price, priceDelta) for (i=0; i<numOptions; i++) { #else //ENABLE_OPENMP for (i=start; i<end; i++) { #endif //ENABLE_OPENMP /* Calling main function to calculate option value based on * Black & Scholes's equation. */ price = BlkSchlsEqEuroNoDiv( sptprice[i], strike[i], rate[i], volatility[i], otime[i], otype[i], 0); prices[i] = price; #ifdef ERR_CHK priceDelta = data[i].DGrefval - price; if( fabs(priceDelta) >= 1e-4 ){ printf("Error on %d. Computed=%.5f, Ref=%.5f, Delta=%.5f\n", i, price, data[i].DGrefval, priceDelta); numError ++; } #endif } } PROFILER_ADD_TIME(PROFILE_WORK, tid + 1, PROFILER_TIMER_NOW, PROFILER_TIMER(0)); return 0; } #endif //ENABLE_TBB int main (int argc, char **argv) { PROFILER_TIMER_INIT(0); FILE *file; int i; int loopnum; fptype * buffer; int * buffer2; int rv; #ifdef PARSEC_VERSION #define __PARSEC_STRING(x) #x #define __PARSEC_XSTRING(x) __PARSEC_STRING(x) printf("PARSEC Benchmark Suite Version "__PARSEC_XSTRING(PARSEC_VERSION)"\n"); fflush(NULL); #else printf("PARSEC Benchmark Suite\n"); fflush(NULL); #endif //PARSEC_VERSION #ifdef ENABLE_PARSEC_HOOKS __parsec_bench_begin(__parsec_blackscholes); #endif if (argc != 4) { printf("Usage:\n\t%s <nthreads> <inputFile> <outputFile>\n", argv[0]); exit(1); } nThreads = atoi(argv[1]); char *inputFile = argv[2]; char *outputFile = argv[3]; PROFILER_ADD_TIME(PROFILE_WORK_SERIAL, 0, PROFILER_TIMER_NOW, PROFILER_TIMER(0)); PROFILER_TIMER_UPDATE(0); //Read input data from file file = fopen(inputFile, "r"); if(file == NULL) { printf("ERROR: Unable to open file `%s'.\n", inputFile); exit(1); } rv = fscanf(file, "%i", &numOptions); if(rv != 1) { printf("ERROR: Unable to read from file `%s'.\n", inputFile); fclose(file); exit(1); } if(nThreads > numOptions) { printf("WARNING: Not enough work, reducing number of threads to match number of options.\n"); nThreads = numOptions; } #if !defined(ENABLE_THREADS) && !defined(ENABLE_OPENMP) && !defined(ENABLE_TBB) if(nThreads != 1) { printf("Error: <nthreads> must be 1 (serial version)\n"); exit(1); } #endif PROFILER_ADD_TIME(PROFILE_FILE_IO, 0, PROFILER_TIMER_NOW, PROFILER_TIMER(0)); PROFILER_TIMER_UPDATE(0); // alloc spaces for the option data data = (OptionData*)malloc(numOptions*sizeof(OptionData)); prices = (fptype*)malloc(numOptions*sizeof(fptype)); PROFILER_ADD_TIME(PROFILE_MALLOCATOR, 0, PROFILER_TIMER_NOW, PROFILER_TIMER(0)); PROFILER_TIMER_UPDATE(0); for ( loopnum = 0; loopnum < numOptions; ++ loopnum ) { rv = fscanf(file, "%f %f %f %f %f %f %c %f %f", &data[loopnum].s, &data[loopnum].strike, &data[loopnum].r, &data[loopnum].divq, &data[loopnum].v, &data[loopnum].t, &data[loopnum].OptionType, &data[loopnum].divs, &data[loopnum].DGrefval); if(rv != 9) { printf("ERROR: Unable to read from file `%s'.\n", inputFile); fclose(file); exit(1); } } rv = fclose(file); if(rv != 0) { printf("ERROR: Unable to close file `%s'.\n", inputFile); exit(1); } PROFILER_ADD_TIME(PROFILE_FILE_IO, 0, PROFILER_TIMER_NOW, PROFILER_TIMER(0)); PROFILER_TIMER_UPDATE(0); #ifdef ENABLE_THREADS MAIN_INITENV(,8000000,nThreads); #endif printf("Num of Options: %d\n", numOptions); printf("Num of Runs: %d\n", NUM_RUNS); PROFILER_ADD_TIME(PROFILE_WORK_SERIAL, 0, PROFILER_TIMER_NOW, PROFILER_TIMER(0)); #define PAD 256 #define LINESIZE 64 PROFILER_TIMER_UPDATE(0); buffer = (fptype *) malloc(5 * numOptions * sizeof(fptype) + PAD); sptprice = (fptype *) (((unsigned long long)buffer + PAD) & ~(LINESIZE - 1)); strike = sptprice + numOptions; rate = strike + numOptions; volatility = rate + numOptions; otime = volatility + numOptions; buffer2 = (int *) malloc(numOptions * sizeof(fptype) + PAD); otype = (int *) (((unsigned long long)buffer2 + PAD) & ~(LINESIZE - 1)); PROFILER_ADD_TIME(PROFILE_MALLOCATOR, 0, PROFILER_TIMER_NOW, PROFILER_TIMER(0)); PROFILER_TIMER_UPDATE(0); for (i=0; i<numOptions; i++) { otype[i] = (data[i].OptionType == 'P') ? 1 : 0; sptprice[i] = data[i].s; strike[i] = data[i].strike; rate[i] = data[i].r; volatility[i] = data[i].v; otime[i] = data[i].t; } printf("Size of data: %d\n", numOptions * (sizeof(OptionData) + sizeof(int))); PROFILER_ADD_TIME(PROFILE_WORK_SERIAL, 0, PROFILER_TIMER_NOW, PROFILER_TIMER(0)); #ifdef ENABLE_PARSEC_HOOKS __parsec_roi_begin(); #endif #ifdef ENABLE_THREADS #ifdef WIN32 HANDLE *threads; int *nums; threads = (HANDLE *) malloc (nThreads * sizeof(HANDLE)); nums = (int *) malloc (nThreads * sizeof(int)); for(i=0; i<nThreads; i++) { nums[i] = i; threads[i] = CreateThread(0, 0, bs_thread, &nums[i], 0, 0); } WaitForMultipleObjects(nThreads, threads, TRUE, INFINITE); free(threads); free(nums); #else PROFILER_TIMER_UPDATE(0); int *tids; tids = (int *) malloc (nThreads * sizeof(int)); PROFILER_ADD_TIME(PROFILE_MALLOCATOR, 0, PROFILER_TIMER_NOW, PROFILER_TIMER(0)); for(i=0; i<nThreads; i++) { tids[i]=i; CREATE_WITH_ARG(bs_thread, &tids[i]); } WAIT_FOR_END(nThreads); PROFILER_TIMER_UPDATE(0); free(tids); PROFILER_ADD_TIME(PROFILE_MALLOCATOR, 0, PROFILER_TIMER_NOW, PROFILER_TIMER(0)); #endif //WIN32 #else //ENABLE_THREADS #ifdef ENABLE_OPENMP { int tid=0; omp_set_num_threads(nThreads); bs_thread(&tid); } #else //ENABLE_OPENMP #ifdef ENABLE_TBB tbb::task_scheduler_init init(nThreads); int tid=0; bs_thread(&tid); #else //ENABLE_TBB //serial version int tid=0; bs_thread(&tid); #endif //ENABLE_TBB #endif //ENABLE_OPENMP #endif //ENABLE_THREADS #ifdef ENABLE_PARSEC_HOOKS __parsec_roi_end(); #endif PROFILER_TIMER_UPDATE(0); //Write prices to output file file = fopen(outputFile, "w"); if(file == NULL) { printf("ERROR: Unable to open file `%s'.\n", outputFile); exit(1); } rv = fprintf(file, "%i\n", numOptions); if(rv < 0) { printf("ERROR: Unable to write to file `%s'.\n", outputFile); fclose(file); exit(1); } for(i=0; i<numOptions; i++) { rv = fprintf(file, "%.18f\n", prices[i]); if(rv < 0) { printf("ERROR: Unable to write to file `%s'.\n", outputFile); fclose(file); exit(1); } } rv = fclose(file); if(rv != 0) { printf("ERROR: Unable to close file `%s'.\n", outputFile); exit(1); } PROFILER_ADD_TIME(PROFILE_FILE_IO, 0, PROFILER_TIMER_NOW, PROFILER_TIMER(0)); #ifdef ERR_CHK printf("Num Errors: %d\n", numError); #endif PROFILER_TIMER_UPDATE(0); free(data); free(prices); PROFILER_ADD_TIME(PROFILE_MALLOCATOR, 0, PROFILER_TIMER_NOW, PROFILER_TIMER(0)); PROFILER_DUMP(0, 1); PROFILER_DUMP(1, nThreads); #ifdef ENABLE_PARSEC_HOOKS __parsec_bench_end(); #endif return 0; }
ft.c
/*-------------------------------------------------------------------- NAS Parallel Benchmarks 3.0 structured OpenMP C versions - FT This benchmark is an OpenMP C version of the NPB FT code. The OpenMP C 2.3 versions are derived by RWCP from the serial Fortran versions in "NPB 2.3-serial" developed by NAS. 3.0 translation is performed by the UVSQ. 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 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: D. Bailey W. Saphir OpenMP C version: S. Satoh 3.0 structure translation: M. Popov --------------------------------------------------------------------*/ #include "../common/npb-C.h" #include "../math/nas_math.h" #include "../paging_benchmark.h" /* global variables */ #include "global.h" #include <nautilus/nautilus.h> #include <nautilus/shell.h> /* function declarations */ static void evolve(dcomplex u0[NZ][NY][NX], dcomplex u1[NZ][NY][NX], int t, int indexmap[NZ][NY][NX], int d[3]); static void compute_initial_conditions(dcomplex u0[NZ][NY][NX], int d[3]); static void ipow46(double a, int exponent, double *result); static void setup(void); static void compute_indexmap(int indexmap[NZ][NY][NX], int d[3]); static void print_timers(void); static void fft(int dir, dcomplex x1[NZ][NY][NX], dcomplex x2[NZ][NY][NX]); static void cffts1(int is, int d[3], dcomplex x[NZ][NY][NX], dcomplex xout[NZ][NY][NX], dcomplex y0[NX][FFTBLOCKPAD], dcomplex y1[NX][FFTBLOCKPAD]); static void cffts2(int is, int d[3], dcomplex x[NZ][NY][NX], dcomplex xout[NZ][NY][NX], dcomplex y0[NX][FFTBLOCKPAD], dcomplex y1[NX][FFTBLOCKPAD]); static void cffts3(int is, int d[3], dcomplex x[NZ][NY][NX], dcomplex xout[NZ][NY][NX], dcomplex y0[NX][FFTBLOCKPAD], dcomplex y1[NX][FFTBLOCKPAD]); static void fft_init (int n); static void cfftz (int is, int m, int n, dcomplex x[NX][FFTBLOCKPAD], dcomplex y[NX][FFTBLOCKPAD]); static void fftz2 (int is, int l, int m, int n, int ny, int ny1, dcomplex u[NX], dcomplex x[NX][FFTBLOCKPAD], dcomplex y[NX][FFTBLOCKPAD]); static int ilog2(int n); static void checksum(int i, dcomplex u1[NZ][NY][NX], int d[3]); static void verify (int d1, int d2, int d3, int nt, boolean *verified, char *class); /*-------------------------------------------------------------------- c FT benchmark c-------------------------------------------------------------------*/ static int program_FT(char *_buf, void* _priv); static struct shell_cmd_impl nas_ft_impl = { .cmd = "nas-ft", .help_str = "NAS parallel benchmark FT", .handler = program_FT, }; nk_register_shell_cmd(nas_ft_impl); #ifdef NAUT_CONFIG_ASPACE_PAGING int program_FT_paging(char * _buf, void *_priv){ return paging_wrapper(_buf, _priv, &program_FT); } static struct shell_cmd_impl nas_ft_paging_impl = { .cmd = "nas-ft-paging", .help_str = "NAS parallel benchmark FT with paging", .handler = program_FT_paging, }; nk_register_shell_cmd(nas_ft_paging_impl); #endif int program_FT(char * _buf, void *_priv) { /*c------------------------------------------------------------------- c-------------------------------------------------------------------*/ int i, ierr; /*------------------------------------------------------------------ c u0, u1, u2 are the main arrays in the problem. c Depending on the decomposition, these arrays will have different c dimensions. To accomodate all possibilities, we allocate them as c one-dimensional arrays and pass them to subroutines for different c views c - u0 contains the initial (transformed) initial condition c - u1 and u2 are working arrays c - indexmap maps i,j,k of u0 to the correct i^2+j^2+k^2 for the c time evolution operator. c-----------------------------------------------------------------*/ /*-------------------------------------------------------------------- c Large arrays are in common so that they are allocated on the c heap rather than the stack. This common block is not c referenced directly anywhere else. Padding is to avoid accidental c cache problems, since all array sizes are powers of two. c-------------------------------------------------------------------*/ static dcomplex u0[NZ][NY][NX]; static dcomplex pad1[3]; static dcomplex u1[NZ][NY][NX]; static dcomplex pad2[3]; static dcomplex u2[NZ][NY][NX]; static dcomplex pad3[3]; static int indexmap[NZ][NY][NX]; int iter; int nthreads = 1; double total_time, mflops; boolean verified; char class; /*-------------------------------------------------------------------- c Run the entire problem once to make sure all data is touched. c This reduces variable startup costs, which is important for such a c short benchmark. The other NPB 2 implementations are similar. c-------------------------------------------------------------------*/ for (i = 0; i < T_MAX; i++) { timer_clear(i); } setup(); compute_indexmap(indexmap, dims[2]); compute_initial_conditions(u1, dims[0]); fft_init (dims[0][0]); fft(1, u1, u0); /*-------------------------------------------------------------------- c Start over from the beginning. Note that all operations must c be timed, in contrast to other benchmarks. c-------------------------------------------------------------------*/ for (i = 0; i < T_MAX; i++) { timer_clear(i); } timer_start(T_TOTAL); if (TIMERS_ENABLED == TRUE) timer_start(T_SETUP); compute_indexmap(indexmap, dims[2]); compute_initial_conditions(u1, dims[0]); fft_init (dims[0][0]); if (TIMERS_ENABLED == TRUE) { timer_stop(T_SETUP); } if (TIMERS_ENABLED == TRUE) { timer_start(T_FFT); } fft(1, u1, u0); if (TIMERS_ENABLED == TRUE) { timer_stop(T_FFT); } for (iter = 1; iter <= niter; iter++) { if (TIMERS_ENABLED == TRUE) { timer_start(T_EVOLVE); } evolve(u0, u1, iter, indexmap, dims[0]); if (TIMERS_ENABLED == TRUE) { timer_stop(T_EVOLVE); } if (TIMERS_ENABLED == TRUE) { timer_start(T_FFT); } fft(-1, u1, u2); if (TIMERS_ENABLED == TRUE) { timer_stop(T_FFT); } if (TIMERS_ENABLED == TRUE) { timer_start(T_CHECKSUM); } checksum(iter, u2, dims[0]); if (TIMERS_ENABLED == TRUE) { timer_stop(T_CHECKSUM); } } verify(NX, NY, NZ, niter, &verified, &class); #pragma omp parallel { #if defined(_OPENMP) #pragma omp master nthreads = omp_get_num_threads(); #endif /* _OPENMP */ } /* end parallel */ timer_stop(T_TOTAL); total_time = timer_read(T_TOTAL); if( total_time != 0.0) { mflops = 1.0e-6*(double)(NTOTAL) * (14.8157+7.19641*log((double)(NTOTAL)) + (5.23518+7.21113*log((double)(NTOTAL)))*niter) /total_time; } else { mflops = 0.0; } c_print_results("FT", class, NX, NY, NZ, niter, nthreads, total_time, mflops, " floating point", verified, NPBVERSION, COMPILETIME, CS1, CS2, CS3, CS4, CS5, CS6, CS7); if (TIMERS_ENABLED == TRUE) print_timers(); return 0; } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void evolve(dcomplex u0[NZ][NY][NX], dcomplex u1[NZ][NY][NX], int t, int indexmap[NZ][NY][NX], int d[3]) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c evolve u0 -> u1 (t time steps) in fourier space c-------------------------------------------------------------------*/ int i, j, k; #pragma omp parallel for default(shared) private(i,j,k) for (k = 0; k < d[2]; k++) { for (j = 0; j < d[1]; j++) { for (i = 0; i < d[0]; i++) { crmul(u1[k][j][i], u0[k][j][i], ex[t*indexmap[k][j][i]]); } } } } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void compute_initial_conditions(dcomplex u0[NZ][NY][NX], int d[3]) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c Fill in array u0 with initial conditions from c random number generator c-------------------------------------------------------------------*/ int k; double x0, start, an, dummy; static double tmp[NX*2*MAXDIM+1]; int i,j,t; start = SEED; /*-------------------------------------------------------------------- c Jump to the starting element for our first plane. c-------------------------------------------------------------------*/ ipow46(A, (zstart[0]-1)*2*NX*NY + (ystart[0]-1)*2*NX, &an); dummy = randlc(&start, an); ipow46(A, 2*NX*NY, &an); /*-------------------------------------------------------------------- c Go through by z planes filling in one square at a time. c-------------------------------------------------------------------*/ for (k = 0; k < dims[0][2]; k++) { x0 = start; vranlc(2*NX*dims[0][1], &x0, A, tmp); t = 1; for (j = 0; j < dims[0][1]; j++) for (i = 0; i < NX; i++) { u0[k][j][i].real = tmp[t++]; u0[k][j][i].imag = tmp[t++]; } if (k != dims[0][2]) dummy = randlc(&start, an); } } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void ipow46(double a, int exponent, double *result) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c compute a^exponent mod 2^46 c-------------------------------------------------------------------*/ double dummy, q, r; int n, n2; /*-------------------------------------------------------------------- c Use c a^n = a^(n/2)*a^(n/2) if n even else c a^n = a*a^(n-1) if n odd c-------------------------------------------------------------------*/ *result = 1; if (exponent == 0) return; q = a; r = 1; n = exponent; while (n > 1) { n2 = n/2; if (n2 * 2 == n) { dummy = randlc(&q, q); n = n2; } else { dummy = randlc(&r, q); n = n-1; } } dummy = randlc(&r, q); *result = r; } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void setup(void) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ int ierr, i, j, fstatus; printf("\n\n NAS Parallel Benchmarks 3.0 structured OpenMP C version" " - FT Benchmark\n\n"); niter = NITER_DEFAULT; printf(" Size : %3dx%3dx%3d\n", NX, NY, NZ); printf(" Iterations : %7d\n", niter); /* 1004 format(' Number of processes : ', i7) 1005 format(' Processor array : ', i3, 'x', i3) 1006 format(' WARNING: compiled for ', i5, ' processes. ', > ' Will not verify. ')*/ for (i = 0;i < 3 ; i++) { dims[i][0] = NX; dims[i][1] = NY; dims[i][2] = NZ; } for (i = 0; i < 3; i++) { xstart[i] = 1; xend[i] = NX; ystart[i] = 1; yend[i] = NY; zstart[i] = 1; zend[i] = NZ; } /*-------------------------------------------------------------------- c Set up info for blocking of ffts and transposes. This improves c performance on cache-based systems. Blocking involves c working on a chunk of the problem at a time, taking chunks c along the first, second, or third dimension. c c - In cffts1 blocking is on 2nd dimension (with fft on 1st dim) c - In cffts2/3 blocking is on 1st dimension (with fft on 2nd and 3rd dims) c Since 1st dim is always in processor, we'll assume it's long enough c (default blocking factor is 16 so min size for 1st dim is 16) c The only case we have to worry about is cffts1 in a 2d decomposition. c so the blocking factor should not be larger than the 2nd dimension. c-------------------------------------------------------------------*/ fftblock = FFTBLOCK_DEFAULT; fftblockpad = FFTBLOCKPAD_DEFAULT; if (fftblock != FFTBLOCK_DEFAULT) fftblockpad = fftblock+3; } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void compute_indexmap(int indexmap[NZ][NY][NX], int d[3]) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c compute function from local (i,j,k) to ibar^2+jbar^2+kbar^2 c for time evolution exponent. c-------------------------------------------------------------------*/ int i, j, k, ii, ii2, jj, ij2, kk; double ap; /*-------------------------------------------------------------------- c basically we want to convert the fortran indices c 1 2 3 4 5 6 7 8 c to c 0 1 2 3 -4 -3 -2 -1 c The following magic formula does the trick: c mod(i-1+n/2, n) - n/2 c-------------------------------------------------------------------*/ #pragma omp parallel for default(shared) private(i,j,k,ii,ii2,jj,ij2,kk) for (i = 0; i < dims[2][0]; i++) { ii = (i+1+xstart[2]-2+NX/2)%NX - NX/2; ii2 = ii*ii; for (j = 0; j < dims[2][1]; j++) { jj = (j+1+ystart[2]-2+NY/2)%NY - NY/2; ij2 = jj*jj+ii2; for (k = 0; k < dims[2][2]; k++) { kk = (k+1+zstart[2]-2+NZ/2)%NZ - NZ/2; indexmap[k][j][i] = kk*kk+ij2; } } } /*-------------------------------------------------------------------- c compute array of exponentials for time evolution. c-------------------------------------------------------------------*/ ap = - 4.0 * ALPHA * PI * PI; ex[0] = 1.0; ex[1] = exp(ap); for (i = 2; i <= EXPMAX; i++) { ex[i] = ex[i-1]*ex[1]; } } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void print_timers(void) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ int i; char *tstrings[] = { " total ", " setup ", " fft ", " evolve ", " checksum ", " fftlow ", " fftcopy " }; for (i = 0; i < T_MAX; i++) { if (timer_read(i) != 0.0) { printf("timer %2d(%16s( :%10.6f\n", i, tstrings[i], timer_read(i)); } } } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void fft(int dir, dcomplex x1[NZ][NY][NX], dcomplex x2[NZ][NY][NX]) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ dcomplex y0[NX][FFTBLOCKPAD]; dcomplex y1[NX][FFTBLOCKPAD]; /*-------------------------------------------------------------------- c note: args x1, x2 must be different arrays c note: args for cfftsx are (direction, layout, xin, xout, scratch) c xin/xout may be the same and it can be somewhat faster c if they are c-------------------------------------------------------------------*/ if (dir == 1) { cffts1(1, dims[0], x1, x1, y0, y1); /* x1 -> x1 */ cffts2(1, dims[1], x1, x1, y0, y1); /* x1 -> x1 */ cffts3(1, dims[2], x1, x2, y0, y1); /* x1 -> x2 */ } else { cffts3(-1, dims[2], x1, x1, y0, y1); /* x1 -> x1 */ cffts2(-1, dims[1], x1, x1, y0, y1); /* x1 -> x1 */ cffts1(-1, dims[0], x1, x2, y0, y1); /* x1 -> x2 */ } } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void cffts1(int is, int d[3], dcomplex x[NZ][NY][NX], dcomplex xout[NZ][NY][NX], dcomplex y0[NX][FFTBLOCKPAD], dcomplex y1[NX][FFTBLOCKPAD]) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ int logd[3]; int i, j, k, jj; for (i = 0; i < 3; i++) { logd[i] = ilog2(d[i]); } #pragma omp parallel default(shared) private(i,j,k,jj) shared(is) { dcomplex y0[NX][FFTBLOCKPAD]; dcomplex y1[NX][FFTBLOCKPAD]; #pragma omp for for (k = 0; k < d[2]; k++) { for (jj = 0; jj <= d[1] - fftblock; jj+=fftblock) { /* if (TIMERS_ENABLED == TRUE) timer_start(T_FFTCOPY); */ for (j = 0; j < fftblock; j++) { for (i = 0; i < d[0]; i++) { y0[i][j].real = x[k][j+jj][i].real; y0[i][j].imag = x[k][j+jj][i].imag; } } /* if (TIMERS_ENABLED == TRUE) timer_stop(T_FFTCOPY); */ /* if (TIMERS_ENABLED == TRUE) timer_start(T_FFTLOW); */ cfftz (is, logd[0], d[0], y0, y1); /* if (TIMERS_ENABLED == TRUE) timer_stop(T_FFTLOW); */ /* if (TIMERS_ENABLED == TRUE) timer_start(T_FFTCOPY); */ for (j = 0; j < fftblock; j++) { for (i = 0; i < d[0]; i++) { xout[k][j+jj][i].real = y0[i][j].real; xout[k][j+jj][i].imag = y0[i][j].imag; } } /* if (TIMERS_ENABLED == TRUE) timer_stop(T_FFTCOPY); */ } } } } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void cffts2(int is, int d[3], dcomplex x[NZ][NY][NX], dcomplex xout[NZ][NY][NX], dcomplex y0[NX][FFTBLOCKPAD], dcomplex y1[NX][FFTBLOCKPAD]) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ int logd[3]; int i, j, k, ii; for (i = 0; i < 3; i++) { logd[i] = ilog2(d[i]); } #pragma omp parallel default(shared) private(i,j,k,ii) shared(is) { dcomplex y0[NX][FFTBLOCKPAD]; dcomplex y1[NX][FFTBLOCKPAD]; #pragma omp for for (k = 0; k < d[2]; k++) { for (ii = 0; ii <= d[0] - fftblock; ii+=fftblock) { /* if (TIMERS_ENABLED == TRUE) timer_start(T_FFTCOPY); */ for (j = 0; j < d[1]; j++) { for (i = 0; i < fftblock; i++) { y0[j][i].real = x[k][j][i+ii].real; y0[j][i].imag = x[k][j][i+ii].imag; } } /* if (TIMERS_ENABLED == TRUE) timer_stop(T_FFTCOPY); */ /* if (TIMERS_ENABLED == TRUE) timer_start(T_FFTLOW); */ cfftz (is, logd[1], d[1], y0, y1); /* if (TIMERS_ENABLED == TRUE) timer_stop(T_FFTLOW); */ /* if (TIMERS_ENABLED == TRUE) timer_start(T_FFTCOPY); */ for (j = 0; j < d[1]; j++) { for (i = 0; i < fftblock; i++) { xout[k][j][i+ii].real = y0[j][i].real; xout[k][j][i+ii].imag = y0[j][i].imag; } } /* if (TIMERS_ENABLED == TRUE) timer_stop(T_FFTCOPY); */ } } } } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void cffts3(int is, int d[3], dcomplex x[NZ][NY][NX], dcomplex xout[NZ][NY][NX], dcomplex y0[NX][FFTBLOCKPAD], dcomplex y1[NX][FFTBLOCKPAD]) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ int logd[3]; int i, j, k, ii; for (i = 0;i < 3; i++) { logd[i] = ilog2(d[i]); } #pragma omp parallel default(shared) private(i,j,k,ii) shared(is) { dcomplex y0[NX][FFTBLOCKPAD]; dcomplex y1[NX][FFTBLOCKPAD]; #pragma omp for for (j = 0; j < d[1]; j++) { for (ii = 0; ii <= d[0] - fftblock; ii+=fftblock) { /* if (TIMERS_ENABLED == TRUE) timer_start(T_FFTCOPY); */ for (k = 0; k < d[2]; k++) { for (i = 0; i < fftblock; i++) { y0[k][i].real = x[k][j][i+ii].real; y0[k][i].imag = x[k][j][i+ii].imag; } } /* if (TIMERS_ENABLED == TRUE) timer_stop(T_FFTCOPY); */ /* if (TIMERS_ENABLED == TRUE) timer_start(T_FFTLOW); */ cfftz (is, logd[2], d[2], y0, y1); /* if (TIMERS_ENABLED == TRUE) timer_stop(T_FFTLOW); */ /* if (TIMERS_ENABLED == TRUE) timer_start(T_FFTCOPY); */ for (k = 0; k < d[2]; k++) { for (i = 0; i < fftblock; i++) { xout[k][j][i+ii].real = y0[k][i].real; xout[k][j][i+ii].imag = y0[k][i].imag; } } /* if (TIMERS_ENABLED == TRUE) timer_stop(T_FFTCOPY); */ } } } } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void fft_init (int n) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c compute the roots-of-unity array that will be used for subsequent FFTs. c-------------------------------------------------------------------*/ int m,nu,ku,i,j,ln; double t, ti; /*-------------------------------------------------------------------- c Initialize the U array with sines and cosines in a manner that permits c stride one access at each FFT iteration. c-------------------------------------------------------------------*/ nu = n; m = ilog2(n); u[0].real = (double)m; u[0].imag = 0.0; ku = 1; ln = 1; for (j = 1; j <= m; j++) { t = PI / ln; for (i = 0; i <= ln - 1; i++) { ti = i * t; u[i+ku].real = cos(ti); u[i+ku].imag = sin(ti); } ku = ku + ln; ln = 2 * ln; } } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void cfftz (int is, int m, int n, dcomplex x[NX][FFTBLOCKPAD], dcomplex y[NX][FFTBLOCKPAD]) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c Computes NY N-point complex-to-complex FFTs of X using an algorithm due c to Swarztrauber. X is both the input and the output array, while Y is a c scratch array. It is assumed that N = 2^M. Before calling CFFTZ to c perform FFTs, the array U must be initialized by calling CFFTZ with IS c set to 0 and M set to MX, where MX is the maximum value of M for any c subsequent call. c-------------------------------------------------------------------*/ int i,j,l,mx; /*-------------------------------------------------------------------- c Check if input parameters are invalid. c-------------------------------------------------------------------*/ mx = (int)(u[0].real); if ((is != 1 && is != -1) || m < 1 || m > mx) { printf("CFFTZ: Either U has not been initialized, or else\n" "one of the input parameters is invalid%5d%5d%5d\n", is, m, mx); exit(1); } /*-------------------------------------------------------------------- c Perform one variant of the Stockham FFT. c-------------------------------------------------------------------*/ for (l = 1; l <= m; l+=2) { fftz2 (is, l, m, n, fftblock, fftblockpad, u, x, y); if (l == m) break; fftz2 (is, l + 1, m, n, fftblock, fftblockpad, u, y, x); } /*-------------------------------------------------------------------- c Copy Y to X. c-------------------------------------------------------------------*/ if (m % 2 == 1) { for (j = 0; j < n; j++) { for (i = 0; i < fftblock; i++) { x[j][i].real = y[j][i].real; x[j][i].imag = y[j][i].imag; } } } } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void fftz2 (int is, int l, int m, int n, int ny, int ny1, dcomplex u[NX], dcomplex x[NX][FFTBLOCKPAD], dcomplex y[NX][FFTBLOCKPAD]) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c Performs the L-th iteration of the second variant of the Stockham FFT. c-------------------------------------------------------------------*/ int k,n1,li,lj,lk,ku,i,j,i11,i12,i21,i22; dcomplex u1,x11,x21; /*-------------------------------------------------------------------- c Set initial parameters. c-------------------------------------------------------------------*/ n1 = n / 2; if (l-1 == 0) { lk = 1; } else { lk = 2 << ((l - 1)-1); } if (m-l == 0) { li = 1; } else { li = 2 << ((m - l)-1); } lj = 2 * lk; ku = li; for (i = 0; i < li; i++) { i11 = i * lk; i12 = i11 + n1; i21 = i * lj; i22 = i21 + lk; if (is >= 1) { u1.real = u[ku+i].real; u1.imag = u[ku+i].imag; } else { u1.real = u[ku+i].real; u1.imag = -u[ku+i].imag; } /*-------------------------------------------------------------------- c This loop is vectorizable. c-------------------------------------------------------------------*/ for (k = 0; k < lk; k++) { for (j = 0; j < ny; j++) { double x11real, x11imag; double x21real, x21imag; x11real = x[i11+k][j].real; x11imag = x[i11+k][j].imag; x21real = x[i12+k][j].real; x21imag = x[i12+k][j].imag; y[i21+k][j].real = x11real + x21real; y[i21+k][j].imag = x11imag + x21imag; y[i22+k][j].real = u1.real * (x11real - x21real) - u1.imag * (x11imag - x21imag); y[i22+k][j].imag = u1.real * (x11imag - x21imag) + u1.imag * (x11real - x21real); } } } } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static int ilog2(int n) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ int nn, lg; if (n == 1) { return 0; } lg = 1; nn = 2; while (nn < n) { nn = nn << 1; lg++; } return lg; } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void checksum(int i, dcomplex u1[NZ][NY][NX], int d[3]) { #pragma omp parallel default(shared) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ int j, q,r,s, ierr; dcomplex chk,allchk; chk.real = 0.0; chk.imag = 0.0; #pragma omp for nowait for (j = 1; j <= 1024; j++) { q = j%NX+1; if (q >= xstart[0] && q <= xend[0]) { r = (3*j)%NY+1; if (r >= ystart[0] && r <= yend[0]) { s = (5*j)%NZ+1; if (s >= zstart[0] && s <= zend[0]) { cadd(chk,chk,u1[s-zstart[0]][r-ystart[0]][q-xstart[0]]); } } } } #pragma omp critical { sums[i].real += chk.real; sums[i].imag += chk.imag; } #pragma omp barrier #pragma omp single { /* complex % real */ sums[i].real = sums[i].real/(double)(NTOTAL); sums[i].imag = sums[i].imag/(double)(NTOTAL); printf("T = %5d Checksum = %22.12e %22.12e\n", i, sums[i].real, sums[i].imag); } } } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void verify (int d1, int d2, int d3, int nt, boolean *verified, char *class) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ int ierr, size, i; double err, epsilon; /*-------------------------------------------------------------------- c Sample size reference checksums c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c Class S size reference checksums c-------------------------------------------------------------------*/ double vdata_real_s[6+1] = { 0.0, 5.546087004964e+02, 5.546385409189e+02, 5.546148406171e+02, 5.545423607415e+02, 5.544255039624e+02, 5.542683411902e+02 }; double vdata_imag_s[6+1] = { 0.0, 4.845363331978e+02, 4.865304269511e+02, 4.883910722336e+02, 4.901273169046e+02, 4.917475857993e+02, 4.932597244941e+02 }; /*-------------------------------------------------------------------- c Class W size reference checksums c-------------------------------------------------------------------*/ double vdata_real_w[6+1] = { 0.0, 5.673612178944e+02, 5.631436885271e+02, 5.594024089970e+02, 5.560698047020e+02, 5.530898991250e+02, 5.504159734538e+02 }; double vdata_imag_w[6+1] = { 0.0, 5.293246849175e+02, 5.282149986629e+02, 5.270996558037e+02, 5.260027904925e+02, 5.249400845633e+02, 5.239212247086e+02 }; /*-------------------------------------------------------------------- c Class A size reference checksums c-------------------------------------------------------------------*/ double vdata_real_a[6+1] = { 0.0, 5.046735008193e+02, 5.059412319734e+02, 5.069376896287e+02, 5.077892868474e+02, 5.085233095391e+02, 5.091487099959e+02 }; double vdata_imag_a[6+1] = { 0.0, 5.114047905510e+02, 5.098809666433e+02, 5.098144042213e+02, 5.101336130759e+02, 5.104914655194e+02, 5.107917842803e+02 }; /*-------------------------------------------------------------------- c Class B size reference checksums c-------------------------------------------------------------------*/ double vdata_real_b[20+1] = { 0.0, 5.177643571579e+02, 5.154521291263e+02, 5.146409228649e+02, 5.142378756213e+02, 5.139626667737e+02, 5.137423460082e+02, 5.135547056878e+02, 5.133910925466e+02, 5.132470705390e+02, 5.131197729984e+02, 5.130070319283e+02, 5.129070537032e+02, 5.128182883502e+02, 5.127393733383e+02, 5.126691062020e+02, 5.126064276004e+02, 5.125504076570e+02, 5.125002331720e+02, 5.124551951846e+02, 5.124146770029e+02 }; double vdata_imag_b[20+1] = { 0.0, 5.077803458597e+02, 5.088249431599e+02, 5.096208912659e+02, 5.101023387619e+02, 5.103976610617e+02, 5.105948019802e+02, 5.107404165783e+02, 5.108576573661e+02, 5.109577278523e+02, 5.110460304483e+02, 5.111252433800e+02, 5.111968077718e+02, 5.112616233064e+02, 5.113203605551e+02, 5.113735928093e+02, 5.114218460548e+02, 5.114656139760e+02, 5.115053595966e+02, 5.115415130407e+02, 5.115744692211e+02 }; /*-------------------------------------------------------------------- c Class C size reference checksums c-------------------------------------------------------------------*/ double vdata_real_c[20+1] = { 0.0, 5.195078707457e+02, 5.155422171134e+02, 5.144678022222e+02, 5.140150594328e+02, 5.137550426810e+02, 5.135811056728e+02, 5.134569343165e+02, 5.133651975661e+02, 5.132955192805e+02, 5.132410471738e+02, 5.131971141679e+02, 5.131605205716e+02, 5.131290734194e+02, 5.131012720314e+02, 5.130760908195e+02, 5.130528295923e+02, 5.130310107773e+02, 5.130103090133e+02, 5.129905029333e+02, 5.129714421109e+02 }; double vdata_imag_c[20+1] = { 0.0, 5.149019699238e+02, 5.127578201997e+02, 5.122251847514e+02, 5.121090289018e+02, 5.121143685824e+02, 5.121496764568e+02, 5.121870921893e+02, 5.122193250322e+02, 5.122454735794e+02, 5.122663649603e+02, 5.122830879827e+02, 5.122965869718e+02, 5.123075927445e+02, 5.123166486553e+02, 5.123241541685e+02, 5.123304037599e+02, 5.123356167976e+02, 5.123399592211e+02, 5.123435588985e+02, 5.123465164008e+02 }; epsilon = 1.0e-12; *verified = TRUE; *class = 'U'; if (d1 == 64 && d2 == 64 && d3 == 64 && nt == 6) { *class = 'S'; for (i = 1; i <= nt; i++) { err = (get_real(sums[i]) - vdata_real_s[i]) / vdata_real_s[i]; if (fabs(err) > epsilon) { *verified = FALSE; break; } err = (get_imag(sums[i]) - vdata_imag_s[i]) / vdata_imag_s[i]; if (fabs(err) > epsilon) { *verified = FALSE; break; } } } else if (d1 == 128 && d2 == 128 && d3 == 32 && nt == 6) { *class = 'W'; for (i = 1; i <= nt; i++) { err = (get_real(sums[i]) - vdata_real_w[i]) / vdata_real_w[i]; if (fabs(err) > epsilon) { *verified = FALSE; break; } err = (get_imag(sums[i]) - vdata_imag_w[i]) / vdata_imag_w[i]; if (fabs(err) > epsilon) { *verified = FALSE; break; } } } else if (d1 == 256 && d2 == 256 && d3 == 128 && nt == 6) { *class = 'A'; for (i = 1; i <= nt; i++) { err = (get_real(sums[i]) - vdata_real_a[i]) / vdata_real_a[i]; if (fabs(err) > epsilon) { *verified = FALSE; break; } err = (get_imag(sums[i]) - vdata_imag_a[i]) / vdata_imag_a[i]; if (fabs(err) > epsilon) { *verified = FALSE; break; } } } else if (d1 == 512 && d2 == 256 && d3 == 256 && nt == 20) { *class = 'B'; for (i = 1; i <= nt; i++) { err = (get_real(sums[i]) - vdata_real_b[i]) / vdata_real_b[i]; if (fabs(err) > epsilon) { *verified = FALSE; break; } err = (get_imag(sums[i]) - vdata_imag_b[i]) / vdata_imag_b[i]; if (fabs(err) > epsilon) { *verified = FALSE; break; } } } else if (d1 == 512 && d2 == 512 && d3 == 512 && nt == 20) { *class = 'C'; for (i = 1; i <= nt; i++) { err = (get_real(sums[i]) - vdata_real_c[i]) / vdata_real_c[i]; if (fabs(err) > epsilon) { *verified = FALSE; break; } err = (get_imag(sums[i]) - vdata_imag_c[i]) / vdata_imag_c[i]; if (fabs(err) > epsilon) { *verified = FALSE; break; } } } if (*class != 'U') { printf("Result verification successful\n"); } else { printf("Result verification failed\n"); } printf("class = %1c\n", *class); }
GB_binop__rdiv_fp64.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__rdiv_fp64 // A.*B function (eWiseMult): GB_AemultB__rdiv_fp64 // A*D function (colscale): GB_AxD__rdiv_fp64 // D*A function (rowscale): GB_DxB__rdiv_fp64 // C+=B function (dense accum): GB_Cdense_accumB__rdiv_fp64 // C+=b function (dense accum): GB_Cdense_accumb__rdiv_fp64 // C+=A+B function (dense ewise3): GB_Cdense_ewise3_accum__rdiv_fp64 // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__rdiv_fp64 // C=scalar+B GB_bind1st__rdiv_fp64 // C=scalar+B' GB_bind1st_tran__rdiv_fp64 // C=A+scalar GB_bind2nd__rdiv_fp64 // C=A'+scalar GB_bind2nd_tran__rdiv_fp64 // C type: double // A type: double // B,b type: double // BinaryOp: cij = (bij / aij) #define GB_ATYPE \ double #define GB_BTYPE \ double #define GB_CTYPE \ double // 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) \ double aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ double bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ double 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 = (y / x) ; // 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_RDIV || GxB_NO_FP64 || GxB_NO_RDIV_FP64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB_Cdense_ewise3_accum__rdiv_fp64 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__rdiv_fp64 ( 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__rdiv_fp64 ( 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__rdiv_fp64 ( 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 double double bwork = (*((double *) 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__rdiv_fp64 ( 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 double *GB_RESTRICT Cx = (double *) 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__rdiv_fp64 ( 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 double *GB_RESTRICT Cx = (double *) 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__rdiv_fp64 ( 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__rdiv_fp64 ( 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__rdiv_fp64 ( 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 double *Cx = (double *) Cx_output ; double x = (*((double *) x_input)) ; double *Bx = (double *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { double bij = Bx [p] ; Cx [p] = (bij / x) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__rdiv_fp64 ( 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 ; double *Cx = (double *) Cx_output ; double *Ax = (double *) Ax_input ; double y = (*((double *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { double aij = Ax [p] ; Cx [p] = (y / aij) ; } 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) \ { \ double aij = Ax [pA] ; \ Cx [pC] = (aij / x) ; \ } GrB_Info GB_bind1st_tran__rdiv_fp64 ( 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 \ double #if GB_DISABLE return (GrB_NO_VALUE) ; #else double x = (*((const double *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ double } //------------------------------------------------------------------------------ // 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) \ { \ double aij = Ax [pA] ; \ Cx [pC] = (y / aij) ; \ } GrB_Info GB_bind2nd_tran__rdiv_fp64 ( 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 double y = (*((const double *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
dng_simd_type.h
/*****************************************************************************/ // Copyright 2017-2019 Adobe Systems Incorporated // All Rights Reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file in // accordance with the terms of the Adobe license agreement accompanying it. /*****************************************************************************/ #ifndef __dng_simd_type__ #define __dng_simd_type__ /*****************************************************************************/ #include "dng_flags.h" /*****************************************************************************/ #if qDNGIntelCompiler #include <immintrin.h> #endif // qDNGIntelCompiler /*****************************************************************************/ enum SIMDType { Scalar, SSE2, // Pentium 4 AVX, // Sandy Bridge AVX2, // Haswell F16C = AVX2, //Ivy bridge AVX512_SKX, // Sky Lake Server SIMD_Sentinel }; /*****************************************************************************/ template <int SIMDType> class SIMDTraits { public: static const int kVecSizeFloat = 1; static const int kVecSizeInt32 = 1; }; template <> class SIMDTraits<SSE2> { public: static const int kVecSizeFloat = 4; static const int kVecSizeInt32 = 4; }; template <> class SIMDTraits<AVX> { public: static const int kVecSizeFloat = 8; static const int kVecSizeInt32 = 4; }; template <> class SIMDTraits<AVX2> { public: static const int kVecSizeFloat = 8; static const int kVecSizeInt32 = 8; }; template <> class SIMDTraits<AVX512_SKX> { public: static const int kVecSizeFloat = 16; static const int kVecSizeInt32 = 16; }; const SIMDType SIMDTypeMaxValue = SIMDType(SIMD_Sentinel - 1); extern SIMDType gDNGMaxSIMD; /*****************************************************************************/ #if qDNGIntelCompiler // Intel compiler. // Macros are preferred for "#pragma simd" because at some point these will // all change to OpenMP 4.x compliant "#pragma omp simd" directives (no longer // Intel-specific). // // Note that _Pragma(x) requires C99 or C++11 support. // Pre-defined feature levels. #define CR_SIMD_MIN_FEATURE (_FEATURE_SSE2) #define CR_AVX_FEATURE (_FEATURE_AVX) #define CR_AVX2_FEATURE (_FEATURE_AVX|_FEATURE_FMA|_FEATURE_AVX2) #define CR_F16C_FEATURE CR_AVX2_FEATURE #define CR_AVX512_SKX_FEATURE (_FEATURE_AVX512F|_FEATURE_AVX512CD|_FEATURE_AVX512BW|_FEATURE_AVX512DQ|_FEATURE_AVX512VL) #define CR_COMPILER_USING_AVX512_SKX (__AVX512F__ && __AVX512VL__ && __AVX512BW__ && __AVX512DQ__ && __AVX512CD__) #define __SIMDTYPE_TFY(x) #x #define _SIMDTYPE_TFY(x) __SIMDTYPE_TFY(x) #if qDNGDebug // Debug build. //#define INTEL_PRAGMA_SIMD_ASSERT_C(clause) _Pragma(PM2__STR1__(simd clause)) #define INTEL_PRAGMA_SIMD_ASSERT _Pragma("simd") #define INTEL_PRAGMA_SIMD_ASSERT_VECLEN_FLOAT(s) _Pragma(_SIMDTYPE_TFY(simd vectorlength( SIMDTraits<s>::kVecSizeFloat ) )) #define INTEL_PRAGMA_SIMD_ASSERT_VECLEN_INT32(s) _Pragma(_SIMDTYPE_TFY(simd vectorlength( SIMDTraits<s>::kVecSizeInt32 ) )) #define INTEL_PRAGMA_SIMD_ASSERT_VECLEN_INT16(s) _Pragma(_SIMDTYPE_TFY(simd vectorlength( SIMDTraits<s>::kVecSizeInt32*2 ) )) #define INTEL_PRAGMA_SIMD_ASSERT_VECLEN_INT8(s) _Pragma(_SIMDTYPE_TFY(simd vectorlength( SIMDTraits<s>::kVecSizeInt32*4 ) )) #else // Release build. //#define INTEL_PRAGMA_SIMD_ASSERT_C(clause) _Pragma(PM2__STR1__(simd assert clause)) #define INTEL_PRAGMA_SIMD_ASSERT _Pragma("simd assert") #if 1 #if (__INTEL_COMPILER < 1800) #define INTEL_PRAGMA_SIMD_ASSERT_VECLEN_FLOAT(s) _Pragma(_SIMDTYPE_TFY(simd assert vectorlength( SIMDTraits<s>::kVecSizeFloat ) )) #define INTEL_PRAGMA_SIMD_ASSERT_VECLEN_INT32(s) _Pragma(_SIMDTYPE_TFY(simd assert vectorlength( SIMDTraits<s>::kVecSizeInt32 ) )) #define INTEL_PRAGMA_SIMD_ASSERT_VECLEN_INT16(s) _Pragma(_SIMDTYPE_TFY(simd assert vectorlength( SIMDTraits<s>::kVecSizeInt32*2 ) )) #define INTEL_PRAGMA_SIMD_ASSERT_VECLEN_INT8(s) _Pragma(_SIMDTYPE_TFY(simd assert vectorlength( SIMDTraits<s>::kVecSizeInt32*4 ) )) #else // FIX_ME_ERIC_CHAN: I removed the assert to fix compile time error when using Intel compiler version 18. // Need to figure out correct fix when we switch to newer version. - tknoll 10/30/2017. #define INTEL_PRAGMA_SIMD_ASSERT_VECLEN_FLOAT(s) _Pragma(_SIMDTYPE_TFY(simd vectorlength( SIMDTraits<s>::kVecSizeFloat ) )) #define INTEL_PRAGMA_SIMD_ASSERT_VECLEN_INT32(s) _Pragma(_SIMDTYPE_TFY(simd vectorlength( SIMDTraits<s>::kVecSizeInt32 ) )) #define INTEL_PRAGMA_SIMD_ASSERT_VECLEN_INT16(s) _Pragma(_SIMDTYPE_TFY(simd vectorlength( SIMDTraits<s>::kVecSizeInt32*2 ) )) #define INTEL_PRAGMA_SIMD_ASSERT_VECLEN_INT8(s) _Pragma(_SIMDTYPE_TFY(simd vectorlength( SIMDTraits<s>::kVecSizeInt32*4 ) )) #endif #else // Don't force #define INTEL_PRAGMA_SIMD_ASSERT_VECLEN_FLOAT(s) _Pragma(_SIMDTYPE_TFY(simd assert)) #define INTEL_PRAGMA_SIMD_ASSERT_VECLEN_INT32(s) _Pragma(_SIMDTYPE_TFY(simd assert)) #define INTEL_PRAGMA_SIMD_ASSERT_VECLEN_INT16(s) _Pragma(_SIMDTYPE_TFY(simd assert)) #define INTEL_PRAGMA_SIMD_ASSERT_VECLEN_INT8(s) _Pragma(_SIMDTYPE_TFY(simd assert)) #endif #endif #define SET_CPU_FEATURE(simd) _allow_cpu_features( (simd >= AVX512_SKX) ? CR_AVX512_SKX_FEATURE : (simd >= AVX2) ? CR_AVX2_FEATURE : ((simd >= AVX) ? CR_AVX_FEATURE : CR_SIMD_MIN_FEATURE) ) //#define SET_CPU_FEATURE_NOFMA(simd) _allow_cpu_features( ((simd >= AVX512_SKX) ? CR_AVX512_SKX_FEATURE : (simd >= AVX2) ? CR_AVX2_FEATURE : ((simd >= AVX) ? CR_AVX_FEATURE : CR_SIMD_MIN_FEATURE)) & ~_FEATURE_FMA ) #define SET_CPU_FEATURE_NOFMA(simd) _allow_cpu_features( (simd >= AVX) ? CR_AVX_FEATURE : CR_SIMD_MIN_FEATURE) #define INTEL_PRAGMA_NOVECTOR _Pragma("novector") #define INTEL_COMPILER_NEEDED_NOTE #else // Non-Intel compiler. Use empty definitions for the macros. // Credit: http://www.highprogrammer.com/alan/windev/visualstudio.html, but avoid using $ character #define Stringize( L ) #L #define MakeString( M, L ) M(L) #define _x_Line MakeString( Stringize, __LINE__ ) #if qDNGValidateTarget // Do not warn about Intel compiler if building dng_validate. #define INTEL_COMPILER_NEEDED_NOTE #else #if !(defined (IOS_ENV) || defined(ANDROID_ENV)) && (defined(__x86_64__) || defined(__i386__)) #ifndef _MSC_VER #define INTEL_COMPILER_NEEDED_NOTE _Pragma("message(\"NOTE: Intel Compiler needed for optimizations in \" __FILE__ \":\" _x_Line )") #else // Intel compiler understands C99 _Pragma, but not Microsoft, so use MS-specific __pragma instead #define INTEL_COMPILER_NEEDED_NOTE __pragma(message("NOTE: Intel Compiler needed for optimizations in " __FILE__ ":" _x_Line " in " __FUNCTION__)) #endif #else #define INTEL_COMPILER_NEEDED_NOTE #endif #endif #define INTEL_PRAGMA_SIMD_ASSERT //#define INTEL_PRAGMA_SIMD_ASSERT_C(clause) #define SET_CPU_FEATURE(simd) #define INTEL_PRAGMA_SIMD_ASSERT_VECLEN_FLOAT(simd) #define INTEL_PRAGMA_SIMD_ASSERT_VECLEN_INT16(simd) #define INTEL_PRAGMA_SIMD_ASSERT_VECLEN_INT32(simd) #define INTEL_PRAGMA_SIMD_ASSERT_VECLEN_INT8(simd) #define INTEL_PRAGMA_NOVECTOR #endif // qDNGIntelCompiler /*****************************************************************************/ #endif // __dng_simd_type__ /*****************************************************************************/
otcalc.c
/****************************************************************************** * Python extension module for calculating Lyman-alpha optical depths. * * Function calc_optdepth() takes arguments: * n_HI in [m^-3 (proper)], sightline neutral hydrogen density, * v_Hub in [km/s], sightline Hubble velocity, * v_pec in [km/s], sightline gas peculiar velocity, * b in [m/s], sightline Doppler parameter for Voigt profile, * dx in [m (proper)], sightline spatial bin width(s), * nlos, number of sightlines, * nbins, number of bins in each sightline, * nthreads, number of OpenMP threads to use in calculation, * * where n_HI, v_Hub, v_pec, b and dx are 1D NumPy arrays (of dtype np.float64). * nlos, nbins and nthreads are Python integers. * * It returns an array of Lyman-alpha optical depths. * * LHW 04/12/17 * updated 26/04/17 *****************************************************************************/ #include <math.h> #include <omp.h> #include "Python.h" #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include "numpy/arrayobject.h" /* Constants for Voigt profile */ #define PI 3.14159265358979323846 /* Dimensionless */ #define LAMBDA_LYA_H1 1.2156701e-7 /* Lya wavelength in m */ #define FOSC_LYA 0.416400 /* Dimensionless */ #define ECHARGE 1.60217662e-19 /* Coulombs */ #define EMASS 9.10938356e-31 /* kg */ #define C 2.99792458e8 /* m/s */ #define EPSILON0 8.85418782e-12 /* m^-3 kg^-1 s^4 A^2 */ #define GAMMA_LYA_H1 6.265e8 /* Lya decay rate in s^-1 */ /* Prototypes */ void sighandler(int sig); double voigt_profile (double vdiff, double b); static PyObject* calc_optdepth(PyObject *self, PyObject *args); /*---------------------------------------------------------------------------*/ /* MODULE FUNCTIONS ---------------------------------------------------------*/ /* Signal handler to allow interrupts when extension in use */ void sighandler(int sig) { fprintf(stderr,"\nSignal = %s (SIGID = %d). \n",strsignal(sig), sig); exit(sig); } /* Voigt profile function */ double voigt_profile (double vdiff, double b) { /* Takes relative velocities in [km/s] and b in [m/s] */ /* Returns profile in [m^2 s] */ double sigma_av_Lya, k2, k3, a; double T0, T1, T2; double numer, subfrac, profile; /* Convert units */ vdiff *= 1e3; /* km/s to m/s */ /* Average cross section */ sigma_av_Lya = FOSC_LYA*ECHARGE*ECHARGE/(4*EMASS*C*EPSILON0); /* m^2 */ /* Profile factors */ k2 = GAMMA_LYA_H1*LAMBDA_LYA_H1/(4.0*PI); /* m/s */ k3 = sigma_av_Lya*LAMBDA_LYA_H1/(sqrt(PI)*b); /* m^2 s */ a = k2/b; /* dimensionless */ T0 = (vdiff/b) * (vdiff/b); T1 = exp(-T0); T2 = 1.5/T0; numer = ( T1*T1*(4.0*T0*T0 + 7.0*T0 + 4.0 + T2) - T2 - 1.0 ); subfrac = a/sqrt(PI)/T0*numer; profile = (T0 < 1.0e-6) ? T1 : T1 - subfrac; return k3*profile; /* m^2 s */ } /* Python callable function */ static PyObject* calc_optdepth(PyObject *self, PyObject *args) { PyArrayObject *arr1=NULL, *arr2=NULL, *arr3=NULL, *arr4=NULL, *arr5=NULL; PyObject *val1=NULL, *val2=NULL, *val3=NULL; PyArrayObject *out_arr=NULL; int ndims, i; long nlos, nbins, nthreads; npy_float64 *n_HI, *v_Hub, *v_pec, *b, *dx; npy_float64 *tau_lya=NULL, *out_ptr; /* Signal handler to allow interrupts */ signal(SIGINT,sighandler); /******************************************************************************/ /* Parse arguments and copy Python variables into C variables */ printf("\nOTCALC running...\n"); if (!PyArg_ParseTuple(args, "O!O!O!O!O!O!O!O!", &PyArray_Type, &arr1, &PyArray_Type, &arr2, &PyArray_Type, &arr3, &PyArray_Type, &arr4, &PyArray_Type, &arr5, &PyLong_Type, &val1, &PyLong_Type, &val2, &PyLong_Type, &val3)) { return NULL; } /* Array dimensions */ ndims = PyArray_DIM(arr1,0); if (PyArray_DIM(arr2,0) != ndims || PyArray_DIM(arr3,0) != ndims || PyArray_DIM(arr4,0) != ndims || PyArray_DIM(arr5,0) != ndims) { PyErr_SetString(PyExc_ValueError, "Input array dimensions don't match"); return NULL; } nlos = PyLong_AsLong(val1); nbins = PyLong_AsLong(val2); if (nbins*nlos != ndims) { PyErr_SetString(PyExc_ValueError, "ndims != nlos*nbins"); return NULL; } printf("Loaded nbins = %ld, nlos = %ld\n",nbins,nlos); nthreads = PyLong_AsLong(val3); omp_set_num_threads(nthreads); printf("Using max. of %d threads for calculation\n", omp_get_max_threads()); /* Allocate memory for C arrays */ n_HI = (npy_float64 *)malloc(sizeof(npy_float64)*ndims); if (n_HI==NULL) { free(n_HI); printf("malloc error!\n"); exit(0); } v_Hub = (npy_float64 *)malloc(sizeof(npy_float64)*ndims); if (v_Hub==NULL) { free(v_Hub); printf("malloc error!\n"); exit(0); } v_pec = (npy_float64 *)malloc(sizeof(npy_float64)*ndims); if (v_pec==NULL) { free(v_pec); printf("malloc error!\n"); exit(0); } b = (npy_float64 *)malloc(sizeof(npy_float64)*ndims); if (b==NULL) { free(b); printf("malloc error!\n"); exit(0); } dx = (npy_float64 *)malloc(sizeof(npy_float64)*ndims); if (dx==NULL) { free(dx); printf("malloc error!\n"); exit(0); } /* Copy Python arrays into C arrays */ for(i=0; i<ndims; i++) { n_HI[i] = *(npy_float64 *)PyArray_GETPTR1(arr1, i); v_Hub[i] = *(npy_float64 *)PyArray_GETPTR1(arr2, i); v_pec[i] = *(npy_float64 *)PyArray_GETPTR1(arr3, i); b[i] = *(npy_float64 *)PyArray_GETPTR1(arr4, i); dx[i] = *(npy_float64 *)PyArray_GETPTR1(arr5, i); } /* Sanity prints */ printf("\nSome sanity prints [proper units]:\n"); printf("n_HI[0] = %lf [m^-3]\n", n_HI[0]); printf("v_Hub[0] = %lf [km/s]\n", v_Hub[0]); printf("v_pec[0] = %lf [km/s]\n", v_pec[0]); printf("b[0] = %lf [m/s]\n", b[0]); printf("dx[0] = %lf [m]\n\n", dx[0]); /******************************************************************************/ /* Optical depth calculation */ tau_lya = (npy_float64 *)calloc(ndims,sizeof(npy_float64)); if (tau_lya==NULL) { free(tau_lya); printf("calloc error!\n"); exit(0); } #pragma omp parallel { /* private (thread-local) variables */ int j, k, inj, ink; npy_float64 v_rel, vp; #pragma omp for private(i) for (i=0; i<nlos; i++) { /* index ordering is (nbins*i + j) */ for (j=0; j<nbins; j++) { inj = i*nbins + j; for (k=0; k<nbins; k++) { ink = i*nbins + k; v_rel = v_Hub[inj] - v_Hub[ink] - v_pec[ink]; /* relative velocity in km/s */ vp = voigt_profile(v_rel, b[ink]); tau_lya[inj] += vp*n_HI[ink]*dx[ink]; /* UNITS: all proper with [vp] = m^2, [n_HI] = m^-3, [dx] = m */ } } } } /* Create output array */ out_arr = PyArray_FromDims(1, &ndims, NPY_DOUBLE); /* Copy optical depths into output array */ for (i=0; i<ndims; i++) { out_ptr = (npy_float64 *)PyArray_GETPTR1(out_arr, i); *out_ptr = tau_lya[i]; } /* Deallocate memory for C arrays */ free(n_HI); free(v_Hub); free(v_pec); free(b); free(dx); free(tau_lya); return PyArray_Return(out_arr); } /*---------------------------------------------------------------------------*/ /* MODULE INITIALIZATION ----------------------------------------------------*/ /* Note module designed for use with Python 3! */ static PyMethodDef otcalc_methods[] = { {"calc_optdepth", calc_optdepth, METH_VARARGS, ""}, {NULL, NULL, 0, NULL} /* Sentinel */ }; static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "otcalc", NULL, -1, otcalc_methods, NULL, NULL, NULL, NULL, }; PyMODINIT_FUNC *PyInit_otcalc(void) { PyObject *m; m = PyModule_Create(&moduledef); if (m == NULL) { return NULL; } import_array(); return m; }
visual-effects.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % V V IIIII SSSSS U U AAA L % % V V I SS U U A A L % % V V I SSS U U AAAAA L % % V V I SS U U A A L % % V IIIII SSSSS UUU A A LLLLL % % % % EEEEE FFFFF FFFFF EEEEE CCCC TTTTT SSSSS % % E F F E C T SS % % EEE FFF FFF EEE C T SSS % % E F F E C T SS % % EEEEE F F EEEEE CCCC T SSSSS % % % % % % MagickCore Image Special 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/annotate.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/cache.h" #include "MagickCore/cache-view.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/decorate.h" #include "MagickCore/distort.h" #include "MagickCore/draw.h" #include "MagickCore/effect.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/gem-private.h" #include "MagickCore/geometry.h" #include "MagickCore/layer.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.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/splay-tree.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/threshold.h" #include "MagickCore/transform.h" #include "MagickCore/transform-private.h" #include "MagickCore/utility.h" #include "MagickCore/visual-effects.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d d N o i s e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AddNoiseImage() adds random noise to the image. % % The format of the AddNoiseImage method is: % % Image *AddNoiseImage(const Image *image,const NoiseType noise_type, % const double attenuate,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o noise_type: The type of noise: Uniform, Gaussian, Multiplicative, % Impulse, Laplacian, or Poisson. % % o attenuate: attenuate the random distribution. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AddNoiseImage(const Image *image,const NoiseType noise_type, const double attenuate,ExceptionInfo *exception) { #define AddNoiseImageTag "AddNoise/Image" CacheView *image_view, *noise_view; Image *noise_image; MagickBooleanType status; MagickOffsetType progress; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif /* Initialize noise 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) noise_image=AccelerateAddNoiseImage(image,noise_type,attenuate,exception); if (noise_image != (Image *) NULL) return(noise_image); #endif noise_image=CloneImage(image,0,0,MagickTrue,exception); if (noise_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(noise_image,DirectClass,exception) == MagickFalse) { noise_image=DestroyImage(noise_image); return((Image *) NULL); } /* Add noise in each row. */ status=MagickTrue; progress=0; random_info=AcquireRandomInfoThreadSet(); image_view=AcquireVirtualCacheView(image,exception); noise_view=AcquireAuthenticCacheView(noise_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,noise_image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; const Quantum *magick_restrict p; ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(noise_view,0,y,noise_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++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait noise_traits=GetPixelChannelTraits(noise_image,channel); if ((traits == UndefinedPixelTrait) || (noise_traits == UndefinedPixelTrait)) continue; if ((noise_traits & CopyPixelTrait) != 0) { SetPixelChannel(noise_image,channel,p[i],q); continue; } SetPixelChannel(noise_image,channel,ClampToQuantum( GenerateDifferentialNoise(random_info[id],p[i],noise_type,attenuate)), q); } p+=GetPixelChannels(image); q+=GetPixelChannels(noise_image); } sync=SyncCacheViewAuthenticPixels(noise_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,AddNoiseImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } noise_view=DestroyCacheView(noise_view); image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); if (status == MagickFalse) noise_image=DestroyImage(noise_image); return(noise_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B l u e S h i f t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BlueShiftImage() mutes the colors of the image to simulate a scene at % nighttime in the moonlight. % % The format of the BlueShiftImage method is: % % Image *BlueShiftImage(const Image *image,const double factor, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o factor: the shift factor. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *BlueShiftImage(const Image *image,const double factor, ExceptionInfo *exception) { #define BlueShiftImageTag "BlueShift/Image" CacheView *image_view, *shift_view; Image *shift_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Allocate blue shift 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); shift_image=CloneImage(image,0,0,MagickTrue,exception); if (shift_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(shift_image,DirectClass,exception) == MagickFalse) { shift_image=DestroyImage(shift_image); return((Image *) NULL); } /* Blue-shift DirectClass image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); shift_view=AcquireAuthenticCacheView(shift_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,shift_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; PixelInfo pixel; Quantum quantum; const Quantum *magick_restrict p; ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(shift_view,0,y,shift_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { quantum=GetPixelRed(image,p); if (GetPixelGreen(image,p) < quantum) quantum=GetPixelGreen(image,p); if (GetPixelBlue(image,p) < quantum) quantum=GetPixelBlue(image,p); pixel.red=0.5*(GetPixelRed(image,p)+factor*quantum); pixel.green=0.5*(GetPixelGreen(image,p)+factor*quantum); pixel.blue=0.5*(GetPixelBlue(image,p)+factor*quantum); quantum=GetPixelRed(image,p); if (GetPixelGreen(image,p) > quantum) quantum=GetPixelGreen(image,p); if (GetPixelBlue(image,p) > quantum) quantum=GetPixelBlue(image,p); pixel.red=0.5*(pixel.red+factor*quantum); pixel.green=0.5*(pixel.green+factor*quantum); pixel.blue=0.5*(pixel.blue+factor*quantum); SetPixelRed(shift_image,ClampToQuantum(pixel.red),q); SetPixelGreen(shift_image,ClampToQuantum(pixel.green),q); SetPixelBlue(shift_image,ClampToQuantum(pixel.blue),q); p+=GetPixelChannels(image); q+=GetPixelChannels(shift_image); } sync=SyncCacheViewAuthenticPixels(shift_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,BlueShiftImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); shift_view=DestroyCacheView(shift_view); if (status == MagickFalse) shift_image=DestroyImage(shift_image); return(shift_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C h a r c o a l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CharcoalImage() creates a new image that is a copy of an existing one with % the edge highlighted. It allocates the memory necessary for the new Image % structure and returns a pointer to the new image. % % The format of the CharcoalImage method is: % % Image *CharcoalImage(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 *CharcoalImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { Image *charcoal_image, *edge_image; MagickBooleanType status; 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); edge_image=EdgeImage(image,radius,exception); if (edge_image == (Image *) NULL) return((Image *) NULL); edge_image->alpha_trait=UndefinedPixelTrait; charcoal_image=(Image *) NULL; status=ClampImage(edge_image,exception); if (status != MagickFalse) charcoal_image=BlurImage(edge_image,radius,sigma,exception); edge_image=DestroyImage(edge_image); if (charcoal_image == (Image *) NULL) return((Image *) NULL); status=NormalizeImage(charcoal_image,exception); if (status != MagickFalse) status=NegateImage(charcoal_image,MagickFalse,exception); if (status != MagickFalse) status=GrayscaleImage(charcoal_image,image->intensity,exception); if (status == MagickFalse) charcoal_image=DestroyImage(charcoal_image); return(charcoal_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o l o r i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ColorizeImage() blends the fill color with each pixel in the image. % A percentage blend is specified with opacity. Control the application % of different color components by specifying a different percentage for % each component (e.g. 90/100/10 is 90% red, 100% green, and 10% blue). % % The format of the ColorizeImage method is: % % Image *ColorizeImage(const Image *image,const char *blend, % const PixelInfo *colorize,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o blend: A character string indicating the level of blending as a % percentage. % % o colorize: A color value. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ColorizeImage(const Image *image,const char *blend, const PixelInfo *colorize,ExceptionInfo *exception) { #define ColorizeImageTag "Colorize/Image" #define Colorize(pixel,blend_percentage,colorize) \ (((pixel)*(100.0-(blend_percentage))+(colorize)*(blend_percentage))/100.0) CacheView *image_view; GeometryInfo geometry_info; Image *colorize_image; MagickBooleanType status; MagickOffsetType progress; MagickStatusType flags; PixelInfo blend_percentage; ssize_t y; /* Allocate colorized 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); colorize_image=CloneImage(image,0,0,MagickTrue,exception); if (colorize_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(colorize_image,DirectClass,exception) == MagickFalse) { colorize_image=DestroyImage(colorize_image); return((Image *) NULL); } if ((IsGrayColorspace(colorize_image->colorspace) != MagickFalse) || (IsPixelInfoGray(colorize) != MagickFalse)) (void) SetImageColorspace(colorize_image,sRGBColorspace,exception); if ((colorize_image->alpha_trait == UndefinedPixelTrait) && (colorize->alpha_trait != UndefinedPixelTrait)) (void) SetImageAlpha(colorize_image,OpaqueAlpha,exception); if (blend == (const char *) NULL) return(colorize_image); GetPixelInfo(colorize_image,&blend_percentage); flags=ParseGeometry(blend,&geometry_info); blend_percentage.red=geometry_info.rho; blend_percentage.green=geometry_info.rho; blend_percentage.blue=geometry_info.rho; blend_percentage.black=geometry_info.rho; blend_percentage.alpha=(MagickRealType) TransparentAlpha; if ((flags & SigmaValue) != 0) blend_percentage.green=geometry_info.sigma; if ((flags & XiValue) != 0) blend_percentage.blue=geometry_info.xi; if ((flags & PsiValue) != 0) blend_percentage.alpha=geometry_info.psi; if (blend_percentage.colorspace == CMYKColorspace) { if ((flags & PsiValue) != 0) blend_percentage.black=geometry_info.psi; if ((flags & ChiValue) != 0) blend_percentage.alpha=geometry_info.chi; } /* Colorize DirectClass image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(colorize_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(colorize_image,colorize_image,colorize_image->rows,1) #endif for (y=0; y < (ssize_t) colorize_image->rows; y++) { MagickBooleanType sync; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,colorize_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) colorize_image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(colorize_image); i++) { PixelTrait traits = GetPixelChannelTraits(colorize_image, (PixelChannel) i); if (traits == UndefinedPixelTrait) continue; if ((traits & CopyPixelTrait) != 0) continue; SetPixelChannel(colorize_image,(PixelChannel) i,ClampToQuantum( Colorize(q[i],GetPixelInfoChannel(&blend_percentage,(PixelChannel) i), GetPixelInfoChannel(colorize,(PixelChannel) i))),q); } q+=GetPixelChannels(colorize_image); } 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 atomic #endif progress++; proceed=SetImageProgress(image,ColorizeImageTag,progress, colorize_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); if (status == MagickFalse) colorize_image=DestroyImage(colorize_image); return(colorize_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o l o r M a t r i x I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ColorMatrixImage() applies color transformation to an image. This method % permits saturation changes, hue rotation, luminance to alpha, and various % other effects. Although variable-sized transformation matrices can be used, % typically one uses a 5x5 matrix for an RGBA image and a 6x6 for CMYKA % (or RGBA with offsets). The matrix is similar to those used by Adobe Flash % except offsets are in column 6 rather than 5 (in support of CMYKA images) % and offsets are normalized (divide Flash offset by 255). % % The format of the ColorMatrixImage method is: % % Image *ColorMatrixImage(const Image *image, % const KernelInfo *color_matrix,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o color_matrix: the color matrix. % % o exception: return any errors or warnings in this structure. % */ /* FUTURE: modify to make use of a MagickMatrix Mutliply function That should be provided in "matrix.c" (ASIDE: actually distorts should do this too but currently doesn't) */ MagickExport Image *ColorMatrixImage(const Image *image, const KernelInfo *color_matrix,ExceptionInfo *exception) { #define ColorMatrixImageTag "ColorMatrix/Image" CacheView *color_view, *image_view; double ColorMatrix[6][6] = { { 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 }, { 0.0, 1.0, 0.0, 0.0, 0.0, 0.0 }, { 0.0, 0.0, 1.0, 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0, 1.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 }, { 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 } }; Image *color_image; MagickBooleanType status; MagickOffsetType progress; ssize_t i; ssize_t u, v, y; /* Map given color_matrix, into a 6x6 matrix RGBKA and a constant */ 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); i=0; for (v=0; v < (ssize_t) color_matrix->height; v++) for (u=0; u < (ssize_t) color_matrix->width; u++) { if ((v < 6) && (u < 6)) ColorMatrix[v][u]=color_matrix->values[i]; i++; } /* Initialize color image. */ color_image=CloneImage(image,0,0,MagickTrue,exception); if (color_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(color_image,DirectClass,exception) == MagickFalse) { color_image=DestroyImage(color_image); return((Image *) NULL); } if (image->debug != MagickFalse) { char format[MagickPathExtent], *message; (void) LogMagickEvent(TransformEvent,GetMagickModule(), " ColorMatrix image with color matrix:"); message=AcquireString(""); for (v=0; v < 6; v++) { *message='\0'; (void) FormatLocaleString(format,MagickPathExtent,"%.20g: ",(double) v); (void) ConcatenateString(&message,format); for (u=0; u < 6; u++) { (void) FormatLocaleString(format,MagickPathExtent,"%+f ", ColorMatrix[v][u]); (void) ConcatenateString(&message,format); } (void) LogMagickEvent(TransformEvent,GetMagickModule(),"%s",message); } message=DestroyString(message); } /* Apply the ColorMatrix to image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); color_view=AcquireAuthenticCacheView(color_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,color_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { PixelInfo pixel; 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=GetCacheViewAuthenticPixels(color_view,0,y,color_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } GetPixelInfo(image,&pixel); for (x=0; x < (ssize_t) image->columns; x++) { ssize_t h; size_t height; GetPixelInfoPixel(image,p,&pixel); height=color_matrix->height > 6 ? 6UL : color_matrix->height; for (h=0; h < (ssize_t) height; h++) { double sum; sum=ColorMatrix[h][0]*GetPixelRed(image,p)+ColorMatrix[h][1]* GetPixelGreen(image,p)+ColorMatrix[h][2]*GetPixelBlue(image,p); if (image->colorspace == CMYKColorspace) sum+=ColorMatrix[h][3]*GetPixelBlack(image,p); if (image->alpha_trait != UndefinedPixelTrait) sum+=ColorMatrix[h][4]*GetPixelAlpha(image,p); sum+=QuantumRange*ColorMatrix[h][5]; switch (h) { case 0: pixel.red=sum; break; case 1: pixel.green=sum; break; case 2: pixel.blue=sum; break; case 3: pixel.black=sum; break; case 4: pixel.alpha=sum; break; default: break; } } SetPixelViaPixelInfo(color_image,&pixel,q); p+=GetPixelChannels(image); q+=GetPixelChannels(color_image); } if (SyncCacheViewAuthenticPixels(color_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,ColorMatrixImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } color_view=DestroyCacheView(color_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) color_image=DestroyImage(color_image); return(color_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I m p l o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ImplodeImage() creates a new image that is a copy of an existing % one with the image pixels "implode" by the specified percentage. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ImplodeImage method is: % % Image *ImplodeImage(const Image *image,const double amount, % const PixelInterpolateMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o implode_image: Method ImplodeImage returns a pointer to the image % after it is implode. A null image is returned if there is a memory % shortage. % % o image: the image. % % o amount: Define the extent of the implosion. % % o method: the pixel interpolation method. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ImplodeImage(const Image *image,const double amount, const PixelInterpolateMethod method,ExceptionInfo *exception) { #define ImplodeImageTag "Implode/Image" CacheView *canvas_view, *implode_view, *interpolate_view; double radius; Image *canvas_image, *implode_image; MagickBooleanType status; MagickOffsetType progress; PointInfo center, scale; ssize_t y; /* Initialize implode 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); canvas_image=CloneImage(image,0,0,MagickTrue,exception); if (canvas_image == (Image *) NULL) return((Image *) NULL); if ((canvas_image->alpha_trait == UndefinedPixelTrait) && (canvas_image->background_color.alpha != OpaqueAlpha)) (void) SetImageAlphaChannel(canvas_image,OpaqueAlphaChannel,exception); implode_image=CloneImage(canvas_image,0,0,MagickTrue,exception); if (implode_image == (Image *) NULL) { canvas_image=DestroyImage(canvas_image); return((Image *) NULL); } if (SetImageStorageClass(implode_image,DirectClass,exception) == MagickFalse) { canvas_image=DestroyImage(canvas_image); implode_image=DestroyImage(implode_image); return((Image *) NULL); } /* Compute scaling factor. */ scale.x=1.0; scale.y=1.0; center.x=0.5*canvas_image->columns; center.y=0.5*canvas_image->rows; radius=center.x; if (canvas_image->columns > canvas_image->rows) scale.y=(double) canvas_image->columns*PerceptibleReciprocal((double) canvas_image->rows); else if (canvas_image->columns < canvas_image->rows) { scale.x=(double) canvas_image->rows*PerceptibleReciprocal((double) canvas_image->columns); radius=center.y; } /* Implode image. */ status=MagickTrue; progress=0; canvas_view=AcquireVirtualCacheView(canvas_image,exception); interpolate_view=AcquireVirtualCacheView(canvas_image,exception); implode_view=AcquireAuthenticCacheView(implode_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(canvas_image,implode_image,canvas_image->rows,1) #endif for (y=0; y < (ssize_t) canvas_image->rows; y++) { double distance; PointInfo delta; const Quantum *magick_restrict p; ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(canvas_view,0,y,canvas_image->columns,1, exception); q=QueueCacheViewAuthenticPixels(implode_view,0,y,implode_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } delta.y=scale.y*(double) (y-center.y); for (x=0; x < (ssize_t) canvas_image->columns; x++) { ssize_t i; /* Determine if the pixel is within an ellipse. */ delta.x=scale.x*(double) (x-center.x); distance=delta.x*delta.x+delta.y*delta.y; if (distance >= (radius*radius)) for (i=0; i < (ssize_t) GetPixelChannels(canvas_image); i++) { PixelChannel channel = GetPixelChannelChannel(canvas_image,i); PixelTrait traits = GetPixelChannelTraits(canvas_image,channel); PixelTrait implode_traits = GetPixelChannelTraits(implode_image, channel); if ((traits == UndefinedPixelTrait) || (implode_traits == UndefinedPixelTrait)) continue; SetPixelChannel(implode_image,channel,p[i],q); } else { double factor; /* Implode the pixel. */ factor=1.0; if (distance > 0.0) factor=pow(sin(MagickPI*sqrt((double) distance)*PerceptibleReciprocal(radius)/2),-amount); status=InterpolatePixelChannels(canvas_image,interpolate_view, implode_image,method,(double) (factor*delta.x*PerceptibleReciprocal(scale.x)+center.x), (double) (factor*delta.y*PerceptibleReciprocal(scale.y)+center.y),q,exception); if (status == MagickFalse) break; } p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(implode_image); } if (SyncCacheViewAuthenticPixels(implode_view,exception) == MagickFalse) status=MagickFalse; if (canvas_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(canvas_image,ImplodeImageTag,progress, canvas_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } implode_view=DestroyCacheView(implode_view); interpolate_view=DestroyCacheView(interpolate_view); canvas_view=DestroyCacheView(canvas_view); canvas_image=DestroyImage(canvas_image); if (status == MagickFalse) implode_image=DestroyImage(implode_image); return(implode_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o r p h I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % The MorphImages() method requires a minimum of two images. The first % image is transformed into the second by a number of intervening images % as specified by frames. % % The format of the MorphImage method is: % % Image *MorphImages(const Image *image,const size_t number_frames, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o number_frames: Define the number of in-between image to generate. % The more in-between frames, the smoother the morph. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MorphImages(const Image *image,const size_t number_frames, ExceptionInfo *exception) { #define MorphImageTag "Morph/Image" double alpha, beta; Image *morph_image, *morph_images; MagickBooleanType status; MagickOffsetType scene; const Image *next; ssize_t n; ssize_t y; /* Clone first frame in sequence. */ 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); morph_images=CloneImage(image,0,0,MagickTrue,exception); if (morph_images == (Image *) NULL) return((Image *) NULL); if (GetNextImageInList(image) == (Image *) NULL) { /* Morph single image. */ for (n=1; n < (ssize_t) number_frames; n++) { morph_image=CloneImage(image,0,0,MagickTrue,exception); if (morph_image == (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } AppendImageToList(&morph_images,morph_image); if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,MorphImageTag,(MagickOffsetType) n, number_frames); if (proceed == MagickFalse) status=MagickFalse; } } return(GetFirstImageInList(morph_images)); } /* Morph image sequence. */ status=MagickTrue; scene=0; next=image; for ( ; GetNextImageInList(next) != (Image *) NULL; next=GetNextImageInList(next)) { for (n=0; n < (ssize_t) number_frames; n++) { CacheView *image_view, *morph_view; beta=(double) (n+1.0)/(double) (number_frames+1.0); alpha=1.0-beta; morph_image=ResizeImage(next,(size_t) (alpha*next->columns+beta* GetNextImageInList(next)->columns+0.5),(size_t) (alpha*next->rows+beta* GetNextImageInList(next)->rows+0.5),next->filter,exception); if (morph_image == (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } status=SetImageStorageClass(morph_image,DirectClass,exception); if (status == MagickFalse) { morph_image=DestroyImage(morph_image); return((Image *) NULL); } AppendImageToList(&morph_images,morph_image); morph_images=GetLastImageInList(morph_images); morph_image=ResizeImage(GetNextImageInList(next),morph_images->columns, morph_images->rows,GetNextImageInList(next)->filter,exception); if (morph_image == (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } image_view=AcquireVirtualCacheView(morph_image,exception); morph_view=AcquireAuthenticCacheView(morph_images,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(morph_image,morph_image,morph_image->rows,1) #endif for (y=0; y < (ssize_t) morph_images->rows; y++) { MagickBooleanType sync; const Quantum *magick_restrict p; ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,morph_image->columns,1, exception); q=GetCacheViewAuthenticPixels(morph_view,0,y,morph_images->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) morph_images->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(morph_image); i++) { PixelChannel channel = GetPixelChannelChannel(morph_image,i); PixelTrait traits = GetPixelChannelTraits(morph_image,channel); PixelTrait morph_traits=GetPixelChannelTraits(morph_images,channel); if ((traits == UndefinedPixelTrait) || (morph_traits == UndefinedPixelTrait)) continue; if ((morph_traits & CopyPixelTrait) != 0) { SetPixelChannel(morph_image,channel,p[i],q); continue; } SetPixelChannel(morph_image,channel,ClampToQuantum(alpha* GetPixelChannel(morph_images,channel,q)+beta*p[i]),q); } p+=GetPixelChannels(morph_image); q+=GetPixelChannels(morph_images); } sync=SyncCacheViewAuthenticPixels(morph_view,exception); if (sync == MagickFalse) status=MagickFalse; } morph_view=DestroyCacheView(morph_view); image_view=DestroyCacheView(image_view); morph_image=DestroyImage(morph_image); } if (n < (ssize_t) number_frames) break; /* Clone last frame in sequence. */ morph_image=CloneImage(GetNextImageInList(next),0,0,MagickTrue,exception); if (morph_image == (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } AppendImageToList(&morph_images,morph_image); morph_images=GetLastImageInList(morph_images); if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,MorphImageTag,scene, GetImageListLength(image)); if (proceed == MagickFalse) status=MagickFalse; } scene++; } if (GetNextImageInList(next) != (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } return(GetFirstImageInList(morph_images)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P l a s m a I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PlasmaImage() initializes an image with plasma fractal values. The image % must be initialized with a base color and the random number generator % seeded before this method is called. % % The format of the PlasmaImage method is: % % MagickBooleanType PlasmaImage(Image *image,const SegmentInfo *segment, % size_t attenuate,size_t depth,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o segment: Define the region to apply plasma fractals values. % % o attenuate: Define the plasma attenuation factor. % % o depth: Limit the plasma recursion depth. % % o exception: return any errors or warnings in this structure. % */ static inline Quantum PlasmaPixel(RandomInfo *magick_restrict random_info, const double pixel,const double noise) { MagickRealType plasma; plasma=pixel+noise*GetPseudoRandomValue(random_info)-noise/2.0; return(ClampToQuantum(plasma)); } static MagickBooleanType PlasmaImageProxy(Image *image,CacheView *image_view, CacheView *u_view,CacheView *v_view,RandomInfo *magick_restrict random_info, const SegmentInfo *magick_restrict segment,size_t attenuate,size_t depth, ExceptionInfo *exception) { double plasma; MagickStatusType status; const Quantum *magick_restrict u, *magick_restrict v; Quantum *magick_restrict q; ssize_t i; ssize_t x, x_mid, y, y_mid; if ((fabs(segment->x2-segment->x1) < MagickEpsilon) && (fabs(segment->y2-segment->y1) < MagickEpsilon)) return(MagickTrue); if (depth != 0) { SegmentInfo local_info; /* Divide the area into quadrants and recurse. */ depth--; attenuate++; x_mid=CastDoubleToLong(ceil((segment->x1+segment->x2)/2-0.5)); y_mid=CastDoubleToLong(ceil((segment->y1+segment->y2)/2-0.5)); local_info=(*segment); local_info.x2=(double) x_mid; local_info.y2=(double) y_mid; status=PlasmaImageProxy(image,image_view,u_view,v_view,random_info, &local_info,attenuate,depth,exception); local_info=(*segment); local_info.y1=(double) y_mid; local_info.x2=(double) x_mid; status&=PlasmaImageProxy(image,image_view,u_view,v_view,random_info, &local_info,attenuate,depth,exception); local_info=(*segment); local_info.x1=(double) x_mid; local_info.y2=(double) y_mid; status&=PlasmaImageProxy(image,image_view,u_view,v_view,random_info, &local_info,attenuate,depth,exception); local_info=(*segment); local_info.x1=(double) x_mid; local_info.y1=(double) y_mid; status&=PlasmaImageProxy(image,image_view,u_view,v_view,random_info, &local_info,attenuate,depth,exception); return(status == 0 ? MagickFalse : MagickTrue); } x_mid=CastDoubleToLong(ceil((segment->x1+segment->x2)/2-0.5)); y_mid=CastDoubleToLong(ceil((segment->y1+segment->y2)/2-0.5)); if ((fabs(segment->x1-x_mid) < MagickEpsilon) && (fabs(segment->x2-x_mid) < MagickEpsilon) && (fabs(segment->y1-y_mid) < MagickEpsilon) && (fabs(segment->y2-y_mid) < MagickEpsilon)) return(MagickFalse); /* Average pixels and apply plasma. */ status=MagickTrue; plasma=(double) QuantumRange/(2.0*attenuate); if ((fabs(segment->x1-x_mid) >= MagickEpsilon) || (fabs(segment->x2-x_mid) >= MagickEpsilon)) { /* Left pixel. */ x=CastDoubleToLong(ceil(segment->x1-0.5)); u=GetCacheViewVirtualPixels(u_view,x,CastDoubleToLong(ceil( segment->y1-0.5)),1,1,exception); v=GetCacheViewVirtualPixels(v_view,x,CastDoubleToLong(ceil( segment->y2-0.5)),1,1,exception); q=QueueCacheViewAuthenticPixels(image_view,x,y_mid,1,1,exception); if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) || (q == (Quantum *) NULL)) return(MagickTrue); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; q[i]=PlasmaPixel(random_info,((double) u[i]+v[i])/2.0,plasma); } status=SyncCacheViewAuthenticPixels(image_view,exception); if (fabs(segment->x1-segment->x2) >= MagickEpsilon) { /* Right pixel. */ x=CastDoubleToLong(ceil(segment->x2-0.5)); u=GetCacheViewVirtualPixels(u_view,x,CastDoubleToLong(ceil( segment->y1-0.5)),1,1,exception); v=GetCacheViewVirtualPixels(v_view,x,CastDoubleToLong(ceil( segment->y2-0.5)),1,1,exception); q=QueueCacheViewAuthenticPixels(image_view,x,y_mid,1,1,exception); if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) || (q == (Quantum *) NULL)) return(MagickFalse); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; q[i]=PlasmaPixel(random_info,((double) u[i]+v[i])/2.0,plasma); } status=SyncCacheViewAuthenticPixels(image_view,exception); } } if ((fabs(segment->y1-y_mid) >= MagickEpsilon) || (fabs(segment->y2-y_mid) >= MagickEpsilon)) { if ((fabs(segment->x1-x_mid) >= MagickEpsilon) || (fabs(segment->y2-y_mid) >= MagickEpsilon)) { /* Bottom pixel. */ y=CastDoubleToLong(ceil(segment->y2-0.5)); u=GetCacheViewVirtualPixels(u_view,CastDoubleToLong(ceil( segment->x1-0.5)),y,1,1,exception); v=GetCacheViewVirtualPixels(v_view,CastDoubleToLong(ceil( segment->x2-0.5)),y,1,1,exception); q=QueueCacheViewAuthenticPixels(image_view,x_mid,y,1,1,exception); if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) || (q == (Quantum *) NULL)) return(MagickTrue); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; q[i]=PlasmaPixel(random_info,((double) u[i]+v[i])/2.0,plasma); } status=SyncCacheViewAuthenticPixels(image_view,exception); } if (fabs(segment->y1-segment->y2) >= MagickEpsilon) { /* Top pixel. */ y=CastDoubleToLong(ceil(segment->y1-0.5)); u=GetCacheViewVirtualPixels(u_view,CastDoubleToLong(ceil( segment->x1-0.5)),y,1,1,exception); v=GetCacheViewVirtualPixels(v_view,CastDoubleToLong(ceil( segment->x2-0.5)),y,1,1,exception); q=QueueCacheViewAuthenticPixels(image_view,x_mid,y,1,1,exception); if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) || (q == (Quantum *) NULL)) return(MagickTrue); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; q[i]=PlasmaPixel(random_info,((double) u[i]+v[i])/2.0,plasma); } status=SyncCacheViewAuthenticPixels(image_view,exception); } } if ((fabs(segment->x1-segment->x2) >= MagickEpsilon) || (fabs(segment->y1-segment->y2) >= MagickEpsilon)) { /* Middle pixel. */ x=CastDoubleToLong(ceil(segment->x1-0.5)); y=CastDoubleToLong(ceil(segment->y1-0.5)); u=GetCacheViewVirtualPixels(u_view,x,y,1,1,exception); x=CastDoubleToLong(ceil(segment->x2-0.5)); y=CastDoubleToLong(ceil(segment->y2-0.5)); v=GetCacheViewVirtualPixels(v_view,x,y,1,1,exception); q=QueueCacheViewAuthenticPixels(image_view,x_mid,y_mid,1,1,exception); if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) || (q == (Quantum *) NULL)) return(MagickTrue); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; q[i]=PlasmaPixel(random_info,((double) u[i]+v[i])/2.0,plasma); } status=SyncCacheViewAuthenticPixels(image_view,exception); } if ((fabs(segment->x2-segment->x1) < 3.0) && (fabs(segment->y2-segment->y1) < 3.0)) return(status == 0 ? MagickFalse : MagickTrue); return(MagickFalse); } MagickExport MagickBooleanType PlasmaImage(Image *image, const SegmentInfo *segment,size_t attenuate,size_t depth, ExceptionInfo *exception) { CacheView *image_view, *u_view, *v_view; MagickBooleanType status; RandomInfo *random_info; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); image_view=AcquireAuthenticCacheView(image,exception); u_view=AcquireVirtualCacheView(image,exception); v_view=AcquireVirtualCacheView(image,exception); random_info=AcquireRandomInfo(); status=PlasmaImageProxy(image,image_view,u_view,v_view,random_info,segment, attenuate,depth,exception); random_info=DestroyRandomInfo(random_info); v_view=DestroyCacheView(v_view); u_view=DestroyCacheView(u_view); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P o l a r o i d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PolaroidImage() simulates a Polaroid picture. % % The format of the PolaroidImage method is: % % Image *PolaroidImage(const Image *image,const DrawInfo *draw_info, % const char *caption,const double angle, % const PixelInterpolateMethod method,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o caption: the Polaroid caption. % % o angle: Apply the effect along this angle. % % o method: the pixel interpolation method. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *PolaroidImage(const Image *image,const DrawInfo *draw_info, const char *caption,const double angle,const PixelInterpolateMethod method, ExceptionInfo *exception) { Image *bend_image, *caption_image, *flop_image, *picture_image, *polaroid_image, *rotate_image, *trim_image; size_t height; ssize_t quantum; /* Simulate a Polaroid picture. */ 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); quantum=(ssize_t) MagickMax(MagickMax((double) image->columns,(double) image->rows)/25.0,10.0); height=image->rows+2*quantum; caption_image=(Image *) NULL; if (caption != (const char *) NULL) { char *text; /* Generate caption image. */ caption_image=CloneImage(image,image->columns,1,MagickTrue,exception); if (caption_image == (Image *) NULL) return((Image *) NULL); text=InterpretImageProperties((ImageInfo *) NULL,(Image *) image,caption, exception); if (text != (char *) NULL) { char geometry[MagickPathExtent]; DrawInfo *annotate_info; MagickBooleanType status; ssize_t count; TypeMetric metrics; annotate_info=CloneDrawInfo((const ImageInfo *) NULL,draw_info); (void) CloneString(&annotate_info->text,text); count=FormatMagickCaption(caption_image,annotate_info,MagickTrue, &metrics,&text,exception); status=SetImageExtent(caption_image,image->columns,(size_t) ((count+1)*(metrics.ascent-metrics.descent)+0.5),exception); if (status == MagickFalse) caption_image=DestroyImage(caption_image); else { caption_image->background_color=image->border_color; (void) SetImageBackgroundColor(caption_image,exception); (void) CloneString(&annotate_info->text,text); (void) FormatLocaleString(geometry,MagickPathExtent,"+0+%.20g", metrics.ascent); if (annotate_info->gravity == UndefinedGravity) (void) CloneString(&annotate_info->geometry,AcquireString( geometry)); (void) AnnotateImage(caption_image,annotate_info,exception); height+=caption_image->rows; } annotate_info=DestroyDrawInfo(annotate_info); text=DestroyString(text); } } picture_image=CloneImage(image,image->columns+2*quantum,height,MagickTrue, exception); if (picture_image == (Image *) NULL) { if (caption_image != (Image *) NULL) caption_image=DestroyImage(caption_image); return((Image *) NULL); } picture_image->background_color=image->border_color; (void) SetImageBackgroundColor(picture_image,exception); (void) CompositeImage(picture_image,image,OverCompositeOp,MagickTrue,quantum, quantum,exception); if (caption_image != (Image *) NULL) { (void) CompositeImage(picture_image,caption_image,OverCompositeOp, MagickTrue,quantum,(ssize_t) (image->rows+3*quantum/2),exception); caption_image=DestroyImage(caption_image); } (void) QueryColorCompliance("none",AllCompliance, &picture_image->background_color,exception); (void) SetImageAlphaChannel(picture_image,OpaqueAlphaChannel,exception); rotate_image=RotateImage(picture_image,90.0,exception); picture_image=DestroyImage(picture_image); if (rotate_image == (Image *) NULL) return((Image *) NULL); picture_image=rotate_image; bend_image=WaveImage(picture_image,0.01*picture_image->rows,2.0* picture_image->columns,method,exception); picture_image=DestroyImage(picture_image); if (bend_image == (Image *) NULL) return((Image *) NULL); picture_image=bend_image; rotate_image=RotateImage(picture_image,-90.0,exception); picture_image=DestroyImage(picture_image); if (rotate_image == (Image *) NULL) return((Image *) NULL); picture_image=rotate_image; picture_image->background_color=image->background_color; polaroid_image=ShadowImage(picture_image,80.0,2.0,quantum/3,quantum/3, exception); if (polaroid_image == (Image *) NULL) { picture_image=DestroyImage(picture_image); return(picture_image); } flop_image=FlopImage(polaroid_image,exception); polaroid_image=DestroyImage(polaroid_image); if (flop_image == (Image *) NULL) { picture_image=DestroyImage(picture_image); return(picture_image); } polaroid_image=flop_image; (void) CompositeImage(polaroid_image,picture_image,OverCompositeOp, MagickTrue,(ssize_t) (-0.01*picture_image->columns/2.0),0L,exception); picture_image=DestroyImage(picture_image); (void) QueryColorCompliance("none",AllCompliance, &polaroid_image->background_color,exception); rotate_image=RotateImage(polaroid_image,angle,exception); polaroid_image=DestroyImage(polaroid_image); if (rotate_image == (Image *) NULL) return((Image *) NULL); polaroid_image=rotate_image; trim_image=TrimImage(polaroid_image,exception); polaroid_image=DestroyImage(polaroid_image); if (trim_image == (Image *) NULL) return((Image *) NULL); polaroid_image=trim_image; return(polaroid_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e p i a T o n e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSepiaToneImage() applies a special effect to the image, similar to the % effect achieved in a photo darkroom by sepia toning. Threshold ranges from % 0 to QuantumRange and is a measure of the extent of the sepia toning. A % threshold of 80% is a good starting point for a reasonable tone. % % The format of the SepiaToneImage method is: % % Image *SepiaToneImage(const Image *image,const double threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: the tone threshold. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SepiaToneImage(const Image *image,const double threshold, ExceptionInfo *exception) { #define SepiaToneImageTag "SepiaTone/Image" CacheView *image_view, *sepia_view; Image *sepia_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Initialize sepia-toned 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); sepia_image=CloneImage(image,0,0,MagickTrue,exception); if (sepia_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(sepia_image,DirectClass,exception) == MagickFalse) { sepia_image=DestroyImage(sepia_image); return((Image *) NULL); } /* Tone each row of the image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); sepia_view=AcquireAuthenticCacheView(sepia_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,sepia_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *magick_restrict p; ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(sepia_view,0,y,sepia_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 intensity, tone; intensity=GetPixelIntensity(image,p); tone=intensity > threshold ? (double) QuantumRange : intensity+ (double) QuantumRange-threshold; SetPixelRed(sepia_image,ClampToQuantum(tone),q); tone=intensity > (7.0*threshold/6.0) ? (double) QuantumRange : intensity+(double) QuantumRange-7.0*threshold/6.0; SetPixelGreen(sepia_image,ClampToQuantum(tone),q); tone=intensity < (threshold/6.0) ? 0 : intensity-threshold/6.0; SetPixelBlue(sepia_image,ClampToQuantum(tone),q); tone=threshold/7.0; if ((double) GetPixelGreen(image,q) < tone) SetPixelGreen(sepia_image,ClampToQuantum(tone),q); if ((double) GetPixelBlue(image,q) < tone) SetPixelBlue(sepia_image,ClampToQuantum(tone),q); SetPixelAlpha(sepia_image,GetPixelAlpha(image,p),q); p+=GetPixelChannels(image); q+=GetPixelChannels(sepia_image); } if (SyncCacheViewAuthenticPixels(sepia_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,SepiaToneImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } sepia_view=DestroyCacheView(sepia_view); image_view=DestroyCacheView(image_view); (void) NormalizeImage(sepia_image,exception); (void) ContrastImage(sepia_image,MagickTrue,exception); if (status == MagickFalse) sepia_image=DestroyImage(sepia_image); return(sepia_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h a d o w I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShadowImage() simulates a shadow from the specified image and returns it. % % The format of the ShadowImage method is: % % Image *ShadowImage(const Image *image,const double alpha, % const double sigma,const ssize_t x_offset,const ssize_t y_offset, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o alpha: percentage transparency. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o x_offset: the shadow x-offset. % % o y_offset: the shadow y-offset. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ShadowImage(const Image *image,const double alpha, const double sigma,const ssize_t x_offset,const ssize_t y_offset, ExceptionInfo *exception) { #define ShadowImageTag "Shadow/Image" CacheView *image_view; ChannelType channel_mask; Image *border_image, *clone_image, *shadow_image; MagickBooleanType status; PixelInfo background_color; RectangleInfo border_info; 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); assert(exception->signature == MagickCoreSignature); clone_image=CloneImage(image,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) return((Image *) NULL); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(clone_image,sRGBColorspace,exception); (void) SetImageVirtualPixelMethod(clone_image,EdgeVirtualPixelMethod, exception); border_info.width=(size_t) floor(2.0*sigma+0.5); border_info.height=(size_t) floor(2.0*sigma+0.5); border_info.x=0; border_info.y=0; (void) QueryColorCompliance("none",AllCompliance,&clone_image->border_color, exception); clone_image->alpha_trait=BlendPixelTrait; border_image=BorderImage(clone_image,&border_info,OverCompositeOp,exception); clone_image=DestroyImage(clone_image); if (border_image == (Image *) NULL) return((Image *) NULL); if (border_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(border_image,OpaqueAlphaChannel,exception); /* Shadow image. */ status=MagickTrue; background_color=border_image->background_color; background_color.alpha_trait=BlendPixelTrait; image_view=AcquireAuthenticCacheView(border_image,exception); for (y=0; y < (ssize_t) border_image->rows; y++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(image_view,0,y,border_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) border_image->columns; x++) { if (border_image->alpha_trait != UndefinedPixelTrait) background_color.alpha=GetPixelAlpha(border_image,q)*alpha/100.0; SetPixelViaPixelInfo(border_image,&background_color,q); q+=GetPixelChannels(border_image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (status == MagickFalse) { border_image=DestroyImage(border_image); return((Image *) NULL); } channel_mask=SetImageChannelMask(border_image,AlphaChannel); shadow_image=BlurImage(border_image,0.0,sigma,exception); border_image=DestroyImage(border_image); if (shadow_image == (Image *) NULL) return((Image *) NULL); (void) SetPixelChannelMask(shadow_image,channel_mask); if (shadow_image->page.width == 0) shadow_image->page.width=shadow_image->columns; if (shadow_image->page.height == 0) shadow_image->page.height=shadow_image->rows; shadow_image->page.width+=x_offset-(ssize_t) border_info.width; shadow_image->page.height+=y_offset-(ssize_t) border_info.height; shadow_image->page.x+=x_offset-(ssize_t) border_info.width; shadow_image->page.y+=y_offset-(ssize_t) border_info.height; return(shadow_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S k e t c h I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SketchImage() simulates a pencil sketch. 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 SketchImage() selects a suitable radius for you. Angle gives the angle % of the sketch. % % The format of the SketchImage method is: % % Image *SketchImage(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. % */ MagickExport Image *SketchImage(const Image *image,const double radius, const double sigma,const double angle,ExceptionInfo *exception) { CacheView *random_view; Image *blend_image, *blur_image, *dodge_image, *random_image, *sketch_image; MagickBooleanType status; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif /* Sketch image. */ random_image=CloneImage(image,image->columns << 1,image->rows << 1, MagickTrue,exception); if (random_image == (Image *) NULL) return((Image *) NULL); status=MagickTrue; random_info=AcquireRandomInfoThreadSet(); random_view=AcquireAuthenticCacheView(random_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(random_image,random_image,random_image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) random_image->rows; y++) { const int id = GetOpenMPThreadId(); Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(random_view,0,y,random_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) random_image->columns; x++) { double value; ssize_t i; value=GetPseudoRandomValue(random_info[id]); for (i=0; i < (ssize_t) GetPixelChannels(random_image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; q[i]=ClampToQuantum(QuantumRange*value); } q+=GetPixelChannels(random_image); } if (SyncCacheViewAuthenticPixels(random_view,exception) == MagickFalse) status=MagickFalse; } random_view=DestroyCacheView(random_view); random_info=DestroyRandomInfoThreadSet(random_info); if (status == MagickFalse) { random_image=DestroyImage(random_image); return(random_image); } blur_image=MotionBlurImage(random_image,radius,sigma,angle,exception); random_image=DestroyImage(random_image); if (blur_image == (Image *) NULL) return((Image *) NULL); dodge_image=EdgeImage(blur_image,radius,exception); blur_image=DestroyImage(blur_image); if (dodge_image == (Image *) NULL) return((Image *) NULL); status=ClampImage(dodge_image,exception); if (status != MagickFalse) status=NormalizeImage(dodge_image,exception); if (status != MagickFalse) status=NegateImage(dodge_image,MagickFalse,exception); if (status != MagickFalse) status=TransformImage(&dodge_image,(char *) NULL,"50%",exception); sketch_image=CloneImage(image,0,0,MagickTrue,exception); if (sketch_image == (Image *) NULL) { dodge_image=DestroyImage(dodge_image); return((Image *) NULL); } (void) CompositeImage(sketch_image,dodge_image,ColorDodgeCompositeOp, MagickTrue,0,0,exception); dodge_image=DestroyImage(dodge_image); blend_image=CloneImage(image,0,0,MagickTrue,exception); if (blend_image == (Image *) NULL) { sketch_image=DestroyImage(sketch_image); return((Image *) NULL); } if (blend_image->alpha_trait != BlendPixelTrait) (void) SetImageAlpha(blend_image,TransparentAlpha,exception); (void) SetImageArtifact(blend_image,"compose:args","20x80"); (void) CompositeImage(sketch_image,blend_image,BlendCompositeOp,MagickTrue, 0,0,exception); blend_image=DestroyImage(blend_image); return(sketch_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S o l a r i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SolarizeImage() applies a special effect to the image, similar to the effect % achieved in a photo darkroom by selectively exposing areas of photo % sensitive paper to light. Threshold ranges from 0 to QuantumRange and is a % measure of the extent of the solarization. % % The format of the SolarizeImage method is: % % MagickBooleanType SolarizeImage(Image *image,const double threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: Define the extent of the solarization. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SolarizeImage(Image *image, const double threshold,ExceptionInfo *exception) { #define SolarizeImageTag "Solarize/Image" CacheView *image_view; 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 (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); if (image->storage_class == PseudoClass) { ssize_t i; /* Solarize colormap. */ for (i=0; i < (ssize_t) image->colors; i++) { if ((double) image->colormap[i].red > threshold) image->colormap[i].red=QuantumRange-image->colormap[i].red; if ((double) image->colormap[i].green > threshold) image->colormap[i].green=QuantumRange-image->colormap[i].green; if ((double) image->colormap[i].blue > threshold) image->colormap[i].blue=QuantumRange-image->colormap[i].blue; } return(SyncImage(image,exception)); } /* Solarize 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++) { ssize_t x; 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; } for (x=0; x < (ssize_t) image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if ((double) q[i] > threshold) q[i]=QuantumRange-q[i]; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_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,SolarizeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t e g a n o I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SteganoImage() hides a digital watermark within the image. Recover % the hidden watermark later to prove that the authenticity of an image. % Offset defines the start position within the image to hide the watermark. % % The format of the SteganoImage method is: % % Image *SteganoImage(const Image *image,Image *watermark, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o watermark: the watermark image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SteganoImage(const Image *image,const Image *watermark, ExceptionInfo *exception) { #define GetBit(alpha,i) ((((size_t) (alpha) >> (size_t) (i)) & 0x01) != 0) #define SetBit(alpha,i,set) (Quantum) ((set) != 0 ? (size_t) (alpha) \ | (one << (size_t) (i)) : (size_t) (alpha) & ~(one << (size_t) (i))) #define SteganoImageTag "Stegano/Image" CacheView *stegano_view, *watermark_view; Image *stegano_image; int c; MagickBooleanType status; PixelInfo pixel; Quantum *q; ssize_t x; size_t depth, one; ssize_t i, j, k, y; /* Initialize steganographic image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(watermark != (const Image *) NULL); assert(watermark->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); one=1UL; stegano_image=CloneImage(image,0,0,MagickTrue,exception); if (stegano_image == (Image *) NULL) return((Image *) NULL); stegano_image->depth=MAGICKCORE_QUANTUM_DEPTH; if (SetImageStorageClass(stegano_image,DirectClass,exception) == MagickFalse) { stegano_image=DestroyImage(stegano_image); return((Image *) NULL); } /* Hide watermark in low-order bits of image. */ c=0; i=0; j=0; depth=stegano_image->depth; k=stegano_image->offset; status=MagickTrue; watermark_view=AcquireVirtualCacheView(watermark,exception); stegano_view=AcquireAuthenticCacheView(stegano_image,exception); for (i=(ssize_t) depth-1; (i >= 0) && (j < (ssize_t) depth); i--) { for (y=0; (y < (ssize_t) watermark->rows) && (j < (ssize_t) depth); y++) { for (x=0; (x < (ssize_t) watermark->columns) && (j < (ssize_t) depth); x++) { ssize_t offset; (void) GetOneCacheViewVirtualPixelInfo(watermark_view,x,y,&pixel, exception); offset=k/(ssize_t) stegano_image->columns; if (offset >= (ssize_t) stegano_image->rows) break; q=GetCacheViewAuthenticPixels(stegano_view,k % (ssize_t) stegano_image->columns,k/(ssize_t) stegano_image->columns,1,1, exception); if (q == (Quantum *) NULL) break; switch (c) { case 0: { SetPixelRed(stegano_image,SetBit(GetPixelRed(stegano_image,q),j, GetBit(GetPixelInfoIntensity(stegano_image,&pixel),i)),q); break; } case 1: { SetPixelGreen(stegano_image,SetBit(GetPixelGreen(stegano_image,q),j, GetBit(GetPixelInfoIntensity(stegano_image,&pixel),i)),q); break; } case 2: { SetPixelBlue(stegano_image,SetBit(GetPixelBlue(stegano_image,q),j, GetBit(GetPixelInfoIntensity(stegano_image,&pixel),i)),q); break; } } if (SyncCacheViewAuthenticPixels(stegano_view,exception) == MagickFalse) break; c++; if (c == 3) c=0; k++; if (k == (ssize_t) (stegano_image->columns*stegano_image->columns)) k=0; if (k == stegano_image->offset) j++; } } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,SteganoImageTag,(MagickOffsetType) (depth-i),depth); if (proceed == MagickFalse) status=MagickFalse; } } stegano_view=DestroyCacheView(stegano_view); watermark_view=DestroyCacheView(watermark_view); if (status == MagickFalse) stegano_image=DestroyImage(stegano_image); return(stegano_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t e r e o A n a g l y p h I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % StereoAnaglyphImage() combines two images and produces a single image that % is the composite of a left and right image of a stereo pair. Special % red-green stereo glasses are required to view this effect. % % The format of the StereoAnaglyphImage method is: % % Image *StereoImage(const Image *left_image,const Image *right_image, % ExceptionInfo *exception) % Image *StereoAnaglyphImage(const Image *left_image, % const Image *right_image,const ssize_t x_offset,const ssize_t y_offset, % ExceptionInfo *exception) % % A description of each parameter follows: % % o left_image: the left image. % % o right_image: the right image. % % o exception: return any errors or warnings in this structure. % % o x_offset: amount, in pixels, by which the left image is offset to the % right of the right image. % % o y_offset: amount, in pixels, by which the left image is offset to the % bottom of the right image. % % */ MagickExport Image *StereoImage(const Image *left_image, const Image *right_image,ExceptionInfo *exception) { return(StereoAnaglyphImage(left_image,right_image,0,0,exception)); } MagickExport Image *StereoAnaglyphImage(const Image *left_image, const Image *right_image,const ssize_t x_offset,const ssize_t y_offset, ExceptionInfo *exception) { #define StereoImageTag "Stereo/Image" const Image *image; Image *stereo_image; MagickBooleanType status; ssize_t y; assert(left_image != (const Image *) NULL); assert(left_image->signature == MagickCoreSignature); if (left_image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", left_image->filename); assert(right_image != (const Image *) NULL); assert(right_image->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=left_image; if ((left_image->columns != right_image->columns) || (left_image->rows != right_image->rows)) ThrowImageException(ImageError,"LeftAndRightImageSizesDiffer"); /* Initialize stereo image attributes. */ stereo_image=CloneImage(left_image,left_image->columns,left_image->rows, MagickTrue,exception); if (stereo_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(stereo_image,DirectClass,exception) == MagickFalse) { stereo_image=DestroyImage(stereo_image); return((Image *) NULL); } (void) SetImageColorspace(stereo_image,sRGBColorspace,exception); /* Copy left image to red channel and right image to blue channel. */ status=MagickTrue; for (y=0; y < (ssize_t) stereo_image->rows; y++) { const Quantum *magick_restrict p, *magick_restrict q; ssize_t x; Quantum *magick_restrict r; p=GetVirtualPixels(left_image,-x_offset,y-y_offset,image->columns,1, exception); q=GetVirtualPixels(right_image,0,y,right_image->columns,1,exception); r=QueueAuthenticPixels(stereo_image,0,y,stereo_image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL) || (r == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) stereo_image->columns; x++) { SetPixelRed(stereo_image,GetPixelRed(left_image,p),r); SetPixelGreen(stereo_image,GetPixelGreen(right_image,q),r); SetPixelBlue(stereo_image,GetPixelBlue(right_image,q),r); if ((GetPixelAlphaTraits(stereo_image) & CopyPixelTrait) != 0) SetPixelAlpha(stereo_image,(GetPixelAlpha(left_image,p)+ GetPixelAlpha(right_image,q))/2,r); p+=GetPixelChannels(left_image); q+=GetPixelChannels(right_image); r+=GetPixelChannels(stereo_image); } if (SyncAuthenticPixels(stereo_image,exception) == MagickFalse) break; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,StereoImageTag,(MagickOffsetType) y, stereo_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } if (status == MagickFalse) stereo_image=DestroyImage(stereo_image); return(stereo_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S w i r l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SwirlImage() swirls the pixels about the center of the image, where % degrees indicates the sweep of the arc through which each pixel is moved. % You get a more dramatic effect as the degrees move from 1 to 360. % % The format of the SwirlImage method is: % % Image *SwirlImage(const Image *image,double degrees, % const PixelInterpolateMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o degrees: Define the tightness of the swirling effect. % % o method: the pixel interpolation method. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SwirlImage(const Image *image,double degrees, const PixelInterpolateMethod method,ExceptionInfo *exception) { #define SwirlImageTag "Swirl/Image" CacheView *canvas_view, *interpolate_view, *swirl_view; double radius; Image *canvas_image, *swirl_image; MagickBooleanType status; MagickOffsetType progress; PointInfo center, scale; ssize_t y; /* Initialize swirl 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); canvas_image=CloneImage(image,0,0,MagickTrue,exception); if (canvas_image == (Image *) NULL) return((Image *) NULL); swirl_image=CloneImage(canvas_image,0,0,MagickTrue,exception); if (swirl_image == (Image *) NULL) { canvas_image=DestroyImage(canvas_image); return((Image *) NULL); } if (SetImageStorageClass(swirl_image,DirectClass,exception) == MagickFalse) { canvas_image=DestroyImage(canvas_image); swirl_image=DestroyImage(swirl_image); return((Image *) NULL); } if (swirl_image->background_color.alpha_trait != UndefinedPixelTrait) (void) SetImageAlphaChannel(swirl_image,OnAlphaChannel,exception); /* Compute scaling factor. */ center.x=(double) canvas_image->columns/2.0; center.y=(double) canvas_image->rows/2.0; radius=MagickMax(center.x,center.y); scale.x=1.0; scale.y=1.0; if (canvas_image->columns > canvas_image->rows) scale.y=(double) canvas_image->columns/(double) canvas_image->rows; else if (canvas_image->columns < canvas_image->rows) scale.x=(double) canvas_image->rows/(double) canvas_image->columns; degrees=(double) DegreesToRadians(degrees); /* Swirl image. */ status=MagickTrue; progress=0; canvas_view=AcquireVirtualCacheView(canvas_image,exception); interpolate_view=AcquireVirtualCacheView(image,exception); swirl_view=AcquireAuthenticCacheView(swirl_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(canvas_image,swirl_image,canvas_image->rows,1) #endif for (y=0; y < (ssize_t) canvas_image->rows; y++) { double distance; PointInfo delta; const Quantum *magick_restrict p; ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(canvas_view,0,y,canvas_image->columns,1, exception); q=QueueCacheViewAuthenticPixels(swirl_view,0,y,swirl_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } delta.y=scale.y*(double) (y-center.y); for (x=0; x < (ssize_t) canvas_image->columns; x++) { /* Determine if the pixel is within an ellipse. */ delta.x=scale.x*(double) (x-center.x); distance=delta.x*delta.x+delta.y*delta.y; if (distance >= (radius*radius)) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(canvas_image); i++) { PixelChannel channel = GetPixelChannelChannel(canvas_image,i); PixelTrait traits = GetPixelChannelTraits(canvas_image,channel); PixelTrait swirl_traits = GetPixelChannelTraits(swirl_image, channel); if ((traits == UndefinedPixelTrait) || (swirl_traits == UndefinedPixelTrait)) continue; SetPixelChannel(swirl_image,channel,p[i],q); } } else { double cosine, factor, sine; /* Swirl the pixel. */ factor=1.0-sqrt((double) distance)/radius; sine=sin((double) (degrees*factor*factor)); cosine=cos((double) (degrees*factor*factor)); status=InterpolatePixelChannels(canvas_image,interpolate_view, swirl_image,method,((cosine*delta.x-sine*delta.y)/scale.x+center.x), (double) ((sine*delta.x+cosine*delta.y)/scale.y+center.y),q, exception); if (status == MagickFalse) break; } p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(swirl_image); } if (SyncCacheViewAuthenticPixels(swirl_view,exception) == MagickFalse) status=MagickFalse; if (canvas_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(canvas_image,SwirlImageTag,progress, canvas_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } swirl_view=DestroyCacheView(swirl_view); interpolate_view=DestroyCacheView(interpolate_view); canvas_view=DestroyCacheView(canvas_view); canvas_image=DestroyImage(canvas_image); if (status == MagickFalse) swirl_image=DestroyImage(swirl_image); return(swirl_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TintImage() applies a color vector to each pixel in the image. The length % of the vector is 0 for black and white and at its maximum for the midtones. % The vector weighting function is f(x)=(1-(4.0*((x-0.5)*(x-0.5)))) % % The format of the TintImage method is: % % Image *TintImage(const Image *image,const char *blend, % const PixelInfo *tint,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o blend: A color value used for tinting. % % o tint: A color value used for tinting. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *TintImage(const Image *image,const char *blend, const PixelInfo *tint,ExceptionInfo *exception) { #define TintImageTag "Tint/Image" CacheView *image_view, *tint_view; double intensity; GeometryInfo geometry_info; Image *tint_image; MagickBooleanType status; MagickOffsetType progress; PixelInfo color_vector; MagickStatusType flags; ssize_t y; /* Allocate tint 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); tint_image=CloneImage(image,0,0,MagickTrue,exception); if (tint_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(tint_image,DirectClass,exception) == MagickFalse) { tint_image=DestroyImage(tint_image); return((Image *) NULL); } if ((IsGrayColorspace(image->colorspace) != MagickFalse) && (IsPixelInfoGray(tint) == MagickFalse)) (void) SetImageColorspace(tint_image,sRGBColorspace,exception); if (blend == (const char *) NULL) return(tint_image); /* Determine RGB values of the color. */ GetPixelInfo(image,&color_vector); flags=ParseGeometry(blend,&geometry_info); color_vector.red=geometry_info.rho; color_vector.green=geometry_info.rho; color_vector.blue=geometry_info.rho; color_vector.alpha=(MagickRealType) OpaqueAlpha; if ((flags & SigmaValue) != 0) color_vector.green=geometry_info.sigma; if ((flags & XiValue) != 0) color_vector.blue=geometry_info.xi; if ((flags & PsiValue) != 0) color_vector.alpha=geometry_info.psi; if (image->colorspace == CMYKColorspace) { color_vector.black=geometry_info.rho; if ((flags & PsiValue) != 0) color_vector.black=geometry_info.psi; if ((flags & ChiValue) != 0) color_vector.alpha=geometry_info.chi; } intensity=(double) GetPixelInfoIntensity((const Image *) NULL,tint); color_vector.red=(double) (color_vector.red*tint->red/100.0-intensity); color_vector.green=(double) (color_vector.green*tint->green/100.0-intensity); color_vector.blue=(double) (color_vector.blue*tint->blue/100.0-intensity); color_vector.black=(double) (color_vector.black*tint->black/100.0-intensity); color_vector.alpha=(double) (color_vector.alpha*tint->alpha/100.0-intensity); /* Tint image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); tint_view=AcquireAuthenticCacheView(tint_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,tint_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(tint_view,0,y,tint_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { PixelInfo pixel; double weight; GetPixelInfo(image,&pixel); weight=QuantumScale*GetPixelRed(image,p)-0.5; pixel.red=(MagickRealType) GetPixelRed(image,p)+color_vector.red* (1.0-(4.0*(weight*weight))); weight=QuantumScale*GetPixelGreen(image,p)-0.5; pixel.green=(MagickRealType) GetPixelGreen(image,p)+color_vector.green* (1.0-(4.0*(weight*weight))); weight=QuantumScale*GetPixelBlue(image,p)-0.5; pixel.blue=(MagickRealType) GetPixelBlue(image,p)+color_vector.blue* (1.0-(4.0*(weight*weight))); weight=QuantumScale*GetPixelBlack(image,p)-0.5; pixel.black=(MagickRealType) GetPixelBlack(image,p)+color_vector.black* (1.0-(4.0*(weight*weight))); pixel.alpha=(MagickRealType) GetPixelAlpha(image,p); SetPixelViaPixelInfo(tint_image,&pixel,q); p+=GetPixelChannels(image); q+=GetPixelChannels(tint_image); } if (SyncCacheViewAuthenticPixels(tint_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,TintImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } tint_view=DestroyCacheView(tint_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) tint_image=DestroyImage(tint_image); return(tint_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % V i g n e t t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % VignetteImage() softens the edges of the image in vignette style. % % The format of the VignetteImage method is: % % Image *VignetteImage(const Image *image,const double radius, % const double sigma,const ssize_t x,const ssize_t y, % 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 x, y: Define the x and y ellipse offset. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *VignetteImage(const Image *image,const double radius, const double sigma,const ssize_t x,const ssize_t y,ExceptionInfo *exception) { char ellipse[MagickPathExtent]; DrawInfo *draw_info; Image *canvas, *blur_image, *oval_image, *vignette_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); canvas=CloneImage(image,0,0,MagickTrue,exception); if (canvas == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(canvas,DirectClass,exception) == MagickFalse) { canvas=DestroyImage(canvas); return((Image *) NULL); } canvas->alpha_trait=BlendPixelTrait; oval_image=CloneImage(canvas,canvas->columns,canvas->rows,MagickTrue, exception); if (oval_image == (Image *) NULL) { canvas=DestroyImage(canvas); return((Image *) NULL); } (void) QueryColorCompliance("#000000",AllCompliance, &oval_image->background_color,exception); (void) SetImageBackgroundColor(oval_image,exception); draw_info=CloneDrawInfo((const ImageInfo *) NULL,(const DrawInfo *) NULL); (void) QueryColorCompliance("#ffffff",AllCompliance,&draw_info->fill, exception); (void) QueryColorCompliance("#ffffff",AllCompliance,&draw_info->stroke, exception); (void) FormatLocaleString(ellipse,MagickPathExtent,"ellipse %g,%g,%g,%g," "0.0,360.0",image->columns/2.0,image->rows/2.0,image->columns/2.0-x, image->rows/2.0-y); draw_info->primitive=AcquireString(ellipse); (void) DrawImage(oval_image,draw_info,exception); draw_info=DestroyDrawInfo(draw_info); blur_image=BlurImage(oval_image,radius,sigma,exception); oval_image=DestroyImage(oval_image); if (blur_image == (Image *) NULL) { canvas=DestroyImage(canvas); return((Image *) NULL); } blur_image->alpha_trait=UndefinedPixelTrait; (void) CompositeImage(canvas,blur_image,IntensityCompositeOp,MagickTrue, 0,0,exception); blur_image=DestroyImage(blur_image); vignette_image=MergeImageLayers(canvas,FlattenLayer,exception); canvas=DestroyImage(canvas); if (vignette_image != (Image *) NULL) (void) TransformImageColorspace(vignette_image,image->colorspace,exception); return(vignette_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W a v e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WaveImage() creates a "ripple" effect in the image by shifting the pixels % vertically along a sine wave whose amplitude and wavelength is specified % by the given parameters. % % The format of the WaveImage method is: % % Image *WaveImage(const Image *image,const double amplitude, % const double wave_length,const PixelInterpolateMethod method, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o amplitude, wave_length: Define the amplitude and wave length of the % sine wave. % % o interpolate: the pixel interpolation method. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *WaveImage(const Image *image,const double amplitude, const double wave_length,const PixelInterpolateMethod method, ExceptionInfo *exception) { #define WaveImageTag "Wave/Image" CacheView *canvas_image_view, *wave_view; float *sine_map; Image *canvas_image, *wave_image; MagickBooleanType status; MagickOffsetType progress; ssize_t i; ssize_t y; /* Initialize wave 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); canvas_image=CloneImage(image,0,0,MagickTrue,exception); if (canvas_image == (Image *) NULL) return((Image *) NULL); if ((canvas_image->alpha_trait == UndefinedPixelTrait) && (canvas_image->background_color.alpha != OpaqueAlpha)) (void) SetImageAlpha(canvas_image,OpaqueAlpha,exception); wave_image=CloneImage(canvas_image,canvas_image->columns,(size_t) (canvas_image->rows+2.0*fabs(amplitude)),MagickTrue,exception); if (wave_image == (Image *) NULL) { canvas_image=DestroyImage(canvas_image); return((Image *) NULL); } if (SetImageStorageClass(wave_image,DirectClass,exception) == MagickFalse) { canvas_image=DestroyImage(canvas_image); wave_image=DestroyImage(wave_image); return((Image *) NULL); } /* Allocate sine map. */ sine_map=(float *) AcquireQuantumMemory((size_t) wave_image->columns, sizeof(*sine_map)); if (sine_map == (float *) NULL) { canvas_image=DestroyImage(canvas_image); wave_image=DestroyImage(wave_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) wave_image->columns; i++) sine_map[i]=(float) fabs(amplitude)+amplitude*sin((double) ((2.0*MagickPI*i)*PerceptibleReciprocal(wave_length))); /* Wave image. */ status=MagickTrue; progress=0; canvas_image_view=AcquireVirtualCacheView(canvas_image,exception); wave_view=AcquireAuthenticCacheView(wave_image,exception); (void) SetCacheViewVirtualPixelMethod(canvas_image_view, BackgroundVirtualPixelMethod); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(canvas_image,wave_image,wave_image->rows,1) #endif for (y=0; y < (ssize_t) wave_image->rows; y++) { const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(canvas_image_view,0,y,canvas_image->columns,1, exception); q=QueueCacheViewAuthenticPixels(wave_view,0,y,wave_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) wave_image->columns; x++) { status=InterpolatePixelChannels(canvas_image,canvas_image_view, wave_image,method,(double) x,(double) (y-sine_map[x]),q,exception); if (status == MagickFalse) break; p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(wave_image); } if (SyncCacheViewAuthenticPixels(wave_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(canvas_image,WaveImageTag,progress, canvas_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } wave_view=DestroyCacheView(wave_view); canvas_image_view=DestroyCacheView(canvas_image_view); canvas_image=DestroyImage(canvas_image); sine_map=(float *) RelinquishMagickMemory(sine_map); if (status == MagickFalse) wave_image=DestroyImage(wave_image); return(wave_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W a v e l e t D e n o i s e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WaveletDenoiseImage() removes noise from the image using a wavelet % transform. The wavelet transform is a fast hierarchical scheme for % processing an image using a set of consecutive lowpass and high_pass filters, % followed by a decimation. This results in a decomposition into different % scales which can be regarded as different “frequency bands”, determined by % the mother wavelet. Adapted from dcraw.c by David Coffin. % % The format of the WaveletDenoiseImage method is: % % Image *WaveletDenoiseImage(const Image *image,const double threshold, % const double softness,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: set the threshold for smoothing. % % o softness: attenuate the smoothing threshold. % % o exception: return any errors or warnings in this structure. % */ static inline void HatTransform(const float *magick_restrict pixels, const size_t stride,const size_t extent,const size_t scale,float *kernel) { const float *magick_restrict p, *magick_restrict q, *magick_restrict r; ssize_t i; p=pixels; q=pixels+scale*stride; r=pixels+scale*stride; for (i=0; i < (ssize_t) scale; i++) { kernel[i]=0.25f*(*p+(*p)+(*q)+(*r)); p+=stride; q-=stride; r+=stride; } for ( ; i < (ssize_t) (extent-scale); i++) { kernel[i]=0.25f*(2.0f*(*p)+*(p-scale*stride)+*(p+scale*stride)); p+=stride; } q=p-scale*stride; r=pixels+stride*(extent-2); for ( ; i < (ssize_t) extent; i++) { kernel[i]=0.25f*(*p+(*p)+(*q)+(*r)); p+=stride; q+=stride; r-=stride; } } MagickExport Image *WaveletDenoiseImage(const Image *image, const double threshold,const double softness,ExceptionInfo *exception) { CacheView *image_view, *noise_view; float *kernel, *pixels; Image *noise_image; MagickBooleanType status; MagickSizeType number_pixels; MemoryInfo *pixels_info; ssize_t channel; static const float noise_levels[] = { 0.8002f, 0.2735f, 0.1202f, 0.0585f, 0.0291f, 0.0152f, 0.0080f, 0.0044f }; /* Initialize noise 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) noise_image=AccelerateWaveletDenoiseImage(image,threshold,exception); if (noise_image != (Image *) NULL) return(noise_image); #endif noise_image=CloneImage(image,0,0,MagickTrue,exception); if (noise_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(noise_image,DirectClass,exception) == MagickFalse) { noise_image=DestroyImage(noise_image); return((Image *) NULL); } if (AcquireMagickResource(WidthResource,4*image->columns) == MagickFalse) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); pixels_info=AcquireVirtualMemory(3*image->columns,image->rows* sizeof(*pixels)); kernel=(float *) AcquireQuantumMemory(MagickMax(image->rows,image->columns)+1, GetOpenMPMaximumThreads()*sizeof(*kernel)); if ((pixels_info == (MemoryInfo *) NULL) || (kernel == (float *) NULL)) { if (kernel != (float *) NULL) kernel=(float *) RelinquishMagickMemory(kernel); if (pixels_info != (MemoryInfo *) NULL) pixels_info=RelinquishVirtualMemory(pixels_info); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(float *) GetVirtualMemoryBlob(pixels_info); status=MagickTrue; number_pixels=(MagickSizeType) image->columns*image->rows; image_view=AcquireAuthenticCacheView(image,exception); noise_view=AcquireAuthenticCacheView(noise_image,exception); for (channel=0; channel < (ssize_t) GetPixelChannels(image); channel++) { ssize_t i; size_t high_pass, low_pass; ssize_t level, y; PixelChannel pixel_channel; PixelTrait traits; if (status == MagickFalse) continue; traits=GetPixelChannelTraits(image,(PixelChannel) channel); if (traits == UndefinedPixelTrait) continue; pixel_channel=GetPixelChannelChannel(image,channel); if ((pixel_channel != RedPixelChannel) && (pixel_channel != GreenPixelChannel) && (pixel_channel != BluePixelChannel)) continue; /* Copy channel from image to wavelet pixel array. */ i=0; for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *magick_restrict p; ssize_t x; p=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (x=0; x < (ssize_t) image->columns; x++) { pixels[i++]=(float) p[channel]; p+=GetPixelChannels(image); } } /* Low pass filter outputs are called approximation kernel & high pass filters are referred to as detail kernel. The detail kernel have high values in the noisy parts of the signal. */ high_pass=0; for (level=0; level < 5; level++) { double magnitude; ssize_t x; low_pass=(size_t) (number_pixels*((level & 0x01)+1)); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,1) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); float *magick_restrict p, *magick_restrict q; ssize_t c; p=kernel+id*image->columns; q=pixels+y*image->columns; HatTransform(q+high_pass,1,image->columns,((size_t) 1UL << level),p); q+=low_pass; for (c=0; c < (ssize_t) image->columns; c++) *q++=(*p++); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,1) \ magick_number_threads(image,image,image->columns,1) #endif for (x=0; x < (ssize_t) image->columns; x++) { const int id = GetOpenMPThreadId(); float *magick_restrict p, *magick_restrict q; ssize_t r; p=kernel+id*image->rows; q=pixels+x+low_pass; HatTransform(q,image->columns,image->rows,((size_t) 1UL << level),p); for (r=0; r < (ssize_t) image->rows; r++) { *q=(*p++); q+=image->columns; } } /* To threshold, each coefficient is compared to a threshold value and attenuated / shrunk by some factor. */ magnitude=threshold*noise_levels[level]; for (i=0; i < (ssize_t) number_pixels; ++i) { pixels[high_pass+i]-=pixels[low_pass+i]; if (pixels[high_pass+i] < -magnitude) pixels[high_pass+i]+=magnitude-softness*magnitude; else if (pixels[high_pass+i] > magnitude) pixels[high_pass+i]-=magnitude-softness*magnitude; else pixels[high_pass+i]*=softness; if (high_pass != 0) pixels[i]+=pixels[high_pass+i]; } high_pass=low_pass; } /* Reconstruct image from the thresholded wavelet kernel. */ i=0; for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; Quantum *magick_restrict q; ssize_t x; ssize_t offset; q=GetCacheViewAuthenticPixels(noise_view,0,y,noise_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; break; } offset=GetPixelChannelOffset(noise_image,pixel_channel); for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType pixel; pixel=(MagickRealType) pixels[i]+pixels[low_pass+i]; q[offset]=ClampToQuantum(pixel); i++; q+=GetPixelChannels(noise_image); } sync=SyncCacheViewAuthenticPixels(noise_view,exception); if (sync == MagickFalse) status=MagickFalse; } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,AddNoiseImageTag,(MagickOffsetType) channel,GetPixelChannels(image)); if (proceed == MagickFalse) status=MagickFalse; } } noise_view=DestroyCacheView(noise_view); image_view=DestroyCacheView(image_view); kernel=(float *) RelinquishMagickMemory(kernel); pixels_info=RelinquishVirtualMemory(pixels_info); if (status == MagickFalse) noise_image=DestroyImage(noise_image); return(noise_image); }
GB_unaryop__identity_int64_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_int64_uint32 // op(A') function: GB_tran__identity_int64_uint32 // C type: int64_t // A type: uint32_t // cast: int64_t cij = (int64_t) aij // unaryop: cij = aij #define GB_ATYPE \ uint32_t #define GB_CTYPE \ int64_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) \ int64_t z = (int64_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_INT64 || GxB_NO_UINT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__identity_int64_uint32 ( int64_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_int64_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
Example_ploop.1.c
/* * @@name: ploop.1c * @@type: C * @@compilable: yes * @@linkable: no * @@expect: success */ void simple(int n, float *a, float *b) { int i; #pragma omp parallel for for (i=1; i<n; i++) /* i is private by default */ b[i] = (a[i] + a[i-1]) / 2.0; }
nqueens.c
/**********************************************************************************************/ /* This program is part of the Barcelona OpenMP Tasks Suite */ /* Copyright (C) 2009 Barcelona Supercomputing Center - Centro Nacional de Supercomputacion */ /* Copyright (C) 2009 Universitat Politecnica de Catalunya */ /* */ /* This program 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 of the License, or */ /* (at your option) any later version. */ /* */ /* This program 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 this program; if not, write to the Free Software */ /* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /**********************************************************************************************/ /* * Original code from the Cilk project (by Keith Randall) * * Copyright (c) 2000 Massachusetts Institute of Technology * Copyright (c) 2000 Matteo Frigo */ #include <stdlib.h> #include <stdio.h> #include <memory.h> #include <alloca.h> #include "bots.h" #include "app-desc.h" #include <omp.h> /* Checking information */ static int solutions[] = { 1, 0, 0, 2, 10, /* 5 */ 4, 40, 92, 352, 724, /* 10 */ 2680, 14200, 73712, 365596, }; #define MAX_SOLUTIONS sizeof(solutions)/sizeof(int) #ifdef FORCE_TIED_TASKS int mycount=0; #pragma omp threadprivate(mycount) #endif int total_count; /* * <a> contains array of <n> queen positions. Returns 1 * if none of the queens conflict, and returns 0 otherwise. */ int ok(int n, char *a) { int i, j; char p, q; for (i = 0; i < n; i++) { p = a[i]; for (j = i + 1; j < n; j++) { q = a[j]; if (q == p || q == p - (j - i) || q == p + (j - i)) return 0; } } return 1; } #ifndef FORCE_TIED_TASKS void nqueens_ser (int n, int j, char *a, int *solutions) #else void nqueens_ser (int n, int j, char *a) #endif { #ifndef FORCE_TIED_TASKS int res; #endif int i; if (n == j) { /* good solution, count it */ #ifndef FORCE_TIED_TASKS *solutions = 1; #else mycount++; #endif return; } #ifndef FORCE_TIED_TASKS *solutions = 0; #endif /* try each possible position for queen <j> */ for (i = 0; i < n; i++) { { /* allocate a temporary array and copy <a> into it */ a[j] = (char) i; if (ok(j + 1, a)) { #ifndef FORCE_TIED_TASKS nqueens_ser(n, j + 1, a,&res); *solutions += res; #else nqueens_ser(n, j + 1, a); #endif } } } } #if defined(IF_CUTOFF) #ifndef FORCE_TIED_TASKS void nqueens(int n, int j, char *a, int *solutions, int depth) #else void nqueens(int n, int j, char *a, int depth) #endif { #ifndef FORCE_TIED_TASKS int *csols; #endif int i; if (n == j) { /* good solution, count it */ #ifndef FORCE_TIED_TASKS *solutions = 1; #else mycount++; #endif return; } #ifndef FORCE_TIED_TASKS *solutions = 0; csols = alloca(n*sizeof(int)); memset(csols,0,n*sizeof(int)); #endif /* try each possible position for queen <j> */ for (i = 0; i < n; i++) { #pragma omp task untied if(depth < bots_cutoff_value) { /* allocate a temporary array and copy <a> into it */ char * b = alloca(n * sizeof(char)); memcpy(b, a, j * sizeof(char)); b[j] = (char) i; if (ok(j + 1, b)) #ifndef FORCE_TIED_TASKS nqueens(n, j + 1, b,&csols[i],depth+1); #else nqueens(n, j + 1, b,depth+1); #endif } } #pragma omp taskwait #ifndef FORCE_TIED_TASKS for ( i = 0; i < n; i++) *solutions += csols[i]; #endif } #elif defined(FINAL_CUTOFF) #ifndef FORCE_TIED_TASKS void nqueens(int n, int j, char *a, int *solutions, int depth) #else void nqueens(int n, int j, char *a, int depth) #endif { #ifndef FORCE_TIED_TASKS int *csols; #endif int i; if (n == j) { /* good solution, count it */ #ifndef FORCE_TIED_TASKS *solutions += 1; #else mycount++; #endif return; } #ifndef FORCE_TIED_TASKS char final = omp_in_final(); if ( !final ) { *solutions = 0; csols = alloca(n*sizeof(int)); memset(csols,0,n*sizeof(int)); } #endif /* try each possible position for queen <j> */ for (i = 0; i < n; i++) { #pragma omp task untied final(depth+1 >= bots_cutoff_value) mergeable { char *b; int *sol; if ( omp_in_final() && depth+1 > bots_cutoff_value ) { b = a; #ifndef FORCE_TIED_TASKS sol = solutions; #endif } else { /* allocate a temporary array and copy <a> into it */ b = alloca(n * sizeof(char)); memcpy(b, a, j * sizeof(char)); #ifndef FORCE_TIED_TASKS sol = &csols[i]; #endif } b[j] = i; if (ok(j + 1, b)) #ifndef FORCE_TIED_TASKS nqueens(n, j + 1, b,sol,depth+1); #else nqueens(n, j + 1, b,depth+1); #endif } } #pragma omp taskwait #ifndef FORCE_TIED_TASKS if ( !final ) { for ( i = 0; i < n; i++) *solutions += csols[i]; } #endif } #elif defined(MANUAL_CUTOFF) #ifndef FORCE_TIED_TASKS void nqueens(int n, int j, char *a, int *solutions, int depth) #else void nqueens(int n, int j, char *a, int depth) #endif { #ifndef FORCE_TIED_TASKS int *csols; #endif int i; if (n == j) { /* good solution, count it */ #ifndef FORCE_TIED_TASKS *solutions = 1; #else mycount++; #endif return; } #ifndef FORCE_TIED_TASKS *solutions = 0; csols = alloca(n*sizeof(int)); memset(csols,0,n*sizeof(int)); #endif /* try each possible position for queen <j> */ for (i = 0; i < n; i++) { if ( depth < bots_cutoff_value ) { #pragma omp task untied { /* allocate a temporary array and copy <a> into it */ char * b = alloca(n * sizeof(char)); memcpy(b, a, j * sizeof(char)); b[j] = (char) i; if (ok(j + 1, b)) #ifndef FORCE_TIED_TASKS nqueens(n, j + 1, b,&csols[i],depth+1); #else nqueens(n, j + 1, b,depth+1); #endif } } else { a[j] = (char) i; if (ok(j + 1, a)) #ifndef FORCE_TIED_TASKS nqueens_ser(n, j + 1, a,&csols[i]); #else nqueens_ser(n, j + 1, a); #endif } } #pragma omp taskwait #ifndef FORCE_TIED_TASKS for ( i = 0; i < n; i++) *solutions += csols[i]; #endif } #else #ifndef FORCE_TIED_TASKS void nqueens(int n, int j, char *a, int *solutions, int depth) #else void nqueens(int n, int j, char *a, int depth) #endif { #ifndef FORCE_TIED_TASKS int *csols; #endif int i; if (n == j) { /* good solution, count it */ #ifndef FORCE_TIED_TASKS *solutions = 1; #else mycount++; #endif return; } #ifndef FORCE_TIED_TASKS *solutions = 0; csols = alloca(n*sizeof(int)); memset(csols,0,n*sizeof(int)); #endif /* try each possible position for queen <j> */ for (i = 0; i < n; i++) { #pragma omp task untied { /* allocate a temporary array and copy <a> into it */ char * b = alloca(n * sizeof(char)); memcpy(b, a, j * sizeof(char)); b[j] = (char) i; if (ok(j + 1, b)) #ifndef FORCE_TIED_TASKS nqueens(n, j + 1, b,&csols[i],depth); //FIXME: depth or depth+1 ??? #else nqueens(n, j + 1, b,depth); //FIXME: see above #endif } } #pragma omp taskwait #ifndef FORCE_TIED_TASKS for ( i = 0; i < n; i++) *solutions += csols[i]; #endif } #endif void find_queens (int size) { total_count=0; bots_message("Computing N-Queens algorithm (n=%d) ", size); #pragma omp parallel { #pragma omp single { char *a; a = alloca(size * sizeof(char)); #ifndef FORCE_TIED_TASKS nqueens(size, 0, a, &total_count,0); #else nqueens(size, 0, a, 0); #endif } #ifdef FORCE_TIED_TASKS #pragma omp atomic total_count += mycount; #endif } bots_message(" completed!\n"); } int verify_queens (int size) { if ( size > MAX_SOLUTIONS ) return BOTS_RESULT_NA; if ( total_count == solutions[size-1]) return BOTS_RESULT_SUCCESSFUL; return BOTS_RESULT_UNSUCCESSFUL; }
mozilla_ng_fmt_plug.c
/* * Cracker for Mozilla's key3.db's master password. * * All the real logic here is borrowed from Milen Rangelov's Hashkill project * and from Deque's article. * * Thanks to Jim Fougeron for all the help! * * This software is Copyright (c) 2014, Sanju Kholia <sanju.kholia [at] * gmail.com> and Dhiru Kholia <dhiru [at] openwall.com>, 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_mozilla; #elif FMT_REGISTERS_H john_register_one(&fmt_mozilla); #else #include <string.h> #ifdef _OPENMP #include <omp.h> #define OMP_SCALE 2048 // XXX #endif #include "arch.h" #include "md5.h" #include "misc.h" #include "common.h" #include "formats.h" #include "johnswap.h" #include "params.h" #include "options.h" #include "memdbg.h" #include "stdint.h" #include <openssl/des.h> #include "sha.h" #define FORMAT_LABEL "Mozilla" #define FORMAT_NAME "Mozilla key3.db" #define FORMAT_TAG "$mozilla$" #define TAG_LENGTH (sizeof(FORMAT_TAG) - 1) #define ALGORITHM_NAME "SHA1 3DES 32/" ARCH_BITS_STR #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH 0 #define PLAINTEXT_LENGTH 125 #define BINARY_SIZE 16 #define BINARY_ALIGN sizeof(ARCH_WORD_32) #define SALT_SIZE sizeof(struct custom_salt) #define SALT_ALIGN sizeof(int) #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 static struct fmt_tests tests[] = { {"$mozilla$*3*20*1*5199adfab24e85e3f308bacf692115f23dcd4f8f*11*2a864886f70d010c050103*16*9debdebd4596b278de029b2b2285ce2e*20*2c4d938ccb3f7f1551262185ccee947deae3b8ae", "12345678"}, {"$mozilla$*3*20*1*4f184f0d3c91cf52ee9190e65389b4d4c8fc66f2*11*2a864886f70d010c050103*16*590d1771368107d6be64844780707787*20*b8458c712ffcc2ff938409804cf3805e4bb7d722", "openwall"}, {"$mozilla$*3*20*1*897f35ff10348f0d3a7739dbf0abddc62e2e64c3*11*2a864886f70d010c050103*16*1851b917997b3119f82b8841a764db62*20*197958dd5e114281f59f9026ad8b7cfe3de7196a", "password"}, {NULL} }; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static int *saved_len; static ARCH_WORD_32 (*crypt_out)[BINARY_SIZE / sizeof(ARCH_WORD_32)]; static struct custom_salt { SHA_CTX pctx; int password_check_length; unsigned char password_check[20]; int global_salt_length; unsigned char global_salt[20]; int local_salt_length; // entry-salt (ES) unsigned char local_salt[20]; } *cur_salt; static void init(struct fmt_main *self) { #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 saved_key = mem_calloc_tiny(sizeof(*saved_key) * self->params.max_keys_per_crypt, MEM_ALIGN_WORD); saved_len = mem_calloc_tiny(sizeof(*saved_len) * self->params.max_keys_per_crypt, MEM_ALIGN_WORD); crypt_out = mem_calloc_tiny(sizeof(*crypt_out) * self->params.max_keys_per_crypt, MEM_ALIGN_WORD); } static int ishex(char *q) { while (atoi16[ARCH_INDEX(*q)] != 0x7F) q++; return !*q; } static int valid(char *ciphertext, struct fmt_main *self) { char *p, *keepptr; int res; if (strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH)) return 0; keepptr=strdup(ciphertext); p = &keepptr[TAG_LENGTH]; if (*p != '*') goto err; if ((p = strtok(p, "*")) == NULL) /* version */ goto err; res = atoi(p); if (res != 3) /* we only know about this particular version */ goto err; if ((p = strtok(NULL, "*")) == NULL) /* local_salt_length */ goto err; res = atoi(p); if (res > 20) goto err; if ((p = strtok(NULL, "*")) == NULL) /* nnLen (we ignore nnlen) */ goto err; if ((p = strtok(NULL, "*")) == NULL) /* local_salt */ goto err; if (strlen(p) != res * 2) goto err; if (!ishex(p)) goto err; if ((p = strtok(NULL, "*")) == NULL) /* oidDatalen */ goto err; res = atoi(p); if (res > 20) goto err; if ((p = strtok(NULL, "*")) == NULL) /* oidData */ goto err; if (strlen(p) != res * 2) goto err; if (!ishex(p)) goto err; if ((p = strtok(NULL, "*")) == NULL) /* password_check_length */ goto err; res = atoi(p); if (res > 20) goto err; if ((p = strtok(NULL, "*")) == NULL) /* password_check */ goto err; if (strlen(p) != res * 2) goto err; if (!ishex(p)) goto err; if ((p = strtok(NULL, "*")) == NULL) /* global_salt_length */ goto err; res = atoi(p); if (res > 20) goto err; if ((p = strtok(NULL, "*")) == NULL) /* global_salt */ goto err; if (strlen(p) != res * 2) goto err; if (!ishex(p)) goto err; MEM_FREE(keepptr); return 1; err: MEM_FREE(keepptr); return 0; } static void *get_salt(char *ciphertext) { int i; static struct custom_salt cs; char *p, *q; memset(&cs, 0, SALT_SIZE); // cs.local_salt needs to be zero padded to length 20 p = ciphertext + TAG_LENGTH; q = strchr(p, '*'); // version p = q + 1; q = strchr(p, '*'); // local_salt_length p = q + 1; cs.local_salt_length = atoi(p); q = strchr(p, '*'); // nnLen p = q + 1; q = strchr(p, '*'); // local_salt p = q + 1; for (i = 0; i < cs.local_salt_length; i++) cs.local_salt[i] = (atoi16[ARCH_INDEX(p[2 * i])] << 4) | atoi16[ARCH_INDEX(p[2 * i + 1])]; q = strchr(p, '*'); // oidLen (unused) p = q + 1; q = strchr(p, '*'); // oidData (unused) p = q + 1; q = strchr(p, '*'); // password_check_length p = q + 1; cs.password_check_length = atoi(p); q = strchr(p, '*'); // password_check p = q + 1; for (i = 0; i < cs.password_check_length; i++) cs.password_check[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; q = strchr(p, '*'); // global_salt_length p = q + 1; cs.global_salt_length = atoi(p); q = strchr(p, '*'); // global_salt p = q + 1; for (i = 0; i < cs.global_salt_length; i++) cs.global_salt[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; // Calculate partial sha1 data for password hashing SHA1_Init(&cs.pctx); SHA1_Update(&cs.pctx, cs.global_salt, cs.global_salt_length); return (void *)&cs; } static void *get_binary(char *ciphertext) { static union { unsigned char c[BINARY_SIZE]; ARCH_WORD dummy; } buf; unsigned char *out = buf.c; char *p, *q; int i; p = ciphertext + TAG_LENGTH; q = strchr(p, '*'); // version p = q + 1; q = strchr(p, '*'); // local_salt_length p = q + 1; q = strchr(p, '*'); // nnLen p = q + 1; q = strchr(p, '*'); // local_salt p = q + 1; q = strchr(p, '*'); // oidLen (unused) p = q + 1; q = strchr(p, '*'); // oidData (unused) p = q + 1; q = strchr(p, '*'); // password_check_length p = q + 1; q = strchr(p, '*'); // password_check p = q + 1; for (i = 0; i < BINARY_SIZE; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } return out; } static int get_hash_0(int index) { return crypt_out[index][0] & 0xf; } static int get_hash_1(int index) { return crypt_out[index][0] & 0xff; } static int get_hash_2(int index) { return crypt_out[index][0] & 0xfff; } static int get_hash_3(int index) { return crypt_out[index][0] & 0xffff; } static int get_hash_4(int index) { return crypt_out[index][0] & 0xfffff; } static int get_hash_5(int index) { return crypt_out[index][0] & 0xffffff; } static int get_hash_6(int index) { return crypt_out[index][0] & 0x7ffffff; } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; } // http://www.drh-consultancy.demon.co.uk/key3.html static int crypt_all(int *pcount, struct db_salt *salt) { int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for for (index = 0; index < count; index++) #endif { SHA_CTX ctx, ctxi, ctxo; int i; union { unsigned char uc[64]; uint32_t ui[64/4]; } pad; unsigned char buffer[20]; unsigned char tk[20]; unsigned char key[40]; DES_cblock ivec; DES_key_schedule ks1, ks2, ks3; // HP = SHA1(global-salt||password) // Copy already calculated partial hash data memcpy(&ctx, &cur_salt->pctx, sizeof(SHA_CTX)); SHA1_Update(&ctx, saved_key[index], saved_len[index]); SHA1_Final(buffer, &ctx); // CHP = SHA1(HP||entry-salt) // entry-salt (ES) is local_salt SHA1_Init(&ctx); SHA1_Update(&ctx, buffer, 20); SHA1_Update(&ctx, cur_salt->local_salt, cur_salt->local_salt_length); SHA1_Final(buffer, &ctx); // Step 0 for all hmac, store off the first half (the key is the same for all 3) // this will avoid having to setup the ipad/opad 2 times, and also avoids 4 SHA calls // reducing the hmac calls from 12 SHA limbs, down to 8 and ipad/opad loads from 3 // down to 1. It adds 4 CTX memcpy's, but that is a very fair trade off. SHA1_Init(&ctxi); SHA1_Init(&ctxo); memset(pad.uc, 0x36, 64); for (i = 0; i < 20; ++i) pad.uc[i] ^= buffer[i]; SHA1_Update(&ctxi, pad.uc, 64); for (i = 0; i < 64/4; ++i) pad.ui[i] ^= 0x36363636^0x5c5c5c5c; SHA1_Update(&ctxo, pad.uc, 64); // k1 = HMAC(PES||ES) // use CHP as the key, PES is ES which is zero padded to length 20 // NOTE, memcpy ctxi/ctxo to harvest off the preloaded hmac key memcpy(&ctx, &ctxi, sizeof(ctx)); SHA1_Update(&ctx, cur_salt->local_salt, 20); SHA1_Update(&ctx, cur_salt->local_salt, cur_salt->local_salt_length); SHA1_Final(buffer, &ctx); memcpy(&ctx, &ctxo, sizeof(ctx)); SHA1_Update(&ctx, buffer, 20); SHA1_Final(key, &ctx); // tk = HMAC(PES) // use CHP as the key // NOTE, memcpy ctxi/ctxo to harvest off the preloaded hmac key memcpy(&ctx, &ctxi, sizeof(ctx)); SHA1_Update(&ctx, cur_salt->local_salt, 20); SHA1_Final(buffer, &ctx); memcpy(&ctx, &ctxo, sizeof(ctx)); SHA1_Update(&ctx, buffer, 20); SHA1_Final(tk, &ctx); // k2 = HMAC(tk||ES) // use CHP as the key // NOTE, ctxi and ctxo are no longer needed after this hmac, so we simply use them SHA1_Update(&ctxi, tk, 20); SHA1_Update(&ctxi, cur_salt->local_salt, cur_salt->local_salt_length); SHA1_Final(buffer, &ctxi); SHA1_Update(&ctxo, buffer, 20); SHA1_Final(key+20, &ctxo); // k = k1||k2 // encrypt "password-check" string using this key DES_set_key((C_Block *) key, &ks1); DES_set_key((C_Block *) (key+8), &ks2); DES_set_key((C_Block *) (key+16), &ks3); memcpy(ivec, key + 32, 8); // last 8 bytes! // PKCS#5 padding (standard block padding) DES_ede3_cbc_encrypt((unsigned char*)"password-check\x02\x02", (unsigned char*)crypt_out[index], 16, &ks1, &ks2, &ks3, &ivec, DES_ENCRYPT); } return count; } static int cmp_all(void *binary, int count) { int index = 0; #ifdef _OPENMP for (; index < count; index++) #endif if (((ARCH_WORD_32*)binary)[0] == crypt_out[index][0]) 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 void mozilla_set_key(char *key, int index) { saved_len[index] = strlen(key); strncpy(saved_key[index], key, sizeof(saved_key[0])); } static char *get_key(int index) { return saved_key[index]; } struct fmt_main fmt_mozilla = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, BINARY_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP, #if FMT_MAIN_VERSION > 11 { NULL }, #endif tests }, { init, fmt_default_done, fmt_default_reset, fmt_default_prepare, valid, fmt_default_split, get_binary, get_salt, #if FMT_MAIN_VERSION > 11 { NULL }, #endif 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, set_salt, mozilla_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
noflush.c
#include <omp.h> #include <stdio.h> #include <stdlib.h> int main() { int data, flag = 0; #pragma omp parallel num_threads(2) { if (omp_get_thread_num()==0) { /* Write to the data buffer that will be read by thread */ data = 42; /* Set flag to release thread 1 */ flag = 1; } else if (omp_get_thread_num()==1) { /* Loop until we see the update to the flag */ while (flag < 1) { } /* print flag and data */ printf("flag=%d data=%d\n", flag, data); } } return 0; }
omp_smithW_orig.c
/********************************************************************************* * Smith–Waterman algorithm * Purpose: Local alignment of nucleotide or protein sequences * Authors: Daniel Holanda, Hanoch Griner, Taynara Pinheiro * Compilation: gcc omp_smithW.c -o omp_smithW -fopenmp -DDEBUG * Execution: ./omp_smithW <number_of_threads> <number_of_col> <number_of_rows> *********************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <omp.h> #include <time.h> /*-------------------------------------------------------------------- * Text Tweaks */ #define RESET "\033[0m" #define BOLDRED "\033[1m\033[31m" /* Bold Red */ /* End of text tweaks */ /*-------------------------------------------------------------------- * Constants */ #define PATH -1 #define NONE 0 #define UP 1 #define LEFT 2 #define DIAGONAL 3 /* End of constants */ /*-------------------------------------------------------------------- * Helpers */ #define min(x, y) (((x) < (y)) ? (x) : (y)) #define max(a,b) ((a) > (b) ? a : b) // #define DEBUG /* End of Helpers */ /*-------------------------------------------------------------------- * Functions Prototypes */ void similarityScore(long long int i, long long int j, int* H, int* P, long long int* maxPos); int matchMissmatchScore(long long int i, long long int j); void backtrack(int* P, long long int maxPos); void printMatrix(int* matrix); void printPredecessorMatrix(int* matrix); void generate(void); long long int nElement(long long int i); void calcFirstDiagElement(long long int *i, long long int *si, long long int *sj); /* End of prototypes */ /*-------------------------------------------------------------------- * Global Variables */ //Defines size of strings to be compared long long int m ; //Columns - Size of string a long long int n ; //Lines - Size of string b //Defines scores int matchScore = 5; int missmatchScore = -3; int gapScore = -4; //Strings over the Alphabet Sigma char *a, *b; /* End of global variables */ /*-------------------------------------------------------------------- * Function: main */ int main(int argc, char* argv[]) { int thread_count = strtol(argv[1], NULL, 10); m = strtoll(argv[2], NULL, 10); n = strtoll(argv[3], NULL, 10); #ifdef DEBUG printf("\nMatrix[%lld][%lld]\n", n, m); #endif //Allocates a and b a = malloc(m * sizeof(char)); b = malloc(n * sizeof(char)); //Because now we have zeros m++; n++; //Allocates similarity matrix H int *H; H = calloc(m * n, sizeof(int)); //Allocates predecessor matrix P int *P; P = calloc(m * n, sizeof(int)); //Gen rand arrays a and b generate(); //Uncomment this to test the sequence available at //http://vlab.amrita.edu/?sub=3&brch=274&sim=1433&cnt=1 // OBS: m=11 n=7 // a[0] = 'C'; // a[1] = 'G'; // a[2] = 'T'; // a[3] = 'G'; // a[4] = 'A'; // a[5] = 'A'; // a[6] = 'T'; // a[7] = 'T'; // a[8] = 'C'; // a[9] = 'A'; // a[10] = 'T'; // b[0] = 'G'; // b[1] = 'A'; // b[2] = 'C'; // b[3] = 'T'; // b[4] = 'T'; // b[5] = 'A'; // b[6] = 'C'; //Start position for backtrack long long int maxPos = 0; //Calculates the similarity matrix long long int i, j; //Gets Initial time double initialTime = omp_get_wtime(); long long int si, sj, ai, aj; //Because now we have zeros ((m-1) + (n-1) - 1) long long int nDiag = m + n - 3; long long int nEle; #pragma omp parallel num_threads(thread_count) \ default(none) shared(H, P, maxPos, nDiag) private(nEle, i, si, sj, ai, aj) { for (i = 1; i <= nDiag; ++i) { nEle = nElement(i); calcFirstDiagElement(&i, &si, &sj); #pragma omp for for (j = 1; j <= nEle; ++j) { ai = si - j + 1; aj = sj + j - 1; similarityScore(ai, aj, H, P, &maxPos); } } } backtrack(P, maxPos); //Gets final time double finalTime = omp_get_wtime(); printf("\nElapsed time: %f\n\n", finalTime - initialTime); #ifdef DEBUG printf("\nSimilarity Matrix:\n"); printMatrix(H); printf("\nPredecessor Matrix:\n"); printPredecessorMatrix(P); #endif //Frees similarity matrixes free(H); free(P); //Frees input arrays free(a); free(b); return 0; } /* End of main */ /*-------------------------------------------------------------------- * Function: nElement * Purpose: Calculate the number of i-diagonal elements */ long long int nElement(long long int i) { if (i < m && i < n) { //Number of elements in the diagonal is increasing return i; } else if (i < max(m, n)) { //Number of elements in the diagonal is stable long int min = min(m, n); return min - 1; } else { //Number of elements in the diagonal is decreasing long int min = min(m, n); return 2 * min - i + abs(m - n) - 2; } } /*-------------------------------------------------------------------- * Function: calcElement * Purpose: Calculate the position of (si, sj)-element */ void calcFirstDiagElement(long long int *i, long long int *si, long long int *sj) { // Calculate the first element of diagonal if (*i < n) { *si = *i; *sj = 1; } else { *si = n - 1; *sj = *i - n + 2; } } /*-------------------------------------------------------------------- * Function: SimilarityScore * Purpose: Calculate the maximum Similarity-Score H(i,j) */ void similarityScore(long long int i, long long int j, int* H, int* P, long long int* maxPos) { int up, left, diag; //Stores index of element long long int index = m * i + j; //Get element above up = H[index - m] + gapScore; //Get element on the left left = H[index - 1] + gapScore; //Get element on the diagonal diag = H[index - m - 1] + matchMissmatchScore(i, j); //Calculates the maximum int max = NONE; int pred = NONE; /* === Matrix === * a[0] ... a[n] * b[0] * ... * b[n] * * generate 'a' from 'b', if '←' insert e '↑' remove * a=GAATTCA * b=GACTT-A * * generate 'b' from 'a', if '←' insert e '↑' remove * b=GACTT-A * a=GAATTCA */ if (diag > max) { //same letter ↖ max = diag; pred = DIAGONAL; } if (up > max) { //remove letter ↑ max = up; pred = UP; } if (left > max) { //insert letter ← max = left; pred = LEFT; } //Inserts the value in the similarity and predecessor matrixes H[index] = max; P[index] = pred; //Updates maximum score to be used as seed on backtrack #pragma omp critical if (max > H[*maxPos]) { *maxPos = index; } } /* End of similarityScore */ /*-------------------------------------------------------------------- * Function: matchMissmatchScore * Purpose: Similarity function on the alphabet for match/missmatch */ int matchMissmatchScore(long long int i, long long int j) { if (a[j - 1] == b[i - 1]) return matchScore; else return missmatchScore; } /* End of matchMissmatchScore */ /*-------------------------------------------------------------------- * Function: backtrack * Purpose: Modify matrix to print, path change from value to PATH */ void backtrack(int* P, long long int maxPos) { //hold maxPos value long long int predPos; //backtrack from maxPos to startPos = 0 do { if (P[maxPos] == DIAGONAL) predPos = maxPos - m - 1; else if (P[maxPos] == UP) predPos = maxPos - m; else if (P[maxPos] == LEFT) predPos = maxPos - 1; P[maxPos] *= PATH; maxPos = predPos; } while (P[maxPos] != NONE); } /* End of backtrack */ /*-------------------------------------------------------------------- * Function: printMatrix * Purpose: Print Matrix */ void printMatrix(int* matrix) { long long int i, j; printf("-\t-\t"); for (j = 0; j < m-1; j++) { printf("%c\t", a[j]); } printf("\n-\t"); for (i = 0; i < n; i++) { //Lines for (j = 0; j < m; j++) { if (j==0 && i>0) printf("%c\t", b[i-1]); printf("%d\t", matrix[m * i + j]); } printf("\n"); } } /* End of printMatrix */ /*-------------------------------------------------------------------- * Function: printPredecessorMatrix * Purpose: Print predecessor matrix */ void printPredecessorMatrix(int* matrix) { long long int i, j, index; printf(" "); for (j = 0; j < m-1; j++) { printf("%c ", a[j]); } printf("\n "); for (i = 0; i < n; i++) { //Lines for (j = 0; j < m; j++) { if (j==0 && i>0) printf("%c ", b[i-1]); index = m * i + j; if (matrix[index] < 0) { printf(BOLDRED); if (matrix[index] == -UP) printf("↑ "); else if (matrix[index] == -LEFT) printf("← "); else if (matrix[index] == -DIAGONAL) printf("↖ "); else printf("- "); printf(RESET); } else { if (matrix[index] == UP) printf("↑ "); else if (matrix[index] == LEFT) printf("← "); else if (matrix[index] == DIAGONAL) printf("↖ "); else printf("- "); } } printf("\n"); } } /* End of printPredecessorMatrix */ /*-------------------------------------------------------------------- * Function: generate * Purpose: Generate arrays a and b */ void generate() { //Random seed srand(time(NULL)); //Generates the values of a long long int i; for (i = 0; i < m; i++) { int aux = rand() % 4; if (aux == 0) a[i] = 'A'; else if (aux == 2) a[i] = 'C'; else if (aux == 3) a[i] = 'G'; else a[i] = 'T'; } //Generates the values of b for (i = 0; i < n; i++) { int aux = rand() % 4; if (aux == 0) b[i] = 'A'; else if (aux == 2) b[i] = 'C'; else if (aux == 3) b[i] = 'G'; else b[i] = 'T'; } } /* End of generate */ /*-------------------------------------------------------------------- * External References: * http://vlab.amrita.edu/?sub=3&brch=274&sim=1433&cnt=1 * http://pt.slideshare.net/avrilcoghlan/the-smith-waterman-algorithm * http://baba.sourceforge.net/ */
search.h
// -*- C++ -*- // Copyright (C) 2007, 2008, 2009 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library 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. // This 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 // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // <http://www.gnu.org/licenses/>. /** @file parallel/search.h * @brief Parallel implementation base for std::search() and * std::search_n(). * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Felix Putze. #ifndef _GLIBCXX_PARALLEL_SEARCH_H #define _GLIBCXX_PARALLEL_SEARCH_H 1 #include <bits/stl_algobase.h> #include <parallel/parallel.h> #include <parallel/equally_split.h> namespace __gnu_parallel { /** * @brief Precalculate advances for Knuth-Morris-Pratt algorithm. * @param elements Begin iterator of sequence to search for. * @param length Length of sequence to search for. * @param advances Returned offsets. */ template<typename RandomAccessIterator, typename _DifferenceTp> void calc_borders(RandomAccessIterator elements, _DifferenceTp length, _DifferenceTp* off) { typedef _DifferenceTp difference_type; off[0] = -1; if (length > 1) off[1] = 0; difference_type k = 0; for (difference_type j = 2; j <= length; j++) { while ((k >= 0) && !(elements[k] == elements[j-1])) k = off[k]; off[j] = ++k; } } // Generic parallel find algorithm (requires random access iterator). /** @brief Parallel std::search. * @param begin1 Begin iterator of first sequence. * @param end1 End iterator of first sequence. * @param begin2 Begin iterator of second sequence. * @param end2 End iterator of second sequence. * @param pred Find predicate. * @return Place of finding in first sequences. */ template<typename _RandomAccessIterator1, typename _RandomAccessIterator2, typename Pred> _RandomAccessIterator1 search_template(_RandomAccessIterator1 begin1, _RandomAccessIterator1 end1, _RandomAccessIterator2 begin2, _RandomAccessIterator2 end2, Pred pred) { typedef std::iterator_traits<_RandomAccessIterator1> traits_type; typedef typename traits_type::difference_type difference_type; _GLIBCXX_CALL((end1 - begin1) + (end2 - begin2)); difference_type pattern_length = end2 - begin2; // Pattern too short. if(pattern_length <= 0) return end1; // Last point to start search. difference_type input_length = (end1 - begin1) - pattern_length; // Where is first occurrence of pattern? defaults to end. difference_type result = (end1 - begin1); difference_type *splitters; // Pattern too long. if (input_length < 0) return end1; omp_lock_t result_lock; omp_init_lock(&result_lock); thread_index_t num_threads = std::max<difference_type>(1, std::min<difference_type>(input_length, get_max_threads())); difference_type advances[pattern_length]; calc_borders(begin2, pattern_length, advances); # pragma omp parallel num_threads(num_threads) { # pragma omp single { num_threads = omp_get_num_threads(); splitters = new difference_type[num_threads + 1]; equally_split(input_length, num_threads, splitters); } thread_index_t iam = omp_get_thread_num(); difference_type start = splitters[iam], stop = splitters[iam + 1]; difference_type pos_in_pattern = 0; bool found_pattern = false; while (start <= stop && !found_pattern) { // Get new value of result. #pragma omp flush(result) // No chance for this thread to find first occurrence. if (result < start) break; while (pred(begin1[start + pos_in_pattern], begin2[pos_in_pattern])) { ++pos_in_pattern; if (pos_in_pattern == pattern_length) { // Found new candidate for result. omp_set_lock(&result_lock); result = std::min(result, start); omp_unset_lock(&result_lock); found_pattern = true; break; } } // Make safe jump. start += (pos_in_pattern - advances[pos_in_pattern]); pos_in_pattern = (advances[pos_in_pattern] < 0) ? 0 : advances[pos_in_pattern]; } } //parallel omp_destroy_lock(&result_lock); delete[] splitters; // Return iterator on found element. return (begin1 + result); } } // end namespace #endif /* _GLIBCXX_PARALLEL_SEARCH_H */
DRB025-simdtruedep-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. */ /* This one has race condition due to true dependence. But data races happen at instruction level, not thread level. Data race pair: a[i+1]@68:5 vs. a[i]@68:12 */ #include <stdlib.h> #include <omp.h> int main(int argc,char *argv[]) { int i; int len = 100; if (argc > 1) len = atoi(argv[1]); int a[len]; int b[len]; #pragma omp parallel for private (i) for (i = 0; i <= len - 1; i += 1) { a[i] = i; b[i] = i + 1; } for (i = 0; i <= len - 1 - 1; i += 1) { a[i + 1] = a[i] * b[i]; } for (i = 0; i <= len - 1; i += 1) { printf("%d %d\n",a[i],b[i]); } return 0; }
blackscholes.c
// ----------------------------------------------------------------------------- // Notes/Imports /* Notes: - 'NOTE: Removed' indicates that a line of code was commented out for compatability reasons Any significant change to the benchmark is wrapped in a --begin HORNET ... --end HORNET clause (commented out) TODO 1.) check and remove extra __H_fflush(); calls CHANGES: 1.) library function call names 2.) print statements 3.) calls to __H_read_line have temporary space allocated (see bug list in mcpu.hpp). 4.) P/C in the input files changed to 1 0 to satisfy an INT alignment bug */ #ifdef LINKING #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #else #include "rts.h" #endif //#define LINKING // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // Black Scholes main algorithm // Copyright (c) 2007 Intel Corp. // Black-Scholes // Analytical method for calculating European Options // // // Reference Source: Options, Futures, and Other Derivatives, 3rd Edition, Prentice // Hall, John C. Hull, #define ENABLE_THREADS_HORNET //#define ENABLE_THREADS //#define WIN32 #ifdef ENABLE_PARSEC_HOOKS #include <hooks.h> #endif // Multi-threaded pthreads header #ifdef ENABLE_THREADS #define MAX_THREADS 1024 // Add the following line so that icc 9.0 is compatible with pthread lib. #define __thread __threadp MAIN_ENV #undef __thread BARDEC(barrier); #endif // Multi-threaded OpenMP header #ifdef ENABLE_OPENMP #include <omp.h> #endif // Multi-threaded header for Windows #ifdef WIN32 #pragma warning(disable : 4305) #pragma warning(disable : 4244) //#include <windows.h> #define MAX_THREADS 1024 #endif //Precision to use for calculations // TODO: find a way to parameterize these to the commented out fragments #define FP_PRECISION // if this line is commented out, assume double #define fptype float //((FP_PRECISION == 32) ? float : double) #define __H_sqrt __H_sqrt_s //((FP_PRECISION == 32) ? __H_sqrt_s : __H_sqrt_d) #define __H_log __H_log_s //((FP_PRECISION == 32) ? __H_log_s : __H_log_d) #define __H_exp __H_exp_s //((FP_PRECISION == 32) ? __H_exp_s : __H_exp_d) #define print_fp print_float // or print_double #define NUM_RUNS 100 // HORNET: DO NOT CHANGE THE ORDER OF THE FIELDS IN THIS STRUCT! // (doing so will break the __H_read_line call, unless you also change setup.py) typedef struct OptionData_ { fptype s; // spot price fptype strike; // strike price fptype r; // risk-free interest rate fptype divq; // dividend rate fptype v; // volatility fptype t; // time to maturity or option expiration in years // (1yr = 1.0, 6mos = 0.5, 3mos = 0.25, ..., etc) int OptionType; // Option type. "P"=PUT, "C"=CALL // HORNET: this was char OptionType. Changed to int // OptionType because of word alignment. fptype divs; // dividend vals (not used in this test) fptype DGrefval; // DerivaGem Reference Value } OptionData; int * __H_MUTEX_BARRIER_START = 0x003ffffc; int ** __PROXY_numOptions = 0x003ffff4; fptype ** __PROXY_prices = 0x003ffff0; int ** __PROXY_otype = 0x003fffec; fptype ** __PROXY_sptprice = 0x003fffe8; fptype ** __PROXY_strike = 0x003fffe4; fptype ** __PROXY_rate = 0x003fffe0; fptype ** __PROXY_volatility = 0x003fffdc; fptype ** __PROXY_otime = 0x003fffd8; //int numError = 0; int nThreads; //int nThreadsMask; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // Cumulative Normal Distribution Function // See Hull, Section 11.8, P.243-244 #define inv_sqrt_2xPI 0.39894228040143270286 fptype CNDF ( fptype InputX ) { int sign; fptype OutputX; fptype xInput; fptype xNPrimeofX; fptype expValues; fptype xK2; fptype xK2_2, xK2_3; fptype xK2_4, xK2_5; fptype xLocal, xLocal_1; fptype xLocal_2, xLocal_3; // Check for negative value of InputX if (InputX < 0.0) { InputX = -InputX; sign = 1; } else sign = 0; xInput = InputX; // Compute NPrimeX term common to both four & six decimal accuracy calcs expValues = __H_exp(-0.5f * InputX * InputX); xNPrimeofX = expValues; xNPrimeofX = xNPrimeofX * inv_sqrt_2xPI; xK2 = 0.2316419 * xInput; xK2 = 1.0 + xK2; xK2 = 1.0 / xK2; xK2_2 = xK2 * xK2; xK2_3 = xK2_2 * xK2; xK2_4 = xK2_3 * xK2; xK2_5 = xK2_4 * xK2; xLocal_1 = xK2 * 0.319381530; xLocal_2 = xK2_2 * (-0.356563782); xLocal_3 = xK2_3 * 1.781477937; xLocal_2 = xLocal_2 + xLocal_3; xLocal_3 = xK2_4 * (-1.821255978); xLocal_2 = xLocal_2 + xLocal_3; xLocal_3 = xK2_5 * 1.330274429; xLocal_2 = xLocal_2 + xLocal_3; xLocal_1 = xLocal_2 + xLocal_1; xLocal = xLocal_1 * xNPrimeofX; xLocal = 1.0 - xLocal; OutputX = xLocal; if (sign) { OutputX = 1.0 - OutputX; } return OutputX; } // For debugging void print_xmm(fptype in, char* s) { __H_printf("%s: %f\n", s, in); } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// fptype BlkSchlsEqEuroNoDiv( fptype sptprice, fptype strike, fptype rate, fptype volatility, fptype time, int otype, float timet ) { fptype OptionPrice; // local private working variables for the calculation fptype xStockPrice; fptype xStrikePrice; fptype xRiskFreeRate; fptype xVolatility; fptype xTime; fptype xSqrtTime; fptype logValues; fptype xLogTerm; fptype xD1; fptype xD2; fptype xPowerTerm; fptype xDen; fptype d1; fptype d2; fptype FutureValueX; fptype NofXd1; fptype NofXd2; fptype NegNofXd1; fptype NegNofXd2; xStockPrice = sptprice; xStrikePrice = strike; xRiskFreeRate = rate; xVolatility = volatility; xTime = time; xSqrtTime = __H_sqrt(xTime); logValues = __H_log( sptprice / strike ); xLogTerm = logValues; xPowerTerm = xVolatility * xVolatility; xPowerTerm = xPowerTerm * 0.5; xD1 = xRiskFreeRate + xPowerTerm; xD1 = xD1 * xTime; xD1 = xD1 + xLogTerm; xDen = xVolatility * xSqrtTime; xD1 = xD1 / xDen; xD2 = xD1 - xDen; d1 = xD1; d2 = xD2; NofXd1 = CNDF( d1 ); NofXd2 = CNDF( d2 ); FutureValueX = strike * ( __H_exp( -(rate)*(time) ) ); if (otype == 0) { OptionPrice = (sptprice * NofXd1) - (FutureValueX * NofXd2); } else { NegNofXd1 = (1.0 - NofXd1); NegNofXd2 = (1.0 - NofXd2); OptionPrice = (FutureValueX * NegNofXd2) - (sptprice * NegNofXd1); } return OptionPrice; } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// #ifdef WIN32 DWORD WINAPI bs_thread(LPVOID tid_ptr){ #else int bs_thread(void *tid_ptr) { #endif #ifdef ENABLE_THREADS BARRIER(barrier); #endif #ifdef ENABLE_THREADS_HORNET while (!*__H_MUTEX_BARRIER_START) { /* spin while the master thread works on loading the run data */ /*print_string("Spinning thread # "); print_int(*(int *)tid_ptr); print_string("\n"); __H_fflush();*/ }; #endif int i, j; fptype price; fptype priceDelta; int numOptions = **__PROXY_numOptions; int tid = *(int *)tid_ptr; fptype * prices = *__PROXY_prices; int * otype = *__PROXY_otype; fptype * sptprice = *__PROXY_sptprice; fptype * strike = *__PROXY_strike; fptype * rate = *__PROXY_rate; fptype * volatility = *__PROXY_volatility; fptype * otime = *__PROXY_otime; int start = tid * (numOptions / nThreads); int end = start + (numOptions / nThreads); //print_string("tid="); //print_int(tid); //print_string(" go (start: "); //print_int(start); //print_string(", end: "); //print_int(end); //print_string(")\n"); for (j=0; j<NUM_RUNS; j++) { //print_string("tid="); //print_int(tid); //print_string(", runs="); //print_int(j); //print_string("\n"); __H_fflush(); #ifdef ENABLE_OPENMP #pragma omp parallel for for (i=0; i<numOptions; i++) { #else //ENABLE_OPENMP for (i=start; i<end; i++) { #endif //ENABLE_OPENMP // Calling main function to calculate option value based on Black & // Sholes's equation. price = BlkSchlsEqEuroNoDiv( sptprice[i], strike[i], rate[i], volatility[i], otime[i], otype[i], 0); prices[i] = price; print_string("\nBlkSchlsEqEuroNoDiv loop["); print_int(j); print_string("]["); print_int(i); print_string("] "); print_string("Price: "); print_float(price); print_string("\n"); __H_fflush(); /*print_fp(sptprice[i]); print_string("\n"); print_fp(strike[i]); print_string("\n"); print_fp(rate[i]); print_string("\n"); print_fp(volatility[i]); print_string("\n"); print_fp(otime[i]); print_string("\n"); print_int(otype[i]); print_string("\n"); __H_fflush();*/ #ifdef ERR_CHK __H_exit(51); // data no longer has global scope, and DGrefval isn't being properly shared priceDelta = data[i].DGrefval - price; if( fabs(priceDelta) >= 1e-4 ) { print_string("Error on "); print_int(i); print_string(", Computed="); print_fp(price); print_string(", Ref="); print_fp(data[i].DGrefval); print_string(", Delta="); print_fp(priceDelta); print_string("\n"); numError++; } #endif } } #ifdef ENABLE_THREADS //print_string("tid="); //print_int(tid); //print_string(" done\n"); BARRIER(barrier); #else//ENABLE_THREADS #endif//ENABLE_THREADS return 0; } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// int main(int argc, char **argv) { // initialize the master thread barrier if (cpu_id() == 0) { *__H_MUTEX_BARRIER_START = 0; } unsigned id = cpu_id(); #ifdef ENABLE_THREADS_HORNET nThreads = 4; //nThreadsMask = 0x1FF; // 4 1s in lsb positions -- TODO: turn into a function #else nThreads = 1; //nThreadsMask = 0x1; #endif print_string("Starting thread # "); print_int(id); print_string("\n"); __H_fflush(); #ifdef ENABLE_THREADS_HORNET if (id == 0) { // only intialize with the master thread #endif print_string("Starting "); print_int(nThreads); print_string(" Blackscholes threads.\n"); __H_fflush(); int numOptions; OptionData *data; int file; int i; int loopnum; fptype * buffer; int * buffer2; int rv; fptype * prices; int * otype; fptype * sptprice; fptype * strike; fptype * rate; fptype * volatility; fptype * otime; #ifdef PARSEC_VERSION #define __PARSEC_STRING(x) #x #define __PARSEC_XSTRING(x) __PARSEC_STRING(x) __H_printf("PARSEC Benchmark Suite Version "__PARSEC_XSTRING(PARSEC_VERSION)"\n"); __H_fflush(NULL); #else __H_printf("PARSEC Benchmark Suite\n"); __H_fflush(NULL); #endif #ifdef ENABLE_PARSEC_HOOKS __parsec_bench_begin(__parsec_blackscholes); #endif char * inputFile = "in_4K.bin"; char * outputFile = "results"; //Read input data from file file = __H_fopen(inputFile); if (file == 0) { // was: NULL print_string("\nERROR: Unable to read from file: "); print_string(inputFile); print_string("\n"); __H_exit(1); } int tmp; rv = __H_read_line(file, (char *) &tmp, 4); numOptions = tmp; *__PROXY_numOptions = (int *) malloc(sizeof(int)); **__PROXY_numOptions = tmp; if(rv != 4) { print_string("\nERROR: Couldn't read numOptions count in file: "); print_string(inputFile); print_string("\n"); __H_fclose(file); __H_exit(1); } print_string("Processing "); print_int(numOptions); print_string(" stock options.\n"); __H_fflush(); if (nThreads > numOptions) { print_string("\nWARNING: Not enough work, reducing number of threads to match number of options.\n"); nThreads = numOptions; __H_fflush(); } #if !defined(ENABLE_THREADS) && !defined(ENABLE_OPENMP) && !defined(ENABLE_THREADS_HORNET) if(nThreads != 1) { print_string("Error: <nthreads> must be 1 (serial version)\n"); __H_exit(1); } #endif // alloc spaces for the option data #ifdef FP_PRECISION int epl = 36; #else int epl = 68; #endif OptionData tmp_OptionData; data = (OptionData*) malloc(numOptions*sizeof(OptionData)); prices = (fptype*) malloc(numOptions*sizeof(fptype)); *__PROXY_prices = prices; for ( loopnum = 0; loopnum < numOptions; ++ loopnum ) { rv = __H_read_line(file, (char *) &tmp_OptionData, epl); data[loopnum].s = tmp_OptionData.s; data[loopnum].strike = tmp_OptionData.strike; data[loopnum].r = tmp_OptionData.r; data[loopnum].divq = tmp_OptionData.divq; data[loopnum].v = tmp_OptionData.v; data[loopnum].t = tmp_OptionData.t; data[loopnum].OptionType = tmp_OptionData.OptionType; data[loopnum].divs = tmp_OptionData.divs; data[loopnum].DGrefval = tmp_OptionData.DGrefval; print_string("Reading line: "); print_int(loopnum); print_string("\n"); __H_fflush(); /*print_string("\ns: "); print_fp(data[loopnum].s); print_string("\n"); print_string("strike: "); print_fp(data[loopnum].strike); print_string("\n"); print_string("r: "); print_fp(data[loopnum].r); print_string("\n"); print_string("divq: "); print_fp(data[loopnum].divq); print_string("\n"); print_string("v: "); print_fp(data[loopnum].v); print_string("\n"); print_string("t: "); print_fp(data[loopnum].t); print_string("\n"); print_string("OptionType: "); print_int(data[loopnum].OptionType); print_string("\n"); print_string("divs: "); print_fp(data[loopnum].divs); print_string("\n"); print_string("DGrefval: "); print_fp(data[loopnum].DGrefval); print_string("\n\n"); __H_fflush();*/ if (rv != epl) { print_string("ERROR: Wrong byte count on line "); print_int(loopnum); print_string(" ~ expected: "); print_int(epl); print_string(", actual: "); print_int(rv); print_string("\n"); __H_exit(1); } } rv = __H_fclose(file); if(rv != 0) { print_string("ERROR: Unable to close file."); __H_exit(1); } #ifdef ENABLE_THREADS MAIN_INITENV(,8000000,nThreads); BARINIT(barrier, nThreads); #endif /*print_string("Num of Options: "); print_int(numOptions); print_string("\n"); __H_fflush(); print_string("Num of Runs: "); print_int(NUM_RUNS); print_string("\n"); __H_fflush();*/ #define PAD 256 #define LINESIZE 64 buffer = (fptype *) malloc(5 * numOptions * sizeof(fptype) + PAD); sptprice = (fptype *) (((unsigned long long)buffer + PAD) & ~(LINESIZE - 1)); *__PROXY_sptprice = sptprice; strike = sptprice + numOptions; *__PROXY_strike = strike; rate = strike + numOptions; *__PROXY_rate = rate; volatility = rate + numOptions; *__PROXY_volatility = volatility; otime = volatility + numOptions; *__PROXY_otime = otime; buffer2 = (int *) malloc(numOptions * sizeof(fptype) + PAD); otype = (int *) (((unsigned long long)buffer2 + PAD) & ~(LINESIZE - 1)); *__PROXY_otype = otype; for (i=0; i<numOptions; i++) { // TODO: collapse this into the data[] to speedup initialization time otype[i] = (data[i].OptionType) ? 1 : 0; // --begin HORNET used to be " == 'P'..." sptprice[i] = data[i].s; strike[i] = data[i].strike; rate[i] = data[i].r; volatility[i] = data[i].v; otime[i] = data[i].t; print_string("Copying line: "); print_int(i); print_string("\n"); __H_fflush(); } //print_string("Size of data: "); //print_int((int) numOptions * (sizeof(OptionData) + sizeof(int))); //print_string("\n"); //__H_fflush(); #ifdef ENABLE_THREADS_HORNET } else { __H_enable_memory_hierarchy(); } #endif // ----------------------------------------------------------------------------- // Threads fork // ----------------------------------------------------------------------------- #ifdef ENABLE_PARSEC_HOOKS __parsec_roi_begin(); #endif #ifdef ENABLE_THREADS int tids[nThreads]; for(i=0; i<nThreads; i++) { tids[i]=i; CREATE_WITH_ARG(bs_thread, &tids[i]); } __H_printf("%d threads spawned", i); WAIT_FOR_END(nThreads); #else//ENABLE_THREADS #ifdef ENABLE_THREADS_HORNET /* This is the block that is relevant for Hornet developers/users */ if (id == 0) { __H_enable_memory_hierarchy(); *__H_MUTEX_BARRIER_START = 1; } int tid=id; bs_thread(&tid); #else//ENABLE_THREADS_HORNET #ifdef ENABLE_OPENMP { int tid=0; omp_set_num_threads(nThreads); bs_thread(&tid); } #else //ENABLE_OPENMP #ifdef WIN32 if (nThreads > 1) { HANDLE threads[MAX_THREADS]; int nums[MAX_THREADS]; for(i=0; i<nThreads; i++) { nums[i] = i; threads[i] = CreateThread(0, 0, bs_thread, &nums[i], 0, 0); } WaitForMultipleObjects(nThreads, threads, TRUE, INFINITE); } else #endif { __H_exit(50); // this code segment needs to be updated before being run again int tid=0; bs_thread(*numOptions_shared, &tid); } #endif //ENABLE_OPENMP #endif //ENABLE_THREADS_HORNET #endif //ENABLE_THREADS #ifdef ENABLE_PARSEC_HOOKS __parsec_roi_end(); #endif // ----------------------------------------------------------------------------- // Threads join // ----------------------------------------------------------------------------- /* After all threads finish their jobs... SKIP THE POST PROCESSING AND TERMINATE EXECUTION //Write prices to output file file = __H_fopen(outputFile, "w"); if(file == NULL) { __H_printf("ERROR: Unable to open file `%s'.\n", outputFile); __H_exit(1); } rv = f__H_printf(file, "%i\n", numOptions); if(rv < 0) { __H_printf("ERROR: Unable to write to file `%s'.\n", outputFile); fclose(file); __H_exit(1); } for(i=0; i<numOptions; i++) { rv = f__H_printf(file, "%.18f\n", prices[i]); if(rv < 0) { __H_printf("ERROR: Unable to write to file `%s'.\n", outputFile); fclose(file); __H_exit(1); } } rv = fclose(file); if(rv != 0) { __H_printf("ERROR: Unable to close file `%s'.\n", outputFile); __H_exit(1); } #ifdef ERR_CHK __H_printf("Num Errors: %d\n", numError); #endif free(data); free(prices); #ifdef ENABLE_PARSEC_HOOKS __parsec_bench_end(); #endif */ print_string("Thread # "); print_int(id); print_string(" completed!\n"); __H_fflush(); return 0; }
vision.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % V V IIIII SSSSS IIIII OOO N N % % V V I SS I O O NN N % % V V I SSS I O O N N N % % V V I SS I O O N NN % % V IIIII SSSSS IIIII OOO N N % % % % % % MagickCore Computer Vision Methods % % % % Software Design % % Cristy % % September 2014 % % % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/blob.h" #include "MagickCore/cache-view.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.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/gem.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/opencl-private.h" #include "MagickCore/paint.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/property.h" #include "MagickCore/quantum.h" #include "MagickCore/resource_.h" #include "MagickCore/signature-private.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/token.h" #include "MagickCore/vision.h" // iOS: #include "ios_error.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o n n e c t e d C o m p o n e n t s I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ConnectedComponentsImage() returns the connected-components of the image % uniquely labeled. The returned connected components image colors member % defines the number of unique objects. Choose from 4 or 8-way connectivity. % % You are responsible for freeing the connected components objects resources % with this statement; % % objects = (CCObjectInfo *) RelinquishMagickMemory(objects); % % The format of the ConnectedComponentsImage method is: % % Image *ConnectedComponentsImage(const Image *image, % const size_t connectivity,CCObjectInfo **objects, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o connectivity: how many neighbors to visit, choose from 4 or 8. % % o objects: return the attributes of each unique object. % % o exception: return any errors or warnings in this structure. % */ static int CCObjectInfoCompare(const void *x,const void *y) { CCObjectInfo *p, *q; p=(CCObjectInfo *) x; q=(CCObjectInfo *) y; return((int) (q->area-(ssize_t) p->area)); } MagickExport Image *ConnectedComponentsImage(const Image *image, const size_t connectivity,CCObjectInfo **objects,ExceptionInfo *exception) { #define ConnectedComponentsImageTag "ConnectedComponents/Image" CacheView *component_view, *image_view, *object_view; CCObjectInfo *object; char *c; const char *artifact, *metrics[CCMaxMetrics]; double max_threshold, min_threshold; Image *component_image; MagickBooleanType status; MagickOffsetType progress; MatrixInfo *equivalences; RectangleInfo bounding_box; register ssize_t i; size_t size; ssize_t background_id, connect4[2][2] = { { -1, 0 }, { 0, -1 } }, connect8[4][2] = { { -1, -1 }, { -1, 0 }, { -1, 1 }, { 0, -1 } }, dx, dy, first, last, n, step, y; /* Initialize connected components 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); if (objects != (CCObjectInfo **) NULL) *objects=(CCObjectInfo *) NULL; component_image=CloneImage(image,0,0,MagickTrue,exception); if (component_image == (Image *) NULL) return((Image *) NULL); component_image->depth=MAGICKCORE_QUANTUM_DEPTH; if (AcquireImageColormap(component_image,MaxColormapSize,exception) == MagickFalse) { component_image=DestroyImage(component_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Initialize connected components equivalences. */ size=image->columns*image->rows; if (image->columns != (size/image->rows)) { component_image=DestroyImage(component_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } equivalences=AcquireMatrixInfo(size,1,sizeof(ssize_t),exception); if (equivalences == (MatrixInfo *) NULL) { component_image=DestroyImage(component_image); return((Image *) NULL); } for (n=0; n < (ssize_t) (image->columns*image->rows); n++) (void) SetMatrixElement(equivalences,n,0,&n); object=(CCObjectInfo *) AcquireQuantumMemory(MaxColormapSize,sizeof(*object)); if (object == (CCObjectInfo *) NULL) { equivalences=DestroyMatrixInfo(equivalences); component_image=DestroyImage(component_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } (void) memset(object,0,MaxColormapSize*sizeof(*object)); for (i=0; i < (ssize_t) MaxColormapSize; i++) { object[i].id=i; object[i].bounding_box.x=(ssize_t) image->columns; object[i].bounding_box.y=(ssize_t) image->rows; GetPixelInfo(image,&object[i].color); } /* Find connected components. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); for (n=0; n < (ssize_t) (connectivity > 4 ? 4 : 2); n++) { if (status == MagickFalse) continue; dx=connectivity > 4 ? connect8[n][1] : connect4[n][1]; dy=connectivity > 4 ? connect8[n][0] : connect4[n][0]; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y-1,image->columns,3,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } p+=GetPixelChannels(image)*image->columns; for (x=0; x < (ssize_t) image->columns; x++) { PixelInfo pixel, target; ssize_t neighbor_offset, obj, offset, ox, oy, root; /* Is neighbor an authentic pixel and a different color than the pixel? */ GetPixelInfoPixel(image,p,&pixel); if (((x+dx) < 0) || ((x+dx) >= (ssize_t) image->columns) || ((y+dy) < 0) || ((y+dy) >= (ssize_t) image->rows)) { p+=GetPixelChannels(image); continue; } neighbor_offset=dy*(GetPixelChannels(image)*image->columns)+dx* GetPixelChannels(image); GetPixelInfoPixel(image,p+neighbor_offset,&target); if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse) { p+=GetPixelChannels(image); continue; } /* Resolve this equivalence. */ offset=y*image->columns+x; neighbor_offset=dy*image->columns+dx; ox=offset; status=GetMatrixElement(equivalences,ox,0,&obj); while (obj != ox) { ox=obj; status=GetMatrixElement(equivalences,ox,0,&obj); } oy=offset+neighbor_offset; status=GetMatrixElement(equivalences,oy,0,&obj); while (obj != oy) { oy=obj; status=GetMatrixElement(equivalences,oy,0,&obj); } if (ox < oy) { status=SetMatrixElement(equivalences,oy,0,&ox); root=ox; } else { status=SetMatrixElement(equivalences,ox,0,&oy); root=oy; } ox=offset; status=GetMatrixElement(equivalences,ox,0,&obj); while (obj != root) { status=GetMatrixElement(equivalences,ox,0,&obj); status=SetMatrixElement(equivalences,ox,0,&root); } oy=offset+neighbor_offset; status=GetMatrixElement(equivalences,oy,0,&obj); while (obj != root) { status=GetMatrixElement(equivalences,oy,0,&obj); status=SetMatrixElement(equivalences,oy,0,&root); } status=SetMatrixElement(equivalences,y*image->columns+x,0,&root); p+=GetPixelChannels(image); } } } /* Label connected components. */ n=0; component_view=AcquireAuthenticCacheView(component_image,exception); for (y=0; y < (ssize_t) component_image->rows; y++) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(component_view,0,y,component_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) component_image->columns; x++) { ssize_t id, offset; offset=y*image->columns+x; status=GetMatrixElement(equivalences,offset,0,&id); if (id != offset) status=GetMatrixElement(equivalences,id,0,&id); else { id=n++; if (id >= (ssize_t) MaxColormapSize) break; } status=SetMatrixElement(equivalences,offset,0,&id); if (x < object[id].bounding_box.x) object[id].bounding_box.x=x; if (x >= (ssize_t) object[id].bounding_box.width) object[id].bounding_box.width=(size_t) x; if (y < object[id].bounding_box.y) object[id].bounding_box.y=y; if (y >= (ssize_t) object[id].bounding_box.height) object[id].bounding_box.height=(size_t) y; object[id].color.red+=QuantumScale*GetPixelRed(image,p); object[id].color.green+=QuantumScale*GetPixelGreen(image,p); object[id].color.blue+=QuantumScale*GetPixelBlue(image,p); if (image->alpha_trait != UndefinedPixelTrait) object[id].color.alpha+=QuantumScale*GetPixelAlpha(image,p); if (image->colorspace == CMYKColorspace) object[id].color.black+=QuantumScale*GetPixelBlack(image,p); object[id].centroid.x+=x; object[id].centroid.y+=y; object[id].area++; SetPixelIndex(component_image,(Quantum) id,q); p+=GetPixelChannels(image); q+=GetPixelChannels(component_image); } if (n > (ssize_t) MaxColormapSize) break; if (SyncCacheViewAuthenticPixels(component_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; progress++; proceed=SetImageProgress(image,ConnectedComponentsImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } component_view=DestroyCacheView(component_view); image_view=DestroyCacheView(image_view); equivalences=DestroyMatrixInfo(equivalences); if (n > (ssize_t) MaxColormapSize) { object=(CCObjectInfo *) RelinquishMagickMemory(object); component_image=DestroyImage(component_image); ThrowImageException(ResourceLimitError,"TooManyObjects"); } background_id=0; min_threshold=0.0; max_threshold=0.0; component_image->colors=(size_t) n; for (i=0; i < (ssize_t) component_image->colors; i++) { object[i].bounding_box.width-=(object[i].bounding_box.x-1); object[i].bounding_box.height-=(object[i].bounding_box.y-1); object[i].color.red/=(QuantumScale*object[i].area); object[i].color.green/=(QuantumScale*object[i].area); object[i].color.blue/=(QuantumScale*object[i].area); if (image->alpha_trait != UndefinedPixelTrait) object[i].color.alpha/=(QuantumScale*object[i].area); if (image->colorspace == CMYKColorspace) object[i].color.black/=(QuantumScale*object[i].area); object[i].centroid.x/=object[i].area; object[i].centroid.y/=object[i].area; max_threshold+=object[i].area; if (object[i].area > object[background_id].area) background_id=i; } max_threshold+=MagickEpsilon; n=(-1); artifact=GetImageArtifact(image,"connected-components:background-id"); if (artifact != (const char *) NULL) background_id=(ssize_t) StringToDouble(artifact,(char **) NULL); artifact=GetImageArtifact(image,"connected-components:area-threshold"); if (artifact != (const char *) NULL) { /* Merge any object not within the min and max area threshold. */ (void) sscanf(artifact,"%lf%*[ -]%lf",&min_threshold,&max_threshold); for (i=0; i < (ssize_t) component_image->colors; i++) if (((object[i].area < min_threshold) || (object[i].area >= max_threshold)) && (i != background_id)) object[i].merge=MagickTrue; } artifact=GetImageArtifact(image,"connected-components:keep-colors"); if (artifact != (const char *) NULL) { register const char *p; /* Keep selected objects based on color, merge others. */ for (i=0; i < (ssize_t) component_image->colors; i++) object[i].merge=MagickTrue; for (p=artifact; ; ) { char color[MagickPathExtent]; PixelInfo pixel; register const char *q; for (q=p; *q != '\0'; q++) if (*q == ';') break; (void) CopyMagickString(color,p,(size_t) MagickMin(q-p+1, MagickPathExtent)); (void) QueryColorCompliance(color,AllCompliance,&pixel,exception); for (i=0; i < (ssize_t) component_image->colors; i++) if (IsFuzzyEquivalencePixelInfo(&object[i].color,&pixel) != MagickFalse) object[i].merge=MagickFalse; if (*q == '\0') break; p=q+1; } } artifact=GetImageArtifact(image,"connected-components:keep-ids"); if (artifact == (const char *) NULL) artifact=GetImageArtifact(image,"connected-components:keep"); if (artifact != (const char *) NULL) { /* Keep selected objects based on id, merge others. */ for (i=0; i < (ssize_t) component_image->colors; i++) object[i].merge=MagickTrue; for (c=(char *) artifact; *c != '\0'; ) { while ((isspace((int) ((unsigned char) *c)) != 0) || (*c == ',')) c++; first=(ssize_t) strtol(c,&c,10); if (first < 0) first+=(ssize_t) component_image->colors; last=first; while (isspace((int) ((unsigned char) *c)) != 0) c++; if (*c == '-') { last=(ssize_t) strtol(c+1,&c,10); if (last < 0) last+=(ssize_t) component_image->colors; } step=(ssize_t) (first > last ? -1 : 1); for ( ; first != (last+step); first+=step) object[first].merge=MagickFalse; } } artifact=GetImageArtifact(image,"connected-components:keep-top"); if (artifact != (const char *) NULL) { CCObjectInfo *top_objects; ssize_t top_ids; /* Keep top objects. */ top_ids=(ssize_t) StringToDouble(artifact,(char **) NULL); top_objects=(CCObjectInfo *) AcquireQuantumMemory(component_image->colors, sizeof(*top_objects)); if (top_objects == (CCObjectInfo *) NULL) { object=(CCObjectInfo *) RelinquishMagickMemory(object); component_image=DestroyImage(component_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } (void) memcpy(top_objects,object,component_image->colors*sizeof(*object)); qsort((void *) top_objects,component_image->colors,sizeof(*top_objects), CCObjectInfoCompare); for (i=top_ids+1; i < (ssize_t) component_image->colors; i++) object[top_objects[i].id].merge=MagickTrue; top_objects=(CCObjectInfo *) RelinquishMagickMemory(top_objects); } artifact=GetImageArtifact(image,"connected-components:remove-colors"); if (artifact != (const char *) NULL) { register const char *p; /* Remove selected objects based on color, keep others. */ for (p=artifact; ; ) { char color[MagickPathExtent]; PixelInfo pixel; register const char *q; for (q=p; *q != '\0'; q++) if (*q == ';') break; (void) CopyMagickString(color,p,(size_t) MagickMin(q-p+1, MagickPathExtent)); (void) QueryColorCompliance(color,AllCompliance,&pixel,exception); for (i=0; i < (ssize_t) component_image->colors; i++) if (IsFuzzyEquivalencePixelInfo(&object[i].color,&pixel) != MagickFalse) object[i].merge=MagickTrue; if (*q == '\0') break; p=q+1; } } artifact=GetImageArtifact(image,"connected-components:remove-ids"); if (artifact == (const char *) NULL) artifact=GetImageArtifact(image,"connected-components:remove"); if (artifact != (const char *) NULL) for (c=(char *) artifact; *c != '\0'; ) { /* Remove selected objects based on id, keep others. */ while ((isspace((int) ((unsigned char) *c)) != 0) || (*c == ',')) c++; first=(ssize_t) strtol(c,&c,10); if (first < 0) first+=(ssize_t) component_image->colors; last=first; while (isspace((int) ((unsigned char) *c)) != 0) c++; if (*c == '-') { last=(ssize_t) strtol(c+1,&c,10); if (last < 0) last+=(ssize_t) component_image->colors; } step=(ssize_t) (first > last ? -1 : 1); for ( ; first != (last+step); first+=step) object[first].merge=MagickTrue; } artifact=GetImageArtifact(image,"connected-components:perimeter-threshold"); if (artifact != (const char *) NULL) { /* Merge any object not within the min and max perimeter threshold. */ (void) sscanf(artifact,"%lf%*[ -]%lf",&min_threshold,&max_threshold); metrics[++n]="perimeter"; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic) shared(status) \ magick_number_threads(component_image,component_image,component_image->colors,1) #endif for (i=0; i < (ssize_t) component_image->colors; i++) { CacheView *component_view; RectangleInfo bounding_box; size_t pattern[4] = { 1, 0, 0, 0 }; ssize_t y; /* Compute perimeter of each object. */ if (status == MagickFalse) continue; component_view=AcquireAuthenticCacheView(component_image,exception); bounding_box=object[i].bounding_box; for (y=(-1); y < (ssize_t) bounding_box.height+1; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(component_view,bounding_box.x-1, bounding_box.y+y,bounding_box.width+2,2,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (x=(-1); x < (ssize_t) bounding_box.width+1; x++) { Quantum pixels[4]; register ssize_t v; size_t foreground; /* An Algorithm for Calculating Objects’ Shape Features in Binary Images, Lifeng He, Yuyan Chao. */ foreground=0; for (v=0; v < 2; v++) { register ssize_t u; for (u=0; u < 2; u++) { ssize_t offset; offset=v*(bounding_box.width+2)* GetPixelChannels(component_image)+u* GetPixelChannels(component_image); pixels[2*v+u]=GetPixelIndex(component_image,p+offset); if ((ssize_t) pixels[2*v+u] == i) foreground++; } } if (foreground == 1) pattern[1]++; else if (foreground == 2) { if ((((ssize_t) pixels[0] == i) && ((ssize_t) pixels[3] == i)) || (((ssize_t) pixels[1] == i) && ((ssize_t) pixels[2] == i))) pattern[0]++; /* diagonal */ else pattern[2]++; } else if (foreground == 3) pattern[3]++; p+=GetPixelChannels(component_image); } } component_view=DestroyCacheView(component_view); object[i].metric[n]=ceil(MagickSQ1_2*pattern[1]+1.0*pattern[2]+ MagickSQ1_2*pattern[3]+MagickSQ2*pattern[0]-0.5); } for (i=0; i < (ssize_t) component_image->colors; i++) if (((object[i].metric[n] < min_threshold) || (object[i].metric[n] >= max_threshold)) && (i != background_id)) object[i].merge=MagickTrue; } artifact=GetImageArtifact(image,"connected-components:circularity-threshold"); if (artifact != (const char *) NULL) { /* Merge any object not within the min and max circularity threshold. */ (void) sscanf(artifact,"%lf%*[ -]%lf",&min_threshold,&max_threshold); metrics[++n]="circularity"; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic) shared(status) \ magick_number_threads(component_image,component_image,component_image->colors,1) #endif for (i=0; i < (ssize_t) component_image->colors; i++) { CacheView *component_view; RectangleInfo bounding_box; size_t pattern[4] = { 1, 0, 0, 0 }; ssize_t y; /* Compute perimeter of each object. */ if (status == MagickFalse) continue; component_view=AcquireAuthenticCacheView(component_image,exception); bounding_box=object[i].bounding_box; for (y=(-1); y < (ssize_t) bounding_box.height; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(component_view,bounding_box.x-1, bounding_box.y+y,bounding_box.width+2,2,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (x=(-1); x < (ssize_t) bounding_box.width; x++) { Quantum pixels[4]; register ssize_t v; size_t foreground; /* An Algorithm for Calculating Objects’ Shape Features in Binary Images, Lifeng He, Yuyan Chao. */ foreground=0; for (v=0; v < 2; v++) { register ssize_t u; for (u=0; u < 2; u++) { ssize_t offset; offset=v*(bounding_box.width+2)* GetPixelChannels(component_image)+u* GetPixelChannels(component_image); pixels[2*v+u]=GetPixelIndex(component_image,p+offset); if ((ssize_t) pixels[2*v+u] == i) foreground++; } } if (foreground == 1) pattern[1]++; else if (foreground == 2) { if ((((ssize_t) pixels[0] == i) && ((ssize_t) pixels[3] == i)) || (((ssize_t) pixels[1] == i) && ((ssize_t) pixels[2] == i))) pattern[0]++; /* diagonal */ else pattern[2]++; } else if (foreground == 3) pattern[3]++; p+=GetPixelChannels(component_image); } } component_view=DestroyCacheView(component_view); object[i].metric[n]=ceil(MagickSQ1_2*pattern[1]+1.0*pattern[2]+ MagickSQ1_2*pattern[3]+MagickSQ2*pattern[0]-0.5); object[i].metric[n]=4.0*MagickPI*object[i].area/(object[i].metric[n]* object[i].metric[n]); } for (i=0; i < (ssize_t) component_image->colors; i++) if (((object[i].metric[n] < min_threshold) || (object[i].metric[n] >= max_threshold)) && (i != background_id)) object[i].merge=MagickTrue; } artifact=GetImageArtifact(image,"connected-components:diameter-threshold"); if (artifact != (const char *) NULL) { /* Merge any object not within the min and max diameter threshold. */ (void) sscanf(artifact,"%lf%*[ -]%lf",&min_threshold,&max_threshold); metrics[++n]="diameter"; for (i=0; i < (ssize_t) component_image->colors; i++) { object[i].metric[n]=ceil(sqrt(4.0*object[i].area/MagickPI)-0.5); if (((object[i].metric[n] < min_threshold) || (object[i].metric[n] >= max_threshold)) && (i != background_id)) object[i].merge=MagickTrue; } } artifact=GetImageArtifact(image,"connected-components:major-axis-threshold"); if (artifact != (const char *) NULL) { /* Merge any object not within the min and max ellipse major threshold. */ (void) sscanf(artifact,"%lf%*[ -]%lf",&min_threshold,&max_threshold); metrics[++n]="major-axis"; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic) shared(status) \ magick_number_threads(component_image,component_image,component_image->colors,1) #endif for (i=0; i < (ssize_t) component_image->colors; i++) { CacheView *component_view; double M00 = 0.0, M01 = 0.0, M02 = 0.0, M10 = 0.0, M11 = 0.0, M20 = 0.0; PointInfo centroid = { 0.0, 0.0 }; RectangleInfo bounding_box; register const Quantum *magick_restrict p; register ssize_t x; ssize_t y; /* Compute ellipse major axis of each object. */ if (status == MagickFalse) continue; component_view=AcquireAuthenticCacheView(component_image,exception); bounding_box=object[i].bounding_box; for (y=0; y < (ssize_t) bounding_box.height; y++) { if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(component_view,bounding_box.x, bounding_box.y+y,bounding_box.width,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (x=0; x < (ssize_t) bounding_box.width; x++) { if ((ssize_t) GetPixelIndex(component_image,p) == i) { M00++; M10+=x; M01+=y; } p+=GetPixelChannels(component_image); } } centroid.x=M10*PerceptibleReciprocal(M00); centroid.y=M01*PerceptibleReciprocal(M00); for (y=0; y < (ssize_t) bounding_box.height; y++) { if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(component_view,bounding_box.x, bounding_box.y+y,bounding_box.width,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (x=0; x < (ssize_t) bounding_box.width; x++) { if ((ssize_t) GetPixelIndex(component_image,p) == i) { M11+=(x-centroid.x)*(y-centroid.y); M20+=(x-centroid.x)*(x-centroid.x); M02+=(y-centroid.y)*(y-centroid.y); } p+=GetPixelChannels(component_image); } } component_view=DestroyCacheView(component_view); object[i].metric[n]=sqrt((2.0*PerceptibleReciprocal(M00))*((M20+M02)+ sqrt(4.0*M11*M11+(M20-M02)*(M20-M02)))); } for (i=0; i < (ssize_t) component_image->colors; i++) if (((object[i].metric[n] < min_threshold) || (object[i].metric[n] >= max_threshold)) && (i != background_id)) object[i].merge=MagickTrue; } artifact=GetImageArtifact(image,"connected-components:minor-axis-threshold"); if (artifact != (const char *) NULL) { /* Merge any object not within the min and max ellipse minor threshold. */ (void) sscanf(artifact,"%lf%*[ -]%lf",&min_threshold,&max_threshold); metrics[++n]="minor-axis"; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic) shared(status) \ magick_number_threads(component_image,component_image,component_image->colors,1) #endif for (i=0; i < (ssize_t) component_image->colors; i++) { CacheView *component_view; double M00 = 0.0, M01 = 0.0, M02 = 0.0, M10 = 0.0, M11 = 0.0, M20 = 0.0; PointInfo centroid = { 0.0, 0.0 }; RectangleInfo bounding_box; register const Quantum *magick_restrict p; register ssize_t x; ssize_t y; /* Compute ellipse major axis of each object. */ if (status == MagickFalse) continue; component_view=AcquireAuthenticCacheView(component_image,exception); bounding_box=object[i].bounding_box; for (y=0; y < (ssize_t) bounding_box.height; y++) { if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(component_view,bounding_box.x, bounding_box.y+y,bounding_box.width,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (x=0; x < (ssize_t) bounding_box.width; x++) { if ((ssize_t) GetPixelIndex(component_image,p) == i) { M00++; M10+=x; M01+=y; } p+=GetPixelChannels(component_image); } } centroid.x=M10*PerceptibleReciprocal(M00); centroid.y=M01*PerceptibleReciprocal(M00); for (y=0; y < (ssize_t) bounding_box.height; y++) { if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(component_view,bounding_box.x, bounding_box.y+y,bounding_box.width,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (x=0; x < (ssize_t) bounding_box.width; x++) { if ((ssize_t) GetPixelIndex(component_image,p) == i) { M11+=(x-centroid.x)*(y-centroid.y); M20+=(x-centroid.x)*(x-centroid.x); M02+=(y-centroid.y)*(y-centroid.y); } p+=GetPixelChannels(component_image); } } component_view=DestroyCacheView(component_view); object[i].metric[n]=sqrt((2.0*PerceptibleReciprocal(M00))*((M20+M02)- sqrt(4.0*M11*M11+(M20-M02)*(M20-M02)))); } for (i=0; i < (ssize_t) component_image->colors; i++) if (((object[i].metric[n] < min_threshold) || (object[i].metric[n] >= max_threshold)) && (i != background_id)) object[i].merge=MagickTrue; } artifact=GetImageArtifact(image, "connected-components:eccentricity-threshold"); if (artifact != (const char *) NULL) { /* Merge any object not within the min and max eccentricity threshold. */ (void) sscanf(artifact,"%lf%*[ -]%lf",&min_threshold,&max_threshold); metrics[++n]="eccentricy"; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic) shared(status) \ magick_number_threads(component_image,component_image,component_image->colors,1) #endif for (i=0; i < (ssize_t) component_image->colors; i++) { CacheView *component_view; double M00 = 0.0, M01 = 0.0, M02 = 0.0, M10 = 0.0, M11 = 0.0, M20 = 0.0; PointInfo centroid = { 0.0, 0.0 }, ellipse_axis = { 0.0, 0.0 }; RectangleInfo bounding_box; register const Quantum *magick_restrict p; register ssize_t x; ssize_t y; /* Compute eccentricity of each object. */ if (status == MagickFalse) continue; component_view=AcquireAuthenticCacheView(component_image,exception); bounding_box=object[i].bounding_box; for (y=0; y < (ssize_t) bounding_box.height; y++) { if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(component_view,bounding_box.x, bounding_box.y+y,bounding_box.width,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (x=0; x < (ssize_t) bounding_box.width; x++) { if ((ssize_t) GetPixelIndex(component_image,p) == i) { M00++; M10+=x; M01+=y; } p+=GetPixelChannels(component_image); } } centroid.x=M10*PerceptibleReciprocal(M00); centroid.y=M01*PerceptibleReciprocal(M00); for (y=0; y < (ssize_t) bounding_box.height; y++) { if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(component_view,bounding_box.x, bounding_box.y+y,bounding_box.width,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (x=0; x < (ssize_t) bounding_box.width; x++) { if ((ssize_t) GetPixelIndex(component_image,p) == i) { M11+=(x-centroid.x)*(y-centroid.y); M20+=(x-centroid.x)*(x-centroid.x); M02+=(y-centroid.y)*(y-centroid.y); } p+=GetPixelChannels(component_image); } } component_view=DestroyCacheView(component_view); ellipse_axis.x=sqrt((2.0*PerceptibleReciprocal(M00))*((M20+M02)+ sqrt(4.0*M11*M11+(M20-M02)*(M20-M02)))); ellipse_axis.y=sqrt((2.0*PerceptibleReciprocal(M00))*((M20+M02)- sqrt(4.0*M11*M11+(M20-M02)*(M20-M02)))); object[i].metric[n]=sqrt(1.0-(ellipse_axis.y*ellipse_axis.y* PerceptibleReciprocal(ellipse_axis.x*ellipse_axis.x))); } for (i=0; i < (ssize_t) component_image->colors; i++) if (((object[i].metric[n] < min_threshold) || (object[i].metric[n] >= max_threshold)) && (i != background_id)) object[i].merge=MagickTrue; } artifact=GetImageArtifact(image,"connected-components:angle-threshold"); if (artifact != (const char *) NULL) { /* Merge any object not within the min and max ellipse angle threshold. */ (void) sscanf(artifact,"%lf%*[ -]%lf",&min_threshold,&max_threshold); metrics[++n]="angle"; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic) shared(status) \ magick_number_threads(component_image,component_image,component_image->colors,1) #endif for (i=0; i < (ssize_t) component_image->colors; i++) { CacheView *component_view; double M00 = 0.0, M01 = 0.0, M02 = 0.0, M10 = 0.0, M11 = 0.0, M20 = 0.0; PointInfo centroid = { 0.0, 0.0 }; RectangleInfo bounding_box; register const Quantum *magick_restrict p; register ssize_t x; ssize_t y; /* Compute ellipse angle of each object. */ if (status == MagickFalse) continue; component_view=AcquireAuthenticCacheView(component_image,exception); bounding_box=object[i].bounding_box; for (y=0; y < (ssize_t) bounding_box.height; y++) { if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(component_view,bounding_box.x, bounding_box.y+y,bounding_box.width,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (x=0; x < (ssize_t) bounding_box.width; x++) { if ((ssize_t) GetPixelIndex(component_image,p) == i) { M00++; M10+=x; M01+=y; } p+=GetPixelChannels(component_image); } } centroid.x=M10*PerceptibleReciprocal(M00); centroid.y=M01*PerceptibleReciprocal(M00); for (y=0; y < (ssize_t) bounding_box.height; y++) { if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(component_view,bounding_box.x, bounding_box.y+y,bounding_box.width,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (x=0; x < (ssize_t) bounding_box.width; x++) { if ((ssize_t) GetPixelIndex(component_image,p) == i) { M11+=(x-centroid.x)*(y-centroid.y); M20+=(x-centroid.x)*(x-centroid.x); M02+=(y-centroid.y)*(y-centroid.y); } p+=GetPixelChannels(component_image); } } component_view=DestroyCacheView(component_view); object[i].metric[n]=RadiansToDegrees(1.0/2.0*atan(2.0*M11* PerceptibleReciprocal(M20-M02))); if (fabs(M11) < 0.0) { if ((fabs(M20-M02) >= 0.0) && ((M20-M02) < 0.0)) object[i].metric[n]+=90.0; } else if (M11 < 0.0) { if (fabs(M20-M02) >= 0.0) { if ((M20-M02) < 0.0) object[i].metric[n]+=90.0; else object[i].metric[n]+=180.0; } } else if ((fabs(M20-M02) >= 0.0) && ((M20-M02) < 0.0)) object[i].metric[n]+=90.0; } for (i=0; i < (ssize_t) component_image->colors; i++) if (((object[i].metric[n] < min_threshold) || (object[i].metric[n] >= max_threshold)) && (i != background_id)) object[i].merge=MagickTrue; } /* Merge any object not within the min and max area threshold. */ component_view=AcquireAuthenticCacheView(component_image,exception); object_view=AcquireVirtualCacheView(component_image,exception); for (i=0; i < (ssize_t) component_image->colors; i++) { register ssize_t j; size_t id; if (status == MagickFalse) continue; if ((object[i].merge == MagickFalse) || (i == background_id)) continue; /* keep object */ /* Merge this object. */ for (j=0; j < (ssize_t) component_image->colors; j++) object[j].census=0; bounding_box=object[i].bounding_box; for (y=0; y < (ssize_t) bounding_box.height; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(component_view,bounding_box.x, bounding_box.y+y,bounding_box.width,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) bounding_box.width; x++) { register ssize_t n; if (status == MagickFalse) continue; j=(ssize_t) GetPixelIndex(component_image,p); if (j == i) for (n=0; n < (ssize_t) (connectivity > 4 ? 4 : 2); n++) { register const Quantum *p; /* Compute area of adjacent objects. */ if (status == MagickFalse) continue; dx=connectivity > 4 ? connect8[n][1] : connect4[n][1]; dy=connectivity > 4 ? connect8[n][0] : connect4[n][0]; p=GetCacheViewVirtualPixels(object_view,bounding_box.x+x+dx, bounding_box.y+y+dy,1,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } j=(ssize_t) GetPixelIndex(component_image,p); if (j != i) object[j].census++; } p+=GetPixelChannels(component_image); } } /* Merge with object of greatest adjacent area. */ id=0; for (j=1; j < (ssize_t) component_image->colors; j++) if (object[j].census > object[id].census) id=(size_t) j; object[i].area=0.0; for (y=0; y < (ssize_t) bounding_box.height; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(component_view,bounding_box.x, bounding_box.y+y,bounding_box.width,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) bounding_box.width; x++) { if ((ssize_t) GetPixelIndex(component_image,q) == i) SetPixelIndex(component_image,(Quantum) id,q); q+=GetPixelChannels(component_image); } if (SyncCacheViewAuthenticPixels(component_view,exception) == MagickFalse) status=MagickFalse; } } object_view=DestroyCacheView(object_view); component_view=DestroyCacheView(component_view); artifact=GetImageArtifact(image,"connected-components:mean-color"); if (IsStringTrue(artifact) != MagickFalse) { /* Replace object with mean color. */ for (i=0; i < (ssize_t) component_image->colors; i++) component_image->colormap[i]=object[i].color; } (void) SyncImage(component_image,exception); artifact=GetImageArtifact(image,"connected-components:verbose"); if ((IsStringTrue(artifact) != MagickFalse) || (objects != (CCObjectInfo **) NULL)) { /* Report statistics on each unique object. */ for (i=0; i < (ssize_t) component_image->colors; i++) { object[i].bounding_box.width=0; object[i].bounding_box.height=0; object[i].bounding_box.x=(ssize_t) component_image->columns; object[i].bounding_box.y=(ssize_t) component_image->rows; object[i].centroid.x=0; object[i].centroid.y=0; object[i].census=object[i].area == 0.0 ? 0.0 : 1.0; object[i].area=0; } component_view=AcquireVirtualCacheView(component_image,exception); for (y=0; y < (ssize_t) component_image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(component_view,0,y,component_image->columns, 1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) component_image->columns; x++) { size_t id; id=(size_t) GetPixelIndex(component_image,p); if (x < object[id].bounding_box.x) object[id].bounding_box.x=x; if (x > (ssize_t) object[id].bounding_box.width) object[id].bounding_box.width=(size_t) x; if (y < object[id].bounding_box.y) object[id].bounding_box.y=y; if (y > (ssize_t) object[id].bounding_box.height) object[id].bounding_box.height=(size_t) y; object[id].centroid.x+=x; object[id].centroid.y+=y; object[id].area++; p+=GetPixelChannels(component_image); } } for (i=0; i < (ssize_t) component_image->colors; i++) { object[i].bounding_box.width-=(object[i].bounding_box.x-1); object[i].bounding_box.height-=(object[i].bounding_box.y-1); object[i].centroid.x=object[i].centroid.x/object[i].area; object[i].centroid.y=object[i].centroid.y/object[i].area; } component_view=DestroyCacheView(component_view); qsort((void *) object,component_image->colors,sizeof(*object), CCObjectInfoCompare); if (objects == (CCObjectInfo **) NULL) { register ssize_t j; artifact=GetImageArtifact(image, "connected-components:exclude-header"); if (IsStringTrue(artifact) == MagickFalse) { (void) fprintf(thread_stdout,"Objects ("); artifact=GetImageArtifact(image, "connected-components:exclude-ids"); if (IsStringTrue(artifact) == MagickFalse) (void) fprintf(thread_stdout,"id: "); (void) fprintf(thread_stdout,"bounding-box centroid area mean-color"); for (j=0; j <= n; j++) (void) fprintf(thread_stdout," %s",metrics[j]); (void) fprintf(thread_stdout,"):\n"); } for (i=0; i < (ssize_t) component_image->colors; i++) if (object[i].census > 0.0) { char mean_color[MagickPathExtent]; GetColorTuple(&object[i].color,MagickFalse,mean_color); (void) fprintf(thread_stdout," "); artifact=GetImageArtifact(image, "connected-components:exclude-ids"); if (IsStringTrue(artifact) == MagickFalse) (void) fprintf(thread_stdout,"%.20g: ",(double) object[i].id); (void) fprintf(thread_stdout, "%.20gx%.20g%+.20g%+.20g %.1f,%.1f %.*g %s",(double) object[i].bounding_box.width,(double) object[i].bounding_box.height,(double) object[i].bounding_box.x,(double) object[i].bounding_box.y, object[i].centroid.x,object[i].centroid.y, GetMagickPrecision(),(double) object[i].area,mean_color); for (j=0; j <= n; j++) (void) fprintf(thread_stdout," %.*g",GetMagickPrecision(), object[i].metric[j]); (void) fprintf(thread_stdout,"\n"); } } } if (objects == (CCObjectInfo **) NULL) object=(CCObjectInfo *) RelinquishMagickMemory(object); else *objects=object; return(component_image); }
kernel_sqrexp.c
/*! @copyright (c) 2017 King Abdullah University of Science and * Technology (KAUST). All rights reserved. * * STARS-H is a software package, provided by King Abdullah * University of Science and Technology (KAUST) * * @generate NDIM -> n 1 2 3 4 * Generate different functions for different dimensions. This hack improves * performance in certain cases. Value 'n' stands for general case, whereas all * other values correspond to static values of dimensionality. * During code generation step, each appearance of @NDIM (including this one) * will be replace by proposed values. If you want to use this file outside * STARS-H, simply do substitutions yourself. * * @file src/applications/spatial/kernel_sqrexp.c * @version 0.1.1 * @author Aleksandr Mikhalev * @date 2018-11-06 */ #include "common.h" #include "starsh.h" #include "starsh-spatial.h" // If dimensionality is static #if (@NDIM != n) //! Replace variable ndim with static integer value #define ndim @NDIM #endif void starsh_ssdata_block_sqrexp_kernel_@NDIMd(int nrows, int ncols, STARSH_int *irow, STARSH_int *icol, void *row_data, void *col_data, void *result, int ld) //! Square exponential kernel for @NDIM-dimensional spatial statistics problem /*! Fills matrix \f$ A \f$ with values * \f[ * A_{ij} = \sigma^2 e^{-\frac{1}{2} \left( \frac{r_{ij}}{\beta} * \right)^2} + \mu \delta(r_{ij}), * \f] * where \f$ \delta \f$ is the delta function * \f[ * \delta(x) = \left\{ \begin{array}{ll} 0, & x \ne 0\\ 1, & x = 0 * \end{array} \right., * \f] * \f$ r_{ij} \f$ is a distance between \f$i\f$-th and \f$j\f$-th spatial * points and variance \f$ \sigma \f$, correlation length \f$ \beta \f$ and * noise \f$ \mu \f$ come from \p row_data (\ref STARSH_ssdata object). No * memory is allocated in this function! * * @param[in] nrows: Number of rows of \f$ A \f$. * @param[in] ncols: Number of columns of \f$ A \f$. * @param[in] irow: Array of row indexes. * @param[in] icol: Array of column indexes. * @param[in] row_data: Pointer to physical data (\ref STARSH_ssdata object). * @param[in] col_data: Pointer to physical data (\ref STARSH_ssdata object). * @param[out] result: Pointer to memory of \f$ A \f$. * @param[in] ld: Leading dimension of `result`. * @sa starsh_ssdata_block_sqrexp_kernel_1d(), * starsh_ssdata_block_sqrexp_kernel_2d(), * starsh_ssdata_block_sqrexp_kernel_3d(), * starsh_ssdata_block_sqrexp_kernel_4d(), * starsh_ssdata_block_sqrexp_kernel_nd(). * @ingroup app-spatial-kernels * */ { int i, j, k; STARSH_ssdata *data1 = row_data; STARSH_ssdata *data2 = col_data; double tmp, dist; // Read parameters // If dimensionality is not static #if (@NDIM == n) int ndim = data1->particles.ndim; #endif double beta = -2*data1->beta*data1->beta; double noise = data1->noise; double sigma = data1->sigma; // Get coordinates STARSH_int count1 = data1->particles.count; STARSH_int count2 = data2->particles.count; double *x1[ndim], *x2[ndim]; x1[0] = data1->particles.point; x2[0] = data2->particles.point; //#pragma omp simd for(i = 1; i < ndim; i++) { x1[i] = x1[0]+i*count1; x2[i] = x2[0]+i*count2; } double *x1_cur, *x2_cur; double *buffer = result; // Fill column-major matrix //#pragma omp simd for(j = 0; j < ncols; j++) { for(i = 0; i < nrows; i++) { dist = 0.0; for(k = 0; k < ndim; k++) { tmp = x1[k][irow[i]]-x2[k][icol[j]]; dist += tmp*tmp; } dist = dist/beta; if(dist == 0) buffer[j*(size_t)ld+i] = sigma+noise; else buffer[j*(size_t)ld+i] = sigma*exp(dist); } } } void starsh_ssdata_block_sqrexp_kernel_@NDIMd_simd(int nrows, int ncols, STARSH_int *irow, STARSH_int *icol, void *row_data, void *col_data, void *result, int ld) //! Square exponential kernel for @NDIM-dimensional spatial statistics problem /*! Fills matrix \f$ A \f$ with values * \f[ * A_{ij} = \sigma^2 e^{-\frac{1}{2} \left( \frac{r_{ij}}{\beta} * \right)^2} + \mu \delta(r_{ij}), * \f] * where \f$ \delta \f$ is the delta function * \f[ * \delta(x) = \left\{ \begin{array}{ll} 0, & x \ne 0\\ 1, & x = 0 * \end{array} \right., * \f] * \f$ r_{ij} \f$ is a distance between \f$i\f$-th and \f$j\f$-th spatial * points and variance \f$ \sigma \f$, correlation length \f$ \beta \f$ and * noise \f$ \mu \f$ come from \p row_data (\ref STARSH_ssdata object). No * memory is allocated in this function! * * Uses SIMD instructions. * * @param[in] nrows: Number of rows of \f$ A \f$. * @param[in] ncols: Number of columns of \f$ A \f$. * @param[in] irow: Array of row indexes. * @param[in] icol: Array of column indexes. * @param[in] row_data: Pointer to physical data (\ref STARSH_ssdata object). * @param[in] col_data: Pointer to physical data (\ref STARSH_ssdata object). * @param[out] result: Pointer to memory of \f$ A \f$. * @param[in] ld: Leading dimension of `result`. * @sa starsh_ssdata_block_sqrexp_kernel_1d(), * starsh_ssdata_block_sqrexp_kernel_2d(), * starsh_ssdata_block_sqrexp_kernel_3d(), * starsh_ssdata_block_sqrexp_kernel_4d(), * starsh_ssdata_block_sqrexp_kernel_nd(). * @ingroup app-spatial-kernels * */ { int i, j, k; STARSH_ssdata *data1 = row_data; STARSH_ssdata *data2 = col_data; double tmp, dist; // Read parameters // If dimensionality is not static #if (@NDIM == n) int ndim = data1->particles.ndim; #endif double beta = -2*data1->beta*data1->beta; double noise = data1->noise; double sigma = data1->sigma; // Get coordinates STARSH_int count1 = data1->particles.count; STARSH_int count2 = data2->particles.count; double *x1[ndim], *x2[ndim]; x1[0] = data1->particles.point; x2[0] = data2->particles.point; #pragma omp simd for(i = 1; i < ndim; i++) { x1[i] = x1[0]+i*count1; x2[i] = x2[0]+i*count2; } double *x1_cur, *x2_cur; double *buffer = result; // Fill column-major matrix #pragma omp simd for(j = 0; j < ncols; j++) { for(i = 0; i < nrows; i++) { dist = 0.0; for(k = 0; k < ndim; k++) { tmp = x1[k][irow[i]]-x2[k][icol[j]]; dist += tmp*tmp; } dist = dist/beta; if(dist == 0) buffer[j*(size_t)ld+i] = sigma+noise; else buffer[j*(size_t)ld+i] = sigma*exp(dist); } } }
gemm.c
/** * gemm.c: This file was adapted from PolyBench/GPU 1.0 test suite * to run on GPU with OpenMP 4.0 pragmas and OpenCL driver. * * http://www.cse.ohio-state.edu/~pouchet/software/polybench/GPU * * Contacts: Marcio M Pereira <mpereira@ic.unicamp.br> * Rafael Cardoso F Sousa <rafael.cardoso@students.ic.unicamp.br> * Luís Felipe Mattos <ra107822@students.ic.unicamp.br> */ #include <unistd.h> #include <stdio.h> #include <time.h> #include <sys/time.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <omp.h> #include "../../common/polybenchUtilFuncts.h" #define GPU 1 //define the error threshold for the results "not matching" #define PERCENT_DIFF_ERROR_THRESHOLD 0.05 /* Problem size */ #define NI 1024 #define NJ 1024 #define NK 1024 /* Declared constant values for ALPHA and BETA (same as values in PolyBench 2.0) */ #define ALPHA 32412.0f #define BETA 2123.0f /* Can switch DATA_TYPE between float and double */ typedef float DATA_TYPE; void gemm(DATA_TYPE *A, DATA_TYPE *B, DATA_TYPE *C) { int i,j,k; for (i = 0; i < NI; i++) { for (j = 0; j < NJ; j++) { C[i*NJ + j] *= BETA; for (k = 0; k < NK; ++k) { C[i*NJ + j] += ALPHA * A[i*NK + k] * B[k*NJ + j]; } } } } void gemm_OMP(DATA_TYPE *A, DATA_TYPE *B, DATA_TYPE *C) { int i,j,k; #pragma omp target device(GPU) map(to: A[:NI*NK], B[:NK*NJ]) map(tofrom: C[:NI*NJ]) #pragma omp parallel for collapse(2) for (i = 0; i < NI; i++) { for (j = 0; j < NJ; j++) { C[i*NJ + j] *= BETA; for (k = 0; k < NK; ++k) { C[i*NJ + j] += ALPHA * A[i*NK + k] * B[k*NJ + j]; } } } } void init(DATA_TYPE *A, DATA_TYPE *B, DATA_TYPE *C, DATA_TYPE *C_OMP) { int i, j; for (i = 0; i < NI; i++) { for (j = 0; j < NK; j++) { A[i*NK + j] = ((DATA_TYPE) i*j) / NI; } } for (i = 0; i < NK; i++) { for (j = 0; j < NJ; j++) { B[i*NJ + j] = ((DATA_TYPE) i*j + 1) / NJ; } } for (i = 0; i < NI; i++) { for (j = 0; j < NJ; j++) { C[i*NJ + j] = ((DATA_TYPE) i*j + 2) / NJ; C_OMP[i*NJ + j] = ((DATA_TYPE) i*j + 2) / NJ; } } } void compareResults(DATA_TYPE* C, DATA_TYPE* C_outputFromGpu) { int i, j, fail; fail = 0; // Compare C1 and C2 for (i=0; i < NI; i++) { for (j=0; j < NJ; j++) { if (percentDiff(C[i*NJ + j], C_outputFromGpu[i*NJ + j]) > PERCENT_DIFF_ERROR_THRESHOLD) { fail++; } } } // Print results printf(">>\n Non-Matching CPU-GPU Outputs Beyond Error Threshold of %4.2f%s: %d\n", PERCENT_DIFF_ERROR_THRESHOLD, "%", fail); } int main(int argc, char *argv[]) { double t_start, t_end; DATA_TYPE* A; DATA_TYPE* B; DATA_TYPE* C; DATA_TYPE* C_outputFromGpu; A = (DATA_TYPE*)malloc(NI*NK*sizeof(DATA_TYPE)); B = (DATA_TYPE*)malloc(NK*NJ*sizeof(DATA_TYPE)); C = (DATA_TYPE*)malloc(NI*NJ*sizeof(DATA_TYPE)); C_outputFromGpu = (DATA_TYPE*)malloc(NI*NJ*sizeof(DATA_TYPE)); fprintf(stdout, "<< Matrix-multiply C=alpha.A.B+beta.C >>\n"); fprintf(stdout, "<< Size of Matrices: 1024 * 1024 >>\n"); fprintf(stdout, "<< Computation: >>\n\n"); fprintf(stdout, " for (i = 0; i < 1024; i++) \n"); fprintf(stdout, " for (j = 0; j < 1024; j++) {\n"); fprintf(stdout, " C[i][j] *= BETA; \n"); fprintf(stdout, " for (k = 0; k < 1024; ++k) \n"); fprintf(stdout, " C[i][j] += ALPHA * A[i][k] * B[k][j];\n"); fprintf(stdout, " }\n\n"); fprintf(stdout, "<< Initializing Matrices A, B & C ... "); init(A, B, C, C_outputFromGpu); fprintf(stdout, ">>\n<< Start computation of matrix C on GPU... "); t_start = rtclock(); gemm_OMP(A, B, C_outputFromGpu); t_end = rtclock(); fprintf(stdout, ">>\n GPU Runtime: %0.6lfs\n", t_end - t_start); fprintf(stdout, "\n<< Start computation of matrix C on CPU... "); t_start = rtclock(); gemm(A, B, C); t_end = rtclock(); fprintf(stdout, ">>\n CPU Runtime: %0.6lfs\n", t_end - t_start); fprintf(stdout, "<< Comparing Results ... "); compareResults(C, C_outputFromGpu); free(A); free(B); free(C); free(C_outputFromGpu); return 0; }
Parser.h
//===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines the Parser interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_PARSE_PARSER_H #define LLVM_CLANG_PARSE_PARSER_H #include "clang/AST/OpenMPClause.h" #include "clang/AST/Availability.h" #include "clang/Basic/BitmaskEnum.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/OperatorPrecedence.h" #include "clang/Basic/Specifiers.h" #include "clang/Lex/CodeCompletionHandler.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/Sema.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/SaveAndRestore.h" #include <memory> #include <stack> namespace clang { class PragmaHandler; class Scope; class BalancedDelimiterTracker; class CorrectionCandidateCallback; class DeclGroupRef; class DiagnosticBuilder; struct LoopHint; class Parser; class ParsingDeclRAIIObject; class ParsingDeclSpec; class ParsingDeclarator; class ParsingFieldDeclarator; class ColonProtectionRAIIObject; class InMessageExpressionRAIIObject; class PoisonSEHIdentifiersRAIIObject; class OMPClause; class ObjCTypeParamList; class ObjCTypeParameter; /// Parser - This implements a parser for the C family of languages. After /// parsing units of the grammar, productions are invoked to handle whatever has /// been read. /// class Parser : public CodeCompletionHandler { friend class ColonProtectionRAIIObject; friend class InMessageExpressionRAIIObject; friend class PoisonSEHIdentifiersRAIIObject; friend class ObjCDeclContextSwitch; friend class ParenBraceBracketBalancer; friend class BalancedDelimiterTracker; Preprocessor &PP; /// Tok - The current token we are peeking ahead. All parsing methods assume /// that this is valid. Token Tok; // PrevTokLocation - The location of the token we previously // consumed. This token is used for diagnostics where we expected to // see a token following another token (e.g., the ';' at the end of // a statement). SourceLocation PrevTokLocation; /// Tracks an expected type for the current token when parsing an expression. /// Used by code completion for ranking. PreferredTypeBuilder PreferredType; unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0; unsigned short MisplacedModuleBeginCount = 0; /// Actions - These are the callbacks we invoke as we parse various constructs /// in the file. Sema &Actions; DiagnosticsEngine &Diags; /// ScopeCache - Cache scopes to reduce malloc traffic. enum { ScopeCacheSize = 16 }; unsigned NumCachedScopes; Scope *ScopeCache[ScopeCacheSize]; /// Identifiers used for SEH handling in Borland. These are only /// allowed in particular circumstances // __except block IdentifierInfo *Ident__exception_code, *Ident___exception_code, *Ident_GetExceptionCode; // __except filter expression IdentifierInfo *Ident__exception_info, *Ident___exception_info, *Ident_GetExceptionInfo; // __finally IdentifierInfo *Ident__abnormal_termination, *Ident___abnormal_termination, *Ident_AbnormalTermination; /// Contextual keywords for Microsoft extensions. IdentifierInfo *Ident__except; mutable IdentifierInfo *Ident_sealed; /// Ident_super - IdentifierInfo for "super", to support fast /// comparison. IdentifierInfo *Ident_super; /// Ident_vector, Ident_bool - cached IdentifierInfos for "vector" and /// "bool" fast comparison. Only present if AltiVec or ZVector are enabled. IdentifierInfo *Ident_vector; IdentifierInfo *Ident_bool; /// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison. /// Only present if AltiVec enabled. IdentifierInfo *Ident_pixel; /// Objective-C contextual keywords. IdentifierInfo *Ident_instancetype; /// Identifier for "introduced". IdentifierInfo *Ident_introduced; /// Identifier for "deprecated". IdentifierInfo *Ident_deprecated; /// Identifier for "obsoleted". IdentifierInfo *Ident_obsoleted; /// Identifier for "unavailable". IdentifierInfo *Ident_unavailable; /// Identifier for "message". IdentifierInfo *Ident_message; /// Identifier for "strict". IdentifierInfo *Ident_strict; /// Identifier for "replacement". IdentifierInfo *Ident_replacement; /// Identifiers used by the 'external_source_symbol' attribute. IdentifierInfo *Ident_language, *Ident_defined_in, *Ident_generated_declaration; /// C++11 contextual keywords. mutable IdentifierInfo *Ident_final; mutable IdentifierInfo *Ident_GNU_final; mutable IdentifierInfo *Ident_override; // C++2a contextual keywords. mutable IdentifierInfo *Ident_import; mutable IdentifierInfo *Ident_module; // C++ type trait keywords that can be reverted to identifiers and still be // used as type traits. llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits; std::unique_ptr<PragmaHandler> AlignHandler; std::unique_ptr<PragmaHandler> GCCVisibilityHandler; std::unique_ptr<PragmaHandler> OptionsHandler; std::unique_ptr<PragmaHandler> PackHandler; std::unique_ptr<PragmaHandler> MSStructHandler; std::unique_ptr<PragmaHandler> UnusedHandler; std::unique_ptr<PragmaHandler> WeakHandler; std::unique_ptr<PragmaHandler> RedefineExtnameHandler; std::unique_ptr<PragmaHandler> FPContractHandler; std::unique_ptr<PragmaHandler> OpenCLExtensionHandler; std::unique_ptr<PragmaHandler> OpenMPHandler; std::unique_ptr<PragmaHandler> PCSectionHandler; std::unique_ptr<PragmaHandler> MSCommentHandler; std::unique_ptr<PragmaHandler> MSDetectMismatchHandler; std::unique_ptr<PragmaHandler> MSPointersToMembers; std::unique_ptr<PragmaHandler> MSVtorDisp; std::unique_ptr<PragmaHandler> MSInitSeg; std::unique_ptr<PragmaHandler> MSDataSeg; std::unique_ptr<PragmaHandler> MSBSSSeg; std::unique_ptr<PragmaHandler> MSConstSeg; std::unique_ptr<PragmaHandler> MSCodeSeg; std::unique_ptr<PragmaHandler> MSSection; std::unique_ptr<PragmaHandler> MSRuntimeChecks; std::unique_ptr<PragmaHandler> MSIntrinsic; std::unique_ptr<PragmaHandler> MSOptimize; std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler; std::unique_ptr<PragmaHandler> OptimizeHandler; std::unique_ptr<PragmaHandler> LoopHintHandler; std::unique_ptr<PragmaHandler> UnrollHintHandler; std::unique_ptr<PragmaHandler> NoUnrollHintHandler; std::unique_ptr<PragmaHandler> UnrollAndJamHintHandler; std::unique_ptr<PragmaHandler> NoUnrollAndJamHintHandler; std::unique_ptr<PragmaHandler> FPHandler; std::unique_ptr<PragmaHandler> STDCFENVHandler; std::unique_ptr<PragmaHandler> STDCCXLIMITHandler; std::unique_ptr<PragmaHandler> STDCUnknownHandler; std::unique_ptr<PragmaHandler> AttributePragmaHandler; std::unique_ptr<CommentHandler> CommentSemaHandler; /// Whether the '>' token acts as an operator or not. This will be /// true except when we are parsing an expression within a C++ /// template argument list, where the '>' closes the template /// argument list. bool GreaterThanIsOperator; /// ColonIsSacred - When this is false, we aggressively try to recover from /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not /// safe in case statements and a few other things. This is managed by the /// ColonProtectionRAIIObject RAII object. bool ColonIsSacred; /// When true, we are directly inside an Objective-C message /// send expression. /// /// This is managed by the \c InMessageExpressionRAIIObject class, and /// should not be set directly. bool InMessageExpression; /// Gets set to true after calling ProduceSignatureHelp, it is for a /// workaround to make sure ProduceSignatureHelp is only called at the deepest /// function call. bool CalledSignatureHelp = false; /// The "depth" of the template parameters currently being parsed. unsigned TemplateParameterDepth; /// RAII class that manages the template parameter depth. class TemplateParameterDepthRAII { unsigned &Depth; unsigned AddedLevels; public: explicit TemplateParameterDepthRAII(unsigned &Depth) : Depth(Depth), AddedLevels(0) {} ~TemplateParameterDepthRAII() { Depth -= AddedLevels; } void operator++() { ++Depth; ++AddedLevels; } void addDepth(unsigned D) { Depth += D; AddedLevels += D; } void setAddedDepth(unsigned D) { Depth = Depth - AddedLevels + D; AddedLevels = D; } unsigned getDepth() const { return Depth; } unsigned getOriginalDepth() const { return Depth - AddedLevels; } }; /// Factory object for creating ParsedAttr objects. AttributeFactory AttrFactory; /// Gathers and cleans up TemplateIdAnnotations when parsing of a /// top-level declaration is finished. SmallVector<TemplateIdAnnotation *, 16> TemplateIds; /// Identifiers which have been declared within a tentative parse. SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers; /// Tracker for '<' tokens that might have been intended to be treated as an /// angle bracket instead of a less-than comparison. /// /// This happens when the user intends to form a template-id, but typoes the /// template-name or forgets a 'template' keyword for a dependent template /// name. /// /// We track these locations from the point where we see a '<' with a /// name-like expression on its left until we see a '>' or '>>' that might /// match it. struct AngleBracketTracker { /// Flags used to rank candidate template names when there is more than one /// '<' in a scope. enum Priority : unsigned short { /// A non-dependent name that is a potential typo for a template name. PotentialTypo = 0x0, /// A dependent name that might instantiate to a template-name. DependentName = 0x2, /// A space appears before the '<' token. SpaceBeforeLess = 0x0, /// No space before the '<' token NoSpaceBeforeLess = 0x1, LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue*/ DependentName) }; struct Loc { Expr *TemplateName; SourceLocation LessLoc; AngleBracketTracker::Priority Priority; unsigned short ParenCount, BracketCount, BraceCount; bool isActive(Parser &P) const { return P.ParenCount == ParenCount && P.BracketCount == BracketCount && P.BraceCount == BraceCount; } bool isActiveOrNested(Parser &P) const { return isActive(P) || P.ParenCount > ParenCount || P.BracketCount > BracketCount || P.BraceCount > BraceCount; } }; SmallVector<Loc, 8> Locs; /// Add an expression that might have been intended to be a template name. /// In the case of ambiguity, we arbitrarily select the innermost such /// expression, for example in 'foo < bar < baz', 'bar' is the current /// candidate. No attempt is made to track that 'foo' is also a candidate /// for the case where we see a second suspicious '>' token. void add(Parser &P, Expr *TemplateName, SourceLocation LessLoc, Priority Prio) { if (!Locs.empty() && Locs.back().isActive(P)) { if (Locs.back().Priority <= Prio) { Locs.back().TemplateName = TemplateName; Locs.back().LessLoc = LessLoc; Locs.back().Priority = Prio; } } else { Locs.push_back({TemplateName, LessLoc, Prio, P.ParenCount, P.BracketCount, P.BraceCount}); } } /// Mark the current potential missing template location as having been /// handled (this happens if we pass a "corresponding" '>' or '>>' token /// or leave a bracket scope). void clear(Parser &P) { while (!Locs.empty() && Locs.back().isActiveOrNested(P)) Locs.pop_back(); } /// Get the current enclosing expression that might hve been intended to be /// a template name. Loc *getCurrent(Parser &P) { if (!Locs.empty() && Locs.back().isActive(P)) return &Locs.back(); return nullptr; } }; AngleBracketTracker AngleBrackets; IdentifierInfo *getSEHExceptKeyword(); /// True if we are within an Objective-C container while parsing C-like decls. /// /// This is necessary because Sema thinks we have left the container /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will /// be NULL. bool ParsingInObjCContainer; /// Whether to skip parsing of function bodies. /// /// This option can be used, for example, to speed up searches for /// declarations/definitions when indexing. bool SkipFunctionBodies; /// The location of the expression statement that is being parsed right now. /// Used to determine if an expression that is being parsed is a statement or /// just a regular sub-expression. SourceLocation ExprStatementTokLoc; /// Flags describing a context in which we're parsing a statement. enum class ParsedStmtContext { /// This context permits declarations in language modes where declarations /// are not statements. AllowDeclarationsInC = 0x1, /// This context permits standalone OpenMP directives. AllowStandaloneOpenMPDirectives = 0x2, /// This context is at the top level of a GNU statement expression. InStmtExpr = 0x4, /// The context of a regular substatement. SubStmt = 0, /// The context of a compound-statement. Compound = AllowDeclarationsInC | AllowStandaloneOpenMPDirectives, LLVM_MARK_AS_BITMASK_ENUM(InStmtExpr) }; /// Act on an expression statement that might be the last statement in a /// GNU statement expression. Checks whether we are actually at the end of /// a statement expression and builds a suitable expression statement. StmtResult handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx); public: Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies); ~Parser() override; const LangOptions &getLangOpts() const { return PP.getLangOpts(); } const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); } Preprocessor &getPreprocessor() const { return PP; } Sema &getActions() const { return Actions; } AttributeFactory &getAttrFactory() { return AttrFactory; } const Token &getCurToken() const { return Tok; } Scope *getCurScope() const { return Actions.getCurScope(); } void incrementMSManglingNumber() const { return Actions.incrementMSManglingNumber(); } Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); } // Type forwarding. All of these are statically 'void*', but they may all be // different actual classes based on the actions in place. typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; typedef OpaquePtr<TemplateName> TemplateTy; typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists; typedef Sema::FullExprArg FullExprArg; // Parsing methods. /// Initialize - Warm up the parser. /// void Initialize(); /// Parse the first top-level declaration in a translation unit. bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result); /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if /// the EOF was encountered. bool ParseTopLevelDecl(DeclGroupPtrTy &Result, bool IsFirstDecl = false); bool ParseTopLevelDecl() { DeclGroupPtrTy Result; return ParseTopLevelDecl(Result); } /// ConsumeToken - Consume the current 'peek token' and lex the next one. /// This does not work with special tokens: string literals, code completion, /// annotation tokens and balanced tokens must be handled using the specific /// consume methods. /// Returns the location of the consumed token. SourceLocation ConsumeToken() { assert(!isTokenSpecial() && "Should consume special tokens with Consume*Token"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } bool TryConsumeToken(tok::TokenKind Expected) { if (Tok.isNot(Expected)) return false; assert(!isTokenSpecial() && "Should consume special tokens with Consume*Token"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return true; } bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) { if (!TryConsumeToken(Expected)) return false; Loc = PrevTokLocation; return true; } /// ConsumeAnyToken - Dispatch to the right Consume* method based on the /// current token type. This should only be used in cases where the type of /// the token really isn't known, e.g. in error recovery. SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) { if (isTokenParen()) return ConsumeParen(); if (isTokenBracket()) return ConsumeBracket(); if (isTokenBrace()) return ConsumeBrace(); if (isTokenStringLiteral()) return ConsumeStringToken(); if (Tok.is(tok::code_completion)) return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken() : handleUnexpectedCodeCompletionToken(); if (Tok.isAnnotation()) return ConsumeAnnotationToken(); return ConsumeToken(); } SourceLocation getEndOfPreviousToken() { return PP.getLocForEndOfToken(PrevTokLocation); } /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds /// to the given nullability kind. IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) { return Actions.getNullabilityKeyword(nullability); } private: //===--------------------------------------------------------------------===// // Low-Level token peeking and consumption methods. // /// isTokenParen - Return true if the cur token is '(' or ')'. bool isTokenParen() const { return Tok.isOneOf(tok::l_paren, tok::r_paren); } /// isTokenBracket - Return true if the cur token is '[' or ']'. bool isTokenBracket() const { return Tok.isOneOf(tok::l_square, tok::r_square); } /// isTokenBrace - Return true if the cur token is '{' or '}'. bool isTokenBrace() const { return Tok.isOneOf(tok::l_brace, tok::r_brace); } /// isTokenStringLiteral - True if this token is a string-literal. bool isTokenStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); } /// isTokenSpecial - True if this token requires special consumption methods. bool isTokenSpecial() const { return isTokenStringLiteral() || isTokenParen() || isTokenBracket() || isTokenBrace() || Tok.is(tok::code_completion) || Tok.isAnnotation(); } /// Returns true if the current token is '=' or is a type of '='. /// For typos, give a fixit to '=' bool isTokenEqualOrEqualTypo(); /// Return the current token to the token stream and make the given /// token the current token. void UnconsumeToken(Token &Consumed) { Token Next = Tok; PP.EnterToken(Consumed, /*IsReinject*/true); PP.Lex(Tok); PP.EnterToken(Next, /*IsReinject*/true); } SourceLocation ConsumeAnnotationToken() { assert(Tok.isAnnotation() && "wrong consume method"); SourceLocation Loc = Tok.getLocation(); PrevTokLocation = Tok.getAnnotationEndLoc(); PP.Lex(Tok); return Loc; } /// ConsumeParen - This consume method keeps the paren count up-to-date. /// SourceLocation ConsumeParen() { assert(isTokenParen() && "wrong consume method"); if (Tok.getKind() == tok::l_paren) ++ParenCount; else if (ParenCount) { AngleBrackets.clear(*this); --ParenCount; // Don't let unbalanced )'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeBracket - This consume method keeps the bracket count up-to-date. /// SourceLocation ConsumeBracket() { assert(isTokenBracket() && "wrong consume method"); if (Tok.getKind() == tok::l_square) ++BracketCount; else if (BracketCount) { AngleBrackets.clear(*this); --BracketCount; // Don't let unbalanced ]'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeBrace - This consume method keeps the brace count up-to-date. /// SourceLocation ConsumeBrace() { assert(isTokenBrace() && "wrong consume method"); if (Tok.getKind() == tok::l_brace) ++BraceCount; else if (BraceCount) { AngleBrackets.clear(*this); --BraceCount; // Don't let unbalanced }'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeStringToken - Consume the current 'peek token', lexing a new one /// and returning the token kind. This method is specific to strings, as it /// handles string literal concatenation, as per C99 5.1.1.2, translation /// phase #6. SourceLocation ConsumeStringToken() { assert(isTokenStringLiteral() && "Should only consume string literals with this method"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// Consume the current code-completion token. /// /// This routine can be called to consume the code-completion token and /// continue processing in special cases where \c cutOffParsing() isn't /// desired, such as token caching or completion with lookahead. SourceLocation ConsumeCodeCompletionToken() { assert(Tok.is(tok::code_completion)); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } ///\ brief When we are consuming a code-completion token without having /// matched specific position in the grammar, provide code-completion results /// based on context. /// /// \returns the source location of the code-completion token. SourceLocation handleUnexpectedCodeCompletionToken(); /// Abruptly cut off parsing; mainly used when we have reached the /// code-completion point. void cutOffParsing() { if (PP.isCodeCompletionEnabled()) PP.setCodeCompletionReached(); // Cut off parsing by acting as if we reached the end-of-file. Tok.setKind(tok::eof); } /// Determine if we're at the end of the file or at a transition /// between modules. bool isEofOrEom() { tok::TokenKind Kind = Tok.getKind(); return Kind == tok::eof || Kind == tok::annot_module_begin || Kind == tok::annot_module_end || Kind == tok::annot_module_include; } /// Checks if the \p Level is valid for use in a fold expression. bool isFoldOperator(prec::Level Level) const; /// Checks if the \p Kind is a valid operator for fold expressions. bool isFoldOperator(tok::TokenKind Kind) const; /// Initialize all pragma handlers. void initializePragmaHandlers(); /// Destroy and reset all pragma handlers. void resetPragmaHandlers(); /// Handle the annotation token produced for #pragma unused(...) void HandlePragmaUnused(); /// Handle the annotation token produced for /// #pragma GCC visibility... void HandlePragmaVisibility(); /// Handle the annotation token produced for /// #pragma pack... void HandlePragmaPack(); /// Handle the annotation token produced for /// #pragma ms_struct... void HandlePragmaMSStruct(); /// Handle the annotation token produced for /// #pragma comment... void HandlePragmaMSComment(); void HandlePragmaMSPointersToMembers(); void HandlePragmaMSVtorDisp(); void HandlePragmaMSPragma(); bool HandlePragmaMSSection(StringRef PragmaName, SourceLocation PragmaLocation); bool HandlePragmaMSSegment(StringRef PragmaName, SourceLocation PragmaLocation); bool HandlePragmaMSInitSeg(StringRef PragmaName, SourceLocation PragmaLocation); /// Handle the annotation token produced for /// #pragma align... void HandlePragmaAlign(); /// Handle the annotation token produced for /// #pragma clang __debug dump... void HandlePragmaDump(); /// Handle the annotation token produced for /// #pragma weak id... void HandlePragmaWeak(); /// Handle the annotation token produced for /// #pragma weak id = id... void HandlePragmaWeakAlias(); /// Handle the annotation token produced for /// #pragma redefine_extname... void HandlePragmaRedefineExtname(); /// Handle the annotation token produced for /// #pragma STDC FP_CONTRACT... void HandlePragmaFPContract(); /// Handle the annotation token produced for /// #pragma STDC FENV_ACCESS... void HandlePragmaFEnvAccess(); /// \brief Handle the annotation token produced for /// #pragma clang fp ... void HandlePragmaFP(); /// Handle the annotation token produced for /// #pragma OPENCL EXTENSION... void HandlePragmaOpenCLExtension(); /// Handle the annotation token produced for /// #pragma clang __debug captured StmtResult HandlePragmaCaptured(); /// Handle the annotation token produced for /// #pragma clang loop and #pragma unroll. bool HandlePragmaLoopHint(LoopHint &Hint); bool ParsePragmaAttributeSubjectMatchRuleSet( attr::ParsedSubjectMatchRuleSet &SubjectMatchRules, SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc); void HandlePragmaAttribute(); /// GetLookAheadToken - This peeks ahead N tokens and returns that token /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1) /// returns the token after Tok, etc. /// /// Note that this differs from the Preprocessor's LookAhead method, because /// the Parser always has one token lexed that the preprocessor doesn't. /// const Token &GetLookAheadToken(unsigned N) { if (N == 0 || Tok.is(tok::eof)) return Tok; return PP.LookAhead(N-1); } public: /// NextToken - This peeks ahead one token and returns it without /// consuming it. const Token &NextToken() { return PP.LookAhead(0); } /// getTypeAnnotation - Read a parsed type out of an annotation token. static ParsedType getTypeAnnotation(const Token &Tok) { return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue()); } private: static void setTypeAnnotation(Token &Tok, ParsedType T) { Tok.setAnnotationValue(T.getAsOpaquePtr()); } /// Read an already-translated primary expression out of an annotation /// token. static ExprResult getExprAnnotation(const Token &Tok) { return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue()); } /// Set the primary expression corresponding to the given annotation /// token. static void setExprAnnotation(Token &Tok, ExprResult ER) { Tok.setAnnotationValue(ER.getAsOpaquePointer()); } public: // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to // find a type name by attempting typo correction. bool TryAnnotateTypeOrScopeToken(); bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS, bool IsNewScope); bool TryAnnotateCXXScopeToken(bool EnteringContext = false); private: enum AnnotatedNameKind { /// Annotation has failed and emitted an error. ANK_Error, /// The identifier is a tentatively-declared name. ANK_TentativeDecl, /// The identifier is a template name. FIXME: Add an annotation for that. ANK_TemplateName, /// The identifier can't be resolved. ANK_Unresolved, /// Annotation was successful. ANK_Success }; AnnotatedNameKind TryAnnotateName(bool IsAddressOfOperand, CorrectionCandidateCallback *CCC = nullptr); /// Push a tok::annot_cxxscope token onto the token stream. void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation); /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens, /// replacing them with the non-context-sensitive keywords. This returns /// true if the token was replaced. bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, bool &isInvalid) { if (!getLangOpts().AltiVec && !getLangOpts().ZVector) return false; if (Tok.getIdentifierInfo() != Ident_vector && Tok.getIdentifierInfo() != Ident_bool && (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel)) return false; return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid); } /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector /// identifier token, replacing it with the non-context-sensitive __vector. /// This returns true if the token was replaced. bool TryAltiVecVectorToken() { if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) || Tok.getIdentifierInfo() != Ident_vector) return false; return TryAltiVecVectorTokenOutOfLine(); } bool TryAltiVecVectorTokenOutOfLine(); bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, bool &isInvalid); /// Returns true if the current token is the identifier 'instancetype'. /// /// Should only be used in Objective-C language modes. bool isObjCInstancetype() { assert(getLangOpts().ObjC); if (Tok.isAnnotation()) return false; if (!Ident_instancetype) Ident_instancetype = PP.getIdentifierInfo("instancetype"); return Tok.getIdentifierInfo() == Ident_instancetype; } /// TryKeywordIdentFallback - For compatibility with system headers using /// keywords as identifiers, attempt to convert the current token to an /// identifier and optionally disable the keyword for the remainder of the /// translation unit. This returns false if the token was not replaced, /// otherwise emits a diagnostic and returns true. bool TryKeywordIdentFallback(bool DisableKeyword); /// Get the TemplateIdAnnotation from the token. TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok); /// TentativeParsingAction - An object that is used as a kind of "tentative /// parsing transaction". It gets instantiated to mark the token position and /// after the token consumption is done, Commit() or Revert() is called to /// either "commit the consumed tokens" or revert to the previously marked /// token position. Example: /// /// TentativeParsingAction TPA(*this); /// ConsumeToken(); /// .... /// TPA.Revert(); /// class TentativeParsingAction { Parser &P; PreferredTypeBuilder PrevPreferredType; Token PrevTok; size_t PrevTentativelyDeclaredIdentifierCount; unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount; bool isActive; public: explicit TentativeParsingAction(Parser& p) : P(p) { PrevPreferredType = P.PreferredType; PrevTok = P.Tok; PrevTentativelyDeclaredIdentifierCount = P.TentativelyDeclaredIdentifiers.size(); PrevParenCount = P.ParenCount; PrevBracketCount = P.BracketCount; PrevBraceCount = P.BraceCount; P.PP.EnableBacktrackAtThisPos(); isActive = true; } void Commit() { assert(isActive && "Parsing action was finished!"); P.TentativelyDeclaredIdentifiers.resize( PrevTentativelyDeclaredIdentifierCount); P.PP.CommitBacktrackedTokens(); isActive = false; } void Revert() { assert(isActive && "Parsing action was finished!"); P.PP.Backtrack(); P.PreferredType = PrevPreferredType; P.Tok = PrevTok; P.TentativelyDeclaredIdentifiers.resize( PrevTentativelyDeclaredIdentifierCount); P.ParenCount = PrevParenCount; P.BracketCount = PrevBracketCount; P.BraceCount = PrevBraceCount; isActive = false; } ~TentativeParsingAction() { assert(!isActive && "Forgot to call Commit or Revert!"); } }; /// A TentativeParsingAction that automatically reverts in its destructor. /// Useful for disambiguation parses that will always be reverted. class RevertingTentativeParsingAction : private Parser::TentativeParsingAction { public: RevertingTentativeParsingAction(Parser &P) : Parser::TentativeParsingAction(P) {} ~RevertingTentativeParsingAction() { Revert(); } }; class UnannotatedTentativeParsingAction; /// ObjCDeclContextSwitch - An object used to switch context from /// an objective-c decl context to its enclosing decl context and /// back. class ObjCDeclContextSwitch { Parser &P; Decl *DC; SaveAndRestore<bool> WithinObjCContainer; public: explicit ObjCDeclContextSwitch(Parser &p) : P(p), DC(p.getObjCDeclContext()), WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) { if (DC) P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC)); } ~ObjCDeclContextSwitch() { if (DC) P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC)); } }; /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the /// input. If so, it is consumed and false is returned. /// /// If a trivial punctuator misspelling is encountered, a FixIt error /// diagnostic is issued and false is returned after recovery. /// /// If the input is malformed, this emits the specified diagnostic and true is /// returned. bool ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned Diag = diag::err_expected, StringRef DiagMsg = ""); /// The parser expects a semicolon and, if present, will consume it. /// /// If the next token is not a semicolon, this emits the specified diagnostic, /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior /// to the semicolon, consumes that extra token. bool ExpectAndConsumeSemi(unsigned DiagID); /// The kind of extra semi diagnostic to emit. enum ExtraSemiKind { OutsideFunction = 0, InsideStruct = 1, InstanceVariableList = 2, AfterMemberFunctionDefinition = 3 }; /// Consume any extra semi-colons until the end of the line. void ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST = TST_unspecified); /// Return false if the next token is an identifier. An 'expected identifier' /// error is emitted otherwise. /// /// The parser tries to recover from the error by checking if the next token /// is a C++ keyword when parsing Objective-C++. Return false if the recovery /// was successful. bool expectIdentifier(); public: //===--------------------------------------------------------------------===// // Scope manipulation /// ParseScope - Introduces a new scope for parsing. The kind of /// scope is determined by ScopeFlags. Objects of this type should /// be created on the stack to coincide with the position where the /// parser enters the new scope, and this object's constructor will /// create that new scope. Similarly, once the object is destroyed /// the parser will exit the scope. class ParseScope { Parser *Self; ParseScope(const ParseScope &) = delete; void operator=(const ParseScope &) = delete; public: // ParseScope - Construct a new object to manage a scope in the // parser Self where the new Scope is created with the flags // ScopeFlags, but only when we aren't about to enter a compound statement. ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true, bool BeforeCompoundStmt = false) : Self(Self) { if (EnteredScope && !BeforeCompoundStmt) Self->EnterScope(ScopeFlags); else { if (BeforeCompoundStmt) Self->incrementMSManglingNumber(); this->Self = nullptr; } } // Exit - Exit the scope associated with this object now, rather // than waiting until the object is destroyed. void Exit() { if (Self) { Self->ExitScope(); Self = nullptr; } } ~ParseScope() { Exit(); } }; /// EnterScope - Start a new scope. void EnterScope(unsigned ScopeFlags); /// ExitScope - Pop a scope off the scope stack. void ExitScope(); private: /// RAII object used to modify the scope flags for the current scope. class ParseScopeFlags { Scope *CurScope; unsigned OldFlags; ParseScopeFlags(const ParseScopeFlags &) = delete; void operator=(const ParseScopeFlags &) = delete; public: ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true); ~ParseScopeFlags(); }; //===--------------------------------------------------------------------===// // Diagnostic Emission and Error recovery. public: DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID); DiagnosticBuilder Diag(unsigned DiagID) { return Diag(Tok, DiagID); } private: void SuggestParentheses(SourceLocation Loc, unsigned DK, SourceRange ParenRange); void CheckNestedObjCContexts(SourceLocation AtLoc); public: /// Control flags for SkipUntil functions. enum SkipUntilFlags { StopAtSemi = 1 << 0, ///< Stop skipping at semicolon /// Stop skipping at specified token, but don't skip the token itself StopBeforeMatch = 1 << 1, StopAtCodeCompletion = 1 << 2 ///< Stop at code completion }; friend constexpr SkipUntilFlags operator|(SkipUntilFlags L, SkipUntilFlags R) { return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) | static_cast<unsigned>(R)); } /// SkipUntil - Read tokens until we get to the specified token, then consume /// it (unless StopBeforeMatch is specified). Because we cannot guarantee /// that the token will ever occur, this skips to the next token, or to some /// likely good stopping point. If Flags has StopAtSemi flag, skipping will /// stop at a ';' character. /// /// If SkipUntil finds the specified token, it returns true, otherwise it /// returns false. bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { return SkipUntil(llvm::makeArrayRef(T), Flags); } bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { tok::TokenKind TokArray[] = {T1, T2}; return SkipUntil(TokArray, Flags); } bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { tok::TokenKind TokArray[] = {T1, T2, T3}; return SkipUntil(TokArray, Flags); } bool SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)); /// SkipMalformedDecl - Read tokens until we get to some likely good stopping /// point for skipping past a simple-declaration. void SkipMalformedDecl(); private: //===--------------------------------------------------------------------===// // Lexing and parsing of C++ inline methods. struct ParsingClass; /// [class.mem]p1: "... the class is regarded as complete within /// - function bodies /// - default arguments /// - exception-specifications (TODO: C++0x) /// - and brace-or-equal-initializers for non-static data members /// (including such things in nested classes)." /// LateParsedDeclarations build the tree of those elements so they can /// be parsed after parsing the top-level class. class LateParsedDeclaration { public: virtual ~LateParsedDeclaration(); virtual void ParseLexedMethodDeclarations(); virtual void ParseLexedMemberInitializers(); virtual void ParseLexedMethodDefs(); virtual void ParseLexedAttributes(); }; /// Inner node of the LateParsedDeclaration tree that parses /// all its members recursively. class LateParsedClass : public LateParsedDeclaration { public: LateParsedClass(Parser *P, ParsingClass *C); ~LateParsedClass() override; void ParseLexedMethodDeclarations() override; void ParseLexedMemberInitializers() override; void ParseLexedMethodDefs() override; void ParseLexedAttributes() override; private: Parser *Self; ParsingClass *Class; }; /// Contains the lexed tokens of an attribute with arguments that /// may reference member variables and so need to be parsed at the /// end of the class declaration after parsing all other member /// member declarations. /// FIXME: Perhaps we should change the name of LateParsedDeclaration to /// LateParsedTokens. struct LateParsedAttribute : public LateParsedDeclaration { Parser *Self; CachedTokens Toks; IdentifierInfo &AttrName; IdentifierInfo *MacroII = nullptr; SourceLocation AttrNameLoc; SmallVector<Decl*, 2> Decls; explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name, SourceLocation Loc) : Self(P), AttrName(Name), AttrNameLoc(Loc) {} void ParseLexedAttributes() override; void addDecl(Decl *D) { Decls.push_back(D); } }; // A list of late-parsed attributes. Used by ParseGNUAttributes. class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> { public: LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { } bool parseSoon() { return ParseSoon; } private: bool ParseSoon; // Are we planning to parse these shortly after creation? }; /// Contains the lexed tokens of a member function definition /// which needs to be parsed at the end of the class declaration /// after parsing all other member declarations. struct LexedMethod : public LateParsedDeclaration { Parser *Self; Decl *D; CachedTokens Toks; /// Whether this member function had an associated template /// scope. When true, D is a template declaration. /// otherwise, it is a member function declaration. bool TemplateScope; explicit LexedMethod(Parser* P, Decl *MD) : Self(P), D(MD), TemplateScope(false) {} void ParseLexedMethodDefs() override; }; /// LateParsedDefaultArgument - Keeps track of a parameter that may /// have a default argument that cannot be parsed yet because it /// occurs within a member function declaration inside the class /// (C++ [class.mem]p2). struct LateParsedDefaultArgument { explicit LateParsedDefaultArgument(Decl *P, std::unique_ptr<CachedTokens> Toks = nullptr) : Param(P), Toks(std::move(Toks)) { } /// Param - The parameter declaration for this parameter. Decl *Param; /// Toks - The sequence of tokens that comprises the default /// argument expression, not including the '=' or the terminating /// ')' or ','. This will be NULL for parameters that have no /// default argument. std::unique_ptr<CachedTokens> Toks; }; /// LateParsedMethodDeclaration - A method declaration inside a class that /// contains at least one entity whose parsing needs to be delayed /// until the class itself is completely-defined, such as a default /// argument (C++ [class.mem]p2). struct LateParsedMethodDeclaration : public LateParsedDeclaration { explicit LateParsedMethodDeclaration(Parser *P, Decl *M) : Self(P), Method(M), TemplateScope(false), ExceptionSpecTokens(nullptr) {} void ParseLexedMethodDeclarations() override; Parser* Self; /// Method - The method declaration. Decl *Method; /// Whether this member function had an associated template /// scope. When true, D is a template declaration. /// otherwise, it is a member function declaration. bool TemplateScope; /// DefaultArgs - Contains the parameters of the function and /// their default arguments. At least one of the parameters will /// have a default argument, but all of the parameters of the /// method will be stored so that they can be reintroduced into /// scope at the appropriate times. SmallVector<LateParsedDefaultArgument, 8> DefaultArgs; /// The set of tokens that make up an exception-specification that /// has not yet been parsed. CachedTokens *ExceptionSpecTokens; }; /// LateParsedMemberInitializer - An initializer for a non-static class data /// member whose parsing must to be delayed until the class is completely /// defined (C++11 [class.mem]p2). struct LateParsedMemberInitializer : public LateParsedDeclaration { LateParsedMemberInitializer(Parser *P, Decl *FD) : Self(P), Field(FD) { } void ParseLexedMemberInitializers() override; Parser *Self; /// Field - The field declaration. Decl *Field; /// CachedTokens - The sequence of tokens that comprises the initializer, /// including any leading '='. CachedTokens Toks; }; /// LateParsedDeclarationsContainer - During parsing of a top (non-nested) /// C++ class, its method declarations that contain parts that won't be /// parsed until after the definition is completed (C++ [class.mem]p2), /// the method declarations and possibly attached inline definitions /// will be stored here with the tokens that will be parsed to create those /// entities. typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer; /// Representation of a class that has been parsed, including /// any member function declarations or definitions that need to be /// parsed after the corresponding top-level class is complete. struct ParsingClass { ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface) : TopLevelClass(TopLevelClass), TemplateScope(false), IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) { } /// Whether this is a "top-level" class, meaning that it is /// not nested within another class. bool TopLevelClass : 1; /// Whether this class had an associated template /// scope. When true, TagOrTemplate is a template declaration; /// otherwise, it is a tag declaration. bool TemplateScope : 1; /// Whether this class is an __interface. bool IsInterface : 1; /// The class or class template whose definition we are parsing. Decl *TagOrTemplate; /// LateParsedDeclarations - Method declarations, inline definitions and /// nested classes that contain pieces whose parsing will be delayed until /// the top-level class is fully defined. LateParsedDeclarationsContainer LateParsedDeclarations; }; /// The stack of classes that is currently being /// parsed. Nested and local classes will be pushed onto this stack /// when they are parsed, and removed afterward. std::stack<ParsingClass *> ClassStack; ParsingClass &getCurrentClass() { assert(!ClassStack.empty() && "No lexed method stacks!"); return *ClassStack.top(); } /// RAII object used to manage the parsing of a class definition. class ParsingClassDefinition { Parser &P; bool Popped; Sema::ParsingClassState State; public: ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface) : P(P), Popped(false), State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) { } /// Pop this class of the stack. void Pop() { assert(!Popped && "Nested class has already been popped"); Popped = true; P.PopParsingClass(State); } ~ParsingClassDefinition() { if (!Popped) P.PopParsingClass(State); } }; /// Contains information about any template-specific /// information that has been parsed prior to parsing declaration /// specifiers. struct ParsedTemplateInfo { ParsedTemplateInfo() : Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { } ParsedTemplateInfo(TemplateParameterLists *TemplateParams, bool isSpecialization, bool lastParameterListWasEmpty = false) : Kind(isSpecialization? ExplicitSpecialization : Template), TemplateParams(TemplateParams), LastParameterListWasEmpty(lastParameterListWasEmpty) { } explicit ParsedTemplateInfo(SourceLocation ExternLoc, SourceLocation TemplateLoc) : Kind(ExplicitInstantiation), TemplateParams(nullptr), ExternLoc(ExternLoc), TemplateLoc(TemplateLoc), LastParameterListWasEmpty(false){ } /// The kind of template we are parsing. enum { /// We are not parsing a template at all. NonTemplate = 0, /// We are parsing a template declaration. Template, /// We are parsing an explicit specialization. ExplicitSpecialization, /// We are parsing an explicit instantiation. ExplicitInstantiation } Kind; /// The template parameter lists, for template declarations /// and explicit specializations. TemplateParameterLists *TemplateParams; /// The location of the 'extern' keyword, if any, for an explicit /// instantiation SourceLocation ExternLoc; /// The location of the 'template' keyword, for an explicit /// instantiation. SourceLocation TemplateLoc; /// Whether the last template parameter list was empty. bool LastParameterListWasEmpty; SourceRange getSourceRange() const LLVM_READONLY; }; void LexTemplateFunctionForLateParsing(CachedTokens &Toks); void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT); static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT); static void LateTemplateParserCleanupCallback(void *P); Sema::ParsingClassState PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface); void DeallocateParsedClasses(ParsingClass *Class); void PopParsingClass(Sema::ParsingClassState); enum CachedInitKind { CIK_DefaultArgument, CIK_DefaultInitializer }; NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS, ParsedAttributes &AccessAttrs, ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo, const VirtSpecifiers &VS, SourceLocation PureSpecLoc); void ParseCXXNonStaticMemberInitializer(Decl *VarD); void ParseLexedAttributes(ParsingClass &Class); void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D, bool EnterScope, bool OnDefinition); void ParseLexedAttribute(LateParsedAttribute &LA, bool EnterScope, bool OnDefinition); void ParseLexedMethodDeclarations(ParsingClass &Class); void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM); void ParseLexedMethodDefs(ParsingClass &Class); void ParseLexedMethodDef(LexedMethod &LM); void ParseLexedMemberInitializers(ParsingClass &Class); void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI); void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod); bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks); bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK); bool ConsumeAndStoreConditional(CachedTokens &Toks); bool ConsumeAndStoreUntil(tok::TokenKind T1, CachedTokens &Toks, bool StopAtSemi = true, bool ConsumeFinalToken = true) { return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken); } bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2, CachedTokens &Toks, bool StopAtSemi = true, bool ConsumeFinalToken = true); //===--------------------------------------------------------------------===// // C99 6.9: External Definitions. struct ParsedAttributesWithRange : ParsedAttributes { ParsedAttributesWithRange(AttributeFactory &factory) : ParsedAttributes(factory) {} void clear() { ParsedAttributes::clear(); Range = SourceRange(); } SourceRange Range; }; struct ParsedAttributesViewWithRange : ParsedAttributesView { ParsedAttributesViewWithRange() : ParsedAttributesView() {} void clearListOnly() { ParsedAttributesView::clearListOnly(); Range = SourceRange(); } SourceRange Range; }; DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs, ParsingDeclSpec *DS = nullptr); bool isDeclarationAfterDeclarator(); bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator); DeclGroupPtrTy ParseDeclarationOrFunctionDefinition( ParsedAttributesWithRange &attrs, ParsingDeclSpec *DS = nullptr, AccessSpecifier AS = AS_none); DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs, ParsingDeclSpec &DS, AccessSpecifier AS); void SkipFunctionBody(); Decl *ParseFunctionDefinition(ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), LateParsedAttrList *LateParsedAttrs = nullptr); void ParseKNRParamDeclarations(Declarator &D); // EndLoc, if non-NULL, is filled with the location of the last token of // the simple-asm. ExprResult ParseSimpleAsm(SourceLocation *EndLoc = nullptr); ExprResult ParseAsmStringLiteral(); // Objective-C External Declarations void MaybeSkipAttributes(tok::ObjCKeywordKind Kind); DeclGroupPtrTy ParseObjCAtDirectives(ParsedAttributesWithRange &Attrs); DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc); Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc, ParsedAttributes &prefixAttrs); class ObjCTypeParamListScope; ObjCTypeParamList *parseObjCTypeParamList(); ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs( ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc, SmallVectorImpl<IdentifierLocPair> &protocolIdents, SourceLocation &rAngleLoc, bool mayBeProtocolList = true); void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc, BalancedDelimiterTracker &T, SmallVectorImpl<Decl *> &AllIvarDecls, bool RBraceMissing); void ParseObjCClassInstanceVariables(Decl *interfaceDecl, tok::ObjCKeywordKind visibility, SourceLocation atLoc); bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P, SmallVectorImpl<SourceLocation> &PLocs, bool WarnOnDeclarations, bool ForObjCContainer, SourceLocation &LAngleLoc, SourceLocation &EndProtoLoc, bool consumeLastToken); /// Parse the first angle-bracket-delimited clause for an /// Objective-C object or object pointer type, which may be either /// type arguments or protocol qualifiers. void parseObjCTypeArgsOrProtocolQualifiers( ParsedType baseType, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SmallVectorImpl<SourceLocation> &protocolLocs, SourceLocation &protocolRAngleLoc, bool consumeLastToken, bool warnOnIncompleteProtocols); /// Parse either Objective-C type arguments or protocol qualifiers; if the /// former, also parse protocol qualifiers afterward. void parseObjCTypeArgsAndProtocolQualifiers( ParsedType baseType, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SmallVectorImpl<SourceLocation> &protocolLocs, SourceLocation &protocolRAngleLoc, bool consumeLastToken); /// Parse a protocol qualifier type such as '<NSCopying>', which is /// an anachronistic way of writing 'id<NSCopying>'. TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc); /// Parse Objective-C type arguments and protocol qualifiers, extending the /// current type with the parsed result. TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc, ParsedType type, bool consumeLastToken, SourceLocation &endLoc); void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, Decl *CDecl); DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc, ParsedAttributes &prefixAttrs); struct ObjCImplParsingDataRAII { Parser &P; Decl *Dcl; bool HasCFunction; typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer; LateParsedObjCMethodContainer LateParsedObjCMethods; ObjCImplParsingDataRAII(Parser &parser, Decl *D) : P(parser), Dcl(D), HasCFunction(false) { P.CurParsedObjCImpl = this; Finished = false; } ~ObjCImplParsingDataRAII(); void finish(SourceRange AtEnd); bool isFinished() const { return Finished; } private: bool Finished; }; ObjCImplParsingDataRAII *CurParsedObjCImpl; void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl); DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc, ParsedAttributes &Attrs); DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd); Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc); Decl *ParseObjCPropertySynthesize(SourceLocation atLoc); Decl *ParseObjCPropertyDynamic(SourceLocation atLoc); IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation); // Definitions for Objective-c context sensitive keywords recognition. enum ObjCTypeQual { objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref, objc_nonnull, objc_nullable, objc_null_unspecified, objc_NumQuals }; IdentifierInfo *ObjCTypeQuals[objc_NumQuals]; bool isTokIdentifier_in() const; ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext Ctx, ParsedAttributes *ParamAttrs); void ParseObjCMethodRequirement(); Decl *ParseObjCMethodPrototype( tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, bool MethodDefinition = true); Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType, tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, bool MethodDefinition=true); void ParseObjCPropertyAttribute(ObjCDeclSpec &DS); Decl *ParseObjCMethodDefinition(); public: //===--------------------------------------------------------------------===// // C99 6.5: Expressions. /// TypeCastState - State whether an expression is or may be a type cast. enum TypeCastState { NotTypeCast = 0, MaybeTypeCast, IsTypeCast }; ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseConstantExpressionInExprEvalContext( TypeCastState isTypeCast = NotTypeCast); ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseCaseExpression(SourceLocation CaseLoc); ExprResult ParseConstraintExpression(); // Expr that doesn't include commas. ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks, unsigned &NumLineToksConsumed, bool IsUnevaluated); private: ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc); ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc); ExprResult ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec); ExprResult ParseCastExpression(bool isUnaryExpression, bool isAddressOfOperand, bool &NotCastExpr, TypeCastState isTypeCast, bool isVectorLiteral = false); ExprResult ParseCastExpression(bool isUnaryExpression, bool isAddressOfOperand = false, TypeCastState isTypeCast = NotTypeCast, bool isVectorLiteral = false); /// Returns true if the next token cannot start an expression. bool isNotExpressionStart(); /// Returns true if the next token would start a postfix-expression /// suffix. bool isPostfixExpressionSuffixStart() { tok::TokenKind K = Tok.getKind(); return (K == tok::l_square || K == tok::l_paren || K == tok::period || K == tok::arrow || K == tok::plusplus || K == tok::minusminus); } bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less); void checkPotentialAngleBracket(ExprResult &PotentialTemplateName); bool checkPotentialAngleBracketDelimiter(const AngleBracketTracker::Loc &, const Token &OpToken); bool checkPotentialAngleBracketDelimiter(const Token &OpToken) { if (auto *Info = AngleBrackets.getCurrent(*this)) return checkPotentialAngleBracketDelimiter(*Info, OpToken); return false; } ExprResult ParsePostfixExpressionSuffix(ExprResult LHS); ExprResult ParseUnaryExprOrTypeTraitExpression(); ExprResult ParseBuiltinPrimaryExpression(); ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok, bool &isCastExpr, ParsedType &CastTy, SourceRange &CastRange); typedef SmallVector<Expr*, 20> ExprListTy; typedef SmallVector<SourceLocation, 20> CommaLocsTy; /// ParseExpressionList - Used for C/C++ (argument-)expression-list. bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs, SmallVectorImpl<SourceLocation> &CommaLocs, llvm::function_ref<void()> ExpressionStarts = llvm::function_ref<void()>()); /// ParseSimpleExpressionList - A simple comma-separated list of expressions, /// used for misc language extensions. bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs, SmallVectorImpl<SourceLocation> &CommaLocs); /// ParenParseOption - Control what ParseParenExpression will parse. enum ParenParseOption { SimpleExpr, // Only parse '(' expression ')' FoldExpr, // Also allow fold-expression <anything> CompoundStmt, // Also allow '(' compound-statement ')' CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}' CastExpr // Also allow '(' type-name ')' <anything> }; ExprResult ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, bool isTypeCast, ParsedType &CastTy, SourceLocation &RParenLoc); ExprResult ParseCXXAmbiguousParenExpression( ParenParseOption &ExprType, ParsedType &CastTy, BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt); ExprResult ParseCompoundLiteralExpression(ParsedType Ty, SourceLocation LParenLoc, SourceLocation RParenLoc); ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false); ExprResult ParseGenericSelectionExpression(); ExprResult ParseObjCBoolLiteral(); ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T); //===--------------------------------------------------------------------===// // C++ Expressions ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand, Token &Replacement); ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false); bool areTokensAdjacent(const Token &A, const Token &B); void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr, bool EnteringContext, IdentifierInfo &II, CXXScopeSpec &SS); bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext, bool *MayBePseudoDestructor = nullptr, bool IsTypename = false, IdentifierInfo **LastII = nullptr, bool OnlyNamespace = false); //===--------------------------------------------------------------------===// // C++11 5.1.2: Lambda expressions /// Result of tentatively parsing a lambda-introducer. enum class LambdaIntroducerTentativeParse { /// This appears to be a lambda-introducer, which has been fully parsed. Success, /// This is a lambda-introducer, but has not been fully parsed, and this /// function needs to be called again to parse it. Incomplete, /// This is definitely an Objective-C message send expression, rather than /// a lambda-introducer, attribute-specifier, or array designator. MessageSend, /// This is not a lambda-introducer. Invalid, }; // [...] () -> type {...} ExprResult ParseLambdaExpression(); ExprResult TryParseLambdaExpression(); bool ParseLambdaIntroducer(LambdaIntroducer &Intro, LambdaIntroducerTentativeParse *Tentative = nullptr); ExprResult ParseLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro); //===--------------------------------------------------------------------===// // C++ 5.2p1: C++ Casts ExprResult ParseCXXCasts(); //===--------------------------------------------------------------------===// // C++ 5.2p1: C++ Type Identification ExprResult ParseCXXTypeid(); //===--------------------------------------------------------------------===// // C++ : Microsoft __uuidof Expression ExprResult ParseCXXUuidof(); //===--------------------------------------------------------------------===// // C++ 5.2.4: C++ Pseudo-Destructor Expressions ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, ParsedType ObjectType); //===--------------------------------------------------------------------===// // C++ 9.3.2: C++ 'this' pointer ExprResult ParseCXXThis(); //===--------------------------------------------------------------------===// // C++ 15: C++ Throw Expression ExprResult ParseThrowExpression(); ExceptionSpecificationType tryParseExceptionSpecification( bool Delayed, SourceRange &SpecificationRange, SmallVectorImpl<ParsedType> &DynamicExceptions, SmallVectorImpl<SourceRange> &DynamicExceptionRanges, ExprResult &NoexceptExpr, CachedTokens *&ExceptionSpecTokens); // EndLoc is filled with the location of the last token of the specification. ExceptionSpecificationType ParseDynamicExceptionSpecification( SourceRange &SpecificationRange, SmallVectorImpl<ParsedType> &Exceptions, SmallVectorImpl<SourceRange> &Ranges); //===--------------------------------------------------------------------===// // C++0x 8: Function declaration trailing-return-type TypeResult ParseTrailingReturnType(SourceRange &Range, bool MayBeFollowedByDirectInit); //===--------------------------------------------------------------------===// // C++ 2.13.5: C++ Boolean Literals ExprResult ParseCXXBoolLiteral(); //===--------------------------------------------------------------------===// // C++ 5.2.3: Explicit type conversion (functional notation) ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS); /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers. /// This should only be called when the current token is known to be part of /// simple-type-specifier. void ParseCXXSimpleTypeSpecifier(DeclSpec &DS); bool ParseCXXTypeSpecifierSeq(DeclSpec &DS); //===--------------------------------------------------------------------===// // C++ 5.3.4 and 5.3.5: C++ new and delete bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs, Declarator &D); void ParseDirectNewDeclarator(Declarator &D); ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start); ExprResult ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start); //===--------------------------------------------------------------------===// // C++ if/switch/while/for condition expression. struct ForRangeInfo; Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt, SourceLocation Loc, Sema::ConditionKind CK, ForRangeInfo *FRI = nullptr); //===--------------------------------------------------------------------===// // C++ Coroutines ExprResult ParseCoyieldExpression(); //===--------------------------------------------------------------------===// // C99 6.7.8: Initialization. /// ParseInitializer /// initializer: [C99 6.7.8] /// assignment-expression /// '{' ... ExprResult ParseInitializer() { if (Tok.isNot(tok::l_brace)) return ParseAssignmentExpression(); return ParseBraceInitializer(); } bool MayBeDesignationStart(); ExprResult ParseBraceInitializer(); ExprResult ParseInitializerWithPotentialDesignator(); //===--------------------------------------------------------------------===// // clang Expressions ExprResult ParseBlockLiteralExpression(); // ^{...} //===--------------------------------------------------------------------===// // Objective-C Expressions ExprResult ParseObjCAtExpression(SourceLocation AtLocation); ExprResult ParseObjCStringLiteral(SourceLocation AtLoc); ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc); ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc); ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue); ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc); ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc); ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc); ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc); ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc); ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc); bool isSimpleObjCMessageExpression(); ExprResult ParseObjCMessageExpression(); ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc, SourceLocation SuperLoc, ParsedType ReceiverType, Expr *ReceiverExpr); ExprResult ParseAssignmentExprWithObjCMessageExprStart( SourceLocation LBracloc, SourceLocation SuperLoc, ParsedType ReceiverType, Expr *ReceiverExpr); bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr); //===--------------------------------------------------------------------===// // C99 6.8: Statements and Blocks. /// A SmallVector of statements, with stack size 32 (as that is the only one /// used.) typedef SmallVector<Stmt*, 32> StmtVector; /// A SmallVector of expressions, with stack size 12 (the maximum used.) typedef SmallVector<Expr*, 12> ExprVector; /// A SmallVector of types. typedef SmallVector<ParsedType, 12> TypeVector; StmtResult ParseStatement(SourceLocation *TrailingElseLoc = nullptr, ParsedStmtContext StmtCtx = ParsedStmtContext::SubStmt); StmtResult ParseStatementOrDeclaration( StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc = nullptr); StmtResult ParseStatementOrDeclarationAfterAttributes( StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs); StmtResult ParseExprStatement(ParsedStmtContext StmtCtx); StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs, ParsedStmtContext StmtCtx); StmtResult ParseCaseStatement(ParsedStmtContext StmtCtx, bool MissingCase = false, ExprResult Expr = ExprResult()); StmtResult ParseDefaultStatement(ParsedStmtContext StmtCtx); StmtResult ParseCompoundStatement(bool isStmtExpr = false); StmtResult ParseCompoundStatement(bool isStmtExpr, unsigned ScopeFlags); void ParseCompoundStatementLeadingPragmas(); bool ConsumeNullStmt(StmtVector &Stmts); StmtResult ParseCompoundStatementBody(bool isStmtExpr = false); bool ParseParenExprOrCondition(StmtResult *InitStmt, Sema::ConditionResult &CondResult, SourceLocation Loc, Sema::ConditionKind CK); StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc); StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc); StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc); StmtResult ParseDoStatement(); StmtResult ParseForStatement(SourceLocation *TrailingElseLoc); StmtResult ParseGotoStatement(); StmtResult ParseContinueStatement(); StmtResult ParseBreakStatement(); StmtResult ParseReturnStatement(); StmtResult ParseAsmStatement(bool &msAsm); StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc); StmtResult ParsePragmaLoopHint(StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs); /// Describes the behavior that should be taken for an __if_exists /// block. enum IfExistsBehavior { /// Parse the block; this code is always used. IEB_Parse, /// Skip the block entirely; this code is never used. IEB_Skip, /// Parse the block as a dependent block, which may be used in /// some template instantiations but not others. IEB_Dependent }; /// Describes the condition of a Microsoft __if_exists or /// __if_not_exists block. struct IfExistsCondition { /// The location of the initial keyword. SourceLocation KeywordLoc; /// Whether this is an __if_exists block (rather than an /// __if_not_exists block). bool IsIfExists; /// Nested-name-specifier preceding the name. CXXScopeSpec SS; /// The name we're looking for. UnqualifiedId Name; /// The behavior of this __if_exists or __if_not_exists block /// should. IfExistsBehavior Behavior; }; bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result); void ParseMicrosoftIfExistsStatement(StmtVector &Stmts); void ParseMicrosoftIfExistsExternalDeclaration(); void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType, ParsedAttributes &AccessAttrs, AccessSpecifier &CurAS); bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs, bool &InitExprsOk); bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names, SmallVectorImpl<Expr *> &Constraints, SmallVectorImpl<Expr *> &Exprs); //===--------------------------------------------------------------------===// // C++ 6: Statements and Blocks StmtResult ParseCXXTryBlock(); StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false); StmtResult ParseCXXCatchBlock(bool FnCatch = false); //===--------------------------------------------------------------------===// // MS: SEH Statements and Blocks StmtResult ParseSEHTryBlock(); StmtResult ParseSEHExceptBlock(SourceLocation Loc); StmtResult ParseSEHFinallyBlock(SourceLocation Loc); StmtResult ParseSEHLeaveStatement(); //===--------------------------------------------------------------------===// // Objective-C Statements StmtResult ParseObjCAtStatement(SourceLocation atLoc, ParsedStmtContext StmtCtx); StmtResult ParseObjCTryStmt(SourceLocation atLoc); StmtResult ParseObjCThrowStmt(SourceLocation atLoc); StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc); StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc); //===--------------------------------------------------------------------===// // C99 6.7: Declarations. /// A context for parsing declaration specifiers. TODO: flesh this /// out, there are other significant restrictions on specifiers than /// would be best implemented in the parser. enum class DeclSpecContext { DSC_normal, // normal context DSC_class, // class context, enables 'friend' DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list DSC_trailing, // C++11 trailing-type-specifier in a trailing return type DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration DSC_top_level, // top-level/namespace declaration context DSC_template_param, // template parameter context DSC_template_type_arg, // template type argument context DSC_objc_method_result, // ObjC method result context, enables 'instancetype' DSC_condition // condition declaration context }; /// Is this a context in which we are parsing just a type-specifier (or /// trailing-type-specifier)? static bool isTypeSpecifier(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_template_param: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: case DeclSpecContext::DSC_objc_method_result: case DeclSpecContext::DSC_condition: return false; case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_type_specifier: case DeclSpecContext::DSC_trailing: case DeclSpecContext::DSC_alias_declaration: return true; } llvm_unreachable("Missing DeclSpecContext case"); } /// Is this a context in which we can perform class template argument /// deduction? static bool isClassTemplateDeductionContext(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_template_param: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: case DeclSpecContext::DSC_condition: case DeclSpecContext::DSC_type_specifier: return true; case DeclSpecContext::DSC_objc_method_result: case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_trailing: case DeclSpecContext::DSC_alias_declaration: return false; } llvm_unreachable("Missing DeclSpecContext case"); } /// Information on a C++0x for-range-initializer found while parsing a /// declaration which turns out to be a for-range-declaration. struct ForRangeInit { SourceLocation ColonLoc; ExprResult RangeExpr; bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); } }; struct ForRangeInfo : ForRangeInit { StmtResult LoopVar; }; DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs); DeclGroupPtrTy ParseSimpleDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs, bool RequireSemi, ForRangeInit *FRI = nullptr); bool MightBeDeclarator(DeclaratorContext Context); DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context, SourceLocation *DeclEnd = nullptr, ForRangeInit *FRI = nullptr); Decl *ParseDeclarationAfterDeclarator(Declarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo()); bool ParseAsmAttributesAfterDeclarator(Declarator &D); Decl *ParseDeclarationAfterDeclaratorAndAttributes( Declarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), ForRangeInit *FRI = nullptr); Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope); Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope); /// When in code-completion, skip parsing of the function/method body /// unless the body contains the code-completion point. /// /// \returns true if the function body was skipped. bool trySkippingFunctionBody(); bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, DeclSpecContext DSC, ParsedAttributesWithRange &Attrs); DeclSpecContext getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context); void ParseDeclarationSpecifiers( DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), AccessSpecifier AS = AS_none, DeclSpecContext DSC = DeclSpecContext::DSC_normal, LateParsedAttrList *LateAttrs = nullptr); bool DiagnoseMissingSemiAfterTagDefinition( DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext, LateParsedAttrList *LateAttrs = nullptr); void ParseSpecifierQualifierList( DeclSpec &DS, AccessSpecifier AS = AS_none, DeclSpecContext DSC = DeclSpecContext::DSC_normal); void ParseObjCTypeQualifierList(ObjCDeclSpec &DS, DeclaratorContext Context); void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, DeclSpecContext DSC); void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl); void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType, Decl *TagDecl); void ParseStructDeclaration( ParsingDeclSpec &DS, llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback); bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false); bool isTypeSpecifierQualifier(); /// isKnownToBeTypeSpecifier - Return true if we know that the specified token /// is definitely a type-specifier. Return false if it isn't part of a type /// specifier or if we're not sure. bool isKnownToBeTypeSpecifier(const Token &Tok) const; /// Return true if we know that we are definitely looking at a /// decl-specifier, and isn't part of an expression such as a function-style /// cast. Return false if it's no a decl-specifier, or we're not sure. bool isKnownToBeDeclarationSpecifier() { if (getLangOpts().CPlusPlus) return isCXXDeclarationSpecifier() == TPResult::True; return isDeclarationSpecifier(true); } /// isDeclarationStatement - Disambiguates between a declaration or an /// expression statement, when parsing function bodies. /// Returns true for declaration, false for expression. bool isDeclarationStatement() { if (getLangOpts().CPlusPlus) return isCXXDeclarationStatement(); return isDeclarationSpecifier(true); } /// isForInitDeclaration - Disambiguates between a declaration or an /// expression in the context of the C 'clause-1' or the C++ // 'for-init-statement' part of a 'for' statement. /// Returns true for declaration, false for expression. bool isForInitDeclaration() { if (getLangOpts().OpenMP) Actions.startOpenMPLoop(); if (getLangOpts().CPlusPlus) return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true); return isDeclarationSpecifier(true); } /// Determine whether this is a C++1z for-range-identifier. bool isForRangeIdentifier(); /// Determine whether we are currently at the start of an Objective-C /// class message that appears to be missing the open bracket '['. bool isStartOfObjCClassMessageMissingOpenBracket(); /// Starting with a scope specifier, identifier, or /// template-id that refers to the current class, determine whether /// this is a constructor declarator. bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false); /// Specifies the context in which type-id/expression /// disambiguation will occur. enum TentativeCXXTypeIdContext { TypeIdInParens, TypeIdUnambiguous, TypeIdAsTemplateArgument }; /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know /// whether the parens contain an expression or a type-id. /// Returns true for a type-id and false for an expression. bool isTypeIdInParens(bool &isAmbiguous) { if (getLangOpts().CPlusPlus) return isCXXTypeId(TypeIdInParens, isAmbiguous); isAmbiguous = false; return isTypeSpecifierQualifier(); } bool isTypeIdInParens() { bool isAmbiguous; return isTypeIdInParens(isAmbiguous); } /// Checks if the current tokens form type-id or expression. /// It is similar to isTypeIdInParens but does not suppose that type-id /// is in parenthesis. bool isTypeIdUnambiguously() { bool IsAmbiguous; if (getLangOpts().CPlusPlus) return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous); return isTypeSpecifierQualifier(); } /// isCXXDeclarationStatement - C++-specialized function that disambiguates /// between a declaration or an expression statement, when parsing function /// bodies. Returns true for declaration, false for expression. bool isCXXDeclarationStatement(); /// isCXXSimpleDeclaration - C++-specialized function that disambiguates /// between a simple-declaration or an expression-statement. /// If during the disambiguation process a parsing error is encountered, /// the function returns true to let the declaration parsing code handle it. /// Returns false if the statement is disambiguated as expression. bool isCXXSimpleDeclaration(bool AllowForRangeDecl); /// isCXXFunctionDeclarator - Disambiguates between a function declarator or /// a constructor-style initializer, when parsing declaration statements. /// Returns true for function declarator and false for constructor-style /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration /// might be a constructor-style initializer. /// If during the disambiguation process a parsing error is encountered, /// the function returns true to let the declaration parsing code handle it. bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr); struct ConditionDeclarationOrInitStatementState; enum class ConditionOrInitStatement { Expression, ///< Disambiguated as an expression (either kind). ConditionDecl, ///< Disambiguated as the declaration form of condition. InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement. ForRangeDecl, ///< Disambiguated as a for-range declaration. Error ///< Can't be any of the above! }; /// Disambiguates between the different kinds of things that can happen /// after 'if (' or 'switch ('. This could be one of two different kinds of /// declaration (depending on whether there is a ';' later) or an expression. ConditionOrInitStatement isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt, bool CanBeForRangeDecl); bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous); bool isCXXTypeId(TentativeCXXTypeIdContext Context) { bool isAmbiguous; return isCXXTypeId(Context, isAmbiguous); } /// TPResult - Used as the result value for functions whose purpose is to /// disambiguate C++ constructs by "tentatively parsing" them. enum class TPResult { True, False, Ambiguous, Error }; /// Based only on the given token kind, determine whether we know that /// we're at the start of an expression or a type-specifier-seq (which may /// be an expression, in C++). /// /// This routine does not attempt to resolve any of the trick cases, e.g., /// those involving lookup of identifiers. /// /// \returns \c TPR_true if this token starts an expression, \c TPR_false if /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot /// tell. TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind); /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a /// declaration specifier, TPResult::False if it is not, /// TPResult::Ambiguous if it could be either a decl-specifier or a /// function-style cast, and TPResult::Error if a parsing error was /// encountered. If it could be a braced C++11 function-style cast, returns /// BracedCastResult. /// Doesn't consume tokens. TPResult isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False, bool *InvalidAsDeclSpec = nullptr); /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or /// \c TPResult::Ambiguous, determine whether the decl-specifier would be /// a type-specifier other than a cv-qualifier. bool isCXXDeclarationSpecifierAType(); /// Determine whether the current token sequence might be /// '<' template-argument-list '>' /// rather than a less-than expression. TPResult isTemplateArgumentList(unsigned TokensToSkip); /// Determine whether an identifier has been tentatively declared as a /// non-type. Such tentative declarations should not be found to name a type /// during a tentative parse, but also should not be annotated as a non-type. bool isTentativelyDeclared(IdentifierInfo *II); // "Tentative parsing" functions, used for disambiguation. If a parsing error // is encountered they will return TPResult::Error. // Returning TPResult::True/False indicates that the ambiguity was // resolved and tentative parsing may stop. TPResult::Ambiguous indicates // that more tentative parsing is necessary for disambiguation. // They all consume tokens, so backtracking should be used after calling them. TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl); TPResult TryParseTypeofSpecifier(); TPResult TryParseProtocolQualifiers(); TPResult TryParsePtrOperatorSeq(); TPResult TryParseOperatorId(); TPResult TryParseInitDeclaratorList(); TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true, bool mayHaveDirectInit = false); TPResult TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr, bool VersusTemplateArg = false); TPResult TryParseFunctionDeclarator(); TPResult TryParseBracketDeclarator(); TPResult TryConsumeDeclarationSpecifier(); public: TypeResult ParseTypeName(SourceRange *Range = nullptr, DeclaratorContext Context = DeclaratorContext::TypeNameContext, AccessSpecifier AS = AS_none, Decl **OwnedType = nullptr, ParsedAttributes *Attrs = nullptr); private: void ParseBlockId(SourceLocation CaretLoc); /// Are [[]] attributes enabled? bool standardAttributesAllowed() const { const LangOptions &LO = getLangOpts(); return LO.DoubleSquareBracketAttributes; } // Check for the start of an attribute-specifier-seq in a context where an // attribute is not allowed. bool CheckProhibitedCXX11Attribute() { assert(Tok.is(tok::l_square)); if (!standardAttributesAllowed() || NextToken().isNot(tok::l_square)) return false; return DiagnoseProhibitedCXX11Attribute(); } bool DiagnoseProhibitedCXX11Attribute(); void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, SourceLocation CorrectLocation) { if (!standardAttributesAllowed()) return; if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) && Tok.isNot(tok::kw_alignas)) return; DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation); } void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, SourceLocation CorrectLocation); void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs, DeclSpec &DS, Sema::TagUseKind TUK); // FixItLoc = possible correct location for the attributes void ProhibitAttributes(ParsedAttributesWithRange &Attrs, SourceLocation FixItLoc = SourceLocation()) { if (Attrs.Range.isInvalid()) return; DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc); Attrs.clear(); } void ProhibitAttributes(ParsedAttributesViewWithRange &Attrs, SourceLocation FixItLoc = SourceLocation()) { if (Attrs.Range.isInvalid()) return; DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc); Attrs.clearListOnly(); } void DiagnoseProhibitedAttributes(const SourceRange &Range, SourceLocation FixItLoc); // Forbid C++11 and C2x attributes that appear on certain syntactic locations // which standard permits but we don't supported yet, for example, attributes // appertain to decl specifiers. void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs, unsigned DiagID); /// Skip C++11 and C2x attributes and return the end location of the /// last one. /// \returns SourceLocation() if there are no attributes. SourceLocation SkipCXX11Attributes(); /// Diagnose and skip C++11 and C2x attributes that appear in syntactic /// locations where attributes are not allowed. void DiagnoseAndSkipCXX11Attributes(); /// Parses syntax-generic attribute arguments for attributes which are /// known to the implementation, and adds them to the given ParsedAttributes /// list with the given attribute syntax. Returns the number of arguments /// parsed for the attribute. unsigned ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void MaybeParseGNUAttributes(Declarator &D, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.is(tok::kw___attribute)) { ParsedAttributes attrs(AttrFactory); SourceLocation endLoc; ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D); D.takeAttributes(attrs, endLoc); } } void MaybeParseGNUAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.is(tok::kw___attribute)) ParseGNUAttributes(attrs, endLoc, LateAttrs); } void ParseGNUAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr, LateParsedAttrList *LateAttrs = nullptr, Declarator *D = nullptr); void ParseGNUAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax, Declarator *D); IdentifierLoc *ParseIdentifierLoc(); unsigned ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void MaybeParseCXX11Attributes(Declarator &D) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) { ParsedAttributesWithRange attrs(AttrFactory); SourceLocation endLoc; ParseCXX11Attributes(attrs, &endLoc); D.takeAttributes(attrs, endLoc); } } void MaybeParseCXX11Attributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) { ParsedAttributesWithRange attrsWithRange(AttrFactory); ParseCXX11Attributes(attrsWithRange, endLoc); attrs.takeAllFrom(attrsWithRange); } } void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs, SourceLocation *endLoc = nullptr, bool OuterMightBeMessageSend = false) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier(false, OuterMightBeMessageSend)) ParseCXX11Attributes(attrs, endLoc); } void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs, SourceLocation *EndLoc = nullptr); void ParseCXX11Attributes(ParsedAttributesWithRange &attrs, SourceLocation *EndLoc = nullptr); /// Parses a C++11 (or C2x)-style attribute argument list. Returns true /// if this results in adding an attribute to the ParsedAttributes list. bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc); IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc); void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr) { if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square)) ParseMicrosoftAttributes(attrs, endLoc); } void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs); void ParseMicrosoftAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr); void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs, SourceLocation *End = nullptr) { const auto &LO = getLangOpts(); if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec)) ParseMicrosoftDeclSpecs(Attrs, End); } void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs, SourceLocation *End = nullptr); bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs); void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs); void DiagnoseAndSkipExtendedMicrosoftTypeAttributes(); SourceLocation SkipExtendedMicrosoftTypeAttributes(); void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs); void ParseBorlandTypeAttributes(ParsedAttributes &attrs); void ParseOpenCLKernelAttributes(ParsedAttributes &attrs); void ParseOpenCLQualifiers(ParsedAttributes &Attrs); /// Parses opencl_unroll_hint attribute if language is OpenCL v2.0 /// or higher. /// \return false if error happens. bool MaybeParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) { if (getLangOpts().OpenCL) return ParseOpenCLUnrollHintAttribute(Attrs); return true; } /// Parses opencl_unroll_hint attribute. /// \return false if error happens. bool ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs); void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs); VersionTuple ParseVersionTuple(SourceRange &Range); void ParseAvailabilityAttribute(IdentifierInfo &Availability, SourceLocation AvailabilityLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); Optional<AvailabilitySpec> ParseAvailabilitySpec(); ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc); void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated, SourceLocation ObjCBridgeRelatedLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseSwiftNewtypeAttribute(IdentifierInfo &SwiftNewtype, SourceLocation SwiftNewtypeLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseAttributeWithTypeArg(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseTypeofSpecifier(DeclSpec &DS); SourceLocation ParseDecltypeSpecifier(DeclSpec &DS); void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS, SourceLocation StartLoc, SourceLocation EndLoc); void ParseUnderlyingTypeSpecifier(DeclSpec &DS); void ParseAtomicSpecifier(DeclSpec &DS); ExprResult ParseAlignArgument(SourceLocation Start, SourceLocation &EllipsisLoc); void ParseAlignmentSpecifier(ParsedAttributes &Attrs, SourceLocation *endLoc = nullptr); VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const; VirtSpecifiers::Specifier isCXX11VirtSpecifier() const { return isCXX11VirtSpecifier(Tok); } void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface, SourceLocation FriendLoc); bool isCXX11FinalKeyword() const; /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to /// enter a new C++ declarator scope and exit it when the function is /// finished. class DeclaratorScopeObj { Parser &P; CXXScopeSpec &SS; bool EnteredScope; bool CreatedScope; public: DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss) : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {} void EnterDeclaratorScope() { assert(!EnteredScope && "Already entered the scope!"); assert(SS.isSet() && "C++ scope was not set!"); CreatedScope = true; P.EnterScope(0); // Not a decl scope. if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS)) EnteredScope = true; } ~DeclaratorScopeObj() { if (EnteredScope) { assert(SS.isSet() && "C++ scope was cleared ?"); P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS); } if (CreatedScope) P.ExitScope(); } }; /// ParseDeclarator - Parse and verify a newly-initialized declarator. void ParseDeclarator(Declarator &D); /// A function that parses a variant of direct-declarator. typedef void (Parser::*DirectDeclParseFunction)(Declarator&); void ParseDeclaratorInternal(Declarator &D, DirectDeclParseFunction DirectDeclParser); enum AttrRequirements { AR_NoAttributesParsed = 0, ///< No attributes are diagnosed. AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes. AR_GNUAttributesParsed = 1 << 1, AR_CXX11AttributesParsed = 1 << 2, AR_DeclspecAttributesParsed = 1 << 3, AR_AllAttributesParsed = AR_GNUAttributesParsed | AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed, AR_VendorAttributesParsed = AR_GNUAttributesParsed | AR_DeclspecAttributesParsed }; void ParseTypeQualifierListOpt( DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed, bool AtomicAllowed = true, bool IdentifierRequired = false, Optional<llvm::function_ref<void()>> CodeCompletionHandler = None); void ParseDirectDeclarator(Declarator &D); void ParseDecompositionDeclarator(Declarator &D); void ParseParenDeclarator(Declarator &D); void ParseFunctionDeclarator(Declarator &D, ParsedAttributes &attrs, BalancedDelimiterTracker &Tracker, bool IsAmbiguous, bool RequiresArg = false); bool ParseRefQualifier(bool &RefQualifierIsLValueRef, SourceLocation &RefQualifierLoc); bool isFunctionDeclaratorIdentifierList(); void ParseFunctionDeclaratorIdentifierList( Declarator &D, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo); void ParseParameterDeclarationClause( Declarator &D, ParsedAttributes &attrs, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo, SourceLocation &EllipsisLoc); void ParseBracketDeclarator(Declarator &D); void ParseMisplacedBracketDeclarator(Declarator &D); //===--------------------------------------------------------------------===// // C++ 7: Declarations [dcl.dcl] /// The kind of attribute specifier we have found. enum CXX11AttributeKind { /// This is not an attribute specifier. CAK_NotAttributeSpecifier, /// This should be treated as an attribute-specifier. CAK_AttributeSpecifier, /// The next tokens are '[[', but this is not an attribute-specifier. This /// is ill-formed by C++11 [dcl.attr.grammar]p6. CAK_InvalidAttributeSpecifier }; CXX11AttributeKind isCXX11AttributeSpecifier(bool Disambiguate = false, bool OuterMightBeMessageSend = false); void DiagnoseUnexpectedNamespace(NamedDecl *Context); DeclGroupPtrTy ParseNamespace(DeclaratorContext Context, SourceLocation &DeclEnd, SourceLocation InlineLoc = SourceLocation()); struct InnerNamespaceInfo { SourceLocation NamespaceLoc; SourceLocation InlineLoc; SourceLocation IdentLoc; IdentifierInfo *Ident; }; using InnerNamespaceInfoList = llvm::SmallVector<InnerNamespaceInfo, 4>; void ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs, unsigned int index, SourceLocation &InlineLoc, ParsedAttributes &attrs, BalancedDelimiterTracker &Tracker); Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context); Decl *ParseExportDeclaration(); DeclGroupPtrTy ParseUsingDirectiveOrDeclaration( DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs); Decl *ParseUsingDirective(DeclaratorContext Context, SourceLocation UsingLoc, SourceLocation &DeclEnd, ParsedAttributes &attrs); struct UsingDeclarator { SourceLocation TypenameLoc; CXXScopeSpec SS; UnqualifiedId Name; SourceLocation EllipsisLoc; void clear() { TypenameLoc = EllipsisLoc = SourceLocation(); SS.clear(); Name.clear(); } }; bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D); DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc, SourceLocation &DeclEnd, AccessSpecifier AS = AS_none); Decl *ParseAliasDeclarationAfterDeclarator( const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc, UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS, ParsedAttributes &Attrs, Decl **OwnedType = nullptr); Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd); Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, SourceLocation &DeclEnd); //===--------------------------------------------------------------------===// // C++ 9: classes [class] and C structs/unions. bool isValidAfterTypeSpecifier(bool CouldBeBitfield); void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, bool EnteringContext, DeclSpecContext DSC, ParsedAttributesWithRange &Attributes); void SkipCXXMemberSpecification(SourceLocation StartLoc, SourceLocation AttrFixitLoc, unsigned TagType, Decl *TagDecl); void ParseCXXMemberSpecification(SourceLocation StartLoc, SourceLocation AttrFixitLoc, ParsedAttributesWithRange &Attrs, unsigned TagType, Decl *TagDecl); ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction, SourceLocation &EqualLoc); bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize, LateParsedAttrList &LateAttrs); void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D, VirtSpecifiers &VS); DeclGroupPtrTy ParseCXXClassMemberDeclaration( AccessSpecifier AS, ParsedAttributes &Attr, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), ParsingDeclRAIIObject *DiagsFromTParams = nullptr); DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas( AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs, DeclSpec::TST TagType, Decl *Tag); void ParseConstructorInitializer(Decl *ConstructorDecl); MemInitResult ParseMemInitializer(Decl *ConstructorDecl); void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo, Decl *ThisDecl); //===--------------------------------------------------------------------===// // C++ 10: Derived classes [class.derived] TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc, SourceLocation &EndLocation); void ParseBaseClause(Decl *ClassDecl); BaseResult ParseBaseSpecifier(Decl *ClassDecl); AccessSpecifier getAccessSpecifierIfPresent() const; bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, IdentifierInfo *Name, SourceLocation NameLoc, bool EnteringContext, ParsedType ObjectType, UnqualifiedId &Id, bool AssumeTemplateId); bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, ParsedType ObjectType, UnqualifiedId &Result); //===--------------------------------------------------------------------===// // OpenMP: Directives and clauses. /// Parse clauses for '#pragma omp declare simd'. DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks, SourceLocation Loc); /// Parse clauses for '#pragma omp declare target'. DeclGroupPtrTy ParseOMPDeclareTargetClauses(); /// Parse '#pragma omp end declare target'. void ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind DKind, SourceLocation Loc); /// Parses declarative OpenMP directives. DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl( AccessSpecifier &AS, ParsedAttributesWithRange &Attrs, DeclSpec::TST TagType = DeclSpec::TST_unspecified, Decl *TagDecl = nullptr); /// Parse 'omp declare reduction' construct. DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS); /// Parses initializer for provided omp_priv declaration inside the reduction /// initializer. void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm); /// Parses 'omp declare mapper' directive. DeclGroupPtrTy ParseOpenMPDeclareMapperDirective(AccessSpecifier AS); /// Parses variable declaration in 'omp declare mapper' directive. TypeResult parseOpenMPDeclareMapperVarDecl(SourceRange &Range, DeclarationName &Name, AccessSpecifier AS = AS_none); /// Parses simple list of variables. /// /// \param Kind Kind of the directive. /// \param Callback Callback function to be called for the list elements. /// \param AllowScopeSpecifier true, if the variables can have fully /// qualified names. /// bool ParseOpenMPSimpleVarList( OpenMPDirectiveKind Kind, const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> & Callback, bool AllowScopeSpecifier); /// Parses declarative or executable directive. /// /// \param StmtCtx The context in which we're parsing the directive. StmtResult ParseOpenMPDeclarativeOrExecutableDirective(ParsedStmtContext StmtCtx); /// Parses clause of kind \a CKind for directive of a kind \a Kind. /// /// \param DKind Kind of current directive. /// \param CKind Kind of current clause. /// \param FirstClause true, if this is the first clause of a kind \a CKind /// in current directive. /// OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, bool FirstClause); /// Parses clause with a single expression of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind, bool ParseOnly); /// Parses simple clause of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly); /// Parses clause with a single expression and an additional argument /// of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind, bool ParseOnly); /// Parses clause without any additional arguments. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly = false); /// Parses clause with the list of variables of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, bool ParseOnly); public: /// Parses simple expression in parens for single-expression clauses of OpenMP /// constructs. /// \param RLoc Returned location of right paren. ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc); /// Data used for parsing list of variables in OpenMP clauses. struct OpenMPVarListDataTy { Expr *TailExpr = nullptr; SourceLocation ColonLoc; SourceLocation RLoc; CXXScopeSpec ReductionOrMapperIdScopeSpec; DeclarationNameInfo ReductionOrMapperId; OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown; OpenMPLinearClauseKind LinKind = OMPC_LINEAR_val; SmallVector<OpenMPMapModifierKind, OMPMapClause::NumberOfModifiers> MapTypeModifiers; SmallVector<SourceLocation, OMPMapClause::NumberOfModifiers> MapTypeModifiersLoc; OpenMPMapClauseKind MapType = OMPC_MAP_unknown; bool IsMapTypeImplicit = false; SourceLocation DepLinMapLoc; }; /// Parses clauses with list. bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, SmallVectorImpl<Expr *> &Vars, OpenMPVarListDataTy &Data); bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, ParsedType ObjectType, SourceLocation *TemplateKWLoc, UnqualifiedId &Result); /// Parses the mapper modifier in map, to, and from clauses. bool parseMapperModifier(OpenMPVarListDataTy &Data); /// Parses map-type-modifiers in map clause. /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list) /// where, map-type-modifier ::= always | close | mapper(mapper-identifier) bool parseMapTypeModifiers(OpenMPVarListDataTy &Data); private: //===--------------------------------------------------------------------===// // C++ 14: Templates [temp] // C++ 14.1: Template Parameters [temp.param] Decl *ParseDeclarationStartingWithTemplate(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); Decl *ParseTemplateDeclarationOrSpecialization(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS); Decl *ParseSingleDeclarationAfterTemplate( DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); bool ParseTemplateParameters(unsigned Depth, SmallVectorImpl<NamedDecl *> &TemplateParams, SourceLocation &LAngleLoc, SourceLocation &RAngleLoc); bool ParseTemplateParameterList(unsigned Depth, SmallVectorImpl<NamedDecl*> &TemplateParams); bool isStartOfTemplateTypeParameter(); NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position); NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position); NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position); NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position); void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc, SourceLocation CorrectLoc, bool AlreadyHasEllipsis, bool IdentifierHasName); void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc, Declarator &D); // C++ 14.3: Template arguments [temp.arg] typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList; bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc, bool ConsumeLastToken, bool ObjCGenericList); bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken, SourceLocation &LAngleLoc, TemplateArgList &TemplateArgs, SourceLocation &RAngleLoc); bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &TemplateName, bool AllowTypeAnnotation = true); void AnnotateTemplateIdTokenAsType(bool IsClassName = false); bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs); ParsedTemplateArgument ParseTemplateTemplateArgument(); ParsedTemplateArgument ParseTemplateArgument(); Decl *ParseExplicitInstantiation(DeclaratorContext Context, SourceLocation ExternLoc, SourceLocation TemplateLoc, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); //===--------------------------------------------------------------------===// // Modules DeclGroupPtrTy ParseModuleDecl(bool IsFirstDecl); Decl *ParseModuleImport(SourceLocation AtLoc); bool parseMisplacedModuleImport(); bool tryParseMisplacedModuleImport() { tok::TokenKind Kind = Tok.getKind(); if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end || Kind == tok::annot_module_include) return parseMisplacedModuleImport(); return false; } bool ParseModuleName( SourceLocation UseLoc, SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path, bool IsImport); //===--------------------------------------------------------------------===// // C++11/G++: Type Traits [Type-Traits.html in the GCC manual] ExprResult ParseTypeTrait(); /// Parse the given string as a type. /// /// This is a dangerous utility function currently employed only by API notes. /// It is not a general entry-point for safely parsing types from strings. /// /// \param typeStr The string to be parsed as a type. /// \param context The name of the context in which this string is being /// parsed, which will be used in diagnostics. /// \param includeLoc The location at which this parse was triggered. TypeResult parseTypeFromString(StringRef typeStr, StringRef context, SourceLocation includeLoc); //===--------------------------------------------------------------------===// // Embarcadero: Arary and Expression Traits ExprResult ParseArrayTypeTrait(); ExprResult ParseExpressionTrait(); //===--------------------------------------------------------------------===// // Preprocessor code-completion pass-through void CodeCompleteDirective(bool InConditional) override; void CodeCompleteInConditionalExclusion() override; void CodeCompleteMacroName(bool IsDefinition) override; void CodeCompletePreprocessorExpression() override; void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned ArgumentIndex) override; void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) override; void CodeCompleteNaturalLanguage() override; }; } // end namespace clang #endif
image.h
// ========================================================================== // // Copyright (c) 2017-2018 The University of Texas at Austin. // // 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. // // A copy of the License is included with this software in the file LICENSE. // // If your copy does not contain the License, you may obtain a copy of the // // License 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. // // // // ========================================================================== // #pragma once #include <cstring> #include <fstream> #include <iostream> #include <sstream> #include "glm/glm.hpp" #include "glog/logging.h" #include "pbrt/memory.h" #include "render/tile.h" #include "utils/profiler_util.h" namespace spray { class TileImage { public: TileImage() : buf_(nullptr), w_(0), h_(0) {} ~TileImage() { FreeAligned(buf_); } void resize(int w, int h) { FreeAligned(buf_); int tile_area = w * h; w_ = w; h_ = h; buf_ = AllocAligned<glm::vec4>(tile_area); } void add(int pixid, const float rgb[3]) { // buf[pixid] += glm::vec4(rgb[0], rgb[1], rgb[2], 0.f); buf_[pixid].r += rgb[0]; buf_[pixid].g += rgb[1]; buf_[pixid].b += rgb[2]; // buf[pixid].a = 0.000001f; } private: int w_, h_; glm::vec4* buf_; }; struct HdrImage { HdrImage() : w(0), h(0), buf(nullptr) {} ~HdrImage() { FreeAligned(buf); } void resize(int width, int height) { FreeAligned(buf); buf = AllocAligned<glm::vec4>(width * height); w = width; h = height; } int bytes() const { return w * h * sizeof(glm::vec4); } void clear() { memset(buf, 0, w * h * sizeof(glm::vec4)); } void clear(std::size_t size) { memset(buf, 0, size * sizeof(glm::vec4)); } void update(int pixid, const float rgb[3], float scale) { #ifdef SPRAY_GLOG_CHECK CHECK_LT(pixid, w * h); #endif buf[pixid] = glm::vec4(scale * rgb[0], scale * rgb[1], scale * rgb[2], 0.000001f); } void update(int pixid, const float rgb[3]) { buf[pixid] = glm::vec4(rgb[0], rgb[1], rgb[2], 0.000001f); } void add(int pixid, const float rgb[3], float scale) { #ifdef SPRAY_GLOG_CHECK CHECK_LT(pixid, w * h); #endif buf[pixid].r += (scale * rgb[0]); buf[pixid].g += (scale * rgb[1]); buf[pixid].b += (scale * rgb[2]); // buf[pixid].a = 0.000001f; } void add(int pixid, const float rgb[3], double scale) { #ifdef SPRAY_GLOG_CHECK CHECK_LT(pixid, w * h); #endif // buf[pixid] += // glm::vec4(scale * rgb[0], scale * rgb[1], scale * rgb[2], 0.f); buf[pixid].r += (scale * rgb[0]); buf[pixid].g += (scale * rgb[1]); buf[pixid].b += (scale * rgb[2]); // buf[pixid].a = 0.000001f; } void add(int pixid, const float rgb[3]) { #ifdef SPRAY_GLOG_CHECK CHECK_LT(pixid, w * h); #endif // buf[pixid] += glm::vec4(rgb[0], rgb[1], rgb[2], 0.f); buf[pixid].r += rgb[0]; buf[pixid].g += rgb[1]; buf[pixid].b += rgb[2]; // buf[pixid].a = 0.000001f; } void scale(const Tile& tile_in, int num_samples) { Tile tile = tile_in; int image_w = w; int pixid_offset, pixid; float scale = 1.f / num_samples; for (int y = tile.y; y < tile.y + tile.h; ++y) { pixid_offset = y * image_w; for (int x = tile.x; x < tile.x + tile.w; ++x) { pixid = pixid_offset + x; buf[pixid].r *= scale; buf[pixid].g *= scale; buf[pixid].b *= scale; } } } void parallelScale(const Tile& tile_in, int num_samples) { Tile tile = tile_in; #pragma omp for collapse(2) schedule(static, 1) for (int y = tile.y; y < tile.y + tile.h; ++y) { for (int x = tile.x; x < tile.x + tile.w; ++x) { int image_w = w; float scale = 1.f / num_samples; int pixid_offset = y * image_w; int pixid = pixid_offset + x; buf[pixid].r *= scale; buf[pixid].g *= scale; buf[pixid].b *= scale; } } } void set(int pixid, const float rgb[3]) { #ifdef SPRAY_GLOG_CHECK CHECK_LT(pixid, w * h); #endif // buf[pixid] += glm::vec4(rgb[0], rgb[1], rgb[2], 0.f); buf[pixid].r = rgb[0]; buf[pixid].g = rgb[1]; buf[pixid].b = rgb[2]; // buf[pixid].a = 0.000001f; } void set(int pixid, const glm::vec4& rgb) { buf[pixid] = rgb; } void composite() { int count = (w * h) << 2; #ifdef SPRAY_TIMING tStartMPI(TIMER_SYNC_IMAGE); #endif if (mpi::rank() == 0) { MPI_Reduce(MPI_IN_PLACE, buf, count, MPI_FLOAT, MPI_SUM, 0, MPI_COMM_WORLD); } else { MPI_Reduce(buf, nullptr, count, MPI_FLOAT, MPI_SUM, 0, MPI_COMM_WORLD); } #ifdef SPRAY_TIMING tStop(TIMER_SYNC_IMAGE); #endif } void writePpm(const char* filename) { std::stringstream header; header << "P3" << std::endl; header << w << " " << h << std::endl; header << "1023" << std::endl; std::ofstream file; file.open(filename, std::ios::out | std::ios::trunc); file << header.str(); for (int y = h - 1; y > -1; --y) { for (int x = 0; x < w; ++x) { int i = y * w + x; float r = glm::clamp(buf[i].r * 1023.f, 0.0f, 1023.0f); float g = glm::clamp(buf[i].g * 1023.f, 0.0f, 1023.0f); float b = glm::clamp(buf[i].b * 1023.f, 0.0f, 1023.0f); file << (unsigned)r << " " << (unsigned)g << " " << (unsigned)b << std::endl; } } file.close(); } static void writePpm(int width, int height, const char* filename, void* rgba) { std::stringstream header; header << "P3" << std::endl; header << width << " " << height << std::endl; header << "1023" << std::endl; std::ofstream file; file.open(filename, std::ios::out | std::ios::trunc); file << header.str(); float* rgba_buf = (float*)rgba; // for (unsigned int y = 0; y < height; ++y) { for (int y = height - 1; y > -1; --y) { int offset = width * y; for (int x = 0; x < width; ++x) { int i = (offset + x) << 2; float r = glm::clamp(rgba_buf[i] * 1023.f, 0.f, 1023.f); float g = glm::clamp(rgba_buf[i + 1] * 1023.f, 0.f, 1023.f); float b = glm::clamp(rgba_buf[i + 2] * 1023.f, 0.f, 1023.f); file << (unsigned)r << " " << (unsigned)g << " " << (unsigned)b << std::endl; } } file.close(); } int w; int h; glm::vec4* buf; }; } // namespace spray
GB_unaryop__minv_int8_fp64.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_int8_fp64 // op(A') function: GB_tran__minv_int8_fp64 // C type: int8_t // A type: double // cast: int8_t cij ; GB_CAST_SIGNED(cij,aij,8) // unaryop: cij = GB_IMINV_SIGNED (aij, 8) #define GB_ATYPE \ double #define GB_CTYPE \ int8_t // 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 = GB_IMINV_SIGNED (x, 8) ; // casting #define GB_CASTING(z, x) \ int8_t z ; GB_CAST_SIGNED(z,x,8) ; // 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_INT8 || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_int8_fp64 ( int8_t *restrict Cx, const double *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_int8_fp64 ( 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
fdtd-2d.pluto_ancc.seq_par.c
#include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <math.h> #define tmax T #define nx N #define ny N double ex[nx][ny +1]; double ey[nx +1][ny]; double hz[nx][ny]; void init_arrays() { int i, j; for (i=0; i<nx+1; i++) { for (j=0; j<ny; j++) { ey[i][j] = 0; } } for (i=0; i<nx; i++) { for (j=0; j<ny+1; j++) { ex[i][j] = 0; } } for (j=0; j<ny; j++) { ey[0][j] = ((double)j)/ny; } for (i=0; i<nx; i++) { for (j=0; j<ny; j++) { hz[i][j] = 0; } } } double rtclock() { struct timezone tzp; struct timeval tp; int stat; gettimeofday (&tp, &tzp); return (tp.tv_sec + tp.tv_usec*1.0e-6); } int main() { init_arrays(); double annot_t_start=0, annot_t_end=0, annot_t_total=0; int annot_i; for (annot_i=0; annot_i<REPS; annot_i++) { annot_t_start = rtclock(); register int i,j,k,t; register int c1t, c2t, c3t, c4t, c5t, c6t, c7t, c8t, c9t, c10t, c11t, c12t; register int newlb_c1, newlb_c2, newlb_c3, newlb_c4, newlb_c5, newlb_c6, newlb_c7, newlb_c8, newlb_c9, newlb_c10, newlb_c11, newlb_c12; register int newub_c1, newub_c2, newub_c3, newub_c4, newub_c5, newub_c6, newub_c7, newub_c8, newub_c9, newub_c10, newub_c11, newub_c12; #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)) int c1, c2, c3, c4, c5, c6, c7, c8, c9; register int lb, ub, lb1, ub1, lb2, ub2; /* Generated from PLuTo-produced CLooG file by CLooG v0.14.1 64 bits in 1.73s. */ for (c1=-1;c1<=floord(3*tmax+ny-3,64);c1++) { lb1=max(max(ceild(32*c1-63,96),ceild(32*c1-tmax+1,32)),0); ub1=min(min(floord(32*c1+31,32),floord(32*c1+ny+31,96)),floord(tmax+ny-1,64)); #pragma omp parallel for shared(c1,lb1,ub1) private(c2,c3,c4,c5,c6,c7,c8,c9) for (c2=lb1; c2<=ub1; c2++) { for (c3=max(max(max(max(max(max(ceild(32*c1-32*c2-7,8),0),ceild(-16*c1-80*c2-119,12)),ceild(4256*c1-8416*c2-3*tmax-4482,520)),ceild(64*c2-ny-6,8)),ceild(8*c1-456*c2-483,56)),ceild(424*c1-872*c2-483,56));c3<=min(min(floord(32*c1-32*c2+nx+31,8),floord(tmax+nx-1,8)),floord(64*c2+nx+62,8));c3++) { if ((c1 <= floord(32*c2+8*c3-nx,32)) && (c2 <= floord(8*c3-nx+ny,64)) && (c3 >= ceild(nx,8))) { for (c8=max(64*c2,8*c3-nx+1);c8<=min(8*c3-nx+ny,64*c2+63);c8++) { hz[nx-1][-8*c3+c8+nx-1]=hz[nx-1][-8*c3+c8+nx-1]-((double)(7))/10*(ey[1+nx-1][-8*c3+c8+nx-1]+ex[nx-1][1+-8*c3+c8+nx-1]-ex[nx-1][-8*c3+c8+nx-1]-ey[nx-1][-8*c3+c8+nx-1]) ; } } if ((c1 <= floord(96*c2-ny,32)) && (c2 >= max(ceild(8*c3-nx+ny+1,64),ceild(ny,64)))) { for (c9=max(64*c2-ny+1,8*c3);c9<=min(8*c3+7,64*c2+nx-ny);c9++) { hz[-64*c2+c9+ny-1][ny-1]=hz[-64*c2+c9+ny-1][ny-1]-((double)(7))/10*(ey[1+-64*c2+c9+ny-1][ny-1]+ex[-64*c2+c9+ny-1][1+ny-1]-ex[-64*c2+c9+ny-1][ny-1]-ey[-64*c2+c9+ny-1][ny-1]) ; } } if (c1 == c2+c3) { for (c7=max(max(32*c3,64*c2-ny+1),0);c7<=min(min(64*c2-1,8*c3+6),64*c2-ny+63);c7++) { for (c8=64*c2;c8<=c7+ny-1;c8++) { ey[0][-c7+c8]=c7 ; ex[0][-c7+c8]=ex[0][-c7+c8]-((double)(1))/2*(hz[0][-c7+c8]-hz[0][-c7+c8-1]) ; for (c9=c7+1;c9<=8*c3+7;c9++) { ey[-c7+c9][-c7+c8]=ey[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9-1][-c7+c8]) ; ex[-c7+c9][-c7+c8]=ex[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9][-c7+c8-1]) ; hz[-c7+c9-1][-c7+c8-1]=hz[-c7+c9-1][-c7+c8-1]-((double)(7))/10*(ey[1+-c7+c9-1][-c7+c8-1]+ex[-c7+c9-1][1+-c7+c8-1]-ex[-c7+c9-1][-c7+c8-1]-ey[-c7+c9-1][-c7+c8-1]) ; } } for (c9=c7+1;c9<=8*c3+7;c9++) { hz[-c7+c9-1][ny-1]=hz[-c7+c9-1][ny-1]-((double)(7))/10*(ey[1+-c7+c9-1][ny-1]+ex[-c7+c9-1][1+ny-1]-ex[-c7+c9-1][ny-1]-ey[-c7+c9-1][ny-1]) ; } } } if (c1 == c2+c3) { for (c7=max(max(64*c2,32*c3),0);c7<=min(8*c3+6,64*c2-ny+63);c7++) { ey[0][0]=c7 ; for (c9=c7+1;c9<=8*c3+7;c9++) { ey[-c7+c9][0]=ey[-c7+c9][0]-((double)(1))/2*(hz[-c7+c9][0]-hz[-c7+c9-1][0]) ; } for (c8=c7+1;c8<=c7+ny-1;c8++) { ey[0][-c7+c8]=c7 ; ex[0][-c7+c8]=ex[0][-c7+c8]-((double)(1))/2*(hz[0][-c7+c8]-hz[0][-c7+c8-1]) ; for (c9=c7+1;c9<=8*c3+7;c9++) { ey[-c7+c9][-c7+c8]=ey[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9-1][-c7+c8]) ; ex[-c7+c9][-c7+c8]=ex[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9][-c7+c8-1]) ; hz[-c7+c9-1][-c7+c8-1]=hz[-c7+c9-1][-c7+c8-1]-((double)(7))/10*(ey[1+-c7+c9-1][-c7+c8-1]+ex[-c7+c9-1][1+-c7+c8-1]-ex[-c7+c9-1][-c7+c8-1]-ey[-c7+c9-1][-c7+c8-1]) ; } } for (c9=c7+1;c9<=8*c3+7;c9++) { hz[-c7+c9-1][ny-1]=hz[-c7+c9-1][ny-1]-((double)(7))/10*(ey[1+-c7+c9-1][ny-1]+ex[-c7+c9-1][1+ny-1]-ex[-c7+c9-1][ny-1]-ey[-c7+c9-1][ny-1]) ; } } } if (c1 == c2+c3) { for (c7=max(max(0,32*c3),64*c2-ny+64);c7<=min(8*c3+6,64*c2-1);c7++) { for (c8=64*c2;c8<=64*c2+63;c8++) { ey[0][-c7+c8]=c7 ; ex[0][-c7+c8]=ex[0][-c7+c8]-((double)(1))/2*(hz[0][-c7+c8]-hz[0][-c7+c8-1]) ; for (c9=c7+1;c9<=8*c3+7;c9++) { ey[-c7+c9][-c7+c8]=ey[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9-1][-c7+c8]) ; ex[-c7+c9][-c7+c8]=ex[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9][-c7+c8-1]) ; hz[-c7+c9-1][-c7+c8-1]=hz[-c7+c9-1][-c7+c8-1]-((double)(7))/10*(ey[1+-c7+c9-1][-c7+c8-1]+ex[-c7+c9-1][1+-c7+c8-1]-ex[-c7+c9-1][-c7+c8-1]-ey[-c7+c9-1][-c7+c8-1]) ; } } } } if (c1 == c2+c3) { for (c7=max(max(max(64*c2,0),32*c3),64*c2-ny+64);c7<=min(8*c3+6,64*c2+62);c7++) { ey[0][0]=c7 ; for (c9=c7+1;c9<=8*c3+7;c9++) { ey[-c7+c9][0]=ey[-c7+c9][0]-((double)(1))/2*(hz[-c7+c9][0]-hz[-c7+c9-1][0]) ; } for (c8=c7+1;c8<=64*c2+63;c8++) { ey[0][-c7+c8]=c7 ; ex[0][-c7+c8]=ex[0][-c7+c8]-((double)(1))/2*(hz[0][-c7+c8]-hz[0][-c7+c8-1]) ; for (c9=c7+1;c9<=8*c3+7;c9++) { ey[-c7+c9][-c7+c8]=ey[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9-1][-c7+c8]) ; ex[-c7+c9][-c7+c8]=ex[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9][-c7+c8-1]) ; hz[-c7+c9-1][-c7+c8-1]=hz[-c7+c9-1][-c7+c8-1]-((double)(7))/10*(ey[1+-c7+c9-1][-c7+c8-1]+ex[-c7+c9-1][1+-c7+c8-1]-ex[-c7+c9-1][-c7+c8-1]-ey[-c7+c9-1][-c7+c8-1]) ; } } } } for (c7=max(max(max(64*c2-ny+1,8*c3-nx+1),0),32*c1-32*c2);c7<=min(min(min(min(64*c2-1,8*c3-nx+7),tmax-1),32*c1-32*c2+31),64*c2-ny+63);c7++) { for (c8=64*c2;c8<=c7+ny-1;c8++) { for (c9=8*c3;c9<=c7+nx-1;c9++) { ey[-c7+c9][-c7+c8]=ey[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9-1][-c7+c8]) ; ex[-c7+c9][-c7+c8]=ex[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9][-c7+c8-1]) ; hz[-c7+c9-1][-c7+c8-1]=hz[-c7+c9-1][-c7+c8-1]-((double)(7))/10*(ey[1+-c7+c9-1][-c7+c8-1]+ex[-c7+c9-1][1+-c7+c8-1]-ex[-c7+c9-1][-c7+c8-1]-ey[-c7+c9-1][-c7+c8-1]) ; } hz[nx-1][-c7+c8-1]=hz[nx-1][-c7+c8-1]-((double)(7))/10*(ey[1+nx-1][-c7+c8-1]+ex[nx-1][1+-c7+c8-1]-ex[nx-1][-c7+c8-1]-ey[nx-1][-c7+c8-1]) ; } for (c9=8*c3;c9<=c7+nx;c9++) { hz[-c7+c9-1][ny-1]=hz[-c7+c9-1][ny-1]-((double)(7))/10*(ey[1+-c7+c9-1][ny-1]+ex[-c7+c9-1][1+ny-1]-ex[-c7+c9-1][ny-1]-ey[-c7+c9-1][ny-1]) ; } } for (c7=max(max(max(64*c2,8*c3-nx+1),0),32*c1-32*c2);c7<=min(min(min(8*c3-nx+7,tmax-1),32*c1-32*c2+31),64*c2-ny+63);c7++) { for (c9=8*c3;c9<=c7+nx-1;c9++) { ey[-c7+c9][0]=ey[-c7+c9][0]-((double)(1))/2*(hz[-c7+c9][0]-hz[-c7+c9-1][0]) ; } for (c8=c7+1;c8<=c7+ny-1;c8++) { for (c9=8*c3;c9<=c7+nx-1;c9++) { ey[-c7+c9][-c7+c8]=ey[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9-1][-c7+c8]) ; ex[-c7+c9][-c7+c8]=ex[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9][-c7+c8-1]) ; hz[-c7+c9-1][-c7+c8-1]=hz[-c7+c9-1][-c7+c8-1]-((double)(7))/10*(ey[1+-c7+c9-1][-c7+c8-1]+ex[-c7+c9-1][1+-c7+c8-1]-ex[-c7+c9-1][-c7+c8-1]-ey[-c7+c9-1][-c7+c8-1]) ; } hz[nx-1][-c7+c8-1]=hz[nx-1][-c7+c8-1]-((double)(7))/10*(ey[1+nx-1][-c7+c8-1]+ex[nx-1][1+-c7+c8-1]-ex[nx-1][-c7+c8-1]-ey[nx-1][-c7+c8-1]) ; } for (c9=8*c3;c9<=c7+nx;c9++) { hz[-c7+c9-1][ny-1]=hz[-c7+c9-1][ny-1]-((double)(7))/10*(ey[1+-c7+c9-1][ny-1]+ex[-c7+c9-1][1+ny-1]-ex[-c7+c9-1][ny-1]-ey[-c7+c9-1][ny-1]) ; } } for (c7=max(max(max(32*c1-32*c2,0),8*c3-nx+1),64*c2-ny+64);c7<=min(min(min(32*c1-32*c2+31,tmax-1),64*c2-1),8*c3-nx+7);c7++) { for (c8=64*c2;c8<=64*c2+63;c8++) { for (c9=8*c3;c9<=c7+nx-1;c9++) { ey[-c7+c9][-c7+c8]=ey[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9-1][-c7+c8]) ; ex[-c7+c9][-c7+c8]=ex[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9][-c7+c8-1]) ; hz[-c7+c9-1][-c7+c8-1]=hz[-c7+c9-1][-c7+c8-1]-((double)(7))/10*(ey[1+-c7+c9-1][-c7+c8-1]+ex[-c7+c9-1][1+-c7+c8-1]-ex[-c7+c9-1][-c7+c8-1]-ey[-c7+c9-1][-c7+c8-1]) ; } hz[nx-1][-c7+c8-1]=hz[nx-1][-c7+c8-1]-((double)(7))/10*(ey[1+nx-1][-c7+c8-1]+ex[nx-1][1+-c7+c8-1]-ex[nx-1][-c7+c8-1]-ey[nx-1][-c7+c8-1]) ; } } for (c7=max(max(max(8*c3-nx+8,64*c2-ny+1),0),32*c1-32*c2);c7<=min(min(min(min(64*c2-1,8*c3-1),tmax-1),32*c1-32*c2+31),64*c2-ny+63);c7++) { for (c8=64*c2;c8<=c7+ny-1;c8++) { for (c9=8*c3;c9<=8*c3+7;c9++) { ey[-c7+c9][-c7+c8]=ey[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9-1][-c7+c8]) ; ex[-c7+c9][-c7+c8]=ex[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9][-c7+c8-1]) ; hz[-c7+c9-1][-c7+c8-1]=hz[-c7+c9-1][-c7+c8-1]-((double)(7))/10*(ey[1+-c7+c9-1][-c7+c8-1]+ex[-c7+c9-1][1+-c7+c8-1]-ex[-c7+c9-1][-c7+c8-1]-ey[-c7+c9-1][-c7+c8-1]) ; } } for (c9=8*c3;c9<=8*c3+7;c9++) { hz[-c7+c9-1][ny-1]=hz[-c7+c9-1][ny-1]-((double)(7))/10*(ey[1+-c7+c9-1][ny-1]+ex[-c7+c9-1][1+ny-1]-ex[-c7+c9-1][ny-1]-ey[-c7+c9-1][ny-1]) ; } } for (c7=max(max(max(max(64*c2,32*c1-32*c2),0),8*c3-nx+1),64*c2-ny+64);c7<=min(min(min(32*c1-32*c2+31,64*c2+62),tmax-1),8*c3-nx+7);c7++) { for (c9=8*c3;c9<=c7+nx-1;c9++) { ey[-c7+c9][0]=ey[-c7+c9][0]-((double)(1))/2*(hz[-c7+c9][0]-hz[-c7+c9-1][0]) ; } for (c8=c7+1;c8<=64*c2+63;c8++) { for (c9=8*c3;c9<=c7+nx-1;c9++) { ey[-c7+c9][-c7+c8]=ey[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9-1][-c7+c8]) ; ex[-c7+c9][-c7+c8]=ex[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9][-c7+c8-1]) ; hz[-c7+c9-1][-c7+c8-1]=hz[-c7+c9-1][-c7+c8-1]-((double)(7))/10*(ey[1+-c7+c9-1][-c7+c8-1]+ex[-c7+c9-1][1+-c7+c8-1]-ex[-c7+c9-1][-c7+c8-1]-ey[-c7+c9-1][-c7+c8-1]) ; } hz[nx-1][-c7+c8-1]=hz[nx-1][-c7+c8-1]-((double)(7))/10*(ey[1+nx-1][-c7+c8-1]+ex[nx-1][1+-c7+c8-1]-ex[nx-1][-c7+c8-1]-ey[nx-1][-c7+c8-1]) ; } } for (c7=max(max(max(64*c2,8*c3-nx+8),0),32*c1-32*c2);c7<=min(min(min(8*c3-1,tmax-1),32*c1-32*c2+31),64*c2-ny+63);c7++) { for (c9=8*c3;c9<=8*c3+7;c9++) { ey[-c7+c9][0]=ey[-c7+c9][0]-((double)(1))/2*(hz[-c7+c9][0]-hz[-c7+c9-1][0]) ; } for (c8=c7+1;c8<=c7+ny-1;c8++) { for (c9=8*c3;c9<=8*c3+7;c9++) { ey[-c7+c9][-c7+c8]=ey[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9-1][-c7+c8]) ; ex[-c7+c9][-c7+c8]=ex[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9][-c7+c8-1]) ; hz[-c7+c9-1][-c7+c8-1]=hz[-c7+c9-1][-c7+c8-1]-((double)(7))/10*(ey[1+-c7+c9-1][-c7+c8-1]+ex[-c7+c9-1][1+-c7+c8-1]-ex[-c7+c9-1][-c7+c8-1]-ey[-c7+c9-1][-c7+c8-1]) ; } } for (c9=8*c3;c9<=8*c3+7;c9++) { hz[-c7+c9-1][ny-1]=hz[-c7+c9-1][ny-1]-((double)(7))/10*(ey[1+-c7+c9-1][ny-1]+ex[-c7+c9-1][1+ny-1]-ex[-c7+c9-1][ny-1]-ey[-c7+c9-1][ny-1]) ; } } for (c7=max(max(8*c3,64*c2-ny+1),32*c1-32*c2);c7<=min(min(min(min(min(64*c2-1,tmax-1),32*c1-32*c2+31),8*c3+6),32*c3-1),64*c2-ny+63);c7++) { for (c8=64*c2;c8<=c7+ny-1;c8++) { ex[0][-c7+c8]=ex[0][-c7+c8]-((double)(1))/2*(hz[0][-c7+c8]-hz[0][-c7+c8-1]) ; for (c9=c7+1;c9<=8*c3+7;c9++) { ey[-c7+c9][-c7+c8]=ey[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9-1][-c7+c8]) ; ex[-c7+c9][-c7+c8]=ex[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9][-c7+c8-1]) ; hz[-c7+c9-1][-c7+c8-1]=hz[-c7+c9-1][-c7+c8-1]-((double)(7))/10*(ey[1+-c7+c9-1][-c7+c8-1]+ex[-c7+c9-1][1+-c7+c8-1]-ex[-c7+c9-1][-c7+c8-1]-ey[-c7+c9-1][-c7+c8-1]) ; } } for (c9=c7+1;c9<=8*c3+7;c9++) { hz[-c7+c9-1][ny-1]=hz[-c7+c9-1][ny-1]-((double)(7))/10*(ey[1+-c7+c9-1][ny-1]+ex[-c7+c9-1][1+ny-1]-ex[-c7+c9-1][ny-1]-ey[-c7+c9-1][ny-1]) ; } } /*@ begin Loop( transform Composite( permut = [['c7', 'c9', 'c8']], regtile = (['c7', 'c8', 'c9'],[3, 1, 1]), scalarreplace = (True, 'double'), vector = (True, ['ivdep','vector always'])) for (c7=max(max(max(32*c1-32*c2,0),8*c3-nx+8),64*c2-ny+64);c7<=min(min(min(tmax-1,32*c1-32*c2+31),64*c2-1),8*c3-1);c7++) { for (c8=64*c2;c8<=64*c2+63;c8++) { for (c9=8*c3;c9<=8*c3+7;c9++) { ey[-c7+c9][-c7+c8]=ey[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9-1][-c7+c8]) ; ex[-c7+c9][-c7+c8]=ex[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9][-c7+c8-1]) ; hz[-c7+c9-1][-c7+c8-1]=hz[-c7+c9-1][-c7+c8-1]-((double)(7))/10*(ey[1+-c7+c9-1][-c7+c8-1]+ex[-c7+c9-1][1+-c7+c8-1]-ex[-c7+c9-1][-c7+c8-1]-ey[-c7+c9-1][-c7+c8-1]) ; } } } ) @*/{ for (c7t=max(max(max(32*c1-32*c2,0),8*c3-nx+8),64*c2-ny+64); c7t<=min(min(min(tmax-1,32*c1-32*c2+31),64*c2-1),8*c3-1)-2; c7t=c7t+3) { for (c9=8*c3; c9<=8*c3+7; c9++ ) { register int cbv_1, cbv_2; cbv_1=64*c2; cbv_2=64*c2+63; #pragma ivdep #pragma vector always for (c8=cbv_1; c8<=cbv_2; c8++ ) { double scv_1, scv_2, scv_3, scv_4, scv_5, scv_6, scv_7, scv_8; double scv_9, scv_10, scv_11, scv_12; scv_1=hz[-(c7t+2)+c9-1][-(c7t+2)+c8-1]; scv_2=hz[-c7t+c9][-c7t+c8]; scv_3=ey[-(c7t+2)+c9][-(c7t+2)+c8]; scv_4=hz[-(c7t+2)+c9][-(c7t+2)+c8]; scv_5=hz[-c7t+c9-1][-c7t+c8-1]; scv_6=ex[-c7t+c9][-c7t+c8]; scv_7=ex[-(c7t+1)+c9][-(c7t+1)+c8]; scv_8=ey[-c7t+c9][-c7t+c8]; scv_9=ex[-(c7t+2)+c9][-(c7t+2)+c8]; scv_10=ey[-(c7t+1)+c9][-(c7t+1)+c8]; scv_11=hz[-(c7t+1)+c9][-(c7t+1)+c8]; scv_12=hz[-(c7t+1)+c9-1][-(c7t+1)+c8-1]; scv_8=scv_8-((double)(1))/2*(scv_2-hz[-c7t+c9-1][-c7t+c8]); scv_10=scv_10-((double)(1))/2*(scv_11-hz[-(c7t+1)+c9-1][-(c7t+1)+c8]); scv_3=scv_3-((double)(1))/2*(scv_4-hz[-(c7t+2)+c9-1][-(c7t+2)+c8]); scv_6=scv_6-((double)(1))/2*(scv_2-hz[-c7t+c9][-c7t+c8-1]); scv_7=scv_7-((double)(1))/2*(scv_11-hz[-(c7t+1)+c9][-(c7t+1)+c8-1]); scv_9=scv_9-((double)(1))/2*(scv_4-hz[-(c7t+2)+c9][-(c7t+2)+c8-1]); scv_5=scv_5-((double)(7))/10*(ey[1+-c7t+c9-1][-c7t+c8-1]+ex[-c7t+c9-1][1+-c7t+c8-1]-ex[-c7t+c9-1][-c7t+c8-1]-ey[-c7t+c9-1][-c7t+c8-1]); scv_12=scv_12-((double)(7))/10*(ey[1+-(c7t+1)+c9-1][-(c7t+1)+c8-1]+ex[-(c7t+1)+c9-1][1+-(c7t+1)+c8-1]-ex[-(c7t+1)+c9-1][-(c7t+1)+c8-1]-ey[-(c7t+1)+c9-1][-(c7t+1)+c8-1]); scv_1=scv_1-((double)(7))/10*(ey[1+-(c7t+2)+c9-1][-(c7t+2)+c8-1]+ex[-(c7t+2)+c9-1][1+-(c7t+2)+c8-1]-ex[-(c7t+2)+c9-1][-(c7t+2)+c8-1]-ey[-(c7t+2)+c9-1][-(c7t+2)+c8-1]); hz[-(c7t+2)+c9-1][-(c7t+2)+c8-1]=scv_1; ey[-(c7t+2)+c9][-(c7t+2)+c8]=scv_3; hz[-c7t+c9-1][-c7t+c8-1]=scv_5; ex[-c7t+c9][-c7t+c8]=scv_6; ex[-(c7t+1)+c9][-(c7t+1)+c8]=scv_7; ey[-c7t+c9][-c7t+c8]=scv_8; ex[-(c7t+2)+c9][-(c7t+2)+c8]=scv_9; ey[-(c7t+1)+c9][-(c7t+1)+c8]=scv_10; hz[-(c7t+1)+c9-1][-(c7t+1)+c8-1]=scv_12; } } } for (c7=c7t; c7<=min(min(min(tmax-1,32*c1-32*c2+31),64*c2-1),8*c3-1); c7=c7+1) { for (c9=8*c3; c9<=8*c3+7; c9++ ) { register int cbv_3, cbv_4; cbv_3=64*c2; cbv_4=64*c2+63; #pragma ivdep #pragma vector always for (c8=cbv_3; c8<=cbv_4; c8++ ) { double scv_13, scv_14, scv_15, scv_16; scv_13=ey[-c7+c9][-c7+c8]; scv_14=hz[-c7+c9][-c7+c8]; scv_15=ex[-c7+c9][-c7+c8]; scv_16=hz[-c7+c9-1][-c7+c8-1]; scv_13=scv_13-((double)(1))/2*(scv_14-hz[-c7+c9-1][-c7+c8]); scv_15=scv_15-((double)(1))/2*(scv_14-hz[-c7+c9][-c7+c8-1]); scv_16=scv_16-((double)(7))/10*(ey[1+-c7+c9-1][-c7+c8-1]+ex[-c7+c9-1][1+-c7+c8-1]-ex[-c7+c9-1][-c7+c8-1]-ey[-c7+c9-1][-c7+c8-1]); ey[-c7+c9][-c7+c8]=scv_13; ex[-c7+c9][-c7+c8]=scv_15; hz[-c7+c9-1][-c7+c8-1]=scv_16; } } } } /*@ end @*/ for (c7=max(max(64*c2,8*c3),32*c1-32*c2);c7<=min(min(min(min(tmax-1,32*c1-32*c2+31),8*c3+6),32*c3-1),64*c2-ny+63);c7++) { for (c9=c7+1;c9<=8*c3+7;c9++) { ey[-c7+c9][0]=ey[-c7+c9][0]-((double)(1))/2*(hz[-c7+c9][0]-hz[-c7+c9-1][0]) ; } for (c8=c7+1;c8<=c7+ny-1;c8++) { ex[0][-c7+c8]=ex[0][-c7+c8]-((double)(1))/2*(hz[0][-c7+c8]-hz[0][-c7+c8-1]) ; for (c9=c7+1;c9<=8*c3+7;c9++) { ey[-c7+c9][-c7+c8]=ey[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9-1][-c7+c8]) ; ex[-c7+c9][-c7+c8]=ex[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9][-c7+c8-1]) ; hz[-c7+c9-1][-c7+c8-1]=hz[-c7+c9-1][-c7+c8-1]-((double)(7))/10*(ey[1+-c7+c9-1][-c7+c8-1]+ex[-c7+c9-1][1+-c7+c8-1]-ex[-c7+c9-1][-c7+c8-1]-ey[-c7+c9-1][-c7+c8-1]) ; } } for (c9=c7+1;c9<=8*c3+7;c9++) { hz[-c7+c9-1][ny-1]=hz[-c7+c9-1][ny-1]-((double)(7))/10*(ey[1+-c7+c9-1][ny-1]+ex[-c7+c9-1][1+ny-1]-ex[-c7+c9-1][ny-1]-ey[-c7+c9-1][ny-1]) ; } } for (c7=max(max(max(max(64*c2,8*c3-nx+8),32*c1-32*c2),0),64*c2-ny+64);c7<=min(min(min(tmax-1,32*c1-32*c2+31),64*c2+62),8*c3-1);c7++) { for (c9=8*c3;c9<=8*c3+7;c9++) { ey[-c7+c9][0]=ey[-c7+c9][0]-((double)(1))/2*(hz[-c7+c9][0]-hz[-c7+c9-1][0]) ; } for (c8=c7+1;c8<=64*c2+63;c8++) { for (c9=8*c3;c9<=8*c3+7;c9++) { ey[-c7+c9][-c7+c8]=ey[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9-1][-c7+c8]) ; ex[-c7+c9][-c7+c8]=ex[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9][-c7+c8-1]) ; hz[-c7+c9-1][-c7+c8-1]=hz[-c7+c9-1][-c7+c8-1]-((double)(7))/10*(ey[1+-c7+c9-1][-c7+c8-1]+ex[-c7+c9-1][1+-c7+c8-1]-ex[-c7+c9-1][-c7+c8-1]-ey[-c7+c9-1][-c7+c8-1]) ; } } } for (c7=max(max(32*c1-32*c2,8*c3),64*c2-ny+64);c7<=min(min(min(min(32*c3-1,8*c3+6),32*c1-32*c2+31),tmax-1),64*c2-1);c7++) { for (c8=64*c2;c8<=64*c2+63;c8++) { ex[0][-c7+c8]=ex[0][-c7+c8]-((double)(1))/2*(hz[0][-c7+c8]-hz[0][-c7+c8-1]) ; for (c9=c7+1;c9<=8*c3+7;c9++) { ey[-c7+c9][-c7+c8]=ey[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9-1][-c7+c8]) ; ex[-c7+c9][-c7+c8]=ex[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9][-c7+c8-1]) ; hz[-c7+c9-1][-c7+c8-1]=hz[-c7+c9-1][-c7+c8-1]-((double)(7))/10*(ey[1+-c7+c9-1][-c7+c8-1]+ex[-c7+c9-1][1+-c7+c8-1]-ex[-c7+c9-1][-c7+c8-1]-ey[-c7+c9-1][-c7+c8-1]) ; } } } for (c7=max(max(max(64*c2,32*c1-32*c2),8*c3),64*c2-ny+64);c7<=min(min(min(min(32*c3-1,8*c3+6),64*c2+62),32*c1-32*c2+31),tmax-1);c7++) { for (c9=c7+1;c9<=8*c3+7;c9++) { ey[-c7+c9][0]=ey[-c7+c9][0]-((double)(1))/2*(hz[-c7+c9][0]-hz[-c7+c9-1][0]) ; } for (c8=c7+1;c8<=64*c2+63;c8++) { ex[0][-c7+c8]=ex[0][-c7+c8]-((double)(1))/2*(hz[0][-c7+c8]-hz[0][-c7+c8-1]) ; for (c9=c7+1;c9<=8*c3+7;c9++) { ey[-c7+c9][-c7+c8]=ey[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9-1][-c7+c8]) ; ex[-c7+c9][-c7+c8]=ex[-c7+c9][-c7+c8]-((double)(1))/2*(hz[-c7+c9][-c7+c8]-hz[-c7+c9][-c7+c8-1]) ; hz[-c7+c9-1][-c7+c8-1]=hz[-c7+c9-1][-c7+c8-1]-((double)(7))/10*(ey[1+-c7+c9-1][-c7+c8-1]+ex[-c7+c9-1][1+-c7+c8-1]-ex[-c7+c9-1][-c7+c8-1]-ey[-c7+c9-1][-c7+c8-1]) ; } } } if ((-c1 == -c2-c3) && (c1 <= floord(72*c3-57,64))) { ey[0][0]=64*c1-64*c3+63 ; for (c9=64*c1-64*c3+64;c9<=8*c3+7;c9++) { ey[-64*c1+64*c3+c9-63][0]=ey[-64*c1+64*c3+c9-63][0]-((double)(1))/2*(hz[-64*c1+64*c3+c9-63][0]-hz[-64*c1+64*c3+c9-63 -1][0]) ; } } if ((-c1 == -c2-c3) && (c1 >= ceild(72*c2-7,8)) && (c1 <= floord(72*c2+55,8))) { ey[0][0]=8*c1-8*c2+7 ; for (c8=8*c1-8*c2+8;c8<=min(64*c2+63,8*c1-8*c2+ny+6);c8++) { ey[0][-8*c1+8*c2+c8-7]=8*c1-8*c2+7 ; ex[0][-8*c1+8*c2+c8-7]=ex[0][-8*c1+8*c2+c8-7]-((double)(1))/2*(hz[0][-8*c1+8*c2+c8-7]-hz[0][-8*c1+8*c2+c8-7 -1]) ; } } if ((-c1 == -c2-c3) && (c1 <= 9*c2-1)) { for (c8=64*c2;c8<=min(64*c2+63,8*c1-8*c2+ny+6);c8++) { ey[0][-8*c1+8*c2+c8-7]=8*c1-8*c2+7 ; ex[0][-8*c1+8*c2+c8-7]=ex[0][-8*c1+8*c2+c8-7]-((double)(1))/2*(hz[0][-8*c1+8*c2+c8-7]-hz[0][-8*c1+8*c2+c8-7 -1]) ; } } if ((-c1 == -9*c2-7) && (-8*c1 == -9*c3+7)) { if ((64*c1+119)%9 == 0) { if ((64*c1+119)%9 == 0) { if ((64*c1+119)%9 == 0) { if ((8*c1+7)%9 == 0) { if ((-7*c1-14)%9 == 0) { if ((8*c1+7)%9 == 0) { if ((-7*c1-14)%9 == 0) { if ((64*c1+119)%9 == 0) { ey[0][0]=(64*c1+119)/9 ; } } } } } } } } } if ((c1 >= 3*c2+1) && (c2 <= min(min(floord(8*c3-57,64),floord(c3-2,2)),floord(tmax-64,64)))) { for (c9=max(64*c2+64,8*c3);c9<=min(8*c3+7,64*c2+nx+62);c9++) { ey[-64*c2+c9-63][0]=ey[-64*c2+c9-63][0]-((double)(1))/2*(hz[-64*c2+c9-63][0]-hz[-64*c2+c9-63 -1][0]) ; } } if ((c1 >= ceild(4*c2+c3-3,4)) && (c2 >= ceild(8*c3-55,64)) && (c3 >= 1) && (c3 <= floord(tmax-8,8))) { for (c8=max(64*c2,8*c3+8);c8<=min(64*c2+63,8*c3+ny+6);c8++) { ex[0][-8*c3+c8-7]=ex[0][-8*c3+c8-7]-((double)(1))/2*(hz[0][-8*c3+c8-7]-hz[0][-8*c3+c8-7 -1]) ; } } } } } annot_t_end = rtclock(); annot_t_total += annot_t_end - annot_t_start; } annot_t_total = annot_t_total / REPS; printf("%f\n", annot_t_total); return ((int) hz[0][0]); }
GB_unop__identity_int64_fc32.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 GBCUDA_DEV #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__identity_int64_fc32) // op(A') function: GB (_unop_tran__identity_int64_fc32) // C type: int64_t // A type: GxB_FC32_t // cast: int64_t cij = GB_cast_to_int64_t ((double) crealf (aij)) // unaryop: cij = aij #define GB_ATYPE \ GxB_FC32_t #define GB_CTYPE \ int64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ int64_t z = GB_cast_to_int64_t ((double) crealf (aij)) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int64_t z = GB_cast_to_int64_t ((double) crealf (aij)) ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT64 || GxB_NO_FC32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_int64_fc32) ( int64_t *Cx, // Cx and Ax may be aliased const GxB_FC32_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_FC32_t aij = Ax [p] ; int64_t z = GB_cast_to_int64_t ((double) crealf (aij)) ; Cx [p] = 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_FC32_t aij = Ax [p] ; int64_t z = GB_cast_to_int64_t ((double) crealf (aij)) ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_int64_fc32) ( 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
GB_unop__identity_int16_fp32.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__identity_int16_fp32) // op(A') function: GB (_unop_tran__identity_int16_fp32) // C type: int16_t // A type: float // cast: int16_t cij = GB_cast_to_int16_t ((double) (aij)) // unaryop: cij = aij #define GB_ATYPE \ float #define GB_CTYPE \ int16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ int16_t z = GB_cast_to_int16_t ((double) (aij)) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ float aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int16_t z = GB_cast_to_int16_t ((double) (aij)) ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT16 || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_int16_fp32) ( int16_t *Cx, // Cx and Ax may be aliased const float *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++) { float aij = Ax [p] ; int16_t z = GB_cast_to_int16_t ((double) (aij)) ; Cx [p] = 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 ; float aij = Ax [p] ; int16_t z = GB_cast_to_int16_t ((double) (aij)) ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_int16_fp32) ( 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
disconnect_utility.h
/* ============================================================================== KratosStructuralApplication A library based on: 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, Janosch Stascheit, Felix Nagel pooyan@cimne.upc.edu rrossi@cimne.upc.edu janosch.stascheit@rub.de nagel@sd.rub.de - CIMNE (International Center for Numerical Methods in Engineering), Gran Capita' s/n, 08034 Barcelona, Spain - Ruhr-University Bochum, Institute for Structural Mechanics, Germany 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 OWNERS. 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. ============================================================================== */ /* ********************************************************* * * Last Modified by: $Author: Nelson $ * Date: $Date: 2011-03-29 11:41:31 $ * Revision: $Revision: 1.1 $ * * ***********************************************************/ #if !defined(KRATOS_DISCONNECT_TRIANGLES_INCLUDED) #define KRATOS_DISCONNECT_TRIANGLES_INCLUDED //System includes #ifdef _OPENMP #include <omp.h> #endif #include "utilities/openmp_utils.h" //External includes #include "boost/smart_ptr.hpp" #include <cmath> //Project includes #include "includes/define.h" #include "containers/array_1d.h" #include "custom_utilities/sd_math_utils.h" #include "custom_utilities/joint.h" #include "includes/model_part.h" #include "includes/mesh.h" #include "geometries/geometry.h" #include "includes/element.h" #include "includes/variables.h" namespace Kratos { class Disconnect_Triangle_Utilities { public: typedef ModelPart::ConditionsContainerType ConditionsArrayType; typedef ModelPart::ElementsContainerType ElementsArrayType; typedef ModelPart::NodesContainerType NodesArrayType; typedef Joint<4> Joint2D; KRATOS_CLASS_POINTER_DEFINITION(Disconnect_Triangle_Utilities); Disconnect_Triangle_Utilities() {} Disconnect_Triangle_Utilities(ModelPart& model_part) {} ~Disconnect_Triangle_Utilities() {} //************************************************************************************** //************************************************************************************** std::vector<Joint2D>::iterator Begin() { return mJointsArray.begin(); } std::vector<Joint2D>::iterator End() { return mJointsArray.end(); } //************************************************************************************** //************************************************************************************** void CreateJoints(ModelPart& model_part, unsigned int& dimension) { Disconnect_Elements(model_part, dimension); //Disconnect_Elements_DG(model_part, dimension); } //************************************************************************************** //************************************************************************************** /// Desconecta los elementos y crea los joints void Disconnect_Elements(ModelPart& model_part, unsigned int& dimension) { KRATOS_TRY Disconnect(model_part); if(dimension==2) CreateJoints2D(model_part); KRATOS_CATCH("") } //************************************************************************************** //************************************************************************************** /// Desconecta los elementos para permirtir hacer DG. Solo elementos Triangulares void Disconnect_Elements_DG(ModelPart& model_part, unsigned int& dimension) { KRATOS_TRY Disconnect(model_part); if(dimension==2) CalculateNeighbourNodes2D(model_part); else CalculateNeighbourNodes3D(model_part); KRATOS_CATCH("") } //************************************************************************************** //************************************************************************************** private: /// Solo valido para triangulos void CalculateNeighbourNodes2D(ModelPart& model_part) { KRATOS_TRY ElementsArrayType& pElements = model_part.Elements(); vector<unsigned int> element_partition; int number_of_threads = OpenMPUtils::GetNumThreads(); OpenMPUtils::CreatePartition(number_of_threads, pElements.size(), element_partition); int count_2 = 0; int count_1 = 0; #pragma omp parallel for private(count_2, count_1) for(int k=0; k<number_of_threads; k++) { ElementsArrayType::iterator it_begin = pElements.ptr_begin()+element_partition[k]; ElementsArrayType::iterator it_end = pElements.ptr_begin()+element_partition[k+1]; for(ElementsArrayType::iterator it=it_begin; it!= it_end; it++) { if(it->GetProperties()[IS_DISCRETE]>=1.00) { WeakPointerVector< Node<3> >& neighb_nodes = it->GetValue(NEIGHBOUR_NODES); Element::GeometryType& geom_1 = it->GetGeometry(); neighb_nodes.clear(); neighb_nodes.resize(6); neighb_nodes(0) = geom_1(1); neighb_nodes(1) = geom_1(2); neighb_nodes(2) = geom_1(2); neighb_nodes(3) = geom_1(0); neighb_nodes(4) = geom_1(0); neighb_nodes(5) = geom_1(1); WeakPointerVector< Element >& neighb_elems = it->GetValue(NEIGHBOUR_ELEMENTS); count_1 = 0; count_2 = 0; for(WeakPointerVector< Element >::iterator neighb = neighb_elems.begin(); neighb!=neighb_elems.end(); ++neighb) { if(neighb->GetProperties()[IS_DISCRETE]>=1.00 && it->Id()!= neighb->Id()) { Element::GeometryType& geom_2 = neighb->GetGeometry(); const int& Id = it->Id(); count_2 = SearchEdge(neighb, Id); EdgesNodes(geom_2, count_2, count_1, neighb_nodes); } count_1++; } } } } KRATOS_CATCH("") } //************************************************************************************** //************************************************************************************** /// Solo valido para tetrahedros void CalculateNeighbourNodes3D(ModelPart& model_part) { KRATOS_TRY ElementsArrayType& pElements = model_part.Elements(); vector<unsigned int> element_partition; int number_of_threads = OpenMPUtils::GetNumThreads(); OpenMPUtils::CreatePartition(number_of_threads, pElements.size(), element_partition); int count_2 = 0; int count_1 = 0; #pragma omp parallel for private(count_2, count_1) for(int k=0; k<number_of_threads; k++) { ElementsArrayType::iterator it_begin = pElements.ptr_begin()+element_partition[k]; ElementsArrayType::iterator it_end = pElements.ptr_begin()+element_partition[k+1]; for(ElementsArrayType::iterator it=it_begin; it!= it_end; it++) { if(it->GetProperties()[IS_DISCRETE]>=1.00) { WeakPointerVector< Node<3> >& neighb_nodes = it->GetValue(NEIGHBOUR_NODES); Element::GeometryType& geom_1 = it->GetGeometry(); neighb_nodes.clear(); neighb_nodes.resize(12); /// usando regla de mano derecha //face 1 of neigh in 0 neighb_nodes(0) = geom_1(1); neighb_nodes(1) = geom_1(3); neighb_nodes(2) = geom_1(2); //face 2 of neigh in 1 neighb_nodes(3) = geom_1(0); neighb_nodes(4) = geom_1(2); neighb_nodes(5) = geom_1(3); //face 3 of neigh in 2 neighb_nodes(6) = geom_1(0); neighb_nodes(7) = geom_1(3); neighb_nodes(8) = geom_1(1); //face 4 of neigh in 3 neighb_nodes(9) = geom_1(0); neighb_nodes(10) = geom_1(1); neighb_nodes(11) = geom_1(2); WeakPointerVector< Element >& neighb_elems = it->GetValue(NEIGHBOUR_ELEMENTS); count_1 = 0; count_2 = 0; for(WeakPointerVector< Element >::iterator neighb = neighb_elems.begin(); neighb!=neighb_elems.end(); ++neighb) { if(neighb->GetProperties()[IS_DISCRETE]>=1.00 && it->Id()!= neighb->Id()) { Element::GeometryType& geom_2 = neighb->GetGeometry(); const int& Id = it->Id(); count_2 = SearchEdge(neighb, Id); EdgesNodes3D(geom_1, geom_2, count_1, count_2, neighb_nodes); } count_1++; } } } } KRATOS_CATCH("") } //************************************************************************************** //************************************************************************************** /// Separate triangle and tetrahedra elements creating new nodes void Disconnect(ModelPart& model_part) { KRATOS_TRY NodesArrayType& pNodes = model_part.Nodes(); unsigned int New_Id = pNodes.size(); NodesArrayType New_pNodes; //NodesArrayType::iterator i_begin = pNodes.begin(); //NodesArrayType::iterator i_end = pNodes.end(); const int dis = pNodes.end() - pNodes.begin(); std::size_t i = 0; ModelPart::NodeIterator inode = model_part.Nodes().begin() + i; std::cout<<std::endl; std::cout<< "DUPLICATING NODES IN MODEL PART"<< std::endl; while(inode!= model_part.Nodes().begin() + dis) { inode = model_part.Nodes().begin() + i; WeakPointerVector< Element >& neighb_elems = inode->GetValue(NEIGHBOUR_ELEMENTS); if(neighb_elems.size()!=0) { for(WeakPointerVector<Element>::iterator ielem = neighb_elems.begin(); ielem!=neighb_elems.end()-1; ielem++) { if(ielem->GetProperties()[IS_DISCRETE]>=1.00) { inode = model_part.Nodes().begin() + i; Element::GeometryType& geom = ielem->GetGeometry(); for(unsigned int j=0; j<geom.size(); j++) { if(geom(j)->Id()==inode->Id()) { New_Id++; Create_New_Node(model_part,New_Id, geom(j)); break; } } inode = model_part.Nodes().begin() + i; } } } i++; inode = model_part.Nodes().begin() + i; } std::cout<< "DUPLICATING NODES IN MODEL PART FINISH" << std::endl; KRATOS_CATCH("") } //************************************************************************************** //************************************************************************************** void CreateJoints2D(ModelPart& model_part) { KRATOS_TRY ElementsArrayType& pElements = model_part.Elements(); unsigned int count = 0; unsigned int count_2 = 0; Joint2D rJoint; vector<unsigned int> element_partition; ElementsArrayType::iterator it_begin = pElements.ptr_begin(); ElementsArrayType::iterator it_end = pElements.ptr_end(); int number_of_threads = OpenMPUtils::GetNumThreads(); OpenMPUtils::CreatePartition(number_of_threads, pElements.size(), element_partition); #pragma omp parallel for for(int k=0; k<number_of_threads; k++) { ElementsArrayType::iterator it_begin=pElements.ptr_begin()+element_partition[k]; ElementsArrayType::iterator it_end=pElements.ptr_begin()+element_partition[k+1]; for (ElementsArrayType::iterator it= it_begin; it!=it_end; ++it) it->Set(ACTIVE, true); } for (ElementsArrayType::iterator it= it_begin; it!=it_end; ++it) { WeakPointerVector< Condition >& neighb_cond = it->GetValue(NEIGHBOUR_CONDITIONS); if(neighb_cond.size()!=0) { for(WeakPointerVector< Condition >::iterator rcond = neighb_cond.begin(); rcond!=neighb_cond.end(); ++rcond) { WeakPointerVector< Element >& neighb_elem_c = rcond->GetValue(NEIGHBOUR_ELEMENTS); neighb_elem_c.push_back(*(it.base())); } } if(it->GetProperties()[IS_DISCRETE]>=1.00) { count = 0; Element::GeometryType& geom_1 = it->GetGeometry(); WeakPointerVector< Element >& neighb_elems = it->GetValue(NEIGHBOUR_ELEMENTS); for(WeakPointerVector< Element >::iterator neighb = neighb_elems.begin(); neighb!=neighb_elems.end(); ++neighb) { bool neighb_is_active = true; if( neighb->IsDefined(ACTIVE) ) neighb_is_active = neighb->Is(ACTIVE); if(neighb->GetProperties()[IS_DISCRETE]>=1.00 && neighb_is_active && it->Id()!= neighb->Id()) { TheNodes(geom_1, count, 0, 1, rJoint); Element::GeometryType& geom_2 = neighb->GetGeometry(); const unsigned int& Id = it->Id(); count_2 = SearchEdge(neighb, Id); TheNodes(geom_2, count_2, 2, 3, rJoint); mJointsArray.push_back(rJoint); it->Set(ACTIVE, false); } count++; } } } /// Check the conditions ConditionsArrayType& pConditions = model_part.Conditions(); for(ConditionsArrayType::iterator rcond = pConditions.begin(); rcond!=pConditions.end(); ++rcond) { CheckConditions(rcond); } KRATOS_CATCH("") } //************************************************************************************** //************************************************************************************** /// Sirve para actulizar los nodos de las condiciones cuando son duplicados solo en condiciones de linea void CheckConditions(ConditionsArrayType::iterator& rcond) { int a = 0; int b = 1; double check = 0.00; const double toler = 1E-8; a = 0; b = 1; Condition::GeometryType& geom_cond = rcond->GetGeometry(); Element::Pointer relem = (rcond->GetValue(NEIGHBOUR_ELEMENTS))(0).lock(); Element::GeometryType& geom_elem = relem->GetGeometry(); array_1d<double,3> cond = geom_cond.GetPoint(1) - geom_cond.GetPoint(0); array_1d<double,3> elem; noalias(cond) = (1.00/norm_2(cond)) * cond; for(unsigned int i = 0; i<geom_elem.size(); i++) { if(i==2) { b = 0; a = 2; } elem = geom_elem.GetPoint(b) - geom_elem.GetPoint(a); noalias(elem) = (1.00/norm_2(elem)) * elem; check = std::fabs(inner_prod(elem, cond)); if( std::fabs(check-1.00)<toler ) break; b++; a++; } /// Las condiciones se nombran contrario a las manecillas del reloj geom_cond(0) = geom_elem(b); geom_cond(1) = geom_elem(a); } //************************************************************************************** //************************************************************************************** int SearchEdge(WeakPointerVector<Element>::iterator& this_elem, const unsigned int& Id) { int count = 0; WeakPointerVector< Element >& neighb_elems = this_elem->GetValue(NEIGHBOUR_ELEMENTS); for(WeakPointerVector<Element>::iterator ielem = neighb_elems.begin(); ielem!=neighb_elems.end(); ++ielem) { if(ielem->Id()!=Id) { count ++; } else break; } return count; } //************************************************************************************** //************************************************************************************** ///Subrutina para tener los nodos correspondientes segun DG en 2D void EdgesNodes(const Element::GeometryType& geom, const int& count_2, const int& count_1, WeakPointerVector< Node<3> >& neighb_nodes) { int i, j; if(count_1==0) { i = 0; j = 1; } if(count_1==1) { i = 2; j = 3; } if(count_1==2) { i = 4; j = 5; } if(count_2==0) { neighb_nodes(i) = geom(2); neighb_nodes(j) = geom(1); } else if (count_2==1) { neighb_nodes(i) = geom(0); neighb_nodes(j) = geom(2); } else { neighb_nodes(i) = geom(1); neighb_nodes(j) = geom(0); } } //************************************************************************************** //************************************************************************************** ///Subrutina para tener los nodos correspondientes segun DG en 2D void EdgesNodes3D(const Element::GeometryType& geom_1, const Element::GeometryType& geom_2, const int& count_1, const int& count_2, WeakPointerVector< Node<3> >& neighb_nodes) { int i = 0, j = 0, k = 0; array_1d<int,3> a; array_1d<int,3> c; array_1d<double,3> diff = ZeroVector(3); if(count_1==0) { i = 0; j = 1; k = 2; c[0] = 1; c[1] = 3; c[2] = 2; } else if(count_1==1) { i = 3; j = 4; k = 5; c[0] = 0; c[1] = 2; c[2] = 3; } else if(count_1==2) { i = 6; j = 7; k = 8; c[0] = 0; c[1] = 3; c[2] = 1; } else { i = 9; j = 10; k = 11; c[0] = 0; c[1] = 1; c[2] = 2; } array_1d<int,3> b; b[0] = i; b[1] = j; b[2] = k; if(count_2==0) { a[0] = 1; a[1] = 3; a[2] = 2; for(int l = 0; l<3; l++) { for(int m=0; m<3; m++) { noalias(diff) = geom_1[c[l]] - geom_2[a[m]]; if(inner_prod(diff, diff)<1E-9) { neighb_nodes(b[l]) = geom_2(a[m]); break; } } } } else if (count_2==1) { a[0] = 0; a[1] = 2; a[2] = 3; for(int l = 0; l<3; l++) { for(int m=0; m<3; m++) { noalias(diff) = geom_1[c[l]] - geom_2[a[m]]; // std::fabs(inner_prod(diff, diff)); if(inner_prod(diff, diff)<1E-9) { neighb_nodes(b[l]) = geom_2(a[m]); break; } } } } else if(count_2==2) { a[0] = 0; a[1] = 3; a[2] = 1; for(int l = 0; l<3; l++) { for(int m=0; m<3; m++) { noalias(diff) = geom_1[c[l]] - geom_2[a[m]]; // std::fabs(inner_prod(diff, diff)); if(inner_prod(diff, diff)<1E-9) { neighb_nodes(b[l]) = geom_2(a[m]); break; } } } } else { a[0] = 0; a[1] = 1; a[2] = 2; for(int l = 0; l<3; l++) { for(int m=0; m<3; m++) { noalias(diff) = geom_1[c[l]] - geom_2[a[m]]; // std::fabs(inner_prod(diff, diff)); if(inner_prod(diff, diff)<1E-9) { neighb_nodes(b[l]) = geom_2(a[m]); break; } } } } } //************************************************************************************** //************************************************************************************** void TheNodes(const Element::GeometryType& geom, const int& count, const int& i, const int& j, Joint2D& rJoint) { if(count==0) { rJoint.InsertNode(i, geom(1)); rJoint.InsertNode(j, geom(2)); } else if (count==1) { rJoint.InsertNode(i, geom(2)); rJoint.InsertNode(j, geom(0)); } else if (count==2) { rJoint.InsertNode(i, geom(0)); rJoint.InsertNode(j, geom(1)); } } ///************************************************************************************************ ///************************************************************************************************ void Create_New_Node(ModelPart& this_model_part, unsigned int& New_Id, Node<3>::Pointer& pNode) { //node to get the DOFs from int step_data_size = this_model_part.GetNodalSolutionStepDataSize(); array_1d<double, 3 > & Coord = pNode->Coordinates(); Node < 3 > ::DofsContainerType& reference_dofs = (this_model_part.NodesBegin())->GetDofs(); Node<3>::Pointer pnode = this_model_part.CreateNewNode(New_Id, Coord[0], Coord[1], Coord[2]); pnode->SetBufferSize(this_model_part.NodesBegin()->GetBufferSize()); //generating the dofs for (Node < 3 > ::DofsContainerType::iterator iii = reference_dofs.begin(); iii != reference_dofs.end(); iii++) { Node < 3 > ::DofType& rDof = *iii; Node < 3 > ::DofType::Pointer p_new_dof = pnode->pAddDof(rDof); if (pNode->IsFixed(iii->GetVariable()) == true) (p_new_dof)->FixDof(); else { (p_new_dof)->FreeDof(); } } unsigned int buffer_size = pnode->GetBufferSize(); for (unsigned int step = 0; step < buffer_size; step++) { double* step_data = pnode->SolutionStepData().Data(step); double* old_node_data = pNode->SolutionStepData().Data(step); //copying this data in the position of the vector we are interested in for (signed int j = 0; j < step_data_size; j++) { step_data[j] = old_node_data[j]; } } const array_1d<double, 3 > & disp = pnode->FastGetSolutionStepValue(DISPLACEMENT); pnode->X0() = pnode->X() - disp[0]; pnode->Y0() = pnode->Y() - disp[1]; pnode->Z0() = pnode->Z() - disp[2]; array_1d<double, 3 > & vel_old = pNode->FastGetSolutionStepValue(VELOCITY); array_1d<double, 3 > & vel_new = pnode->FastGetSolutionStepValue(VELOCITY); vel_new = vel_old; const array_1d<double, 3 > & accel_old = pNode->FastGetSolutionStepValue(ACCELERATION); array_1d<double, 3 > & accel_new = pnode->FastGetSolutionStepValue(ACCELERATION); accel_new = accel_old; pNode = pnode; } //************************************************************************************** //************************************************************************************** private: std::vector<Joint2D> mJointsArray; }; }//namespace Kratos. #endif /*KRATOS_DISCONNECT_TRIANGLES*/
BenchUtils.h
/* * Copyright (c) Facebook, Inc. and its affiliates. * All rights reserved. * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <chrono> #include <vector> #ifdef _OPENMP #include <omp.h> #endif #include "./AlignedVec.h" namespace fbgemm { template <typename T> void randFill(aligned_vector<T>& vec, T low, T high); aligned_vector<float> getRandomSparseVector( unsigned size, float fractionNonZeros = 1.0); void llc_flush(std::vector<char>& llc); int fbgemm_get_num_threads(); int fbgemm_get_thread_num(); /** * @param llc if not nullptr, flush llc */ template <class Fn> double measureWithWarmup( Fn&& fn, int warmupIterations, int measuredIterations, std::vector<char>* llc = nullptr, bool useOpenMP = false) { for (int i = 0; i < warmupIterations; ++i) { if (llc) { llc_flush(*llc); } fn(); } double ttot = 0.0; #ifdef _OPENMP #pragma omp parallel if (useOpenMP) #endif for (int i = 0; i < measuredIterations; ++i) { int thread_id = 0; std::chrono::time_point<std::chrono::high_resolution_clock> start, end; #ifdef _OPENMP if (useOpenMP) { thread_id = omp_get_thread_num(); } #endif if (llc && thread_id == 0) { llc_flush(*llc); } #ifdef _OPENMP if (useOpenMP) { #pragma omp barrier } #endif start = std::chrono::high_resolution_clock::now(); fn(); end = std::chrono::high_resolution_clock::now(); auto dur = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start); if (thread_id == 0) { // TODO: measure load imbalance ttot += dur.count(); } } return ttot / 1e9 / measuredIterations; } } // namespace fbgemm
parallel-simple2.c
/* * parallel-simple2.c -- Archer testcase */ //===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // // See tools/archer/LICENSE.txt for details. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // RUN: %libarcher-compile-and-run | FileCheck %s // REQUIRES: tsan #include <omp.h> #include <stdio.h> int main(int argc, char *argv[]) { int var = 0; // Create team of threads so that there is no implicit happens before // when creating the thread. #pragma omp parallel num_threads(2) {} var++; #pragma omp parallel num_threads(2) shared(var) { if (omp_get_thread_num() == 1) { var++; } } // implicit barrier fprintf(stderr, "DONE\n"); int error = (var != 2); return error; } // CHECK-NOT: ThreadSanitizer: data race // CHECK-NOT: ThreadSanitizer: reported // CHECK: DONE
horn_schunck_pyramidal.c
// This program is free software: you can use, modify and/or redistribute it // under the terms of the simplified BSD License. You should have received a // copy of this license along this program. If not, see // <http://www.opensource.org/licenses/bsd-license.html>. // // Copyright (C) 2012, Javier Sánchez Pérez <jsanchez@dis.ulpgc.es> // All rights reserved. #ifndef HORN_SCHUNCK_PYRAMIDAL_C #define HORN_SCHUNCK_PYRAMIDAL_C #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include "mask.c" #include "zoom.c" #include "xmalloc.c" #define SOR_EXTRAPOLATION_PARAMETER 1.9 #define INPUT_PRESMOOTHING_SIGMA 0.8 /** * * Function to compute the SOR iteration at a given position * (SOR = Successive Over-Relaxation) * */ static float sor_iteration( const float *Au, // constant part of the numerator of u const float *Av, // constant part of the numerator of v const float *Du, // denominator of u const float *Dv, // denominator of v const float *D, // constant part of the numerator float *u, // x component of the flow float *v, // y component of the flow const float al, // alpha smoothness parameter const int p, // current position const int p1, // up-left neighbor const int p2, // up-right neighbor const int p3, // bottom-left neighbor const int p4, // bottom-right neighbor const int p5, // up neighbor const int p6, // left neighbor const int p7, // bottom neighbor const int p8 // right neighbor ) { // set the SOR extrapolation parameter const float w = SOR_EXTRAPOLATION_PARAMETER; // compute the divergence const float ula = 1./12. * (u[p1] + u[p2] + u[p3] + u[p4]) + 1./6. * (u[p5] + u[p6] + u[p7] + u[p8]); const float vla = 1./12. * (v[p1] + v[p2] + v[p3] + v[p4]) + 1./6. * (v[p5] + v[p6] + v[p7] + v[p8]); // store the previous values const float uk = u[p]; const float vk = v[p]; // update the flow u[p] = (1.0 - w) * uk + w * (Au[p] - D[p] * v[p] + al * ula) / Du[p]; v[p] = (1.0 - w) * vk + w * (Av[p] - D[p] * u[p] + al * vla) / Dv[p]; // return the convergence error return (u[p] - uk) * (u[p] - uk) + (v[p] - vk) * (v[p] - vk); } /** * * Horn & Schunck method for optical flow estimation at a single scale * */ void horn_schunck_optical_flow( const float *I1, // source image const float *I2, // target image float *u, // x component of optical flow float *v, // y component of optical flow const int nx, // image width const int ny, // image height const float alpha, // smoothing parameter const int warps, // number of warpings per scale const float TOL, // stopping criterion threshold const int maxiter, // maximum number of iterations const bool verbose // switch on messages ) { if (verbose) fprintf(stderr, "Single-scale Horn-Schunck of a %dx%d " "image\n\ta=%g nw=%d eps=%g mi=%d v=%d\n", nx, ny, alpha, warps, TOL, maxiter, verbose); const int size = nx * ny; const float alpha2 = alpha * alpha; //allocate memory int sf = sizeof(float); float *I2x = xmalloc(size * sf); // x derivative of I2 float *I2y = xmalloc(size * sf); // y derivative of I2 float *I2w = xmalloc(size * sf); // warping of I2 float *I2wx = xmalloc(size * sf); // warping of I2x float *I2wy = xmalloc(size * sf); // warping of I2y float *Au = xmalloc(size * sf); // constant part of numerator of u float *Av = xmalloc(size * sf); // constant part of numerator of v float *Du = xmalloc(size * sf); // denominator of u float *Dv = xmalloc(size * sf); // denominator of v float *D = xmalloc(size * sf); // common numerator of u and v // compute the gradient of the second image gradient(I2, I2x, I2y, nx, ny); // iterative approximation to the Taylor expansions for(int n = 0; n < warps; n++) { if(verbose) fprintf(stderr, "Warping %d:", n); // warp the second image and its derivatives bicubic_interpolation_warp(I2, u, v, I2w, nx, ny, true); bicubic_interpolation_warp(I2x, u, v, I2wx, nx, ny, true); bicubic_interpolation_warp(I2y, u, v, I2wy, nx, ny, true); // store the constant parts of the system for(int i = 0; i < size; i++) { const float I2wl = I2wx[i] * u[i] + I2wy[i] * v[i]; const float dif = I1[i] - I2w[i] + I2wl; Au[i] = dif * I2wx[i]; Av[i] = dif * I2wy[i]; Du[i] = I2wx[i] * I2wx[i] + alpha2; Dv[i] = I2wy[i] * I2wy[i] + alpha2; D[i] = I2wx[i] * I2wy[i]; } int niter = 0; float error = 1000; // iterations of the SOR numerical scheme while(error > TOL && niter < maxiter) { niter++; error = 0; //process the central part of the optical flow #pragma omp parallel for reduction(+:error) for(int i = 1; i < ny-1; i++) for(int j = 1; j < nx-1; j++) { const int k = i * nx + j; error += sor_iteration( Au, Av, Du, Dv, D, u, v, alpha2, k, k-nx-1, k-nx+1, k+nx-1, k+nx+1, k-nx, k-1, k+nx, k+1 ); } // process the first and last rows for(int j = 1; j < nx-1; j++) { // first row int k = j; error += sor_iteration( Au, Av, Du, Dv, D, u, v, alpha2, k, k-1, k+1, k+nx-1, k+nx+1, k, k-1, k+nx, k+1 ); // last row k = (ny-1) * nx + j; error += sor_iteration( Au, Av, Du, Dv, D, u, v, alpha2, k, k-nx-1, k-nx+1, k-1, k+1, k-nx, k-1, k, k+1 ); } // process the first and last columns for(int i = 1; i < ny-1; i++) { // first column int k = i * nx; error += sor_iteration( Au, Av, Du, Dv, D, u, v, alpha2, k, k-nx, k-nx+1, k+nx, k+nx+1, k-nx, k, k+nx, k+1 ); // last column k = (i+1) * nx - 1; error += sor_iteration( Au, Av, Du, Dv, D, u, v, alpha2, k, k-nx-1, k-nx, k+nx-1, k+nx, k-nx, k-1, k+nx, k ); } // process the corners // up-left corner error += sor_iteration( Au, Av, Du, Dv, D, u, v, alpha2, 0, 0, 1, nx, nx+1, 0, 0, nx, 1 ); // up-right corner int k = nx - 1; error += sor_iteration( Au, Av, Du, Dv, D, u, v, alpha2, k, k-1, k, k+nx-1, k+nx, k, k-1, k+nx, k ); // bottom-left corner k = (ny-1) * nx; error += sor_iteration( Au, Av, Du, Dv, D, u, v, alpha2, k, k-nx, k-nx+1,k, k+1, k-nx, k, k, k+1 ); // bottom-right corner k = ny * nx - 1; error += sor_iteration( Au, Av, Du, Dv, D, u, v, alpha2, k, k-1, k, k-nx-1, k-nx, k-nx, k-1, k, k ); error = sqrt(error / size); } if(verbose) fprintf(stderr, "Iterations %d (%g)\n", niter, error); } // free the allocated memory free(I2x); free(I2y); free(I2w); free(I2wx); free(I2wy); free(Au); free(Av); free(Du); free(Dv); free(D); } // compute the largest number of an array static float max_element(const float *x, int n) { int r = 0; for (int i = 1; i < n; i++) if (x[i] > x[r]) r = i; return x[r]; } // compute the smallest number of an array static float min_element(const float *x, int n) { int r = 0; for (int i = 1; i < n; i++) if (x[i] < x[r]) r = i; return x[r]; } /** * * Function to normalize the images between 0 and 255 * **/ static void image_normalization( const float *I1, // first image const float *I2, // second image float *I1n, // first normalized image float *I2n, // second normalized image int size // size of each image ) { // find the max and min of both images const float max1 = max_element(I1, size); const float max2 = max_element(I2, size); const float min1 = min_element(I1, size); const float min2 = min_element(I2, size); // obtain the absolute max and min const float max = max1 > max2 ? max1 : max2; const float min = min1 < min2 ? min1 : min2; const float den = max - min; if(den > 0) // normalize both images for(int i = 0; i < size; i++) { I1n[i] = 255.0 * (I1[i] - min) / den; I2n[i] = 255.0 * (I2[i] - min) / den; } else // copy the original images for(int i = 0; i < size; i++) { I1n[i] = I1[i]; I2n[i] = I2[i]; } } /** * * Procedure to handle the pyramidal approach. * This procedure relies on the previous functions to calculate * large optical flow fields using a pyramidal scheme. * */ void horn_schunck_pyramidal( const float *I1, // source image const float *I2, // target image float *u, // x component of optical flow float *v, // y component of optical flow const int nx, // image width const int ny, // image height const float alpha, // smoothing weight const int nscales, // number of scales const float zfactor, // zoom factor const int warps, // number of warpings per scale const float TOL, // stopping criterion threshold const int maxiter, // maximum number of iterations const bool verbose // switch on messages ) { if (verbose) fprintf(stderr, "Multiscale Horn-Schunck of a %dx%d pair" "\n\ta=%g ns=%d zf=%g nw=%d eps=%g mi=%d\n", nx, ny, alpha, nscales, zfactor, warps, TOL, maxiter); int size = nx * ny; float *I1s[nscales]; float *I2s[nscales]; float *us[nscales]; float *vs[nscales]; int nxx[nscales]; int nyy[nscales]; I1s[0] = xmalloc(size * sizeof(float)); I2s[0] = xmalloc(size * sizeof(float)); // normalize the finest scale images between 0 and 255 image_normalization(I1, I2, I1s[0], I2s[0], size); // presmoothing the finest scale images gaussian(I1s[0], nx, ny, INPUT_PRESMOOTHING_SIGMA); gaussian(I2s[0], nx, ny, INPUT_PRESMOOTHING_SIGMA); us[0] = u; vs[0] = v; nxx[0] = nx; nyy[0] = ny; // create the scales for(int s = 1; s < nscales; s++) { zoom_size(nxx[s-1], nyy[s-1], nxx+s, nyy+s, zfactor); const int sizes = nxx[s] * nyy[s]; I1s[s] = xmalloc(sizes * sizeof(float)); I2s[s] = xmalloc(sizes * sizeof(float)); us[s] = xmalloc(sizes * sizeof(float)); vs[s] = xmalloc(sizes * sizeof(float)); // compute the zoom from the previous finer scale zoom_out(I1s[s-1], I1s[s], nxx[s-1], nyy[s-1], zfactor); zoom_out(I2s[s-1], I2s[s], nxx[s-1], nyy[s-1], zfactor); } // initialize the flow for (int i = 0; i < nxx[nscales-1] * nyy[nscales-1]; i++) { us[nscales-1][i] = 0; vs[nscales-1][i] = 0; } // pyramidal approximation to the optic flow for(int s = nscales-1; s >= 0; s--) { if(verbose) fprintf(stderr, "Scale: %d %dx%d\n", s, nxx[s], nyy[s]); // compute the optical flow at this scale horn_schunck_optical_flow( I1s[s], I2s[s], us[s], vs[s], nxx[s], nyy[s], alpha, warps, TOL, maxiter, verbose ); // if this was the last scale, finish now if (!s) break; // otherwise, upsample the optical flow // zoom the optic flow for the next finer scale zoom_in(us[s], us[s-1], nxx[s], nyy[s], nxx[s-1], nyy[s-1]); zoom_in(vs[s], vs[s-1], nxx[s], nyy[s], nxx[s-1], nyy[s-1]); // scale the optic flow with the appropriate zoom factor for(int i = 0; i < nxx[s-1] * nyy[s-1]; i++) { us[s-1][i] *= 1.0 / zfactor; vs[s-1][i] *= 1.0 / zfactor; } } // free the allocated memory free(I1s[0]); free(I2s[0]); for(int i = 1; i < nscales; i++) { free(I1s[i]); free(I2s[i]); free(us[i]); free(vs[i]); } } #endif//HORN_SCHUNCK_PYRAMIDAL_C
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-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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % 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-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.h" #include "MagickCore/utility.h" /* Define declarations. */ #define BezierQuantum 200 /* 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(); (void) CloneString(&clone_info->primitive,draw_info->primitive); (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; (void) CloneString(&clone_info->text,draw_info->text); (void) CloneString(&clone_info->font,draw_info->font); (void) CloneString(&clone_info->metrics,draw_info->metrics); (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; (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; (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; (void) CloneString(&clone_info->server_name,draw_info->server_name); if (draw_info->dash_pattern != (double *) NULL) { register ssize_t x; for (x=0; draw_info->dash_pattern[x] != 0.0; 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)); } (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->alpha=draw_info->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-MagickEpsilon) > q->points[0].y) return(1); if ((p->points[0].y+MagickEpsilon) < q->points[0].y) return(-1); if ((p->points[0].x-MagickEpsilon) > q->points[0].x) return(1); if ((p->points[0].x+MagickEpsilon) < 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 DrawInfo *magick_unused(draw_info),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((size_t) number_edges, sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) return((PolygonInfo *) NULL); 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) || ((path_info[i].point.y == point.y) && (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 DrawInfo *magick_unused(draw_info),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 PointPrimitive: case ColorPrimitive: case MattePrimitive: case TextPrimitive: case ImagePrimitive: 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) >= MagickEpsilon) || (fabs(q.y-primitive_info[i].point.y) >= MagickEpsilon)) { 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) < MagickEpsilon) && (fabs(p.y-primitive_info[i].point.y) < MagickEpsilon)) 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 == MagickSignature); 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=(~MagickSignature); 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 >= MagickEpsilon) { 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 < -MagickEpsilon) { 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 >= MagickEpsilon) { 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 < -MagickEpsilon) { 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); } static inline ssize_t MagickAbsoluteValue(const ssize_t x) { if (x < 0) return(-x); return(x); } static inline double MagickMax(const double x,const double y) { if (x > y) return(x); return(y); } static inline double MagickMin(const double x,const double y) { if (x < y) return(x); return(y); } 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, point; register ssize_t i; SegmentInfo edge; ssize_t start, stop, y; /* Determine bounding box. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(source != (const Image *) NULL); assert(source->signature == MagickSignature); 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++) { 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 *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); SetPixelInfoPixel(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("#0000",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[MaxTextExtent]; Image *clip_mask; const char *value; DrawInfo *clone_info; MagickStatusType status; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); (void) FormatLocaleString(filename,MaxTextExtent,"%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=(Quantum) 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,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"); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->miterlimit=0; 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); dash_polygon[0]=primitive_info[0]; scale=ExpandAffine(&draw_info->affine); length=scale*(draw_info->dash_pattern[0]-0.5); offset=draw_info->dash_offset != 0.0 ? 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; 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 (length == 0.0) { n++; if (draw_info->dash_pattern[n] == 0.0) n=0; length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5)); } for (total_length=0.0; (total_length+length) <= maximum_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 (draw_info->dash_pattern[n] == 0.0) 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+=MagickEpsilon; dash_polygon[j].point.y+=MagickEpsilon; 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((value == 0.0) && (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 key[2*MaxTextExtent], keyword[MaxTextExtent], geometry[MaxTextExtent], name[MaxTextExtent], pattern[MaxTextExtent], *primitive, *token; const char *q; DrawInfo **graphic_context; MagickBooleanType proceed; MagickStatusType status; double angle, factor, primitive_extent; PointInfo point; PixelInfo start_color; PrimitiveInfo *primitive_info; PrimitiveType primitive_type; register const char *p; register ssize_t i, x; SegmentInfo bounds; size_t length, number_points; ssize_t j, k, n; /* Ensure the annotation info is valid. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickSignature); 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; /* 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); (void) QueryColorCompliance("#000000",AllCompliance,&start_color, exception); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; for (q=primitive; *q != '\0'; ) { /* Interpret graphic primitive. */ GetMagickToken(q,&q,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) { GetMagickToken(q,&q,token); affine.sx=StringToDouble(token,(char **) NULL); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); affine.rx=StringToDouble(token,(char **) NULL); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); affine.ry=StringToDouble(token,(char **) NULL); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); affine.sy=StringToDouble(token,(char **) NULL); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); affine.tx=StringToDouble(token,(char **) NULL); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); affine.ty=StringToDouble(token,(char **) NULL); 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) { GetMagickToken(q,&q,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. */ GetMagickToken(q,&q,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; GetMagickToken(q,&q,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; GetMagickToken(q,&q,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; GetMagickToken(q,&q,token); decorate=ParseCommandOption(MagickDecorateOptions,MagickFalse, token); if (decorate == -1) status=MagickFalse; else graphic_context[n]->decorate=(DecorationType) decorate; break; } if (LocaleCompare("direction",keyword) == 0) { ssize_t direction; GetMagickToken(q,&q,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) { GetMagickToken(q,&q,token); (void) CloneString(&graphic_context[n]->encoding,token); break; } status=MagickFalse; break; } case 'f': case 'F': { if (LocaleCompare("fill",keyword) == 0) { GetMagickToken(q,&q,token); (void) FormatLocaleString(pattern,MaxTextExtent,"%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 (status == MagickFalse) { ImageInfo *pattern_info; pattern_info=AcquireImageInfo(); (void) CopyMagickString(pattern_info->filename,token, MaxTextExtent); graphic_context[n]->fill_pattern=ReadImage(pattern_info, exception); CatchException(exception); pattern_info=DestroyImageInfo(pattern_info); } } break; } if (LocaleCompare("fill-alpha",keyword) == 0) { GetMagickToken(q,&q,token); factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; graphic_context[n]->fill.alpha=(double) QuantumRange* factor*StringToDouble(token,(char **) NULL); break; } if (LocaleCompare("fill-rule",keyword) == 0) { ssize_t fill_rule; GetMagickToken(q,&q,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) { GetMagickToken(q,&q,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) { GetMagickToken(q,&q,token); (void) CloneString(&graphic_context[n]->family,token); break; } if (LocaleCompare("font-size",keyword) == 0) { GetMagickToken(q,&q,token); graphic_context[n]->pointsize=StringToDouble(token,(char **) NULL); break; } if (LocaleCompare("font-stretch",keyword) == 0) { ssize_t stretch; GetMagickToken(q,&q,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; GetMagickToken(q,&q,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) { GetMagickToken(q,&q,token); graphic_context[n]->weight=StringToUnsignedLong(token); if (LocaleCompare(token,"all") == 0) graphic_context[n]->weight=0; if (LocaleCompare(token,"bold") == 0) graphic_context[n]->weight=700; if (LocaleCompare(token,"bolder") == 0) if (graphic_context[n]->weight <= 800) graphic_context[n]->weight+=100; if (LocaleCompare(token,"lighter") == 0) if (graphic_context[n]->weight >= 100) graphic_context[n]->weight-=100; if (LocaleCompare(token,"normal") == 0) graphic_context[n]->weight=400; break; } status=MagickFalse; break; } case 'g': case 'G': { if (LocaleCompare("gradient-units",keyword) == 0) { GetMagickToken(q,&q,token); break; } if (LocaleCompare("gravity",keyword) == 0) { ssize_t gravity; GetMagickToken(q,&q,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; GetMagickToken(q,&q,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) { GetMagickToken(q,&q,token); graphic_context[n]->interline_spacing=StringToDouble(token, (char **) NULL); break; } if (LocaleCompare("interword-spacing",keyword) == 0) { GetMagickToken(q,&q,token); graphic_context[n]->interword_spacing=StringToDouble(token, (char **) NULL); break; } status=MagickFalse; break; } case 'k': case 'K': { if (LocaleCompare("kerning",keyword) == 0) { GetMagickToken(q,&q,token); graphic_context[n]->kerning=StringToDouble(token,(char **) NULL); break; } status=MagickFalse; break; } case 'l': case 'L': { if (LocaleCompare("line",keyword) == 0) primitive_type=LinePrimitive; else status=MagickFalse; break; } case 'm': case 'M': { if (LocaleCompare("matte",keyword) == 0) primitive_type=MattePrimitive; else status=MagickFalse; break; } case 'o': case 'O': { if (LocaleCompare("offset",keyword) == 0) { GetMagickToken(q,&q,token); break; } if (LocaleCompare("opacity",keyword) == 0) { GetMagickToken(q,&q,token); factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; graphic_context[n]->alpha=ClampToQuantum(QuantumRange*(1.0-((1.0- QuantumScale*graphic_context[n]->alpha)*factor* StringToDouble(token,(char **) NULL)))); graphic_context[n]->fill.alpha=(double) graphic_context[n]->alpha; graphic_context[n]->stroke.alpha=(double) graphic_context[n]->alpha; 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) { GetMagickToken(q,&q,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); 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,(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) { GetMagickToken(q,&q,token); if (LocaleCompare("clip-path",token) == 0) { char name[MaxTextExtent]; GetMagickToken(q,&q,token); (void) FormatLocaleString(name,MaxTextExtent,"%s",token); for (p=q; *q != '\0'; ) { GetMagickToken(q,&q,token); if (LocaleCompare(token,"pop") != 0) continue; GetMagickToken(q,(const char **) NULL,token); if (LocaleCompare(token,"clip-path") != 0) continue; break; } (void) CopyMagickString(token,p,(size_t) (q-p-4+1)); (void) SetImageArtifact(image,name,token); GetMagickToken(q,&q,token); break; } if (LocaleCompare("gradient",token) == 0) { char key[2*MaxTextExtent], name[MaxTextExtent], type[MaxTextExtent]; SegmentInfo segment; GetMagickToken(q,&q,token); (void) CopyMagickString(name,token,MaxTextExtent); GetMagickToken(q,&q,token); (void) CopyMagickString(type,token,MaxTextExtent); GetMagickToken(q,&q,token); segment.x1=StringToDouble(token,(char **) NULL); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); segment.y1=StringToDouble(token,(char **) NULL); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); segment.x2=StringToDouble(token,(char **) NULL); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); segment.y2=StringToDouble(token,(char **) NULL); if (LocaleCompare(type,"radial") == 0) { GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); } for (p=q; *q != '\0'; ) { GetMagickToken(q,&q,token); if (LocaleCompare(token,"pop") != 0) continue; GetMagickToken(q,(const char **) NULL,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,MaxTextExtent,"%s",name); (void) SetImageArtifact(image,key,token); (void) FormatLocaleString(key,MaxTextExtent,"%s-geometry",name); (void) FormatLocaleString(geometry,MaxTextExtent, "%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); GetMagickToken(q,&q,token); break; } if (LocaleCompare("pattern",token) == 0) { RectangleInfo bounds; GetMagickToken(q,&q,token); (void) CopyMagickString(name,token,MaxTextExtent); GetMagickToken(q,&q,token); bounds.x=(ssize_t) ceil(StringToDouble(token,(char **) NULL)- 0.5); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); bounds.y=(ssize_t) ceil(StringToDouble(token,(char **) NULL)- 0.5); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); bounds.width=(size_t) floor(StringToDouble(token, (char **) NULL)+0.5); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); bounds.height=(size_t) floor(StringToDouble(token, (char **) NULL)+0.5); for (p=q; *q != '\0'; ) { GetMagickToken(q,&q,token); if (LocaleCompare(token,"pop") != 0) continue; GetMagickToken(q,(const char **) NULL,token); if (LocaleCompare(token,"pattern") != 0) continue; break; } (void) CopyMagickString(token,p,(size_t) (q-p-4+1)); (void) FormatLocaleString(key,MaxTextExtent,"%s",name); (void) SetImageArtifact(image,key,token); (void) FormatLocaleString(key,MaxTextExtent,"%s-geometry",name); (void) FormatLocaleString(geometry,MaxTextExtent, "%.20gx%.20g%+.20g%+.20g",(double) bounds.width,(double) bounds.height,(double) bounds.x,(double) bounds.y); (void) SetImageArtifact(image,key,geometry); GetMagickToken(q,&q,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) { GetMagickToken(q,&q,token); angle=StringToDouble(token,(char **) NULL); 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) { GetMagickToken(q,&q,token); affine.sx=StringToDouble(token,(char **) NULL); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); affine.sy=StringToDouble(token,(char **) NULL); break; } if (LocaleCompare("skewX",keyword) == 0) { GetMagickToken(q,&q,token); angle=StringToDouble(token,(char **) NULL); affine.ry=sin(DegreesToRadians(angle)); break; } if (LocaleCompare("skewY",keyword) == 0) { GetMagickToken(q,&q,token); angle=StringToDouble(token,(char **) NULL); affine.rx=(-tan(DegreesToRadians(angle)/2.0)); break; } if (LocaleCompare("stop-color",keyword) == 0) { PixelInfo stop_color; GetMagickToken(q,&q,token); (void) QueryColorCompliance(token,AllCompliance,&stop_color, exception); (void) GradientImage(image,LinearGradient,ReflectSpread, &start_color,&stop_color,exception); start_color=stop_color; GetMagickToken(q,&q,token); break; } if (LocaleCompare("stroke",keyword) == 0) { GetMagickToken(q,&q,token); (void) FormatLocaleString(pattern,MaxTextExtent,"%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 (status == MagickFalse) { ImageInfo *pattern_info; pattern_info=AcquireImageInfo(); (void) CopyMagickString(pattern_info->filename,token, MaxTextExtent); graphic_context[n]->stroke_pattern=ReadImage(pattern_info, exception); CatchException(exception); pattern_info=DestroyImageInfo(pattern_info); } } break; } if (LocaleCompare("stroke-antialias",keyword) == 0) { GetMagickToken(q,&q,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 *p; p=q; GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); for (x=0; IsPoint(token) != MagickFalse; x++) { GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,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); break; } for (j=0; j < x; j++) { GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); graphic_context[n]->dash_pattern[j]=StringToDouble(token, (char **) NULL); } 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; } GetMagickToken(q,&q,token); break; } if (LocaleCompare("stroke-dashoffset",keyword) == 0) { GetMagickToken(q,&q,token); graphic_context[n]->dash_offset=StringToDouble(token, (char **) NULL); break; } if (LocaleCompare("stroke-linecap",keyword) == 0) { ssize_t linecap; GetMagickToken(q,&q,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; GetMagickToken(q,&q,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) { GetMagickToken(q,&q,token); graphic_context[n]->miterlimit=StringToUnsignedLong(token); break; } if (LocaleCompare("stroke-opacity",keyword) == 0) { GetMagickToken(q,&q,token); factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; graphic_context[n]->stroke.alpha=(double) QuantumRange* factor*StringToDouble(token,(char **) NULL); break; } if (LocaleCompare("stroke-width",keyword) == 0) { GetMagickToken(q,&q,token); graphic_context[n]->stroke_width=StringToDouble(token, (char **) NULL); 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; GetMagickToken(q,&q,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; GetMagickToken(q,&q,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) { GetMagickToken(q,&q,token); graphic_context[n]->text_antialias= StringToLong(token) != 0 ? MagickTrue : MagickFalse; break; } if (LocaleCompare("text-undercolor",keyword) == 0) { GetMagickToken(q,&q,token); (void) QueryColorCompliance(token,AllCompliance, &graphic_context[n]->undercolor,exception); break; } if (LocaleCompare("translate",keyword) == 0) { GetMagickToken(q,&q,token); affine.tx=StringToDouble(token,(char **) NULL); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); affine.ty=StringToDouble(token,(char **) NULL); break; } status=MagickFalse; break; } case 'v': case 'V': { if (LocaleCompare("viewbox",keyword) == 0) { GetMagickToken(q,&q,token); graphic_context[n]->viewbox.x=(ssize_t) ceil(StringToDouble(token, (char **) NULL)-0.5); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); graphic_context[n]->viewbox.y=(ssize_t) ceil(StringToDouble(token, (char **) NULL)-0.5); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); graphic_context[n]->viewbox.width=(size_t) floor(StringToDouble( token,(char **) NULL)+0.5); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); graphic_context[n]->viewbox.height=(size_t) floor(StringToDouble( token,(char **) NULL)+0.5); break; } status=MagickFalse; break; } default: { status=MagickFalse; break; } } if (status == MagickFalse) break; if ((affine.sx != 1.0) || (affine.rx != 0.0) || (affine.ry != 0.0) || (affine.sy != 1.0) || (affine.tx != 0.0) || (affine.ty != 0.0)) { 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 (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; GetMagickToken(q,&q,token); point.x=StringToDouble(token,(char **) NULL); GetMagickToken(q,&q,token); if (*token == ',') GetMagickToken(q,&q,token); point.y=StringToDouble(token,(char **) NULL); GetMagickToken(q,(const char **) NULL,token); if (*token == ',') GetMagickToken(q,&q,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) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); break; } } 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: { length*=5+8*BezierQuantum; 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; GetMagickToken(q,&q,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/2; 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 ((size_t) (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) { (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 ColorPrimitive: case MattePrimitive: { ssize_t method; if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } GetMagickToken(q,&q,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 != ',') GetMagickToken(q,&q,token); primitive_info[j].text=AcquireString(token); break; } case ImagePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } GetMagickToken(q,&q,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: { double length, offset; PointInfo v; v.x=(double) x-gradient->center.x; v.y=(double) y-gradient->center.y; length=sqrt(v.x*v.x+v.y*v.y); if (gradient->spread == RepeatSpread) return(length); offset=length/gradient->radius; return(offset); } } return(0.0); } 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 == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); gradient=(&draw_info->gradient); 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 *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); SetPixelInfoPixel(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[MaxTextExtent]; const char *geometry, *path; DrawInfo *clone_info; ImageInfo *image_info; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); 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,MaxTextExtent,"%s",name); path=GetImageArtifact(image,property); if (path == (const char *) NULL) return(MagickFalse); (void) FormatLocaleString(property,MaxTextExtent,"%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) 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 DrawInfo *draw_info, const PrimitiveInfo *primitive_info) { PathInfo *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(draw_info,primitive_info); if (path_info == (PathInfo *) NULL) return(DestroyPolygonThreadSet(polygon_info)); for (i=0; i < (ssize_t) number_threads; i++) { polygon_info[i]=ConvertPathToPolygon(draw_info,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 (distance != 1.0) 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 (beta == 0.0) { beta=1.0; if (distance != 1.0) 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 **restrict polygon_info; register EdgeInfo *p; register ssize_t i; SegmentInfo bounds; ssize_t start, stop, y; /* Compute bounding box. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickSignature); assert(primitive_info != (PrimitiveInfo *) NULL); if (primitive_info->coordinates == 0) return(MagickTrue); polygon_info=AcquirePolygonThreadSet(draw_info,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) { /* Draw point. */ start=(ssize_t) ceil(bounds.y1-0.5); stop=(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 <= stop; y++) { MagickBooleanType sync; PixelInfo pixel; register ssize_t x; register Quantum *restrict q; ssize_t start, stop; if (status == MagickFalse) continue; start=(ssize_t) ceil(bounds.x1-0.5); stop=(ssize_t) floor(bounds.x2+0.5); x=start; q=GetCacheViewAuthenticPixels(image_view,x,y,(size_t) (stop-x+1),1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } GetPixelInfo(image,&pixel); for ( ; x <= stop; x++) { if ((x == (ssize_t) ceil(primitive_info->point.x-0.5)) && (y == (ssize_t) ceil(primitive_info->point.y-0.5))) { (void) GetStrokeColor(draw_info,x,y,&pixel,exception); SetPixelInfoPixel(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 != BlendPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); start=(ssize_t) ceil(bounds.y1-0.5); stop=(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 <= stop; y++) { const int id = GetOpenMPThreadId(); double fill_alpha, stroke_alpha; PixelInfo fill_color, stroke_color; register Quantum *restrict q; register ssize_t x; ssize_t start, stop; if (status == MagickFalse) continue; start=(ssize_t) ceil(bounds.x1-0.5); stop=(ssize_t) floor(bounds.x2+0.5); q=GetCacheViewAuthenticPixels(image_view,start,y,(size_t) (stop-start+1),1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=start; x <= stop; 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; } (void) GetFillColor(draw_info,x,y,&fill_color,exception); fill_alpha=fill_alpha*fill_color.alpha; CompositePixelOver(image,&fill_color,fill_alpha,q,(double) GetPixelAlpha(image,q),q); (void) GetStrokeColor(draw_info,x,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 PointPrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "PointPrimitive %.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 MattePrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "MattePrimitive %.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; } case ImagePrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "ImagePrimitive %.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) >= MagickEpsilon) || (fabs(q.y-point.y) >= MagickEpsilon)) (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) >= MagickEpsilon) || (fabs(p.y-point.y) >= MagickEpsilon)) (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 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; (void) 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 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); (void) GetFillColor(draw_info,x,y,&pixel,exception); SetPixelInfoPixel(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 *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; } (void) GetFillColor(draw_info,x,y,&pixel,exception); SetPixelInfoPixel(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 *restrict q; register ssize_t x; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { (void) GetFillColor(draw_info,x,y,&pixel,exception); SetPixelInfoPixel(image,&pixel,q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) break; } break; } } break; } case MattePrimitive: { if (image->alpha_trait != BlendPixelTrait) (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; (void) 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 *restrict q; register ssize_t x; 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; } (void) 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 *restrict q; register ssize_t x; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { (void) 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 TextPrimitive: { char geometry[MaxTextExtent]; 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,MaxTextExtent,"%+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; } case ImagePrimitive: { AffineMatrix affine; char composite_geometry[MaxTextExtent]; 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, MaxTextExtent); 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))) { char geometry[MaxTextExtent]; /* Resize image. */ (void) FormatLocaleString(geometry,MaxTextExtent,"%gx%g!", primitive_info[1].point.x,primitive_info[1].point.y); composite_image->filter=image->filter; (void) TransformImage(&composite_image,(char *) NULL,geometry, exception); } if (composite_image->alpha_trait != BlendPixelTrait) (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,MaxTextExtent, "%.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; } 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) && (draw_info->dash_pattern[0] != 0.0) && ((scale*draw_info->stroke_width) >= MagickEpsilon) && (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=(Quantum) 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)) { MagickBooleanType closed_path; /* Draw strokes while respecting line cap/join attributes. */ for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ; closed_path= (primitive_info[i-1].point.x == primitive_info[0].point.x) && (primitive_info[i-1].point.y == primitive_info[0].point.y) ? MagickTrue : MagickFalse; i=(ssize_t) primitive_info[0].coordinates; if ((((draw_info->linecap == RoundCap) || (closed_path != MagickFalse)) && (draw_info->linejoin == RoundJoin)) || (primitive_info[i].primitive != UndefinedPrimitive)) { (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=(Quantum) 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+=(double) (10.0*MagickEpsilon); linecap[2].point.x+=(double) (10.0*MagickEpsilon); linecap[2].point.y+=(double) (10.0*MagickEpsilon); linecap[3].point.y+=(double) (10.0*MagickEpsilon); 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=(Quantum) 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=(q->point.x == p->point.x) && (q->point.y == p->point.y) ? 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) { const char *option; ExceptionInfo *exception; /* Initialize draw attributes. */ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(draw_info != (DrawInfo *) NULL); (void) ResetMagickMemory(draw_info,0,sizeof(*draw_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->alpha=OpaqueAlpha; draw_info->fill_rule=EvenOddRule; 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=(Quantum) TransparentAlpha; draw_info->compose=OverCompositeOp; draw_info->render=MagickTrue; draw_info->debug=IsEventLogging(); if (image_info != (ImageInfo *) NULL) { draw_info->stroke_antialias=image_info->antialias; if (image_info->font != (char *) NULL) draw_info->font=AcquireString(image_info->font); if (image_info->density != (char *) NULL) draw_info->density=AcquireString(image_info->density); draw_info->text_antialias=image_info->antialias; if (image_info->pointsize != 0.0) draw_info->pointsize=image_info->pointsize; draw_info->border_color=image_info->border_color; if (image_info->server_name != (char *) NULL) draw_info->server_name=AcquireString(image_info->server_name); option=GetImageOption(image_info,"encoding"); if (option != (const char *) NULL) (void) CloneString(&draw_info->encoding,option); option=GetImageOption(image_info,"kerning"); if (option != (const char *) NULL) draw_info->kerning=StringToDouble(option,(char **) NULL); option=GetImageOption(image_info,"interline-spacing"); if (option != (const char *) NULL) draw_info->interline_spacing=StringToDouble(option,(char **) NULL); option=GetImageOption(image_info,"interword-spacing"); if (option != (const char *) NULL) draw_info->interword_spacing=StringToDouble(option,(char **) NULL); option=GetImageOption(image_info,"direction"); if (option != (const char *) NULL) draw_info->direction=(DirectionType) ParseCommandOption( MagickDirectionOptions,MagickFalse,option); else draw_info->direction=UndefinedDirection; option=GetImageOption(image_info,"fill"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&draw_info->fill, exception); option=GetImageOption(image_info,"stroke"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&draw_info->stroke, exception); option=GetImageOption(image_info,"strokewidth"); if (option != (const char *) NULL) draw_info->stroke_width=StringToDouble(option,(char **) NULL); option=GetImageOption(image_info,"undercolor"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&draw_info->undercolor, exception); option=GetImageOption(image_info,"gravity"); if (option != (const char *) NULL) draw_info->gravity=(GravityType) ParseCommandOption( MagickGravityOptions,MagickFalse,option); } exception=DestroyExceptionInfo(exception); draw_info->signature=MagickSignature; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + 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 ((start.x == end.x) && (start.y == end.y)) { TracePoint(primitive_info,end); return; } radii.x=fabs(arc.x); radii.y=fabs(arc.y); if ((radii.x == 0.0) || (radii.y == 0.0)) { 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 < MagickEpsilon) { 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+=(double) (2.0*MagickPI); else if ((theta > 0.0) && (sweep == MagickFalse)) theta-=(double) (2.0*MagickPI); arc_segments=(size_t) ceil(fabs((double) (theta/(0.5*MagickPI+ MagickEpsilon)))); 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 ((stop.x == 0.0) && (stop.y == 0.0)) { TracePoint(primitive_info,start); return; } delta=2.0/MagickMax(stop.x,stop.y); step=(double) (MagickPI/8.0); if ((delta >= 0.0) && (delta < (double) (MagickPI/8.0))) step=(double) (MagickPI/(4*(MagickPI/delta/2+0.5))); angle.x=DegreesToRadians(degrees.x); y=degrees.y; while (y < degrees.x) y+=360.0; angle.y=(double) 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) < MagickEpsilon) && (fabs(start.y-end.y) < MagickEpsilon)) { 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 token[MaxTextExtent]; const char *p; int attribute, last_attribute; double x, y; PointInfo end, points[4], point, start; PrimitiveType primitive_type; register PrimitiveInfo *q; register ssize_t i; size_t number_coordinates, z_count; attribute=0; end.x=0.0; end.y=0.0; point.x=0.0; point.y=0.0; start.x=0.0; start.y=0.0; number_coordinates=0; z_count=0; (void) ResetMagickMemory(points,0,sizeof(*points)); 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': { MagickBooleanType large_arc, sweep; double angle; PointInfo arc; /* Compute arc points. */ do { GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); arc.x=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); arc.y=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); angle=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); large_arc=StringToLong(token) != 0 ? MagickTrue : MagickFalse; GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); sweep=StringToLong(token) != 0 ? MagickTrue : MagickFalse; GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); x=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); y=StringToDouble(token,(char **) NULL); 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++) { GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); x=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); y=StringToDouble(token,(char **) NULL); 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 { GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); x=StringToDouble(token,(char **) NULL); 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 { GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); x=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); y=StringToDouble(token,(char **) NULL); 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 { GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); x=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); y=StringToDouble(token,(char **) NULL); 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++) { GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); x=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); y=StringToDouble(token,(char **) NULL); 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++) { GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); x=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); y=StringToDouble(token,(char **) NULL); 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]=points[2]; points[1]=points[3]; } 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++) { GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); x=StringToDouble(token,(char **) NULL); GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); y=StringToDouble(token,(char **) NULL); 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]=points[2]; points[1]=points[3]; } 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 { GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); y=StringToDouble(token,(char **) NULL); 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) >= MagickEpsilon) || (fabs((double) dy) >= MagickEpsilon)) 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) >= MagickEpsilon) || (fabs((double) dy) >= MagickEpsilon)) 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 inline double DrawEpsilonReciprocal(const double x) { #define DrawEpsilon ((double) 1.0e-10) double sign = x < (double) 0.0 ? (double) -1.0 : (double) 1.0; return((sign*x) >= DrawEpsilon ? (double) 1.0/x : sign*( (double) 1.0/DrawEpsilon)); } static PrimitiveInfo *TraceStrokePolygon(const DrawInfo *draw_info, const PrimitiveInfo *primitive_info) { typedef struct _LineSegment { double p, q; } LineSegment; LineSegment dx, dy, inverse_slope, slope, theta; MagickBooleanType closed_path; double delta_theta, dot_product, mid, miterlimit; 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= (primitive_info[number_vertices-1].point.x == primitive_info[0].point.x) && (primitive_info[number_vertices-1].point.y == primitive_info[0].point.y) ? 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) >= MagickEpsilon) || (fabs(dy.p) >= MagickEpsilon)) break; } if (n == (ssize_t) number_vertices) n=(ssize_t) number_vertices-1L; slope.p=DrawEpsilonReciprocal(dx.p)*dy.p; inverse_slope.p=(-1.0*DrawEpsilonReciprocal(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=DrawEpsilonReciprocal(dx.q)*dy.q; inverse_slope.q=(-1.0*DrawEpsilonReciprocal(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)) < MagickEpsilon) { 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)) { max_strokes+=6*BezierQuantum+360; path_p=(PointInfo *) ResizeQuantumMemory(path_p,(size_t) max_strokes, sizeof(*path_p)); path_q=(PointInfo *) ResizeQuantumMemory(path_q,(size_t) max_strokes, sizeof(*path_q)); if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL)) { 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+=(double) (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+=(double) (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); }
GB_unop__identity_fp32_fc32.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__identity_fp32_fc32) // op(A') function: GB (_unop_tran__identity_fp32_fc32) // C type: float // A type: GxB_FC32_t // cast: float cij = (float) crealf (aij) // unaryop: cij = aij #define GB_ATYPE \ GxB_FC32_t #define GB_CTYPE \ float // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ float z = (float) crealf (aij) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ float z = (float) crealf (aij) ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_FP32 || GxB_NO_FC32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_fp32_fc32) ( float *Cx, // Cx and Ax may be aliased const GxB_FC32_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_FC32_t aij = Ax [p] ; float z = (float) crealf (aij) ; Cx [p] = 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_FC32_t aij = Ax [p] ; float z = (float) crealf (aij) ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_fp32_fc32) ( 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
statistic.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS TTTTT AAA TTTTT IIIII SSSSS TTTTT IIIII CCCC % % SS T A A T I SS T I C % % SSS T AAAAA T I SSS T I C % % SS T A A T I SS T I C % % SSSSS T A A T IIIII SSSSS T IIIII CCCC % % % % % % MagickCore Image Statistical 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/animate.h" #include "magick/animate.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/cache-private.h" #include "magick/cache-view.h" #include "magick/client.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/composite.h" #include "magick/composite-private.h" #include "magick/compress.h" #include "magick/constitute.h" #include "magick/deprecate.h" #include "magick/display.h" #include "magick/draw.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/gem.h" #include "magick/geometry.h" #include "magick/list.h" #include "magick/image-private.h" #include "magick/magic.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/paint.h" #include "magick/pixel-private.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/quantize.h" #include "magick/random_.h" #include "magick/random-private.h" #include "magick/resource_.h" #include "magick/segment.h" #include "magick/semaphore.h" #include "magick/signature-private.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/thread-private.h" #include "magick/timer.h" #include "magick/utility.h" #include "magick/version.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E v a l u a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EvaluateImage() applies a value to the image with an arithmetic, relational, % or logical operator to an image. Use these operations to lighten or darken % an image, to increase or decrease contrast in an image, or to produce the % "negative" of an image. % % The format of the EvaluateImageChannel method is: % % MagickBooleanType EvaluateImage(Image *image, % const MagickEvaluateOperator op,const double value, % ExceptionInfo *exception) % MagickBooleanType EvaluateImages(Image *images, % const MagickEvaluateOperator op,const double value, % ExceptionInfo *exception) % MagickBooleanType EvaluateImageChannel(Image *image, % const ChannelType channel,const MagickEvaluateOperator op, % const double value,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o op: A channel op. % % o value: A value value. % % o exception: return any errors or warnings in this structure. % */ static MagickPixelPacket **DestroyPixelThreadSet(MagickPixelPacket **pixels) { register ssize_t i; assert(pixels != (MagickPixelPacket **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixels[i] != (MagickPixelPacket *) NULL) pixels[i]=(MagickPixelPacket *) RelinquishMagickMemory(pixels[i]); pixels=(MagickPixelPacket **) RelinquishMagickMemory(pixels); return(pixels); } static MagickPixelPacket **AcquirePixelThreadSet(const Image *image, const size_t number_images) { MagickPixelPacket **pixels; register ssize_t i, j; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(MagickPixelPacket **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (MagickPixelPacket **) NULL) return((MagickPixelPacket **) NULL); (void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels)); for (i=0; i < (ssize_t) number_threads; i++) { pixels[i]=(MagickPixelPacket *) AcquireQuantumMemory(image->columns, sizeof(**pixels)); if (pixels[i] == (MagickPixelPacket *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) image->columns; j++) GetMagickPixelPacket(image,&pixels[i][j]); } return(pixels); } static inline double EvaluateMax(const double x,const double y) { if (x > y) return(x); return(y); } #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int IntensityCompare(const void *x,const void *y) { const MagickPixelPacket *color_1, *color_2; int intensity; color_1=(const MagickPixelPacket *) x; color_2=(const MagickPixelPacket *) y; intensity=(int) MagickPixelIntensity(color_2)-(int) MagickPixelIntensity(color_1); return(intensity); } #if defined(__cplusplus) || defined(c_plusplus) } #endif static MagickRealType ApplyEvaluateOperator(RandomInfo *random_info, const Quantum pixel,const MagickEvaluateOperator op, const MagickRealType value) { MagickRealType result; result=0.0; switch (op) { case UndefinedEvaluateOperator: break; case AbsEvaluateOperator: { result=(MagickRealType) fabs((double) (pixel+value)); break; } case AddEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case AddModulusEvaluateOperator: { /* This returns a 'floored modulus' of the addition which is a positive result. It differs from % or fmod() which returns a 'truncated modulus' result, where floor() is replaced by trunc() and could return a negative result (which is clipped). */ result=pixel+value; result-=(QuantumRange+1.0)*floor((double) result/(QuantumRange+1.0)); break; } case AndEvaluateOperator: { result=(MagickRealType) ((size_t) pixel & (size_t) (value+0.5)); break; } case CosineEvaluateOperator: { result=(MagickRealType) (QuantumRange*(0.5*cos((double) (2.0*MagickPI* QuantumScale*pixel*value))+0.5)); break; } case DivideEvaluateOperator: { result=pixel/(value == 0.0 ? 1.0 : value); break; } case ExponentialEvaluateOperator: { result=(MagickRealType) (QuantumRange*exp((double) (value*QuantumScale* pixel))); break; } case GaussianNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, GaussianNoise,value); break; } case ImpulseNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, ImpulseNoise,value); break; } case LaplacianNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, LaplacianNoise,value); break; } case LeftShiftEvaluateOperator: { result=(MagickRealType) ((size_t) pixel << (size_t) (value+0.5)); break; } case LogEvaluateOperator: { if ((QuantumScale*pixel) >= MagickEpsilon) result=(MagickRealType) (QuantumRange*log((double) (QuantumScale*value* pixel+1.0))/log((double) (value+1.0))); break; } case MaxEvaluateOperator: { result=(MagickRealType) EvaluateMax((double) pixel,value); break; } case MeanEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case MedianEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case MinEvaluateOperator: { result=(MagickRealType) MagickMin((double) pixel,value); break; } case MultiplicativeNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, MultiplicativeGaussianNoise,value); break; } case MultiplyEvaluateOperator: { result=(MagickRealType) (value*pixel); break; } case OrEvaluateOperator: { result=(MagickRealType) ((size_t) pixel | (size_t) (value+0.5)); break; } case PoissonNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, PoissonNoise,value); break; } case PowEvaluateOperator: { result=(MagickRealType) (QuantumRange*pow((double) (QuantumScale*pixel), (double) value)); break; } case RightShiftEvaluateOperator: { result=(MagickRealType) ((size_t) pixel >> (size_t) (value+0.5)); break; } case RootMeanSquareEvaluateOperator: { result=(MagickRealType) (pixel*pixel+value); break; } case SetEvaluateOperator: { result=value; break; } case SineEvaluateOperator: { result=(MagickRealType) (QuantumRange*(0.5*sin((double) (2.0*MagickPI* QuantumScale*pixel*value))+0.5)); break; } case SubtractEvaluateOperator: { result=(MagickRealType) (pixel-value); break; } case SumEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case ThresholdEvaluateOperator: { result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 : QuantumRange); break; } case ThresholdBlackEvaluateOperator: { result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 : pixel); break; } case ThresholdWhiteEvaluateOperator: { result=(MagickRealType) (((MagickRealType) pixel > value) ? QuantumRange : pixel); break; } case UniformNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, UniformNoise,value); break; } case XorEvaluateOperator: { result=(MagickRealType) ((size_t) pixel ^ (size_t) (value+0.5)); break; } } return(result); } static Image *AcquireImageCanvas(const Image *images,ExceptionInfo *exception) { const Image *p, *q; size_t columns, number_channels, rows; q=images; columns=images->columns; rows=images->rows; number_channels=0; for (p=images; p != (Image *) NULL; p=p->next) { size_t channels; channels=3; if (p->matte != MagickFalse) channels+=1; if (p->colorspace == CMYKColorspace) channels+=1; if (channels > number_channels) { number_channels=channels; q=p; } if (p->columns > columns) columns=p->columns; if (p->rows > rows) rows=p->rows; } return(CloneImage(q,columns,rows,MagickTrue,exception)); } MagickExport MagickBooleanType EvaluateImage(Image *image, const MagickEvaluateOperator op,const double value,ExceptionInfo *exception) { MagickBooleanType status; status=EvaluateImageChannel(image,CompositeChannels,op,value,exception); return(status); } MagickExport Image *EvaluateImages(const Image *images, const MagickEvaluateOperator op,ExceptionInfo *exception) { #define EvaluateImageTag "Evaluate/Image" CacheView *evaluate_view; Image *image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket **magick_restrict evaluate_pixels, zero; RandomInfo **magick_restrict random_info; size_t number_images; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImageCanvas(images,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImage(image); return((Image *) NULL); } number_images=GetImageListLength(images); evaluate_pixels=AcquirePixelThreadSet(images,number_images); if (evaluate_pixels == (MagickPixelPacket **) NULL) { image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return((Image *) NULL); } /* Evaluate image pixels. */ status=MagickTrue; progress=0; GetMagickPixelPacket(images,&zero); random_info=AcquireRandomInfoThreadSet(); evaluate_view=AcquireAuthenticCacheView(image,exception); if (op == MedianEvaluateOperator) { #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_number_threads(image,images,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict evaluate_indexes; register MagickPixelPacket *evaluate_pixel; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } evaluate_indexes=GetCacheViewAuthenticIndexQueue(evaluate_view); evaluate_pixel=evaluate_pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) number_images; i++) evaluate_pixel[i]=zero; next=images; for (i=0; i < (ssize_t) number_images; i++) { register const IndexPacket *indexes; register const PixelPacket *p; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,x,y,1,1,exception); if (p == (const PixelPacket *) NULL) { image_view=DestroyCacheView(image_view); break; } indexes=GetCacheViewVirtualIndexQueue(image_view); evaluate_pixel[i].red=ApplyEvaluateOperator(random_info[id], GetPixelRed(p),op,evaluate_pixel[i].red); evaluate_pixel[i].green=ApplyEvaluateOperator(random_info[id], GetPixelGreen(p),op,evaluate_pixel[i].green); evaluate_pixel[i].blue=ApplyEvaluateOperator(random_info[id], GetPixelBlue(p),op,evaluate_pixel[i].blue); evaluate_pixel[i].opacity=ApplyEvaluateOperator(random_info[id], GetPixelAlpha(p),op,evaluate_pixel[i].opacity); if (image->colorspace == CMYKColorspace) evaluate_pixel[i].index=ApplyEvaluateOperator(random_info[id], *indexes,op,evaluate_pixel[i].index); image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } qsort((void *) evaluate_pixel,number_images,sizeof(*evaluate_pixel), IntensityCompare); SetPixelRed(q,ClampToQuantum(evaluate_pixel[i/2].red)); SetPixelGreen(q,ClampToQuantum(evaluate_pixel[i/2].green)); SetPixelBlue(q,ClampToQuantum(evaluate_pixel[i/2].blue)); SetPixelAlpha(q,ClampToQuantum(evaluate_pixel[i/2].opacity)); if (image->colorspace == CMYKColorspace) SetPixelIndex(evaluate_indexes+i,ClampToQuantum( evaluate_pixel[i/2].index)); q++; } if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_EvaluateImages) #endif proceed=SetImageProgress(images,EvaluateImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } } else { #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_number_threads(image,images,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict evaluate_indexes; register ssize_t i, x; register MagickPixelPacket *evaluate_pixel; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } evaluate_indexes=GetCacheViewAuthenticIndexQueue(evaluate_view); evaluate_pixel=evaluate_pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) evaluate_pixel[x]=zero; next=images; for (i=0; i < (ssize_t) number_images; i++) { register const IndexPacket *indexes; register const PixelPacket *p; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1, exception); if (p == (const PixelPacket *) NULL) { image_view=DestroyCacheView(image_view); break; } indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { evaluate_pixel[x].red=ApplyEvaluateOperator(random_info[id], GetPixelRed(p),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].red); evaluate_pixel[x].green=ApplyEvaluateOperator(random_info[id], GetPixelGreen(p),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].green); evaluate_pixel[x].blue=ApplyEvaluateOperator(random_info[id], GetPixelBlue(p),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].blue); evaluate_pixel[x].opacity=ApplyEvaluateOperator(random_info[id], GetPixelAlpha(p),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].opacity); if (image->colorspace == CMYKColorspace) evaluate_pixel[x].index=ApplyEvaluateOperator(random_info[id], GetPixelIndex(indexes+x),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].index); p++; } image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } if (op == MeanEvaluateOperator) for (x=0; x < (ssize_t) image->columns; x++) { evaluate_pixel[x].red/=number_images; evaluate_pixel[x].green/=number_images; evaluate_pixel[x].blue/=number_images; evaluate_pixel[x].opacity/=number_images; evaluate_pixel[x].index/=number_images; } if (op == RootMeanSquareEvaluateOperator) for (x=0; x < (ssize_t) image->columns; x++) { evaluate_pixel[x].red=sqrt((double) evaluate_pixel[x].red/ number_images); evaluate_pixel[x].green=sqrt((double) evaluate_pixel[x].green/ number_images); evaluate_pixel[x].blue=sqrt((double) evaluate_pixel[x].blue/ number_images); evaluate_pixel[x].opacity=sqrt((double) evaluate_pixel[x].opacity/ number_images); evaluate_pixel[x].index=sqrt((double) evaluate_pixel[x].index/ number_images); } if (op == MultiplyEvaluateOperator) for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; for (j=0; j < (ssize_t) (number_images-1); j++) { evaluate_pixel[x].red*=(MagickRealType) QuantumScale; evaluate_pixel[x].green*=(MagickRealType) QuantumScale; evaluate_pixel[x].blue*=(MagickRealType) QuantumScale; evaluate_pixel[x].opacity*=(MagickRealType) QuantumScale; evaluate_pixel[x].index*=(MagickRealType) QuantumScale; } } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ClampToQuantum(evaluate_pixel[x].red)); SetPixelGreen(q,ClampToQuantum(evaluate_pixel[x].green)); SetPixelBlue(q,ClampToQuantum(evaluate_pixel[x].blue)); SetPixelAlpha(q,ClampToQuantum(evaluate_pixel[x].opacity)); if (image->colorspace == CMYKColorspace) SetPixelIndex(evaluate_indexes+x,ClampToQuantum( evaluate_pixel[x].index)); q++; } if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_EvaluateImages) #endif proceed=SetImageProgress(images,EvaluateImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } } evaluate_view=DestroyCacheView(evaluate_view); evaluate_pixels=DestroyPixelThreadSet(evaluate_pixels); random_info=DestroyRandomInfoThreadSet(random_info); if (status == MagickFalse) image=DestroyImage(image); return(image); } MagickExport MagickBooleanType EvaluateImageChannel(Image *image, const ChannelType channel,const MagickEvaluateOperator op,const double value, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif 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 (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); return(MagickFalse); } status=MagickTrue; progress=0; random_info=AcquireRandomInfoThreadSet(); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_number_threads(image,image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); 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++) { MagickRealType result; if ((channel & RedChannel) != 0) { result=ApplyEvaluateOperator(random_info[id],GetPixelRed(q),op,value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelRed(q,ClampToQuantum(result)); } if ((channel & GreenChannel) != 0) { result=ApplyEvaluateOperator(random_info[id],GetPixelGreen(q),op, value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelGreen(q,ClampToQuantum(result)); } if ((channel & BlueChannel) != 0) { result=ApplyEvaluateOperator(random_info[id],GetPixelBlue(q),op, value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelBlue(q,ClampToQuantum(result)); } if ((channel & OpacityChannel) != 0) { if (image->matte == MagickFalse) { result=ApplyEvaluateOperator(random_info[id],GetPixelOpacity(q), op,value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelOpacity(q,ClampToQuantum(result)); } else { result=ApplyEvaluateOperator(random_info[id],GetPixelAlpha(q), op,value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelAlpha(q,ClampToQuantum(result)); } } if (((channel & IndexChannel) != 0) && (indexes != (IndexPacket *) NULL)) { result=ApplyEvaluateOperator(random_info[id],GetPixelIndex(indexes+x), op,value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelIndex(indexes+x,ClampToQuantum(result)); } 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_EvaluateImageChannel) #endif proceed=SetImageProgress(image,EvaluateImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F u n c t i o n I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FunctionImage() applies a value to the image with an arithmetic, relational, % or logical operator to an image. Use these operations to lighten or darken % an image, to increase or decrease contrast in an image, or to produce the % "negative" of an image. % % The format of the FunctionImageChannel method is: % % MagickBooleanType FunctionImage(Image *image, % const MagickFunction function,const ssize_t number_parameters, % const double *parameters,ExceptionInfo *exception) % MagickBooleanType FunctionImageChannel(Image *image, % const ChannelType channel,const MagickFunction function, % const ssize_t number_parameters,const double *argument, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o function: A channel function. % % o parameters: one or more parameters. % % o exception: return any errors or warnings in this structure. % */ static Quantum ApplyFunction(Quantum pixel,const MagickFunction function, const size_t number_parameters,const double *parameters, ExceptionInfo *exception) { MagickRealType result; register ssize_t i; (void) exception; result=0.0; switch (function) { case PolynomialFunction: { /* * Polynomial * Parameters: polynomial constants, highest to lowest order * For example: c0*x^3 + c1*x^2 + c2*x + c3 */ result=0.0; for (i=0; i < (ssize_t) number_parameters; i++) result=result*QuantumScale*pixel + parameters[i]; result*=QuantumRange; break; } case SinusoidFunction: { /* Sinusoid Function * Parameters: Freq, Phase, Ampl, bias */ double freq,phase,ampl,bias; freq = ( number_parameters >= 1 ) ? parameters[0] : 1.0; phase = ( number_parameters >= 2 ) ? parameters[1] : 0.0; ampl = ( number_parameters >= 3 ) ? parameters[2] : 0.5; bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5; result=(MagickRealType) (QuantumRange*(ampl*sin((double) (2.0*MagickPI* (freq*QuantumScale*pixel + phase/360.0) )) + bias ) ); break; } case ArcsinFunction: { /* Arcsin Function (peged at range limits for invalid results) * Parameters: Width, Center, Range, Bias */ double width,range,center,bias; width = ( number_parameters >= 1 ) ? parameters[0] : 1.0; center = ( number_parameters >= 2 ) ? parameters[1] : 0.5; range = ( number_parameters >= 3 ) ? parameters[2] : 1.0; bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5; result = 2.0/width*(QuantumScale*pixel - center); if ( result <= -1.0 ) result = bias - range/2.0; else if ( result >= 1.0 ) result = bias + range/2.0; else result=(MagickRealType) (range/MagickPI*asin((double) result)+bias); result *= QuantumRange; break; } case ArctanFunction: { /* Arctan Function * Parameters: Slope, Center, Range, Bias */ double slope,range,center,bias; slope = ( number_parameters >= 1 ) ? parameters[0] : 1.0; center = ( number_parameters >= 2 ) ? parameters[1] : 0.5; range = ( number_parameters >= 3 ) ? parameters[2] : 1.0; bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5; result=(MagickRealType) (MagickPI*slope*(QuantumScale*pixel-center)); result=(MagickRealType) (QuantumRange*(range/MagickPI*atan((double) result) + bias ) ); break; } case UndefinedFunction: break; } return(ClampToQuantum(result)); } MagickExport MagickBooleanType FunctionImage(Image *image, const MagickFunction function,const size_t number_parameters, const double *parameters,ExceptionInfo *exception) { MagickBooleanType status; status=FunctionImageChannel(image,CompositeChannels,function, number_parameters,parameters,exception); return(status); } MagickExport MagickBooleanType FunctionImageChannel(Image *image, const ChannelType channel,const MagickFunction function, const size_t number_parameters,const double *parameters, ExceptionInfo *exception) { #define FunctionImageTag "Function/Image " CacheView *image_view; 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); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); return(MagickFalse); } #if defined(MAGICKCORE_OPENCL_SUPPORT) status=AccelerateFunctionImage(image,channel,function,number_parameters, parameters,exception); if (status != MagickFalse) return(status); #endif status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) 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 ssize_t x; register PixelPacket *magick_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) SetPixelRed(q,ApplyFunction(GetPixelRed(q),function, number_parameters,parameters,exception)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ApplyFunction(GetPixelGreen(q),function, number_parameters,parameters,exception)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ApplyFunction(GetPixelBlue(q),function, number_parameters,parameters,exception)); if ((channel & OpacityChannel) != 0) { if (image->matte == MagickFalse) SetPixelOpacity(q,ApplyFunction(GetPixelOpacity(q),function, number_parameters,parameters,exception)); else SetPixelAlpha(q,ApplyFunction((Quantum) GetPixelAlpha(q),function, number_parameters,parameters,exception)); } if (((channel & IndexChannel) != 0) && (indexes != (IndexPacket *) NULL)) SetPixelIndex(indexes+x,ApplyFunction(GetPixelIndex(indexes+x),function, number_parameters,parameters,exception)); 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_FunctionImageChannel) #endif proceed=SetImageProgress(image,FunctionImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l E n t r o p y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelEntropy() returns the entropy of one or more image channels. % % The format of the GetImageChannelEntropy method is: % % MagickBooleanType GetImageChannelEntropy(const Image *image, % const ChannelType channel,double *entropy,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o entropy: the average entropy of the selected channels. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageEntropy(const Image *image, double *entropy,ExceptionInfo *exception) { MagickBooleanType status; status=GetImageChannelEntropy(image,CompositeChannels,entropy,exception); return(status); } MagickExport MagickBooleanType GetImageChannelEntropy(const Image *image, const ChannelType channel,double *entropy,ExceptionInfo *exception) { ChannelStatistics *channel_statistics; size_t channels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageChannelStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); channels=0; channel_statistics[CompositeChannels].entropy=0.0; if ((channel & RedChannel) != 0) { channel_statistics[CompositeChannels].entropy+= channel_statistics[RedChannel].entropy; channels++; } if ((channel & GreenChannel) != 0) { channel_statistics[CompositeChannels].entropy+= channel_statistics[GreenChannel].entropy; channels++; } if ((channel & BlueChannel) != 0) { channel_statistics[CompositeChannels].entropy+= channel_statistics[BlueChannel].entropy; channels++; } if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) { channel_statistics[CompositeChannels].entropy+= channel_statistics[OpacityChannel].entropy; channels++; } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { channel_statistics[CompositeChannels].entropy+= channel_statistics[BlackChannel].entropy; channels++; } channel_statistics[CompositeChannels].entropy/=channels; *entropy=channel_statistics[CompositeChannels].entropy; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e C h a n n e l E x t r e m a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelExtrema() returns the extrema of one or more image channels. % % The format of the GetImageChannelExtrema method is: % % MagickBooleanType GetImageChannelExtrema(const Image *image, % const ChannelType channel,size_t *minima,size_t *maxima, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o minima: the minimum value in the channel. % % o maxima: the maximum value in the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageExtrema(const Image *image, size_t *minima,size_t *maxima,ExceptionInfo *exception) { MagickBooleanType status; status=GetImageChannelExtrema(image,CompositeChannels,minima,maxima, exception); return(status); } MagickExport MagickBooleanType GetImageChannelExtrema(const Image *image, const ChannelType channel,size_t *minima,size_t *maxima, ExceptionInfo *exception) { double max, min; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=GetImageChannelRange(image,channel,&min,&max,exception); *minima=(size_t) ceil(min-0.5); *maxima=(size_t) floor(max+0.5); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l K u r t o s i s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelKurtosis() returns the kurtosis and skewness of one or more % image channels. % % The format of the GetImageChannelKurtosis method is: % % MagickBooleanType GetImageChannelKurtosis(const Image *image, % const ChannelType channel,double *kurtosis,double *skewness, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o kurtosis: the kurtosis of the channel. % % o skewness: the skewness of the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageKurtosis(const Image *image, double *kurtosis,double *skewness,ExceptionInfo *exception) { MagickBooleanType status; status=GetImageChannelKurtosis(image,CompositeChannels,kurtosis,skewness, exception); return(status); } MagickExport MagickBooleanType GetImageChannelKurtosis(const Image *image, const ChannelType channel,double *kurtosis,double *skewness, ExceptionInfo *exception) { double area, mean, standard_deviation, sum_squares, sum_cubes, sum_fourth_power; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); *kurtosis=0.0; *skewness=0.0; area=0.0; mean=0.0; standard_deviation=0.0; sum_squares=0.0; sum_cubes=0.0; sum_fourth_power=0.0; 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=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) { mean+=GetPixelRed(p); sum_squares+=(double) GetPixelRed(p)*GetPixelRed(p); sum_cubes+=(double) GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p); sum_fourth_power+=(double) GetPixelRed(p)*GetPixelRed(p)* GetPixelRed(p)*GetPixelRed(p); area++; } if ((channel & GreenChannel) != 0) { mean+=GetPixelGreen(p); sum_squares+=(double) GetPixelGreen(p)*GetPixelGreen(p); sum_cubes+=(double) GetPixelGreen(p)*GetPixelGreen(p)* GetPixelGreen(p); sum_fourth_power+=(double) GetPixelGreen(p)*GetPixelGreen(p)* GetPixelGreen(p)*GetPixelGreen(p); area++; } if ((channel & BlueChannel) != 0) { mean+=GetPixelBlue(p); sum_squares+=(double) GetPixelBlue(p)*GetPixelBlue(p); sum_cubes+=(double) GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p); sum_fourth_power+=(double) GetPixelBlue(p)*GetPixelBlue(p)* GetPixelBlue(p)*GetPixelBlue(p); area++; } if ((channel & OpacityChannel) != 0) { mean+=GetPixelAlpha(p); sum_squares+=(double) GetPixelOpacity(p)*GetPixelAlpha(p); sum_cubes+=(double) GetPixelOpacity(p)*GetPixelAlpha(p)* GetPixelAlpha(p); sum_fourth_power+=(double) GetPixelAlpha(p)*GetPixelAlpha(p)* GetPixelAlpha(p)*GetPixelAlpha(p); area++; } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { double index; index=(double) GetPixelIndex(indexes+x); mean+=index; sum_squares+=index*index; sum_cubes+=index*index*index; sum_fourth_power+=index*index*index*index; area++; } p++; } } if (y < (ssize_t) image->rows) return(MagickFalse); if (area != 0.0) { mean/=area; sum_squares/=area; sum_cubes/=area; sum_fourth_power/=area; } standard_deviation=sqrt(sum_squares-(mean*mean)); if (standard_deviation != 0.0) { *kurtosis=sum_fourth_power-4.0*mean*sum_cubes+6.0*mean*mean*sum_squares- 3.0*mean*mean*mean*mean; *kurtosis/=standard_deviation*standard_deviation*standard_deviation* standard_deviation; *kurtosis-=3.0; *skewness=sum_cubes-3.0*mean*sum_squares+2.0*mean*mean*mean; *skewness/=standard_deviation*standard_deviation*standard_deviation; } return(y == (ssize_t) image->rows ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l M e a n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelMean() returns the mean and standard deviation of one or more % image channels. % % The format of the GetImageChannelMean method is: % % MagickBooleanType GetImageChannelMean(const Image *image, % const ChannelType channel,double *mean,double *standard_deviation, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o mean: the average value in the channel. % % o standard_deviation: the standard deviation of the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageMean(const Image *image,double *mean, double *standard_deviation,ExceptionInfo *exception) { MagickBooleanType status; status=GetImageChannelMean(image,CompositeChannels,mean,standard_deviation, exception); return(status); } MagickExport MagickBooleanType GetImageChannelMean(const Image *image, const ChannelType channel,double *mean,double *standard_deviation, ExceptionInfo *exception) { ChannelStatistics *channel_statistics; size_t channels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageChannelStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); channels=0; channel_statistics[CompositeChannels].mean=0.0; channel_statistics[CompositeChannels].standard_deviation=0.0; if ((channel & RedChannel) != 0) { channel_statistics[CompositeChannels].mean+= channel_statistics[RedChannel].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[RedChannel].standard_deviation; channels++; } if ((channel & GreenChannel) != 0) { channel_statistics[CompositeChannels].mean+= channel_statistics[GreenChannel].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[GreenChannel].standard_deviation; channels++; } if ((channel & BlueChannel) != 0) { channel_statistics[CompositeChannels].mean+= channel_statistics[BlueChannel].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[BlueChannel].standard_deviation; channels++; } if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) { channel_statistics[CompositeChannels].mean+= (QuantumRange-channel_statistics[OpacityChannel].mean); channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[OpacityChannel].standard_deviation; channels++; } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { channel_statistics[CompositeChannels].mean+= channel_statistics[BlackChannel].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[CompositeChannels].standard_deviation; channels++; } channel_statistics[CompositeChannels].mean/=channels; channel_statistics[CompositeChannels].standard_deviation/=channels; *mean=channel_statistics[CompositeChannels].mean; *standard_deviation=channel_statistics[CompositeChannels].standard_deviation; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l M o m e n t s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelMoments() returns the normalized moments of one or more image % channels. % % The format of the GetImageChannelMoments method is: % % ChannelMoments *GetImageChannelMoments(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 ChannelMoments *GetImageChannelMoments(const Image *image, ExceptionInfo *exception) { #define MaxNumberImageMoments 8 ChannelMoments *channel_moments; double M00[CompositeChannels+1], M01[CompositeChannels+1], M02[CompositeChannels+1], M03[CompositeChannels+1], M10[CompositeChannels+1], M11[CompositeChannels+1], M12[CompositeChannels+1], M20[CompositeChannels+1], M21[CompositeChannels+1], M22[CompositeChannels+1], M30[CompositeChannels+1]; MagickPixelPacket pixel; PointInfo centroid[CompositeChannels+1]; ssize_t channel, channels, y; size_t length; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); length=CompositeChannels+1UL; channel_moments=(ChannelMoments *) AcquireQuantumMemory(length, sizeof(*channel_moments)); if (channel_moments == (ChannelMoments *) NULL) return(channel_moments); (void) ResetMagickMemory(channel_moments,0,length*sizeof(*channel_moments)); (void) ResetMagickMemory(centroid,0,sizeof(centroid)); (void) ResetMagickMemory(M00,0,sizeof(M00)); (void) ResetMagickMemory(M01,0,sizeof(M01)); (void) ResetMagickMemory(M02,0,sizeof(M02)); (void) ResetMagickMemory(M03,0,sizeof(M03)); (void) ResetMagickMemory(M10,0,sizeof(M10)); (void) ResetMagickMemory(M11,0,sizeof(M11)); (void) ResetMagickMemory(M12,0,sizeof(M12)); (void) ResetMagickMemory(M20,0,sizeof(M20)); (void) ResetMagickMemory(M21,0,sizeof(M21)); (void) ResetMagickMemory(M22,0,sizeof(M22)); (void) ResetMagickMemory(M30,0,sizeof(M30)); GetMagickPixelPacket(image,&pixel); 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; /* Compute center of mass (centroid). */ p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,p,indexes+x,&pixel); M00[RedChannel]+=QuantumScale*pixel.red; M10[RedChannel]+=x*QuantumScale*pixel.red; M01[RedChannel]+=y*QuantumScale*pixel.red; M00[GreenChannel]+=QuantumScale*pixel.green; M10[GreenChannel]+=x*QuantumScale*pixel.green; M01[GreenChannel]+=y*QuantumScale*pixel.green; M00[BlueChannel]+=QuantumScale*pixel.blue; M10[BlueChannel]+=x*QuantumScale*pixel.blue; M01[BlueChannel]+=y*QuantumScale*pixel.blue; if (image->matte != MagickFalse) { M00[OpacityChannel]+=QuantumScale*pixel.opacity; M10[OpacityChannel]+=x*QuantumScale*pixel.opacity; M01[OpacityChannel]+=y*QuantumScale*pixel.opacity; } if (image->colorspace == CMYKColorspace) { M00[IndexChannel]+=QuantumScale*pixel.index; M10[IndexChannel]+=x*QuantumScale*pixel.index; M01[IndexChannel]+=y*QuantumScale*pixel.index; } p++; } } for (channel=0; channel <= CompositeChannels; channel++) { /* Compute center of mass (centroid). */ if (M00[channel] < MagickEpsilon) { M00[channel]+=MagickEpsilon; centroid[channel].x=(double) image->columns/2.0; centroid[channel].y=(double) image->rows/2.0; continue; } M00[channel]+=MagickEpsilon; centroid[channel].x=M10[channel]/M00[channel]; centroid[channel].y=M01[channel]/M00[channel]; } 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; /* Compute the image moments. */ p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,p,indexes+x,&pixel); M11[RedChannel]+=(x-centroid[RedChannel].x)*(y- centroid[RedChannel].y)*QuantumScale*pixel.red; M20[RedChannel]+=(x-centroid[RedChannel].x)*(x- centroid[RedChannel].x)*QuantumScale*pixel.red; M02[RedChannel]+=(y-centroid[RedChannel].y)*(y- centroid[RedChannel].y)*QuantumScale*pixel.red; M21[RedChannel]+=(x-centroid[RedChannel].x)*(x- centroid[RedChannel].x)*(y-centroid[RedChannel].y)*QuantumScale* pixel.red; M12[RedChannel]+=(x-centroid[RedChannel].x)*(y- centroid[RedChannel].y)*(y-centroid[RedChannel].y)*QuantumScale* pixel.red; M22[RedChannel]+=(x-centroid[RedChannel].x)*(x- centroid[RedChannel].x)*(y-centroid[RedChannel].y)*(y- centroid[RedChannel].y)*QuantumScale*pixel.red; M30[RedChannel]+=(x-centroid[RedChannel].x)*(x- centroid[RedChannel].x)*(x-centroid[RedChannel].x)*QuantumScale* pixel.red; M03[RedChannel]+=(y-centroid[RedChannel].y)*(y- centroid[RedChannel].y)*(y-centroid[RedChannel].y)*QuantumScale* pixel.red; M11[GreenChannel]+=(x-centroid[GreenChannel].x)*(y- centroid[GreenChannel].y)*QuantumScale*pixel.green; M20[GreenChannel]+=(x-centroid[GreenChannel].x)*(x- centroid[GreenChannel].x)*QuantumScale*pixel.green; M02[GreenChannel]+=(y-centroid[GreenChannel].y)*(y- centroid[GreenChannel].y)*QuantumScale*pixel.green; M21[GreenChannel]+=(x-centroid[GreenChannel].x)*(x- centroid[GreenChannel].x)*(y-centroid[GreenChannel].y)*QuantumScale* pixel.green; M12[GreenChannel]+=(x-centroid[GreenChannel].x)*(y- centroid[GreenChannel].y)*(y-centroid[GreenChannel].y)*QuantumScale* pixel.green; M22[GreenChannel]+=(x-centroid[GreenChannel].x)*(x- centroid[GreenChannel].x)*(y-centroid[GreenChannel].y)*(y- centroid[GreenChannel].y)*QuantumScale*pixel.green; M30[GreenChannel]+=(x-centroid[GreenChannel].x)*(x- centroid[GreenChannel].x)*(x-centroid[GreenChannel].x)*QuantumScale* pixel.green; M03[GreenChannel]+=(y-centroid[GreenChannel].y)*(y- centroid[GreenChannel].y)*(y-centroid[GreenChannel].y)*QuantumScale* pixel.green; M11[BlueChannel]+=(x-centroid[BlueChannel].x)*(y- centroid[BlueChannel].y)*QuantumScale*pixel.blue; M20[BlueChannel]+=(x-centroid[BlueChannel].x)*(x- centroid[BlueChannel].x)*QuantumScale*pixel.blue; M02[BlueChannel]+=(y-centroid[BlueChannel].y)*(y- centroid[BlueChannel].y)*QuantumScale*pixel.blue; M21[BlueChannel]+=(x-centroid[BlueChannel].x)*(x- centroid[BlueChannel].x)*(y-centroid[BlueChannel].y)*QuantumScale* pixel.blue; M12[BlueChannel]+=(x-centroid[BlueChannel].x)*(y- centroid[BlueChannel].y)*(y-centroid[BlueChannel].y)*QuantumScale* pixel.blue; M22[BlueChannel]+=(x-centroid[BlueChannel].x)*(x- centroid[BlueChannel].x)*(y-centroid[BlueChannel].y)*(y- centroid[BlueChannel].y)*QuantumScale*pixel.blue; M30[BlueChannel]+=(x-centroid[BlueChannel].x)*(x- centroid[BlueChannel].x)*(x-centroid[BlueChannel].x)*QuantumScale* pixel.blue; M03[BlueChannel]+=(y-centroid[BlueChannel].y)*(y- centroid[BlueChannel].y)*(y-centroid[BlueChannel].y)*QuantumScale* pixel.blue; if (image->matte != MagickFalse) { M11[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(y- centroid[OpacityChannel].y)*QuantumScale*pixel.opacity; M20[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x- centroid[OpacityChannel].x)*QuantumScale*pixel.opacity; M02[OpacityChannel]+=(y-centroid[OpacityChannel].y)*(y- centroid[OpacityChannel].y)*QuantumScale*pixel.opacity; M21[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x- centroid[OpacityChannel].x)*(y-centroid[OpacityChannel].y)* QuantumScale*pixel.opacity; M12[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(y- centroid[OpacityChannel].y)*(y-centroid[OpacityChannel].y)* QuantumScale*pixel.opacity; M22[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x- centroid[OpacityChannel].x)*(y-centroid[OpacityChannel].y)*(y- centroid[OpacityChannel].y)*QuantumScale*pixel.opacity; M30[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x- centroid[OpacityChannel].x)*(x-centroid[OpacityChannel].x)* QuantumScale*pixel.opacity; M03[OpacityChannel]+=(y-centroid[OpacityChannel].y)*(y- centroid[OpacityChannel].y)*(y-centroid[OpacityChannel].y)* QuantumScale*pixel.opacity; } if (image->colorspace == CMYKColorspace) { M11[IndexChannel]+=(x-centroid[IndexChannel].x)*(y- centroid[IndexChannel].y)*QuantumScale*pixel.index; M20[IndexChannel]+=(x-centroid[IndexChannel].x)*(x- centroid[IndexChannel].x)*QuantumScale*pixel.index; M02[IndexChannel]+=(y-centroid[IndexChannel].y)*(y- centroid[IndexChannel].y)*QuantumScale*pixel.index; M21[IndexChannel]+=(x-centroid[IndexChannel].x)*(x- centroid[IndexChannel].x)*(y-centroid[IndexChannel].y)* QuantumScale*pixel.index; M12[IndexChannel]+=(x-centroid[IndexChannel].x)*(y- centroid[IndexChannel].y)*(y-centroid[IndexChannel].y)* QuantumScale*pixel.index; M22[IndexChannel]+=(x-centroid[IndexChannel].x)*(x- centroid[IndexChannel].x)*(y-centroid[IndexChannel].y)*(y- centroid[IndexChannel].y)*QuantumScale*pixel.index; M30[IndexChannel]+=(x-centroid[IndexChannel].x)*(x- centroid[IndexChannel].x)*(x-centroid[IndexChannel].x)* QuantumScale*pixel.index; M03[IndexChannel]+=(y-centroid[IndexChannel].y)*(y- centroid[IndexChannel].y)*(y-centroid[IndexChannel].y)* QuantumScale*pixel.index; } p++; } } channels=3; M00[CompositeChannels]+=(M00[RedChannel]+M00[GreenChannel]+M00[BlueChannel]); M01[CompositeChannels]+=(M01[RedChannel]+M01[GreenChannel]+M01[BlueChannel]); M02[CompositeChannels]+=(M02[RedChannel]+M02[GreenChannel]+M02[BlueChannel]); M03[CompositeChannels]+=(M03[RedChannel]+M03[GreenChannel]+M03[BlueChannel]); M10[CompositeChannels]+=(M10[RedChannel]+M10[GreenChannel]+M10[BlueChannel]); M11[CompositeChannels]+=(M11[RedChannel]+M11[GreenChannel]+M11[BlueChannel]); M12[CompositeChannels]+=(M12[RedChannel]+M12[GreenChannel]+M12[BlueChannel]); M20[CompositeChannels]+=(M20[RedChannel]+M20[GreenChannel]+M20[BlueChannel]); M21[CompositeChannels]+=(M21[RedChannel]+M21[GreenChannel]+M21[BlueChannel]); M22[CompositeChannels]+=(M22[RedChannel]+M22[GreenChannel]+M22[BlueChannel]); M30[CompositeChannels]+=(M30[RedChannel]+M30[GreenChannel]+M30[BlueChannel]); if (image->matte != MagickFalse) { channels+=1; M00[CompositeChannels]+=M00[OpacityChannel]; M01[CompositeChannels]+=M01[OpacityChannel]; M02[CompositeChannels]+=M02[OpacityChannel]; M03[CompositeChannels]+=M03[OpacityChannel]; M10[CompositeChannels]+=M10[OpacityChannel]; M11[CompositeChannels]+=M11[OpacityChannel]; M12[CompositeChannels]+=M12[OpacityChannel]; M20[CompositeChannels]+=M20[OpacityChannel]; M21[CompositeChannels]+=M21[OpacityChannel]; M22[CompositeChannels]+=M22[OpacityChannel]; M30[CompositeChannels]+=M30[OpacityChannel]; } if (image->colorspace == CMYKColorspace) { channels+=1; M00[CompositeChannels]+=M00[IndexChannel]; M01[CompositeChannels]+=M01[IndexChannel]; M02[CompositeChannels]+=M02[IndexChannel]; M03[CompositeChannels]+=M03[IndexChannel]; M10[CompositeChannels]+=M10[IndexChannel]; M11[CompositeChannels]+=M11[IndexChannel]; M12[CompositeChannels]+=M12[IndexChannel]; M20[CompositeChannels]+=M20[IndexChannel]; M21[CompositeChannels]+=M21[IndexChannel]; M22[CompositeChannels]+=M22[IndexChannel]; M30[CompositeChannels]+=M30[IndexChannel]; } M00[CompositeChannels]/=(double) channels; M01[CompositeChannels]/=(double) channels; M02[CompositeChannels]/=(double) channels; M03[CompositeChannels]/=(double) channels; M10[CompositeChannels]/=(double) channels; M11[CompositeChannels]/=(double) channels; M12[CompositeChannels]/=(double) channels; M20[CompositeChannels]/=(double) channels; M21[CompositeChannels]/=(double) channels; M22[CompositeChannels]/=(double) channels; M30[CompositeChannels]/=(double) channels; for (channel=0; channel <= CompositeChannels; channel++) { /* Compute elliptical angle, major and minor axes, eccentricity, & intensity. */ channel_moments[channel].centroid=centroid[channel]; channel_moments[channel].ellipse_axis.x=sqrt((2.0/M00[channel])* ((M20[channel]+M02[channel])+sqrt(4.0*M11[channel]*M11[channel]+ (M20[channel]-M02[channel])*(M20[channel]-M02[channel])))); channel_moments[channel].ellipse_axis.y=sqrt((2.0/M00[channel])* ((M20[channel]+M02[channel])-sqrt(4.0*M11[channel]*M11[channel]+ (M20[channel]-M02[channel])*(M20[channel]-M02[channel])))); channel_moments[channel].ellipse_angle=RadiansToDegrees(0.5*atan(2.0* M11[channel]/(M20[channel]-M02[channel]+MagickEpsilon))); if (fabs(M11[channel]) < MagickEpsilon) { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=0.0; } else if (M11[channel] < 0.0) { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=180.0; } else { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=0.0; } channel_moments[channel].ellipse_eccentricity=sqrt(1.0-( channel_moments[channel].ellipse_axis.y/ (channel_moments[channel].ellipse_axis.x+MagickEpsilon))); channel_moments[channel].ellipse_intensity=M00[channel]/ (MagickPI*channel_moments[channel].ellipse_axis.x* channel_moments[channel].ellipse_axis.y+MagickEpsilon); } for (channel=0; channel <= CompositeChannels; channel++) { /* Normalize image moments. */ M10[channel]=0.0; M01[channel]=0.0; M11[channel]/=pow(M00[channel],1.0+(1.0+1.0)/2.0); M20[channel]/=pow(M00[channel],1.0+(2.0+0.0)/2.0); M02[channel]/=pow(M00[channel],1.0+(0.0+2.0)/2.0); M21[channel]/=pow(M00[channel],1.0+(2.0+1.0)/2.0); M12[channel]/=pow(M00[channel],1.0+(1.0+2.0)/2.0); M22[channel]/=pow(M00[channel],1.0+(2.0+2.0)/2.0); M30[channel]/=pow(M00[channel],1.0+(3.0+0.0)/2.0); M03[channel]/=pow(M00[channel],1.0+(0.0+3.0)/2.0); M00[channel]=1.0; } for (channel=0; channel <= CompositeChannels; channel++) { /* Compute Hu invariant moments. */ channel_moments[channel].I[0]=M20[channel]+M02[channel]; channel_moments[channel].I[1]=(M20[channel]-M02[channel])* (M20[channel]-M02[channel])+4.0*M11[channel]*M11[channel]; channel_moments[channel].I[2]=(M30[channel]-3.0*M12[channel])* (M30[channel]-3.0*M12[channel])+(3.0*M21[channel]-M03[channel])* (3.0*M21[channel]-M03[channel]); channel_moments[channel].I[3]=(M30[channel]+M12[channel])* (M30[channel]+M12[channel])+(M21[channel]+M03[channel])* (M21[channel]+M03[channel]); channel_moments[channel].I[4]=(M30[channel]-3.0*M12[channel])* (M30[channel]+M12[channel])*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])* (M21[channel]+M03[channel]))+(3.0*M21[channel]-M03[channel])* (M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M21[channel]+M03[channel])* (M21[channel]+M03[channel])); channel_moments[channel].I[5]=(M20[channel]-M02[channel])* ((M30[channel]+M12[channel])*(M30[channel]+M12[channel])- (M21[channel]+M03[channel])*(M21[channel]+M03[channel]))+ 4.0*M11[channel]*(M30[channel]+M12[channel])*(M21[channel]+M03[channel]); channel_moments[channel].I[6]=(3.0*M21[channel]-M03[channel])* (M30[channel]+M12[channel])*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])* (M21[channel]+M03[channel]))-(M30[channel]-3*M12[channel])* (M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M21[channel]+M03[channel])* (M21[channel]+M03[channel])); channel_moments[channel].I[7]=M11[channel]*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M03[channel]+M21[channel])* (M03[channel]+M21[channel]))-(M20[channel]-M02[channel])* (M30[channel]+M12[channel])*(M03[channel]+M21[channel]); } if (y < (ssize_t) image->rows) channel_moments=(ChannelMoments *) RelinquishMagickMemory(channel_moments); return(channel_moments); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l P e r c e p t u a l H a s h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelPerceptualHash() returns the perceptual hash of one or more % image channels. % % The format of the GetImageChannelPerceptualHash method is: % % ChannelPerceptualHash *GetImageChannelPerceptualHash(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 inline double MagickLog10(const double x) { #define Log10Epsilon (1.0e-11) if (fabs(x) < Log10Epsilon) return(log10(Log10Epsilon)); return(log10(fabs(x))); } MagickExport ChannelPerceptualHash *GetImageChannelPerceptualHash( const Image *image,ExceptionInfo *exception) { ChannelMoments *moments; ChannelPerceptualHash *perceptual_hash; Image *hash_image; MagickBooleanType status; register ssize_t i; ssize_t channel; /* Blur then transform to sRGB colorspace. */ hash_image=BlurImage(image,0.0,1.0,exception); if (hash_image == (Image *) NULL) return((ChannelPerceptualHash *) NULL); hash_image->depth=8; status=TransformImageColorspace(hash_image,sRGBColorspace); if (status == MagickFalse) return((ChannelPerceptualHash *) NULL); moments=GetImageChannelMoments(hash_image,exception); hash_image=DestroyImage(hash_image); if (moments == (ChannelMoments *) NULL) return((ChannelPerceptualHash *) NULL); perceptual_hash=(ChannelPerceptualHash *) AcquireQuantumMemory( CompositeChannels+1UL,sizeof(*perceptual_hash)); if (perceptual_hash == (ChannelPerceptualHash *) NULL) return((ChannelPerceptualHash *) NULL); for (channel=0; channel <= CompositeChannels; channel++) for (i=0; i < MaximumNumberOfImageMoments; i++) perceptual_hash[channel].P[i]=(-MagickLog10(moments[channel].I[i])); moments=(ChannelMoments *) RelinquishMagickMemory(moments); /* Blur then transform to HCLp colorspace. */ hash_image=BlurImage(image,0.0,1.0,exception); if (hash_image == (Image *) NULL) { perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory( perceptual_hash); return((ChannelPerceptualHash *) NULL); } hash_image->depth=8; status=TransformImageColorspace(hash_image,HCLpColorspace); if (status == MagickFalse) { perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory( perceptual_hash); return((ChannelPerceptualHash *) NULL); } moments=GetImageChannelMoments(hash_image,exception); hash_image=DestroyImage(hash_image); if (moments == (ChannelMoments *) NULL) { perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory( perceptual_hash); return((ChannelPerceptualHash *) NULL); } for (channel=0; channel <= CompositeChannels; channel++) for (i=0; i < MaximumNumberOfImageMoments; i++) perceptual_hash[channel].Q[i]=(-MagickLog10(moments[channel].I[i])); moments=(ChannelMoments *) RelinquishMagickMemory(moments); return(perceptual_hash); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l R a n g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelRange() returns the range of one or more image channels. % % The format of the GetImageChannelRange method is: % % MagickBooleanType GetImageChannelRange(const Image *image, % const ChannelType channel,double *minima,double *maxima, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o minima: the minimum value in the channel. % % o maxima: the maximum value in the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageRange(const Image *image, double *minima,double *maxima,ExceptionInfo *exception) { return(GetImageChannelRange(image,CompositeChannels,minima,maxima,exception)); } MagickExport MagickBooleanType GetImageChannelRange(const Image *image, const ChannelType channel,double *minima,double *maxima, ExceptionInfo *exception) { MagickPixelPacket pixel; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); *maxima=(-MagickMaximumValue); *minima=MagickMaximumValue; GetMagickPixelPacket(image,&pixel); 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=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,p,indexes+x,&pixel); if ((channel & RedChannel) != 0) { if (pixel.red < *minima) *minima=(double) pixel.red; if (pixel.red > *maxima) *maxima=(double) pixel.red; } if ((channel & GreenChannel) != 0) { if (pixel.green < *minima) *minima=(double) pixel.green; if (pixel.green > *maxima) *maxima=(double) pixel.green; } if ((channel & BlueChannel) != 0) { if (pixel.blue < *minima) *minima=(double) pixel.blue; if (pixel.blue > *maxima) *maxima=(double) pixel.blue; } if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) { if ((QuantumRange-pixel.opacity) < *minima) *minima=(double) (QuantumRange-pixel.opacity); if ((QuantumRange-pixel.opacity) > *maxima) *maxima=(double) (QuantumRange-pixel.opacity); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { if ((double) pixel.index < *minima) *minima=(double) pixel.index; if ((double) pixel.index > *maxima) *maxima=(double) pixel.index; } p++; } } return(y == (ssize_t) image->rows ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l S t a t i s t i c s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelStatistics() returns statistics for each channel in the % image. The statistics include the channel depth, its minima, maxima, mean, % standard deviation, kurtosis and skewness. You can access the red channel % mean, for example, like this: % % channel_statistics=GetImageChannelStatistics(image,exception); % red_mean=channel_statistics[RedChannel].mean; % % Use MagickRelinquishMemory() to free the statistics buffer. % % The format of the GetImageChannelStatistics method is: % % ChannelStatistics *GetImageChannelStatistics(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 ChannelStatistics *GetImageChannelStatistics(const Image *image, ExceptionInfo *exception) { ChannelStatistics *channel_statistics; double area, standard_deviation; MagickPixelPacket number_bins, *histogram; QuantumAny range; register ssize_t i; size_t channels, depth, length; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); length=CompositeChannels+1UL; channel_statistics=(ChannelStatistics *) AcquireQuantumMemory(length, sizeof(*channel_statistics)); histogram=(MagickPixelPacket *) AcquireQuantumMemory(MaxMap+1U, sizeof(*histogram)); if ((channel_statistics == (ChannelStatistics *) NULL) || (histogram == (MagickPixelPacket *) NULL)) { if (histogram != (MagickPixelPacket *) NULL) histogram=(MagickPixelPacket *) RelinquishMagickMemory(histogram); if (channel_statistics != (ChannelStatistics *) NULL) channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(channel_statistics); } (void) ResetMagickMemory(channel_statistics,0,length* sizeof(*channel_statistics)); for (i=0; i <= (ssize_t) CompositeChannels; i++) { channel_statistics[i].depth=1; channel_statistics[i].maxima=(-MagickMaximumValue); channel_statistics[i].minima=MagickMaximumValue; } (void) ResetMagickMemory(histogram,0,(MaxMap+1U)*sizeof(*histogram)); (void) ResetMagickMemory(&number_bins,0,sizeof(number_bins)); 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; /* Compute pixel statistics. */ p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; ) { if (channel_statistics[RedChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[RedChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelRed(p),range) == MagickFalse) { channel_statistics[RedChannel].depth++; continue; } } if (channel_statistics[GreenChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[GreenChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelGreen(p),range) == MagickFalse) { channel_statistics[GreenChannel].depth++; continue; } } if (channel_statistics[BlueChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[BlueChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelBlue(p),range) == MagickFalse) { channel_statistics[BlueChannel].depth++; continue; } } if (image->matte != MagickFalse) { if (channel_statistics[OpacityChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[OpacityChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelAlpha(p),range) == MagickFalse) { channel_statistics[OpacityChannel].depth++; continue; } } } if (image->colorspace == CMYKColorspace) { if (channel_statistics[BlackChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[BlackChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelIndex(indexes+x),range) == MagickFalse) { channel_statistics[BlackChannel].depth++; continue; } } } if ((double) GetPixelRed(p) < channel_statistics[RedChannel].minima) channel_statistics[RedChannel].minima=(double) GetPixelRed(p); if ((double) GetPixelRed(p) > channel_statistics[RedChannel].maxima) channel_statistics[RedChannel].maxima=(double) GetPixelRed(p); channel_statistics[RedChannel].sum+=GetPixelRed(p); channel_statistics[RedChannel].sum_squared+=(double) GetPixelRed(p)* GetPixelRed(p); channel_statistics[RedChannel].sum_cubed+=(double) GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p); channel_statistics[RedChannel].sum_fourth_power+=(double) GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p); if ((double) GetPixelGreen(p) < channel_statistics[GreenChannel].minima) channel_statistics[GreenChannel].minima=(double) GetPixelGreen(p); if ((double) GetPixelGreen(p) > channel_statistics[GreenChannel].maxima) channel_statistics[GreenChannel].maxima=(double) GetPixelGreen(p); channel_statistics[GreenChannel].sum+=GetPixelGreen(p); channel_statistics[GreenChannel].sum_squared+=(double) GetPixelGreen(p)* GetPixelGreen(p); channel_statistics[GreenChannel].sum_cubed+=(double) GetPixelGreen(p)* GetPixelGreen(p)*GetPixelGreen(p); channel_statistics[GreenChannel].sum_fourth_power+=(double) GetPixelGreen(p)*GetPixelGreen(p)*GetPixelGreen(p)*GetPixelGreen(p); if ((double) GetPixelBlue(p) < channel_statistics[BlueChannel].minima) channel_statistics[BlueChannel].minima=(double) GetPixelBlue(p); if ((double) GetPixelBlue(p) > channel_statistics[BlueChannel].maxima) channel_statistics[BlueChannel].maxima=(double) GetPixelBlue(p); channel_statistics[BlueChannel].sum+=GetPixelBlue(p); channel_statistics[BlueChannel].sum_squared+=(double) GetPixelBlue(p)* GetPixelBlue(p); channel_statistics[BlueChannel].sum_cubed+=(double) GetPixelBlue(p)* GetPixelBlue(p)*GetPixelBlue(p); channel_statistics[BlueChannel].sum_fourth_power+=(double) GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p); histogram[ScaleQuantumToMap(GetPixelRed(p))].red++; histogram[ScaleQuantumToMap(GetPixelGreen(p))].green++; histogram[ScaleQuantumToMap(GetPixelBlue(p))].blue++; if (image->matte != MagickFalse) { if ((double) GetPixelAlpha(p) < channel_statistics[OpacityChannel].minima) channel_statistics[OpacityChannel].minima=(double) GetPixelAlpha(p); if ((double) GetPixelAlpha(p) > channel_statistics[OpacityChannel].maxima) channel_statistics[OpacityChannel].maxima=(double) GetPixelAlpha(p); channel_statistics[OpacityChannel].sum+=GetPixelAlpha(p); channel_statistics[OpacityChannel].sum_squared+=(double) GetPixelAlpha(p)*GetPixelAlpha(p); channel_statistics[OpacityChannel].sum_cubed+=(double) GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p); channel_statistics[OpacityChannel].sum_fourth_power+=(double) GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p); histogram[ScaleQuantumToMap(GetPixelAlpha(p))].opacity++; } if (image->colorspace == CMYKColorspace) { if ((double) GetPixelIndex(indexes+x) < channel_statistics[BlackChannel].minima) channel_statistics[BlackChannel].minima=(double) GetPixelIndex(indexes+x); if ((double) GetPixelIndex(indexes+x) > channel_statistics[BlackChannel].maxima) channel_statistics[BlackChannel].maxima=(double) GetPixelIndex(indexes+x); channel_statistics[BlackChannel].sum+=GetPixelIndex(indexes+x); channel_statistics[BlackChannel].sum_squared+=(double) GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x); channel_statistics[BlackChannel].sum_cubed+=(double) GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x)* GetPixelIndex(indexes+x); channel_statistics[BlackChannel].sum_fourth_power+=(double) GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x)* GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x); histogram[ScaleQuantumToMap(GetPixelIndex(indexes+x))].index++; } x++; p++; } } for (i=0; i < (ssize_t) CompositeChannels; i++) { double area, mean, standard_deviation; /* Normalize pixel statistics. */ area=PerceptibleReciprocal((double) image->columns*image->rows); mean=channel_statistics[i].sum*area; channel_statistics[i].sum=mean; channel_statistics[i].sum_squared*=area; channel_statistics[i].sum_cubed*=area; channel_statistics[i].sum_fourth_power*=area; channel_statistics[i].mean=mean; channel_statistics[i].variance=channel_statistics[i].sum_squared; standard_deviation=sqrt(channel_statistics[i].variance-(mean*mean)); area=PerceptibleReciprocal((double) image->columns*image->rows-1.0)* ((double) image->columns*image->rows); standard_deviation=sqrt(area*standard_deviation*standard_deviation); channel_statistics[i].standard_deviation=standard_deviation; } for (i=0; i < (ssize_t) (MaxMap+1U); i++) { if (histogram[i].red > 0.0) number_bins.red++; if (histogram[i].green > 0.0) number_bins.green++; if (histogram[i].blue > 0.0) number_bins.blue++; if ((image->matte != MagickFalse) && (histogram[i].opacity > 0.0)) number_bins.opacity++; if ((image->colorspace == CMYKColorspace) && (histogram[i].index > 0.0)) number_bins.index++; } area=PerceptibleReciprocal((double) image->columns*image->rows); for (i=0; i < (ssize_t) (MaxMap+1U); i++) { /* Compute pixel entropy. */ histogram[i].red*=area; if (number_bins.red > MagickEpsilon) channel_statistics[RedChannel].entropy+=-histogram[i].red* MagickLog10(histogram[i].red)/MagickLog10((double) number_bins.red); histogram[i].green*=area; if (number_bins.green > MagickEpsilon) channel_statistics[GreenChannel].entropy+=-histogram[i].green* MagickLog10(histogram[i].green)/MagickLog10((double) number_bins.green); histogram[i].blue*=area; if (number_bins.blue > MagickEpsilon) channel_statistics[BlueChannel].entropy+=-histogram[i].blue* MagickLog10(histogram[i].blue)/MagickLog10((double) number_bins.blue); if (image->matte != MagickFalse) { histogram[i].opacity*=area; if (number_bins.opacity > MagickEpsilon) channel_statistics[OpacityChannel].entropy+=-histogram[i].opacity* MagickLog10(histogram[i].opacity)/MagickLog10((double) number_bins.opacity); } if (image->colorspace == CMYKColorspace) { histogram[i].index*=area; if (number_bins.index > MagickEpsilon) channel_statistics[IndexChannel].entropy+=-histogram[i].index* MagickLog10(histogram[i].index)/MagickLog10((double) number_bins.index); } } /* Compute overall statistics. */ for (i=0; i < (ssize_t) CompositeChannels; i++) { channel_statistics[CompositeChannels].depth=(size_t) EvaluateMax((double) channel_statistics[CompositeChannels].depth,(double) channel_statistics[i].depth); channel_statistics[CompositeChannels].minima=MagickMin( channel_statistics[CompositeChannels].minima, channel_statistics[i].minima); channel_statistics[CompositeChannels].maxima=EvaluateMax( channel_statistics[CompositeChannels].maxima, channel_statistics[i].maxima); channel_statistics[CompositeChannels].sum+=channel_statistics[i].sum; channel_statistics[CompositeChannels].sum_squared+= channel_statistics[i].sum_squared; channel_statistics[CompositeChannels].sum_cubed+= channel_statistics[i].sum_cubed; channel_statistics[CompositeChannels].sum_fourth_power+= channel_statistics[i].sum_fourth_power; channel_statistics[CompositeChannels].mean+=channel_statistics[i].mean; channel_statistics[CompositeChannels].variance+= channel_statistics[i].variance-channel_statistics[i].mean* channel_statistics[i].mean; standard_deviation=sqrt(channel_statistics[i].variance- (channel_statistics[i].mean*channel_statistics[i].mean)); area=PerceptibleReciprocal((double) image->columns*image->rows-1.0)* ((double) image->columns*image->rows); standard_deviation=sqrt(area*standard_deviation*standard_deviation); channel_statistics[CompositeChannels].standard_deviation=standard_deviation; channel_statistics[CompositeChannels].entropy+= channel_statistics[i].entropy; } channels=3; if (image->matte != MagickFalse) channels++; if (image->colorspace == CMYKColorspace) channels++; channel_statistics[CompositeChannels].sum/=channels; channel_statistics[CompositeChannels].sum_squared/=channels; channel_statistics[CompositeChannels].sum_cubed/=channels; channel_statistics[CompositeChannels].sum_fourth_power/=channels; channel_statistics[CompositeChannels].mean/=channels; channel_statistics[CompositeChannels].kurtosis/=channels; channel_statistics[CompositeChannels].skewness/=channels; channel_statistics[CompositeChannels].entropy/=channels; i=CompositeChannels; area=PerceptibleReciprocal((double) channels*image->columns*image->rows); channel_statistics[i].variance=channel_statistics[i].sum_squared; channel_statistics[i].mean=channel_statistics[i].sum; standard_deviation=sqrt(channel_statistics[i].variance- (channel_statistics[i].mean*channel_statistics[i].mean)); standard_deviation=sqrt(PerceptibleReciprocal((double) channels* image->columns*image->rows-1.0)*channels*image->columns*image->rows* standard_deviation*standard_deviation); channel_statistics[i].standard_deviation=standard_deviation; for (i=0; i <= (ssize_t) CompositeChannels; i++) { /* Compute kurtosis & skewness statistics. */ standard_deviation=PerceptibleReciprocal( channel_statistics[i].standard_deviation); channel_statistics[i].skewness=(channel_statistics[i].sum_cubed-3.0* channel_statistics[i].mean*channel_statistics[i].sum_squared+2.0* channel_statistics[i].mean*channel_statistics[i].mean* channel_statistics[i].mean)*(standard_deviation*standard_deviation* standard_deviation); channel_statistics[i].kurtosis=(channel_statistics[i].sum_fourth_power-4.0* channel_statistics[i].mean*channel_statistics[i].sum_cubed+6.0* channel_statistics[i].mean*channel_statistics[i].mean* channel_statistics[i].sum_squared-3.0*channel_statistics[i].mean* channel_statistics[i].mean*1.0*channel_statistics[i].mean* channel_statistics[i].mean)*(standard_deviation*standard_deviation* standard_deviation*standard_deviation)-3.0; } channel_statistics[CompositeChannels].mean=0.0; channel_statistics[CompositeChannels].standard_deviation=0.0; for (i=0; i < (ssize_t) CompositeChannels; i++) { channel_statistics[CompositeChannels].mean+= channel_statistics[i].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[i].standard_deviation; } channel_statistics[CompositeChannels].mean/=(double) channels; channel_statistics[CompositeChannels].standard_deviation/=(double) channels; histogram=(MagickPixelPacket *) RelinquishMagickMemory(histogram); if (y < (ssize_t) image->rows) channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(channel_statistics); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P o l y n o m i a l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PolynomialImage() returns a new image where each pixel is the sum of the % pixels in the image sequence after applying its corresponding terms % (coefficient and degree pairs). % % The format of the PolynomialImage method is: % % Image *PolynomialImage(const Image *images,const size_t number_terms, % const double *terms,ExceptionInfo *exception) % Image *PolynomialImageChannel(const Image *images, % const size_t number_terms,const ChannelType channel, % const double *terms,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o channel: the channel. % % o number_terms: the number of terms in the list. The actual list length % is 2 x number_terms + 1 (the constant). % % o terms: the list of polynomial coefficients and degree pairs and a % constant. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *PolynomialImage(const Image *images, const size_t number_terms,const double *terms,ExceptionInfo *exception) { Image *polynomial_image; polynomial_image=PolynomialImageChannel(images,DefaultChannels,number_terms, terms,exception); return(polynomial_image); } MagickExport Image *PolynomialImageChannel(const Image *images, const ChannelType channel,const size_t number_terms,const double *terms, ExceptionInfo *exception) { #define PolynomialImageTag "Polynomial/Image" CacheView *polynomial_view; Image *image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket **magick_restrict polynomial_pixels, zero; size_t number_images; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImageCanvas(images,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImage(image); return((Image *) NULL); } number_images=GetImageListLength(images); polynomial_pixels=AcquirePixelThreadSet(images,number_images); if (polynomial_pixels == (MagickPixelPacket **) NULL) { image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return((Image *) NULL); } /* Polynomial image pixels. */ status=MagickTrue; progress=0; GetMagickPixelPacket(images,&zero); polynomial_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict polynomial_indexes; register MagickPixelPacket *polynomial_pixel; register PixelPacket *magick_restrict q; register ssize_t i, x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(polynomial_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } polynomial_indexes=GetCacheViewAuthenticIndexQueue(polynomial_view); polynomial_pixel=polynomial_pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) polynomial_pixel[x]=zero; next=images; for (i=0; i < (ssize_t) number_images; i++) { register const IndexPacket *indexes; register const PixelPacket *p; if (i >= (ssize_t) number_terms) break; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) { image_view=DestroyCacheView(image_view); break; } indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { double coefficient, degree; coefficient=terms[i << 1]; degree=terms[(i << 1)+1]; if ((channel & RedChannel) != 0) polynomial_pixel[x].red+=coefficient*pow(QuantumScale*p->red,degree); if ((channel & GreenChannel) != 0) polynomial_pixel[x].green+=coefficient*pow(QuantumScale*p->green, degree); if ((channel & BlueChannel) != 0) polynomial_pixel[x].blue+=coefficient*pow(QuantumScale*p->blue, degree); if ((channel & OpacityChannel) != 0) polynomial_pixel[x].opacity+=coefficient*pow(QuantumScale* (QuantumRange-p->opacity),degree); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) polynomial_pixel[x].index+=coefficient*pow(QuantumScale*indexes[x], degree); p++; } image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].red)); SetPixelGreen(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].green)); SetPixelBlue(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].blue)); if (image->matte == MagickFalse) SetPixelOpacity(q,ClampToQuantum(QuantumRange-QuantumRange* polynomial_pixel[x].opacity)); else SetPixelAlpha(q,ClampToQuantum(QuantumRange-QuantumRange* polynomial_pixel[x].opacity)); if (image->colorspace == CMYKColorspace) SetPixelIndex(polynomial_indexes+x,ClampToQuantum(QuantumRange* polynomial_pixel[x].index)); q++; } if (SyncCacheViewAuthenticPixels(polynomial_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_PolynomialImages) #endif proceed=SetImageProgress(images,PolynomialImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } polynomial_view=DestroyCacheView(polynomial_view); polynomial_pixels=DestroyPixelThreadSet(polynomial_pixels); if (status == MagickFalse) image=DestroyImage(image); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t a t i s t i c I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % StatisticImage() makes each pixel the min / max / median / mode / etc. of % the neighborhood of the specified width and height. % % The format of the StatisticImage method is: % % Image *StatisticImage(const Image *image,const StatisticType type, % const size_t width,const size_t height,ExceptionInfo *exception) % Image *StatisticImageChannel(const Image *image, % const ChannelType channel,const StatisticType type, % const size_t width,const size_t height,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the image channel. % % o type: the statistic type (median, mode, etc.). % % o width: the width of the pixel neighborhood. % % o height: the height of the pixel neighborhood. % % o exception: return any errors or warnings in this structure. % */ #define ListChannels 5 typedef struct _ListNode { size_t next[9], count, signature; } ListNode; typedef struct _SkipList { ssize_t level; ListNode *nodes; } SkipList; typedef struct _PixelList { size_t length, seed, signature; SkipList lists[ListChannels]; } PixelList; static PixelList *DestroyPixelList(PixelList *pixel_list) { register ssize_t i; if (pixel_list == (PixelList *) NULL) return((PixelList *) NULL); for (i=0; i < ListChannels; i++) if (pixel_list->lists[i].nodes != (ListNode *) NULL) pixel_list->lists[i].nodes=(ListNode *) RelinquishAlignedMemory( pixel_list->lists[i].nodes); pixel_list=(PixelList *) RelinquishMagickMemory(pixel_list); return(pixel_list); } static PixelList **DestroyPixelListThreadSet(PixelList **pixel_list) { register ssize_t i; assert(pixel_list != (PixelList **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixel_list[i] != (PixelList *) NULL) pixel_list[i]=DestroyPixelList(pixel_list[i]); pixel_list=(PixelList **) RelinquishMagickMemory(pixel_list); return(pixel_list); } static PixelList *AcquirePixelList(const size_t width,const size_t height) { PixelList *pixel_list; register ssize_t i; pixel_list=(PixelList *) AcquireMagickMemory(sizeof(*pixel_list)); if (pixel_list == (PixelList *) NULL) return(pixel_list); (void) ResetMagickMemory((void *) pixel_list,0,sizeof(*pixel_list)); pixel_list->length=width*height; for (i=0; i < ListChannels; i++) { pixel_list->lists[i].nodes=(ListNode *) AcquireAlignedMemory(65537UL, sizeof(*pixel_list->lists[i].nodes)); if (pixel_list->lists[i].nodes == (ListNode *) NULL) return(DestroyPixelList(pixel_list)); (void) ResetMagickMemory(pixel_list->lists[i].nodes,0,65537UL* sizeof(*pixel_list->lists[i].nodes)); } pixel_list->signature=MagickCoreSignature; return(pixel_list); } static PixelList **AcquirePixelListThreadSet(const size_t width, const size_t height) { PixelList **pixel_list; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixel_list=(PixelList **) AcquireQuantumMemory(number_threads, sizeof(*pixel_list)); if (pixel_list == (PixelList **) NULL) return((PixelList **) NULL); (void) ResetMagickMemory(pixel_list,0,number_threads*sizeof(*pixel_list)); for (i=0; i < (ssize_t) number_threads; i++) { pixel_list[i]=AcquirePixelList(width,height); if (pixel_list[i] == (PixelList *) NULL) return(DestroyPixelListThreadSet(pixel_list)); } return(pixel_list); } static void AddNodePixelList(PixelList *pixel_list,const ssize_t channel, const size_t color) { register SkipList *list; register ssize_t level; size_t search, update[9]; /* Initialize the node. */ list=pixel_list->lists+channel; list->nodes[color].signature=pixel_list->signature; list->nodes[color].count=1; /* Determine where it belongs in the list. */ search=65536UL; for (level=list->level; level >= 0; level--) { while (list->nodes[search].next[level] < color) search=list->nodes[search].next[level]; update[level]=search; } /* Generate a pseudo-random level for this node. */ for (level=0; ; level++) { pixel_list->seed=(pixel_list->seed*42893621L)+1L; if ((pixel_list->seed & 0x300) != 0x300) break; } if (level > 8) level=8; if (level > (list->level+2)) level=list->level+2; /* If we're raising the list's level, link back to the root node. */ while (level > list->level) { list->level++; update[list->level]=65536UL; } /* Link the node into the skip-list. */ do { list->nodes[color].next[level]=list->nodes[update[level]].next[level]; list->nodes[update[level]].next[level]=color; } while (level-- > 0); } static void GetMaximumPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color, maximum; ssize_t count; unsigned short channels[ListChannels]; /* Find the maximum value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; maximum=list->nodes[color].next[0]; do { color=list->nodes[color].next[0]; if (color > maximum) maximum=color; count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); channels[channel]=(unsigned short) maximum; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetMeanPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { MagickRealType sum; register SkipList *list; register ssize_t channel; size_t color; ssize_t count; unsigned short channels[ListChannels]; /* Find the mean value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; sum=0.0; do { color=list->nodes[color].next[0]; sum+=(MagickRealType) list->nodes[color].count*color; count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; channels[channel]=(unsigned short) sum; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetMedianPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color; ssize_t count; unsigned short channels[ListChannels]; /* Find the median value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; do { color=list->nodes[color].next[0]; count+=list->nodes[color].count; } while (count <= (ssize_t) (pixel_list->length >> 1)); channels[channel]=(unsigned short) color; } GetMagickPixelPacket((const Image *) NULL,pixel); pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetMinimumPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color, minimum; ssize_t count; unsigned short channels[ListChannels]; /* Find the minimum value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; count=0; color=65536UL; minimum=list->nodes[color].next[0]; do { color=list->nodes[color].next[0]; if (color < minimum) minimum=color; count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); channels[channel]=(unsigned short) minimum; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetModePixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color, max_count, mode; ssize_t count; unsigned short channels[5]; /* Make each pixel the 'predominant color' of the specified neighborhood. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; mode=color; max_count=list->nodes[mode].count; count=0; do { color=list->nodes[color].next[0]; if (list->nodes[color].count > max_count) { mode=color; max_count=list->nodes[mode].count; } count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); channels[channel]=(unsigned short) mode; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetNonpeakPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color, next, previous; ssize_t count; unsigned short channels[5]; /* Finds the non peak value for each of the colors. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; next=list->nodes[color].next[0]; count=0; do { previous=color; color=next; next=list->nodes[color].next[0]; count+=list->nodes[color].count; } while (count <= (ssize_t) (pixel_list->length >> 1)); if ((previous == 65536UL) && (next != 65536UL)) color=next; else if ((previous != 65536UL) && (next == 65536UL)) color=previous; channels[channel]=(unsigned short) color; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetRootMeanSquarePixelList(PixelList *pixel_list, MagickPixelPacket *pixel) { MagickRealType sum; register SkipList *list; register ssize_t channel; size_t color; ssize_t count; unsigned short channels[ListChannels]; /* Find the root mean square value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; sum=0.0; do { color=list->nodes[color].next[0]; sum+=(MagickRealType) (list->nodes[color].count*color*color); count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; channels[channel]=(unsigned short) sqrt(sum); } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetStandardDeviationPixelList(PixelList *pixel_list, MagickPixelPacket *pixel) { MagickRealType sum, sum_squared; register SkipList *list; register ssize_t channel; size_t color; ssize_t count; unsigned short channels[ListChannels]; /* Find the standard-deviation value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; sum=0.0; sum_squared=0.0; do { register ssize_t i; color=list->nodes[color].next[0]; sum+=(MagickRealType) list->nodes[color].count*color; for (i=0; i < (ssize_t) list->nodes[color].count; i++) sum_squared+=((MagickRealType) color)*((MagickRealType) color); count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; sum_squared/=pixel_list->length; channels[channel]=(unsigned short) sqrt(sum_squared-(sum*sum)); } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static inline void InsertPixelList(const Image *image,const PixelPacket *pixel, const IndexPacket *indexes,PixelList *pixel_list) { size_t signature; unsigned short index; index=ScaleQuantumToShort(GetPixelRed(pixel)); signature=pixel_list->lists[0].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[0].nodes[index].count++; else AddNodePixelList(pixel_list,0,index); index=ScaleQuantumToShort(GetPixelGreen(pixel)); signature=pixel_list->lists[1].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[1].nodes[index].count++; else AddNodePixelList(pixel_list,1,index); index=ScaleQuantumToShort(GetPixelBlue(pixel)); signature=pixel_list->lists[2].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[2].nodes[index].count++; else AddNodePixelList(pixel_list,2,index); index=ScaleQuantumToShort(GetPixelOpacity(pixel)); signature=pixel_list->lists[3].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[3].nodes[index].count++; else AddNodePixelList(pixel_list,3,index); if (image->colorspace == CMYKColorspace) index=ScaleQuantumToShort(GetPixelIndex(indexes)); signature=pixel_list->lists[4].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[4].nodes[index].count++; else AddNodePixelList(pixel_list,4,index); } static void ResetPixelList(PixelList *pixel_list) { int level; register ListNode *root; register SkipList *list; register ssize_t channel; /* Reset the skip-list. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; root=list->nodes+65536UL; list->level=0; for (level=0; level < 9; level++) root->next[level]=65536UL; } pixel_list->seed=pixel_list->signature++; } MagickExport Image *StatisticImage(const Image *image,const StatisticType type, const size_t width,const size_t height,ExceptionInfo *exception) { Image *statistic_image; statistic_image=StatisticImageChannel(image,DefaultChannels,type,width, height,exception); return(statistic_image); } MagickExport Image *StatisticImageChannel(const Image *image, const ChannelType channel,const StatisticType type,const size_t width, const size_t height,ExceptionInfo *exception) { #define StatisticImageTag "Statistic/Image" CacheView *image_view, *statistic_view; Image *statistic_image; MagickBooleanType status; MagickOffsetType progress; PixelList **magick_restrict pixel_list; size_t neighbor_height, neighbor_width; ssize_t y; /* Initialize statistics 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); statistic_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); if (statistic_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(statistic_image,DirectClass) == MagickFalse) { InheritException(exception,&statistic_image->exception); statistic_image=DestroyImage(statistic_image); return((Image *) NULL); } neighbor_width=width == 0 ? GetOptimalKernelWidth2D((double) width,0.5) : width; neighbor_height=height == 0 ? GetOptimalKernelWidth2D((double) height,0.5) : height; pixel_list=AcquirePixelListThreadSet(neighbor_width,neighbor_height); if (pixel_list == (PixelList **) NULL) { statistic_image=DestroyImage(statistic_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Make each pixel the min / max / median / mode / etc. of the neighborhood. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); statistic_view=AcquireAuthenticCacheView(statistic_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_number_threads(image,statistic_image,statistic_image->rows,1) #endif for (y=0; y < (ssize_t) statistic_image->rows; y++) { const int id = GetOpenMPThreadId(); register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict statistic_indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) neighbor_width/2L),y- (ssize_t) (neighbor_height/2L),image->columns+neighbor_width, neighbor_height,exception); q=QueueCacheViewAuthenticPixels(statistic_view,0,y,statistic_image->columns, 1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); statistic_indexes=GetCacheViewAuthenticIndexQueue(statistic_view); for (x=0; x < (ssize_t) statistic_image->columns; x++) { MagickPixelPacket pixel; register const IndexPacket *magick_restrict s; register const PixelPacket *magick_restrict r; register ssize_t u, v; r=p; s=indexes+x; ResetPixelList(pixel_list[id]); for (v=0; v < (ssize_t) neighbor_height; v++) { for (u=0; u < (ssize_t) neighbor_width; u++) InsertPixelList(image,r+u,s+u,pixel_list[id]); r+=image->columns+neighbor_width; s+=image->columns+neighbor_width; } GetMagickPixelPacket(image,&pixel); SetMagickPixelPacket(image,p+neighbor_width*neighbor_height/2,indexes+x+ neighbor_width*neighbor_height/2,&pixel); switch (type) { case GradientStatistic: { MagickPixelPacket maximum, minimum; GetMinimumPixelList(pixel_list[id],&pixel); minimum=pixel; GetMaximumPixelList(pixel_list[id],&pixel); maximum=pixel; pixel.red=MagickAbsoluteValue(maximum.red-minimum.red); pixel.green=MagickAbsoluteValue(maximum.green-minimum.green); pixel.blue=MagickAbsoluteValue(maximum.blue-minimum.blue); pixel.opacity=MagickAbsoluteValue(maximum.opacity-minimum.opacity); if (image->colorspace == CMYKColorspace) pixel.index=MagickAbsoluteValue(maximum.index-minimum.index); break; } case MaximumStatistic: { GetMaximumPixelList(pixel_list[id],&pixel); break; } case MeanStatistic: { GetMeanPixelList(pixel_list[id],&pixel); break; } case MedianStatistic: default: { GetMedianPixelList(pixel_list[id],&pixel); break; } case MinimumStatistic: { GetMinimumPixelList(pixel_list[id],&pixel); break; } case ModeStatistic: { GetModePixelList(pixel_list[id],&pixel); break; } case NonpeakStatistic: { GetNonpeakPixelList(pixel_list[id],&pixel); break; } case RootMeanSquareStatistic: { GetRootMeanSquarePixelList(pixel_list[id],&pixel); break; } case StandardDeviationStatistic: { GetStandardDeviationPixelList(pixel_list[id],&pixel); break; } } 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) SetPixelOpacity(q,ClampToQuantum(pixel.opacity)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(statistic_indexes+x,ClampToQuantum(pixel.index)); p++; q++; } if (SyncCacheViewAuthenticPixels(statistic_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_StatisticImage) #endif proceed=SetImageProgress(image,StatisticImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } statistic_view=DestroyCacheView(statistic_view); image_view=DestroyCacheView(image_view); pixel_list=DestroyPixelListThreadSet(pixel_list); if (status == MagickFalse) statistic_image=DestroyImage(statistic_image); return(statistic_image); }
GB_binop__lt_int16.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__lt_int16) // A.*B function (eWiseMult): GB (_AemultB_01__lt_int16) // A.*B function (eWiseMult): GB (_AemultB_02__lt_int16) // A.*B function (eWiseMult): GB (_AemultB_03__lt_int16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__lt_int16) // A*D function (colscale): GB (_AxD__lt_int16) // D*A function (rowscale): GB (_DxB__lt_int16) // C+=B function (dense accum): GB (_Cdense_accumB__lt_int16) // C+=b function (dense accum): GB (_Cdense_accumb__lt_int16) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__lt_int16) // C=scalar+B GB (_bind1st__lt_int16) // C=scalar+B' GB (_bind1st_tran__lt_int16) // C=A+scalar GB (_bind2nd__lt_int16) // C=A'+scalar GB (_bind2nd_tran__lt_int16) // C type: bool // A type: int16_t // B,b type: int16_t // BinaryOp: cij = (aij < bij) #define GB_ATYPE \ int16_t #define GB_BTYPE \ int16_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) \ int16_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int16_t bij = GBX (Bx, pB, B_iso) // 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 = 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 = (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_LT || GxB_NO_INT16 || GxB_NO_LT_INT16) //------------------------------------------------------------------------------ // 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 //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__lt_int16) ( 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__lt_int16) ( 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__lt_int16) ( 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 int16_t int16_t bwork = (*((int16_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 //------------------------------------------------------------------------------ GrB_Info GB (_AxD__lt_int16) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, 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 } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__lt_int16) ( 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 bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__lt_int16) ( 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 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) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__lt_int16) ( 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_01_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__lt_int16) ( 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_03__lt_int16) ( 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_03_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__lt_int16) ( 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__lt_int16) ( 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 ; int16_t x = (*((int16_t *) x_input)) ; int16_t *Bx = (int16_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 ; int16_t bij = GBX (Bx, p, false) ; Cx [p] = (x < bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__lt_int16) ( 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 ; int16_t *Ax = (int16_t *) Ax_input ; int16_t y = (*((int16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int16_t aij = GBX (Ax, p, false) ; Cx [p] = (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) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x < aij) ; \ } GrB_Info GB (_bind1st_tran__lt_int16) ( 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 \ int16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t x = (*((const int16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int16_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) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij < y) ; \ } GrB_Info GB (_bind2nd_tran__lt_int16) ( 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 int16_t y = (*((const int16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif