source
stringlengths
3
92
c
stringlengths
26
2.25M
image.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % IIIII M M AAA GGGG EEEEE % % I MM MM A A G E % % I M M M AAAAA G GG EEE % % I M M A A G G E % % IIIII M M A A GGGG EEEEE % % % % % % MagickCore Image Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 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/animate.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.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/colormap.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/compress.h" #include "MagickCore/constitute.h" #include "MagickCore/delegate.h" #include "MagickCore/display.h" #include "MagickCore/draw.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/histogram.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magic.h" #include "MagickCore/magick.h" #include "MagickCore/magick-private.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/module.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/profile.h" #include "MagickCore/property.h" #include "MagickCore/quantize.h" #include "MagickCore/random_.h" #include "MagickCore/resource_.h" #include "MagickCore/segment.h" #include "MagickCore/semaphore.h" #include "MagickCore/signature-private.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/timer.h" #include "MagickCore/token.h" #include "MagickCore/token-private.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #include "MagickCore/version.h" #include "MagickCore/xwindow-private.h" /* Constant declaration. */ const char BackgroundColor[] = "#ffffff", /* white */ BorderColor[] = "#dfdfdf", /* gray */ DefaultTileFrame[] = "15x15+3+3", DefaultTileGeometry[] = "120x120+4+3>", DefaultTileLabel[] = "%f\n%G\n%b", ForegroundColor[] = "#000", /* black */ LoadImageTag[] = "Load/Image", LoadImagesTag[] = "Load/Images", MatteColor[] = "#bdbdbd", /* gray */ PSDensityGeometry[] = "72.0x72.0", PSPageGeometry[] = "612x792", SaveImageTag[] = "Save/Image", SaveImagesTag[] = "Save/Images", TransparentColor[] = "#00000000"; /* transparent black */ const double DefaultResolution = 72.0; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireImage() returns a pointer to an image structure initialized to % default values. % % The format of the AcquireImage method is: % % Image *AcquireImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: Many of the image default values are set from this % structure. For example, filename, compression, depth, background color, % and others. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AcquireImage(const ImageInfo *image_info, ExceptionInfo *exception) { const char *option; Image *image; MagickStatusType flags; /* Allocate image structure. */ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); image=(Image *) AcquireCriticalMemory(sizeof(*image)); (void) memset(image,0,sizeof(*image)); /* Initialize Image structure. */ (void) CopyMagickString(image->magick,"MIFF",MagickPathExtent); image->storage_class=DirectClass; image->depth=MAGICKCORE_QUANTUM_DEPTH; image->colorspace=sRGBColorspace; image->rendering_intent=PerceptualIntent; image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.red_primary.z=0.0300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.green_primary.z=0.1000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.blue_primary.z=0.7900f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; image->chromaticity.white_point.z=0.3583f; image->interlace=NoInterlace; image->ticks_per_second=UndefinedTicksPerSecond; image->compose=OverCompositeOp; (void) QueryColorCompliance(MatteColor,AllCompliance,&image->matte_color, exception); (void) QueryColorCompliance(BackgroundColor,AllCompliance, &image->background_color,exception); (void) QueryColorCompliance(BorderColor,AllCompliance,&image->border_color, exception); (void) QueryColorCompliance(TransparentColor,AllCompliance, &image->transparent_color,exception); GetTimerInfo(&image->timer); image->cache=AcquirePixelCache(0); image->channel_mask=DefaultChannels; image->channel_map=AcquirePixelChannelMap(); image->blob=CloneBlobInfo((BlobInfo *) NULL); image->timestamp=time((time_t *) NULL); image->debug=IsEventLogging(); image->reference_count=1; image->semaphore=AcquireSemaphoreInfo(); image->signature=MagickCoreSignature; if (image_info == (ImageInfo *) NULL) return(image); /* Transfer image info. */ SetBlobExempt(image,image_info->file != (FILE *) NULL ? MagickTrue : MagickFalse); (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick_filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick,image_info->magick,MagickPathExtent); if (image_info->size != (char *) NULL) { (void) ParseAbsoluteGeometry(image_info->size,&image->extract_info); image->columns=image->extract_info.width; image->rows=image->extract_info.height; image->offset=image->extract_info.x; image->extract_info.x=0; image->extract_info.y=0; } if (image_info->extract != (char *) NULL) { RectangleInfo geometry; (void) memset(&geometry,0,sizeof(geometry)); flags=ParseAbsoluteGeometry(image_info->extract,&geometry); if (((flags & XValue) != 0) || ((flags & YValue) != 0)) { image->extract_info=geometry; Swap(image->columns,image->extract_info.width); Swap(image->rows,image->extract_info.height); } } image->compression=image_info->compression; image->quality=image_info->quality; image->endian=image_info->endian; image->interlace=image_info->interlace; image->units=image_info->units; if (image_info->density != (char *) NULL) { GeometryInfo geometry_info; flags=ParseGeometry(image_info->density,&geometry_info); if ((flags & RhoValue) != 0) image->resolution.x=geometry_info.rho; image->resolution.y=image->resolution.x; if ((flags & SigmaValue) != 0) image->resolution.y=geometry_info.sigma; } if (image_info->page != (char *) NULL) { char *geometry; image->page=image->extract_info; geometry=GetPageGeometry(image_info->page); (void) ParseAbsoluteGeometry(geometry,&image->page); geometry=DestroyString(geometry); } if (image_info->depth != 0) image->depth=image_info->depth; image->dither=image_info->dither; image->matte_color=image_info->matte_color; image->background_color=image_info->background_color; image->border_color=image_info->border_color; image->transparent_color=image_info->transparent_color; image->ping=image_info->ping; image->progress_monitor=image_info->progress_monitor; image->client_data=image_info->client_data; if (image_info->cache != (void *) NULL) ClonePixelCacheMethods(image->cache,image_info->cache); /* Set all global options that map to per-image settings. */ (void) SyncImageSettings(image_info,image,exception); /* Global options that are only set for new images. */ option=GetImageOption(image_info,"delay"); if (option != (const char *) NULL) { GeometryInfo geometry_info; flags=ParseGeometry(option,&geometry_info); if ((flags & GreaterValue) != 0) { if (image->delay > (size_t) floor(geometry_info.rho+0.5)) image->delay=(size_t) floor(geometry_info.rho+0.5); } else if ((flags & LessValue) != 0) { if (image->delay < (size_t) floor(geometry_info.rho+0.5)) image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5); } else image->delay=(size_t) floor(geometry_info.rho+0.5); if ((flags & SigmaValue) != 0) image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5); } option=GetImageOption(image_info,"dispose"); if (option != (const char *) NULL) image->dispose=(DisposeType) ParseCommandOption(MagickDisposeOptions, MagickFalse,option); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireImageInfo() allocates the ImageInfo structure. % % The format of the AcquireImageInfo method is: % % ImageInfo *AcquireImageInfo(void) % */ MagickExport ImageInfo *AcquireImageInfo(void) { ImageInfo *image_info; image_info=(ImageInfo *) AcquireCriticalMemory(sizeof(*image_info)); GetImageInfo(image_info); return(image_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e N e x t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireNextImage() initializes the next image in a sequence to % default values. The next member of image points to the newly allocated % image. If there is a memory shortage, next is assigned NULL. % % The format of the AcquireNextImage method is: % % void AcquireNextImage(const ImageInfo *image_info,Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: Many of the image default values are set from this % structure. For example, filename, compression, depth, background color, % and others. % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport void AcquireNextImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { /* Allocate image structure. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); image->next=AcquireImage(image_info,exception); if (GetNextImageInList(image) == (Image *) NULL) return; (void) CopyMagickString(GetNextImageInList(image)->filename,image->filename, MagickPathExtent); if (image_info != (ImageInfo *) NULL) (void) CopyMagickString(GetNextImageInList(image)->filename, image_info->filename,MagickPathExtent); DestroyBlob(GetNextImageInList(image)); image->next->blob=ReferenceBlob(image->blob); image->next->endian=image->endian; image->next->scene=image->scene+1; image->next->previous=image; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A p p e n d I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AppendImages() takes all images from the current image pointer to the end % of the image list and appends them to each other top-to-bottom if the % stack parameter is true, otherwise left-to-right. % % The current gravity setting effects how the image is justified in the % final image. % % The format of the AppendImages method is: % % Image *AppendImages(const Image *images,const MagickBooleanType stack, % ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o stack: A value other than 0 stacks the images top-to-bottom. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AppendImages(const Image *images, const MagickBooleanType stack,ExceptionInfo *exception) { #define AppendImageTag "Append/Image" CacheView *append_view; Image *append_image; MagickBooleanType homogeneous_colorspace, status; MagickOffsetType n; PixelTrait alpha_trait; RectangleInfo geometry; register const Image *next; size_t depth, height, number_images, width; ssize_t x_offset, y, y_offset; /* Compute maximum area of appended area. */ 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); alpha_trait=images->alpha_trait; number_images=1; width=images->columns; height=images->rows; depth=images->depth; homogeneous_colorspace=MagickTrue; next=GetNextImageInList(images); for ( ; next != (Image *) NULL; next=GetNextImageInList(next)) { if (next->depth > depth) depth=next->depth; if (next->colorspace != images->colorspace) homogeneous_colorspace=MagickFalse; if (next->alpha_trait != UndefinedPixelTrait) alpha_trait=BlendPixelTrait; number_images++; if (stack != MagickFalse) { if (next->columns > width) width=next->columns; height+=next->rows; continue; } width+=next->columns; if (next->rows > height) height=next->rows; } /* Append images. */ append_image=CloneImage(images,width,height,MagickTrue,exception); if (append_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(append_image,DirectClass,exception) == MagickFalse) { append_image=DestroyImage(append_image); return((Image *) NULL); } if (homogeneous_colorspace == MagickFalse) (void) SetImageColorspace(append_image,sRGBColorspace,exception); append_image->depth=depth; append_image->alpha_trait=alpha_trait; append_image->page=images->page; (void) SetImageBackgroundColor(append_image,exception); status=MagickTrue; x_offset=0; y_offset=0; next=images; append_view=AcquireAuthenticCacheView(append_image,exception); for (n=0; n < (MagickOffsetType) number_images; n++) { CacheView *image_view; MagickBooleanType proceed; SetGeometry(append_image,&geometry); GravityAdjustGeometry(next->columns,next->rows,next->gravity,&geometry); if (stack != MagickFalse) x_offset-=geometry.x; else y_offset-=geometry.y; image_view=AcquireVirtualCacheView(next,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(next,next,next->rows,1) #endif for (y=0; y < (ssize_t) next->rows; y++) { MagickBooleanType sync; PixelInfo pixel; 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,next->columns,1,exception); q=QueueCacheViewAuthenticPixels(append_view,x_offset,y+y_offset, next->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } GetPixelInfo(next,&pixel); for (x=0; x < (ssize_t) next->columns; x++) { GetPixelInfoPixel(next,p,&pixel); SetPixelViaPixelInfo(append_image,&pixel,q); p+=GetPixelChannels(next); q+=GetPixelChannels(append_image); } sync=SyncCacheViewAuthenticPixels(append_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (stack == MagickFalse) { x_offset+=(ssize_t) next->columns; y_offset=0; } else { x_offset=0; y_offset+=(ssize_t) next->rows; } proceed=SetImageProgress(append_image,AppendImageTag,n,number_images); if (proceed == MagickFalse) break; next=GetNextImageInList(next); } append_view=DestroyCacheView(append_view); if (status == MagickFalse) append_image=DestroyImage(append_image); return(append_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C a t c h I m a g e E x c e p t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CatchImageException() returns if no exceptions are found in the image % sequence, otherwise it determines the most severe exception and reports % it as a warning or error depending on the severity. % % The format of the CatchImageException method is: % % ExceptionType CatchImageException(Image *image) % % A description of each parameter follows: % % o image: An image sequence. % */ MagickExport ExceptionType CatchImageException(Image *image) { ExceptionInfo *exception; ExceptionType severity; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); exception=AcquireExceptionInfo(); CatchException(exception); severity=exception->severity; exception=DestroyExceptionInfo(exception); return(severity); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l i p I m a g e P a t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClipImagePath() sets the image clip mask based any clipping path information % if it exists. % % The format of the ClipImagePath method is: % % MagickBooleanType ClipImagePath(Image *image,const char *pathname, % const MagickBooleanType inside,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o pathname: name of clipping path resource. If name is preceded by #, use % clipping path numbered by name. % % o inside: if non-zero, later operations take effect inside clipping path. % Otherwise later operations take effect outside clipping path. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ClipImage(Image *image,ExceptionInfo *exception) { return(ClipImagePath(image,"#1",MagickTrue,exception)); } MagickExport MagickBooleanType ClipImagePath(Image *image,const char *pathname, const MagickBooleanType inside,ExceptionInfo *exception) { #define ClipImagePathTag "ClipPath/Image" char *property; const char *value; Image *clip_mask; ImageInfo *image_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pathname != NULL); property=AcquireString(pathname); (void) FormatLocaleString(property,MagickPathExtent,"8BIM:1999,2998:%s", pathname); value=GetImageProperty(image,property,exception); property=DestroyString(property); if (value == (const char *) NULL) { ThrowFileException(exception,OptionError,"NoClipPathDefined", image->filename); return(MagickFalse); } image_info=AcquireImageInfo(); (void) CopyMagickString(image_info->filename,image->filename, MagickPathExtent); (void) ConcatenateMagickString(image_info->filename,pathname, MagickPathExtent); clip_mask=BlobToImage(image_info,value,strlen(value),exception); image_info=DestroyImageInfo(image_info); if (clip_mask == (Image *) NULL) return(MagickFalse); if (clip_mask->storage_class == PseudoClass) { (void) SyncImage(clip_mask,exception); if (SetImageStorageClass(clip_mask,DirectClass,exception) == MagickFalse) return(MagickFalse); } if (inside == MagickFalse) (void) NegateImage(clip_mask,MagickFalse,exception); (void) FormatLocaleString(clip_mask->magick_filename,MagickPathExtent, "8BIM:1999,2998:%s\nPS",pathname); (void) SetImageMask(image,WritePixelMask,clip_mask,exception); clip_mask=DestroyImage(clip_mask); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneImage() copies an image and returns the copy as a new image object. % % If the specified columns and rows is 0, an exact copy of the image is % returned, otherwise the pixel data is undefined and must be initialized % with the QueueAuthenticPixels() and SyncAuthenticPixels() methods. On % failure, a NULL image is returned and exception describes the reason for the % failure. % % The format of the CloneImage method is: % % Image *CloneImage(const Image *image,const size_t columns, % const size_t rows,const MagickBooleanType orphan, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the cloned image. % % o rows: the number of rows in the cloned image. % % o detach: With a value other than 0, the cloned image is detached from % its parent I/O stream. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *CloneImage(const Image *image,const size_t columns, const size_t rows,const MagickBooleanType detach,ExceptionInfo *exception) { Image *clone_image; double scale; size_t length; /* Clone the image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if ((image->columns == 0) || (image->rows == 0)) { (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, "NegativeOrZeroImageSize","`%s'",image->filename); return((Image *) NULL); } clone_image=(Image *) AcquireCriticalMemory(sizeof(*clone_image)); (void) memset(clone_image,0,sizeof(*clone_image)); clone_image->signature=MagickCoreSignature; clone_image->storage_class=image->storage_class; clone_image->number_channels=image->number_channels; clone_image->number_meta_channels=image->number_meta_channels; clone_image->metacontent_extent=image->metacontent_extent; clone_image->colorspace=image->colorspace; clone_image->alpha_trait=image->alpha_trait; clone_image->channels=image->channels; clone_image->mask_trait=image->mask_trait; clone_image->columns=image->columns; clone_image->rows=image->rows; clone_image->dither=image->dither; clone_image->image_info=CloneImageInfo(image->image_info); (void) CloneImageProfiles(clone_image,image); (void) CloneImageProperties(clone_image,image); (void) CloneImageArtifacts(clone_image,image); GetTimerInfo(&clone_image->timer); if (image->ascii85 != (void *) NULL) Ascii85Initialize(clone_image); clone_image->extent=image->extent; clone_image->magick_columns=image->magick_columns; clone_image->magick_rows=image->magick_rows; clone_image->type=image->type; clone_image->channel_mask=image->channel_mask; clone_image->channel_map=ClonePixelChannelMap(image->channel_map); (void) CopyMagickString(clone_image->magick_filename,image->magick_filename, MagickPathExtent); (void) CopyMagickString(clone_image->magick,image->magick,MagickPathExtent); (void) CopyMagickString(clone_image->filename,image->filename, MagickPathExtent); clone_image->progress_monitor=image->progress_monitor; clone_image->client_data=image->client_data; clone_image->reference_count=1; clone_image->next=image->next; clone_image->previous=image->previous; clone_image->list=NewImageList(); if (detach == MagickFalse) clone_image->blob=ReferenceBlob(image->blob); else { clone_image->next=NewImageList(); clone_image->previous=NewImageList(); clone_image->blob=CloneBlobInfo((BlobInfo *) NULL); } clone_image->ping=image->ping; clone_image->debug=IsEventLogging(); clone_image->semaphore=AcquireSemaphoreInfo(); if (image->colormap != (PixelInfo *) NULL) { /* Allocate and copy the image colormap. */ clone_image->colors=image->colors; length=(size_t) image->colors; clone_image->colormap=(PixelInfo *) AcquireQuantumMemory(length+1, sizeof(*clone_image->colormap)); if (clone_image->colormap == (PixelInfo *) NULL) { clone_image=DestroyImage(clone_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } (void) memcpy(clone_image->colormap,image->colormap,length* sizeof(*clone_image->colormap)); } if ((columns == 0) || (rows == 0)) { if (image->montage != (char *) NULL) (void) CloneString(&clone_image->montage,image->montage); if (image->directory != (char *) NULL) (void) CloneString(&clone_image->directory,image->directory); clone_image->cache=ReferencePixelCache(image->cache); return(clone_image); } scale=1.0; if (image->columns != 0) scale=(double) columns/(double) image->columns; clone_image->page.width=(size_t) floor(scale*image->page.width+0.5); clone_image->page.x=(ssize_t) ceil(scale*image->page.x-0.5); clone_image->tile_offset.x=(ssize_t) ceil(scale*image->tile_offset.x-0.5); scale=1.0; if (image->rows != 0) scale=(double) rows/(double) image->rows; clone_image->page.height=(size_t) floor(scale*image->page.height+0.5); clone_image->page.y=(ssize_t) ceil(scale*image->page.y-0.5); clone_image->tile_offset.y=(ssize_t) ceil(scale*image->tile_offset.y-0.5); clone_image->cache=ClonePixelCache(image->cache); if (SetImageExtent(clone_image,columns,rows,exception) == MagickFalse) clone_image=DestroyImage(clone_image); return(clone_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneImageInfo() makes a copy of the given image info structure. If % NULL is specified, a new image info structure is created initialized to % default values. % % The format of the CloneImageInfo method is: % % ImageInfo *CloneImageInfo(const ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: the image info. % */ MagickExport ImageInfo *CloneImageInfo(const ImageInfo *image_info) { ImageInfo *clone_info; clone_info=AcquireImageInfo(); if (image_info == (ImageInfo *) NULL) return(clone_info); clone_info->compression=image_info->compression; clone_info->temporary=image_info->temporary; clone_info->adjoin=image_info->adjoin; clone_info->antialias=image_info->antialias; clone_info->scene=image_info->scene; clone_info->number_scenes=image_info->number_scenes; clone_info->depth=image_info->depth; if (image_info->size != (char *) NULL) (void) CloneString(&clone_info->size,image_info->size); if (image_info->extract != (char *) NULL) (void) CloneString(&clone_info->extract,image_info->extract); if (image_info->scenes != (char *) NULL) (void) CloneString(&clone_info->scenes,image_info->scenes); if (image_info->page != (char *) NULL) (void) CloneString(&clone_info->page,image_info->page); clone_info->interlace=image_info->interlace; clone_info->endian=image_info->endian; clone_info->units=image_info->units; clone_info->quality=image_info->quality; if (image_info->sampling_factor != (char *) NULL) (void) CloneString(&clone_info->sampling_factor, image_info->sampling_factor); if (image_info->server_name != (char *) NULL) (void) CloneString(&clone_info->server_name,image_info->server_name); if (image_info->font != (char *) NULL) (void) CloneString(&clone_info->font,image_info->font); if (image_info->texture != (char *) NULL) (void) CloneString(&clone_info->texture,image_info->texture); if (image_info->density != (char *) NULL) (void) CloneString(&clone_info->density,image_info->density); clone_info->pointsize=image_info->pointsize; clone_info->fuzz=image_info->fuzz; clone_info->matte_color=image_info->matte_color; clone_info->background_color=image_info->background_color; clone_info->border_color=image_info->border_color; clone_info->transparent_color=image_info->transparent_color; clone_info->dither=image_info->dither; clone_info->monochrome=image_info->monochrome; clone_info->colorspace=image_info->colorspace; clone_info->type=image_info->type; clone_info->orientation=image_info->orientation; clone_info->ping=image_info->ping; clone_info->verbose=image_info->verbose; clone_info->progress_monitor=image_info->progress_monitor; clone_info->client_data=image_info->client_data; clone_info->cache=image_info->cache; if (image_info->cache != (void *) NULL) clone_info->cache=ReferencePixelCache(image_info->cache); if (image_info->profile != (void *) NULL) clone_info->profile=(void *) CloneStringInfo((StringInfo *) image_info->profile); SetImageInfoFile(clone_info,image_info->file); SetImageInfoBlob(clone_info,image_info->blob,image_info->length); clone_info->stream=image_info->stream; clone_info->custom_stream=image_info->custom_stream; (void) CopyMagickString(clone_info->magick,image_info->magick, MagickPathExtent); (void) CopyMagickString(clone_info->unique,image_info->unique, MagickPathExtent); (void) CopyMagickString(clone_info->filename,image_info->filename, MagickPathExtent); clone_info->channel=image_info->channel; (void) CloneImageOptions(clone_info,image_info); clone_info->debug=IsEventLogging(); clone_info->signature=image_info->signature; return(clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o p y I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CopyImagePixels() copies pixels from the source image as defined by the % geometry the destination image at the specified offset. % % The format of the CopyImagePixels method is: % % MagickBooleanType CopyImagePixels(Image *image,const Image *source_image, % const RectangleInfo *geometry,const OffsetInfo *offset, % ExceptionInfo *exception); % % A description of each parameter follows: % % o image: the destination image. % % o source_image: the source image. % % o geometry: define the dimensions of the source pixel rectangle. % % o offset: define the offset in the destination image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType CopyImagePixels(Image *image, const Image *source_image,const RectangleInfo *geometry, const OffsetInfo *offset,ExceptionInfo *exception) { #define CopyImageTag "Copy/Image" CacheView *image_view, *source_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(source_image != (Image *) NULL); assert(geometry != (RectangleInfo *) NULL); assert(offset != (OffsetInfo *) NULL); if ((offset->x < 0) || (offset->y < 0) || ((ssize_t) (offset->x+geometry->width) > (ssize_t) image->columns) || ((ssize_t) (offset->y+geometry->height) > (ssize_t) image->rows)) ThrowBinaryException(OptionError,"GeometryDoesNotContainImage", image->filename); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); /* Copy image pixels. */ 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(image,source_image,geometry->height,1) #endif for (y=0; y < (ssize_t) geometry->height; y++) { MagickBooleanType sync; register const Quantum *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(source_view,geometry->x,y+geometry->y, geometry->width,1,exception); q=QueueCacheViewAuthenticPixels(image_view,offset->x,y+offset->y, geometry->width,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) geometry->width; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait source_traits=GetPixelChannelTraits(source_image,channel); if ((traits == UndefinedPixelTrait) || ((traits & UpdatePixelTrait) == 0) || (source_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; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,CopyImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImage() dereferences an image, deallocating memory associated with % the image if the reference count becomes zero. % % The format of the DestroyImage method is: % % Image *DestroyImage(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport Image *DestroyImage(Image *image) { MagickBooleanType destroy; /* Dereference image. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); destroy=MagickFalse; LockSemaphoreInfo(image->semaphore); image->reference_count--; if (image->reference_count == 0) destroy=MagickTrue; UnlockSemaphoreInfo(image->semaphore); if (destroy == MagickFalse) return((Image *) NULL); /* Destroy image. */ DestroyImagePixels(image); image->channel_map=DestroyPixelChannelMap(image->channel_map); if (image->montage != (char *) NULL) image->montage=DestroyString(image->montage); if (image->directory != (char *) NULL) image->directory=DestroyString(image->directory); if (image->colormap != (PixelInfo *) NULL) image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap); if (image->geometry != (char *) NULL) image->geometry=DestroyString(image->geometry); DestroyImageProfiles(image); DestroyImageProperties(image); DestroyImageArtifacts(image); if (image->ascii85 != (Ascii85Info *) NULL) image->ascii85=(Ascii85Info *) RelinquishMagickMemory(image->ascii85); if (image->image_info != (ImageInfo *) NULL) image->image_info=DestroyImageInfo(image->image_info); DestroyBlob(image); if (image->semaphore != (SemaphoreInfo *) NULL) RelinquishSemaphoreInfo(&image->semaphore); image->signature=(~MagickCoreSignature); image=(Image *) RelinquishMagickMemory(image); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImageInfo() deallocates memory associated with an ImageInfo % structure. % % The format of the DestroyImageInfo method is: % % ImageInfo *DestroyImageInfo(ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: the image info. % */ MagickExport ImageInfo *DestroyImageInfo(ImageInfo *image_info) { assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); if (image_info->size != (char *) NULL) image_info->size=DestroyString(image_info->size); if (image_info->extract != (char *) NULL) image_info->extract=DestroyString(image_info->extract); if (image_info->scenes != (char *) NULL) image_info->scenes=DestroyString(image_info->scenes); if (image_info->page != (char *) NULL) image_info->page=DestroyString(image_info->page); if (image_info->sampling_factor != (char *) NULL) image_info->sampling_factor=DestroyString( image_info->sampling_factor); if (image_info->server_name != (char *) NULL) image_info->server_name=DestroyString( image_info->server_name); if (image_info->font != (char *) NULL) image_info->font=DestroyString(image_info->font); if (image_info->texture != (char *) NULL) image_info->texture=DestroyString(image_info->texture); if (image_info->density != (char *) NULL) image_info->density=DestroyString(image_info->density); if (image_info->cache != (void *) NULL) image_info->cache=DestroyPixelCache(image_info->cache); if (image_info->profile != (StringInfo *) NULL) image_info->profile=(void *) DestroyStringInfo((StringInfo *) image_info->profile); DestroyImageOptions(image_info); image_info->signature=(~MagickCoreSignature); image_info=(ImageInfo *) RelinquishMagickMemory(image_info); return(image_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D i s a s s o c i a t e I m a g e S t r e a m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DisassociateImageStream() disassociates the image stream. It checks if the % blob of the specified image is referenced by other images. If the reference % count is higher then 1 a new blob is assigned to the specified image. % % The format of the DisassociateImageStream method is: % % void DisassociateImageStream(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void DisassociateImageStream(Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); DisassociateBlob(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageInfo() initializes image_info to default values. % % The format of the GetImageInfo method is: % % void GetImageInfo(ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: the image info. % */ MagickExport void GetImageInfo(ImageInfo *image_info) { char *synchronize; ExceptionInfo *exception; /* File and image dimension members. */ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image_info != (ImageInfo *) NULL); (void) memset(image_info,0,sizeof(*image_info)); image_info->adjoin=MagickTrue; image_info->interlace=NoInterlace; image_info->channel=DefaultChannels; image_info->quality=UndefinedCompressionQuality; image_info->antialias=MagickTrue; image_info->dither=MagickTrue; synchronize=GetEnvironmentValue("MAGICK_SYNCHRONIZE"); if (synchronize != (const char *) NULL) { image_info->synchronize=IsStringTrue(synchronize); synchronize=DestroyString(synchronize); } exception=AcquireExceptionInfo(); (void) QueryColorCompliance(BackgroundColor,AllCompliance, &image_info->background_color,exception); (void) QueryColorCompliance(BorderColor,AllCompliance, &image_info->border_color,exception); (void) QueryColorCompliance(MatteColor,AllCompliance,&image_info->matte_color, exception); (void) QueryColorCompliance(TransparentColor,AllCompliance, &image_info->transparent_color,exception); exception=DestroyExceptionInfo(exception); image_info->debug=IsEventLogging(); image_info->signature=MagickCoreSignature; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e I n f o F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageInfoFile() returns the image info file member. % % The format of the GetImageInfoFile method is: % % FILE *GetImageInfoFile(const ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: the image info. % */ MagickExport FILE *GetImageInfoFile(const ImageInfo *image_info) { return(image_info->file); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageMask() returns the mask associated with the image. % % The format of the GetImageMask method is: % % Image *GetImageMask(const Image *image,const PixelMask type, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o type: the mask type, ReadPixelMask or WritePixelMask. % */ MagickExport Image *GetImageMask(const Image *image,const PixelMask type, ExceptionInfo *exception) { CacheView *mask_view, *image_view; Image *mask_image; MagickBooleanType status; ssize_t y; /* Get image mask. */ assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); switch (type) { case ReadPixelMask: { if ((image->channels & ReadMaskChannel) == 0) return((Image *) NULL); break; } case WritePixelMask: { if ((image->channels & WriteMaskChannel) == 0) return((Image *) NULL); break; } default: { if ((image->channels & CompositeMaskChannel) == 0) return((Image *) NULL); break; } } mask_image=AcquireImage((ImageInfo *) NULL,exception); status=SetImageExtent(mask_image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImage(mask_image)); status=MagickTrue; mask_image->alpha_trait=UndefinedPixelTrait; (void) SetImageColorspace(mask_image,GRAYColorspace,exception); image_view=AcquireVirtualCacheView(image,exception); mask_view=AcquireAuthenticCacheView(mask_image,exception); for (y=0; y < (ssize_t) 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=GetCacheViewAuthenticPixels(mask_view,0,y,mask_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { switch (type) { case ReadPixelMask: { SetPixelGray(mask_image,GetPixelReadMask(image,p),q); break; } case WritePixelMask: { SetPixelGray(mask_image,GetPixelWriteMask(image,p),q); break; } default: { SetPixelGray(mask_image,GetPixelCompositeMask(image,p),q); break; } } p+=GetPixelChannels(image); q+=GetPixelChannels(mask_image); } if (SyncCacheViewAuthenticPixels(mask_view,exception) == MagickFalse) status=MagickFalse; } mask_view=DestroyCacheView(mask_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) mask_image=DestroyImage(mask_image); return(mask_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e R e f e r e n c e C o u n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageReferenceCount() returns the image reference count. % % The format of the GetReferenceCount method is: % % ssize_t GetImageReferenceCount(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport ssize_t GetImageReferenceCount(Image *image) { ssize_t reference_count; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); LockSemaphoreInfo(image->semaphore); reference_count=image->reference_count; UnlockSemaphoreInfo(image->semaphore); return(reference_count); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i r t u a l P i x e l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageVirtualPixelMethod() gets the "virtual pixels" method for the % image. A virtual pixel is any pixel access that is outside the boundaries % of the image cache. % % The format of the GetImageVirtualPixelMethod() method is: % % VirtualPixelMethod GetImageVirtualPixelMethod(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport VirtualPixelMethod GetImageVirtualPixelMethod(const Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); return(GetPixelCacheVirtualMethod(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n t e r p r e t I m a g e F i l e n a m e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InterpretImageFilename() interprets embedded characters in an image filename. % The filename length is returned. % % The format of the InterpretImageFilename method is: % % size_t InterpretImageFilename(const ImageInfo *image_info,Image *image, % const char *format,int value,char *filename,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info.. % % o image: the image. % % o format: A filename describing the format to use to write the numeric % argument. Only the first numeric format identifier is replaced. % % o value: Numeric value to substitute into format filename. % % o filename: return the formatted filename in this character buffer. % % o exception: return any errors or warnings in this structure. % */ MagickExport size_t InterpretImageFilename(const ImageInfo *image_info, Image *image,const char *format,int value,char *filename, ExceptionInfo *exception) { char *q; int c; MagickBooleanType canonical; register const char *p; ssize_t field_width, offset; canonical=MagickFalse; offset=0; (void) CopyMagickString(filename,format,MagickPathExtent); for (p=strchr(format,'%'); p != (char *) NULL; p=strchr(p+1,'%')) { q=(char *) p+1; if (*q == '%') { p=q+1; continue; } field_width=0; if (*q == '0') field_width=(ssize_t) strtol(q,&q,10); switch (*q) { case 'd': case 'o': case 'x': { q++; c=(*q); *q='\0'; (void) FormatLocaleString(filename+(p-format-offset),(size_t) (MagickPathExtent-(p-format-offset)),p,value); offset+=(4-field_width); *q=c; (void) ConcatenateMagickString(filename,q,MagickPathExtent); canonical=MagickTrue; if (*(q-1) != '%') break; p++; break; } case '[': { char pattern[MagickPathExtent]; const char *option; register char *r; register ssize_t i; ssize_t depth; /* Image option. */ if (strchr(p,']') == (char *) NULL) break; depth=1; r=q+1; for (i=0; (i < (MagickPathExtent-1L)) && (*r != '\0'); i++) { if (*r == '[') depth++; if (*r == ']') depth--; if (depth <= 0) break; pattern[i]=(*r++); } pattern[i]='\0'; if (LocaleNCompare(pattern,"filename:",9) != 0) break; option=(const char *) NULL; if (image != (Image *) NULL) option=GetImageProperty(image,pattern,exception); if ((option == (const char *) NULL) && (image != (Image *) NULL)) option=GetImageArtifact(image,pattern); if ((option == (const char *) NULL) && (image_info != (ImageInfo *) NULL)) option=GetImageOption(image_info,pattern); if (option == (const char *) NULL) break; q--; c=(*q); *q='\0'; (void) CopyMagickString(filename+(p-format-offset),option,(size_t) (MagickPathExtent-(p-format-offset))); offset+=strlen(pattern)-strlen(option)+3; *q=c; (void) ConcatenateMagickString(filename,r+1,MagickPathExtent); canonical=MagickTrue; if (*(q-1) != '%') break; p++; break; } default: break; } } for (q=filename; *q != '\0'; q++) if ((*q == '%') && (*(q+1) == '%')) { (void) CopyMagickString(q,q+1,(size_t) (MagickPathExtent-(q-filename))); canonical=MagickTrue; } if (canonical == MagickFalse) (void) CopyMagickString(filename,format,MagickPathExtent); return(strlen(filename)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s H i g h D y n a m i c R a n g e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsHighDynamicRangeImage() returns MagickTrue if any pixel component is % non-integer or exceeds the bounds of the quantum depth (e.g. for Q16 % 0..65535. % % The format of the IsHighDynamicRangeImage method is: % % MagickBooleanType IsHighDynamicRangeImage(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType IsHighDynamicRangeImage(const Image *image, ExceptionInfo *exception) { #if !defined(MAGICKCORE_HDRI_SUPPORT) (void) image; (void) exception; return(MagickFalse); #else CacheView *image_view; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *p; register 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++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double pixel; PixelTrait traits; traits=GetPixelChannelTraits(image,(PixelChannel) i); if (traits == UndefinedPixelTrait) continue; pixel=(double) p[i]; if ((pixel < 0.0) || (pixel > QuantumRange) || (pixel != (double) ((QuantumAny) pixel))) break; } p+=GetPixelChannels(image); if (i < (ssize_t) GetPixelChannels(image)) status=MagickFalse; } if (x < (ssize_t) image->columns) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status != MagickFalse ? MagickFalse : MagickTrue); #endif } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s I m a g e O b j e c t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsImageObject() returns MagickTrue if the image sequence contains a valid % set of image objects. % % The format of the IsImageObject method is: % % MagickBooleanType IsImageObject(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport MagickBooleanType IsImageObject(const Image *image) { register const Image *p; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); for (p=image; p != (Image *) NULL; p=GetNextImageInList(p)) if (p->signature != MagickCoreSignature) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s T a i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsTaintImage() returns MagickTrue any pixel in the image has been altered % since it was first constituted. % % The format of the IsTaintImage method is: % % MagickBooleanType IsTaintImage(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport MagickBooleanType IsTaintImage(const Image *image) { char magick[MagickPathExtent], filename[MagickPathExtent]; register const Image *p; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); (void) CopyMagickString(magick,image->magick,MagickPathExtent); (void) CopyMagickString(filename,image->filename,MagickPathExtent); for (p=image; p != (Image *) NULL; p=GetNextImageInList(p)) { if (p->taint != MagickFalse) return(MagickTrue); if (LocaleCompare(p->magick,magick) != 0) return(MagickTrue); if (LocaleCompare(p->filename,filename) != 0) return(MagickTrue); } return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o d i f y I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ModifyImage() ensures that there is only a single reference to the image % to be modified, updating the provided image pointer to point to a clone of % the original image if necessary. % % The format of the ModifyImage method is: % % MagickBooleanType ModifyImage(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 ModifyImage(Image **image, ExceptionInfo *exception) { Image *clone_image; assert(image != (Image **) NULL); assert(*image != (Image *) NULL); assert((*image)->signature == MagickCoreSignature); if ((*image)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*image)->filename); if (GetImageReferenceCount(*image) <= 1) return(MagickTrue); clone_image=CloneImage(*image,0,0,MagickTrue,exception); LockSemaphoreInfo((*image)->semaphore); (*image)->reference_count--; UnlockSemaphoreInfo((*image)->semaphore); *image=clone_image; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N e w M a g i c k I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % NewMagickImage() creates a blank image canvas of the specified size and % background color. % % The format of the NewMagickImage method is: % % Image *NewMagickImage(const ImageInfo *image_info,const size_t width, % const size_t height,const PixelInfo *background, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width: the image width. % % o height: the image height. % % o background: the image color. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *NewMagickImage(const ImageInfo *image_info, const size_t width,const size_t height,const PixelInfo *background, ExceptionInfo *exception) { CacheView *image_view; Image *image; MagickBooleanType status; ssize_t y; assert(image_info != (const ImageInfo *) NULL); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image_info->signature == MagickCoreSignature); assert(background != (const PixelInfo *) NULL); image=AcquireImage(image_info,exception); image->columns=width; image->rows=height; image->colorspace=background->colorspace; image->alpha_trait=background->alpha_trait; image->fuzz=background->fuzz; image->depth=background->depth; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelViaPixelInfo(image,background,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (status == MagickFalse) image=DestroyImage(image); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e f e r e n c e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReferenceImage() increments the reference count associated with an image % returning a pointer to the image. % % The format of the ReferenceImage method is: % % Image *ReferenceImage(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport Image *ReferenceImage(Image *image) { assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); LockSemaphoreInfo(image->semaphore); image->reference_count++; UnlockSemaphoreInfo(image->semaphore); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s e t I m a g e P a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetImagePage() resets the image page canvas and position. % % The format of the ResetImagePage method is: % % MagickBooleanType ResetImagePage(Image *image,const char *page) % % A description of each parameter follows: % % o image: the image. % % o page: the relative page specification. % */ MagickExport MagickBooleanType ResetImagePage(Image *image,const char *page) { MagickStatusType flags; RectangleInfo geometry; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); flags=ParseAbsoluteGeometry(page,&geometry); if ((flags & WidthValue) != 0) { if ((flags & HeightValue) == 0) geometry.height=geometry.width; image->page.width=geometry.width; image->page.height=geometry.height; } if ((flags & AspectValue) != 0) { if ((flags & XValue) != 0) image->page.x+=geometry.x; if ((flags & YValue) != 0) image->page.y+=geometry.y; } else { if ((flags & XValue) != 0) { image->page.x=geometry.x; if ((image->page.width == 0) && (geometry.x > 0)) image->page.width=image->columns+geometry.x; } if ((flags & YValue) != 0) { image->page.y=geometry.y; if ((image->page.height == 0) && (geometry.y > 0)) image->page.height=image->rows+geometry.y; } } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s e t I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetImagePixels() reset the image pixels, that is, all the pixel components % are zereod. % % The format of the SetImage method is: % % MagickBooleanType ResetImagePixels(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 ResetImagePixels(Image *image, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; size_t length; ssize_t y; void *pixels; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); pixels=AcquirePixelCachePixels(image,&length,exception); if (pixels != (void *) NULL) { /* Reset in-core image pixels. */ (void) memset(pixels,0,length); return(MagickTrue); } /* Reset image pixels. */ status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { (void) memset(q,0,GetPixelChannels(image)*sizeof(Quantum)); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e A l p h a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageAlpha() sets the alpha levels of the image. % % The format of the SetImageAlpha method is: % % MagickBooleanType SetImageAlpha(Image *image,const Quantum alpha, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o alpha: the level of transparency: 0 is fully transparent and QuantumRange % is fully opaque. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageAlpha(Image *image,const Quantum alpha, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); image->alpha_trait=BlendPixelTrait; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=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++) { SetPixelAlpha(image,alpha,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e B a c k g r o u n d C o l o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageBackgroundColor() initializes the image pixels to the image % background color. The background color is defined by the background_color % member of the image structure. % % The format of the SetImage method is: % % MagickBooleanType SetImageBackgroundColor(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 SetImageBackgroundColor(Image *image, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; PixelInfo background; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if ((image->background_color.alpha != OpaqueAlpha) && (image->alpha_trait == UndefinedPixelTrait)) (void) SetImageAlphaChannel(image,OnAlphaChannel,exception); ConformPixelInfo(image,&image->background_color,&background,exception); /* Set image background color. */ status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelViaPixelInfo(image,&background,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e C h a n n e l M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageChannelMask() sets the image channel mask from the specified channel % mask. % % The format of the SetImageChannelMask method is: % % ChannelType SetImageChannelMask(Image *image, % const ChannelType channel_mask) % % A description of each parameter follows: % % o image: the image. % % o channel_mask: the channel mask. % */ MagickExport ChannelType SetImageChannelMask(Image *image, const ChannelType channel_mask) { return(SetPixelChannelMask(image,channel_mask)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e C o l o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageColor() set the entire image canvas to the specified color. % % The format of the SetImageColor method is: % % MagickBooleanType SetImageColor(Image *image,const PixelInfo *color, % ExeptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o background: the image color. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageColor(Image *image, const PixelInfo *color,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); assert(color != (const PixelInfo *) NULL); image->colorspace=color->colorspace; image->alpha_trait=color->alpha_trait; image->fuzz=color->fuzz; image->depth=color->depth; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelViaPixelInfo(image,color,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e S t o r a g e C l a s s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageStorageClass() sets the image class: DirectClass for true color % images or PseudoClass for colormapped images. % % The format of the SetImageStorageClass method is: % % MagickBooleanType SetImageStorageClass(Image *image, % const ClassType storage_class,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o storage_class: The image class. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageStorageClass(Image *image, const ClassType storage_class,ExceptionInfo *exception) { 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); image->storage_class=storage_class; return(SyncImagePixelCache(image,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageExtent() sets the image size (i.e. columns & rows). % % The format of the SetImageExtent method is: % % MagickBooleanType SetImageExtent(Image *image,const size_t columns, % const size_t rows,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: The image width in pixels. % % o rows: The image height in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageExtent(Image *image,const size_t columns, const size_t rows,ExceptionInfo *exception) { if ((columns == 0) || (rows == 0)) ThrowBinaryException(ImageError,"NegativeOrZeroImageSize",image->filename); image->columns=columns; image->rows=rows; if ((image->depth == 0) || (image->depth > (8*sizeof(MagickSizeType)))) ThrowBinaryException(ImageError,"ImageDepthNotSupported",image->filename); return(SyncImagePixelCache(image,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S e t I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageInfo() initializes the 'magick' field of the ImageInfo structure. % It is set to a type of image format based on the prefix or suffix of the % filename. For example, 'ps:image' returns PS indicating a Postscript image. % JPEG is returned for this filename: 'image.jpg'. The filename prefix has % precendence over the suffix. Use an optional index enclosed in brackets % after a file name to specify a desired scene of a multi-resolution image % format like Photo CD (e.g. img0001.pcd[4]). A True (non-zero) return value % indicates success. % % The format of the SetImageInfo method is: % % MagickBooleanType SetImageInfo(ImageInfo *image_info, % const unsigned int frames,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o frames: the number of images you intend to write. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageInfo(ImageInfo *image_info, const unsigned int frames,ExceptionInfo *exception) { char component[MagickPathExtent], magic[MagickPathExtent], *q; const MagicInfo *magic_info; const MagickInfo *magick_info; ExceptionInfo *sans_exception; Image *image; MagickBooleanType status; register const char *p; ssize_t count; /* Look for 'image.format' in filename. */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); *component='\0'; GetPathComponent(image_info->filename,SubimagePath,component); if (*component != '\0') { /* Look for scene specification (e.g. img0001.pcd[4]). */ if (IsSceneGeometry(component,MagickFalse) == MagickFalse) { if (IsGeometry(component) != MagickFalse) (void) CloneString(&image_info->extract,component); } else { size_t first, last; (void) CloneString(&image_info->scenes,component); image_info->scene=StringToUnsignedLong(image_info->scenes); image_info->number_scenes=image_info->scene; p=image_info->scenes; for (q=(char *) image_info->scenes; *q != '\0'; p++) { while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; first=(size_t) strtol(p,&q,10); last=first; while (isspace((int) ((unsigned char) *q)) != 0) q++; if (*q == '-') last=(size_t) strtol(q+1,&q,10); if (first > last) Swap(first,last); if (first < image_info->scene) image_info->scene=first; if (last > image_info->number_scenes) image_info->number_scenes=last; p=q; } image_info->number_scenes-=image_info->scene-1; } } *component='\0'; if (*image_info->magick == '\0') GetPathComponent(image_info->filename,ExtensionPath,component); #if defined(MAGICKCORE_ZLIB_DELEGATE) if (*component != '\0') if ((LocaleCompare(component,"gz") == 0) || (LocaleCompare(component,"Z") == 0) || (LocaleCompare(component,"svgz") == 0) || (LocaleCompare(component,"wmz") == 0)) { char path[MagickPathExtent]; (void) CopyMagickString(path,image_info->filename,MagickPathExtent); path[strlen(path)-strlen(component)-1]='\0'; GetPathComponent(path,ExtensionPath,component); } #endif #if defined(MAGICKCORE_BZLIB_DELEGATE) if (*component != '\0') if (LocaleCompare(component,"bz2") == 0) { char path[MagickPathExtent]; (void) CopyMagickString(path,image_info->filename,MagickPathExtent); path[strlen(path)-strlen(component)-1]='\0'; GetPathComponent(path,ExtensionPath,component); } #endif image_info->affirm=MagickFalse; sans_exception=AcquireExceptionInfo(); if ((*component != '\0') && (IsGlob(component) == MagickFalse)) { MagickFormatType format_type; register ssize_t i; static const char *format_type_formats[] = { "AUTOTRACE", "BROWSE", "DCRAW", "EDIT", "LAUNCH", "MPEG:DECODE", "MPEG:ENCODE", "PRINT", "PS:ALPHA", "PS:CMYK", "PS:COLOR", "PS:GRAY", "PS:MONO", "SCAN", "SHOW", "WIN", (char *) NULL }; /* User specified image format. */ (void) CopyMagickString(magic,component,MagickPathExtent); LocaleUpper(magic); /* Look for explicit image formats. */ format_type=UndefinedFormatType; magick_info=GetMagickInfo(magic,sans_exception); if ((magick_info != (const MagickInfo *) NULL) && (magick_info->format_type != UndefinedFormatType)) format_type=magick_info->format_type; i=0; while ((format_type == UndefinedFormatType) && (format_type_formats[i] != (char *) NULL)) { if ((*magic == *format_type_formats[i]) && (LocaleCompare(magic,format_type_formats[i]) == 0)) format_type=ExplicitFormatType; i++; } if (format_type == UndefinedFormatType) (void) CopyMagickString(image_info->magick,magic,MagickPathExtent); else if (format_type == ExplicitFormatType) { image_info->affirm=MagickTrue; (void) CopyMagickString(image_info->magick,magic,MagickPathExtent); } if (LocaleCompare(magic,"RGB") == 0) image_info->affirm=MagickFalse; /* maybe SGI disguised as RGB */ } /* Look for explicit 'format:image' in filename. */ *magic='\0'; GetPathComponent(image_info->filename,MagickPath,magic); if (*magic == '\0') { (void) CopyMagickString(magic,image_info->magick,MagickPathExtent); magick_info=GetMagickInfo(magic,sans_exception); if (frames == 0) GetPathComponent(image_info->filename,CanonicalPath,component); else GetPathComponent(image_info->filename,SubcanonicalPath,component); (void) CopyMagickString(image_info->filename,component,MagickPathExtent); } else { const DelegateInfo *delegate_info; /* User specified image format. */ LocaleUpper(magic); magick_info=GetMagickInfo(magic,sans_exception); delegate_info=GetDelegateInfo(magic,"*",sans_exception); if (delegate_info == (const DelegateInfo *) NULL) delegate_info=GetDelegateInfo("*",magic,sans_exception); if (((magick_info != (const MagickInfo *) NULL) || (delegate_info != (const DelegateInfo *) NULL)) && (IsMagickConflict(magic) == MagickFalse)) { image_info->affirm=MagickTrue; (void) CopyMagickString(image_info->magick,magic,MagickPathExtent); GetPathComponent(image_info->filename,CanonicalPath,component); (void) CopyMagickString(image_info->filename,component, MagickPathExtent); } } sans_exception=DestroyExceptionInfo(sans_exception); if ((magick_info == (const MagickInfo *) NULL) || (GetMagickEndianSupport(magick_info) == MagickFalse)) image_info->endian=UndefinedEndian; if ((image_info->adjoin != MagickFalse) && (frames > 1)) { /* Test for multiple image support (e.g. image%02d.png). */ (void) InterpretImageFilename(image_info,(Image *) NULL, image_info->filename,(int) image_info->scene,component,exception); if ((LocaleCompare(component,image_info->filename) != 0) && (strchr(component,'%') == (char *) NULL)) image_info->adjoin=MagickFalse; } if ((image_info->adjoin != MagickFalse) && (frames > 0)) { /* Some image formats do not support multiple frames per file. */ magick_info=GetMagickInfo(magic,exception); if (magick_info != (const MagickInfo *) NULL) if (GetMagickAdjoin(magick_info) == MagickFalse) image_info->adjoin=MagickFalse; } if (image_info->affirm != MagickFalse) return(MagickTrue); if (frames == 0) { unsigned char *magick; size_t magick_size; /* Determine the image format from the first few bytes of the file. */ magick_size=GetMagicPatternExtent(exception); if (magick_size == 0) return(MagickFalse); image=AcquireImage(image_info,exception); (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImage(image); return(MagickFalse); } if ((IsBlobSeekable(image) == MagickFalse) || (IsBlobExempt(image) != MagickFalse)) { /* Copy image to seekable temporary file. */ *component='\0'; status=ImageToFile(image,component,exception); (void) CloseBlob(image); if (status == MagickFalse) { image=DestroyImage(image); return(MagickFalse); } SetImageInfoFile(image_info,(FILE *) NULL); (void) CopyMagickString(image->filename,component,MagickPathExtent); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImage(image); return(MagickFalse); } (void) CopyMagickString(image_info->filename,component, MagickPathExtent); image_info->temporary=MagickTrue; } magick=(unsigned char *) AcquireMagickMemory(magick_size); if (magick == (unsigned char *) NULL) { (void) CloseBlob(image); image=DestroyImage(image); return(MagickFalse); } (void) memset(magick,0,magick_size); count=ReadBlob(image,magick_size,magick); (void) SeekBlob(image,-((MagickOffsetType) count),SEEK_CUR); (void) CloseBlob(image); image=DestroyImage(image); /* Check magic cache. */ sans_exception=AcquireExceptionInfo(); magic_info=GetMagicInfo(magick,(size_t) count,sans_exception); magick=(unsigned char *) RelinquishMagickMemory(magick); if ((magic_info != (const MagicInfo *) NULL) && (GetMagicName(magic_info) != (char *) NULL)) { /* Try to use magick_info that was determined earlier by the extension */ if ((magick_info != (const MagickInfo *) NULL) && (GetMagickUseExtension(magick_info) != MagickFalse) && (LocaleCompare(magick_info->module,GetMagicName( magic_info)) == 0)) (void) CopyMagickString(image_info->magick,magick_info->name, MagickPathExtent); else { (void) CopyMagickString(image_info->magick,GetMagicName( magic_info),MagickPathExtent); magick_info=GetMagickInfo(image_info->magick,sans_exception); } if ((magick_info == (const MagickInfo *) NULL) || (GetMagickEndianSupport(magick_info) == MagickFalse)) image_info->endian=UndefinedEndian; sans_exception=DestroyExceptionInfo(sans_exception); return(MagickTrue); } magick_info=GetMagickInfo(image_info->magick,sans_exception); if ((magick_info == (const MagickInfo *) NULL) || (GetMagickEndianSupport(magick_info) == MagickFalse)) image_info->endian=UndefinedEndian; sans_exception=DestroyExceptionInfo(sans_exception); } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e I n f o B l o b % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageInfoBlob() sets the image info blob member. % % The format of the SetImageInfoBlob method is: % % void SetImageInfoBlob(ImageInfo *image_info,const void *blob, % const size_t length) % % A description of each parameter follows: % % o image_info: the image info. % % o blob: the blob. % % o length: the blob length. % */ MagickExport void SetImageInfoBlob(ImageInfo *image_info,const void *blob, const size_t length) { assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); image_info->blob=(void *) blob; image_info->length=length; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e I n f o C u s t o m S t r e a m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageInfoCustomStream() sets the image info custom stream handlers. % % The format of the SetImageInfoCustomStream method is: % % void SetImageInfoCustomStream(ImageInfo *image_info, % CustomStreamInfo *custom_stream) % % A description of each parameter follows: % % o image_info: the image info. % % o custom_stream: your custom stream methods. % */ MagickExport void SetImageInfoCustomStream(ImageInfo *image_info, CustomStreamInfo *custom_stream) { assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); image_info->custom_stream=(CustomStreamInfo *) custom_stream; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e I n f o F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageInfoFile() sets the image info file member. % % The format of the SetImageInfoFile method is: % % void SetImageInfoFile(ImageInfo *image_info,FILE *file) % % A description of each parameter follows: % % o image_info: the image info. % % o file: the file. % */ MagickExport void SetImageInfoFile(ImageInfo *image_info,FILE *file) { assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); image_info->file=file; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageMask() associates a mask with the image. The mask must be the same % dimensions as the image. % % The format of the SetImageMask method is: % % MagickBooleanType SetImageMask(Image *image,const PixelMask type, % const Image *mask,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o type: the mask type, ReadPixelMask or WritePixelMask. % % o mask: the image mask. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageMask(Image *image,const PixelMask type, const Image *mask,ExceptionInfo *exception) { CacheView *mask_view, *image_view; MagickBooleanType status; ssize_t y; /* Set image mask. */ assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (mask == (const Image *) NULL) { switch (type) { case ReadPixelMask: { image->channels=(ChannelType) (image->channels & ~ReadMaskChannel); break; } case WritePixelMask: { image->channels=(ChannelType) (image->channels & ~WriteMaskChannel); } default: { image->channels=(ChannelType) (image->channels & ~CompositeMaskChannel); break; } } return(SyncImagePixelCache(image,exception)); } switch (type) { case ReadPixelMask: { image->channels=(ChannelType) (image->channels | ReadMaskChannel); break; } case WritePixelMask: { image->channels=(ChannelType) (image->channels | WriteMaskChannel); break; } default: { image->channels=(ChannelType) (image->channels | CompositeMaskChannel); break; } } if (SyncImagePixelCache(image,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; image->mask_trait=UpdatePixelTrait; mask_view=AcquireVirtualCacheView(mask,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(mask,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(mask_view,0,y,mask->columns,1,exception); q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType intensity; intensity=0.0; if ((x < (ssize_t) mask->columns) && (y < (ssize_t) mask->rows)) intensity=GetPixelIntensity(mask,p); switch (type) { case ReadPixelMask: { SetPixelReadMask(image,ClampToQuantum(intensity),q); break; } case WritePixelMask: { SetPixelWriteMask(image,ClampToQuantum(intensity),q); break; } default: { SetPixelCompositeMask(image,ClampToQuantum(intensity),q); break; } } p+=GetPixelChannels(mask); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image->mask_trait=UndefinedPixelTrait; mask_view=DestroyCacheView(mask_view); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e R e g i o n M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageRegionMask() associates a mask with the image as defined by the % specified region. % % The format of the SetImageRegionMask method is: % % MagickBooleanType SetImageRegionMask(Image *image,const PixelMask type, % const RectangleInfo *region,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o type: the mask type, ReadPixelMask or WritePixelMask. % % o geometry: the mask region. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageRegionMask(Image *image, const PixelMask type,const RectangleInfo *region,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; /* Set image mask as defined by the region. */ assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (region == (const RectangleInfo *) NULL) { switch (type) { case ReadPixelMask: { image->channels=(ChannelType) (image->channels & ~ReadMaskChannel); break; } case WritePixelMask: { image->channels=(ChannelType) (image->channels & ~WriteMaskChannel); break; } default: { image->channels=(ChannelType) (image->channels & ~CompositeMaskChannel); break; } } return(SyncImagePixelCache(image,exception)); } switch (type) { case ReadPixelMask: { image->channels=(ChannelType) (image->channels | ReadMaskChannel); break; } case WritePixelMask: { image->channels=(ChannelType) (image->channels | WriteMaskChannel); break; } default: { image->channels=(ChannelType) (image->channels | CompositeMaskChannel); break; } } if (SyncImagePixelCache(image,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; image->mask_trait=UpdatePixelTrait; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=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++) { Quantum pixel; pixel=QuantumRange; if (((x >= region->x) && (x < (region->x+(ssize_t) region->width))) && ((y >= region->y) && (y < (region->y+(ssize_t) region->height)))) pixel=(Quantum) 0; switch (type) { case ReadPixelMask: { SetPixelReadMask(image,pixel,q); break; } case WritePixelMask: { SetPixelWriteMask(image,pixel,q); break; } default: { SetPixelCompositeMask(image,pixel,q); break; } } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image->mask_trait=UndefinedPixelTrait; image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e V i r t u a l P i x e l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageVirtualPixelMethod() sets the "virtual pixels" method for the % image and returns the previous setting. A virtual pixel is any pixel access % that is outside the boundaries of the image cache. % % The format of the SetImageVirtualPixelMethod() method is: % % VirtualPixelMethod SetImageVirtualPixelMethod(Image *image, % const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: choose the type of virtual pixel. % % o exception: return any errors or warnings in this structure. % */ MagickExport VirtualPixelMethod SetImageVirtualPixelMethod(Image *image, const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception) { assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); return(SetPixelCacheVirtualMethod(image,virtual_pixel_method,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S m u s h I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SmushImages() takes all images from the current image pointer to the end % of the image list and smushes them to each other top-to-bottom if the % stack parameter is true, otherwise left-to-right. % % The current gravity setting now effects how the image is justified in the % final image. % % The format of the SmushImages method is: % % Image *SmushImages(const Image *images,const MagickBooleanType stack, % ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o stack: A value other than 0 stacks the images top-to-bottom. % % o offset: minimum distance in pixels between images. % % o exception: return any errors or warnings in this structure. % */ static ssize_t SmushXGap(const Image *smush_image,const Image *images, const ssize_t offset,ExceptionInfo *exception) { CacheView *left_view, *right_view; const Image *left_image, *right_image; RectangleInfo left_geometry, right_geometry; register const Quantum *p; register ssize_t i, y; size_t gap; ssize_t x; if (images->previous == (Image *) NULL) return(0); right_image=images; SetGeometry(smush_image,&right_geometry); GravityAdjustGeometry(right_image->columns,right_image->rows, right_image->gravity,&right_geometry); left_image=images->previous; SetGeometry(smush_image,&left_geometry); GravityAdjustGeometry(left_image->columns,left_image->rows, left_image->gravity,&left_geometry); gap=right_image->columns; left_view=AcquireVirtualCacheView(left_image,exception); right_view=AcquireVirtualCacheView(right_image,exception); for (y=0; y < (ssize_t) smush_image->rows; y++) { for (x=(ssize_t) left_image->columns-1; x > 0; x--) { p=GetCacheViewVirtualPixels(left_view,x,left_geometry.y+y,1,1,exception); if ((p == (const Quantum *) NULL) || (GetPixelAlpha(left_image,p) != TransparentAlpha) || ((left_image->columns-x-1) >= gap)) break; } i=(ssize_t) left_image->columns-x-1; for (x=0; x < (ssize_t) right_image->columns; x++) { p=GetCacheViewVirtualPixels(right_view,x,right_geometry.y+y,1,1, exception); if ((p == (const Quantum *) NULL) || (GetPixelAlpha(right_image,p) != TransparentAlpha) || ((x+i) >= (ssize_t) gap)) break; } if ((x+i) < (ssize_t) gap) gap=(size_t) (x+i); } right_view=DestroyCacheView(right_view); left_view=DestroyCacheView(left_view); if (y < (ssize_t) smush_image->rows) return(offset); return((ssize_t) gap-offset); } static ssize_t SmushYGap(const Image *smush_image,const Image *images, const ssize_t offset,ExceptionInfo *exception) { CacheView *bottom_view, *top_view; const Image *bottom_image, *top_image; RectangleInfo bottom_geometry, top_geometry; register const Quantum *p; register ssize_t i, x; size_t gap; ssize_t y; if (images->previous == (Image *) NULL) return(0); bottom_image=images; SetGeometry(smush_image,&bottom_geometry); GravityAdjustGeometry(bottom_image->columns,bottom_image->rows, bottom_image->gravity,&bottom_geometry); top_image=images->previous; SetGeometry(smush_image,&top_geometry); GravityAdjustGeometry(top_image->columns,top_image->rows,top_image->gravity, &top_geometry); gap=bottom_image->rows; top_view=AcquireVirtualCacheView(top_image,exception); bottom_view=AcquireVirtualCacheView(bottom_image,exception); for (x=0; x < (ssize_t) smush_image->columns; x++) { for (y=(ssize_t) top_image->rows-1; y > 0; y--) { p=GetCacheViewVirtualPixels(top_view,top_geometry.x+x,y,1,1,exception); if ((p == (const Quantum *) NULL) || (GetPixelAlpha(top_image,p) != TransparentAlpha) || ((top_image->rows-y-1) >= gap)) break; } i=(ssize_t) top_image->rows-y-1; for (y=0; y < (ssize_t) bottom_image->rows; y++) { p=GetCacheViewVirtualPixels(bottom_view,bottom_geometry.x+x,y,1,1, exception); if ((p == (const Quantum *) NULL) || (GetPixelAlpha(bottom_image,p) != TransparentAlpha) || ((y+i) >= (ssize_t) gap)) break; } if ((y+i) < (ssize_t) gap) gap=(size_t) (y+i); } bottom_view=DestroyCacheView(bottom_view); top_view=DestroyCacheView(top_view); if (x < (ssize_t) smush_image->columns) return(offset); return((ssize_t) gap-offset); } MagickExport Image *SmushImages(const Image *images, const MagickBooleanType stack,const ssize_t offset,ExceptionInfo *exception) { #define SmushImageTag "Smush/Image" const Image *image; Image *smush_image; MagickBooleanType proceed, status; MagickOffsetType n; PixelTrait alpha_trait; RectangleInfo geometry; register const Image *next; size_t height, number_images, width; ssize_t x_offset, y_offset; /* Compute maximum area of smushed area. */ 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=images; alpha_trait=image->alpha_trait; number_images=1; width=image->columns; height=image->rows; next=GetNextImageInList(image); for ( ; next != (Image *) NULL; next=GetNextImageInList(next)) { if (next->alpha_trait != UndefinedPixelTrait) alpha_trait=BlendPixelTrait; number_images++; if (stack != MagickFalse) { if (next->columns > width) width=next->columns; height+=next->rows; if (next->previous != (Image *) NULL) height+=offset; continue; } width+=next->columns; if (next->previous != (Image *) NULL) width+=offset; if (next->rows > height) height=next->rows; } /* Smush images. */ smush_image=CloneImage(image,width,height,MagickTrue,exception); if (smush_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(smush_image,DirectClass,exception) == MagickFalse) { smush_image=DestroyImage(smush_image); return((Image *) NULL); } smush_image->alpha_trait=alpha_trait; (void) SetImageBackgroundColor(smush_image,exception); status=MagickTrue; x_offset=0; y_offset=0; for (n=0; n < (MagickOffsetType) number_images; n++) { SetGeometry(smush_image,&geometry); GravityAdjustGeometry(image->columns,image->rows,image->gravity,&geometry); if (stack != MagickFalse) { x_offset-=geometry.x; y_offset-=SmushYGap(smush_image,image,offset,exception); } else { x_offset-=SmushXGap(smush_image,image,offset,exception); y_offset-=geometry.y; } status=CompositeImage(smush_image,image,OverCompositeOp,MagickTrue,x_offset, y_offset,exception); proceed=SetImageProgress(image,SmushImageTag,n,number_images); if (proceed == MagickFalse) break; if (stack == MagickFalse) { x_offset+=(ssize_t) image->columns; y_offset=0; } else { x_offset=0; y_offset+=(ssize_t) image->rows; } image=GetNextImageInList(image); } if (stack == MagickFalse) smush_image->columns=(size_t) x_offset; else smush_image->rows=(size_t) y_offset; if (status == MagickFalse) smush_image=DestroyImage(smush_image); return(smush_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t r i p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % StripImage() strips an image of all profiles and comments. % % The format of the StripImage method is: % % MagickBooleanType StripImage(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 StripImage(Image *image,ExceptionInfo *exception) { MagickBooleanType status; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); (void) exception; DestroyImageProfiles(image); (void) DeleteImageProperty(image,"comment"); (void) DeleteImageProperty(image,"date:create"); (void) DeleteImageProperty(image,"date:modify"); status=SetImageArtifact(image,"png:exclude-chunk", "bKGD,caNv,cHRM,eXIf,gAMA,iCCP,iTXt,pHYs,sRGB,tEXt,zCCP,zTXt,date"); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImage() initializes the red, green, and blue intensities of each pixel % as defined by the colormap index. % % The format of the SyncImage method is: % % MagickBooleanType SyncImage(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 Quantum PushColormapIndex(Image *image,const Quantum index, MagickBooleanType *range_exception) { if ((size_t) index < image->colors) return(index); *range_exception=MagickTrue; return((Quantum) 0); } MagickExport MagickBooleanType SyncImage(Image *image,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType range_exception, status, taint; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (image->ping != MagickFalse) return(MagickTrue); if (image->storage_class != PseudoClass) return(MagickFalse); assert(image->colormap != (PixelInfo *) NULL); range_exception=MagickFalse; status=MagickTrue; taint=image->taint; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(range_exception,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Quantum index; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { index=PushColormapIndex(image,GetPixelIndex(image,q),&range_exception); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); image->taint=taint; if ((image->ping == MagickFalse) && (range_exception != MagickFalse)) (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageWarning,"InvalidColormapIndex","`%s'",image->filename); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S y n c I m a g e S e t t i n g s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImageSettings() syncs any image_info global options into per-image % attributes. % % Note: in IMv6 free form 'options' were always mapped into 'artifacts', so % that operations and coders can find such settings. In IMv7 if a desired % per-image artifact is not set, then it will directly look for a global % option as a fallback, as such this copy is no longer needed, only the % link set up. % % The format of the SyncImageSettings method is: % % MagickBooleanType SyncImageSettings(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % MagickBooleanType SyncImagesSettings(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SyncImagesSettings(ImageInfo *image_info, Image *images,ExceptionInfo *exception) { Image *image; assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); image=images; for ( ; image != (Image *) NULL; image=GetNextImageInList(image)) (void) SyncImageSettings(image_info,image,exception); (void) DeleteImageOption(image_info,"page"); return(MagickTrue); } MagickExport MagickBooleanType SyncImageSettings(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { const char *option; GeometryInfo geometry_info; MagickStatusType flags; ResolutionType units; /* Sync image options. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); option=GetImageOption(image_info,"background"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&image->background_color, exception); option=GetImageOption(image_info,"black-point-compensation"); if (option != (const char *) NULL) image->black_point_compensation=(MagickBooleanType) ParseCommandOption( MagickBooleanOptions,MagickFalse,option); option=GetImageOption(image_info,"blue-primary"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->chromaticity.blue_primary.x=geometry_info.rho; image->chromaticity.blue_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.blue_primary.y=image->chromaticity.blue_primary.x; } option=GetImageOption(image_info,"bordercolor"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&image->border_color, exception); /* FUTURE: do not sync compose to per-image compose setting here */ option=GetImageOption(image_info,"compose"); if (option != (const char *) NULL) image->compose=(CompositeOperator) ParseCommandOption(MagickComposeOptions, MagickFalse,option); /* -- */ option=GetImageOption(image_info,"compress"); if (option != (const char *) NULL) image->compression=(CompressionType) ParseCommandOption( MagickCompressOptions,MagickFalse,option); option=GetImageOption(image_info,"debug"); if (option != (const char *) NULL) image->debug=(MagickBooleanType) ParseCommandOption(MagickBooleanOptions, MagickFalse,option); option=GetImageOption(image_info,"density"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; } option=GetImageOption(image_info,"depth"); if (option != (const char *) NULL) image->depth=StringToUnsignedLong(option); option=GetImageOption(image_info,"endian"); if (option != (const char *) NULL) image->endian=(EndianType) ParseCommandOption(MagickEndianOptions, MagickFalse,option); option=GetImageOption(image_info,"filter"); if (option != (const char *) NULL) image->filter=(FilterType) ParseCommandOption(MagickFilterOptions, MagickFalse,option); option=GetImageOption(image_info,"fuzz"); if (option != (const char *) NULL) image->fuzz=StringToDoubleInterval(option,(double) QuantumRange+1.0); option=GetImageOption(image_info,"gravity"); if (option != (const char *) NULL) image->gravity=(GravityType) ParseCommandOption(MagickGravityOptions, MagickFalse,option); option=GetImageOption(image_info,"green-primary"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->chromaticity.green_primary.x=geometry_info.rho; image->chromaticity.green_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.green_primary.y=image->chromaticity.green_primary.x; } option=GetImageOption(image_info,"intent"); if (option != (const char *) NULL) image->rendering_intent=(RenderingIntent) ParseCommandOption( MagickIntentOptions,MagickFalse,option); option=GetImageOption(image_info,"intensity"); if (option != (const char *) NULL) image->intensity=(PixelIntensityMethod) ParseCommandOption( MagickPixelIntensityOptions,MagickFalse,option); option=GetImageOption(image_info,"interlace"); if (option != (const char *) NULL) image->interlace=(InterlaceType) ParseCommandOption(MagickInterlaceOptions, MagickFalse,option); option=GetImageOption(image_info,"interpolate"); if (option != (const char *) NULL) image->interpolate=(PixelInterpolateMethod) ParseCommandOption( MagickInterpolateOptions,MagickFalse,option); option=GetImageOption(image_info,"loop"); if (option != (const char *) NULL) image->iterations=StringToUnsignedLong(option); option=GetImageOption(image_info,"mattecolor"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&image->matte_color, exception); option=GetImageOption(image_info,"orient"); if (option != (const char *) NULL) image->orientation=(OrientationType) ParseCommandOption( MagickOrientationOptions,MagickFalse,option); option=GetImageOption(image_info,"page"); if (option != (const char *) NULL) { char *geometry; geometry=GetPageGeometry(option); flags=ParseAbsoluteGeometry(geometry,&image->page); geometry=DestroyString(geometry); } option=GetImageOption(image_info,"quality"); if (option != (const char *) NULL) image->quality=StringToUnsignedLong(option); option=GetImageOption(image_info,"red-primary"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->chromaticity.red_primary.x=geometry_info.rho; image->chromaticity.red_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.red_primary.y=image->chromaticity.red_primary.x; } if (image_info->quality != UndefinedCompressionQuality) image->quality=image_info->quality; option=GetImageOption(image_info,"scene"); if (option != (const char *) NULL) image->scene=StringToUnsignedLong(option); option=GetImageOption(image_info,"taint"); if (option != (const char *) NULL) image->taint=(MagickBooleanType) ParseCommandOption(MagickBooleanOptions, MagickFalse,option); option=GetImageOption(image_info,"tile-offset"); if (option != (const char *) NULL) { char *geometry; geometry=GetPageGeometry(option); flags=ParseAbsoluteGeometry(geometry,&image->tile_offset); geometry=DestroyString(geometry); } option=GetImageOption(image_info,"transparent-color"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&image->transparent_color, exception); option=GetImageOption(image_info,"type"); if (option != (const char *) NULL) image->type=(ImageType) ParseCommandOption(MagickTypeOptions,MagickFalse, option); option=GetImageOption(image_info,"units"); units=image_info->units; if (option != (const char *) NULL) units=(ResolutionType) ParseCommandOption(MagickResolutionOptions, MagickFalse,option); if (units != UndefinedResolution) { if (image->units != units) switch (image->units) { case PixelsPerInchResolution: { if (units == PixelsPerCentimeterResolution) { image->resolution.x/=2.54; image->resolution.y/=2.54; } break; } case PixelsPerCentimeterResolution: { if (units == PixelsPerInchResolution) { image->resolution.x=(double) ((size_t) (100.0*2.54* image->resolution.x+0.5))/100.0; image->resolution.y=(double) ((size_t) (100.0*2.54* image->resolution.y+0.5))/100.0; } break; } default: break; } image->units=units; } option=GetImageOption(image_info,"virtual-pixel"); if (option != (const char *) NULL) (void) SetImageVirtualPixelMethod(image,(VirtualPixelMethod) ParseCommandOption(MagickVirtualPixelOptions,MagickFalse,option), exception); option=GetImageOption(image_info,"white-point"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->chromaticity.white_point.x=geometry_info.rho; image->chromaticity.white_point.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.white_point.y=image->chromaticity.white_point.x; } /* Pointer to allow the lookup of pre-image artifact will fallback to a global option setting/define. This saves a lot of duplication of global options into per-image artifacts, while ensuring only specifically set per-image artifacts are preserved when parenthesis ends. */ if (image->image_info != (ImageInfo *) NULL) image->image_info=DestroyImageInfo(image->image_info); image->image_info=CloneImageInfo(image_info); return(MagickTrue); }
convolution_3x3.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2017 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 __ARM_NEON #include <arm_neon.h> #endif // __ARM_NEON static void conv3x3s1_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for for (int p=0; p<outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); const float* kernel0 = kernel + p*inch*9; for (int q=0; q<inch; q++) { float* outptr = out; float* outptr2 = outptr + outw; const float* img0 = bottom_blob.channel(q); const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w*2; const float* r3 = img0 + w*3; const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; #if __ARM_NEON float32x4_t _k0123 = vld1q_f32(kernel0); float32x4_t _k3456 = vld1q_f32(kernel0+3); float32x4_t _k6789 = vld1q_f32(kernel0+6); #endif // __ARM_NEON int i = 0; for (; i+1 < outh; i+=2) { #if __ARM_NEON int nn = outw >> 2; int remain = outw & 3; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ for (; nn>0; nn--) { float32x4_t _sum1 = vld1q_f32(outptr); float32x4_t _sum2 = vdupq_n_f32(0.f); float32x4_t _sum3 = vld1q_f32(outptr2); float32x4_t _sum4 = vdupq_n_f32(0.f); float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r00n = vld1q_f32(r0 + 4); float32x4_t _r01 = vextq_f32(_r00, _r00n, 1); float32x4_t _r02 = vextq_f32(_r00, _r00n, 2); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r10n = vld1q_f32(r1 + 4); float32x4_t _r11 = vextq_f32(_r10, _r10n, 1); float32x4_t _r12 = vextq_f32(_r10, _r10n, 2); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _r20n = vld1q_f32(r2 + 4); float32x4_t _r21 = vextq_f32(_r20, _r20n, 1); float32x4_t _r22 = vextq_f32(_r20, _r20n, 2); float32x4_t _r30 = vld1q_f32(r3); float32x4_t _r30n = vld1q_f32(r3 + 4); float32x4_t _r31 = vextq_f32(_r30, _r30n, 1); float32x4_t _r32 = vextq_f32(_r30, _r30n, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r00, _k0123, 0); _sum2 = vfmaq_laneq_f32(_sum2, _r01, _k0123, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r02, _k0123, 2); _sum2 = vfmaq_laneq_f32(_sum2, _r10, _k3456, 0); _sum1 = vfmaq_laneq_f32(_sum1, _r11, _k3456, 1); _sum2 = vfmaq_laneq_f32(_sum2, _r12, _k3456, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r20, _k6789, 0); _sum2 = vfmaq_laneq_f32(_sum2, _r21, _k6789, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r22, _k6789, 2); _sum3 = vfmaq_laneq_f32(_sum3, _r10, _k0123, 0); _sum4 = vfmaq_laneq_f32(_sum4, _r11, _k0123, 1); _sum3 = vfmaq_laneq_f32(_sum3, _r12, _k0123, 2); _sum4 = vfmaq_laneq_f32(_sum4, _r20, _k3456, 0); _sum3 = vfmaq_laneq_f32(_sum3, _r21, _k3456, 1); _sum4 = vfmaq_laneq_f32(_sum4, _r22, _k3456, 2); _sum3 = vfmaq_laneq_f32(_sum3, _r30, _k6789, 0); _sum4 = vfmaq_laneq_f32(_sum4, _r31, _k6789, 1); _sum3 = vfmaq_laneq_f32(_sum3, _r32, _k6789, 2); _sum1 = vaddq_f32(_sum1, _sum2); _sum3 = vaddq_f32(_sum3, _sum4); vst1q_f32(outptr, _sum1); vst1q_f32(outptr2, _sum3); r0 += 4; r1 += 4; r2 += 4; r3 += 4; outptr += 4; outptr2 += 4; } #else if (nn > 0) { asm volatile( "veor q6, q6 \n" "veor q15, q15 \n" "pld [%3, #192] \n" "vld1.f32 {d18-d20}, [%3 :64] \n"// r0 "add %3, #16 \n" "veor q13, q13 \n" "veor q14, q14 \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "0: \n" "pld [%1, #128] \n" "vld1.f32 {d14-d15}, [%1 :64] \n"// _sum "vmla.f32 q7, q9, %e14[0] \n" "vmla.f32 q6, q11, %e14[1] \n" "vmla.f32 q13, q12, %f14[0] \n" "pld [%4, #192] \n" "vld1.f32 {d18-d20}, [%4] \n"// r1 "add %4, #16 \n" "vmla.f32 q7, q9, %e15[0] \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "vmla.f32 q6, q11, %e15[1] \n" "vmla.f32 q13, q12, %f15[0] \n" "pld [%2, #128] \n" "vld1.f32 {d16-d17}, [%2] \n"// _sum2 "vmla.f32 q8, q9, %e14[0] \n" "vmla.f32 q14, q11, %e14[1] \n" "vmla.f32 q15, q12, %f14[0] \n" "pld [%5, #192] \n" "vld1.f32 {d18-d20}, [%5 :64] \n"// r2 "add %5, #16 \n" "vmla.f32 q7, q9, %e16[0] \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "vmla.f32 q6, q11, %e16[1] \n" "vmla.f32 q13, q12, %f16[0] \n" "vmla.f32 q8, q9, %e15[0] \n" "vmla.f32 q14, q11, %e15[1] \n" "vmla.f32 q15, q12, %f15[0] \n" "pld [%6, #192] \n" "vld1.f32 {d18-d20}, [%6] \n"// r3 "add %6, #16 \n" "vmla.f32 q8, q9, %e16[0] \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "vmla.f32 q14, q11, %e16[1] \n" "vmla.f32 q15, q12, %f16[0] \n" "vadd.f32 q7, q7, q6 \n" "veor q6, q6 \n" "pld [%3, #192] \n" "vld1.f32 {d18-d20}, [%3 :64] \n"// r0 "vadd.f32 q8, q8, q14 \n" "veor q14, q14 \n" "vadd.f32 q7, q7, q13 \n" "veor q13, q13 \n" "vadd.f32 q8, q8, q15 \n" "veor q15, q15 \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "add %3, #16 \n" "vst1.f32 {d14-d15}, [%1]! \n" "vst1.f32 {d16-d17}, [%2]! \n" "subs %0, #1 \n" "bne 0b \n" "sub %3, #16 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(outptr2), // %2 "=r"(r0), // %3 "=r"(r1), // %4 "=r"(r2), // %5 "=r"(r3) // %6 : "0"(nn), "1"(outptr), "2"(outptr2), "3"(r0), "4"(r1), "5"(r2), "6"(r3), "w"(_k0123), // %14 "w"(_k3456), // %15 "w"(_k6789) // %16 : "cc", "memory", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { #if __ARM_NEON float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _r30 = vld1q_f32(r3); float32x4_t _sum = vmulq_f32(_r00, _k0123); _sum = vmlaq_f32(_sum, _r10, _k3456); _sum = vmlaq_f32(_sum, _r20, _k6789); float32x4_t _sum2 = vmulq_f32(_r10, _k0123); _sum2 = vmlaq_f32(_sum2, _r20, _k3456); _sum2 = vmlaq_f32(_sum2, _r30, _k6789); _sum = vsetq_lane_f32(*outptr, _sum, 3); _sum2 = vsetq_lane_f32(*outptr2, _sum2, 3); #if __aarch64__ *outptr = vaddvq_f32(_sum); *outptr2 = vaddvq_f32(_sum2); #else float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum)); float32x2_t _ss2 = vadd_f32(vget_low_f32(_sum2), vget_high_f32(_sum2)); float32x2_t _sss2 = vpadd_f32(_ss, _ss2); *outptr = vget_lane_f32(_sss2, 0); *outptr2 = vget_lane_f32(_sss2, 1); #endif // __aarch64__ #else float sum = 0; float sum2 = 0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; sum2 += r1[0] * k0[0]; sum2 += r1[1] * k0[1]; sum2 += r1[2] * k0[2]; sum2 += r2[0] * k1[0]; sum2 += r2[1] * k1[1]; sum2 += r2[2] * k1[2]; sum2 += r3[0] * k2[0]; sum2 += r3[1] * k2[1]; sum2 += r3[2] * k2[2]; *outptr += sum; *outptr2 += sum2; #endif r0++; r1++; r2++; r3++; outptr++; outptr2++; } r0 += 2 + w; r1 += 2 + w; r2 += 2 + w; r3 += 2 + w; outptr += outw; outptr2 += outw; } for (; i < outh; i++) { #if __ARM_NEON int nn = outw >> 2; int remain = outw & 3; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ for (; nn>0; nn--) { float32x4_t _sum1 = vld1q_f32(outptr); float32x4_t _sum2 = vdupq_n_f32(0.f); float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r00n = vld1q_f32(r0 + 4); float32x4_t _r01 = vextq_f32(_r00, _r00n, 1); float32x4_t _r02 = vextq_f32(_r00, _r00n, 2); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r10n = vld1q_f32(r1 + 4); float32x4_t _r11 = vextq_f32(_r10, _r10n, 1); float32x4_t _r12 = vextq_f32(_r10, _r10n, 2); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _r20n = vld1q_f32(r2 + 4); float32x4_t _r21 = vextq_f32(_r20, _r20n, 1); float32x4_t _r22 = vextq_f32(_r20, _r20n, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r00, _k0123, 0); _sum2 = vfmaq_laneq_f32(_sum2, _r01, _k0123, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r02, _k0123, 2); _sum2 = vfmaq_laneq_f32(_sum2, _r10, _k3456, 0); _sum1 = vfmaq_laneq_f32(_sum1, _r11, _k3456, 1); _sum2 = vfmaq_laneq_f32(_sum2, _r12, _k3456, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r20, _k6789, 0); _sum2 = vfmaq_laneq_f32(_sum2, _r21, _k6789, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r22, _k6789, 2); _sum1 = vaddq_f32(_sum1, _sum2); vst1q_f32(outptr, _sum1); r0 += 4; r1 += 4; r2 += 4; outptr += 4; } #else if (nn > 0) { asm volatile( "pld [%2, #192] \n" "vld1.f32 {d16-d18}, [%2] \n"// r0 "add %2, #16 \n" "veor q13, q13 \n" "veor q14, q14 \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "0: \n" "pld [%1, #128] \n" "vld1.f32 {d14-d15}, [%1] \n"// _sum "vmla.f32 q7, q8, %e10[0] \n" "vmla.f32 q13, q10, %e10[1] \n" "vmla.f32 q14, q11, %f10[0] \n" "pld [%3, #192] \n" "vld1.f32 {d16-d18}, [%3] \n"// r1 "add %3, #16 \n" "vmla.f32 q7, q8, %e11[0] \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vmla.f32 q13, q10, %e11[1] \n" "vmla.f32 q14, q11, %f11[0] \n" "pld [%4, #192] \n" "vld1.f32 {d16-d18}, [%4] \n"// r2 "add %4, #16 \n" "vmla.f32 q7, q8, %e12[0] \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vmla.f32 q13, q10, %e12[1] \n" "vmla.f32 q14, q11, %f12[0] \n" "pld [%2, #192] \n" "vld1.f32 {d16-d18}, [%2] \n"// r0 "add %2, #16 \n" "vadd.f32 q7, q7, q13 \n" "veor q13, q13 \n" "vadd.f32 q7, q7, q14 \n" "veor q14, q14 \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vst1.f32 {d14-d15}, [%1]! \n" "subs %0, #1 \n" "bne 0b \n" "sub %2, #16 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2) // %4 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "w"(_k0123), // %10 "w"(_k3456), // %11 "w"(_k6789) // %12 : "cc", "memory", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { #if __ARM_NEON float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _sum = vmulq_f32(_r00, _k0123); _sum = vmlaq_f32(_sum, _r10, _k3456); _sum = vmlaq_f32(_sum, _r20, _k6789); _sum = vsetq_lane_f32(*outptr, _sum, 3); #if __aarch64__ *outptr = vaddvq_f32(_sum); #else float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum)); _ss = vpadd_f32(_ss, _ss); *outptr = vget_lane_f32(_ss, 0); #endif // __aarch64__ #else float sum = 0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; *outptr += sum; #endif r0++; r1++; r2++; outptr++; } r0 += 2; r1 += 2; r2 += 2; } kernel0 += 9; } } } static void conv3x3s1_winograd64_transform_kernel_neon(const Mat& kernel, Mat& kernel_tm, int inch, int outch) { kernel_tm.create(8*8, inch, outch); const float ktm[8][3] = { { 1.0f, 0.0f, 0.0f}, {-2.0f/9, -2.0f/9, -2.0f/9}, {-2.0f/9, 2.0f/9, -2.0f/9}, {1.0f/90, 1.0f/45, 2.0f/45}, {1.0f/90, -1.0f/45, 2.0f/45}, {1.0f/45, 1.0f/90, 1.0f/180}, {1.0f/45, -1.0f/90, 1.0f/180}, { 0.0f, 0.0f, 1.0f} }; #pragma omp parallel for for (int p = 0; p<outch; p++) { for (int q = 0; q<inch; q++) { const float* kernel0 = kernel.data + p*inch * 9 + q * 9; float* kernel_tm0 = kernel_tm.channel(p).row(q); // transform kernel, transposed const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; // h float tmp[8][3]; for (int i=0; i<8; 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]; } // v for (int j=0; j<8; j++) { float* tmpp = &tmp[j][0]; for (int i=0; i<8; i++) { kernel_tm0[j*8 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2]; } } } } } static void conv3x3s1_winograd64_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& _bias) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // pad to 6n+2 Mat bottom_blob_bordered = bottom_blob; outw = (outw + 5) / 6 * 6; outh = (outh + 5) / 6 * 6; w = outw + 2; h = outh + 2; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, 0, 0.f); const float* bias = _bias; // BEGIN transform input Mat bottom_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; bottom_blob_tm.create(8*8, w_tm/8 * h_tm/8, inch); // const float itm[8][8] = { // {1.0f, 0.0f, -5.25f, 0.00f, 5.25f, 0.00f, -1.0f, 0.0f}, // // {0.0f, 1.0f, 1.00f, -4.25f, -4.25f, 1.00f, 1.0f, 0.0f}, // {0.0f, -1.0f, 1.00f, 4.25f, -4.25f, -1.00f, 1.0f, 0.0f}, // // {0.0f, 0.5f, 0.25f, -2.50f, -1.25f, 2.00f, 1.0f, 0.0f}, // {0.0f, -0.5f, 0.25f, 2.50f, -1.25f, -2.00f, 1.0f, 0.0f}, // // {0.0f, 2.0f, 4.00f, -2.50f, -5.00f, 0.50f, 1.0f, 0.0f}, // {0.0f, -2.0f, 4.00f, 2.50f, -5.00f, -0.50f, 1.0f, 0.0f}, // // {0.0f, -1.0f, 0.00f, 5.25f, 0.00f, -5.25f, 0.0f, 1.0f} // }; // 0 = r00 - r06 + (r04 - r02) * 5.25 // 7 = r07 - r01 + (r03 - r05) * 5.25 // 1 = (r02 + r06 - r04 * 4.25) + (r01 - r03 * 4.25 + r05) // 2 = (r02 + r06 - r04 * 4.25) - (r01 - r03 * 4.25 + r05) // 3 = (r06 + r02 * 0.25 - r04 * 1.25) + (r01 * 0.5 - r03 * 2.5 + r05 * 2) // 4 = (r06 + r02 * 0.25 - r04 * 1.25) - (r01 * 0.5 - r03 * 2.5 + r05 * 2) // reuse r04 * 1.25 // reuse r03 * 2.5 // 5 = (r06 + (r02 - r04 * 1.25) * 4) + (r01 * 2 - r03 * 2.5 + r05 * 0.5) // 6 = (r06 + (r02 - r04 * 1.25) * 4) - (r01 * 2 - r03 * 2.5 + r05 * 0.5) #pragma omp parallel for for (int q = 0; q<inch; q++) { const Mat img0 = bottom_blob_bordered.channel(q); Mat img0_tm = bottom_blob_tm.channel(q); float tmp[8][8]; // tile for (int i=0; i<h_tm/8; i++) { for (int j=0; j<w_tm/8; j++) { const float* r0 = img0.row(i * 6) + j * 6; float* r0_tm = img0_tm.row(i * w_tm/8 + j); // TODO neon optimize for (int m=0; m<8; m++) { tmp[0][m] = r0[0] - r0[6] + (r0[4] - r0[2]) * 5.25; tmp[7][m] = r0[7] - r0[1] + (r0[3] - r0[5]) * 5.25; float tmp12a = (r0[2] + r0[6] - r0[4] * 4.25); float tmp12b = (r0[1] + r0[5] - r0[3] * 4.25); tmp[1][m] = tmp12a + tmp12b; tmp[2][m] = tmp12a - tmp12b; float tmp34a = (r0[6] + r0[2] * 0.25 - r0[4] * 1.25); float tmp34b = (r0[1] * 0.5 - r0[3] * 2.5 + r0[5] * 2); tmp[3][m] = tmp34a + tmp34b; tmp[4][m] = tmp34a - tmp34b; float tmp56a = (r0[6] + (r0[2] - r0[4] * 1.25) * 4); float tmp56b = (r0[1] * 2 - r0[3] * 2.5 + r0[5] * 0.5); tmp[5][m] = tmp56a + tmp56b; tmp[6][m] = tmp56a - tmp56b; r0 += w; } for (int m=0; m<8; m++) { const float* tmp0 = tmp[m]; r0_tm[0] = tmp0[0] - tmp0[6] + (tmp0[4] - tmp0[2]) * 5.25; r0_tm[7] = tmp0[7] - tmp0[1] + (tmp0[3] - tmp0[5]) * 5.25; float tmp12a = (tmp0[2] + tmp0[6] - tmp0[4] * 4.25); float tmp12b = (tmp0[1] - tmp0[3] * 4.25 + tmp0[5]); r0_tm[1] = tmp12a + tmp12b; r0_tm[2] = tmp12a - tmp12b; float tmp34a = (tmp0[6] + tmp0[2] * 0.25 - tmp0[4] * 1.25); float tmp34b = (tmp0[1] * 0.5 - tmp0[3] * 2.5 + tmp0[5] * 2); r0_tm[3] = tmp34a + tmp34b; r0_tm[4] = tmp34a - tmp34b; float tmp56a = (tmp0[6] + (tmp0[2] - tmp0[4] * 1.25) * 4); float tmp56b = (tmp0[1] * 2 - tmp0[3] * 2.5 + tmp0[5] * 0.5); r0_tm[5] = tmp56a + tmp56b; r0_tm[6] = tmp56a - tmp56b; r0_tm += 8; } } } } } // END transform input // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; top_blob_tm.create(8*8, w_tm/8 * h_tm/8, outch); #pragma omp parallel for for (int p = 0; p<outch; p++) { Mat out0_tm = top_blob_tm.channel(p); const Mat kernel0_tm = kernel_tm.channel(p); out0_tm.fill(0.f); int q = 0; for (; q+3<inch; q+=4) { const float* r0 = bottom_blob_tm.channel(q); const float* r1 = bottom_blob_tm.channel(q+1); const float* r2 = bottom_blob_tm.channel(q+2); const float* r3 = bottom_blob_tm.channel(q+3); const float* k0 = kernel0_tm.row(q); const float* k1 = kernel0_tm.row(q+1); const float* k2 = kernel0_tm.row(q+2); const float* k3 = kernel0_tm.row(q+3); float* output0_tm = out0_tm; // tile for (int i=0; i<h_tm/8 * w_tm/8; i++) { #if __ARM_NEON #if __aarch64__ for (int m=0; m+7<64; m+=8) { float32x4_t _output0_tm = vld1q_f32(output0_tm); float32x4_t _r0 = vld1q_f32(r0); float32x4_t _r1 = vld1q_f32(r1); float32x4_t _r2 = vld1q_f32(r2); float32x4_t _r3 = vld1q_f32(r3); float32x4_t _k0 = vld1q_f32(k0); float32x4_t _k1 = vld1q_f32(k1); float32x4_t _k2 = vld1q_f32(k2); float32x4_t _k3 = vld1q_f32(k3); _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1); _output0_tm = vmlaq_f32(_output0_tm, _r2, _k2); _output0_tm = vmlaq_f32(_output0_tm, _r3, _k3); vst1q_f32(output0_tm, _output0_tm); output0_tm += 4; r0 += 4; r1 += 4; r2 += 4; r3 += 4; k0 += 4; k1 += 4; k2 += 4; k3 += 4; } #else asm volatile( "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "mov r4, %0 \n" "pld [%0, #256] \n" "vld1.f32 {d24-d27}, [%0 :128]!\n"//q12 q13 = output0_tm "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q12, q0, q2 \n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q13, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q12, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%0, #256] \n" "vld1.f32 {d28-d31}, [%0 :128]!\n"//q14 q15 = output0_tm "vmla.f32 q13, q9, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q14, q0, q2 \n" "vst1.f32 {d24-d27}, [r4 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q14, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q15, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q14, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q14, q8, q10 \n" "pld [%0, #256] \n" "vld1.f32 {d24-d27}, [%0 :128]!\n"//q12 q13 = output0_tm "vmla.f32 q15, q9, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q12, q0, q2 \n" "vst1.f32 {d28-d31}, [r4 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q13, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q12, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%0, #256] \n" "vld1.f32 {d28-d31}, [%0 :128]!\n"//q14 q15 = output0_tm "vmla.f32 q13, q9, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q14, q0, q2 \n" "vst1.f32 {d24-d27}, [r4 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q14, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q15, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q14, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q14, q8, q10 \n" "pld [%0, #256] \n" "vld1.f32 {d24-d27}, [%0 :128]!\n"//q12 q13 = output0_tm "vmla.f32 q15, q9, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q12, q0, q2 \n" "vst1.f32 {d28-d31}, [r4 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q13, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q12, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%0, #256] \n" "vld1.f32 {d28-d31}, [%0 :128]!\n"//q14 q15 = output0_tm "vmla.f32 q13, q9, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q14, q0, q2 \n" "vst1.f32 {d24-d27}, [r4 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q14, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q15, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q14, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q14, q8, q10 \n" "pld [%0, #256] \n" "vld1.f32 {d24-d27}, [%0 :128]!\n"//q12 q13 = output0_tm "vmla.f32 q15, q9, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q12, q0, q2 \n" "vst1.f32 {d28-d31}, [r4 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q13, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q12, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%0, #256] \n" "vld1.f32 {d28-d31}, [%0 :128]!\n"//q14 q15 = output0_tm "vmla.f32 q13, q9, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q14, q0, q2 \n" "vst1.f32 {d24-d27}, [r4 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q14, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q15, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q14, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q14, q8, q10 \n" "vmla.f32 q15, q9, q11 \n" "vst1.f32 {d28-d31}, [r4 :128]!\n" : "=r"(output0_tm), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2), // %3 "=r"(r3), // %4 "=r"(k0), // %5 "=r"(k1), // %6 "=r"(k2), // %7 "=r"(k3) // %8 : "0"(output0_tm), "1"(r0), "2"(r1), "3"(r2), "4"(r3), "5"(k0), "6"(k1), "7"(k2), "8"(k3) : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #endif // __aarch64__ k0 -= 64; k1 -= 64; k2 -= 64; k3 -= 64; #else for (int m=0; m<64; m++) { output0_tm[m] += r0[m] * k0[m]; output0_tm[m] += r1[m] * k1[m]; output0_tm[m] += r2[m] * k2[m]; output0_tm[m] += r3[m] * k3[m]; } r0 += 64; r1 += 64; r2 += 64; r3 += 64; output0_tm += 64; #endif // __ARM_NEON } } for (; q<inch; q++) { const float* r0 = bottom_blob_tm.channel(q); const float* k0 = kernel0_tm.row(q); float* output0_tm = out0_tm; // tile for (int i=0; i<h_tm/8 * w_tm/8; i++) { // TODO neon optimize for (int m=0; m<64; m++) { output0_tm[m] += r0[m] * k0[m]; } r0 += 64; output0_tm += 64; } } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; top_blob_bordered.create(outw, outh, outch); { // const float otm[6][8] = { // {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 32.0f, 32.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 16.0f,-16.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 8.0f, 8.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 4.0f, -4.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 16.0f, 16.0f, 2.0f, 2.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 32.0f, -32.0f, 1.0f, -1.0f, 1.0f} // }; // 0 = r0 + (r1 + r2) + (r3 + r4) + (r5 + r6) * 32 // 1 = (r1 - r2) + (r3 - r4) * 2 + (r5 - r6) * 16 // 2 = (r1 + r2) + (r3 + r4) * 4 + (r5 + r6) * 8 // 3 = (r1 - r2) + (r3 - r4) * 8 + (r5 - r6) * 4 // 4 = (r1 + r2) + (r3 + r4) * 16+ (r5 + r6) * 2 // 5 = r7 + (r1 - r2) + (r3 - r4) * 32+ (r5 - r6) int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; #pragma omp parallel for for (int p = 0; p<outch; p++) { const Mat out0_tm = top_blob_tm.channel(p); Mat out0 = top_blob_bordered.channel(p); const float bias0 = bias ? bias[p] : 0.f; float tmp[6][8]; // tile for (int i=0; i<outh/6; i++) { for (int j=0; j<outw/6; j++) { const float* output0_tm = out0_tm.row(i * w_tm/8 + j); float* output0 = out0.row(i * 6) + j * 6; // TODO neon optimize for (int m=0; m<8; m++) { float tmp024a = output0_tm[1] + output0_tm[2]; float tmp135a = output0_tm[1] - output0_tm[2]; float tmp024b = output0_tm[3] + output0_tm[4]; float tmp135b = output0_tm[3] - output0_tm[4]; float tmp024c = output0_tm[5] + output0_tm[6]; float tmp135c = output0_tm[5] - output0_tm[6]; tmp[0][m] = output0_tm[0] + tmp024a + tmp024b + tmp024c * 32; tmp[2][m] = tmp024a + tmp024b * 4 + tmp024c * 8; tmp[4][m] = tmp024a + tmp024b * 16 + tmp024c + tmp024c; tmp[1][m] = tmp135a + tmp135b + tmp135b + tmp135c * 16; tmp[3][m] = tmp135a + tmp135b * 8 + tmp135c * 4; tmp[5][m] = output0_tm[7] + tmp135a + tmp135b * 32 + tmp135c; output0_tm += 8; } for (int m=0; m<6; m++) { const float* tmp0 = tmp[m]; float tmp024a = tmp0[1] + tmp0[2]; float tmp135a = tmp0[1] - tmp0[2]; float tmp024b = tmp0[3] + tmp0[4]; float tmp135b = tmp0[3] - tmp0[4]; float tmp024c = tmp0[5] + tmp0[6]; float tmp135c = tmp0[5] - tmp0[6]; output0[0] = bias0 + tmp0[0] + tmp024a + tmp024b + tmp024c * 32; output0[2] = bias0 + tmp024a + tmp024b * 4 + tmp024c * 8; output0[4] = bias0 + tmp024a + tmp024b * 16 + tmp024c + tmp024c; output0[1] = bias0 + tmp135a + tmp135b + tmp135b + tmp135c * 16; output0[3] = bias0 + tmp135a + tmp135b * 8 + tmp135c * 4; output0[5] = bias0 + tmp0[7] + tmp135a + tmp135b * 32 + tmp135c; 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); } static void conv3x3s2_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2*outw + w; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for for (int p=0; p<outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); const float* kernel0 = kernel + p*inch*9; for (int q=0; q<inch; q++) { float* outptr = out; float* outptr2 = outptr + outw; const float* img0 = bottom_blob.channel(q); const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w*2; const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; #if __ARM_NEON float32x4_t _k0123 = vld1q_f32(k0); float32x4_t _k3456 = vld1q_f32(k1); float32x4_t _k6789 = vld1q_f32(k2); #endif // __ARM_NEON int i = 0; for (; i < outh; i++) { #if __ARM_NEON int nn = outw >> 2; int remain = outw & 3; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ for (; nn>0; nn--) { float32x4_t _outp = vld1q_f32(outptr); float32x4x2_t _r0 = vld2q_f32(r0); float32x4x2_t _r0n = vld2q_f32(r0+8); float32x4_t _r00 = _r0.val[0];// 0 2 4 6 float32x4_t _r01 = _r0.val[1];// 1 3 5 7 float32x4_t _r02 = vextq_f32(_r00, _r0n.val[0], 1);// 2 4 6 8 _outp = vfmaq_laneq_f32(_outp, _r00, _k0123, 0); _outp = vfmaq_laneq_f32(_outp, _r01, _k0123, 1); _outp = vfmaq_laneq_f32(_outp, _r02, _k0123, 2); float32x4x2_t _r1 = vld2q_f32(r1); float32x4x2_t _r1n = vld2q_f32(r1+8); float32x4_t _r10 = _r1.val[0]; float32x4_t _r11 = _r1.val[1]; float32x4_t _r12 = vextq_f32(_r10, _r1n.val[0], 1); _outp = vfmaq_laneq_f32(_outp, _r10, _k3456, 0); _outp = vfmaq_laneq_f32(_outp, _r11, _k3456, 1); _outp = vfmaq_laneq_f32(_outp, _r12, _k3456, 2); float32x4x2_t _r2 = vld2q_f32(r2); float32x4x2_t _r2n = vld2q_f32(r2+8); float32x4_t _r20 = _r2.val[0]; float32x4_t _r21 = _r2.val[1]; float32x4_t _r22 = vextq_f32(_r20, _r2n.val[0], 1); _outp = vfmaq_laneq_f32(_outp, _r20, _k6789, 0); _outp = vfmaq_laneq_f32(_outp, _r21, _k6789, 1); _outp = vfmaq_laneq_f32(_outp, _r22, _k6789, 2); vst1q_f32(outptr, _outp); r0 += 8; r1 += 8; r2 += 8; outptr += 4; } #else if (nn > 0) { asm volatile( "pld [%2, #256] \n" "vld2.f32 {d4-d7}, [%2]! \n" "veor q10, q10 \n" "veor q11, q11 \n" "0: \n" "pld [%1, #128] \n" "vld1.f32 {d0-d1}, [%1] \n" "vmla.f32 q0, q2, %e10[0] \n" "vmla.f32 q10, q3, %e10[1] \n" "pld [%2, #256] \n" "vld2.f32 {d16-d19}, [%2] \n" "vext.32 q1, q2, q8, #1 \n" "vmla.f32 q11, q1, %f10[0] \n" "pld [%3, #256] \n" "vld2.f32 {d4-d7}, [%3]! \n" "vmla.f32 q0, q2, %e11[0] \n" "vmla.f32 q10, q3, %e11[1] \n" "pld [%3, #256] \n" "vld2.f32 {d16-d19}, [%3] \n" "vext.32 q1, q2, q8, #1 \n" "vmla.f32 q11, q1, %f11[0] \n" "pld [%4, #256] \n" "vld2.f32 {d4-d7}, [%4]! \n" "vmla.f32 q0, q2, %e12[0] \n" "vmla.f32 q10, q3, %e12[1] \n" "pld [%4, #256] \n" "vld2.f32 {d16-d19}, [%4] \n" "vext.32 q1, q2, q8, #1 \n" "vmla.f32 q11, q1, %f12[0] \n" "pld [%2, #256] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vadd.f32 q0, q0, q10 \n" "veor q10, q10 \n" "vadd.f32 q0, q0, q11 \n" "veor q11, q11 \n" "subs %0, #1 \n" "vst1.f32 {d0-d1}, [%1]! \n" "bne 0b \n" "sub %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), "=r"(r2) : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "w"(_k0123), // %10 "w"(_k3456), // %11 "w"(_k6789) // %12 : "cc", "memory", "q0", "q1", "q2", "q3", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { #if __ARM_NEON float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _sum = vmulq_f32(_r00, _k0123); _sum = vmlaq_f32(_sum, _r10, _k3456); _sum = vmlaq_f32(_sum, _r20, _k6789); _sum = vsetq_lane_f32(*outptr, _sum, 3); #if __aarch64__ *outptr = vaddvq_f32(_sum); #else float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum)); _ss = vpadd_f32(_ss, _ss); *outptr = vget_lane_f32(_ss, 0); #endif // __aarch64__ #else float sum = 0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; *outptr += sum; #endif // __ARM_NEON r0 += 2; r1 += 2; r2 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } kernel0 += 9; } } }
GB_binop__second_uint32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__second_uint32) // A.*B function (eWiseMult): GB (_AemultB_08__second_uint32) // A.*B function (eWiseMult): GB (_AemultB_02__second_uint32) // A.*B function (eWiseMult): GB (_AemultB_04__second_uint32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__second_uint32) // A*D function (colscale): GB (_AxD__second_uint32) // D*A function (rowscale): GB (_DxB__second_uint32) // C+=B function (dense accum): GB (_Cdense_accumB__second_uint32) // C+=b function (dense accum): GB (_Cdense_accumb__second_uint32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__second_uint32) // C=scalar+B GB ((none)) // C=scalar+B' GB ((none)) // C=A+scalar GB ((none)) // C=A'+scalar GB ((none)) // C type: uint32_t // A type: uint32_t // A pattern? 1 // B type: uint32_t // B pattern? 0 // BinaryOp: cij = bij #define GB_ATYPE \ uint32_t #define GB_BTYPE \ uint32_t #define GB_CTYPE \ uint32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ ; // true if values of A are not used #define GB_A_IS_PATTERN \ 1 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint32_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = y ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 1 // 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_SECOND || GxB_NO_UINT32 || GxB_NO_SECOND_UINT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__second_uint32) ( 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__second_uint32) ( 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__second_uint32) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint32_t uint32_t bwork = (*((uint32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__second_uint32) ( 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 uint32_t *restrict Cx = (uint32_t *) 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__second_uint32) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *restrict Cx = (uint32_t *) 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__second_uint32) ( 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) ; uint32_t alpha_scalar ; uint32_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint32_t *) alpha_scalar_in)) ; beta_scalar = (*((uint32_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__second_uint32) ( 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__second_uint32) ( 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__second_uint32) ( 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__second_uint32) ( 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 //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( 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 uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t x = (*((uint32_t *) x_input)) ; uint32_t *Bx = (uint32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint32_t bij = GBX (Bx, p, false) ; Cx [p] = bij ; } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( 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 ; uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t *Ax = (uint32_t *) Ax_input ; uint32_t y = (*((uint32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; ; ; Cx [p] = y ; } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ #if 0 // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = aij ; \ } GrB_Info GB ((none)) ( 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 \ uint32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t x = (*((const uint32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint32_t } #endif //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ #if 0 // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ ; ; \ Cx [pC] = y ; \ } GrB_Info GB ((none)) ( 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 uint32_t y = (*((const uint32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif #endif
place_report_mpi_omp.c
#define _GNU_SOURCE #include <stdio.h> #include <unistd.h> #include <string.h> #include <sched.h> #include <mpi.h> #include <omp.h> /* Heavily modified from xthi.c code */ /* xthi.c code is used in examples for hybrid MPI/OpenMP affinity from a few HPC sites */ /* xthi.c originally borrowed some of this code from util-linux-2.13-pre7/schedutils/taskset.c */ static char *cpuset_to_cstr(cpu_set_t *mask, char *str) { char *ptr = str; int i, j, entry_made = 0; for (i = 0; i < CPU_SETSIZE; i++) { if (CPU_ISSET(i, mask)) { int run = 0; entry_made = 1; for (j = i + 1; j < CPU_SETSIZE; j++) { if (CPU_ISSET(j, mask)) run++; else break; } if (!run) sprintf(ptr, "%d,", i); else if (run == 1) { sprintf(ptr, "%d,%d,", i, i + 1); i++; } else { sprintf(ptr, "%d-%d,", i, i + run); i += run; } while (*ptr != 0) ptr++; } } ptr -= entry_made; *ptr = 0; return(str); } void place_report_mpi_omp(void) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); int socket_global[144]; char clbuf_global[144][7 * CPU_SETSIZE]; #pragma omp parallel { if (omp_get_thread_num() == 0 && rank == 0){ printf("Running with %d thread(s)\n",omp_get_num_threads()); int bind_policy = omp_get_proc_bind(); switch (bind_policy) { case omp_proc_bind_false: printf(" proc_bind is false\n"); break; case omp_proc_bind_true: printf(" proc_bind is true\n"); break; case omp_proc_bind_master: printf(" proc_bind is master\n"); break; case omp_proc_bind_close: printf(" proc_bind is close\n"); break; case omp_proc_bind_spread: printf(" proc_bind is spread\n"); } printf(" proc_num_places is %d\n",omp_get_num_places()); } int thread = omp_get_thread_num(); cpu_set_t coremask; char clbuf[7 * CPU_SETSIZE], hnbuf[64]; memset(clbuf, 0, sizeof(clbuf)); memset(hnbuf, 0, sizeof(hnbuf)); gethostname(hnbuf, sizeof(hnbuf)); sched_getaffinity(0, sizeof(coremask), &coremask); cpuset_to_cstr(&coremask, clbuf); strcpy(clbuf_global[thread],clbuf); socket_global[omp_get_thread_num()] = omp_get_place_num(); #pragma omp barrier #pragma omp master for (int i=0; i<omp_get_num_threads(); i++){ printf("Hello from rank %02d, thread %02d, on %s. (core affinity = %2s) OpenMP socket is %2d\n", rank, i, hnbuf, clbuf_global[i], socket_global[i]); } } }
CPUMatrixImpl.h
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.md file in the project root for full license information. // // CPUMatrix.h : template implementation of all matrix functions on the CPU side // #pragma once #include "Basics.h" #include "File.h" #include "CPUMatrix.h" #include "TensorOps.h" #include <assert.h> #include <stdexcept> #include <omp.h> #include <math.h> #include <random> #include <chrono> #include <exception> #include <thread> #include <iostream> #include <algorithm> #pragma warning(push) #pragma warning(disable:4244) // 'conversion' conversion from 'type1' to 'type2', possible loss of data #include <boost/random/normal_distribution.hpp> #pragma warning(pop) #include <boost/random/uniform_real_distribution.hpp> #ifdef _WIN32 #define NOMINMAX #include "Windows.h" #else #include <cfloat> #endif #ifdef LEAKDETECT #include <vld.h> #endif #pragma warning(disable : 4100) // unreferenced formal parameter; "struct TensorOpReduction<ElemType, OPFN, typename ReductionOp, N, -1>" trigger this #pragma warning(disable : 4127) // conditional expression is constant; "if (sizeof(ElemType)==sizeof(float))" triggers this #pragma warning(disable : 4244) // unreachable code; triggered for unknown reasons #pragma warning(disable : 4702) // conversion from 'double' to 'float' #ifdef USE_MKL // requires MKL 10.0 and above #include <mkl.h> #else #ifdef _MSC_VER // Visual Studio doesn't define standard complex types properly #define HAVE_LAPACK_CONFIG_H #define LAPACK_COMPLEX_STRUCTURE #endif #include <cblas.h> #include <lapacke.h> #endif #define SWAP(a, b) \ { \ (a) ^= (b); \ (b) ^= (a); \ (a) ^= (b); \ } #define IDX2C(i, j, ld) (((j) * (ld)) + (i)) // 0 based indexing namespace Microsoft { namespace MSR { namespace CNTK { #pragma region Helpful Enum Definitions enum class MatrixOrder { RowMajor = 101, // row-major arrays ColMajor = 102 // column-major arrays }; enum class MatrixTranspose : char { NoTrans = 'N', // trans='N' Trans = 'T', // trans='T' ConjTrans = 'C' // trans='C' }; enum class SymMatrixType : char { Up = 'U', // symmetric matrix is stored in the upper part Low = 'L', // symmetric matrix is stored in thelower part Full = 'F', // full populated NotSymmetric = 'N' // not a symmetric matrix }; enum class MatrixOpSide : char { Left = 'L', // left multiply Right = 'R', // right multiply }; #pragma endregion Helpful Enum Definitions #pragma region Constructors and Destructor template <class ElemType> CPUMatrix<ElemType>::CPUMatrix() { ZeroInit(); } // helper to allocate an array of ElemType // Use this instead of new[] to get NaN initialization for debugging. template <class ElemType> static ElemType* NewArray(size_t n) { // We need to allocate possibly one more element for the following reason. // At some point we might want to fill a buffer with the result of a random // number generator. The RNG is oblivious to whether the buffer is on the // CPU or GPU but it needs to keep an accurate tally of how many numbers it // has generated. The trouble stems from the fact that generating an odd // number gaussians on the GPU is not supported so we must always // generate an even number. So since we wouldn't know how to update the tally // we are making this allocate one more element in the worst case. ElemType* p = new ElemType[AsMultipleOf(n, 2)](); #if 0 // _DEBUG ElemType nan = Matrix<ElemType>::MakeNan(__LINE__); for (size_t i = 0; i < n; i++) p[i] = nan; #endif return p; } template <class ElemType> CPUMatrix<ElemType>::CPUMatrix(const size_t numRows, const size_t numCols) { ZeroInit(); m_numRows = numRows; m_numCols = numCols; SetSizeAllocated(GetNumElements()); if (GetNumElements() != 0) { SetBuffer(NewArray<ElemType>(GetNumElements()), GetNumElements() * sizeof(ElemType)); } } template <class ElemType> CPUMatrix<ElemType>::CPUMatrix(const size_t numRows, const size_t numCols, ElemType* pArray, const size_t matrixFlags) { ZeroInit(); SetValue(numRows, numCols, pArray, matrixFlags); } //copy constructor, deep copy template <class ElemType> CPUMatrix<ElemType>::CPUMatrix(const CPUMatrix<ElemType>& deepCopyFrom) { ZeroInit(); SetValue(deepCopyFrom); } //assignment operator, deep copy template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::operator=(const CPUMatrix<ElemType>& deepCopyFrom) { SetValue(deepCopyFrom); return *this; } //move constructor, shallow copy template <class ElemType> CPUMatrix<ElemType>::CPUMatrix(CPUMatrix<ElemType>&& moveFrom) : Base(/* shallow */ true) { ShallowCopyFrom(moveFrom); moveFrom.ZeroValues(); } // Shortcut of default constructor + shallow copy, to avoid one initialization template <class ElemType> CPUMatrix<ElemType>::CPUMatrix(const CPUMatrix<ElemType>& shallowCopyFrom, bool shallow) : Base(shallow) { ShallowCopyFrom(shallowCopyFrom); } //move assignment operator, shallow copy template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::operator=(CPUMatrix<ElemType>&& moveFrom) { if (this != &moveFrom) { ShallowCopyFrom(moveFrom); // release the pointer from the source object so that the destructor won't release it twice moveFrom.ZeroValues(); } return *this; } template <class ElemType> void CPUMatrix<ElemType>::Clear() { ZeroInit(); } #pragma endregion Constructors and Destructor #pragma region Basic Operators template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::ColumnSlice(size_t startColumn, size_t numCols) const { if (startColumn + numCols > m_numCols) InvalidArgument("The slice (%d+%d) is out of range of the source matrix (%d).", (int) startColumn, (int) numCols, (int) m_numCols); CPUMatrix<ElemType> slice(*this, /* shallow= */ true); slice.m_numCols = numCols; slice.m_sliceViewOffset = m_sliceViewOffset + startColumn * m_numRows; return slice; } // set this(:, 0:numCols-1) = fromMatrix(:, startColumn : startColumn+numCols-1) // TODO: why not say *this = ColumnSlice()? template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignColumnSlice(const CPUMatrix<ElemType>& fromMatrix, size_t startColumn, size_t numCols) { if (startColumn + numCols > fromMatrix.m_numCols) InvalidArgument("The slice (%d+%d) is out of range of the source matrix (%d).", (int) startColumn, (int) numCols, (int) fromMatrix.m_numCols); Clear(); ShallowCopyFrom(fromMatrix); m_numCols = numCols; m_sliceViewOffset = fromMatrix.m_sliceViewOffset + startColumn * m_numRows; return *this; } // set this(: , startColumn:startColumn+numCols-1)= fromMatrix; template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::SetColumnSlice(const CPUMatrix<ElemType>& fromMatrix, size_t startColumn, size_t numCols) { if (startColumn + numCols > m_numCols) LogicError("The slice is out of range of the destination matrix."); if (numCols > fromMatrix.GetNumCols()) InvalidArgument("The slice (%d) is out of range of the source matrix (%d).", (int) numCols, (int) fromMatrix.GetNumCols()); if (m_numRows != fromMatrix.m_numRows) LogicError("The number of rows in source and destination matrices do not match"); memcpy(Data() + startColumn * m_numRows, fromMatrix.Data(), numCols * m_numRows * sizeof(ElemType)); return *this; } template <class ElemType> void CPUMatrix<ElemType>::CopyColumnsStrided(const CPUMatrix<ElemType>& fromMatrix, size_t numCols, size_t srcNumColsStride, size_t destNumColsStride) { if ((((numCols - 1) * srcNumColsStride) + 1) > fromMatrix.m_numCols) LogicError("The numCols to copy and srcNumColsStride specified is out of range of the source matrix."); if ((((numCols - 1) * destNumColsStride) + 1) > m_numCols) LogicError("The numCols to copy and srcNumColsStride specified is out of range of the destination matrix."); if (m_numRows != fromMatrix.m_numRows) LogicError("The number of rows in source and destination matrices do not match"); long n = (long) numCols, m = (long) m_numRows; auto& us = *this; #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (size_t i = 0; i < (m & ~3); i += 4) { us(i, j * destNumColsStride) = fromMatrix(i, j * srcNumColsStride); us(i + 1, j * destNumColsStride) = fromMatrix(i + 1, j * srcNumColsStride); us(i + 2, j * destNumColsStride) = fromMatrix(i + 2, j * srcNumColsStride); us(i + 3, j * destNumColsStride) = fromMatrix(i + 3, j * srcNumColsStride); } // handle remaining for (size_t i = m & ~3; i < m; i++) { us(i, j * destNumColsStride) = fromMatrix(i, j * srcNumColsStride); } } } //for each column of a, we add all rows of a to this starting from startIndex template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignToRowSliceValuesOf(const CPUMatrix<ElemType>& a, const size_t startIndex, const size_t numRows) { if (a.GetNumRows() != numRows) LogicError("AddToRowSliceValuesOf: a.GetNumRows() != numRows."); if (startIndex + numRows > GetNumRows()) LogicError("AddToRowSliceValuesOf: startIndex + numRows exceeds GetNumRows()."); if (a.GetNumCols() != GetNumCols()) LogicError("AddToRowSliceValuesOf: columns does not match."); long n = (long) a.GetNumCols(), m = (long) numRows; auto& us = *this; #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (size_t i = 0, startRow = startIndex; i < (m & ~3); i += 4, startRow += 4) { us(startRow, j) = a(i, j); us(startRow + 1, j) = a(i + 1, j); us(startRow + 2, j) = a(i + 2, j); us(startRow + 3, j) = a(i + 3, j); } // handle remaining stuffs for (size_t i = m & ~3, startRow = startIndex + (m & ~3); i < m; i++, startRow++) { us(startRow, j) = a(i, j); } } return *this; } //for each column of a, we assign numRows starting from startIndex to this template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignRowSliceValuesOf(const CPUMatrix<ElemType>& a, const size_t startIndex, const size_t numRows) { if (startIndex + numRows > a.GetNumRows()) LogicError("AssignRowSliceValuesOf: startIndex + numRows exceeds a.GetNumRows()."); RequireSize(numRows, a.GetNumCols()); long n = (long) a.GetNumCols(); // note: OpenMP requires loop indices to be long, not size_t long k = (long) a.GetNumRows(); #pragma omp parallel for for (long j = 0; j < n; j++) { // memory copy might be faster? memcpy(Data() + j * numRows, a.Data() + j * k + startIndex, sizeof(ElemType) * numRows); // //four-way unrolling // for (long i=0, startRow = startIndex; i<(m & ~3); i+=4, startRow+=4) // { // us(i,j) = a(startRow,j); // us(i+1,j) = a(startRow+1,j); // us(i+2,j) = a(startRow+2,j); // us(i+3,j) = a(startRow+3,j); // } // //handle remaining stuffs // for (long i=m & ~3, startRow = startIndex+(m & ~3); i<m; i++, startRow++) // { // us(i,j) = a(startRow,j); // } } return *this; } //for the row slice of this starting from startIndex we add a to it. template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AddToRowSliceValuesOf(const CPUMatrix<ElemType>& a, const size_t startIndex, const size_t numRows) { if (a.IsEmpty()) LogicError("AddToRowSliceValuesOf: input matrix a is empty."); if (a.GetNumRows() != numRows) LogicError("AddToRowSliceValuesOf: a.GetNumRows() != numRows."); if (startIndex + numRows > GetNumRows()) LogicError("AddToRowSliceValuesOf: startIndex + numRows exceeds GetNumRows()."); if (a.GetNumCols() != GetNumCols()) LogicError("AddToRowSliceValuesOf: columns does not match."); long n = (long) a.GetNumCols(), m = (long) numRows; auto& us = *this; #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0, startRow = (long) startIndex; i < (m & ~3); i += 4, startRow += 4) { us(startRow, j) += a(i, j); us(startRow + 1, j) += a(i + 1, j); us(startRow + 2, j) += a(i + 2, j); us(startRow + 3, j) += a(i + 3, j); } // handle remaining stuffs for (long i = m & ~3, startRow = (long) startIndex + (m & ~3); i < m; i++, startRow++) { us(startRow, j) += a(i, j); } } return *this; } //for each column of this, we add row slice of a starting from startIndex template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AddWithRowSliceValuesOf(const CPUMatrix<ElemType>& a, const size_t startIndex, const size_t numRows) { if (a.IsEmpty()) LogicError("AddWithRowSliceValuesOf: input matrix a is empty."); if (GetNumRows() != numRows) LogicError("AddWithRowSliceValuesOf: GetNumRows() != numRows."); if (startIndex + numRows > a.GetNumRows()) LogicError("AddWithRowSliceValuesOf: startIndex + numRows exceeds a.GetNumRows()."); if (a.GetNumCols() != GetNumCols()) LogicError("AddWithRowSliceValuesOf: columns does not match."); long n = (long) a.GetNumCols(), m = (long) numRows; auto& us = *this; #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0, startRow = (long) startIndex; i < (m & ~3); i += 4, startRow += 4) { us(i, j) += a(startRow, j); us(i + 1, j) += a(startRow + 1, j); us(i + 2, j) += a(startRow + 2, j); us(i + 3, j) += a(startRow + 3, j); } // handle remaining stuffs for (long i = m & ~3, startRow = (long) startIndex + (m & ~3); i < m; i++, startRow++) { us(i, j) += a(startRow, j); } } return *this; } template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::Diagonal() const { if (m_numRows != m_numCols) LogicError("Diagonal can be called only for square matrix. (rows=%d, cols=%d)", (int) m_numRows, (int) m_numCols); CPUMatrix<ElemType> diag(1, m_numCols); auto& us = *this; #pragma omp parallel for for (long i = 0; i < m_numRows; i++) { diag(0, (size_t) i) = us(i, i); } return diag; } template <class ElemType> void CPUMatrix<ElemType>::MinusOneAt(CPUMatrix<ElemType>& c, const size_t position) { if (position < c.GetNumElements()) c.Data()[position] -= 1.0; else RuntimeError("MinusOneAt: position is out of CPU matrix size"); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignRepeatOf(const CPUMatrix<ElemType>& a, const size_t numRowRepeats, const size_t numColRepeats) { if (this == &a) LogicError("AssignRepeatOf: a is the same as [this]. Does not support inplace repeat."); if (a.IsEmpty()) LogicError("AssignRepeatOf: Matrix a is empty."); RequireSize(a.GetNumRows() * numRowRepeats, a.GetNumCols() * numColRepeats); long n = (long) a.GetNumCols(), m = (long) a.GetNumRows(); auto& us = *this; #pragma omp parallel for for (long q = 0; q < numColRepeats; q++) { for (long p = 0; p < numRowRepeats; p++) { long colOffset = q * n; for (long j = 0; j < n; j++, colOffset++) { long rowOffset = p * m; // four-way unrolling for (long i = 0; i < (m & ~3); i += 4, rowOffset += 4) { us(rowOffset, colOffset) = a(i, j); us(rowOffset + 1, colOffset) = a(i + 1, j); us(rowOffset + 2, colOffset) = a(i + 2, j); us(rowOffset + 3, colOffset) = a(i + 3, j); } // handle remaining stuffs for (long i = m & ~3; i < m; i++, rowOffset++) { us(rowOffset, colOffset) = a(i, j); } } } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AddToRowRepeatValuesOf(const CPUMatrix<ElemType>& a, const size_t numRepeats) { if (a.IsEmpty()) LogicError("AddToRowRepeatValuesOf: input matrix a is empty."); if (a.GetNumRows() != GetNumRows() * numRepeats) LogicError("AddToRowRepeatValuesOf: a.GetNumRows() != GetNumRows() * numRepeats."); long n = (long) a.GetNumCols(), m = (long) GetNumRows(); auto& us = *this; #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { for (long k = 0; k < numRepeats; k++) { us(i, j) += a(k * m + i, j); us(i + 1, j) += a(k * m + i + 1, j); us(i + 2, j) += a(k * m + i + 2, j); us(i + 3, j) += a(k * m + i + 3, j); } } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { for (long k = 0; k < numRepeats; k++) { us(i, j) += a(k * m + i, j); } } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignPositiveAndShiftedNegSample(const CPUMatrix<ElemType>& a, const size_t posNumber, const size_t negNumber, const size_t shiftNumber) { a; posNumber; negNumber; shiftNumber; NOT_IMPLEMENTED; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AddFoldedPositiveAndShiftedNegSample(const CPUMatrix<ElemType>& a, const size_t posNumber, const size_t negNumber, const size_t shiftNumber) { a; posNumber; negNumber; shiftNumber; NOT_IMPLEMENTED; } template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::Transpose() { if (IsEmpty()) LogicError("Transpose: Matrix is empty."); CPUMatrix<ElemType> c; c.AssignTransposeOf(*this); return c; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignTransposeOf(const CPUMatrix<ElemType>& a) { if (this == &a) LogicError("AssignTransposeOf: a is the same as [this]. Does not support inplace transpose."); if (a.IsEmpty()) LogicError("AssignTransposeOf: Matrix a is empty."); RequireSize(a.GetNumCols(), a.GetNumRows()); long n = (long) a.GetNumCols(), m = (long) a.GetNumRows(); auto& us = *this; #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(j, i) = a(i, j); us(j, i + 1) = a(i + 1, j); us(j, i + 2) = a(i + 2, j); us(j, i + 3) = a(i + 3, j); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(j, i) = a(i, j); } } return *this; } // dst[i] = src[i] * alpha + dst[i] * beta // scale a column vector and add it to another // The usual special case: If beta = 0, then dst[] is not read, and may be uninitialized or NaN. template <class ElemType> static void ScaleAndAddColumn(ElemType beta, ElemType* dst, const ElemType* src, size_t numRows, ElemType alpha) { if (alpha != 1) // rare case: just do the full thing for (size_t i = 0; i < numRows; i++) dst[i] = beta * dst[i] + alpha * src[i]; else if (beta == 1) // used in backprop for (size_t i = 0; i < numRows; i++) dst[i] += src[i]; else if (beta == 0) // plain assignment memcpy(dst, src, sizeof(ElemType) * numRows); else // alpha=1, arbitrary beta: also rare case for (size_t i = 0; i < numRows; i++) dst[i] = beta * dst[i] + src[i]; } // *this[:,j] = a[:,idx[j]] * alpha + *this[:,j] * beta template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::DoGatherColumnsOf(ElemType beta, const CPUMatrix<ElemType>& idx, const CPUMatrix<ElemType>& a, ElemType alpha) { if (idx.GetNumRows() != 1) // index is 1-dimensional only InvalidArgument("DoGatherColumnsOf: Map must be a row vector."); if (beta) VerifySize(a.GetNumRows(), idx.GetNumCols()); else Resize(a.GetNumRows(), idx.GetNumCols()); auto& us = *this; // race-condition consideration: Since this loops over independent output columns, this has no race condition. Cf. DoScatterColumnsOf(). #pragma omp parallel for // TODO: Depending in circumstance, it may be more efficient to parallelize over rows. foreach_column(jOut, us) { auto jInF = idx(0, jOut); // this is the column we need to get if (std::isnan(jInF) || jInF < 0) // negative index means gap continue; size_t jIn = (size_t)jInF; if (jIn >= a.GetNumCols()) InvalidArgument("DoGatherColumnsOf: Map out of bounds. %ld >= %ld", (long int)jIn, (long int)a.GetNumCols()); ScaleAndAddColumn(beta, &us(0,jOut), &a(0,jIn), us.GetNumRows(), alpha); } return *this; } // *this[:,idx[j]] = a[:,j] * alpha + *this[:,idx[j]] * beta template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::DoScatterColumnsOf(ElemType beta, const CPUMatrix<ElemType>& idx, const CPUMatrix<ElemType>& a, ElemType alpha) { if (idx.GetNumRows() != 1) // index is 1-dimensional only InvalidArgument("DoScatterColumnsOf: Map must be a row vector."); if (idx.GetNumCols() != a.GetNumCols()) InvalidArgument("DoScatterColumnsOf: Map must have width of input vector."); if (a.GetNumRows() != GetNumRows()) InvalidArgument("DoScatterColumnsOf: Output must have same height as input vector."); auto& us = *this; // pre-scale with beta upfront // Scatter may add more than one source column to the same target, so we must pre-scale with beta, and then just keep adding. Scale(beta, us); // if beta is 0, then this will be a memset() ScatterValues(idx.Data(), a.Data(), us.Data(), alpha, idx.GetNumCols(), a.GetNumRows(), GetNumCols(), idx.GetNumRows()); return *this; } template <class ElemType> void CPUMatrix<ElemType>::SetValue(const ElemType v) { if (IsEmpty()) LogicError("SetValue: Matrix is empty."); bool isFinite = std::numeric_limits<ElemType>::is_integer || std::isfinite((double) v); if (isFinite && v == 0) { memset(Data(), 0, sizeof(ElemType) * GetNumElements()); } else { ElemType* bufPtr = Data(); long m = (long) GetNumElements(); // 2-way thread parallelism is sufficient for the memory bound // operation of just setting the values of an array. const unsigned SETVALUE_NUM_THREADS = 2; UNUSED(SETVALUE_NUM_THREADS); // in case OMP is turned off. #pragma omp parallel for num_threads(SETVALUE_NUM_THREADS) // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { bufPtr[i] = v; bufPtr[i + 1] = v; bufPtr[i + 2] = v; bufPtr[i + 3] = v; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { bufPtr[i] = v; } } } template <class ElemType> void CPUMatrix<ElemType>::MaskColumnsValue(const CPUMatrix<char>& columnsMask, ElemType val, size_t numColsPerMaskEntry) { if (GetNumCols() != (columnsMask.GetNumCols() * numColsPerMaskEntry)) RuntimeError("MaskColumnsValue: Matrix number of columns must equal 'column mask number of columns * numColsPerMaskEntry'."); auto& us = *this; long n = (long)columnsMask.GetNumCols(), m = (long) GetNumRows(); #pragma omp parallel for for (long j = 0; j < n; j++) { if (columnsMask(0, j) == 1) continue; for (long k = 0; k < numColsPerMaskEntry; ++k) { // four-way unrolling for (size_t i = 0; i < (m & ~3); i += 4) { us(i, (j * numColsPerMaskEntry) + k) = val; us(i + 1, (j * numColsPerMaskEntry) + k) = val; us(i + 2, (j * numColsPerMaskEntry) + k) = val; us(i + 3, (j * numColsPerMaskEntry) + k) = val; } // handle remaining for (size_t i = m & ~3; i < m; i++) { us(i, (j * numColsPerMaskEntry) + k) = val; } } } } template <class ElemType> void CPUMatrix<ElemType>::SetColumn(const ElemType* colPointer, size_t j) { if (IsEmpty()) LogicError("SetColumn: Matrix is empty."); if (colPointer == NULL) return; auto& us = *this; long m = (long) GetNumRows(); #pragma omp parallel for // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) = colPointer[i]; us(i + 1, j) = colPointer[i + 1]; us(i + 2, j) = colPointer[i + 2]; us(i + 3, j) = colPointer[i + 3]; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) = colPointer[i]; } } template <class ElemType> void CPUMatrix<ElemType>::SetColumn(const ElemType val, size_t j) { if (IsEmpty()) LogicError("SetColumn: Matrix is empty."); auto& us = *this; long m = (long) GetNumRows(); #pragma omp parallel for // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) = val; us(i + 1, j) = val; us(i + 2, j) = val; us(i + 3, j) = val; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) = val; } } template <class ElemType> void CPUMatrix<ElemType>::SetColumn(const CPUMatrix<ElemType>& valMat, size_t j) { if (IsEmpty()) LogicError("SetColumn: Matrix is empty."); if (valMat.GetNumRows() != GetNumRows() || valMat.GetNumCols() != 1) LogicError("The valMat matrix has incorrect number of rows or columns."); auto& us = *this; long m = (long) GetNumRows(); #pragma omp parallel for // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) = valMat(i, 0); us(i + 1, j) = valMat(i + 1, 0); us(i + 2, j) = valMat(i + 2, 0); us(i + 3, j) = valMat(i + 3, 0); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) = valMat(i, 0); } } template <class ElemType> void CPUMatrix<ElemType>::SetValue(const CPUMatrix<ElemType>& deepCopyFrom) { if (this == &deepCopyFrom) return; SetValue(deepCopyFrom.GetNumRows(), deepCopyFrom.GetNumCols(), deepCopyFrom.Data(), 0); } #if 0 template <class ElemType> void CPUMatrix<ElemType>::SetValue(const GPUMatrix<ElemType>& /*deepCopyFrom*/) { NOT_IMPLEMENTED; } template <class ElemType> void CPUMatrix<ElemType>::SetValue(const CPUSparseMatrix<ElemType>& deepCopyFrom) { deepCopyFrom.AssignColumnSliceToDense(*this, 0, deepCopyFrom.GetNumCols()); } template <class ElemType> void CPUMatrix<ElemType>::SetValue(const GPUSparseMatrix<ElemType>& /*deepCopyFrom*/) { NOT_IMPLEMENTED; } #endif template <class ElemType> void CPUMatrix<ElemType>::SetValue(const size_t numRows, const size_t numCols, ElemType* pArray, const size_t matrixFlags) { if (pArray == nullptr && numRows * numCols > 0) InvalidArgument("Invalid pArray. pArray == nullptr, but matrix is of size %d * %d = %d.", (int)numRows, (int)numCols, (int)(numRows * numCols)); SetFormat(matrixFormatDense); SetComputeDeviceId(CPUDEVICE); // if it's externally managed, then populate the structure if (matrixFlags & matrixFlagDontOwnBuffer) { // free previous array allocation if any before overwriting delete[] Buffer(); m_numRows = numRows; m_numCols = numCols; SetBuffer(pArray, GetNumElements() * sizeof(ElemType), true); SetSizeAllocated(GetNumElements()); } else { RequireSize(numRows, numCols); if (!IsEmpty()) { if (!(matrixFlags & matrixFormatRowMajor)) // compatible to internal structure memcpy(Data(), pArray, GetNumElements() * sizeof(ElemType)); else // need to transpose { ElemType* bufPtr = Data(); auto& us = *this; if (sizeof(ElemType) == sizeof(double)) { #pragma omp parallel for foreach_column (j, us) { cblas_dcopy((int) numRows, reinterpret_cast<double*>(pArray + j), (int) numCols, reinterpret_cast<double*>(bufPtr + LocateColumn(j)), 1); } } else { #pragma omp parallel for foreach_column (j, us) { { #pragma warning(suppress : 4244) cblas_scopy((int) numRows, reinterpret_cast<float*>(pArray + j), (int) numCols, reinterpret_cast<float*>(bufPtr + LocateColumn(j)), 1); } } } } } } } template <class ElemType> void CPUMatrix<ElemType>::SetDiagonalValue(const ElemType v) { if (GetNumRows() != GetNumCols()) LogicError("SetDiagonalValue: NumRows and NumCols do not agree."); auto& us = *this; long m = (long) GetNumRows(); #pragma omp parallel for // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, i) = v; us(i + 1, i + 1) = v; us(i + 2, i + 2) = v; us(i + 3, i + 3) = v; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, i) = v; } } template <class ElemType> void CPUMatrix<ElemType>::SetDiagonalValue(const CPUMatrix<ElemType>& vector) { if (IsEmpty() || vector.IsEmpty()) LogicError("SetDiagonalValue: Matrix is empty."); if (GetNumRows() != GetNumCols()) LogicError("SetDiagonalValue: NumRows and NumCols do not agree."); if (vector.GetNumRows() != 1 && vector.GetNumCols() != 1) LogicError("SetDiagonalValue: input vector must be a vector."); if (vector.GetNumElements() == 1) // reduce to simple form SetDiagonalValue(vector(0, 0)); else if (vector.GetNumRows() != GetNumRows() && vector.GetNumCols() != GetNumRows()) LogicError("SetDiagonalValue: input vector's dimension does not agree with [this]."); else { auto& us = *this; long m = (long) GetNumRows(); if (vector.GetNumRows() == 1) // row vector { #pragma omp parallel for // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, i) = vector(0, i); us(i + 1, i + 1) = vector(0, i + 1); us(i + 2, i + 2) = vector(0, i + 2); us(i + 3, i + 3) = vector(0, i + 3); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, i) = vector(0, i); } } else { #pragma omp parallel for // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, i) = vector(i, 0); us(i + 1, i + 1) = vector(i + 1, 0); us(i + 2, i + 2) = vector(i + 2, 0); us(i + 3, i + 3) = vector(i + 3, 0); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, i) = vector(i, 0); } } } } template <class ElemType> void CPUMatrix<ElemType>::SetUniformRandomValue(const ElemType low, const ElemType high, unsigned long seed) { if (IsEmpty()) LogicError("SetUniformRandomValue: Matrix is empty."); std::mt19937_64 generator; generator.seed(seed == USE_TIME_BASED_SEED ? (unsigned long) time(NULL) : seed); boost::random::uniform_real_distribution<ElemType> r(low, high); ElemType* bufPtr = Data(); long m = (long) GetNumElements(); // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { bufPtr[i] = r(generator); bufPtr[i + 1] = r(generator); bufPtr[i + 2] = r(generator); bufPtr[i + 3] = r(generator); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { bufPtr[i] = r(generator); } } template <class ElemType> void CPUMatrix<ElemType>::SetUniformRandomValue(RNGHandle& rngHandle, const ElemType low, const ElemType high) { if (IsEmpty()) LogicError("SetUniformRandomValue: Matrix is empty."); CPURNGHandle* cpuRNGHandle = dynamic_cast<CPURNGHandle*>(&rngHandle); if (cpuRNGHandle == nullptr) LogicError("rngHandle must be a CPURNGHandle."); boost::random::uniform_real_distribution<ElemType> r(low, high); std::generate(Data(), Data() + GetNumElements(), [&cpuRNGHandle, &r]() {return r(cpuRNGHandle->Generator()); }); } template <class ElemType> void CPUMatrix<ElemType>::SetGaussianRandomValue(RNGHandle& rngHandle, const ElemType mean, const ElemType stdev) { if (IsEmpty()) LogicError("SetGaussianRandomValue: Matrix is empty."); CPURNGHandle* cpuRNGHandle = dynamic_cast<CPURNGHandle*>(&rngHandle); if (cpuRNGHandle == nullptr) LogicError("rngHandle must be a CPURNGHandle."); boost::random::normal_distribution<ElemType> r(mean, stdev); auto n = AsMultipleOf(GetNumElements(), 2); std::generate(Data(), Data() + n, [&cpuRNGHandle, &r]() {return r(cpuRNGHandle->Generator()); }); } template <class ElemType> void CPUMatrix<ElemType>::SetGumbelRandomValue(RNGHandle& rngHandle, const ElemType loc, const ElemType scale) { if (IsEmpty()) LogicError("SetGumbelRandomValue: Matrix is empty."); CPURNGHandle* cpuRNGHandle = dynamic_cast<CPURNGHandle*>(&rngHandle); if (cpuRNGHandle == nullptr) LogicError("rngHandle must be a CPURNGHandle."); boost::random::uniform_real_distribution<ElemType> r(0, 1); std::generate(Data(), Data() + GetNumElements(), [&cpuRNGHandle, &r, loc, scale]() {return loc - scale * log(-log1p(-r(cpuRNGHandle->Generator()))); }); } template <class ElemType> void CPUMatrix<ElemType>::SetGaussianRandomValue(const ElemType mean, const ElemType sigma, unsigned long seed) { if (sigma <= 0) InvalidArgument("SetGaussianRandomValue: sigma must be a positive value."); if (IsEmpty()) LogicError("SetGaussianRandomValue: Matrix is empty."); auto& us = *this; std::mt19937_64 generator(seed == USE_TIME_BASED_SEED ? (unsigned long) time(NULL) : seed); boost::random::normal_distribution<ElemType> r(mean, sigma); // #pragma omp parallel for is not thread safe. Also the results would not be deterministic foreach_coord (i, j, us) { us(i, j) = r(generator); } } template <class ElemType> void CPUMatrix<ElemType>::SetTruncatedNormalRandomValue(const ElemType mean, const ElemType sigma, unsigned long seed) { if (sigma <= 0) InvalidArgument("SetTruncatedNormalRandomValue: sigma must be a positive value."); if (IsEmpty()) LogicError("SetTruncatedNormalRandomValue: Matrix is empty."); auto& us = *this; std::mt19937_64 generator(seed == USE_TIME_BASED_SEED ? (unsigned long)time(NULL) : seed); boost::random::normal_distribution<ElemType> r(mean, sigma); const ElemType high = mean + 2 * sigma; const ElemType low = mean - 2 * sigma; // #pragma omp parallel for is not thread safe. Also the results would not be deterministic foreach_coord(i, j, us) { ElemType tmp = 0; do tmp = r(generator); while (tmp < low || tmp > high ); // Rejection sampling is fine here because the acceptance probability is about 0.9545 us(i, j) = tmp; } } template <class ElemType> void CPUMatrix<ElemType>::AddGaussianRandomValue(const ElemType mean, const ElemType sigma, unsigned long seed) { if (sigma <= 0) InvalidArgument("SetUniformRandomValue: sigma must be a positive value."); if (IsEmpty()) LogicError("SetUniformRandomValue: Matrix is empty."); auto& us = *this; std::mt19937_64 generator; generator.seed(seed == USE_TIME_BASED_SEED ? (unsigned long) time(NULL) : seed); boost::random::normal_distribution<ElemType> r(mean, sigma); long m = (long) GetNumRows(), n = (long) GetNumCols(); for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) = r(generator); us(i + 1, j) = r(generator); us(i + 2, j) = r(generator); us(i + 3, j) = r(generator); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) = r(generator); } } } //maskRate: percentage of values masked out (similar to dropout rate) //scaleValue: which scale value to set to the left ones (unmasked items). template <class ElemType> void CPUMatrix<ElemType>::SetUniformRandomMask(const ElemType maskRate, const ElemType scaleValue, RNGHandle& rngHandle) { if (IsEmpty()) LogicError("SetUniformRandomValue: Matrix is empty."); CPURNGHandle* cpuRNGHandle = dynamic_cast<CPURNGHandle*>(&rngHandle); if (cpuRNGHandle == nullptr) LogicError("rngHandle must be a CPURNGHandle."); auto& us = *this; boost::random::uniform_real_distribution<ElemType> r(0, 1); long m = (long) GetNumRows(), n = (long) GetNumCols(); ElemType v; for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { v = r(cpuRNGHandle->Generator()); us(i, j) = v <= maskRate ? 0 : scaleValue; v = r(cpuRNGHandle->Generator()); us(i + 1, j) = v <= maskRate ? 0 : scaleValue; v = r(cpuRNGHandle->Generator()); us(i + 2, j) = v <= maskRate ? 0 : scaleValue; v = r(cpuRNGHandle->Generator()); us(i + 3, j) = v <= maskRate ? 0 : scaleValue; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { v = r(cpuRNGHandle->Generator()); us(i, j) = v <= maskRate ? 0 : scaleValue; } } } template <class ElemType> ElemType CPUMatrix<ElemType>::Adagrad(CPUMatrix<ElemType>& gradients, const bool needAveMultiplier) { ElemType aveMultiplier = 0; if (IsEmpty() || gradients.GetNumCols() != GetNumCols() || gradients.GetNumRows() != GetNumRows()) { RequireSize(gradients.GetNumRows(), gradients.GetNumCols()); SetValue(0.0); } if (GetNumRows() != gradients.GetNumRows() || GetNumCols() != gradients.GetNumCols()) LogicError("The matrix gradients must have the same rows and columns as this matrix."); ElemType *a = Data(), *d_v = gradients.Data(); size_t n = GetNumElements(); const ElemType floor = 1e-16f; ElemType a0, a1, a2, a3; // disable omp here because aveMultiper needs to be added atomically. however, it seems the result is incorrect even if rmp atomic and amp critical are used. // #pragma omp parallel for for (long i = 0; i < (n & ~3); i += 4) // four-way unrolling { a[i] += d_v[i] * d_v[i]; a[i + 1] += d_v[i + 1] * d_v[i + 1]; a[i + 2] += d_v[i + 2] * d_v[i + 2]; a[i + 3] += d_v[i + 3] * d_v[i + 3]; a0 = sqrt(a[i] + floor); a1 = sqrt(a[i + 1] + floor); a2 = sqrt(a[i + 2] + floor); a3 = sqrt(a[i + 3] + floor); d_v[i] /= a0; d_v[i + 1] /= a1; d_v[i + 2] /= a2; d_v[i + 3] /= a3; if (needAveMultiplier) { aveMultiplier += 1 / a0 + 1 / a1 + 1 / a2 + 1 / a3; } } // get the last few elements if any for (long i = n & ~3; i < n; i++) { a[i] += d_v[i] * d_v[i]; a0 = sqrt(a[i] + floor); d_v[i] /= a0; if (needAveMultiplier) { aveMultiplier += 1 / a0; } } if (needAveMultiplier && n > 0) return aveMultiplier / n; else return 1; } template <class ElemType> void CPUMatrix<ElemType>::FSAdagrad(CPUMatrix<ElemType>& gradients, CPUMatrix<ElemType>& functionValues, ElemType learnRatePerSample, ElemType momentum, ElemType adaWeight, ElemType adaMul, bool unitGainMomentum) { auto unitGainFactor = ElemType(unitGainMomentum ? (1.0 - momentum) : 1.0); size_t numColsNeeded = 2 * gradients.GetNumCols(); if (IsEmpty() || (GetNumCols() < numColsNeeded)) { RequireSize(gradients.GetNumRows(), numColsNeeded); SetValue(0.0); } if (GetNumRows() != gradients.GetNumRows() || GetNumCols() != numColsNeeded) LogicError("The matrix gradients does not have expected dimensions."); size_t n = gradients.GetNumElements(); ElemType* grad = gradients.Data(); ElemType* smoothAda = Data(); ElemType* smoothMom = Data() + n; ElemType* val = functionValues.Data(); #pragma omp parallel for // TODO: Unroll 4-times for better performance leveraging vectorization for (long i = 0; i < n; i++) { ElemType g = grad[i]; ElemType adaSqr = adaWeight * smoothAda[i] + (1.0f - adaWeight) * g * g; smoothAda[i] = adaSqr; if (adaSqr != 0.0f) { ElemType ada = sqrt(adaSqr); ElemType w = adaMul * ((ElemType) 1.0 / ada); if (w > 10.0f) w = 10.0f; g *= w; } if (momentum > 0.0f) { g = momentum * smoothMom[i] + unitGainFactor * g; smoothMom[i] = g; } g *= learnRatePerSample; val[i] -= g; } } template <class ElemType> void CPUMatrix<ElemType>::Adam(CPUMatrix<ElemType>& gradients, CPUMatrix<ElemType>& functionValues, ElemType learnRatePerSample, ElemType momentum, ElemType adaWeight, ElemType adaMul, ElemType epsilon, bool unitGainMomentum, bool adamax) { size_t numColsNeeded = 2 * gradients.GetNumCols(); auto unitGainFactor = ElemType(unitGainMomentum ? (1.0 - momentum) : 1.0); if (IsEmpty() || (GetNumCols() < numColsNeeded)) { RequireSize(gradients.GetNumRows(), numColsNeeded); SetValue(0.0); } if (GetNumRows() != gradients.GetNumRows() || GetNumCols() != numColsNeeded) LogicError("The matrix gradients does not have expected dimensions."); size_t n = gradients.GetNumElements(); ElemType* grad = gradients.Data(); ElemType* smoothAda = Data(); ElemType* smoothMom = Data() + n; ElemType* val = functionValues.Data(); #pragma omp parallel for // TODO: Unroll 4-times for better performance leveraging vectorization for (long i = 0; i < n; i++) { ElemType g = grad[i]; ElemType ada; if (!adamax) { ElemType adaSqr = adaWeight * smoothAda[i] + (1.0f - adaWeight) * g * g; smoothAda[i] = adaSqr; ada = sqrt(adaSqr); } else ada = smoothAda[i] = std::max(adaWeight * smoothAda[i], abs(g)); ElemType w = adaMul * (ElemType)( 1.0 / (ada + epsilon)); g = momentum * smoothMom[i] + unitGainFactor * g; smoothMom[i] = g; val[i] -= g * w * learnRatePerSample; } } template <class ElemType> ElemType CPUMatrix<ElemType>::RmsProp(CPUMatrix<ElemType>& gradients, ElemType RMS_GAMMA, ElemType RMS_WGT_INC, ElemType RMS_WGT_MAX, ElemType RMS_WGT_DEC, ElemType RMS_WGT_MIN, const bool needAveMultiplier, const bool initialized) { const ElemType floor = 1e-6f; size_t n = gradients.GetNumElements(); ElemType* curr_grad = gradients.Data(); if (IsEmpty() || GetNumCols() < gradients.GetNumCols() * 3 || !initialized) { RequireSize(gradients.GetNumRows(), gradients.GetNumCols() * 3); SetValue(0.0); ElemType* avars = Data(); // accumulated variances for RMS scaling ElemType* steps = Data() + 2 * n; // current step size // initialize moving average of gradient-squared for (long i = 0; i < n; i++) avars[i] = curr_grad[i] * curr_grad[i]; // initialize starting step size for (long i = 0; i < n; i++) steps[i] = ElemType(0.02); } ElemType* avars = Data(); // accumulated variances for RMS scaling ElemType* signs = Data() + n; // sign of previous gradient ElemType* steps = Data() + 2 * n; // current step size if (GetNumRows() != gradients.GetNumRows() || GetNumCols() != gradients.GetNumCols() * 3) LogicError("The matrix gradients does not have expected dimensions."); ElemType ONE_MINUS_GAMMA = ElemType(1.0) - RMS_GAMMA; // int upd[] = { // 2,2,0, // 2,2,0, // 1,1,1, // 2,2,0, // 1,2,1, // 0,2,2, // 1,1,1, // 0,2,2, // 0,2,2, // }; // for (long i=0; i<n; i++) // { // avars[i] = RMS_GAMMA * avars[i] + ONE_MINUS_GAMMA * (curr_grad[i] * curr_grad[i]); // // grad sign base 3: 0->neg, 1->zero, 2->pos // const int grad_sign = 1 + (ElemType(0) < curr_grad[i]) - (curr_grad[i] < ElemType(0)); // // signs[i] contains three consecutive grad_sign // signs[i] = 3*(int(signs[i]) % 9) + grad_sign; // switch(upd[int(signs[i])]) // { // case 0: // steps[i] = max(steps[i] * RMS_WGT_DEC, RMS_WGT_MIN); // break; // case 2: // steps[i] = min(steps[i] * RMS_WGT_INC, RMS_WGT_MAX); // break; // } // curr_grad[i] *= steps[i] / sqrt(avars[i] + floor); // } ElemType aveMultiplier = 0, a; for (long i = 0; i < n; i++) { avars[i] = RMS_GAMMA * avars[i] + ONE_MINUS_GAMMA * (curr_grad[i] * curr_grad[i]); const int grad_sign = (ElemType(0) < curr_grad[i]) - (curr_grad[i] < ElemType(0)); if (signs[i] * grad_sign > 0) steps[i] = std::min(steps[i] * RMS_WGT_INC, RMS_WGT_MAX); else steps[i] = std::max(steps[i] * RMS_WGT_DEC, RMS_WGT_MIN); a = steps[i] / sqrt(avars[i] + floor); curr_grad[i] *= a; signs[i] = (ElemType) grad_sign; if (needAveMultiplier) aveMultiplier += a; } if (needAveMultiplier) return aveMultiplier / n; else return 1; } template <class ElemType> void CPUMatrix<ElemType>::AdaDelta(CPUMatrix<ElemType>& gradients, CPUMatrix<ElemType>& functionValues, ElemType learningRate, ElemType rho, ElemType epsilon) { size_t numColsNeeded = 2 * gradients.GetNumCols(); if (IsEmpty() || (GetNumCols() < numColsNeeded)) { RequireSize(gradients.GetNumRows(), numColsNeeded); SetValue(0.0); } if (GetNumRows() != gradients.GetNumRows() || GetNumCols() != numColsNeeded) LogicError("The matrix gradients does not have expected dimensions."); size_t n = gradients.GetNumElements(); ElemType* grad = gradients.Data(); ElemType* smoothAda = Data(); ElemType* smoothX2 = Data() + n; ElemType* val = functionValues.Data(); #pragma omp parallel for // TODO: Unroll 4-times for better performance leveraging vectorization for (long i = 0; i < n; i++) { ElemType g = grad[i]; ElemType adaSqr = rho * smoothAda[i] + (1 - rho) * g * g; smoothAda[i] = adaSqr; ElemType x2 = smoothX2[i]; ElemType deltaX = -sqrt(x2 + epsilon) / sqrt(adaSqr + epsilon) * g; smoothX2[i] = rho * smoothX2[i] + (1 - rho) * deltaX * deltaX; val[i] += learningRate * deltaX; } } template <class ElemType> void CPUMatrix<ElemType>::Reshape(const size_t numRows, const size_t numCols) { if (numRows * numCols != GetNumElements()) InvalidArgument("Reshape: Total number of elements does not match."); m_numRows = numRows; m_numCols = numCols; } // RequireSize() -- Tests if the matrix is the right size. If not, resizes the matrix. This avoids the VerifyResizable check if we're already the right size. template <class ElemType> void CPUMatrix<ElemType>::RequireSize(const size_t numRows, const size_t numCols, bool growOnly /*=true*/) { if (GetNumRows() != numRows || GetNumCols() != numCols) Resize(numRows, numCols, growOnly); } // Resize() -- change matrix size // This function is cheap if the matrix size does not change. // Current content is not preserved. // If growOnly is true, resize will not reallocate memory if the current memory is large enough (i.e., will not shrink). // If this object does not own its memory then new memory cannot be allocated (one can still shrink and/or reshape). template <class ElemType> void CPUMatrix<ElemType>::Resize(const size_t numRows, const size_t numCols, bool growOnly /*=true*/) { if (GetNumRows() == numRows && GetNumCols() == numCols) return; VerifyResizable(__func__); size_t numElements = numRows * numCols; if (numElements > GetSizeAllocated() || // grow allocation (!growOnly && (numElements != GetSizeAllocated()))) // shrink allocation (not if 'growOnly') { // reallocate buffer ElemType* pArray = nullptr; if (numElements > 0) { pArray = NewArray<ElemType>(numElements); } // success: update the object delete[] Buffer(); SetBuffer(pArray, numElements * sizeof(ElemType)); SetSizeAllocated(numElements); } // success m_sliceViewOffset = 0; m_numRows = numRows; m_numCols = numCols; } // allocated by the callee but should be deleted by the caller // TODO: change to use STL vector instead template <class ElemType> ElemType* CPUMatrix<ElemType>::CopyToArray() const { size_t numElements = GetNumElements(); if (numElements != 0) { ElemType* arrayCopyTo = NewArray<ElemType>(numElements); memcpy(arrayCopyTo, Data(), sizeof(ElemType) * numElements); return arrayCopyTo; } else { return nullptr; } } //memory will be allocated by the callee if not enough but need to be deleted by the caller after it's done //return number of elements copied template <class ElemType> size_t CPUMatrix<ElemType>::CopyToArray(ElemType*& arrayCopyTo, size_t& currentArraySize) const { size_t numElements = GetNumElements(); if (numElements > currentArraySize) { delete arrayCopyTo; arrayCopyTo = NewArray<ElemType>(numElements); currentArraySize = numElements; } if (numElements != 0) { memcpy(arrayCopyTo, Data(), sizeof(ElemType) * numElements); } return numElements; } template <typename ElemType> void CPUMatrix<ElemType>::CopySection(size_t /*numRows*/, size_t /*numCols*/, ElemType* /*dst*/, size_t /*colStride*/) const { // REVIEW alexeyk: currently not used by CPU, but implement when possible. RuntimeError("Not implemented."); } template <class ElemType> inline size_t CPUMatrix<ElemType>::LocateColumn(const size_t col) const { // For performance reason avoid extra validation in release. assert(col == 0 || col < GetNumCols()); return col * m_numRows; // matrix in column-wise storage } template <class ElemType> inline size_t CPUMatrix<ElemType>::LocateElement(const size_t row, const size_t col) const { // For performance reason avoid extra validation in release. assert(row < m_numRows); return LocateColumn(col) + row; // matrix in column-wise storage } #pragma endregion Basic Operators #pragma region Member BLAS Functions template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::operator+=(ElemType alpha) { return AssignSumOf(alpha, *this); } template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::operator+(ElemType alpha) const { CPUMatrix<ElemType> c(GetNumRows(), GetNumCols()); c.AssignSumOf(alpha, *this); return c; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignSumOf(const ElemType alpha, const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignSumOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) = alpha + a(i, j); us(i + 1, j) = alpha + a(i + 1, j); us(i + 2, j) = alpha + a(i + 2, j); us(i + 3, j) = alpha + a(i + 3, j); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) = alpha + a(i, j); } } return *this; } //if [this] and a have same dimension then [this]=[this]+a //if a is a column vector, add to all columns of [this] //if a is a row vector, add to all rows of [this] //if a is a scalar, add it to all elements. template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::operator+=(const CPUMatrix<ElemType>& a) { // if (a.GetNumElements() == 1) // *this += a(0,0); // else ScaleAndAdd(1, a, *this); return *this; } //if [this] and a have same dimension then OUTPUT=[this]+a //if a is a column vector, add to all columns of [this] //if a is a row vector, add to all rows of [this] template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::operator+(const CPUMatrix<ElemType>& a) const { if (GetNumElements() == 1) { CPUMatrix<ElemType> c(a); c += (*this)(0, 0); return c; } else if (a.GetNumElements() == 1) { CPUMatrix<ElemType> c(*this); c += a(0, 0); return c; } else { CPUMatrix<ElemType> c(*this); // this implementation will introduce a copy overhead. but make resue of the code c += a; return c; } } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignSumOf(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b) { if (a.GetNumElements() == 1) { SetValue(b); (*this) += a; } else { SetValue(a); (*this) += b; } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::operator-=(ElemType alpha) { return AssignDifferenceOf(*this, alpha); } template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::operator-(ElemType alpha) const { CPUMatrix<ElemType> c(GetNumRows(), GetNumCols()); c.AssignDifferenceOf(*this, alpha); return c; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignDifferenceOf(const ElemType alpha, const CPUMatrix<ElemType>& a) { auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) = alpha - a(i, j); us(i + 1, j) = alpha - a(i + 1, j); us(i + 2, j) = alpha - a(i + 2, j); us(i + 3, j) = alpha - a(i + 3, j); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) = alpha - a(i, j); } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignDifferenceOf(const CPUMatrix<ElemType>& a, const ElemType alpha) { auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) = a(i, j) - alpha; us(i + 1, j) = a(i + 1, j) - alpha; us(i + 2, j) = a(i + 2, j) - alpha; us(i + 3, j) = a(i + 3, j) - alpha; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) = a(i, j) - alpha; } } return *this; } //if [this] and a have same dimension then [this]=[this]-a //if a is a column vector, minus it from all columns of [this] //if a is a row vector, minus it from all rows of [this] template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::operator-=(const CPUMatrix<ElemType>& a) { ScaleAndAdd(-1, a, *this); return *this; } //if [this] and a have same dimension then output=[this]-a //if a is a column vector, minus it from all columns of [this] //if a is a row vector, minus it from all rows of [this] template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::operator-(const CPUMatrix<ElemType>& a) const { CPUMatrix<ElemType> c(*this); // this implementation will introduce a copy overhead. but make resue of the code c -= a; return c; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignDifferenceOf(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b) { if (this != &a) { RequireSize(a.GetNumRows(), a.GetNumCols()); SetValue(a); } (*this) -= b; return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::operator*=(ElemType alpha) { Scale(alpha, *this); return *this; } template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::operator*(ElemType alpha) const { CPUMatrix<ElemType> c(GetNumRows(), GetNumCols()); Scale(alpha, *this, c); return c; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignProductOf(const ElemType alpha, const CPUMatrix<ElemType>& a) { Scale(alpha, a, *this); return *this; } // [this]=a*b template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignProductOf(const CPUMatrix<ElemType>& a, const bool transposeA, const CPUMatrix<ElemType>& b, const bool transposeB) { if (a.GetNumElements() == 1) { if (transposeB) AssignTransposeOf(b); (*this) *= a(0, 0); } else if (b.GetNumElements() == 1) { if (transposeA) AssignTransposeOf(a); (*this) *= b(0, 0); } else Multiply(a, transposeA, b, transposeB, *this); return *this; } template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::operator*(const CPUMatrix<ElemType>& a) const { auto& us = *this; if (GetNumElements() == 1) { CPUMatrix<ElemType> c; c.AssignProductOf(us(0, 0), a); return c; } else if (a.GetNumElements() == 1) { CPUMatrix<ElemType> c; c.AssignProductOf(a(0, 0), us); return c; } else { CPUMatrix<ElemType> c; Multiply(*this, a, c); return c; } } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::operator/=(ElemType alpha) { (*this) *= 1 / alpha; return (*this); } template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::operator/(ElemType alpha) const { return ((*this) * (1 / alpha)); } //element-wise power template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::operator^=(ElemType alpha) { auto& us = *this; ElementWisePower(alpha, us, us); return us; } //element-wise power template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::operator^(ElemType alpha) const { CPUMatrix<ElemType> c(GetNumRows(), GetNumCols()); ElementWisePower(alpha, *this, c); return c; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignElementPowerOf(const CPUMatrix<ElemType>& a, const ElemType power) { ElementWisePower(power, a, *this); return *this; } //[this]=[this] .* a (we cannot override operator .* in c++) template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::ElementMultiplyWith(const CPUMatrix<ElemType>& a) { return AssignElementProductOf(*this, a); } //[this]=[this] .* a (we cannot override operator .* in c++) template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::ElementDivideBy(const CPUMatrix<ElemType>& a) { return AssignElementDivisionOf(*this, a); } //[this]=a .* b template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignElementProductOf(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b) { if (a.IsEmpty() || b.IsEmpty()) LogicError("AssignElementProductOf: Matrix is empty."); if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols())) InvalidArgument("AssignElementProductOf: The input matrix dimensions do not match."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) = a(i, j) * b(i, j); us(i + 1, j) = a(i + 1, j) * b(i + 1, j); us(i + 2, j) = a(i + 2, j) * b(i + 2, j); us(i + 3, j) = a(i + 3, j) * b(i + 3, j); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) = a(i, j) * b(i, j); } } return *this; } //[this] +=a .* b template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AddElementProductOf(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b) { if (a.IsEmpty() || b.IsEmpty()) LogicError("AddElementProductOf: Matrix is empty."); if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols())) InvalidArgument("AddElementProductOf : The input matrix dimensions do not match."); if (!(a.GetNumRows() == GetNumRows() && a.GetNumCols() == GetNumCols())) InvalidArgument("AddElementProductOf : The input matrix dimensions do not match [this]."); auto& us = *this; long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) += a(i, j) * b(i, j); us(i + 1, j) += a(i + 1, j) * b(i + 1, j); us(i + 2, j) += a(i + 2, j) * b(i + 2, j); us(i + 3, j) += a(i + 3, j) * b(i + 3, j); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) += a(i, j) * b(i, j); } } return *this; } //[this]=a ./ b // TODO: This clips the divisor by a small value. Is that really what one would want? template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignElementDivisionOf(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b) { if (a.IsEmpty() || b.IsEmpty()) LogicError("AssignElementDivisionOf: Matrix is empty."); if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols())) InvalidArgument("AssignElementDivisionOf : The input matrix dimensions do not match."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); ElemType smallValue = EPS_IN_INVERSE; #pragma omp parallel for foreach_coord (i, j, us) { ElemType v = b(i, j); if (v >= 0 && v < smallValue) us(i, j) = a(i, j) / smallValue; else if (v < 0 && v > -smallValue) us(i, j) = a(i, j) / (-smallValue); else us(i, j) = a(i, j) / v; } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::ColumnElementMultiplyWith(const CPUMatrix<ElemType>& a) { if (a.IsEmpty() || IsEmpty()) LogicError("ColumnElementMultiplyWith: Matrix is empty."); if (!(a.GetNumRows() == GetNumRows() && a.GetNumCols() == 1)) InvalidArgument("ColumnElementMultiplyWith: The input matrix should be a col vector and match [this]'s rows."); auto& us = *this; long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) *= a(i, 0); us(i + 1, j) *= a(i + 1, 0); us(i + 2, j) *= a(i + 2, 0); us(i + 3, j) *= a(i + 3, 0); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) *= a(i, 0); } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::RowElementMultiplyWith(const CPUMatrix<ElemType>& a) { if (a.IsEmpty() || IsEmpty()) LogicError("RowElementMultiplyWith: Matrix is empty."); if (!(a.GetNumRows() == 1 && a.GetNumCols() == GetNumCols())) InvalidArgument("RowElementMultiplyWith: The input matrix should be a row vector and match [this]'s columns."); auto& us = *this; long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { ElemType v = a(0, j); // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) *= v; us(i + 1, j) *= v; us(i + 2, j) *= v; us(i + 3, j) *= v; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) *= v; } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::RowElementDivideBy(const CPUMatrix<ElemType>& a) { if (a.IsEmpty() || IsEmpty()) LogicError("RowElementDivideBy: Matrix is empty."); if (!(a.GetNumRows() == 1 && a.GetNumCols() == GetNumCols())) InvalidArgument("RowElementDivideBy: The input matrix should be a row vector and match [this]'s columns."); auto& us = *this; long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { ElemType v = a(0, j); if (v >= 0 && v < EPS_IN_INVERSE) v = EPS_IN_INVERSE; else if (v < 0 && v > -EPS_IN_INVERSE) v = (-EPS_IN_INVERSE); // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) /= v; us(i + 1, j) /= v; us(i + 2, j) /= v; us(i + 3, j) /= v; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) /= v; } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::ColumnElementDivideBy(const CPUMatrix<ElemType>& a) { if (a.IsEmpty() || IsEmpty()) LogicError("ColumnElementDivideBy: Matrix is empty."); if (!(a.GetNumRows() == GetNumRows() && a.GetNumCols() == 1)) InvalidArgument("ColumnElementDivideBy: The input matrix should be a col vector and match [this]'s rows."); auto& us = *this; long m = (long) GetNumRows(), n = (long) GetNumCols(); ElemType smallValue = EPS_IN_INVERSE; #pragma omp parallel for for (long j = 0; j < n; j++) { for (long i = 0; i < m; i++) { ElemType v = a(i, 0); if (v >= 0 && v < smallValue) us(i, j) /= smallValue; else if (v < 0 && v > -smallValue) us(i, j) /= (-smallValue); else us(i, j) /= v; } } return *this; } //[this]=1 ./ a template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::ElementInverse() { return AssignElementInverseOf(*this); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignElementInverseOf(const CPUMatrix<ElemType>& a) { ElemType smallValue = EPS_IN_INVERSE; if (a.IsEmpty()) LogicError("AssignElementInverseOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); #pragma omp parallel for foreach_coord (i, j, us) { if (a(i, j) < 0 && a(i, j) > -smallValue) us(i, j) = 1 / (-smallValue); else if (a(i, j) >= 0 && a(i, j) < smallValue) us(i, j) = 1 / smallValue; else us(i, j) = 1 / a(i, j); } return *this; } //[this]=sigmoid([this]) element wise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceSigmoid() { return AssignSigmoidOf(*this); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignSigmoidOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignSigmoidOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); #pragma omp parallel for foreach_coord (i, j, us) { if (a(i, j) >= 0) us(i, j) = 1 / (1 + exp(-a(i, j))); else { ElemType v = exp(a(i, j)); us(i, j) = v / (1 + v); } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceLinearRectifierDerivative() { return AssignLinearRectifierDerivativeOf(*this); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignLinearRectifierDerivativeOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignLinearRectifierDerivativeOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) = a(i, j) > 0.0f ? 1.0f : 0.0f; us(i + 1, j) = a(i + 1, j) > 0.0f ? 1.0f : 0.0f; us(i + 2, j) = a(i + 2, j) > 0.0f ? 1.0f : 0.0f; us(i + 3, j) = a(i + 3, j) > 0.0f ? 1.0f : 0.0f; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) = a(i, j) > 0.0f ? 1.0f : 0.0f; } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceSigmoidDerivative() { return AssignSigmoidDerivativeOf(*this); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignSigmoidDerivativeOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignSigmoidDerivativeOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { ElemType v = a(i, j); us(i, j) = v * (1 - v); ElemType v1 = a(i + 1, j); us(i + 1, j) = v1 * (1 - v1); ElemType v2 = a(i + 2, j); us(i + 2, j) = v2 * (1 - v2); ElemType v3 = a(i + 3, j); us(i + 3, j) = v3 * (1 - v3); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { ElemType v = a(i, j); us(i, j) = v * (1 - v); } } return *this; } //[this]=tanh([this]) element wise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceTanh() { return AssignTanhOf(*this); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignTanhOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignTanhOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) = tanh(a(i, j)); us(i + 1, j) = tanh(a(i + 1, j)); us(i + 2, j) = tanh(a(i + 2, j)); us(i + 3, j) = tanh(a(i + 3, j)); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) = tanh(a(i, j)); } } return *this; } //[this]=softmax([this]) element wise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceLogSoftmax(const bool isColWise) { return AssignLogSoftmaxOf(*this, isColWise); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignLogSoftmaxOf(const CPUMatrix<ElemType>& a, const bool isColWise) { if (a.IsEmpty()) LogicError("AssignLogSoftmaxOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); if (isColWise) { #pragma omp parallel for foreach_column (j, a) { // we need to extract max before applying exp to avoid overflow ElemType maxV = a(0, j); foreach_row (i, a) maxV = std::max(maxV, a(i, j)); ElemType sum = 0; foreach_row (i, a) sum += exp(us(i, j) = a(i, j) - maxV); sum = log(sum); foreach_row (i, us) us(i, j) -= sum; } } else { #pragma omp parallel for foreach_row (i, a) { // we need to extract max before applying exp to avoid overflow ElemType maxV = a(i, 0); foreach_column (j, a) maxV = std::max(maxV, a(i, j)); ElemType sum = 0; foreach_column (j, a) sum += exp(us(i, j) = a(i, j) - maxV); sum = log(sum); foreach_column (j, us) us(i, j) -= sum; } } return *this; } //[this]=hardmax([this]) //the max element is 1 else is 0 template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceHardmax(const bool isColWise) { return AssignHardmaxOf(*this, isColWise); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignHardmaxOf(const CPUMatrix<ElemType>& a, const bool isColWise) { if (a.IsEmpty()) LogicError("AssignHardmaxOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); if (isColWise) { #pragma omp parallel for foreach_column (j, a) { // we need to extract max ElemType maxV = a(0, j); long maxI = 0; foreach_row (i, a) { if (maxV < a(i, j)) { maxV = a(i, j); maxI = i; } } foreach_row (i, us) us(i, j) = (i == maxI) ? 1.0f : 0.0f; } } else { #pragma omp parallel for foreach_row (i, a) { // we need to extract max ElemType maxV = a(i, 0); long maxJ = 0; foreach_column (j, a) { if (maxV < a(i, j)) { maxV = a(i, j); maxJ = j; } } foreach_column (j, us) us(i, j) = (j == maxJ) ? 1.0f : 0.0f; } } return *this; } //[this]=sqrt([this]) element wise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceSqrt() { return AssignSqrtOf(*this); } //to prevent negative values caused by floating operations, we force inputs to be >=0 //this may, however, hide problems in the caller. template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignSqrtOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignSqrtOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) = sqrt(max((ElemType)0, a(i, j))); us(i + 1, j) = sqrt(max((ElemType)0, a(i + 1, j))); us(i + 2, j) = sqrt(max((ElemType)0, a(i + 2, j))); us(i + 3, j) = sqrt(max((ElemType)0, a(i + 3, j))); } // remaining for (long i = m & ~3; i < m; i++) { us(i, j) = sqrt(max((ElemType)0, a(i, j))); } } return *this; } //[this]=exp([this]) element wise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceExp() { return AssignExpOf(*this); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignExpOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignExpOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) = exp(a(i, j)); us(i + 1, j) = exp(a(i + 1, j)); us(i + 2, j) = exp(a(i + 2, j)); us(i + 3, j) = exp(a(i + 3, j)); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) = exp(a(i, j)); } } return *this; } //[this]=exp([this]) element wise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceAbs() { return AssignAbsOf(*this); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignAbsOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignAbsOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) = abs(a(i, j)); us(i + 1, j) = abs(a(i + 1, j)); us(i + 2, j) = abs(a(i + 2, j)); us(i + 3, j) = abs(a(i + 3, j)); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) = abs(a(i, j)); } } return *this; } //[this]=log([this]) element wise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceLog() { return AssignLogOf(*this); } //[this]=log([this]) element wise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceLog10() { return AssignLog10Of(*this); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignLogOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignLogOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); #pragma omp parallel for foreach_coord (i, j, a) { const ElemType v = a(i, j); if (v < EPS_IN_LOG) { us(i, j) = LOG_OF_EPS_IN_LOG; } else us(i, j) = log(v); } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignLog10Of(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignLogOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); #pragma omp parallel for foreach_coord (i, j, a) { const ElemType v = a(i, j); if (v <= 0) LogicError("AssignLogOf: Log can only applied to numbers larger than 0."); else if (v < EPS_IN_LOG) { us(i, j) = LOG10_OF_EPS_IN_LOG; } else us(i, j) = log10(v); } return *this; } //[this]=cos([this]) element wise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceCosine() { return AssignCosineOf(*this); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignCosineOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignCosineOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); #pragma omp parallel for foreach_coord (i, j, a) { const ElemType v = a(i, j); us(i, j) = cos(v); } return *this; } //[this]=-sin([this]) element wise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceNegativeSine() { return AssignNegativeSineOf(*this); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignNegativeSineOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignCosineOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); #pragma omp parallel for foreach_coord (i, j, a) { const ElemType v = a(i, j); us(i, j) = -sin(v); } return *this; } //Threshold truncating: this[i] = max( this[i], threshold ) template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceTruncateBottom(const ElemType threshold) { if (IsEmpty()) LogicError("InplaceTruncateBottom: Matrix is empty."); auto& us = *this; long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { if (us(i, j) < threshold) us(i, j) = threshold; if (us(i + 1, j) < threshold) us(i + 1, j) = threshold; if (us(i + 2, j) < threshold) us(i + 2, j) = threshold; if (us(i + 3, j) < threshold) us(i + 3, j) = threshold; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { if (us(i, j) < threshold) us(i, j) = threshold; } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceTruncate(const ElemType threshold) { if (IsEmpty()) LogicError("InplaceTruncate: Matrix is empty."); auto& us = *this; ElemType locThresholdPos = abs(threshold); ElemType locTHresholdNeg = -locThresholdPos; long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { if (us(i, j) > locThresholdPos) us(i, j) = locThresholdPos; else if (us(i, j) < locTHresholdNeg) us(i, j) = locTHresholdNeg; if (us(i + 1, j) > locThresholdPos) us(i + 1, j) = locThresholdPos; else if (us(i + 1, j) < locTHresholdNeg) us(i + 1, j) = locTHresholdNeg; if (us(i + 2, j) > locThresholdPos) us(i + 2, j) = locThresholdPos; else if (us(i + 2, j) < locTHresholdNeg) us(i + 2, j) = locTHresholdNeg; if (us(i + 3, j) > locThresholdPos) us(i + 3, j) = locThresholdPos; else if (us(i + 3, j) < locTHresholdNeg) us(i + 3, j) = locTHresholdNeg; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { if (us(i, j) > locThresholdPos) us(i, j) = locThresholdPos; else if (us(i, j) < locTHresholdNeg) us(i, j) = locTHresholdNeg; } } return *this; } //x= x-threshold if x>threshold, x+threshold if x<-threshold, 0 otherwise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceSoftThreshold(const ElemType threshold) { if (IsEmpty()) LogicError("InplaceTruncate: Matrix is empty."); long m = (long) GetNumElements(); ElemType* bufPtr = Data(); #pragma omp parallel for for (long i = 0; i < (m & ~3); i += 4) // four-way unrolling { if (bufPtr[i] > threshold) bufPtr[i] -= threshold; else if (bufPtr[i] < -threshold) bufPtr[i] += threshold; else bufPtr[i] = 0; if (bufPtr[i + 1] > threshold) bufPtr[i + 1] -= threshold; else if (bufPtr[i + 1] < -threshold) bufPtr[i + 1] += threshold; else bufPtr[i + 1] = 0; if (bufPtr[i + 2] > threshold) bufPtr[i + 2] -= threshold; else if (bufPtr[i + 2] < -threshold) bufPtr[i + 2] += threshold; else bufPtr[i + 2] = 0; if (bufPtr[i + 3] > threshold) bufPtr[i + 3] -= threshold; else if (bufPtr[i + 3] < -threshold) bufPtr[i + 3] += threshold; else bufPtr[i + 3] = 0; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { if (bufPtr[i] > threshold) bufPtr[i] -= threshold; else if (bufPtr[i] < -threshold) bufPtr[i] += threshold; else bufPtr[i] = 0; } return *this; } //Threshold truncating: this[i] = max( a[i], threshold ) template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignTruncateBottomOf(const CPUMatrix<ElemType>& a, const ElemType threshold) { if (a.IsEmpty()) LogicError("AssignTruncateBottomOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); #pragma omp parallel for foreach_coord (i, j, a) { if (a(i, j) < threshold) us(i, j) = threshold; else us(i, j) = a(i, j); } return *this; } //Threshold truncating: this[i] = min( this[i], threshold ) template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceTruncateTop(const ElemType threshold) { if (IsEmpty()) LogicError("InplaceTruncateTop: Matrix is empty."); auto& us = *this; #pragma omp parallel for foreach_coord (i, j, us) { if (us(i, j) > threshold) us(i, j) = threshold; } return *this; } //Threshold truncating: this[i] = min( a[i], threshold ) template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignTruncateTopOf(const CPUMatrix<ElemType>& a, const ElemType threshold) { if (a.IsEmpty()) LogicError("AssignTruncateTopOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); #pragma omp parallel for foreach_coord (i, j, a) { if (a(i, j) > threshold) us(i, j) = threshold; else us(i, j) = a(i, j); } return *this; } //Threshold truncating: this[i] = 0 if abs(this[i]<threshold). template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::SetToZeroIfAbsLessThan(const ElemType threshold) { if (IsEmpty()) LogicError("SetToZeroIfAbsLessThan: Matrix is empty."); auto& us = *this; #pragma omp parallel for foreach_coord (i, j, us) { if (abs(us(i, j)) < threshold) us(i, j) = 0; } return *this; } //sum of all abs(elements) template <class ElemType> ElemType CPUMatrix<ElemType>::SumOfAbsElements() const { if (IsEmpty()) LogicError("SumOfAbsElements: Matrix is empty."); if (sizeof(ElemType) == sizeof(double)) { return (ElemType) cblas_dasum((int) GetNumElements(), reinterpret_cast<double*>(Data()), 1); } else { #pragma warning(suppress : 4244) return cblas_sasum((int) GetNumElements(), reinterpret_cast<float*>(Data()), 1); } } //sum of all elements template <class ElemType> ElemType CPUMatrix<ElemType>::SumOfElements() const { if (IsEmpty()) LogicError("SumOfElements: Matrix is empty."); ElemType sum = 0; long m = (long) GetNumElements(); // note: OpenMP requires loop indices to be long, not size_t ElemType* bufPtr = Data(); //four-way unrolling #pragma omp parallel for reduction(+ : sum) for (long i = 0; i < (m & ~3); i += 4) { sum += bufPtr[i] + bufPtr[i + 1] + bufPtr[i + 2] + bufPtr[i + 3]; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { sum += bufPtr[i]; } return sum; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignSumOfElements(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignSumOfElements: Matrix a is empty."); auto& us = *this; us.RequireSize(1, 1); us(0, 0) = a.SumOfElements(); return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignOneHot(const CPUMatrix<ElemType>& a, vector<size_t>& shape, size_t axis) { if (a.IsEmpty()) LogicError("AssignOneHot: Matrix a is empty."); if (axis >= shape.size()) LogicError("AssignOneHot: axis is not correct"); size_t item_size = 1; for (size_t i = 0; i < shape.size() && i < axis; i++) item_size *= shape[i]; size_t num_class = shape[axis]; auto& us = *this; auto nCols = a.GetNumCols(); auto nRows = num_class * a.GetNumRows(); us.RequireSize(nRows, nCols); ElemType* bufPtr = Data(); ElemType* aBufPtr = a.Data(); memset(bufPtr, 0, sizeof(ElemType) * nRows *nCols); #pragma omp parallel for for (long i = 0; i < a.GetNumElements(); i++) { if (aBufPtr[i] >= 0 && aBufPtr[i] < num_class) { size_t block_id = i / item_size; size_t item_id = i % item_size; bufPtr[block_id * num_class * item_size + item_id + item_size * (size_t)aBufPtr[i]] = 1; } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::GatherFromTarget(const CPUMatrix<ElemType>& indices, const CPUMatrix<ElemType>& target, size_t row_elements) { if (indices.IsEmpty() || target.IsEmpty()) LogicError("GatherFromTarget: input matrix is empty."); if (row_elements == 0) LogicError("GatherFromTarget: target matrix at least need 1 dim."); auto nCols = indices.GetNumCols(); auto nRows = indices.GetNumRows() * row_elements; this->RequireSize(nRows, nCols); ElemType* indicesBufPtr = indices.Data(); ElemType* targetBufPtr = target.Data(); ElemType* buffer = Data(); #pragma omp parallel for for (int i = 0; i < indices.GetNumElements(); i++) { memcpy(buffer + i * row_elements, targetBufPtr + ((size_t)indicesBufPtr[i] * row_elements), sizeof(ElemType) * row_elements); } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::ScatterToIndices(const CPUMatrix<ElemType>& values, const CPUMatrix<ElemType>& indices, size_t row_elements) { if (indices.IsEmpty() || values.IsEmpty()) LogicError("ScatterToIndices: input matrix is empty."); ElemType* indicesBufPtr = indices.Data(); ElemType* valueBufPtr = values.Data(); ElemType* buffer = Data(); ScatterValues(indicesBufPtr, valueBufPtr, buffer, (ElemType)1, indices.GetNumElements(), row_elements, this->GetNumCols()); return *this; } template <class ElemType> bool CPUMatrix<ElemType>::IsEqualTo(const CPUMatrix<ElemType>& a, const ElemType threshold /*= 1e-8*/) const { return AreEqual(*this, a, threshold); } template <class ElemType> void CPUMatrix<ElemType>::VectorSum(const CPUMatrix<ElemType>& a, CPUMatrix<ElemType>& c, const bool isColWise) { if (a.IsEmpty()) LogicError("VectorSum: Input matrix a is empty."); const int m = (int) a.GetNumRows(); const int n = (int) a.GetNumCols(); assert(m > 0 && n > 0); // converting from size_t to int may cause overflow if (isColWise) // col-wise { c.RequireSize(1, n); #pragma omp parallel for foreach_column (j, a) { ElemType v = 0; foreach_row (i, a) { #pragma omp atomic v += a(i, j); } c(0, j) = v; } } else { c.RequireSize(m, 1); #pragma omp parallel for foreach_row (i, a) { ElemType v = 0; foreach_column (j, a) { #pragma omp atomic v += a(i, j); } c(i, 0) = v; } } } template <class ElemType> void CPUMatrix<ElemType>::VectorNorm1(CPUMatrix<ElemType>& c, const bool isColWise) const { if (IsEmpty()) LogicError("VectorNorm1: Matrix is empty."); auto& us = *this; const int m = (int) us.GetNumRows(); const int n = (int) us.GetNumCols(); assert(m > 0 && n > 0); // converting from size_t to int may cause overflow if (isColWise) // col-wise { c.RequireSize(1, n); #pragma omp parallel for foreach_column (j, us) { ElemType v = 0; foreach_row (i, us) { #pragma omp atomic v += abs(us(i, j)); } c(0, j) = v; } } else { c.RequireSize(m, 1); #pragma omp parallel for foreach_row (i, us) { ElemType v = 0; foreach_column (j, us) { #pragma omp atomic v += abs(us(i, j)); } c(i, 0) = v; } } } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignVectorNorm1Of(CPUMatrix<ElemType>& a, const bool isColWise) { a.VectorNorm1(*this, isColWise); return *this; } template <class ElemType> void CPUMatrix<ElemType>::VectorNorm2(CPUMatrix<ElemType>& c, const bool isColWise) const { if (IsEmpty()) LogicError("VectorNorm2: Matrix is empty."); auto& us = *this; const int m = (int) us.GetNumRows(); const int n = (int) us.GetNumCols(); assert(m > 0 && n > 0); // converting from size_t to int may cause overflow ElemType* bufPtr = us.Data(); if (isColWise) // col-wise { c.RequireSize(1, n); if (sizeof(ElemType) == sizeof(double)) { #pragma omp parallel for foreach_column (j, c) { c(0, j) = (ElemType) cblas_dnrm2(m, reinterpret_cast<double*>(bufPtr + us.LocateColumn(j)), 1); } } else { #pragma omp parallel for foreach_column (j, c) { #pragma warning(suppress : 4244) c(0, j) = cblas_snrm2(m, reinterpret_cast<float*>(bufPtr + us.LocateColumn(j)), 1); } } } else { c.RequireSize(m, 1); if (sizeof(ElemType) == sizeof(double)) { #pragma omp parallel for foreach_row (i, c) { c(i, 0) = cblas_dnrm2(n, reinterpret_cast<double*>(bufPtr + i), m); } } else { #pragma omp parallel for foreach_row (i, c) { #pragma warning(suppress : 4244) c(i, 0) = cblas_snrm2(n, reinterpret_cast<float*>(bufPtr + i), m); } } } } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignVectorNorm2Of(CPUMatrix<ElemType>& a, const bool isColWise) { a.VectorNorm2(*this, isColWise); return *this; } template <class ElemType> void CPUMatrix<ElemType>::VectorNormInf(CPUMatrix<ElemType>& c, const bool isColWise) const { if (IsEmpty()) LogicError("VectorNormInf: Matrix is empty."); auto& us = *this; const int m = (int) us.GetNumRows(); const int n = (int) us.GetNumCols(); assert(m > 0 && n > 0); // converting from size_t to int may cause overflow if (isColWise) // col-wise { c.RequireSize(1, n); // #pragma omp parallel for foreach_column (j, us) { ElemType v = 0; foreach_row (i, us) { v = std::max(v, abs(us(i, j))); } c(0, j) = v; } } else { c.RequireSize(m, 1); // #pragma omp parallel for foreach_row (i, us) { ElemType v = 0; foreach_column (j, us) { v = std::max(v, abs(us(i, j))); } c(i, 0) = v; } } } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignVectorNormInfOf(CPUMatrix<ElemType>& a, const bool isColWise) { a.VectorNormInf(*this, isColWise); return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignInnerProductOf(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, const bool isColWise) { InnerProduct(a, b, *this, isColWise); return *this; } //column-wise crossproduct template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignKhatriRaoProductOf(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b) { if (a.IsEmpty() || b.IsEmpty()) LogicError("AssignKhatriRaoProductOf: Matrix is empty."); long cols = (long) a.GetNumCols(); if (cols != b.GetNumCols()) InvalidArgument("a.GetNumCols() != b.GetNumCols()"); long rowsA = (long) a.GetNumRows(); long rowsB = (long) b.GetNumRows(); RequireSize(rowsA * rowsB, cols); #ifdef __INTEL_COMPILER // TODO: check this #pragma simd statement #endif #pragma omp parallel for for (long k = 0; k < cols; k++) { long jj = 0; for (long j = 0; j < rowsB; j++) { for (long i = 0; i < rowsA; i++) { (*this)(jj++, k) = a(i, k) * b(j, k); } } } return *this; } //column-wise reshaped product. Used to compute KhatriRaoProduct Gradient // this = reshape each column of a from (K1xK2,1) to (K1, K2) // if each column of a is not transposed, each (K1, K2) times each column of b (K2, frames). // the output is a (K1, frames) matrix // if each column of a is tranposed, each (K1, K2)^T times each column of b(K1, frames) and output is (K2, frames) template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AddColumnReshapeProductOf(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, const bool transposeAColumn) { if (a.IsEmpty() || b.IsEmpty()) LogicError("AddColumnReshapeProductOf: Matrix is empty."); long cols = (long) a.GetNumCols(); if (cols != b.GetNumCols()) InvalidArgument("AddColumnReshapeProductOf: a.GetNumCols() != b.GetNumCols()"); long rowsA = (long) a.GetNumRows(); long rowsB = (long) b.GetNumRows(); if (rowsA % rowsB != 0) InvalidArgument("AddColumnReshapeProductOf: number of rows in a should be multiples of that in b."); long rowsC = rowsA / rowsB; if (rowsC != GetNumRows() || cols != GetNumCols()) InvalidArgument("AddColumnReshapeProductOf: This matrix does not have the right size."); auto& us = *this; if (transposeAColumn) { // find nrows and ncols of tbe reshaped a long nrows = rowsB; long ncols = rowsC; #ifdef __INTEL_COMPILER // TODO: check this #pragma simd statement #endif #pragma omp parallel for foreach_column (t, a) { size_t k = 0; for (size_t j = 0; j < ncols; j++) // row and col is transposed { ElemType v = 0; for (size_t i = 0; i < nrows; i++) { v += a(k, t) * b(i, t); k++; } us(j, t) += v; } } } else { size_t ncols = rowsB; size_t nrows = rowsC; #ifdef __INTEL_COMPILER // TODO: check this #pragma simd statement #endif #pragma omp parallel for foreach_column (t, a) { size_t k = 0; for (size_t j = 0; j < ncols; j++) { for (size_t i = 0; i < nrows; i++) { us(i, t) += a(k, t) * b(j, t); k++; } } } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AddWithScaleOf(ElemType alpha, const CPUMatrix<ElemType>& a) { ScaleAndAdd(alpha, a, *this); return *this; } template <class ElemType> ElemType CPUMatrix<ElemType>::FrobeniusNorm() const { if (IsEmpty()) LogicError("FrobeniusNorm: Matrix is empty."); ElemType v = 0; long m = (long) GetNumElements(); ElemType* bufPtr = Data(); //four-way unrolling #pragma omp parallel for reduction(+ : v) for (long i = 0; i < (m & ~3); i += 4) { v += bufPtr[i] * bufPtr[i] + bufPtr[i + 1] * bufPtr[i + 1] + bufPtr[i + 2] * bufPtr[i + 2] + bufPtr[i + 3] * bufPtr[i + 3]; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { v += bufPtr[i] * bufPtr[i]; } return sqrt(v); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignFrobeniusNormOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignFrobeniusNormOf: Matrix a is empty."); auto& us = *this; us.RequireSize(1, 1); us(0, 0) = a.FrobeniusNorm(); return us; } template <class ElemType> ElemType CPUMatrix<ElemType>::MatrixNormInf() const { if (IsEmpty()) LogicError("MatrixNormInf: Matrix is empty."); auto& us = *this; ElemType v = 0; #pragma omp parallel for foreach_coord (i, j, us) { #pragma omp critical { v = std::max(v, abs(us(i, j))); } } return v; } template <class ElemType> ElemType CPUMatrix<ElemType>::MatrixNorm0() const { if (IsEmpty()) LogicError("MatrixNorm0: Matrix is empty."); auto& us = *this; ElemType v = 0; #pragma omp parallel for foreach_coord (i, j, us) { if (us(i, j) != 0) { #pragma omp critical { ++v; } } } return v; } template <class ElemType> ElemType CPUMatrix<ElemType>::MatrixNorm1() const { if (IsEmpty()) LogicError("MatrixNorm1: Matrix is empty."); auto& us = *this; ElemType sum = 0; #pragma omp parallel for reduction(+ : sum) foreach_coord (i, j, us) { sum += abs(us(i, j)); } return sum; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignSignOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignSignOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); #pragma omp parallel for foreach_column (j, us) { foreach_row (i, us) { ElemType v = a(i, j); if (!std::isnan(v)) us(i, j) = (v == (ElemType) 0 ? (ElemType) 0 : (v > 0 ? (ElemType) 1 : (ElemType)(-1))); else us(i, j) = v; } } return us; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AddSignOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AddSignOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); #pragma omp parallel for foreach_column (j, us) { foreach_row (i, us) { ElemType v = a(i, j); if (!std::isnan(v)) us(i, j) += (v == (ElemType) 0 ? (ElemType) 0 : (v > 0 ? (ElemType) 1 : (ElemType)(-1))); else us(i, j) = v; } } return us; } //I decided to use CPUMatrix<ElemType>& maxIndexes instead of integer vector because the result may be used to do additional calculation template <class ElemType> void CPUMatrix<ElemType>::VectorMax(CPUMatrix<ElemType>& maxIndexes, CPUMatrix<ElemType>& maxValues, const bool isColWise, int topK) const { if (IsEmpty()) LogicError("VectorMax: Matrix is empty."); auto& us = *this; const int m = (int) GetNumRows(); const int n = (int) GetNumCols(); if (topK > m) InvalidArgument("VectorMax: TopK must be less or equal than the number of rows"); assert(m > 0 && n > 0); // converting from size_t to int may cause overflow if (isColWise) // col-wise { maxValues.RequireSize(topK, n); maxIndexes.RequireSize(topK, n); if (topK == 1) { #pragma omp parallel for for (int j = 0; j < n; j++) { ElemType v = us(0, j); size_t index = 0; foreach_row (i, us) { if (v < us(i, j)) { index = i; v = us(i, j); } } maxValues(0, j) = v; maxIndexes(0, j) = (ElemType) index; } } else { std::vector<int> indices(m); int i = 0; std::generate(indices.begin(), indices.end(), [&i] { return i++; }); const ElemType* curVal = Data(); ElemType* curIdx = maxIndexes.Data(); ElemType* curMax = maxValues.Data(); for (int icol = 0; icol < n; icol++, curVal += m, curIdx += topK, curMax += topK) { // Partial sort, descending order. std::nth_element(indices.begin(), indices.begin() + topK, indices.end(), [curVal](const int& a, const int& b) { return curVal[a] > curVal[b]; }); // REVIEW alexeyk: the following produces warning (see SCL_SECURE_NO_WARNINGS) so use loop instead. // std::transform(indices.begin(), indices.begin() + topK, curIdx, [](const int& a) { return static_cast<ElemType>(a); }); for (int i2 = 0; i2 < topK; i2++) { curIdx[i2] = static_cast<ElemType>(indices[i2]); curMax[i2] = curVal[indices[i2]]; } } } } else { if (topK > 1) RuntimeError("Row-wise TopK max is not supported."); maxValues.RequireSize(m, 1); maxIndexes.RequireSize(m, 1); #pragma omp parallel for for (int i = 0; i < m; i++) { ElemType v = us(i, 0); size_t index = 0; foreach_column (j, us) { if (v < us(i, j)) { index = j; v = us(i, j); } } maxValues(i, 0) = v; maxIndexes(i, 0) = (ElemType) index; } } } template <class ElemType> void CPUMatrix<ElemType>::VectorMin(CPUMatrix<ElemType>& minIndexes, CPUMatrix<ElemType>& minValues, const bool isColWise) const { if (IsEmpty()) LogicError("VectorMin: Matrix is empty."); auto& us = *this; const int m = (int) GetNumRows(); const int n = (int) GetNumCols(); assert(m > 0 && n > 0); // converting from size_t to int may cause overflow if (isColWise) // col-wise { minValues.RequireSize(1, n); minIndexes.RequireSize(1, n); #pragma omp parallel for for (int j = 0; j < n; j++) { ElemType v = us(0, j); size_t index = 0; foreach_row (i, us) { if (v > us(i, j)) { index = i; v = us(i, j); } } minValues(0, j) = v; minIndexes(0, j) = (ElemType) index; } } else { minValues.RequireSize(m, 1); minIndexes.RequireSize(m, 1); #pragma omp parallel for for (int i = 0; i < m; i++) { ElemType v = us(i, 0); size_t index = 0; foreach_column (j, us) { if (v > us(i, j)) { index = j; v = us(i, j); } } minValues(i, 0) = v; minIndexes(i, 0) = (ElemType) index; } } } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignNumOfDiff(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, bool searchInCol) { if (a.GetNumCols() != b.GetNumCols()) throw std::invalid_argument("AssignNumOfDiff: a and b must have the same number of columns."); if (!searchInCol && a.GetNumRows() != b.GetNumRows()) throw std::invalid_argument("AssignNumOfDiff: a and b must have the same number of rows."); ElemType n = 0; if (!searchInCol) { foreach_coord (i, j, a) { n += (a(i, j) != b(i, j)); } } else { size_t crow = b.GetNumRows(); const ElemType* curCol = b.Data(); for (size_t icol = 0; icol < a.GetNumCols(); icol++, curCol += crow) { auto res = std::find(curCol, curCol + crow, a(0, icol)); if (res == curCol + crow) n++; } } RequireSize(1, 1); // result should be one element (*this)(0, 0) = n; return *this; } #pragma endregion Member BLAS Functions #pragma region Other helper Functions struct PrintRange { // print from begin to skipBegin, then from skipEnd to end // skipBegin = end if no split size_t begin; size_t skipBegin; size_t skipEnd; size_t end; bool IsEmpty() const { return end <= begin; } // examples: // * 3..10 // * -3..-3: include end-3..end and 0..3 PrintRange(ptrdiff_t first, ptrdiff_t last, size_t total) { if (first >= 0 && last >= 0) { begin = (size_t)first; end = (size_t)last + 1; if (end > total) // allow INT_MAX, meaning to end end = total; skipBegin = end; skipEnd = end; } else if (first < 0 && last < 0) { begin = 0; skipBegin = (size_t)(-last); skipEnd = (size_t)(total + first); if (skipEnd <= skipBegin) skipBegin = skipEnd = total; end = total; } else // if other combinations are ever of interest then implement them here LogicError("Print: Bounds must be either both positive or both negative."); } }; // use negative ranges to print corners, e.g. Print("name", -3, -3, -3, -3) will print the first 3 and last 3 rows/cols template <class ElemType> void CPUMatrix<ElemType>::Print(const char* matrixName, ptrdiff_t rowFirst, ptrdiff_t rowLast, ptrdiff_t colFirst, ptrdiff_t colLast) const { fprintf(stderr, "\n###### "); if (matrixName != nullptr) fprintf(stderr, "%s ", matrixName); fprintf(stderr, "(%lu, %lu)", (unsigned long)GetNumRows(), (unsigned long)GetNumCols()); if (rowFirst != 0 || colFirst != 0 || (size_t)(rowLast + 1) != GetNumRows() || (size_t)(colLast + 1) != GetNumCols()) fprintf(stderr, " [%ld:%ld, %ld:%ld]", (long)rowFirst, (long)rowLast, (long)colFirst, (long)colLast); fprintf(stderr, " ######\n\n"); if (IsEmpty()) { fprintf(stderr, "(empty)\n"); return; } PrintRange rowRange(rowFirst, rowLast, GetNumRows()); PrintRange colRange(colFirst, colLast, GetNumCols()); if (rowRange.IsEmpty() || colRange.IsEmpty()) { fprintf(stderr, "(empty)\n"); return; } const auto& us = *this; if (rowRange.begin > 0) fprintf(stderr, "...\n"); for (size_t i = rowRange.begin; i < rowRange.end; i++) { if (i == rowRange.skipBegin) // insert ... between the two blocks if any { fprintf(stderr, "...\n"); i = rowRange.skipEnd; } if (colRange.begin > 0) // ... at line start fprintf(stderr, "...\t"); for (size_t j = colRange.begin; j < colRange.end; j++) { if (j == colRange.skipBegin) { fprintf(stderr, "...\t"); j = colRange.skipEnd; } fprintf(stderr, "%.10f\t", us(i, j)); } if (colRange.end < GetNumCols()) // ... at line end fprintf(stderr, "..."); fprintf(stderr, "\n"); } if (rowRange.end < GetNumRows()) fprintf(stderr, "...\n"); } template <class ElemType> void CPUMatrix<ElemType>::Print(const char* matrixName /*=nullptr*/) const { Print(matrixName, 0, GetNumRows() - 1, 0, GetNumCols() - 1); } // file I/O //matrixName is used to verify that correct matrix is read. template <class ElemType> void CPUMatrix<ElemType>::ReadFromFile(FILE*, const char* /*matrixName*/) { RuntimeError("not implemented."); } //matrixName is used to verify that correct matrix is read. template <class ElemType> void CPUMatrix<ElemType>::WriteToFile(FILE*, const char* /*matrixName*/) { RuntimeError("not implemented."); } //assume each column is an input sample. Each sample is stored in [channel, row, col] (r00, g00, b00, r01, g01, b01, r10, g10, b10, r11, g11, b11) template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignPackedConvolutionInput(const CPUMatrix<ElemType>& inputSubBatch, const size_t inputWidth, const size_t inputHeight, const size_t inputChannels, const size_t outputWidth, const size_t outputHeight, const size_t /*outputChannels*/, const size_t kernelWidth, const size_t kernelHeight, const size_t horizontalSubsample, const size_t verticalSubsample, const bool zeroPadding) { if (verticalSubsample > kernelHeight || horizontalSubsample > kernelWidth) LogicError("Arguments verticalSubsample (or horitzontalSubsample) must be less or equal than kernelHeight (or kernelWidth)."); const size_t packedInputRows = kernelWidth * kernelHeight * inputChannels; const size_t packedInputColsPerSample = outputWidth * outputHeight; // output size per channel const size_t inputDim = inputWidth * inputHeight * inputChannels; const size_t smallBatchSize = inputSubBatch.GetNumCols(); const long inputHeightTimesChannel = (long) (inputHeight * inputChannels); RequireSize(packedInputRows, packedInputColsPerSample * smallBatchSize); if (zeroPadding) SetValue((ElemType) 0); const long halfKernelWidth = (long) kernelWidth / 2; const long halfKernelHeight = (long) kernelHeight / 2; #pragma omp parallel for // each input element is copied to many places for (long sample = 0; sample < smallBatchSize; sample++) { for (long id = 0; id < inputDim; id++) { // IN_ELEM_ROWPOS(channel, row, col) = (channel + (row + col * inputHeight) * inputChannels) // IN_ELEM_COLPOS = sample const long y = id / inputHeightTimesChannel; // inputCol const long nXC = id % inputHeightTimesChannel; // channel + inputRow*inputChannels const long x = nXC / (long) inputChannels; // inputRow const long c = nXC % (long) inputChannels; // channel long x0 = 0, y0 = 0, x1 = 0, y1 = 0; if (zeroPadding) { x0 = (long) max((ElemType)0, ceil((x - (ElemType)kernelHeight + 1.0f + halfKernelHeight) / (ElemType)verticalSubsample)); // row : first wrow in which x is in x1 = (long) (x + halfKernelHeight - x0 * verticalSubsample); // first posxInKernel y0 = (long) max((ElemType)0, ceil((y - (ElemType)kernelWidth + 1.0f + halfKernelWidth) / (ElemType)horizontalSubsample)); // col : first wcol in which y is in y1 = (long) (y + halfKernelWidth - y0 * horizontalSubsample); // first posyInKernel } else { x0 = (long) max((ElemType)0, ceil((x - (ElemType)kernelHeight + 1) / (ElemType)verticalSubsample)); // row : first wrow in which x is in x1 = (long) (x - x0 * verticalSubsample); // first posxInKernel y0 = (long) max((ElemType)0, ceil((y - (ElemType)kernelWidth + 1) / (ElemType)horizontalSubsample)); // col : first wcol in which y is in y1 = (long) (y - y0 * horizontalSubsample); // first posyInKernel } assert(x1 >= 0 && x1 < kernelHeight && y1 >= 0 && y1 < kernelWidth); // PACK_ELEM_ROWPOS(channel, posxInKernel, posyInKernel) = (channel * kernelWidth * kernelHeight + posxInKernel + posyInKernel * kernelHeight) // PACK_ELEM_COLPOS(sample, wrow, wcol) = (sample*packedInputColsPerSample + outputHeight*wcol + wrow ElemType currentInputValue = inputSubBatch(id, sample); long packColBase = (long) (sample * packedInputColsPerSample + y0 * outputHeight); for (long wcol = y0, posyInKernel = y1; wcol < (long) outputWidth && posyInKernel >= 0; wcol++, posyInKernel -= (long) horizontalSubsample) { long packRowBase = (long) (c * kernelWidth * kernelHeight + posyInKernel * kernelHeight); for (long wrow = x0, posxInKernel = x1; wrow < (long) outputHeight && posxInKernel >= 0; wrow++, posxInKernel -= (long) verticalSubsample) { const long packRow = packRowBase + posxInKernel; const long packCol = packColBase + wrow; (*this)(packRow, packCol) = currentInputValue; } packColBase += (long) outputHeight; } } } return *this; } //assume each column is an input sample. Each sample is stored in [channel, row, col] (r00, g00, b00, r01, g01, b01, r10, g10, b10, r11, g11, b11) template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::UnpackConvolutionInput(CPUMatrix<ElemType>& inputSubBatch, const size_t inputWidth, const size_t inputHeight, const size_t inputChannels, const size_t outputWidth, const size_t outputHeight, const size_t /*outputChannels*/, const size_t kernelWidth, const size_t kernelHeight, const size_t horizontalSubsample, const size_t verticalSubsample, const bool zeroPadding) const { if (verticalSubsample > kernelHeight || horizontalSubsample > kernelWidth) LogicError("Arguments verticalSubsample (or horizonSubsample) must be less than or equal to kernelHeight (or kernelWidth)."); const size_t packedInputColsPerSample = outputWidth * outputHeight; // output size per channel const size_t inputDim = inputWidth * inputHeight * inputChannels; const size_t smallBatchSize = inputSubBatch.GetNumCols(); const long inputHeightTimesChannel = (long) (inputHeight * inputChannels); const long halfKernelWidth = (long) kernelWidth / 2; const long halfKernelHeight = (long) kernelHeight / 2; #pragma omp parallel for // each input element is copied to many places for (long sample = 0; sample < smallBatchSize; sample++) { for (long id = 0; id < inputDim; id++) { // IN_ELEM_ROWPOS(channel, row, col) = (channel + (row + col * inputHeight) * inputChannels) // IN_ELEM_COLPOS = sample const long y = id / inputHeightTimesChannel; // inputCol const long nXC = id % inputHeightTimesChannel; // channel + inputRow*inputChannels const long x = nXC / (long) inputChannels; // inputRow const long c = nXC % (long) inputChannels; // channel long x0 = 0, y0 = 0, x1 = 0, y1 = 0; if (zeroPadding) { x0 = (long) max((ElemType)0, ceil((x - (ElemType) kernelHeight + 1.0f + halfKernelHeight) / (ElemType) verticalSubsample)); // row : first wrow in which x is in x1 = (long) (x + halfKernelHeight - x0 * verticalSubsample); // first posxInKernel y0 = (long) max((ElemType)0, ceil((y - (ElemType) kernelWidth + 1.0f + halfKernelWidth) / (ElemType) horizontalSubsample)); // col : first wcol in which y is in y1 = (long) (y + halfKernelWidth - y0 * horizontalSubsample); // first posyInKernel } else { x0 = (long) max((ElemType)0, ceil((x - (ElemType) kernelHeight + 1) / (ElemType) verticalSubsample)); // row : first wrow in which x is in x1 = (long) (x - x0 * verticalSubsample); // first posxInKernel y0 = (long) max((ElemType)0, ceil((y - (ElemType) kernelWidth + 1) / (ElemType) horizontalSubsample)); // col : first wcol in which y is in y1 = (long) (y - y0 * horizontalSubsample); // first posyInKernel } assert(x1 >= 0 && x1 < kernelHeight && y1 >= 0 && y1 < kernelWidth); // PACK_ELEM_ROWPOS(channel, posxInKernel, posyInKernel) = (channel * kernelWidth * kernelHeight + posxInKernel + posyInKernel * kernelHeight) // PACK_ELEM_COLPOS(sample, wrow, wcol) = (sample*packedInputColsPerSample + outputHeight*wcol + wrow ElemType currentInputValue = inputSubBatch(id, sample); long packColBase = (long) (sample * packedInputColsPerSample + y0 * outputHeight); for (long wcol = y0, posyInKernel = y1; wcol < (long) outputWidth && posyInKernel >= 0; wcol++, posyInKernel -= (long) horizontalSubsample) { long packRowBase = (long) (c * kernelWidth * kernelHeight + posyInKernel * kernelHeight); for (long wrow = x0, posxInKernel = x1; wrow < (long) outputHeight && posxInKernel >= 0; wrow++, posxInKernel -= (long) verticalSubsample) { const long packRow = packRowBase + posxInKernel; const long packCol = packColBase + wrow; currentInputValue += (*this)(packRow, packCol); } packColBase += (long) outputHeight; } inputSubBatch(id, sample) = currentInputValue; } } return inputSubBatch; } //assume each column is an input sample. Each sample is stored in (r00, g00, b00, r01, g01, b01, r10, g10, b10, r11, g11, b11) template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignMaxPoolingResult(const CPUMatrix<ElemType>& inputBatch, const size_t channels, const size_t /*inputWidth*/, const size_t inputHeight, const size_t /*inputSizePerSample*/, const size_t /*outputWidth*/, const size_t outputHeight, const size_t outputSizePerSample, const size_t windowWidth, const size_t windowHeight, const size_t horizontalSubsample, const size_t verticalSubsample) { const long inputHeightTimesChannel = (long) (inputHeight * channels); const long outputHeightTimesChannel = (long) (outputHeight * channels); const size_t batchSize = inputBatch.GetNumCols(); RequireSize(outputSizePerSample, batchSize); // IN_ELEM_ROWPOS(channel, row, col) = (channel + (row + col * inputHeight) * channels) // IN_ELEM_COLPOS = sample // OUT_ELEM_ROWPOS(channel, wrow, wcol) = (channel + (wrow + wcol * outputHeight) * channels) // OUT_ELEM_COLPOS = sample #pragma omp parallel for for (long sample = 0; sample < (long) batchSize; sample++) { for (long outputIndexWithinSample = 0; outputIndexWithinSample < outputSizePerSample; outputIndexWithinSample++) { const long y = outputIndexWithinSample / outputHeightTimesChannel; // wcol const long nXC = outputIndexWithinSample % outputHeightTimesChannel; // channel + wrow*channels const long x = (long) (nXC / channels); // wrow const long c = (long) (nXC % channels); // channel ElemType maxVal = -FLT_MAX; ElemType minVal = FLT_MAX; const long rowInWindowBase = (long) ((x * verticalSubsample + y * horizontalSubsample * inputHeight) * channels + c); for (long colInWindow = 0; colInWindow < windowWidth; colInWindow++) { long rowInInput = rowInWindowBase + colInWindow * inputHeightTimesChannel; for (long rowInWindow = 0; rowInWindow < windowHeight; rowInWindow++) { const ElemType val = inputBatch(rowInInput, sample); // pf[rowInWindow*channels]; maxVal = std::max(maxVal, val); minVal = std::min(minVal, val); rowInInput += (long) channels; } } (*this)(outputIndexWithinSample, sample) = maxVal; } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AddMaxPoolingGradient(const CPUMatrix<ElemType>& outputGradientBatch, const CPUMatrix<ElemType>& inputBatch, const CPUMatrix<ElemType>& outputBatch, const size_t channels, const size_t /*inputWidth*/, const size_t inputHeight, const size_t inputSizePerSample, const size_t outputWidth, const size_t outputHeight, const size_t /*outputSizePerSample*/, const size_t windowWidth, const size_t windowHeight, const size_t horizontalSubsample, const size_t verticalSubsample) { size_t batchSize = inputBatch.GetNumCols(); const long inputHeightTimesChannel = (long) (inputHeight * channels); const long outputHeightTimesChannel = (long) (outputHeight * channels); // IN_ELEM_ROWPOS(channel, row, col) = (channel + (row + col * inputHeight) * channels) // IN_ELEM_COLPOS = sample // OUT_ELEM_ROWPOS(channel, wrow, wcol) = (channel + (wrow + wcol * outputHeight) * channels) // OUT_ELEM_COLPOS = sample #pragma omp parallel for for (long sample = 0; sample < batchSize; sample++) { for (long inputIndexWithinSample = 0; inputIndexWithinSample < inputSizePerSample; inputIndexWithinSample++) { const long y = inputIndexWithinSample / inputHeightTimesChannel; // col in input const long nXC = inputIndexWithinSample % inputHeightTimesChannel; // channel + row*chanels const long x = (long) (nXC / channels); // row in input const long c = (long) (nXC % channels); // channel long startOutX = (long) max((ElemType)0, ceil((x - (ElemType) windowHeight + 1) / (ElemType) verticalSubsample)); // inclusive start long endOutX = (long) ((x / verticalSubsample < outputHeight - 1) ? x / verticalSubsample : outputHeight - 1); // inclusive end long startOutY = (long) max((ElemType)0, ceil((y - (ElemType) windowWidth + 1) / (ElemType) horizontalSubsample)); // inclusive start long endOutY = (long) ((y / horizontalSubsample < outputWidth - 1) ? y / horizontalSubsample : outputWidth - 1); // inclusive end ElemType inputValue = inputBatch(inputIndexWithinSample, sample); for (long outY = startOutY; outY <= endOutY; outY++) { for (long outX = startOutX; outX <= endOutX; outX++) { long outputIndex = (long) (outY * outputHeightTimesChannel + outX * channels + c); if (inputValue == outputBatch(outputIndex, sample)) (*this)(inputIndexWithinSample, sample) += outputGradientBatch(outputIndex, sample); } } } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignAveragePoolingResult(const CPUMatrix<ElemType>& inputBatch, const size_t channels, const size_t /*inputWidth*/, const size_t inputHeight, const size_t /*inputSizePerSample*/, const size_t /*outputWidth*/, const size_t outputHeight, const size_t outputSizePerSample, const size_t windowWidth, const size_t windowHeight, const size_t horizontalSubsample, const size_t verticalSubsample) { const long inputHeightTimesChannel = (long) (inputHeight * channels); const long outputHeightTimesChannel = (long) (outputHeight * channels); const size_t batchSize = inputBatch.GetNumCols(); const size_t windowSize = windowWidth * windowHeight; RequireSize(outputSizePerSample, batchSize); // IN_ELEM_ROWPOS(channel, row, col) = (channel + (row + col * inputHeight) * channels) // IN_ELEM_COLPOS = sample // OUT_ELEM_ROWPOS(channel, wrow, wcol) = (channel + (wrow + wcol * outputHeight) * channels) // OUT_ELEM_COLPOS = sample #pragma omp parallel for for (long sample = 0; sample < batchSize; sample++) { for (long outputIndexWithinSample = 0; outputIndexWithinSample < outputSizePerSample; outputIndexWithinSample++) { const long y = outputIndexWithinSample / outputHeightTimesChannel; // wcol const long nXC = outputIndexWithinSample % outputHeightTimesChannel; // channel + wrow*channels const long x = (long) (nXC / channels); // wrow const long c = (long) (nXC % channels); // channel ElemType sum = 0; const long rowInWindowBase = (long) ((x * verticalSubsample + y * horizontalSubsample * inputHeight) * channels + c); for (long colInWindow = 0; colInWindow < windowWidth; colInWindow++) { long rowInInput = rowInWindowBase + colInWindow * inputHeightTimesChannel; for (long rowInWindow = 0; rowInWindow < windowHeight; rowInWindow++) { sum += inputBatch(rowInInput, sample); rowInInput += (long) channels; } } (*this)(outputIndexWithinSample, sample) = sum / windowSize; } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AddAveragePoolingGradient(const CPUMatrix<ElemType>& outputGradientBatch, const size_t channels, const size_t /*inputWidth*/, const size_t inputHeight, const size_t inputSizePerSample, const size_t outputWidth, const size_t outputHeight, const size_t /*outputSizePerSample*/, const size_t windowWidth, const size_t windowHeight, const size_t horizontalSubsample, const size_t verticalSubsample) { size_t batchSize = outputGradientBatch.GetNumCols(); const long inputHeightTimesChannel = (long) (inputHeight * channels); const long outputHeightTimesChannel = (long) (outputHeight * channels); const long windowSize = (long) (windowWidth * windowHeight); // IN_ELEM_ROWPOS(channel, row, col) = (channel + (row + col * inputHeight) * channels) // IN_ELEM_COLPOS = sample // OUT_ELEM_ROWPOS(channel, wrow, wcol) = (channel + (wrow + wcol * outputHeight) * channels) // OUT_ELEM_COLPOS = sample #pragma omp parallel for for (long sample = 0; sample < batchSize; sample++) { for (long inputIndexWithinSample = 0; inputIndexWithinSample < inputSizePerSample; inputIndexWithinSample++) { const long y = inputIndexWithinSample / inputHeightTimesChannel; // col in input const long nXC = inputIndexWithinSample % inputHeightTimesChannel; // channel + row*chanels const long x = nXC / (long) channels; // row in input const long c = nXC % (long) channels; // channel long startOutX = (long) max((ElemType)0, ceil((x - (ElemType) windowHeight + 1) / (ElemType) verticalSubsample)); // inclusive start long endOutX = (long) ((x / verticalSubsample < outputHeight - 1) ? x / (long) verticalSubsample : outputHeight - 1); // inclusive end long startOutY = (long) max((ElemType)0, ceil((y - (ElemType) windowWidth + 1) / (ElemType) horizontalSubsample)); // inclusive start long endOutY = (long) ((y / horizontalSubsample < outputWidth - 1) ? y / horizontalSubsample : outputWidth - 1); // inclusive end for (long outY = startOutY; outY <= endOutY; outY++) { for (long outX = startOutX; outX <= endOutX; outX++) { long outputIndex = outY * outputHeightTimesChannel + outX * (long) channels + c; (*this)(inputIndexWithinSample, sample) += outputGradientBatch(outputIndex, sample) / windowSize; } } } } return *this; } #pragma endregion Other Helper Functions template <class ElemType> void CPUMatrix<ElemType>::ConvolutionForward(const CPUMatrix<ElemType>& kernel, const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowIwht, const CPUMatrix<int>& mpRowRun, const CPUMatrix<int>& runs, CPUMatrix<ElemType>& output) const { #pragma omp parallel for for (int64_t sample = 0; sample < (int64_t)output.GetNumCols(); sample++) { for (size_t row = 0; row < output.GetNumRows(); row++) { int colBase = mpRowCol(row, 0); int ivBase = mpRowIwht(row, 0); assert(0 <= colBase && colBase < GetNumRows()); ElemType sum = 0; int i0 = mpRowRun(row, 0); int skip = runs(i0++, 0); int size = runs(i0++, 0); int imask = i0 + size; for (int i = 0; i < size; i++) { if (runs(imask + i, 0) == 0) continue; int dcol = runs(i0 + i, 0); assert(0 <= colBase + dcol && colBase + dcol < GetNumRows()); sum += kernel.Data()[ivBase + skip + i] * (*this)(colBase + dcol, sample); } output(row, sample) = sum; } } } template <class ElemType> void CPUMatrix<ElemType>::ConvolutionBackwardData(const CPUMatrix<ElemType>& kernel, const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowIwht, const CPUMatrix<int>& mpRowRun, const CPUMatrix<int>& runs, CPUMatrix<ElemType>& grad) const { #pragma omp parallel for for (int64_t sample = 0; sample < (int64_t)GetNumCols(); sample++) { for (size_t row = 0; row < GetNumRows(); row++) { int colBase = mpRowCol(row, 0); int ivBase = mpRowIwht(row, 0); assert(0 <= colBase && colBase < grad.GetNumRows()); ElemType curGrad = (*this)(row, sample); int i0 = mpRowRun(row, 0); int skip = runs(i0++, 0); int size = runs(i0++, 0); int imask = i0 + size; for (int i = 0; i < size; i++) { if (runs(imask + i, 0) == 0) continue; int dcol = runs(i0 + i, 0); assert(0 <= colBase + dcol && colBase + dcol < grad.GetNumRows()); grad(colBase + dcol, sample) += curGrad * kernel.Data()[ivBase + skip + i]; } } } } template <class ElemType> void CPUMatrix<ElemType>::ConvolutionBackwardKernel(const CPUMatrix<ElemType>& in, const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowIwht, const CPUMatrix<int>& mpRowRun, const CPUMatrix<int>& runs, CPUMatrix<ElemType>& kernelGrad) const { // Do NOT parallelize these loops! for (size_t sample = 0; sample < GetNumCols(); sample++) { for (size_t row = 0; row < GetNumRows(); row++) { int colBase = mpRowCol(row, 0); int ivBase = mpRowIwht(row, 0); assert(0 <= colBase && colBase < in.GetNumRows()); ElemType curGrad = (*this)(row, sample); int i0 = mpRowRun(row, 0); int skip = runs(i0++, 0); int size = runs(i0++, 0); int imask = i0 + size; for (int i = 0; i < size; i++) { if (runs(imask + i, 0) == 0) continue; int dcol = runs(i0 + i, 0); assert(0 <= colBase + dcol && colBase + dcol < in.GetNumRows()); kernelGrad.Data()[ivBase + skip + i] += curGrad * in(colBase + dcol, sample); } } } } template <class ElemType> void CPUMatrix<ElemType>::UnrollConvolutionInput(size_t unrollCols, size_t mapOutSize, const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowRun, const CPUMatrix<int>& runs, CPUMatrix<ElemType>& output) const { size_t batchSize = GetNumCols(); #pragma omp parallel for for (int64_t sample = 0; sample < (int64_t)batchSize; sample++) { for (size_t row = 0; row < mapOutSize; row++) { int colBase = mpRowCol(row, 0); assert(0 <= colBase && colBase < GetNumRows()); int i0 = mpRowRun(row, 0); int skip = runs(i0++, 0); int size = runs(i0++, 0); int imask = i0 + size; for (int i = 0; i < size; i++) { if (runs(imask + i, 0) == 0) continue; int dcol = runs(i0 + i, 0); assert(0 <= colBase + dcol && colBase + dcol < GetNumRows()); output.Data()[(row * batchSize + sample) * unrollCols + skip + i] = (*this)(colBase + dcol, sample); } } } } template <class ElemType> void CPUMatrix<ElemType>::UnrollConvolutionOutput(size_t unrollCols, size_t mapInCount, size_t mapOutCount, const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowRun, const CPUMatrix<int>& runs, CPUMatrix<ElemType>& output) const { if (mpRowCol.GetNumRows() % mapOutCount != 0) InvalidArgument("The number of rows in mpRowCol must be multiple of mapOutCount."); size_t mapOutSize = mpRowCol.GetNumRows() / mapOutCount; size_t batchSize = GetNumCols(); size_t kernelSize = runs(1, 0); if (kernelSize % mapInCount != 0) InvalidArgument("kernelSize must be multiple of mapInCount."); size_t kernelMapSize = kernelSize / mapInCount; #pragma omp parallel for for (int64_t sample = 0; sample < (int64_t)GetNumCols(); sample++) { for (size_t row = 0; row < mapOutSize; row++) { int colBase = mpRowCol(row, 0); int i0 = mpRowRun(row, 0); int skip = runs(i0++, 0); int size = runs(i0++, 0); int imask = i0 + size; for (int i = 0; i < std::min(size, (int)kernelMapSize); i++) { if (runs(imask + i, 0) == 0) continue; int dcol = runs(i0 + i, 0); size_t isrc = row; size_t idst = ((colBase + dcol) * batchSize + sample) * unrollCols + ((skip + i) % kernelMapSize) * mapOutCount; for (size_t outMap = 0; outMap < mapOutCount; outMap++, isrc += mapOutSize) { assert(isrc < GetNumElements()); assert(idst + outMap < output.GetNumElements()); output.Data()[idst + outMap] = (*this)(isrc, sample); } } } } } template <class ElemType> void CPUMatrix<ElemType>::UnrollConvolutionInputForKernelBackprop(size_t mapOutSize, const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowRun, const CPUMatrix<int>& runs, CPUMatrix<ElemType>& output) const { size_t batchSize = GetNumCols(); size_t unrollCols = mapOutSize * batchSize; #pragma omp parallel for for (int64_t sample = 0; sample < (int64_t)batchSize; sample++) { for (size_t row = 0; row < mapOutSize; row++) { int colBase = mpRowCol(row, 0); assert(0 <= colBase && colBase < GetNumRows()); int i0 = mpRowRun(row, 0); int skip = runs(i0++, 0); int size = runs(i0++, 0); int imask = i0 + size; for (int i = 0; i < size; i++) { if (runs(imask + i, 0) == 0) continue; int dcol = runs(i0 + i, 0); assert(0 <= colBase + dcol && colBase + dcol < GetNumRows()); size_t idst = (skip + i) * unrollCols + row * batchSize + sample; assert(idst < output.GetNumElements()); output.Data()[idst] = (*this)(colBase + dcol, sample); } } } } template <class ElemType> void CPUMatrix<ElemType>::MaxPoolingForward(const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowIndices, const CPUMatrix<int>& indices, CPUMatrix<ElemType>& output) const { #pragma omp parallel for for (int64_t sample = 0; sample < (int64_t)output.GetNumCols(); sample++) { for (size_t row = 0; row < output.GetNumRows(); row++) { int colBase = mpRowCol(row, 0); assert(0 <= colBase && colBase < GetNumRows()); assert(std::numeric_limits<ElemType>::has_infinity); ElemType res = -std::numeric_limits<ElemType>::infinity(); int i0 = mpRowIndices(row, 0); int size = indices(i0++, 0); assert(size > 0); for (int i = 0; i < size; i++) { int dcol = indices(i0 + i, 0); assert(0 <= colBase + dcol && colBase + dcol < GetNumRows()); res = std::max(res, (*this)(colBase + dcol, sample)); } output(row, sample) = res; } } } template <class ElemType> void CPUMatrix<ElemType>::MaxPoolingBackward(const CPUMatrix<ElemType>& out, const CPUMatrix<ElemType>& in, const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowIndices, const CPUMatrix<int>& indices, CPUMatrix<ElemType>& grad) const { #pragma omp parallel for for (int64_t sample = 0; sample < (int64_t)GetNumCols(); sample++) { for (size_t row = 0; row < GetNumRows(); row++) { int colBase = mpRowCol(row, 0); assert(0 <= colBase && colBase < grad.GetNumRows()); int i0 = mpRowIndices(row, 0); int size = indices(i0++, 0); assert(size > 0); ElemType g = (*this)(row, sample); ElemType m = out(row, sample); for (int i = 0; i < size; i++) { int dcol = indices(i0 + i, 0); assert(0 <= colBase + dcol && colBase + dcol < grad.GetNumRows()); if (in(colBase + dcol, sample) >= m) { #pragma omp atomic grad(colBase + dcol, sample) += g; break; } } } } } // For each image, for each ROI, this function treats that ROI as an image // and does max pooling so that it has output size pooledHeight x pooledWidth. // It loops over each location in the output tensor, computes which ROI // and image should populate that location, computes the subset of the image // corresponding to the ROI and which pixels in that subset should go into the // output location, then takes the max value over that window. // src: Images [W x H x C x N] // roiData: ROIs [4 x numROIs x N], // dst: Pooled ROIs [PW x PH x C x numROIs x N] // argmax: max positions [PW x PH x C x numROIs x N] // where PW = Pooled Width, PH = Pooled Height, C = Channels, N = Batch Size template <class ElemType> void CPUMatrix<ElemType>::ROIPoolingForward(const size_t numRois, const size_t numImg, const size_t channels, const size_t width, const size_t height, const size_t pooledWidth, const size_t pooledHeight, const CPUMatrix<ElemType>& roiData, CPUMatrix<ElemType>& output, CPUMatrix<ElemType>& argmax) const { size_t roiOutputSize = pooledHeight * pooledWidth * channels; #pragma omp parallel for for (int imgIdx = 0; imgIdx < numImg; imgIdx++) { auto img = ColumnSlice(imgIdx, 1); auto rois = roiData.ColumnSlice(imgIdx, 1); #pragma omp parallel for for (int roiIdx = 0; roiIdx < numRois; roiIdx++) { // each ROI is 4 elements: (x, y, w, h). int base = roiIdx * 4; // scaled ROI numbers (relative to original image size) // roi points are doubles that represent location relative to image ElemType scX = rois(base, (ElemType)0); ElemType scY = rois(base + (ElemType)1, (ElemType)0); ElemType scW = rois(base + (ElemType)2, (ElemType)0); ElemType scH = rois(base + (ElemType)3, (ElemType)0); // compute actual spatial location of the ROI in our featuremap. size_t x = (size_t)round(scX * width); size_t y = (size_t)round(scY * height); ElemType roiW = (ElemType)max(round(scW * width), (ElemType)1); ElemType roiH = (ElemType)max(round(scH * height), (ElemType)1); const ElemType winW = roiW / (ElemType)pooledWidth; const ElemType winH = roiH / (ElemType)pooledHeight; // inspired by Ross Girshick fast-rcnn caffe cpu: https://github.com/rbgirshick/fast-rcnn // loop over spatial locations in output. #pragma omp parallel for for (int outw = 0; outw < pooledWidth; outw++) { for (int outh = 0; outh < pooledHeight; outh++) { // compute the top left corner of the input // spatial window corresponding to this output unit size_t hstart = (size_t)floor(outh * winH); size_t wstart = (size_t)floor(outw * winW); // compute bottom right corner (not included) size_t hend = (size_t)ceil((outh + 1) * winH); size_t wend = (size_t)ceil((outw + 1) * winW); // offset window based on ROI top left corner. // these indices are into the input slice. hstart = min(max(hstart + y, (size_t)0), height); wstart = min(max(wstart + x, (size_t)0), width); hend = min(max(hend + y, (size_t)0), height); wend = min(max(wend + x, (size_t)0), width); bool isempty = (hend <= hstart) || (wend <= wstart); for (size_t c = 0; c < channels; c++) { // [W x H x C x R x N]; R = ROIs per image size_t outputIdx = roiIdx * roiOutputSize + outw + outh * pooledWidth + c * pooledHeight * pooledWidth; size_t maxidx = 0; ElemType maxval = isempty ? (ElemType)0 : -FLT_MAX; size_t baseIdx = c * height * width; for (size_t h = hstart; h < hend; h++) { for (size_t w = wstart; w < wend; w++) { // stored argmax indices are relative to the current channel. size_t dataIdx = w + h * width; if (img(baseIdx + dataIdx, 0) > maxval) { maxval = img(baseIdx + dataIdx, 0); maxidx = dataIdx; } } } output(outputIdx, imgIdx) = maxval; argmax(outputIdx, imgIdx) = maxidx; } } } } } } // This function loops over locations in the input to the ROIPoolingNode (image locations). // It loops over the ROIs corresponding to that image, seeing which ones could contain the current location // in their output. For each ROI, it checks the argmax data to see if that ROI indeed chose // this pixel location as the maximum. If so, it increments the gradient term for the input location. template <class ElemType> void CPUMatrix<ElemType>::ROIPoolingBackward(const size_t numRois, const size_t numImg, const size_t channels, const size_t width, const size_t height, const size_t pooledWidth, const size_t pooledHeight, const CPUMatrix<ElemType>& roiData, CPUMatrix<ElemType>& grad, CPUMatrix<ElemType>& argmax) const { // loop over images in the batch. #pragma omp parallel for for (int imgIdx = 0; imgIdx < numImg; imgIdx++) { // ROIs for this image. length 4*numRois; auto rois = roiData.ColumnSlice(imgIdx, 1).Data(); // gradient values for all ROIs from this image. length numRois*pooledHeight*pooledWidth*channels; auto pooledGrad = ColumnSlice(imgIdx, 1).Data(); auto argmaxCol = argmax.ColumnSlice(imgIdx, 1).Data(); // loop over spatial locations in the image. #pragma omp parallel for for (int w = 0; w < width; w++) { #pragma omp parallel for for (int h = 0; h < width; h++) { // loop over the ROIs seeing which ones contain this location. for (int roiN = 0; roiN < numRois; roiN++) { // each ROI is 4 elements: (x, y, w, h). int roiOffset = roiN * 4; // ROI data is relative to original image size size_t roiStartW = (size_t)round(rois[roiOffset + 0] * width); size_t roiStartH = (size_t)round(rois[roiOffset + 1] * height); size_t roiWidth = max((size_t)round(rois[roiOffset + 2] * width), (size_t)1); size_t roiHeight = max((size_t)round(rois[roiOffset + 3] * height), (size_t)1); // skip this ROI if it doesn't contain the current input location. const bool inROI = (w >= roiStartW && w < roiStartW + roiWidth && h >= roiStartH && h < roiStartH + roiHeight); if (!inROI) continue; ElemType winH = (ElemType)roiHeight / (ElemType)pooledHeight; ElemType winW = (ElemType)roiWidth / (ElemType)pooledWidth; // what pooled nodes in the output for this ROI could have pooled this input location? size_t phstart = (size_t)((h - roiStartH) / winH); size_t pwstart = (size_t)((w - roiStartW) / winW); size_t phend = (size_t)(ceil((h - roiStartH + 1) / winH)); size_t pwend = (size_t)(ceil((w - roiStartW + 1) / winW)); phstart = min(max(phstart, (size_t)0), pooledHeight); phend = min(max(phend, (size_t)0), pooledHeight); pwstart = min(max(pwstart, (size_t)0), pooledWidth); pwend = min(max(pwend, (size_t)0), pooledWidth); for (size_t c = 0; c < channels; c++) { ElemType gradient = 0; // [W x H x C x N] size_t index = w + h*width + c*height*width; // go right up to channel c of the current ROI. size_t offset = (roiN * channels + c) * pooledWidth * pooledHeight; const ElemType* offsetPoolGrad = pooledGrad + offset; const ElemType* offsetArgmax = argmaxCol + offset; for (size_t ph = phstart; ph < phend; ph++) { for (size_t pw = pwstart; pw < pwend; pw++) { if ((size_t)offsetArgmax[ph * pooledWidth + pw] == (w + h * width)) gradient += offsetPoolGrad[ph * pooledWidth + pw]; } } grad(index, imgIdx) = gradient; } } } } } } template <class ElemType> void CPUMatrix<ElemType>::MaxUnpooling(const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowIndices, const CPUMatrix<int>& indices, const CPUMatrix<ElemType>& poolInput, CPUMatrix<ElemType>& input) const { #pragma omp parallel for for (int64_t sample = 0; sample < (int64_t)GetNumCols(); sample++) { for (size_t row = 0; row < GetNumRows(); row++) { int colBase = mpRowCol(row, 0); assert(0 <= colBase && colBase < input.GetNumRows()); int i0 = mpRowIndices(row, 0); int size = indices(i0++, 0); assert(size > 0); ElemType curMax = poolInput(colBase + indices(i0, 0), sample); ElemType prevMax = curMax; int imax = 0; for (int i = 1; i < size; i++) { int dcol = indices(i0 + i, 0); assert(0 <= colBase + dcol && colBase + dcol < poolInput.GetNumRows()); curMax = std::max(curMax, poolInput(colBase + dcol, sample)); if (curMax > prevMax) { prevMax = curMax; imax = i; } } int dcol = indices(i0 + imax, 0); assert(0 <= colBase + dcol && colBase + dcol < input.GetNumRows()); input(colBase + dcol, sample) = (*this)(row, sample); //int i = (int)poolIn(row, sample); //assert(0 <= i && i < size); //int dcol = indices(i0 + i, 0); //assert(0 <= colBase + dcol && colBase + dcol < input.GetNumRows()); //input(colBase + dcol, sample) = (*this)(row, sample); } } } template <class ElemType> void CPUMatrix<ElemType>::AveragePoolingForward(const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowIndices, const CPUMatrix<int>& indices, CPUMatrix<ElemType>& output, const bool poolIncludePad) const { #pragma omp parallel for for (int64_t sample = 0; sample < (int64_t)output.GetNumCols(); sample++) { for (size_t row = 0; row < output.GetNumRows(); row++) { int colBase = mpRowCol(row, 0); assert(0 <= colBase && colBase < GetNumRows()); ElemType sum = 0; int i0 = mpRowIndices(row, 0); int size = indices(i0++, 0); assert(size > 0); for (int i = 0; i < size; i++) { int dcol = indices(i0 + i, 0); assert(0 <= colBase + dcol && colBase + dcol < GetNumRows()); sum += (*this)(colBase + dcol, sample); } // Note that we divide by size which is the number of actual elements (does not include padding). // if poolIncludePad == true, use avg_pool_include_pad if (poolIncludePad) size = indices(0, 0); output(row, sample) = sum / size; } } } template <class ElemType> void CPUMatrix<ElemType>::AveragePoolingBackward(const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowIndices, const CPUMatrix<int>& indices, CPUMatrix<ElemType>& grad, const bool poolIncludePad) const { #pragma omp parallel for for (int64_t sample = 0; sample < (int64_t)GetNumCols(); sample++) { for (size_t row = 0; row < GetNumRows(); row++) { int colBase = mpRowCol(row, 0); assert(0 <= colBase && colBase < grad.GetNumRows()); int i0 = mpRowIndices(row, 0); int size = indices(i0++, 0); int tmp = size; if (poolIncludePad) size = indices(0, 0); assert(size > 0); ElemType g = (*this)(row, sample) / size; size = tmp; for (int i = 0; i < size; i++) { int dcol = indices(i0 + i, 0); assert(0 <= colBase + dcol && colBase + dcol < grad.GetNumRows()); #pragma omp atomic grad(colBase + dcol, sample) += g; } } } } template <class ElemType> void CPUMatrix<ElemType>::BatchNormalizationForward(const CPUMatrix<ElemType>& scale, const CPUMatrix<ElemType>& bias, bool inferenceOnly, double expAvgFactor, double blendFactor, CPUMatrix<ElemType>& runMean, CPUMatrix<ElemType>& runVariance, CPUMatrix<ElemType>& out, double epsilon, CPUMatrix<ElemType>& saveMean, CPUMatrix<ElemType>& saveInvStdDev) const { if (GetNumRows() % scale.GetNumRows() != 0) LogicError("The number of rows of this matrx must be multiple of the number of rows of the scale matrix."); if (!inferenceOnly || expAvgFactor != 0 || blendFactor != 1) RuntimeError("Batch normalization training on CPU is not yet implemented."); saveMean.Resize(0, 0); // only doing inference: these two are not produced saveInvStdDev.Resize(0, 0); bool spatial = GetNumRows() != scale.GetNumRows(); if (spatial) { size_t spatialSize = GetNumRows() / scale.GetNumRows(); #pragma omp parallel for for (long icol = 0; icol < out.GetNumCols(); icol++) { for (long irow = 0; irow < out.GetNumRows(); irow++) { size_t imap = irow / spatialSize; ElemType stdDev = sqrt(runVariance(imap, 0) + epsilon); out(irow, icol) = scale(imap, 0) * ((*this)(irow, icol) - runMean(imap, 0)) / stdDev + bias(imap, 0); } } } else { #pragma omp parallel for for (long icol = 0; icol < out.GetNumCols(); icol++) { for (long irow = 0; irow < out.GetNumRows(); irow++) { ElemType stdDev = sqrt(runVariance(irow, 0) + epsilon); out(irow, icol) = scale(irow, 0) * ((*this)(irow, icol) - runMean(irow, 0)) / stdDev + bias(irow, 0); } } } } template <class ElemType> void CPUMatrix<ElemType>::BatchNormalizationBackward(const CPUMatrix<ElemType>& in, CPUMatrix<ElemType>& grad, const CPUMatrix<ElemType>& scale, double blendFactor, const CPUMatrix<ElemType>& saveMean, const CPUMatrix<ElemType>& saveInvStdDev, CPUMatrix<ElemType>& scaleGrad, CPUMatrix<ElemType>& biasGrad) const { UNUSED(in); UNUSED(grad); UNUSED(scale); UNUSED(blendFactor), UNUSED(saveMean); UNUSED(saveInvStdDev); UNUSED(scaleGrad); UNUSED(biasGrad); RuntimeError("Batch normalization training on CPU is not yet implemented."); } #pragma region Static BLAS Functions /// <summary>Matrix-matrix multiply with col-major matrices (a and b may be transposed): c = alpha * op(a) * op(b) + beta*c</summary> /// <param name="alpha">Scalar</param> /// <param name="a">Input matrix</param> /// <param name="transposeA">Whether matrix a is transposed</param> /// <param name="b">Input matrix</param> /// <param name="transposeB">Whether matrix b is transposed</param> /// <param name="beta">Scalar</param> /// <param name="c">Resulting matrix, user is responsible for allocating this</param> template <class ElemType> void CPUMatrix<ElemType>::MultiplyAndWeightedAdd(ElemType alpha, const CPUMatrix<ElemType>& a, const bool transposeA, const CPUMatrix<ElemType>& b, const bool transposeB, ElemType beta, CPUMatrix<ElemType>& c, shared_ptr<QuantizedMultiplier<ElemType>> pQuantizedMultiplier) { if (a.IsEmpty() || b.IsEmpty()) return; int m, n, k, l; int lda, ldb, ldc; CBLAS_TRANSPOSE mklTransA; CBLAS_TRANSPOSE mklTransB; if (transposeA) { m = (int) a.GetNumCols(); k = (int) a.GetNumRows(); lda = k; mklTransA = CBLAS_TRANSPOSE::CblasTrans; } else { m = (int) a.GetNumRows(); k = (int) a.GetNumCols(); lda = m; mklTransA = CBLAS_TRANSPOSE::CblasNoTrans; } if (transposeB) { l = (int) b.GetNumCols(); n = (int) b.GetNumRows(); ldb = n; mklTransB = CBLAS_TRANSPOSE::CblasTrans; } else { l = (int) b.GetNumRows(); n = (int) b.GetNumCols(); ldb = l; mklTransB = CBLAS_TRANSPOSE::CblasNoTrans; } assert(m > 0 && k > 0 && l > 0 && n > 0); // converting from size_t to int may cause overflow if (k != l) InvalidArgument("CPUMatrix<ElemType>::MultiplyAndWeightedAdd : The inner dimensions of a and b must match."); if (beta == 0) c.RequireSize(m, n); else c.VerifySize(m, n); // Can't resize if beta != 0 ldc = (int) c.GetNumRows(); if (pQuantizedMultiplier == nullptr) { if (sizeof(ElemType) == sizeof(double)) { cblas_dgemm((CBLAS_ORDER) (int)MatrixOrder::ColMajor, mklTransA, mklTransB, m, n, k, alpha, reinterpret_cast<double*>(a.Data()), lda, reinterpret_cast<double*>(b.Data()), ldb, beta, reinterpret_cast<double*>(c.Data()), ldc); } else { #pragma warning(suppress : 4244) cblas_sgemm((CBLAS_ORDER) (int)MatrixOrder::ColMajor, mklTransA, mklTransB, m, n, k, alpha, reinterpret_cast<float*>(a.Data()), lda, reinterpret_cast<float*>(b.Data()), ldb, beta, reinterpret_cast<float*>(c.Data()), ldc); } } else { // TODO: support transpose product if (mklTransA == CBLAS_TRANSPOSE::CblasTrans || mklTransB == CBLAS_TRANSPOSE::CblasTrans) LogicError("Quantized multiplier currently doesn't support transpose."); pQuantizedMultiplier->Multiply(m, n, k, a.Data(), b.Data(), c.Data()); } } template <class ElemType> void CPUMatrix<ElemType>::Multiply1x1AndWeightedAdd(ElemType alpha, const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, ElemType beta, CPUMatrix<ElemType>& c) { if (a.GetNumElements() != 1) InvalidArgument("the argument a must be a scalar"); // a is a scalar ElemType f = alpha * a.Get00Element(); if (beta == 0) // don't even read the memory if beta is 0 #pragma omp parallel for foreach_coord (i, j, c) c(i, j) = b(i, j) * f; else #pragma omp parallel for foreach_coord (i, j, c) c(i, j) = b(i, j) * f + c(i, j) * beta; } template <class ElemType> void CPUMatrix<ElemType>::ColumnwiseScaleAndWeightedAdd(ElemType alpha, const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& v, ElemType beta, CPUMatrix<ElemType>& c) { if (v.GetNumRows() != 1 && v.GetNumCols() != 1) InvalidArgument("the argument v must be a vector"); // v is a vector if (beta == 0) c.RequireSize(a.GetNumRows(), a.GetNumCols()); else c.VerifySize(a.GetNumRows(), a.GetNumCols()); // Can't resize if beta != 0 const ElemType* vd = v.Data(); if (beta == 0) // don't even read the memory if beta is 0 #pragma omp parallel for foreach_coord(i, j, c) c(i, j) = alpha * a(i, j) * vd[j]; else #pragma omp parallel for foreach_coord(i, j, c) c(i, j) = alpha * a(i, j) * vd[j] + c(i, j) * beta; } /* compute singular value decomposition as A = U*SIGMA*VT W is used as temp working memory */ template <class ElemType> void CPUMatrix<ElemType>::SVD(const CPUMatrix<ElemType>& A, CPUMatrix<ElemType>& SIGMA, CPUMatrix<ElemType>& U, CPUMatrix<ElemType>& VT, CPUMatrix<ElemType>& W) { if (A.IsEmpty()) LogicError("SVD: input matrix is empty."); int info; int m, n, lda, ldu, ldvt; m = (int) A.GetNumRows(); n = (int) A.GetNumCols(); W.GetNumRows(); // W is used as temp working memory lda = m; ldu = m; ldvt = n; U.RequireSize(m, m); SIGMA.RequireSize(std::min(m, n), 1); VT.RequireSize(n, n); if (sizeof(ElemType) == sizeof(double)) { #ifdef USE_MKL double wkopt; int lwork = -1; dgesvd("All", "All", &m, &n, reinterpret_cast<double*>(A.Data()), &lda, reinterpret_cast<double*>(SIGMA.Data()), reinterpret_cast<double*>(U.Data()), &ldu, reinterpret_cast<double*>(VT.Data()), &ldvt, &wkopt, &lwork, &info); lwork = (int) wkopt; W.RequireSize(lwork, 1); dgesvd("All", "All", &m, &n, reinterpret_cast<double*>(A.Data()), &lda, reinterpret_cast<double*>(SIGMA.Data()), reinterpret_cast<double*>(U.Data()), &ldu, reinterpret_cast<double*>(VT.Data()), &ldvt, reinterpret_cast<double*>(W.Data()), &lwork, &info); #else std::vector<double> superb(std::max(std::min(m, n) - 1, 1)); info = LAPACKE_dgesvd((int) MatrixOrder::ColMajor, 'A', 'A', (int) m, (int) n, reinterpret_cast<double*>(A.Data()), (int) lda, reinterpret_cast<double*>(SIGMA.Data()), reinterpret_cast<double*>(U.Data()), (int) ldu, reinterpret_cast<double*>(VT.Data()), (int) ldvt, &superb[0]); #endif } else { #ifdef USE_MKL float wkopt; int lwork = -1; sgesvd("All", "All", &m, &n, reinterpret_cast<float*>(A.Data()), &lda, reinterpret_cast<float*>(SIGMA.Data()), reinterpret_cast<float*>(U.Data()), &ldu, reinterpret_cast<float*>(VT.Data()), &ldvt, &wkopt, &lwork, &info); lwork = (int) wkopt; W.RequireSize(lwork, 1); sgesvd("All", "All", &m, &n, reinterpret_cast<float*>(A.Data()), &lda, reinterpret_cast<float*>(SIGMA.Data()), reinterpret_cast<float*>(U.Data()), &ldu, reinterpret_cast<float*>(VT.Data()), &ldvt, reinterpret_cast<float*>(W.Data()), &lwork, &info); #else std::vector<float> superb(std::max(std::min(m, n) - 1, 1)); info = LAPACKE_sgesvd((int) MatrixOrder::ColMajor, 'A', 'A', (int) m, (int) n, reinterpret_cast<float*>(A.Data()), (int) lda, reinterpret_cast<float*>(SIGMA.Data()), reinterpret_cast<float*>(U.Data()), (int) ldu, reinterpret_cast<float*>(VT.Data()), (int) ldvt, &superb[0]); #endif } if (info > 0) { RuntimeError("The algorithm computing SVD failed to converge.\n"); } } /// <summary>Matrix-matrix multiply with col-major matrices (a and b may be transposed): c = op(a) * op(b) + c</summary> /// <param name="a">Input matrix</param> /// <param name="transposeA">Whether matrix a is transposed</param> /// <param name="b">Input matrix</param> /// <param name="transposeB">Whether matrix b is transposed</param> /// <param name="c">Resulting matrix, user is responsible for allocating this</param> template <class ElemType> void CPUMatrix<ElemType>::MultiplyAndAdd(const CPUMatrix<ElemType>& a, const bool transposeA, const CPUMatrix<ElemType>& b, const bool transposeB, CPUMatrix<ElemType>& c) { return CPUMatrix<ElemType>::MultiplyAndWeightedAdd(1.0, a, transposeA, b, transposeB, 1.0, c); } template <class ElemType> void CPUMatrix<ElemType>::AssignSoftmaxSum(const CPUMatrix<ElemType>& softmax, CPUMatrix<ElemType>& c) { ElemType log_likelihood = 0.0; size_t batch_size = GetNumCols(); #pragma omp parallel for reduction(+ : log_likelihood) for (int instance_id = 0; instance_id < batch_size; instance_id++) { int sample = (int) (*this)(0, instance_id); log_likelihood += softmax(instance_id, sample); } c(0, 0) = -log_likelihood; } template <class ElemType> void CPUMatrix<ElemType>::AssignNCEUnnormalizedEval(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, const CPUMatrix<ElemType>& bias, CPUMatrix<ElemType>& c) //this: samples+probs // a: hidden // b: embedding // tmp: softmax // c: loglikelihood { ElemType log_likelihood = 0.0; size_t batch_size = GetNumCols(); #pragma omp parallel for reduction(+ : log_likelihood) for (int instance_id = 0; instance_id < batch_size; instance_id++) { int sample = -(int) (*this)(0, instance_id); ElemType score = bias(sample, 0); for (int dim = 0; dim < b.GetNumRows(); dim++) score += b(dim, sample) * a(dim, instance_id); log_likelihood += score; } c(0, 0) = -log_likelihood; } //samples+prob gradient hidden embedding embedding/hidden //a.m_CPUMatrix->AssignNCEDerivative(*tmp.m_CPUMatrix, *a.m_CPUMatrix, *b.m_CPUMatrix, inputIndex, *c.m_CPUMatrix); template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignNCEDerivative(const CPUMatrix<ElemType>& tmp, const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, size_t inputIndex, CPUMatrix<ElemType>& c) { size_t sample_size = GetNumRows() / 2; size_t batch_size = GetNumCols(); if (inputIndex == 1) { #pragma omp parallel for for (int instance_id = 0; instance_id < batch_size; instance_id++) for (int sample_id = 0; sample_id < sample_size; sample_id++) { int sample = (int) (*this)(2 * sample_id, instance_id); for (int dim = 0; dim < b.GetNumRows(); dim++) c(dim, instance_id) -= b(dim, sample) * tmp(sample_id, instance_id); } } else if (inputIndex == 2) { int i_blocks = omp_get_num_threads() * 16; // Assume only one block in k direction. // We don't need to explicitly block in the j direction. #pragma omp parallel for for (int ib = 0; ib < i_blocks; ib++) for (int instance_id = 0; instance_id < batch_size; instance_id++) for (int sample_id = 0; sample_id < sample_size; sample_id++) { int sample = (int) (*this)(2 * sample_id, instance_id); if (sample % i_blocks == ib) for (int dim = 0; dim < b.GetNumRows(); dim++) c(dim, sample) -= a(dim, instance_id) * tmp(sample_id, instance_id); } } else if (inputIndex == 3) { // Assume only one block in k direction. // We don't need to explicitly block in the j direction. for (int instance_id = 0; instance_id < batch_size; instance_id++) for (int sample_id = 0; sample_id < sample_size; sample_id++) { int sample = (int) (*this)(2 * sample_id, instance_id); c(0, sample) -= tmp(sample_id, instance_id); } } else InvalidArgument("The argument inputIndex must be 1 or 2 or 3."); return *this; } template <class ElemType> void CPUMatrix<ElemType>::AssignNoiseContrastiveEstimation(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, const CPUMatrix<ElemType>& bias, CPUMatrix<ElemType>& tmp, CPUMatrix<ElemType>& c) //this: samples+probs // a: hidden // b: embedding // tmp: softmax // c: loglikelihood { double log_likelihood = 0.0; size_t sample_size = GetNumRows() / 2; size_t batch_size = GetNumCols(); size_t num_noise_samples = sample_size - 1; double log_num_noise_samples = std::log(num_noise_samples); #pragma omp parallel for reduction(+ : log_likelihood) for (int instance_id = 0; instance_id < batch_size; instance_id++) for (int sample_id = 0; sample_id < sample_size; sample_id++) { int sample = (int) (*this)(2 * sample_id, instance_id); double score = bias(0, sample); for (int dim = 0; dim < b.GetNumRows(); dim++) score += a(dim, instance_id) * b(dim, sample); double sample_prob = -(*this)(2 * sample_id + 1, instance_id); if (sample_id == 0) sample_prob = -sample_prob; double score_noise = log_num_noise_samples + sample_prob; double z = LogAdd(score, score_noise); double logprob = score - z; double logprob_noise = score_noise - z; tmp(sample_id, instance_id) = (ElemType) -std::exp(logprob); if (sample_id == 0) tmp(sample_id, instance_id) += 1; log_likelihood += sample_id == 0 ? logprob : logprob_noise; } c(0, 0) = (ElemType) -log_likelihood; } /// <summary>Matrix-matrix multiply with col-major matrices (a and b may be transposed): c = op(a) * op(b)</summary> /// <param name="a">Input matrix</param> /// <param name="transposeA">Whether matrix a is transposed</param> /// <param name="b">Input matrix</param> /// <param name="transposeB">Whether matrix b is transposed</param> /// <param name="c">Resulting matrix, user is responsible for allocating this</param> template <class ElemType> void CPUMatrix<ElemType>::Multiply(const CPUMatrix<ElemType>& a, const bool transposeA, const CPUMatrix<ElemType>& b, const bool transposeB, CPUMatrix<ElemType>& c) { return CPUMatrix<ElemType>::MultiplyAndWeightedAdd(1.0, a, transposeA, b, transposeB, 0.0, c); } /// <summary>Matrix-matrix multiply with col-major matrices (a and b are not transposed): c = a * b</summary> /// <param name="a">Input matrix</param> /// <param name="b">Input matrix</param> /// <param name="c">Resulting matrix, user is responsible for allocating this</param> template <class ElemType> void CPUMatrix<ElemType>::Multiply(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, CPUMatrix<ElemType>& c) { return CPUMatrix<ElemType>::MultiplyAndWeightedAdd(1.0, a, false, b, false, 0.0, c); } /// <summary>Matrix-scalar multiply with col-major matrices: c = alpha * a + c</summary> /// if a is a column vector, add to all columns of c /// if a is a row vector, add to all rows of c /// if a is a scalar, add to all rows of c /// <param name="alpha">Scalar</param> /// <param name="a">Input matrix</param> /// <param name="c">Resulting matrix, user is responsible for allocating this</param> template <class ElemType> void CPUMatrix<ElemType>::ScaleAndAdd(ElemType alpha, const CPUMatrix<ElemType>& a, CPUMatrix<ElemType>& c) { if (a.IsEmpty() || c.IsEmpty()) LogicError("ScaleAndAdd: one of the input matrices is empty."); if (a.GetNumRows() != 1 && a.GetNumCols() != 1) // a is not a col or row vector { const int m = (int) a.GetNumRows(); const int n = (int) a.GetNumCols(); const int len = m * n; const int incx = 1; const int incy = 1; assert(m > 0 && n > 0 && len > 0); // converting from size_t to int may cause overflow if ((int) c.GetNumRows() != m || (int) c.GetNumCols() != n) InvalidArgument("Dimension of matrix c does not match dimension of matrix a."); if (sizeof(ElemType) == sizeof(double)) { cblas_daxpy(len, alpha, reinterpret_cast<double*>(a.Data()), incx, reinterpret_cast<double*>(c.Data()), incy); } else { #pragma warning(suppress : 4244) cblas_saxpy(len, alpha, reinterpret_cast<float*>(a.Data()), incx, reinterpret_cast<float*>(c.Data()), incy); } } else if (a.GetNumElements() == 1) // scalar, add to all elements { ElemType v = alpha * a(0, 0); long m = (long) c.GetNumRows(), n = (long) c.GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { c(i, j) += v; c(i + 1, j) += v; c(i + 2, j) += v; c(i + 3, j) += v; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { c(i, j) += v; } } } else if (a.GetNumCols() == 1) // col vector, add it to all columns { int m = (int) c.GetNumRows(); if (m != (int) a.GetNumRows()) InvalidArgument("To add column vector, rows should match."); ElemType* aBufPtr = a.Data(); ElemType* cBufPtr = c.Data(); if (sizeof(ElemType) == sizeof(double)) { #pragma omp parallel for foreach_column (j, c) { cblas_daxpy(m, alpha, reinterpret_cast<double*>(aBufPtr), 1, reinterpret_cast<double*>(cBufPtr + c.LocateColumn(j)), 1); } } else { #pragma omp parallel for foreach_column (j, c) { #pragma warning(suppress : 4244) cblas_saxpy(m, alpha, reinterpret_cast<float*>(aBufPtr), 1, reinterpret_cast<float*>(cBufPtr + c.LocateColumn(j)), 1); } } } else // row vector, add it to all rows { int m = (int) c.GetNumRows(); int n = (int) c.GetNumCols(); if (n != (int) a.GetNumCols()) InvalidArgument("To add row vector, cols should match."); ElemType* aBufPtr = a.Data(); ElemType* cBufPtr = c.Data(); if (sizeof(ElemType) == sizeof(double)) { #pragma omp parallel for foreach_row (i, c) { cblas_daxpy(n, alpha, reinterpret_cast<double*>(aBufPtr), 1, reinterpret_cast<double*>(cBufPtr + i), m); } } else { #pragma omp parallel for foreach_row (i, c) { #pragma warning(suppress : 4244) cblas_saxpy(n, alpha, reinterpret_cast<float*>(aBufPtr), 1, reinterpret_cast<float*>(cBufPtr + i), m); } } } } /// <summary>c += alpha * (a-b)</summary> /// if a, b, c must have same dim /// <param name="alpha">Scalar</param> /// <param name="a">Input matrix</param> /// <param name="b">Input matrix</param> /// <param name="c">Resulting matrix, user is responsible for allocating this</param> template <class ElemType> void CPUMatrix<ElemType>::AddScaledDifference(const ElemType alpha, const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, CPUMatrix<ElemType>& c) { if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumRows() == c.GetNumRows() && a.GetNumCols() == b.GetNumCols() && a.GetNumCols() == c.GetNumCols())) { InvalidArgument("AddScaledDifference: a, b, and c must have same dimension."); } if (a.IsEmpty()) LogicError("AddScaledDifference: Input matrix a is empty."); ElemType* aBufPtr = a.Data(); ElemType* bBufPtr = b.Data(); ElemType* cBufPtr = c.Data(); long m = (long) c.GetNumElements(); #pragma omp parallel for // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { cBufPtr[i] += alpha * (aBufPtr[i] - bBufPtr[i]); cBufPtr[i + 1] += alpha * (aBufPtr[i + 1] - bBufPtr[i + 1]); cBufPtr[i + 2] += alpha * (aBufPtr[i + 2] - bBufPtr[i + 2]); cBufPtr[i + 3] += alpha * (aBufPtr[i + 3] - bBufPtr[i + 3]); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { cBufPtr[i] += alpha * (aBufPtr[i] - bBufPtr[i]); } } /// <summary> c = alpha * (a-b)</summary> /// if a, b, c must have same dim /// <param name="alpha">Scalar</param> /// <param name="a">Input matrix</param> /// <param name="b">Input matrix</param> /// <param name="c">Resulting matrix, user is responsible for allocating this</param> template <class ElemType> void CPUMatrix<ElemType>::AssignScaledDifference(const ElemType alpha, const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, CPUMatrix<ElemType>& c) { if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols())) { InvalidArgument("AssignScaledDifference: a, b must have same dimension."); } if (a.IsEmpty()) LogicError("AssignScaledDifference: Input matrix a is empty."); if (&c != &a && &c != &b) c.RequireSize(a.GetNumRows(), a.GetNumCols()); ElemType* aBufPtr = a.Data(); ElemType* bBufPtr = b.Data(); ElemType* cBufPtr = c.Data(); long m = (long) c.GetNumElements(); #pragma omp parallel for // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { cBufPtr[i] = alpha * (aBufPtr[i] - bBufPtr[i]); cBufPtr[i + 1] = alpha * (aBufPtr[i + 1] - bBufPtr[i + 1]); cBufPtr[i + 2] = alpha * (aBufPtr[i + 2] - bBufPtr[i + 2]); cBufPtr[i + 3] = alpha * (aBufPtr[i + 3] - bBufPtr[i + 3]); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { cBufPtr[i] = alpha * (aBufPtr[i] - bBufPtr[i]); } } // c[ci,cj] += a[ai,aj] template <class ElemType> void CPUMatrix<ElemType>::AddElementToElement(ElemType beta, const CPUMatrix<ElemType>& a, const size_t ai, const size_t aj, CPUMatrix<ElemType>& c, const size_t ci, const size_t cj) { if (ai >= a.GetNumRows() || aj >= a.GetNumCols() || ci >= c.GetNumRows() || cj >= c.GetNumCols()) InvalidArgument("AddElementToElement: index out of range."); ElemType us = beta ? beta * c(ci, cj) : 0; // do not multiply if beta is 0, could be a NaN us += a(ai, aj); c(ci, cj) = us; } ////c[ci,cj] += a[ai,aj] //template<class ElemType> //void CPUMatrix<ElemType>::AddLogElementToElement(const CPUMatrix<ElemType>& a, const size_t ai, const size_t aj, CPUMatrix<ElemType>& c, const size_t ci, const size_t cj) //{ // if (ai >= a.GetNumRows() || aj >=a.GetNumCols() || // ci >= c.GetNumRows() || cj >=c.GetNumCols()) // InvalidArgument("AddElementToElement: index out of range."); // // ElemType v = a(ai,aj); // c(ci, cj) += ((v < EPS_IN_LOG) ? LOG_OF_EPS_IN_LOG : log(v)); //} #if 0 // now done as AddElementToElement (beta=0) // c[ci,cj] = a[ai,aj] template <class ElemType> void CPUMatrix<ElemType>::AssignElementToElement(const CPUMatrix<ElemType>& a, const size_t ai, const size_t aj, CPUMatrix<ElemType>& c, const size_t ci, const size_t cj) { if (ai >= a.GetNumRows() || aj >= a.GetNumCols() || ci >= c.GetNumRows() || cj >= c.GetNumCols()) InvalidArgument("AssignElementToElement: index out of range."); c(ci, cj) = a(ai, aj); } #endif /// <summary>c += alpha * (a-b)</summary> /// if a, b, c must have same dim /// <param name="alpha">1X1 matrix</param> /// <param name="a">Input matrix</param> /// <param name="b">Input matrix</param> /// <param name="c">Resulting matrix, user is responsible for allocating this</param> template <class ElemType> void CPUMatrix<ElemType>::AddScaledDifference(const CPUMatrix<ElemType>& alpha, const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, CPUMatrix<ElemType>& c) { if (alpha.GetNumElements() != 1) InvalidArgument("AddScaledDifference: alpha must be a 1X1 matrix."); AddScaledDifference(alpha(0, 0), a, b, c); } /// <summary> c = alpha * (a-b)</summary> /// if a, b, c must have same dim /// <param name="alpha">1X1 matrix</param> /// <param name="a">Input matrix</param> /// <param name="b">Input matrix</param> /// <param name="c">Resulting matrix, user is responsible for allocating this</param> template <class ElemType> void CPUMatrix<ElemType>::AssignScaledDifference(const CPUMatrix<ElemType>& alpha, const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, CPUMatrix<ElemType>& c) { if (alpha.GetNumElements() != 1) InvalidArgument("AddScaledDifference: alpha must be a 1X1 matrix."); AssignScaledDifference(alpha(0, 0), a, b, c); } /// <summary>Matrix-scalar multiply with col-major matrices: c = alpha * a</summary> /// <param name="alpha">Scalar</param> /// <param name="a">Input matrix</param> /// <param name="c">Resulting matrix, user is responsible for allocating this</param> template <class ElemType> /*static*/ void CPUMatrix<ElemType>::Scale(ElemType alpha, const CPUMatrix<ElemType>& a, CPUMatrix<ElemType>& c) { if (a.IsEmpty()) LogicError("Scale: Input matrix a is empty."); const int m = (int) a.GetNumRows(); const int n = (int) a.GetNumCols(); assert(m > 0 && n > 0); // converting from size_t to int may cause overflow c.RequireSize(m, n); ElemType* aBufPtr = a.Data(); ElemType* cBufPtr = c.Data(); if (alpha == 0) { memset(cBufPtr, 0, sizeof(ElemType) * c.GetNumElements()); return; } long size = (long) c.GetNumElements(); #pragma omp parallel for // four-way unrolling for (long i = 0; i < (size & ~3); i += 4) { cBufPtr[i] = alpha * aBufPtr[i]; cBufPtr[i + 1] = alpha * aBufPtr[i + 1]; cBufPtr[i + 2] = alpha * aBufPtr[i + 2]; cBufPtr[i + 3] = alpha * aBufPtr[i + 3]; } // remaining elements for (long i = size & ~3; i < size; i++) { cBufPtr[i] = alpha * aBufPtr[i]; } } /// <summary>Matrix-scalar multiply with col-major matrices: a = alpha * a</summary> /// <param name="alpha">Scalar</param> /// <param name="a">Input matrix</param> template <class ElemType> /*static*/ void CPUMatrix<ElemType>::Scale(ElemType alpha, CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("Scale: Input matrix a is empty."); const int m = (int) a.GetNumRows(); const int n = (int) a.GetNumCols(); const int len = m * n; const int incx = 1; assert(m > 0 && n > 0 && len > 0); // converting from size_t to int may cause overflow if (alpha == 0 && incx == 1) { memset(a.Data(), 0, sizeof(ElemType) * len); } else if (sizeof(ElemType) == sizeof(double)) { cblas_dscal(len, alpha, reinterpret_cast<double*>(a.Data()), incx); } else { #pragma warning(suppress : 4244) cblas_sscal(len, alpha, reinterpret_cast<float*>(a.Data()), incx); } } /// <summary>Matrix multiply with col-major matrices: a = alpha[1,1] * a</summary> /// <param name="alpha">1x1 matrix</param> /// <param name="a">Input matrix</param> template <class ElemType> /*static*/ void CPUMatrix<ElemType>::Scale(CPUMatrix<ElemType> alpha, CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("Scale: Input matrix a is empty."); if (alpha.GetNumElements() != 1) LogicError("Matrix alpha must be 1x1"); CPUMatrix<ElemType>::Scale(alpha(0, 0), a); } template <class ElemType> void CPUMatrix<ElemType>::InnerProduct(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, CPUMatrix<ElemType>& c, const bool isColWise) { if (a.IsEmpty() || b.IsEmpty()) LogicError("InnerProduct: one of the input matrices is empty."); const int m = (int) a.GetNumRows(); const int n = (int) a.GetNumCols(); const int k = (int) b.GetNumRows(); const int l = (int) b.GetNumCols(); assert(m > 0 && n > 0 && k > 0 && l > 0); // converting from size_t to int may cause overflow if (m != k || n != l) InvalidArgument("InnerProduct: Matrices a and b should have same dimension."); if ((isColWise && m == 1) || !isColWise && n == 1) // in this case it's equivalent to element-wise product { c.AssignElementProductOf(a, b); } else if (isColWise) // col-wise { c.RequireSize(1, n); ElemType* aBufPtr = a.Data(); ElemType* bBufPtr = b.Data(); if (sizeof(ElemType) == sizeof(double)) { #pragma omp parallel for foreach_column (j, c) { c(0, j) = (ElemType) cblas_ddot(m, reinterpret_cast<double*>(aBufPtr + a.LocateColumn(j)), 1, reinterpret_cast<double*>(bBufPtr + b.LocateColumn(j)), 1); } } else { #pragma omp parallel for foreach_column (j, c) { #pragma warning(suppress : 4244) c(0, j) = (ElemType) cblas_sdot(m, reinterpret_cast<float*>(aBufPtr + a.LocateColumn(j)), 1, reinterpret_cast<float*>(bBufPtr + b.LocateColumn(j)), 1); } } } else { c.RequireSize(m, 1); ElemType* aBufPtr = a.Data(); ElemType* bBufPtr = b.Data(); if (sizeof(ElemType) == sizeof(double)) { #pragma omp parallel for foreach_row (i, c) { c(i, 0) = cblas_ddot(n, reinterpret_cast<double*>(aBufPtr + i), m, reinterpret_cast<double*>(bBufPtr + i), m); } } else { #pragma omp parallel for foreach_row (i, c) { #pragma warning(suppress : 4244) c(i, 0) = cblas_sdot(n, reinterpret_cast<float*>(aBufPtr + i), m, reinterpret_cast<float*>(bBufPtr + i), m); } } } } // treat matrices as vectors. do vec(a)^T vec(b) template <class ElemType> ElemType CPUMatrix<ElemType>::InnerProductOfMatrices(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b) { if (a.IsEmpty() || b.IsEmpty()) LogicError("InnerProductOfMatrices: one of the input matrices is empty."); const int m = (int) a.GetNumRows(); const int n = (int) a.GetNumCols(); const int k = (int) b.GetNumRows(); const int l = (int) b.GetNumCols(); assert(m > 0 && n > 0 && k > 0 && l > 0); // converting from size_t to int may cause overflow if (m != k || n != l) InvalidArgument("InnerProductOfMatrices: Matrices a and b should have same dimension."); if (sizeof(ElemType) == sizeof(double)) { return (ElemType) cblas_ddot((int) a.GetNumElements(), reinterpret_cast<double*>(a.Data()), 1, reinterpret_cast<double*>(b.Data()), 1); } else { #pragma warning(suppress : 4244) return (ElemType) cblas_sdot((int) a.GetNumElements(), reinterpret_cast<float*>(a.Data()), 1, reinterpret_cast<float*>(b.Data()), 1); } } template <class ElemType> void CPUMatrix<ElemType>::ElementWisePower(ElemType alpha, const CPUMatrix<ElemType>& a, CPUMatrix<ElemType>& c) { if (a.IsEmpty()) LogicError("Scale: The input matrix a is empty."); c.RequireSize(a.GetNumRows(), a.GetNumCols()); if (alpha == 2) { #pragma omp parallel for foreach_coord (i, j, c) { c(i, j) = a(i, j) * a(i, j); } } else if (alpha == 3) { #pragma omp parallel for foreach_coord (i, j, c) { c(i, j) = a(i, j) * a(i, j) * a(i, j); } } else { #pragma omp parallel for foreach_coord (i, j, c) { c(i, j) = pow(a(i, j), alpha); } } } template <class ElemType> bool CPUMatrix<ElemType>::AreEqual(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, const ElemType threshold /*= 1e-8*/) { if (a.GetNumRows() != b.GetNumRows() || a.GetNumCols() != b.GetNumCols()) return false; bool result = true; #pragma omp parallel for foreach_coord (i, j, a) { if (abs(a(i, j) - b(i, j)) > threshold) { result = false; break; } } return result; } // see Matrix<ElemType>::TensorShuffleScaleAndAdd() for comments template <class ElemType> void CPUMatrix<ElemType>::TensorShuffleScaleAndAdd(ElemType keepWeight, const CPUMatrix<ElemType>& a, size_t D, size_t S, size_t M, size_t K, size_t T, ElemType scaleFactor, const CPUMatrix<ElemType>& b, CPUMatrix<ElemType>& c) { size_t N = D * S * M * K * T; const auto pa = a.Data(); const auto pb = b.Data(); auto pc = c.Data(); // Note: This code is written to match a GPU implementation. It is not super-efficient on the CPU. for (size_t na = 0; na < N; na++) // loop over all elements { // recover the 5 indices from the loop counter size_t d = na % D; size_t s = (na / D) % S; size_t m = (na / D / S) % M; size_t k = (na / D / S / M) % K; size_t t = (na / D / S / M / K) % T; // compute index for the a and b/c tensors assert(na == (((t * K + k) * M + m) * S + s) * D + d); // input tensor of dimension (D x S x M x K x T) size_t nb = (((t * S + s) * M + m) * K + k) * D + d; // output tensor of dimension (D x K x M x S x T): k/K and s/S swapped assert(nb < N); // perform the computation ElemType cval = keepWeight ? keepWeight * pb[nb] : 0; // if weight is 0 then don't bother to read memory (efficiency) or to multiply (NaN-safe) cval += scaleFactor * pa[na]; pc[nb] = cval; } } template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::Ones(const size_t rows, const size_t cols) { CPUMatrix<ElemType> c(rows, cols); // will initialize to 0 c.SetValue(1); return c; } template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::Zeros(const size_t rows, const size_t cols) { CPUMatrix<ElemType> c(rows, cols); // will initialize to 0 c.SetValue(0); return c; } template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::Eye(const size_t rows) { CPUMatrix<ElemType> c(rows, rows); // will initialize to 0 c.SetDiagonalValue(1); return c; } template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::RandomUniform(const size_t rows, const size_t cols, const ElemType low, const ElemType high, unsigned long seed) { CPUMatrix<ElemType> c(rows, cols); // will initialize to 0 c.SetUniformRandomValue(low, high, seed); return c; } template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::RandomGaussian(const size_t rows, const size_t cols, const ElemType mean, const ElemType sigma, unsigned long seed) { CPUMatrix<ElemType> c(rows, cols); // will initialize to 0 c.SetGaussianRandomValue(mean, sigma, seed); return c; } template <class ElemType> bool CPUMatrix<ElemType>::HasElement(const CPUMatrix<ElemType>& mat, const ElemType v) { bool bHas = false; bool isvFinite = std::isfinite(v); #pragma omp parallel for for (long j = 0; j < mat.GetNumElements(); j++) { #pragma omp flush(bHas) if (!bHas) { ElemType cur = mat.Data()[j]; if (isvFinite && std::isfinite(cur)) { if (cur == v) bHas = true; } else if (std::isnan(v) && std::isnan(cur)) bHas = true; else if (std::isinf(v) && std::isinf(cur) && std::signbit(v) == std::signbit(cur)) bHas = true; } } return bHas; } // CPUMatrix<ElemType>& AssignElementProductOfWithShiftNeg(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, size_t shift, size_t negnumber); //[this]=a .* b // here, a and b must be two row vectors of the same size, i.e. [1,m] // the inputs are two rwo vectors // the output is a matrix of size(neg+1, col) template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignElementProductOfWithShiftNeg(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, size_t shift, size_t negnumber) { if (a.IsEmpty() || b.IsEmpty()) LogicError("AssignElementProductOfWithShiftNeg: Matrix is empty."); if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols())) InvalidArgument("AssignElementProductOfWithShiftNeg: The input matrix dimensions do not match."); if (a.GetNumRows() != 1) InvalidArgument("AssignElementProductOfWithShiftNeg: The input matrix must be a row vector."); auto& us = *this; if (this != &a) { RequireSize(negnumber + 1, a.GetNumCols()); // RequireSize(a.GetNumRows(), a.GetNumCols()); } long m = (long) GetNumRows(), n = (long) GetNumCols(); // a and b are of size (1,n) // #pragma omp parallel for for (long j = 0; j < n; j++) { us(0, j) = a(0, j) * b(0, j); } for (long j = 0; j < n; j++) { for (long i = 1; i < m; i++) { us(i, j) = a(0, j) * b(0, (j + shift + i - 1) % n); } } return *this; } template <class ElemType> void CPUMatrix<ElemType>::InnerProductWithShiftNeg(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, CPUMatrix<ElemType>& c, const bool isColWise, size_t shift, size_t negnumber) { if (a.IsEmpty() || b.IsEmpty()) LogicError("InnerProduct: one of the input matrices is empty."); const int m = (int) a.GetNumRows(); const int n = (int) a.GetNumCols(); const int k = (int) b.GetNumRows(); const int l = (int) b.GetNumCols(); assert(m > 0 && n > 0 && k > 0 && l > 0); // converting from size_t to int may cause overflow if (m != k || n != l) InvalidArgument("InnerProduct: Matrices a and b should have same dimension."); if ((isColWise && m == 1) || !isColWise && n == 1) // in this case it's equivalent to element-wise product { InvalidArgument("InnerProduct: Both matrices should be normal ones, not vectors"); // c.AssignElementProductOf(a, b); } else if (isColWise) // col-wise { c.RequireSize(negnumber + 1, n); // this line ischanged ElemType* aBufPtr = a.Data(); ElemType* bBufPtr = b.Data(); if (sizeof(ElemType) == sizeof(double)) { for (long j = 0; j < n; j++) { c(0, j) = (ElemType) cblas_ddot(m, reinterpret_cast<double*>(aBufPtr + a.LocateColumn(j)), 1, reinterpret_cast<double*>(bBufPtr + b.LocateColumn(j)), 1); } for (long j = 0; j < n; j++) { for (long i = 1; i < negnumber + 1; i++) { c(i, j) = (ElemType) cblas_ddot(m, reinterpret_cast<double*>(aBufPtr + a.LocateColumn(j)), 1, reinterpret_cast<double*>(bBufPtr + b.LocateColumn((j + shift + i - 1) % n)), 1); } } } else { for (long j = 0; j < n; j++) { c(0, j) = (ElemType) cblas_sdot(m, reinterpret_cast<float*>(aBufPtr + a.LocateColumn(j)), 1, reinterpret_cast<float*>(bBufPtr + b.LocateColumn(j)), 1); } for (long j = 0; j < n; j++) { for (long i = 1; i < negnumber + 1; i++) { c(i, j) = (ElemType) cblas_sdot(m, reinterpret_cast<float*>(aBufPtr + a.LocateColumn(j)), 1, reinterpret_cast<float*>(bBufPtr + b.LocateColumn((j + shift + i - 1) % n)), 1); } } } } else { InvalidArgument("InnerProduct: Rowwise is not supported yet"); c.RequireSize(m, 1); ElemType* aBufPtr = a.Data(); ElemType* bBufPtr = b.Data(); if (sizeof(ElemType) == sizeof(double)) { #pragma omp parallel for foreach_row (i, c) { c(i, 0) = (ElemType) cblas_ddot(n, reinterpret_cast<double*>(aBufPtr + i), m, reinterpret_cast<double*>(bBufPtr + i), m); } } else { #pragma omp parallel for foreach_row (i, c) { #pragma warning(suppress : 4244) c(i, 0) = cblas_sdot(n, reinterpret_cast<float*>(aBufPtr + i), m, reinterpret_cast<float*>(bBufPtr + i), m); } } } } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::GetARowByIndex(const CPUMatrix<ElemType>& a, size_t index) { if (a.IsEmpty()) LogicError("GetARowByIndex: the input matrices is empty."); const int m = (int) a.GetNumRows(); const int n = (int) a.GetNumCols(); if (index < 0 || index >= m) LogicError("GetARowByIndex: the row index is out of range."); assert(m > 0 && n > 0); // converting from size_t to int may cause overflow auto& us = *this; RequireSize(1, n); for (long j = 0; j < n; j++) { us(0, j) = a(index, j); } return *this; } // input: a, a row vector // input: b, a matrix. b.col == a.col // input firstmatrixfixed: If true, keep a's order. Otherwise, keep b's order // output: c, a matrix. c.size == b.size /* Example, a = [a1 a2 a3] b = [b11 b12 b13; b21 b22 b23 ] if true: shift = 1 then c = [a1*b12 a2*b13 a3*b11 a1*b22 a2*b23 a3*b21] if shift = 2 then c = [ a1*b13 a2*b11 a3*b12 a1*b23 a2*b21 a3*b22] i.e. we do column-wise shift if false: shift = 1 then c = [a2*b11 a3*b12 a1*b13 a2*b21 a3*b22 a1*b23] shift = 2 then c = [ a3*b11 a1*b12 a2*b13 a3*b21 a1*b22 a2*b23] */ template <class ElemType> void CPUMatrix<ElemType>::ConductRowElementMultiplyWithShift(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, CPUMatrix<ElemType>& c, size_t shift, bool bFirstmatrixfixed) { if (a.IsEmpty() || b.IsEmpty()) LogicError("InnerProduct: one of the input matrices is empty."); const int m = (int) a.GetNumRows(); const int n = (int) a.GetNumCols(); const int k = (int) b.GetNumRows(); const int l = (int) b.GetNumCols(); assert(m > 0 && n > 0 && k > 0 && l > 0); // converting from size_t to int may cause overflow if (m != 1 || n != l) InvalidArgument("InnerProduct: Matrices a and b should have same dimension."); c.RequireSize(k, l); // c must the the same size of b if (bFirstmatrixfixed) { for (long j = 0; j < l; j++) { for (long i = 0; i < k; i++) { c(i, j) = a(0, j) * b(i, (j + shift) % l); } } } else { for (long j = 0; j < l; j++) { for (long i = 0; i < k; i++) { c(i, j) = a(0, (j + shift) % l) * b(i, j); } } } } // CPUMatrix<ElemType>& AssignElementProductOfWithShift(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, size_t shift); //[this]=a .* b // here, a and b must be two row vectors of the same size, i.e. [1,m]. We will do element product with shift. // inputs are 2 row vectors // output is a row vector template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignElementProductOfWithShift(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, size_t shift) { if (a.IsEmpty() || b.IsEmpty()) LogicError("AssignElementProductOfWithShiftNeg: Matrix is empty."); if (a.GetNumRows() != b.GetNumRows() || a.GetNumCols() != b.GetNumCols()) InvalidArgument("AssignElementProductOfWithShiftNeg: The input matrix dimensions do not match."); if (a.GetNumRows() != 1) InvalidArgument("AssignElementProductOfWithShiftNeg: The input matrix must be a row vector."); auto& us = *this; if (this != &a) { RequireSize(1, a.GetNumCols()); // RequireSize(a.GetNumRows(), a.GetNumCols()); } // long m = (long)GetNumRows(), n = (long)GetNumCols(); // a and b are of size (1,n) long n = (long) GetNumCols(); // a and b are of size (1,n) #pragma omp parallel for for (long j = 0; j < n; j++) { us(0, j) = a(0, j) * b(0, (j + shift) % n); } return *this; } #pragma endregion Static BLAS Functions // 'double' version of LogAdd inline double LogAddD(double x, double y) { return LogAdd(x, y); } template <class ElemType> ElemType CPUMatrix<ElemType>::LogSumOfElements() const { ElemType fAlpha = (ElemType) LZERO; ElemType* bufPtr = Data(); for (int k = 0; k < GetNumElements(); k++) fAlpha = (ElemType) LogAddD(fAlpha, bufPtr[k]); return fAlpha; } template <class ElemType> void CPUMatrix<ElemType>::RCRFBackwardCompute(const CPUMatrix<ElemType>& alpha, CPUMatrix<ElemType>& beta, const CPUMatrix<ElemType>& lbls, const CPUMatrix<ElemType>& pair_scores) { int iNumPos = (int) lbls.GetNumCols(); int iNumLab = (int) lbls.GetNumRows(); int lastLbl = -1; for (int ik = 0; ik < lbls.GetNumRows(); ik++) if (lbls(ik, iNumPos - 1) != 0) { lastLbl = ik; break; } beta.RequireSize(iNumLab, iNumPos); for (int t = iNumPos - 1; t >= 0; t--) { #pragma omp parallel for for (int k = 0; k < iNumLab; k++) { _rcrfBackwardCompute(t, k, alpha, beta, pair_scores); } } }; // Calculate alpha in forward-backward calculation. equation (6), (7) in ftp://ftp.idsia.ch/pub/juergen/icml2006.pdf // GPU x dimension corresponds to utterances, y dimension corresponds to phone sequence in each utterance // prob (input): the posterior output from the network // alpha (output): alpha for forward-backward calculation. // phoneSeq (input): phone ID sequence for each utterance in this minibatch, each col is one utterance // phoneBound (input): phone boundary (frame index) of each phone for each utterance in this minibatch, each col is one utterance // uttToChanInd (input): map from utterance ID to minibatch channel ID. We need this because each channel may contain more than one utterance. // uttFrameNum (input): the frame number of each utterance. The size of this vector = the number of all utterances in this minibatch // uttBeginFrame(input): the positon of the first frame of each utterance in the minibatch channel. We need this because each channel may contain more than one utterance. // uttPhoneNum (input): the phone number of each utterance. The size of this vector = the number of all utterances in this minibatch // numChannels (input): channel number in this minibatch // uttNum (input): number of utterances // t (input): time stamp to process // maxPhoneNum (input): the max number of phones between utterances // totalPhoneNum (input): the total number of phones of all utterances // blankTokenId (input): id of the CTC blank token // delayConstraint -- label output delay constraint introduced during training that allows to have shorter delay during inference. // Alpha and Beta scores outside of the delay boundary are set to zero. // Setting this parameter smaller will result in shorted delay between label output during decoding. // delayConstraint=-1 means no constraint template<class ElemType> void _assignAlphaScore( const ElemType *prob, ElemType *alphaScore, ElemType *phoneSeq, ElemType *phoneBound, const std::vector<size_t>& uttToChanInd, const std::vector<size_t>& uttFrameNum, const std::vector<size_t>& uttBeginFrame, const std::vector<size_t>& uttPhoneNum, size_t numChannels, const size_t uttNum, const size_t t, const size_t maxPhoneNum, // Maximum length of utterance in this MB const size_t totalPhoneNum, // Total number of phones const size_t blankTokenId, const int delayConstraint) { for (size_t uttId = 0;uttId < uttNum;uttId++) { // Number of phones and frames in this utterance size_t frameNum = uttFrameNum[uttId]; if (t >= frameNum) continue; size_t phoneNum = uttPhoneNum[uttId]; #pragma omp parallel for for (int phoneSeqId = 1;phoneSeqId < phoneNum - 1;phoneSeqId++) { // Index of the label in the sequence // Current and previous phone indices in phoneSeq matrix size_t labelid = uttId*maxPhoneNum + phoneSeqId; // Actual current phone label size_t phoneId = (size_t)(phoneSeq[labelid]); // Index of the current frame in minibatch size_t timeId = (t + uttBeginFrame[uttId])*numChannels + uttToChanInd[uttId]; // Index of probability of observing phoneId at frame timeId size_t probId = timeId*totalPhoneNum + phoneId; size_t alphaId = maxPhoneNum* timeId + phoneSeqId; // alpha_t(s) if (t == 0) { // Initialize recursion if (phoneSeqId == 1 || phoneSeqId == 2) { alphaScore[alphaId] = prob[probId]; } } else { if (phoneSeqId >= 1) { size_t timeId_1 = timeId - numChannels; // Index corresponding to (t-1) size_t alphaId_0 = maxPhoneNum* timeId_1 + phoneSeqId; // alpha_{t-1}(s) size_t alphaId_1 = alphaId_0 - 1; // alpha_{t-1}(s-1) size_t alphaId_2 = alphaId_0 - 2; // alpha_{t-1}(s-2) ElemType x = LZERO; ElemType ascore; if (phoneSeqId > 2) { size_t labelid_2 = labelid - 2; // if current label is not blank and not equal prev non-blank label if ((size_t)(phoneSeq[labelid]) != blankTokenId && phoneId != (size_t)(phoneSeq[labelid_2])) { x = LogAdd(x, alphaScore[alphaId_2]); } } if (phoneSeqId > 1) { x = LogAdd(x, alphaScore[alphaId_1]); } x = LogAdd(x, alphaScore[alphaId_0]); if (phoneId != SIZE_MAX) ascore = prob[probId]; // Probability of observing given label at given time else ascore = 0; alphaScore[alphaId] = (ElemType)x + ascore; if (delayConstraint != -1) { size_t labelid_r = labelid + 2; size_t phoneBoundId_r = (size_t)(phoneBound[labelid_r]); if (phoneId == blankTokenId) { // only constraint right side if (t > phoneBoundId_r + delayConstraint - 1) alphaScore[alphaId] = LZERO; } else if (phoneId != blankTokenId) { if (t > phoneBoundId_r + delayConstraint) alphaScore[alphaId] = LZERO; } } } } } } } // Calculate beta in forward-backward calculation, equation (10), (11) in ftp://ftp.idsia.ch/pub/juergen/icml2006.pdf // See _assignAlphaScore for the explanation of parameters template<class ElemType> void _assignBetaScore( const ElemType *prob, ElemType *betaScore, ElemType *phoneSeq, ElemType *phoneBound, const std::vector<size_t>& uttToChanInd, const std::vector<size_t>& uttFrameNum, const std::vector<size_t>& uttBeginFrame, const std::vector<size_t>& uttPhoneNum, const size_t numChannels, const size_t uttNum, const long t, const size_t maxPhoneNum, const size_t totalPhoneNum, const size_t blankTokenId, const int delayConstraint) { for (size_t uttId = 0;uttId < uttNum;uttId++) { // Number of phones and frames in this utterance size_t frameNum = uttFrameNum[uttId]; if (t >= frameNum) continue; size_t phoneNum = uttPhoneNum[uttId]; #pragma omp parallel for for (int phoneSeqId = 1;phoneSeqId < phoneNum - 1;phoneSeqId++) { size_t labelid = uttId*maxPhoneNum + phoneSeqId; size_t labelid_2 = labelid + 2; size_t phoneId = (LONG64)(phoneSeq[labelid]); size_t timeId = (t + uttBeginFrame[uttId])*numChannels + uttToChanInd[uttId]; size_t probId = timeId*totalPhoneNum + phoneId; size_t betaid = maxPhoneNum* timeId + phoneSeqId; size_t timeId_1 = timeId + numChannels; size_t betaid_0 = maxPhoneNum* timeId_1 + phoneSeqId; size_t betaid_1 = betaid_0 + 1; size_t betaid_2 = betaid_0 + 2; if (t == frameNum - 1) { if (phoneSeqId == phoneNum - 3 || phoneSeqId == phoneNum - 2) { betaScore[betaid] = prob[probId]; } } else { if (phoneSeqId >= 1) { ElemType x = LZERO; ElemType ascore; if (phoneSeqId < phoneNum - 3) { if (phoneSeq[labelid] != blankTokenId && phoneId != phoneSeq[labelid_2]) { x = LogAdd(x, betaScore[betaid_2]); } } if (phoneSeqId < phoneNum - 2) { x = LogAdd(x, betaScore[betaid_1]); } x = LogAdd(x, betaScore[betaid_0]); if (phoneId != SIZE_MAX) ascore = prob[probId]; else ascore = 0; betaScore[betaid] = (ElemType)x + ascore; if (delayConstraint != -1) { size_t phoneBoundId_r = (size_t)(phoneBound[labelid_2]); if (phoneId == blankTokenId) { if (t > phoneBoundId_r + delayConstraint - 1) betaScore[betaid] = LZERO; } else if (phoneId != blankTokenId) { if (t > phoneBoundId_r + delayConstraint) betaScore[betaid] = LZERO; } } } } } } } // Calculate CTC score. equation (8) in ftp://ftp.idsia.ch/pub/juergen/icml2006.pdf template<class ElemType> void _assignTotalScore(ElemType *betaScore, std::vector<ElemType>& totalScore, const size_t uttNum, const std::vector<size_t>& uttToChanInd, const std::vector<size_t>& uttBeginFrame, const size_t numChannels, const size_t maxPhoneNum) { #pragma omp parallel for for (int uttId = 0; uttId < uttNum; uttId++) { if (uttId < uttNum) { LONG64 alphaId_0 = (uttBeginFrame[uttId] * numChannels + uttToChanInd[uttId]) * maxPhoneNum; betaScore[alphaId_0] = LogAdd(betaScore[alphaId_0 + 1], betaScore[alphaId_0 + 2]); totalScore[uttId] = betaScore[alphaId_0]; } } } // Calculate derivative, equation (15) in ftp://ftp.idsia.ch/pub/juergen/icml2006.pdf // See _assignAlphaScore for the explanation of parameters template<class ElemType> void _assignCTCScore( ElemType *CTCscore, ElemType *prob, ElemType *alphaScore, ElemType *betaScore, ElemType *phoneSeq, const size_t uttNum, const std::vector<size_t>& uttToChanInd, const std::vector<size_t>& uttBeginFrame, const std::vector<size_t>& uttPhoneNum, const std::vector<size_t>& uttFrameNum, const size_t numChannels, const size_t maxPhoneNum, const size_t totalPhoneNum) { for (size_t uttId = 0;uttId < uttNum;uttId++) { #pragma omp parallel for for (int t = 0; t < uttFrameNum[uttId]; t++) { size_t phoneNum = uttPhoneNum[uttId]; size_t alphaId_0 = (uttBeginFrame[uttId] * numChannels + uttToChanInd[uttId]) * maxPhoneNum; size_t timeId = (t + uttBeginFrame[uttId])*numChannels + uttToChanInd[uttId]; ElemType P_lx = betaScore[alphaId_0]; for (int s = 1; s < phoneNum - 1; s++) { long phoneId = phoneSeq[uttId*maxPhoneNum + s]; size_t alphaId = maxPhoneNum* timeId + s; size_t probId = timeId*totalPhoneNum + phoneId; if (phoneId != SIZE_MAX) { ElemType logoccu = alphaScore[alphaId] + betaScore[alphaId] - prob[probId] - (ElemType)P_lx; CTCscore[probId] = LogAdd(CTCscore[probId], logoccu); } } for (int s = 0; s < totalPhoneNum; s++) { size_t probId = timeId*totalPhoneNum + s; ElemType logoccu = CTCscore[probId]; if (logoccu < LZERO) CTCscore[probId] = 0.0f; else CTCscore[probId] = exp(logoccu); } } } } template<class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignCTCScore( const CPUMatrix<ElemType>& prob, CPUMatrix<ElemType>& alpha, CPUMatrix<ElemType>& beta, const CPUMatrix<ElemType>& phoneSeq, const CPUMatrix<ElemType>& phoneBoundary, CPUMatrix<ElemType> & totalScore, const std::vector<size_t>& uttToChanInd, const std::vector<size_t> & uttBeginFrame, const std::vector<size_t> & uttFrameNum, const std::vector<size_t> & uttPhoneNum, const size_t numParallelSequences, const size_t maxFrameNum, const size_t blankTokenId, const int delayConstraint, const bool isColWise) { // Column wise representation of sequences in input matrices (each column is one sequence/utterance) if (isColWise) { // Total number of phones size_t totalPhoneNum = prob.GetNumRows(); size_t uttNum = uttFrameNum.size(); // Max number of phones in utterances in this minibatch size_t maxPhoneNum = phoneSeq.GetNumRows(); for (size_t t = 0; t < maxFrameNum; t++) { _assignAlphaScore(prob.Data(), alpha.Data(), phoneSeq.Data(), phoneBoundary.Data(), uttToChanInd, uttFrameNum, uttBeginFrame, uttPhoneNum, numParallelSequences, uttNum, t, maxPhoneNum, totalPhoneNum, blankTokenId, delayConstraint); } for (LONG64 t = maxFrameNum - 1; t >= 0; t--) { _assignBetaScore(prob.Data(), beta.Data(), phoneSeq.Data(), phoneBoundary.Data(), uttToChanInd, uttFrameNum, uttBeginFrame, uttPhoneNum, numParallelSequences, uttNum, t, maxPhoneNum, totalPhoneNum, blankTokenId, delayConstraint); } std::vector<ElemType> scores(uttNum); _assignTotalScore(beta.Data(), scores, uttNum, uttToChanInd, uttBeginFrame, numParallelSequences, maxPhoneNum); _assignCTCScore(Data(), prob.Data(), alpha.Data(), beta.Data(), phoneSeq.Data(), uttNum, uttToChanInd, uttBeginFrame, uttPhoneNum, uttFrameNum, numParallelSequences, maxPhoneNum, totalPhoneNum); totalScore(0, 0) = 0.0; for (size_t utt = 0; utt < uttNum; utt++) { totalScore(0,0) -= scores[utt]; } return *this; } else { LogicError("Only ColWise minibatch layout is supported."); } return *this; } /// the kernel function for RCRF backward computation template <class ElemType> void CPUMatrix<ElemType>::_rcrfBackwardCompute(size_t t, size_t k, const CPUMatrix<ElemType>& alpha, CPUMatrix<ElemType>& beta, const CPUMatrix<ElemType>& pair_scores) { size_t iNumLab = alpha.GetNumRows(); size_t iNumPos = alpha.GetNumCols(); ElemType fSum; ElemType fTmp = (ElemType) LZERO; if (t == iNumPos - 1) { fSum = (ElemType) LZERO; for (int j = 0; j < iNumLab; j++) { fSum = (ElemType) LogAddD(fSum, alpha(j, t)); } fTmp = alpha(k, t) - fSum; beta(k, t) = fTmp; } else { for (int j = 0; j < iNumLab; j++) { fSum = (ElemType) LZERO; for (int m = 0; m < iNumLab; m++) { fSum = (ElemType) LogAddD(fSum, alpha(m, t) + pair_scores(j, m)); } fTmp = (ElemType) LogAddD(fTmp, beta(j, t + 1) + alpha(k, t) + pair_scores(j, k) - fSum); } beta(k, t) = fTmp; } } template <class ElemType> void CPUMatrix<ElemType>::RCRFTransGrdCompute(const CPUMatrix<ElemType>& lbls, const CPUMatrix<ElemType>& alpha, const CPUMatrix<ElemType>& beta, const CPUMatrix<ElemType>& pair_scores, CPUMatrix<ElemType>& grd) { int iNumPos = (int) alpha.GetNumCols(); int iNumLab = (int) alpha.GetNumRows(); int firstLbl = -1; for (int ik = 0; ik < lbls.GetNumRows(); ik++) if (lbls(ik, 0) != 0) { firstLbl = ik; break; } for (size_t tPos = 0; tPos < iNumPos; tPos++) { CPUMatrix<ElemType> b = beta.ColumnSlice(tPos, 1); CPUMatrix<ElemType> a; if (tPos > 0) a = alpha.ColumnSlice(tPos - 1, 1); #pragma omp parallel for for (int i = 0; i < iNumLab; i++) { _rcrfTransGrdCompute(i, lbls, alpha, beta, pair_scores, grd, tPos); } // transition score int i = -1; if (tPos == 0) i = firstLbl; else { for (int ik = 0; ik < lbls.GetNumRows(); ik++) if (lbls(ik, tPos - 1) != 0) { i = ik; break; } } int j = -1; for (int ik = 0; ik < lbls.GetNumRows(); ik++) { if (lbls(ik, tPos) != 0) { j = ik; break; } } grd(j, i) -= 1.0; } }; template <class ElemType> void CPUMatrix<ElemType>::_rcrfTransGrdCompute(size_t i, const CPUMatrix<ElemType>& lbls, const CPUMatrix<ElemType>& alpha, const CPUMatrix<ElemType>& beta, const CPUMatrix<ElemType>& pair_scores, CPUMatrix<ElemType>& grd, const size_t tPos // position ) { int iNumLab = (int) alpha.GetNumRows(); int firstLbl = -1; for (int ik = 0; ik < lbls.GetNumRows(); ik++) if (lbls(ik, 0) != 0) { firstLbl = ik; break; } CPUMatrix<ElemType> b = beta.ColumnSlice(tPos, 1); CPUMatrix<ElemType> a; if (tPos > 0) a = alpha.ColumnSlice(tPos - 1, 1); { ElemType fTmp = (ElemType) LZERO; for (int j = 0; j < iNumLab; j++) { if (tPos == 0) { if (i == firstLbl) { fTmp = 0; } else { fTmp = (ElemType) LZERO; } } else { fTmp = a(i, 0); } fTmp += pair_scores(j, i); ElemType fSum = (ElemType) LZERO; for (int k = 0; k < iNumLab; k++) { ElemType fTmp2; if (tPos == 0) { if (k == firstLbl) { fTmp2 = 0; } else { fTmp2 = (ElemType) LZERO; } } else { fTmp2 = a(k, 0); } fSum = (ElemType) LogAddD(fSum, fTmp2 + pair_scores(j, k)); } fTmp -= fSum; fTmp += b(j, 0); grd(j, i) += exp(fTmp); } } }; template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::DropFrame(const CPUMatrix<ElemType>& label, const CPUMatrix<ElemType>& gamma, const ElemType& threshhold) { auto& us = *this; if (us.GetNumCols() != gamma.GetNumCols() || us.GetNumRows() != gamma.GetNumRows()) LogicError("DropFrame: target matrix is not in the same size as gamm matrix."); #pragma omp parallel for foreach_column (j, label) { bool dropframe = false; foreach_row (i, label) { if (fabs(label(i, j) - 1.0f) < 0.1) { if (gamma(i, j) < threshhold) dropframe = true; break; } } foreach_row (i, label) { us(i, j) = 0.0f; } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignSequenceError(const ElemType hsmoothingWeight, const CPUMatrix<ElemType>& label, const CPUMatrix<ElemType>& dnnoutput, const CPUMatrix<ElemType>& gamma, ElemType alpha) { auto& us = *this; foreach_coord (i, j, us) us(i, j) += alpha * (label(i, j) - (1 - hsmoothingWeight) * dnnoutput(i, j) - hsmoothingWeight * gamma(i, j)); return *this; } // note: this function does not depend on the <ElemType> parameter template <class ElemType> int CPUMatrix<ElemType>::SetNumThreads(int numThreads) { if (numThreads == 0) // use default return numThreads; int mthreads = (int) std::thread::hardware_concurrency(); if (numThreads <= 0) numThreads = std::max(1, mthreads + numThreads); if (numThreads > mthreads) numThreads = mthreads; #ifdef _OPENMP omp_set_num_threads(numThreads); numThreads = omp_get_max_threads(); #ifdef USE_MKL mkl_set_num_threads(numThreads); #elif defined(USE_OPENBLAS) openblas_set_num_threads(numThreads); #endif #endif return numThreads; } template <class ElemType> int CPUMatrix<ElemType>::GetMaxNumThreads() { int numThreads = (int)std::thread::hardware_concurrency(); #ifdef _OPENMP numThreads = omp_get_max_threads(); #endif return numThreads; } // To ensure Intel MKL calls return the same results on all Intel or Intel compatible CPUs, // the function set CBWR compatible mode. template <class ElemType> void CPUMatrix<ElemType>::SetCompatibleMode() { #ifdef USE_MKL if (mkl_cbwr_set(MKL_CBWR_COMPATIBLE) != MKL_CBWR_SUCCESS) RuntimeError("Could not set MKL compatible mode."); #endif } // ======================================================================= // TensorView support // ======================================================================= // To save time, this makes extensive use of templates and macros. // ----------------------------------------------------------------------- // function to compute the value for a given output location (perform reduction if needed) // ----------------------------------------------------------------------- // perform loop over reduction index m // This function is declared inside a wrapper struct to allow partial specialization (m = -1). template <class ElemType, typename OPFN, typename ReductionOp, size_t N, int m> struct TensorOpReduction { // reduction case (non-reduction case is specialized) static inline ElemType Loop(array<ElemType*, N> pointers, const OPFN& opfn, const ReductionOp& reductionOp, const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, N>& reducingStrides) { array<ptrdiff_t, N - 1> strides; // N-1 because last one is the result pointer, which is unused in reduction for (size_t i = 0; i < N - 1; i++) // N = a small constant, this will be unrolled strides[i] = reducingStrides[i][(size_t) m]; double aggregate = TensorOpReduction<ElemType, OPFN, ReductionOp, N, m - 1>::Loop(pointers, opfn, reductionOp, reducingOpDims, reducingStrides); for (size_t dim = reducingOpDims[(size_t)m] - 1; dim-- > 0;) { // advance the pointers for (size_t i = 0; i < N - 1; i++) pointers[i] += strides[i]; // note: last pointer (result) is unused and untouched here // need to descend into one loop deeper aggregate = reductionOp(aggregate, TensorOpReduction<ElemType, OPFN, ReductionOp, N, m - 1>::Loop(pointers, opfn, reductionOp, reducingOpDims, reducingStrides)); } // Actually it would be nicer to return double but we keep ElementType so that test don't return different numbers than previous implementation. return static_cast<double>(aggregate); } }; // perform loop over reduction index m // This is the specialized version for m = -1, which terminates the recursion. template <class ElemType, typename OPFN, typename ReductionOp, size_t N> struct TensorOpReduction<ElemType, OPFN, ReductionOp, N, -1> { static inline ElemType Loop(array<ElemType*, N> pointers, const OPFN& opfn, const ReductionOp& reductionOp, const SmallVector<size_t>&, const array<SmallVector<ptrdiff_t>, N>&) { return opfn(pointers); // finally we are doing some work!!! } }; // perform loop over reduction index m, while keeping track of the number of elements and their corresponding indices. // This function is declared inside a wrapper struct to allow partial specialization (m = -1). template <class ElemType, size_t N, int m> struct TensorArgOpReduction { static inline std::pair<ElemType, size_t> ReduceAll(array<ElemType*, N> pointers, const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, N>& reducingStrides, ElementWiseOperator reductionOp) { size_t counter = 0; size_t index = 0; ElemType val = (ElemType)0; switch (reducingOpDims.size()) { case 3: val = TensorArgOpReduction<ElemType, N, 2>::Loop(pointers, reducingOpDims, reducingStrides, reductionOp, counter, index); break; case 2: val = TensorArgOpReduction<ElemType, N, 1>::Loop(pointers, reducingOpDims, reducingStrides, reductionOp, counter, index); break; case 1: val = TensorArgOpReduction<ElemType, N, 0>::Loop(pointers, reducingOpDims, reducingStrides, reductionOp, counter, index); break; case 0: val = TensorArgOpReduction<ElemType, N, -1>::Loop(pointers, reducingOpDims, reducingStrides, reductionOp, counter, index); break; default: LogicError("TensorOp: %d non-flattened input dimensions are not supported.", (int)reducingOpDims.size()); } return make_pair(val, index); } // reduction case (non-reduction case is specialized) static inline ElemType Loop(array<ElemType*, N> pointers, const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, N>& reducingStrides, ElementWiseOperator reductionOp, size_t& counter, size_t& index) { array<ptrdiff_t, N - 1> strides; // N-1 because last one is the result pointer, which is unused in reduction for (size_t i = 0; i < N - 1; i++) // N = a small constant, this will be unrolled strides[i] = reducingStrides[i][(size_t)m]; ElemType aggregate = TensorArgOpReduction<ElemType, N, m - 1>::Loop(pointers, reducingOpDims, reducingStrides, reductionOp, counter, index); for (size_t dim = reducingOpDims[(size_t)m] - 1; dim-- > 0;) { // advance the pointers for (size_t i = 0; i < N - 1; i++) pointers[i] += strides[i]; // note: last pointer (result) is unused and untouched here ElemType val = TensorArgOpReduction<ElemType, N, m - 1>::Loop(pointers, reducingOpDims, reducingStrides, reductionOp, counter, index); bool update = false; switch (reductionOp) { case ElementWiseOperator::opArgmin: update = (aggregate > val); break; case ElementWiseOperator::opArgmax: update = (aggregate < val); break; } if (update) { aggregate = val; index = counter - 1; } } return aggregate; } }; // perform loop over reduction index m // This is the specialized version for m = -1, which terminates the recursion. template <class ElemType, size_t N> struct TensorArgOpReduction<ElemType, N, -1> { static inline ElemType Loop(array<ElemType*, N> pointers, const SmallVector<size_t>&, const array<SmallVector<ptrdiff_t>, N>&, ElementWiseOperator reductionOp, size_t& counter, size_t& index) { counter++; return *pointers[0]; // finally we are doing some work!!! } }; // ----------------------------------------------------------------------- // perform loop over regular index k for N-nary operations (N counting the output) // ----------------------------------------------------------------------- // perform loop over regular index k and reducing index m for N operands (counting the output) template <class ElemType, typename OPFN, typename ReductionOp, size_t N, bool vectorizable, int m, int k> struct TensorOpIteration { static inline void Loop(ElemType beta, array<ElemType*, N> pointers, ElemType alpha, const OPFN& opfn, const ReductionOp& reductionOp, const SmallVector<size_t>& regularOpDims, const array<SmallVector<ptrdiff_t>, N>& regularStrides, const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, N>& reducingStrides) { // non-scalar case: still nested result loops left array<ptrdiff_t, N> strides; for (size_t i = 0; i < N; i++) // N = a small constant, this will be unrolled strides[i] = regularStrides[i][(size_t) k]; for (size_t dim = regularOpDims[(size_t) k]; dim-- > 0;) { // need to descend into one loop deeper TensorOpIteration<ElemType, OPFN, ReductionOp, N, vectorizable, m, k - 1>::Loop(beta, pointers, alpha, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides); // advance the pointers for (size_t i = 0; i < N; i++) pointers[i] += strides[i]; } } }; // Special version for innermost loop with strides all being 1 and no further reduction. Compiler can use SSE. // This is a very common case, e.g. adding vectors or computing the Sigmoid. template <class ElemType, typename OPFN, typename ReductionOp> struct TensorOpIteration<ElemType, OPFN, ReductionOp, 3, true /*vectorizable*/, -1 /*no reduction*/, 0 /*innermost loop*/> { static inline void Loop(ElemType beta, array<ElemType*, 3> pointers, ElemType alpha, const OPFN& opfn, const ReductionOp& reductionOp, const SmallVector<size_t>& regularOpDims, const array<SmallVector<ptrdiff_t>, 3>& regularStrides, const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, 3>& reducingStrides) { ElemType* pa = pointers[0]; ElemType* pb = pointers[1]; ElemType* pc = pointers[2]; size_t K = regularOpDims[0]; // special-case beta and alpha to allow the compiler to short-circuit it if (beta != 0) #pragma omp parallel for for (int k = 0; k < (int) K; k++) TensorOpIteration<ElemType, OPFN, ReductionOp, 3, true /*vectorizable*/, -1 /*no reduction*/, -1 /*scalar*/>::Loop(beta, array<ElemType*, 3>{pa + k, pb + k, pc + k}, alpha, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides); else if (alpha != 1) #pragma omp parallel for for (int k = 0; k < (int) K; k++) TensorOpIteration<ElemType, OPFN, ReductionOp, 3, true /*vectorizable*/, -1 /*no reduction*/, -1 /*scalar*/>::Loop(0, array<ElemType*, 3>{pa + k, pb + k, pc + k}, alpha, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides); else #pragma omp parallel for for (int k = 0; k < (int) K; k++) TensorOpIteration<ElemType, OPFN, ReductionOp, 3, true /*vectorizable*/, -1 /*no reduction*/, -1 /*scalar*/>::Loop(0, array<ElemType*, 3>{pa + k, pb + k, pc + k}, 1, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides); // TODO: According to Amit, the VS compiler is not able to vectorize into lambdas. Solution: change the lambda to take an N, or to implement the loop inside (with 1 element by default). // TODO: The signedness of k (required for omp) causes an extra sign-extend. // TODO: OMP adds LOTS of overhead. Do we need a guard, a min size when to use it? } }; // and unary template <class ElemType, typename OPFN, typename ReductionOp> struct TensorOpIteration<ElemType, OPFN, ReductionOp, 2, true /*vectorizable*/, -1 /*no reduction*/, 0 /*innermost loop*/> { static inline void Loop(ElemType beta, array<ElemType*, 2> pointers, ElemType alpha, const OPFN& opfn, const ReductionOp& reductionOp, const SmallVector<size_t>& regularOpDims, const array<SmallVector<ptrdiff_t>, 2>& regularStrides, const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, 2>& reducingStrides) { ElemType* pa = pointers[0]; ElemType* pb = pointers[1]; size_t K = regularOpDims[0]; // special-case beta and alpha to allow the compiler to short-circuit it if (beta != 0) #pragma omp parallel for for (int k = 0; k < (int) K; k++) TensorOpIteration<ElemType, OPFN, ReductionOp, 2, true /*vectorizable*/, -1 /*no reduction*/, -1 /*scalar*/>::Loop(beta, array<ElemType*, 2>{pa + k, pb + k}, alpha, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides); else if (alpha != 1) #pragma omp parallel for for (int k = 0; k < (int) K; k++) TensorOpIteration<ElemType, OPFN, ReductionOp, 2, true /*vectorizable*/, -1 /*no reduction*/, -1 /*scalar*/>::Loop(0, array<ElemType*, 2>{pa + k, pb + k}, alpha, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides); else #pragma omp parallel for for (int k = 0; k < (int) K; k++) TensorOpIteration<ElemType, OPFN, ReductionOp, 2, true /*vectorizable*/, -1 /*no reduction*/, -1 /*scalar*/>::Loop(0, array<ElemType*, 2>{pa + k, pb + k}, 1, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides); } }; template <class ElemType, typename OPFN, typename ReductionOp, size_t N, bool vectorizable, int m> struct TensorOpIteration<ElemType, OPFN, ReductionOp, N, vectorizable, m, -1> { static inline void Loop(ElemType beta, array<ElemType*, N> pointers, ElemType alpha, const OPFN& opfn, const ReductionOp& reductionOp, const SmallVector<size_t>&, const array<SmallVector<ptrdiff_t>, N>&, const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, N>& reducingStrides) { // we are at element level for the result: perform the op (there may still be reduction) ElemType val = TensorOpReduction<ElemType, OPFN, ReductionOp, N, m>::Loop(pointers, opfn, reductionOp, reducingOpDims, reducingStrides); // scale val *= alpha; // combine with previous value in target matrix, then write it out auto* pout = pointers.back(); if (beta != 0) val += beta * *pout; // save *pout = val; return; } }; // perform loop over regular index k and reducing index m for N operands (counting the output), the difference // between TensorOpIteration and TensorArgOpIteration, is that the latter store the index of the result, instead of // the result. The reason that they aren't combined is because of performance. template <class ElemType, size_t N, int k> struct TensorArgOpIteration { static inline void Loop(array<ElemType*, N> pointers, const SmallVector<size_t>& regularOpDims, const array<SmallVector<ptrdiff_t>, N>& regularStrides, const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, N>& reducingStrides, ElementWiseOperator reductionOp) { // non-scalar case: still nested result loops left array<ptrdiff_t, N> strides; for (size_t i = 0; i < N; i++) // N = a small constant, this will be unrolled strides[i] = regularStrides[i][(size_t)k]; for (size_t dim = regularOpDims[(size_t)k]; dim-- > 0;) { // need to descend into one loop deeper TensorArgOpIteration<ElemType, N, k - 1>::Loop(pointers, regularOpDims, regularStrides, reducingOpDims, reducingStrides, reductionOp); // advance the pointers for (size_t i = 0; i < N; i++) pointers[i] += strides[i]; } } }; template <class ElemType, size_t N> struct TensorArgOpIteration<ElemType, N, -1> { static inline void Loop(array<ElemType*, N> pointers, const SmallVector<size_t>&, const array<SmallVector<ptrdiff_t>, N>&, const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, N>& reducingStrides, ElementWiseOperator reductionOp) { // we are at element level for the result: perform the op (there may still be reduction) auto val = TensorArgOpReduction<ElemType, N, 2>::ReduceAll(pointers, reducingOpDims, reducingStrides, reductionOp); auto* pout = pointers.back(); *pout = (ElemType)val.second; return; } }; // ----------------------------------------------------------------------- // map runtime parameters N to template parameters // ----------------------------------------------------------------------- // tensor operation with k+1 dimensions (-1 means scalar) template <class ElemType, typename OPFN, typename ReductionOp, size_t N, int k> static void TensorOpWithRegularLoop(ElemType beta, const array<ElemType*, N>& pointers, ElemType alpha, const OPFN& opfn, ReductionOp reductionOp, const SmallVector<size_t>& regularOpDims, const array<SmallVector<ptrdiff_t>, N>& regularStrides, const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, N>& reducingStrides) { size_t dims = reducingOpDims.size(); switch (dims) { case 2: return TensorOpIteration<ElemType, OPFN, ReductionOp, N, false /*vectorizable*/, 1, k>::Loop(beta, pointers, alpha, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides); case 1: return TensorOpIteration<ElemType, OPFN, ReductionOp, N, false /*vectorizable*/, 0, k>::Loop(beta, pointers, alpha, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides); case 0: { // if all leading dimensions are 1, we can let the compiler do some unrolling bool leadingAllOne = true; for (size_t i = 0; i < N; i++) leadingAllOne &= k >= 0 && regularStrides[i][0] == 1; if (leadingAllOne) // special version that uses a hard-coded increment of 1 for all leading dimensions return TensorOpIteration<ElemType, OPFN, ReductionOp, N, true /*vectorizable*/, -1, k>::Loop(beta, pointers, alpha, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides); else return TensorOpIteration<ElemType, OPFN, ReductionOp, N, false /*vectorizable*/, -1, k>::Loop(beta, pointers, alpha, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides); } default: LogicError("TensorOp: %d non-flattened reduction dimensions are not supported.", (int) dims); } } // tensor operation, generalized in number of arguments, operation already provided as a lambda // This function now expands into different k. template <class ElemType, typename OPFN, typename ReductionOp, size_t N> static void TensorOpWithFnAndReduction(ElemType beta, array<ElemType*, N> pointers, ElemType alpha, const OPFN& opfn, const ReductionOp& reductionOp, const array<size_t, N>& offsets, const SmallVector<size_t>& regularOpDims, const array<SmallVector<ptrdiff_t>, N>& regularStrides, const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, N>& reducingStrides) { for (size_t i = 0; i < N; i++) // N = a small constant, this will be unrolled pointers[i] += offsets[i]; size_t dims = regularOpDims.size(); switch (dims) { case 4: return TensorOpWithRegularLoop<ElemType, OPFN, ReductionOp, N, 3>(beta, pointers, alpha, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides); case 3: return TensorOpWithRegularLoop<ElemType, OPFN, ReductionOp, N, 2>(beta, pointers, alpha, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides); case 2: return TensorOpWithRegularLoop<ElemType, OPFN, ReductionOp, N, 1>(beta, pointers, alpha, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides); case 1: return TensorOpWithRegularLoop<ElemType, OPFN, ReductionOp, N, 0>(beta, pointers, alpha, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides); case 0: return TensorOpWithRegularLoop<ElemType, OPFN, ReductionOp, N, -1>(beta, pointers, alpha, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides); default: LogicError("TensorOp: %d non-flattened input dimensions are not supported.", (int)dims); } } // tensor operation, generalized in number of arguments, operation already provided as a lambda // This function now expands into different reductionOps template <class ElemType, typename OPFN, size_t N> static void TensorOpWithFn(ElemType beta, array<ElemType*, N> pointers, ElemType alpha, const OPFN& opfn, ElementWiseOperator reductionOp, const array<size_t, N>& offsets, const SmallVector<size_t>& regularOpDims, const array<SmallVector<ptrdiff_t>, N>& regularStrides, const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, N>& reducingStrides) { // BUGBUG: Using always 'double' as type of aggregator even for ElemType==float. Reason: otherwise some e2e test would fail as historically we // used double for aggregator of sum. But: // * for min and max reductions this is meaningless. // * It is not consitent with what we do on GPU, there we aggregate on ElemType. // * It costs performance. // TODO: apdapt e2e tests to run with aggregator of type ElemType. #define CaseTensorOpWithFnAndReduction(oper) \ case ElementWiseOperator::op##oper: \ return TensorOpWithFnAndReduction(beta, pointers, alpha, opfn, [](double a, double b) \ { \ return Op##oper(a, b); \ }, \ offsets, regularOpDims, regularStrides, reducingOpDims, reducingStrides) switch (reductionOp) { CaseTensorOpWithFnAndReduction(Sum); CaseTensorOpWithFnAndReduction(LogSum); CaseTensorOpWithFnAndReduction(Min); CaseTensorOpWithFnAndReduction(Max); CaseTensorOpWithFnAndReduction(ElementwiseProduct); default: LogicError("Specified ElementWiseOperator op %d not suported as reduction operation.", (int)reductionOp); } } // ----------------------------------------------------------------------- // entry points from Matrix.cpp; also map op to a lambda // ----------------------------------------------------------------------- // perform unary operation 'op' on a giving 'this', reinterpreting the matrices as tensors as specified by the dims and strides // This maps 'op' to a lambda. template <class ElemType> void CPUMatrix<ElemType>::TensorOp(ElemType beta, const CPUMatrix<ElemType>& a, ElemType alpha, ElementWiseOperator op, ElementWiseOperator reductionOp, const array<size_t, 2>& offsets, const SmallVector<size_t>& regularOpDims, const array<SmallVector<ptrdiff_t>, 2>& regularStrides, const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, 2>& reducingStrides) { if (reductionOp != ElementWiseOperator::opSum && reductionOp != ElementWiseOperator::opLogSum && reductionOp != ElementWiseOperator::opMin && reductionOp != ElementWiseOperator::opMax && reductionOp != ElementWiseOperator::opElementwiseProduct) InvalidArgument("TensorOp: Unary reduction operations other than opMax, opMin, opSum, and opLogSum are not implemented."); // TODO: Change the lambda to take a pointer and a number of elements, so that we can pass it 1 or 4 elements, in order for it to SSE-vectorize. #define CaseUnaryTensorOp(oper) \ case ElementWiseOperator::op##oper: \ return TensorOpWithFn(beta, pointers, alpha, [](const array<ElemType*, 2>& pp) \ { \ return Op##oper((*(pp[0]))); \ }, \ reductionOp, offsets, regularOpDims, regularStrides, reducingOpDims, reducingStrides) array<ElemType*, 2> pointers = {a.Data(), Data()}; switch (op) { ForAllUnaryOps(CaseUnaryTensorOp); default: LogicError("TensorOp: Unknown unary op code %d.", (int) op); } } // perform binary operation 'op' on a and b giving 'this', reinterpreting the matrices as tensors as specified by the dims and strides // This maps 'op' to a lambda. template <class ElemType> void CPUMatrix<ElemType>::TensorOp(ElemType beta, const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, ElemType alpha, ElementWiseOperator op, ElementWiseOperator reductionOp, const array<size_t, 3>& offsets, const SmallVector<size_t>& regularOpDims, const array<SmallVector<ptrdiff_t>, 3>& regularStrides, const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, 3>& reducingStrides) { if (reductionOp != ElementWiseOperator::opSum) InvalidArgument("TensorOp (binary): The only permitted binary reduction operation is opSum."); #define CaseBinaryTensorOp(oper) \ case ElementWiseOperator::op##oper: \ return TensorOpWithFn(beta, pointers, alpha, [](const array<ElemType*, 3>& pp) \ { \ return Op##oper((*(pp[0])), (*(pp[1]))); \ }, \ reductionOp, offsets, regularOpDims, regularStrides, reducingOpDims, reducingStrides) array<ElemType*, 3> pointers = {a.Data(), b.Data(), Data()}; switch (op) { ForAllBinaryOps(CaseBinaryTensorOp); default: LogicError("TensorOp: Unknown op binary code %d.", (int) op); } } // perform ternary operation 'op' on a, and c giving 'this', reinterpreting the matrices as tensors as specified by the dims and strides // This maps 'op' to a lambda. template <class ElemType> void CPUMatrix<ElemType>::TensorOp(ElemType beta, const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, const CPUMatrix<ElemType>& c, ElemType alpha, ElementWiseOperator op, ElementWiseOperator reductionOp, const array<size_t, 4>& offsets, const SmallVector<size_t>& regularOpDims, const array<SmallVector<ptrdiff_t>, 4>& regularStrides, const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, 4>& reducingStrides) { if (reductionOp != ElementWiseOperator::opSum) InvalidArgument("TensorOp: The only permitted ternary reduction operation is opSum."); #define CaseTernaryTensorOp(oper) \ case ElementWiseOperator::op##oper: \ return TensorOpWithFn(beta, pointers, alpha, [](const array<ElemType*, 4>& pp) \ { \ return Op##oper((*(pp[0])), (*(pp[1])), (*(pp[2]))); \ }, \ reductionOp, offsets, regularOpDims, regularStrides, reducingOpDims, reducingStrides) array<ElemType*, 4> pointers = {a.Data(), b.Data(), c.Data(), Data()}; switch (op) { ForAllTernaryOps(CaseTernaryTensorOp); default: LogicError("TensorOp: Unknown ternary op code %d.", (int) op); } } template <class ElemType> int CPUMatrix<ElemType>::Argmin() const { int minArg = -1; ElemType minValue = std::numeric_limits<ElemType>::max(); #pragma omp parallel { int localMinArg = -1; ElemType localMinValue = std::numeric_limits<ElemType>::max(); #pragma omp for for (int index = 0; index < (int)GetNumElements(); ++index) { if (localMinValue > Data()[index]) { localMinArg = index; localMinValue = Data()[index]; } // If we have more then one min value, select the one with lower index. else if ((localMinValue == Data()[index]) && (localMinArg > index)) { localMinArg = index; } } #pragma omp critical { if (minValue > localMinValue) { minArg = localMinArg; minValue = localMinValue; } // If we have more then one min value, select the one with lower index. else if ((minValue == localMinValue) && (minArg > localMinArg)) { minArg = localMinArg; } } } return minArg; } template <class ElemType> int CPUMatrix<ElemType>::Argmax() const { int maxArg = -1; ElemType maxValue = std::numeric_limits<ElemType>::min(); #pragma omp parallel { int localMaxArg = -1; ElemType localMaxValue = std::numeric_limits<ElemType>::min(); #pragma omp for for (int index = 0; index < (int)GetNumElements(); ++index) { if (localMaxValue < Data()[index]) { localMaxArg = index; localMaxValue = Data()[index]; } // If we have more then one max value, select the one with lower index. else if ((localMaxValue == Data()[index]) && (localMaxArg > index)) { localMaxArg = index; } } #pragma omp critical { if (maxValue < localMaxValue) { maxArg = localMaxArg; maxValue = localMaxValue; } // If we have more then one max value, select the one with lower index. else if ((maxValue == localMaxValue) && (maxArg > localMaxArg)) { maxArg = localMaxArg; } } } return maxArg; } template <class ElemType> int CPUMatrix<ElemType>::ArgOp(ElementWiseOperator reductionOp) const { switch (reductionOp) { case ElementWiseOperator::opArgmin: return Argmin(); break; case ElementWiseOperator::opArgmax: return Argmax(); break; } InvalidArgument("ArgOp: Arg reduction operations other than opArgmax, and opArgmin are not implemented."); return -1; } template <class ElemType> void CPUMatrix<ElemType>::TensorArgOp(const CPUMatrix<ElemType>& a, ElementWiseOperator reductionOp, const array<size_t, 2>& offsets, const SmallVector<size_t>& regularOpDims, const array<SmallVector<ptrdiff_t>, 2>& regularStrides, const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, 2>& reducingStrides) { if (reductionOp != ElementWiseOperator::opArgmin && reductionOp != ElementWiseOperator::opArgmax) InvalidArgument("TensorOp: Arg reduction operations other than opArgmax, and opArgmin are not implemented."); if (GetNumElements() == 1) { Data()[0] = (ElemType) a.ArgOp(reductionOp); } else { const size_t N = 2; array<ElemType*, N> pointers = { a.Data(), Data() }; for (size_t i = 0; i < N; i++) pointers[i] += offsets[i]; switch (regularOpDims.size()) { case 2: TensorArgOpIteration<ElemType, N, 1>::Loop(pointers, regularOpDims, regularStrides, reducingOpDims, reducingStrides, reductionOp); break; case 1: TensorArgOpIteration<ElemType, N, 0>::Loop(pointers, regularOpDims, regularStrides, reducingOpDims, reducingStrides, reductionOp); break; case 0: TensorArgOpIteration<ElemType, N, -1>::Loop(pointers, regularOpDims, regularStrides, reducingOpDims, reducingStrides, reductionOp); break; default: LogicError("TensorOp: %d non-flattened input dimensions are not supported.", (int)regularOpDims.size()); } } } template <class ElemType> void CPUMatrix<ElemType>::ScatterValues(ElemType* indices, ElemType* value, ElemType* data, ElemType alpha, size_t num_indices, size_t rows, size_t cols, size_t indices_step) { if (!indices || !value || !data) LogicError("ScatterValues: input data is null."); #pragma omp parallel { int ithread = omp_get_thread_num(); int nthread = omp_get_num_threads(); for (auto i = 0; i < num_indices; i++) { auto col_r = indices[i * indices_step]; if (std::isnan(col_r) || col_r < 0) continue; auto col = (size_t)col_r; //ignore the elements that is not partitioned into this thread if (col % nthread != ithread) continue; if (col >= cols) InvalidArgument("ScatterValues: Indices map out of bounds. %ld >= %ld", (long int)col, (long int)cols); auto index = col * rows; auto offset = i * rows; for (auto j = 0; j < rows; j++) data[index + j] = data[index + j] + alpha * value[offset + j]; } } } // We use Matrix<char> as the backing store for QuantizedMatrix // Let's explicitly instantiate the methods we need for that purpose template CPUMatrix<char>::CPUMatrix(const size_t numRows, const size_t numCols); template CPUMatrix<char>::CPUMatrix(const size_t numRows, const size_t numCols, char* pArray, const size_t matrixFlags); template CPUMatrix<char>::CPUMatrix(); template CPUMatrix<char>::CPUMatrix(CPUMatrix<char> const&); template CPUMatrix<char>::CPUMatrix(CPUMatrix<char>&&); template size_t CPUMatrix<char>::LocateElement(size_t, size_t) const; template CPUMatrix<char> CPUMatrix<char>::ColumnSlice(size_t startColumn, size_t numCols) const; template CPUMatrix<char>& CPUMatrix<char>::operator=(CPUMatrix<char>&&); template void CPUMatrix<char>::SetValue(const char); template void CPUMatrix<char>::SetValue(const size_t numRows, const size_t numCols, char* pArray, size_t matrixFlags); template void CPUMatrix<char>::SetValue(CPUMatrix<char> const&); //template void CPUMatrix<char>::SetValue(GPUMatrix<char> const&); //template void CPUMatrix<char>::SetValue(CPUSparseMatrix<char> const&); //template void CPUMatrix<char>::SetValue(GPUSparseMatrix<char> const&); template void CPUMatrix<char>::RequireSize(const size_t numRows, const size_t numCols, bool growOnly); template void CPUMatrix<char>::Resize(const size_t numRows, const size_t numCols, bool growOnly); template char* CPUMatrix<char>::CopyToArray(void) const; template void CPUMatrix<char>::CopySection(size_t numRows, size_t numCols, char* dst, size_t colStride) const; template void CPUMatrix<char>::Reshape(const size_t, const size_t); // Support <short> template CPUMatrix<short>::CPUMatrix(const size_t numRows, const size_t numCols); template CPUMatrix<short>::CPUMatrix(const size_t numRows, const size_t numCols, short* pArray, const size_t matrixFlags); template CPUMatrix<short>::CPUMatrix(); template CPUMatrix<short>::CPUMatrix(CPUMatrix<short> const&); template CPUMatrix<short>::CPUMatrix(CPUMatrix<short>&&); template size_t CPUMatrix<short>::LocateElement(size_t, size_t) const; template CPUMatrix<short> CPUMatrix<short>::ColumnSlice(size_t startColumn, size_t numCols) const; template CPUMatrix<short>& CPUMatrix<short>::operator=(CPUMatrix<short>&&); template void CPUMatrix<short>::SetValue(const short); template void CPUMatrix<short>::SetValue(const size_t numRows, const size_t numCols, short* pArray, size_t matrixFlags); template void CPUMatrix<short>::SetValue(CPUMatrix<short> const&); //template void CPUMatrix<short>::SetValue(GPUMatrix<short> const&); //template void CPUMatrix<short>::SetValue(CPUSparseMatrix<short> const&); //template void CPUMatrix<short>::SetValue(GPUSparseMatrix<short> const&); template void CPUMatrix<short>::RequireSize(const size_t numRows, const size_t numCols, bool growOnly); template void CPUMatrix<short>::Resize(const size_t numRows, const size_t numCols, bool growOnly); template short* CPUMatrix<short>::CopyToArray(void) const; template void CPUMatrix<short>::CopySection(size_t numRows, size_t numCols, short* dst, size_t colStride) const; template void CPUMatrix<short>::Reshape(const size_t, const size_t); template CPUMatrix<int>::CPUMatrix(const size_t, const size_t, int*, const size_t); }}}
GB_extractTuples.c
//------------------------------------------------------------------------------ // GB_extractTuples: extract all the tuples from a matrix //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // Extracts all tuples from a matrix, like [I,J,X] = find (A). If any // parameter I, J and/or X is NULL, then that component is not extracted. The // size of the I, J, and X arrays (those that are not NULL) is given by nvals, // which must be at least as large as GrB_nvals (&nvals, A). The values in the // matrix are typecasted to the type of X, as needed. // This function does the work for the user-callable GrB_*_extractTuples // functions. #include "GB.h" #define GB_FREE_ALL \ { \ GB_FREE (Ap) ; \ GB_FREE (X_bitmap) ; \ } GrB_Info GB_extractTuples // extract all tuples from a matrix ( GrB_Index *I_out, // array for returning row indices of tuples GrB_Index *J_out, // array for returning col indices of tuples void *X, // array for returning values of tuples GrB_Index *p_nvals, // I,J,X size on input; # tuples on output const GB_Type_code xcode, // type of array X const GrB_Matrix A, // matrix to extract tuples from GB_Context Context ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- GrB_Info info ; GB_void *GB_RESTRICT X_bitmap = NULL ; int64_t *GB_RESTRICT Ap = NULL ; ASSERT_MATRIX_OK (A, "A to extract", GB0) ; ASSERT (p_nvals != NULL) ; // delete any lingering zombies and assemble any pending tuples; // allow A to remain jumbled GB_MATRIX_WAIT_IF_PENDING_OR_ZOMBIES (A) ; GB_BURBLE_DENSE (A, "(A %s) ") ; ASSERT (xcode <= GB_UDT_code) ; const GB_Type_code acode = A->type->code ; // xcode and A must be compatible if (!GB_code_compatible (xcode, acode)) { return (GrB_DOMAIN_MISMATCH) ; } const int64_t anz = GB_NNZ (A) ; if (anz == 0) { // no work to do (*p_nvals) = 0 ; return (GrB_SUCCESS) ; } int64_t nvals = *p_nvals ; // size of I,J,X on input if (nvals < anz && (I_out != NULL || J_out != NULL || X != NULL)) { // output arrays are not big enough return (GrB_INSUFFICIENT_SPACE) ; } const size_t asize = A->type->size ; //------------------------------------------------------------------------- // determine the number of threads to use //------------------------------------------------------------------------- GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ; int nthreads = GB_nthreads (anz + A->nvec, chunk, nthreads_max) ; //------------------------------------------------------------------------- // handle the CSR/CSC format //-------------------------------------------------------------------------- GrB_Index *I, *J ; if (A->is_csc) { I = I_out ; J = J_out ; } else { I = J_out ; J = I_out ; } //-------------------------------------------------------------------------- // bitmap case //-------------------------------------------------------------------------- if (GB_IS_BITMAP (A)) { //---------------------------------------------------------------------- // allocate workspace //---------------------------------------------------------------------- bool need_typecast = (X != NULL) && (xcode != acode) ; if (need_typecast) { // X must be typecasted int64_t anzmax = GB_IMAX (anz, 1) ; X_bitmap = GB_MALLOC (anzmax * asize, GB_void) ; } Ap = GB_MALLOC (A->vdim+1, int64_t) ; if (Ap == NULL || (need_typecast && X_bitmap == NULL)) { // out of memory GB_FREE_ALL ; return (GrB_OUT_OF_MEMORY) ; } //---------------------------------------------------------------------- // extract the tuples //---------------------------------------------------------------------- // TODO: pass xcode to GB_convert_bitmap_worker and let it do the // typecasting. This works for now, however. GB_OK (GB_convert_bitmap_worker (Ap, I, J, need_typecast ? X_bitmap : X, NULL, A, Context)) ; //---------------------------------------------------------------------- // typecast the result if needed //---------------------------------------------------------------------- if (need_typecast) { // typecast the values from X_bitmap into X GB_cast_array ((GB_void *) X, xcode, X_bitmap, acode, NULL, asize, anz, nthreads) ; } } else { //---------------------------------------------------------------------- // sparse, hypersparse, or full case //---------------------------------------------------------------------- //---------------------------------------------------------------------- // extract the row indices //---------------------------------------------------------------------- if (I != NULL) { if (A->i == NULL) { // A is full; construct the row indices int64_t avlen = A->vlen ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { I [p] = (p % avlen) ; } } else { GB_memcpy (I, A->i, anz * sizeof (int64_t), nthreads) ; } } //---------------------------------------------------------------------- // extract the column indices //---------------------------------------------------------------------- if (J != NULL) { if (!GB_extract_vector_list ((int64_t *) J, A, nthreads)) { // out of memory return (GrB_OUT_OF_MEMORY) ; } } //---------------------------------------------------------------------- // extract the values //---------------------------------------------------------------------- if (X != NULL) { // typecast or copy the values from A into X GB_cast_array ((GB_void *) X, xcode, (GB_void *) A->x, acode, NULL, asize, anz, nthreads) ; } } //-------------------------------------------------------------------------- // free workspace and return result //-------------------------------------------------------------------------- *p_nvals = anz ; // number of tuples extracted GB_FREE_ALL ; return (GrB_SUCCESS) ; }
image-view.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % IIIII M M AAA GGGG EEEEE % % I MM MM A A G E % % I M M M AAAAA G GG EEE % % I M M A A G G E % % IIIII M M A A GGGG EEEEE % % % % V V IIIII EEEEE W W % % V V I E W W % % V V I EEE W W W % % V V I E WW WW % % V IIIII EEEEE W W % % % % % % MagickCore Image View Methods % % % % Software Design % % Cristy % % March 2003 % % % % % % Copyright 1999-2019 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/MagickCore.h" #include "MagickCore/exception-private.h" #include "MagickCore/memory-private.h" #include "MagickCore/monitor-private.h" #include "MagickCore/thread-private.h" /* Typedef declarations. */ struct _ImageView { char *description; RectangleInfo extent; Image *image; CacheView *view; ExceptionInfo *exception; MagickBooleanType debug; size_t signature; }; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e I m a g e V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneImageView() makes a copy of the specified image view. % % The format of the CloneImageView method is: % % ImageView *CloneImageView(const ImageView *image_view) % % A description of each parameter follows: % % o image_view: the image view. % */ MagickExport ImageView *CloneImageView(const ImageView *image_view) { ImageView *clone_view; assert(image_view != (ImageView *) NULL); assert(image_view->signature == MagickCoreSignature); clone_view=(ImageView *) AcquireCriticalMemory(sizeof(*clone_view)); (void) memset(clone_view,0,sizeof(*clone_view)); clone_view->description=ConstantString(image_view->description); clone_view->extent=image_view->extent; clone_view->view=CloneCacheView(image_view->view); clone_view->exception=AcquireExceptionInfo(); InheritException(clone_view->exception,image_view->exception); clone_view->debug=image_view->debug; clone_view->signature=MagickCoreSignature; return(clone_view); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y I m a g e V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImageView() deallocates memory associated with a image view. % % The format of the DestroyImageView method is: % % ImageView *DestroyImageView(ImageView *image_view) % % A description of each parameter follows: % % o image_view: the image view. % */ MagickExport ImageView *DestroyImageView(ImageView *image_view) { assert(image_view != (ImageView *) NULL); assert(image_view->signature == MagickCoreSignature); if (image_view->description != (char *) NULL) image_view->description=DestroyString(image_view->description); image_view->view=DestroyCacheView(image_view->view); image_view->exception=DestroyExceptionInfo(image_view->exception); image_view->signature=(~MagickCoreSignature); image_view=(ImageView *) RelinquishMagickMemory(image_view); return(image_view); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D u p l e x T r a n s f e r I m a g e V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DuplexTransferImageViewIterator() iterates over three image views in % parallel and calls your transfer method for each scanline of the view. The % source and duplex pixel extent is not confined to the image canvas-- that is % you can include negative offsets or widths or heights that exceed the image % dimension. However, the destination image view is confined to the image % canvas-- that is no negative offsets or widths or heights that exceed the % image dimension are permitted. % % The callback signature is: % % MagickBooleanType DuplexTransferImageViewMethod(const ImageView *source, % const ImageView *duplex,ImageView *destination,const ssize_t y, % const int thread_id,void *context) % % Use this pragma if the view is not single threaded: % % #pragma omp critical % % to define a section of code in your callback transfer method that must be % executed by a single thread at a time. % % The format of the DuplexTransferImageViewIterator method is: % % MagickBooleanType DuplexTransferImageViewIterator(ImageView *source, % ImageView *duplex,ImageView *destination, % DuplexTransferImageViewMethod transfer,void *context) % % A description of each parameter follows: % % o source: the source image view. % % o duplex: the duplex image view. % % o destination: the destination image view. % % o transfer: the transfer callback method. % % o context: the user defined context. % */ MagickExport MagickBooleanType DuplexTransferImageViewIterator( ImageView *source,ImageView *duplex,ImageView *destination, DuplexTransferImageViewMethod transfer,void *context) { Image *destination_image, *source_image; MagickBooleanType status; MagickOffsetType progress; #if defined(MAGICKCORE_OPENMP_SUPPORT) size_t height; #endif ssize_t y; assert(source != (ImageView *) NULL); assert(source->signature == MagickCoreSignature); if (transfer == (DuplexTransferImageViewMethod) NULL) return(MagickFalse); source_image=source->image; destination_image=destination->image; status=SetImageStorageClass(destination_image,DirectClass, destination->exception); if (status == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) height=source->extent.height-source->extent.y; #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(source_image,destination_image,height,1) #endif for (y=source->extent.y; y < (ssize_t) source->extent.height; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register const Quantum *magick_restrict duplex_pixels, *magick_restrict pixels; register Quantum *magick_restrict destination_pixels; if (status == MagickFalse) continue; pixels=GetCacheViewVirtualPixels(source->view,source->extent.x,y, source->extent.width,1,source->exception); if (pixels == (const Quantum *) NULL) { status=MagickFalse; continue; } duplex_pixels=GetCacheViewVirtualPixels(duplex->view,duplex->extent.x,y, duplex->extent.width,1,duplex->exception); if (duplex_pixels == (const Quantum *) NULL) { status=MagickFalse; continue; } destination_pixels=GetCacheViewAuthenticPixels(destination->view, destination->extent.x,y,destination->extent.width,1, destination->exception); if (destination_pixels == (Quantum *) NULL) { status=MagickFalse; continue; } if (transfer(source,duplex,destination,y,id,context) == MagickFalse) status=MagickFalse; sync=SyncCacheViewAuthenticPixels(destination->view,destination->exception); if (sync == MagickFalse) status=MagickFalse; if (source_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(source_image,source->description,progress, source->extent.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i e w A u t h e n t i c M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageViewAuthenticMetacontent() returns the image view authentic % meta-content. % % The format of the GetImageViewAuthenticPixels method is: % % void *GetImageViewAuthenticMetacontent( % const ImageView *image_view) % % A description of each parameter follows: % % o image_view: the image view. % */ MagickExport void *GetImageViewAuthenticMetacontent( const ImageView *image_view) { assert(image_view != (ImageView *) NULL); assert(image_view->signature == MagickCoreSignature); return(GetCacheViewAuthenticMetacontent(image_view->view)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i e w A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageViewAuthenticPixels() returns the image view authentic pixels. % % The format of the GetImageViewAuthenticPixels method is: % % Quantum *GetImageViewAuthenticPixels(const ImageView *image_view) % % A description of each parameter follows: % % o image_view: the image view. % */ MagickExport Quantum *GetImageViewAuthenticPixels( const ImageView *image_view) { assert(image_view != (ImageView *) NULL); assert(image_view->signature == MagickCoreSignature); return(GetCacheViewAuthenticPixelQueue(image_view->view)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i e w E x c e p t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageViewException() returns the severity, reason, and description of any % error that occurs when utilizing a image view. % % The format of the GetImageViewException method is: % % char *GetImageViewException(const PixelImage *image_view, % ExceptionType *severity) % % A description of each parameter follows: % % o image_view: the pixel image_view. % % o severity: the severity of the error is returned here. % */ MagickExport char *GetImageViewException(const ImageView *image_view, ExceptionType *severity) { char *description; assert(image_view != (const ImageView *) NULL); assert(image_view->signature == MagickCoreSignature); assert(severity != (ExceptionType *) NULL); *severity=image_view->exception->severity; description=(char *) AcquireQuantumMemory(2UL*MagickPathExtent, sizeof(*description)); if (description == (char *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); *description='\0'; if (image_view->exception->reason != (char *) NULL) (void) CopyMagickString(description,GetLocaleExceptionMessage( image_view->exception->severity,image_view->exception->reason), MagickPathExtent); if (image_view->exception->description != (char *) NULL) { (void) ConcatenateMagickString(description," (",MagickPathExtent); (void) ConcatenateMagickString(description,GetLocaleExceptionMessage( image_view->exception->severity,image_view->exception->description), MagickPathExtent); (void) ConcatenateMagickString(description,")",MagickPathExtent); } return(description); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i e w E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageViewExtent() returns the image view extent. % % The format of the GetImageViewExtent method is: % % RectangleInfo GetImageViewExtent(const ImageView *image_view) % % A description of each parameter follows: % % o image_view: the image view. % */ MagickExport RectangleInfo GetImageViewExtent(const ImageView *image_view) { assert(image_view != (ImageView *) NULL); assert(image_view->signature == MagickCoreSignature); return(image_view->extent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i e w I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageViewImage() returns the image associated with the image view. % % The format of the GetImageViewImage method is: % % MagickCore *GetImageViewImage(const ImageView *image_view) % % A description of each parameter follows: % % o image_view: the image view. % */ MagickExport Image *GetImageViewImage(const ImageView *image_view) { assert(image_view != (ImageView *) NULL); assert(image_view->signature == MagickCoreSignature); return(image_view->image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageViewIterator() iterates over the image view in parallel and calls % your get method for each scanline of the view. The pixel extent is % not confined to the image canvas-- that is you can include negative offsets % or widths or heights that exceed the image dimension. Any updates to % the pixels in your callback are ignored. % % The callback signature is: % % MagickBooleanType GetImageViewMethod(const ImageView *source, % const ssize_t y,const int thread_id,void *context) % % Use this pragma if the view is not single threaded: % % #pragma omp critical % % to define a section of code in your callback get method that must be % executed by a single thread at a time. % % The format of the GetImageViewIterator method is: % % MagickBooleanType GetImageViewIterator(ImageView *source, % GetImageViewMethod get,void *context) % % A description of each parameter follows: % % o source: the source image view. % % o get: the get callback method. % % o context: the user defined context. % */ MagickExport MagickBooleanType GetImageViewIterator(ImageView *source, GetImageViewMethod get,void *context) { Image *source_image; MagickBooleanType status; MagickOffsetType progress; #if defined(MAGICKCORE_OPENMP_SUPPORT) size_t height; #endif ssize_t y; assert(source != (ImageView *) NULL); assert(source->signature == MagickCoreSignature); if (get == (GetImageViewMethod) NULL) return(MagickFalse); source_image=source->image; status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) height=source->extent.height-source->extent.y; #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(source_image,source_image,height,1) #endif for (y=source->extent.y; y < (ssize_t) source->extent.height; y++) { const int id = GetOpenMPThreadId(); register const Quantum *pixels; if (status == MagickFalse) continue; pixels=GetCacheViewVirtualPixels(source->view,source->extent.x,y, source->extent.width,1,source->exception); if (pixels == (const Quantum *) NULL) { status=MagickFalse; continue; } if (get(source,y,id,context) == MagickFalse) status=MagickFalse; if (source_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(source_image,source->description,progress, source->extent.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i e w V i r t u a l M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageViewVirtualMetacontent() returns the image view virtual % meta-content. % % The format of the GetImageViewVirtualMetacontent method is: % % const void *GetImageViewVirtualMetacontent( % const ImageView *image_view) % % A description of each parameter follows: % % o image_view: the image view. % */ MagickExport const void *GetImageViewVirtualMetacontent( const ImageView *image_view) { assert(image_view != (ImageView *) NULL); assert(image_view->signature == MagickCoreSignature); return(GetCacheViewVirtualMetacontent(image_view->view)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i e w V i r t u a l P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageViewVirtualPixels() returns the image view virtual pixels. % % The format of the GetImageViewVirtualPixels method is: % % const Quantum *GetImageViewVirtualPixels(const ImageView *image_view) % % A description of each parameter follows: % % o image_view: the image view. % */ MagickExport const Quantum *GetImageViewVirtualPixels( const ImageView *image_view) { assert(image_view != (ImageView *) NULL); assert(image_view->signature == MagickCoreSignature); return(GetCacheViewVirtualPixelQueue(image_view->view)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s I m a g e V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsImageView() returns MagickTrue if the the parameter is verified as a image % view object. % % The format of the IsImageView method is: % % MagickBooleanType IsImageView(const ImageView *image_view) % % A description of each parameter follows: % % o image_view: the image view. % */ MagickExport MagickBooleanType IsImageView(const ImageView *image_view) { if (image_view == (const ImageView *) NULL) return(MagickFalse); if (image_view->signature != MagickCoreSignature) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N e w I m a g e V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % NewImageView() returns a image view required for all other methods in the % Image View API. % % The format of the NewImageView method is: % % ImageView *NewImageView(MagickCore *wand,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport ImageView *NewImageView(Image *image,ExceptionInfo *exception) { ImageView *image_view; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); image_view=(ImageView *) AcquireCriticalMemory(sizeof(*image_view)); (void) memset(image_view,0,sizeof(*image_view)); image_view->description=ConstantString("ImageView"); image_view->image=image; image_view->view=AcquireVirtualCacheView(image_view->image,exception); image_view->extent.width=image->columns; image_view->extent.height=image->rows; image_view->extent.x=0; image_view->extent.y=0; image_view->exception=AcquireExceptionInfo(); image_view->debug=IsEventLogging(); image_view->signature=MagickCoreSignature; return(image_view); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N e w I m a g e V i e w R e g i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % NewImageViewRegion() returns a image view required for all other methods % in the Image View API. % % The format of the NewImageViewRegion method is: % % ImageView *NewImageViewRegion(MagickCore *wand,const ssize_t x, % const ssize_t y,const size_t width,const size_t height, % ExceptionInfo *exception) % % A description of each parameter follows: % % o wand: the magick wand. % % o x,y,columns,rows: These values define the perimeter of a extent of % pixel_wands view. % % o exception: return any errors or warnings in this structure. % */ MagickExport ImageView *NewImageViewRegion(Image *image,const ssize_t x, const ssize_t y,const size_t width,const size_t height, ExceptionInfo *exception) { ImageView *image_view; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); image_view=(ImageView *) AcquireCriticalMemory(sizeof(*image_view)); (void) memset(image_view,0,sizeof(*image_view)); image_view->description=ConstantString("ImageView"); image_view->view=AcquireVirtualCacheView(image_view->image,exception); image_view->image=image; image_view->extent.width=width; image_view->extent.height=height; image_view->extent.x=x; image_view->extent.y=y; image_view->exception=AcquireExceptionInfo(); image_view->debug=IsEventLogging(); image_view->signature=MagickCoreSignature; return(image_view); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e V i e w D e s c r i p t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageViewDescription() associates a description with an image view. % % The format of the SetImageViewDescription method is: % % void SetImageViewDescription(ImageView *image_view, % const char *description) % % A description of each parameter follows: % % o image_view: the image view. % % o description: the image view description. % */ MagickExport void SetImageViewDescription(ImageView *image_view, const char *description) { assert(image_view != (ImageView *) NULL); assert(image_view->signature == MagickCoreSignature); image_view->description=ConstantString(description); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageViewIterator() iterates over the image view in parallel and calls % your set method for each scanline of the view. The pixel extent is % confined to the image canvas-- that is no negative offsets or widths or % heights that exceed the image dimension. The pixels are initiallly % undefined and any settings you make in the callback method are automagically % synced back to your image. % % The callback signature is: % % MagickBooleanType SetImageViewMethod(ImageView *destination, % const ssize_t y,const int thread_id,void *context) % % Use this pragma if the view is not single threaded: % % #pragma omp critical % % to define a section of code in your callback set method that must be % executed by a single thread at a time. % % The format of the SetImageViewIterator method is: % % MagickBooleanType SetImageViewIterator(ImageView *destination, % SetImageViewMethod set,void *context) % % A description of each parameter follows: % % o destination: the image view. % % o set: the set callback method. % % o context: the user defined context. % */ MagickExport MagickBooleanType SetImageViewIterator(ImageView *destination, SetImageViewMethod set,void *context) { Image *destination_image; MagickBooleanType status; MagickOffsetType progress; #if defined(MAGICKCORE_OPENMP_SUPPORT) size_t height; #endif ssize_t y; assert(destination != (ImageView *) NULL); assert(destination->signature == MagickCoreSignature); if (set == (SetImageViewMethod) NULL) return(MagickFalse); destination_image=destination->image; status=SetImageStorageClass(destination_image,DirectClass, destination->exception); if (status == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) height=destination->extent.height-destination->extent.y; #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(destination_image,destination_image,height,1) #endif for (y=destination->extent.y; y < (ssize_t) destination->extent.height; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register Quantum *magick_restrict pixels; if (status == MagickFalse) continue; pixels=GetCacheViewAuthenticPixels(destination->view,destination->extent.x, y,destination->extent.width,1,destination->exception); if (pixels == (Quantum *) NULL) { status=MagickFalse; continue; } if (set(destination,y,id,context) == MagickFalse) status=MagickFalse; sync=SyncCacheViewAuthenticPixels(destination->view,destination->exception); if (sync == MagickFalse) status=MagickFalse; if (destination_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(destination_image,destination->description, progress,destination->extent.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s f e r I m a g e V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransferImageViewIterator() iterates over two image views in parallel and % calls your transfer method for each scanline of the view. The source pixel % extent is not confined to the image canvas-- that is you can include % negative offsets or widths or heights that exceed the image dimension. % However, the destination image view is confined to the image canvas-- that % is no negative offsets or widths or heights that exceed the image dimension % are permitted. % % The callback signature is: % % MagickBooleanType TransferImageViewMethod(const ImageView *source, % ImageView *destination,const ssize_t y,const int thread_id, % void *context) % % Use this pragma if the view is not single threaded: % % #pragma omp critical % % to define a section of code in your callback transfer method that must be % executed by a single thread at a time. % % The format of the TransferImageViewIterator method is: % % MagickBooleanType TransferImageViewIterator(ImageView *source, % ImageView *destination,TransferImageViewMethod transfer,void *context) % % A description of each parameter follows: % % o source: the source image view. % % o destination: the destination image view. % % o transfer: the transfer callback method. % % o context: the user defined context. % */ MagickExport MagickBooleanType TransferImageViewIterator(ImageView *source, ImageView *destination,TransferImageViewMethod transfer,void *context) { Image *destination_image, *source_image; MagickBooleanType status; MagickOffsetType progress; #if defined(MAGICKCORE_OPENMP_SUPPORT) size_t height; #endif ssize_t y; assert(source != (ImageView *) NULL); assert(source->signature == MagickCoreSignature); if (transfer == (TransferImageViewMethod) NULL) return(MagickFalse); source_image=source->image; destination_image=destination->image; status=SetImageStorageClass(destination_image,DirectClass, destination->exception); if (status == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) height=source->extent.height-source->extent.y; #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(source_image,destination_image,height,1) #endif for (y=source->extent.y; y < (ssize_t) source->extent.height; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register const Quantum *magick_restrict pixels; register Quantum *magick_restrict destination_pixels; if (status == MagickFalse) continue; pixels=GetCacheViewVirtualPixels(source->view,source->extent.x,y, source->extent.width,1,source->exception); if (pixels == (const Quantum *) NULL) { status=MagickFalse; continue; } destination_pixels=GetCacheViewAuthenticPixels(destination->view, destination->extent.x,y,destination->extent.width,1, destination->exception); if (destination_pixels == (Quantum *) NULL) { status=MagickFalse; continue; } if (transfer(source,destination,y,id,context) == MagickFalse) status=MagickFalse; sync=SyncCacheViewAuthenticPixels(destination->view,destination->exception); if (sync == MagickFalse) status=MagickFalse; if (source_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(source_image,source->description,progress, source->extent.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U p d a t e I m a g e V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UpdateImageViewIterator() iterates over the image view in parallel and calls % your update method for each scanline of the view. The pixel extent is % confined to the image canvas-- that is no negative offsets or widths or % heights that exceed the image dimension are permitted. Updates to pixels % in your callback are automagically synced back to the image. % % The callback signature is: % % MagickBooleanType UpdateImageViewMethod(ImageView *source, % const ssize_t y,const int thread_id,void *context) % % Use this pragma if the view is not single threaded: % % #pragma omp critical % % to define a section of code in your callback update method that must be % executed by a single thread at a time. % % The format of the UpdateImageViewIterator method is: % % MagickBooleanType UpdateImageViewIterator(ImageView *source, % UpdateImageViewMethod update,void *context) % % A description of each parameter follows: % % o source: the source image view. % % o update: the update callback method. % % o context: the user defined context. % */ MagickExport MagickBooleanType UpdateImageViewIterator(ImageView *source, UpdateImageViewMethod update,void *context) { Image *source_image; MagickBooleanType status; MagickOffsetType progress; #if defined(MAGICKCORE_OPENMP_SUPPORT) size_t height; #endif ssize_t y; assert(source != (ImageView *) NULL); assert(source->signature == MagickCoreSignature); if (update == (UpdateImageViewMethod) NULL) return(MagickFalse); source_image=source->image; status=SetImageStorageClass(source_image,DirectClass,source->exception); if (status == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) height=source->extent.height-source->extent.y; #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(source_image,source_image,height,1) #endif for (y=source->extent.y; y < (ssize_t) source->extent.height; y++) { const int id = GetOpenMPThreadId(); register Quantum *magick_restrict pixels; if (status == MagickFalse) continue; pixels=GetCacheViewAuthenticPixels(source->view,source->extent.x,y, source->extent.width,1,source->exception); if (pixels == (Quantum *) NULL) { status=MagickFalse; continue; } if (update(source,y,id,context) == MagickFalse) status=MagickFalse; status=SyncCacheViewAuthenticPixels(source->view,source->exception); if (status == MagickFalse) status=MagickFalse; if (source_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(source_image,source->description,progress, source->extent.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); }
vectors_utils.h
//------------------------------------------------------------------------------ // // VECTOR UTILS // Utils to work with Eigen::VectorXd // //------------------------------------------------------------------------------ #ifndef VECTORS_UTILS #define VECTORS_UTILS //STL libs #include<vector> #include<iostream> #include<string> #include<fstream> #include<math.h> //Eigen libs #include "Eigen/Dense" //OpenMP #include<omp.h> //------------------------------------------------------------------------------ // (pseudo)norms of a vector and related functions //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Compute the square of a Euclidean norm of a vector inline double norm_squared(const Eigen::VectorXd &vec) { int len = vec.size(); double sum = 0.; for (int i = 0; i < len; i++) { sum += vec(i)*vec(i); } return sum; } //------------------------------------------------------------------------------ //Compute the Euclidean norm of a vector inline double norm(const Eigen::VectorXd &vec) { int len = vec.size(); double sum = 0.; for (int i = 0; i < len; i++) { sum += vec(i)*vec(i); } sum = sqrt(sum); return sum; } //------------------------------------------------------------------------------ //Action of a degenerate bilinear form on two vectors inline double degenerate_bilinear_form(Eigen::VectorXd &v1, Eigen::VectorXd &v2, Eigen::MatrixXd &mat) { Eigen::VectorXd temp = std::move(mat*v2); double res = v1.dot(temp); return res; } //------------------------------------------------------------------------------ //Normalize a vector w.r.t a given non-degenerate bilinear form inline Eigen::VectorXd normalize(Eigen::VectorXd &point, Eigen::MatrixXd &mat) { Eigen::VectorXd res(point.size()); double norm = std::move(degenerate_bilinear_form(point, point, mat)); norm = sqrt(norm); res = res / norm; return res; } //------------------------------------------------------------------------------ //Normalize a collection of vectors w.r.t a given degenerate bilinear form inline std::vector<Eigen::VectorXd> normalize(std::vector<Eigen::VectorXd> &points, Eigen::MatrixXd &mat) { int len = points.size(); std::vector<Eigen::VectorXd> res(len); #pragma omp parallel for for (int i = 0; i < len; i++) { res[i] = std::move(normalize(points[i],mat)); } return res; } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Conversion between different formats //------------------------------------------------------------------------------ //From Eigen::VectorXd to std::vector<double> inline std::vector<double> vector_eigen_to_std(Eigen::VectorXd &vec) { int size = vec.size(); std::vector<double> res(size); for (int i = 0; i < size; i++) { res[i] = vec(i); } return res; } //------------------------------------------------------------------------------ //From std::vector<double> to Eigen::VectorXd inline Eigen::VectorXd vector_std_to_eigen(std::vector<double> &vec) { int size = vec.size(); Eigen::VectorXd res(size); for (int i = 0; i < size; i++) { res[i] = vec[i]; } return res; } //------------------------------------------------------------------------------ //Convert a collection of std::vector<double> to a collection of Eigen::VectorXd inline std::vector<Eigen::VectorXd> vector_vector_data_to_vector_eigenv(std::vector<std::vector<double>> &data) { int size = data.size(); std::vector<Eigen::VectorXd> res(size); for (int i = 0; i < size; i++) { res[i] = vector_std_to_eigen(data[i]); } return res; } //------------------------------------------------------------------------------ //Convert a collection of Eigen::VectorXd to a collection of std::vector<double> inline std::vector<Eigen::VectorXd> vector_double_data_to_vector_eigenv(std::vector<double> &data) { int size = data.size(); std::vector<Eigen::VectorXd> res(size); for (int i = 0; i < size; i++) { Eigen::VectorXd temp(1); temp(0) = data[i]; res[i] = std::move(temp); } return res; } //------------------------------------------------------------------------------ // OTHER UTILS //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Find the max in a vector inline double find_max(const Eigen::VectorXd &vec) { int len = vec.size(); double max = vec(0); for (int i = 1; i < len; i++) { if (max < vec(i)) max = vec(i); } return max; } //------------------------------------------------------------------------------ //Find the min in a vector inline double find_min(const Eigen::VectorXd &vec) { int len = vec.size(); double min = vec(0); for (int i = 1; i < len; i++) { if (min > vec(i)) min = vec(i); } return min; } //------------------------------------------------------------------------------ //Check if all the entries of a vector are positive inline bool all_positive(Eigen::VectorXd &vec) { bool res = true; int len = vec.size(); for(int i = 0; i < len; i++) { if (vec(i) < 0) { res = false; break; } } return res; } //------------------------------------------------------------------------------ //Set to zero all the entries less than a given epsilon inline void round_epsilon(Eigen::VectorXd &vec, double epsilon) { int len = vec.size(); for(int i = 0; i < len; i++) { if (abs(vec(i)) < epsilon) { vec(i) = 0; } } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // GEOMETRY UTILS //------------------------------------------------------------------------------ //Reflect a vector on the boundaries of (0,1)^n inline void boundary_reflection(Eigen::VectorXd &vec, Eigen::VectorXd &point, double epsilon) { int len = vec.size(); for(int i = 0; i < len; i++) { if (point(i)<epsilon) { if (vec(i) < epsilon) { vec(i) = -1.*vec(i); } } if (point(i)>1-epsilon) { if (vec(i) > epsilon) { vec(i) = -1.*vec(i); } } } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Read/Write a vector from/to file //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Write a vector to file inline void write_eigen_vectorxf_to_file(std::string filename, char separating_char, Eigen::VectorXd &vec) { std::ofstream file; file.open(filename); int len = vec.size(); for (int i = 0; i < len-1; i++) { file << vec(i); file << separating_char; } file << vec(len-1); file.close(); } //------------------------------------------------------------------------------ //Read a vector from file inline void read_eigen_vectorxd_to_file(std::string filename, char separating_char, Eigen::VectorXd &vec) { std::ifstream file(filename); std::string str_read; if (file.is_open()) { getline(file,str_read); std::vector<std::string> str_vec; int pos = str_read.find(separating_char); int i = 1; while (pos > 0) { std::string temp; temp = str_read.substr(0, pos); str_read.erase(0,pos+1); str_vec.push_back(temp); i++; pos = str_read.find(separating_char); } str_vec.push_back(str_read); vec = std::move(Eigen::VectorXd::Zero(i)); for (int j = 0; j < i; j++) { vec(j) = std::__cxx11::stod(str_vec[j]); } } else { std::cerr << "read_eigen_Eigen::VectorXd_to_file : File not found." << std::endl; } } #endif /* VECTORS_UTILS */
convolution_1x1.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2017 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 __ARM_NEON #include <arm_neon.h> #endif // __ARM_NEON static void conv1x1s1_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias) { int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const float* kernel = _kernel; const float* bias = _bias; int nn_outch = 0; int remain_outch_start = 0; #if __ARM_NEON && __aarch64__ nn_outch = outch >> 3; remain_outch_start = nn_outch << 3; #pragma omp parallel for for (int pp=0; pp<nn_outch; pp++) { int p = pp * 8; Mat out0 = top_blob.channel(p); Mat out1 = top_blob.channel(p+1); Mat out2 = top_blob.channel(p+2); Mat out3 = top_blob.channel(p+3); Mat out4 = top_blob.channel(p+4); Mat out5 = top_blob.channel(p+5); Mat out6 = top_blob.channel(p+6); Mat out7 = top_blob.channel(p+7); const float bias0 = bias ? bias[p] : 0.f; const float bias1 = bias ? bias[p+1] : 0.f; const float bias2 = bias ? bias[p+2] : 0.f; const float bias3 = bias ? bias[p+3] : 0.f; const float bias4 = bias ? bias[p+4] : 0.f; const float bias5 = bias ? bias[p+5] : 0.f; const float bias6 = bias ? bias[p+6] : 0.f; const float bias7 = bias ? bias[p+7] : 0.f; out0.fill(bias0); out1.fill(bias1); out2.fill(bias2); out3.fill(bias3); out4.fill(bias4); out5.fill(bias5); out6.fill(bias6); out7.fill(bias7); int q = 0; for (; q+7<inch; q+=8) { float* outptr0 = out0; float* outptr1 = out1; float* outptr2 = out2; float* outptr3 = out3; float* outptr4 = out4; float* outptr5 = out5; float* outptr6 = out6; float* outptr7 = out7; const float* img0 = bottom_blob.channel(q); const float* img1 = bottom_blob.channel(q+1); const float* img2 = bottom_blob.channel(q+2); const float* img3 = bottom_blob.channel(q+3); const float* img4 = bottom_blob.channel(q+4); const float* img5 = bottom_blob.channel(q+5); const float* img6 = bottom_blob.channel(q+6); const float* img7 = bottom_blob.channel(q+7); const float* kernel0 = kernel + p*inch + q; const float* kernel1 = kernel + (p+1)*inch + q; const float* kernel2 = kernel + (p+2)*inch + q; const float* kernel3 = kernel + (p+3)*inch + q; const float* kernel4 = kernel + (p+4)*inch + q; const float* kernel5 = kernel + (p+5)*inch + q; const float* kernel6 = kernel + (p+6)*inch + q; const float* kernel7 = kernel + (p+7)*inch + q; const float* r0 = img0; const float* r1 = img1; const float* r2 = img2; const float* r3 = img3; const float* r4 = img4; const float* r5 = img5; const float* r6 = img6; const float* r7 = img7; int size = outw * outh; int nn = size >> 2; int remain = size & 3; float32x4_t _k0 = vld1q_f32(kernel0); float32x4_t _k1 = vld1q_f32(kernel1); float32x4_t _k2 = vld1q_f32(kernel2); float32x4_t _k3 = vld1q_f32(kernel3); float32x4_t _k4 = vld1q_f32(kernel4); float32x4_t _k5 = vld1q_f32(kernel5); float32x4_t _k6 = vld1q_f32(kernel6); float32x4_t _k7 = vld1q_f32(kernel7); float32x4_t _k0n = vld1q_f32(kernel0+4); float32x4_t _k1n = vld1q_f32(kernel1+4); float32x4_t _k2n = vld1q_f32(kernel2+4); float32x4_t _k3n = vld1q_f32(kernel3+4); float32x4_t _k4n = vld1q_f32(kernel4+4); float32x4_t _k5n = vld1q_f32(kernel5+4); float32x4_t _k6n = vld1q_f32(kernel6+4); float32x4_t _k7n = vld1q_f32(kernel7+4); #ifdef __clang__ // gcc reject over 30 oprands :( if (nn > 0) { asm volatile( "prfm pldl1keep, [%9, #128] \n" "ld1 {v17.4s}, [%9], #16 \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v18.4s}, [%1] \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v19.4s}, [%2] \n" "0: \n" "fmla v18.4s, v17.4s, %34.s[0] \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v20.4s}, [%3] \n" "fmla v19.4s, v17.4s, %35.s[0] \n" "prfm pldl1keep, [%4, #128] \n" "ld1 {v21.4s}, [%4] \n" "fmla v20.4s, v17.4s, %36.s[0] \n" "prfm pldl1keep, [%5, #128] \n" "ld1 {v22.4s}, [%5] \n" "fmla v21.4s, v17.4s, %37.s[0] \n" "prfm pldl1keep, [%6, #128] \n" "ld1 {v23.4s}, [%6] \n" "fmla v22.4s, v17.4s, %38.s[0] \n" "prfm pldl1keep, [%10, #128] \n" "ld1 {v16.4s}, [%10], #16 \n" "fmla v23.4s, v17.4s, %39.s[0] \n" "prfm pldl1keep, [%7, #128] \n" "ld1 {v24.4s}, [%7] \n" "fmla v18.4s, v16.4s, %34.s[1] \n" "fmla v19.4s, v16.4s, %35.s[1] \n" "prfm pldl1keep, [%8, #128] \n" "ld1 {v25.4s}, [%8] \n" "fmla v24.4s, v17.4s, %40.s[0] \n" "fmla v25.4s, v17.4s, %41.s[0] \n" "fmla v20.4s, v16.4s, %36.s[1] \n" "fmla v21.4s, v16.4s, %37.s[1] \n" "prfm pldl1keep, [%11, #128] \n" "ld1 {v17.4s}, [%11], #16 \n" "fmla v22.4s, v16.4s, %38.s[1] \n" "fmla v23.4s, v16.4s, %39.s[1] \n" "fmla v18.4s, v17.4s, %34.s[2] \n" "fmla v19.4s, v17.4s, %35.s[2] \n" "fmla v24.4s, v16.4s, %40.s[1] \n" "fmla v25.4s, v16.4s, %41.s[1] \n" "fmla v20.4s, v17.4s, %36.s[2] \n" "fmla v21.4s, v17.4s, %37.s[2] \n" "prfm pldl1keep, [%12, #128] \n" "ld1 {v16.4s}, [%12], #16 \n" "fmla v22.4s, v17.4s, %38.s[2] \n" "fmla v23.4s, v17.4s, %39.s[2] \n" "fmla v18.4s, v16.4s, %34.s[3] \n" "fmla v19.4s, v16.4s, %35.s[3] \n" "fmla v24.4s, v17.4s, %40.s[2] \n" "fmla v25.4s, v17.4s, %41.s[2] \n" "fmla v20.4s, v16.4s, %36.s[3] \n" "fmla v21.4s, v16.4s, %37.s[3] \n" "prfm pldl1keep, [%13, #128] \n" "ld1 {v17.4s}, [%13], #16 \n" "fmla v22.4s, v16.4s, %38.s[3] \n" "fmla v23.4s, v16.4s, %39.s[3] \n" "fmla v18.4s, v17.4s, %42.s[0] \n" "fmla v19.4s, v17.4s, %43.s[0] \n" "fmla v24.4s, v16.4s, %40.s[3] \n" "fmla v25.4s, v16.4s, %41.s[3] \n" "fmla v20.4s, v17.4s, %44.s[0] \n" "fmla v21.4s, v17.4s, %45.s[0] \n" "prfm pldl1keep, [%14, #128] \n" "ld1 {v16.4s}, [%14], #16 \n" "fmla v22.4s, v17.4s, %46.s[0] \n" "fmla v23.4s, v17.4s, %47.s[0] \n" "fmla v18.4s, v16.4s, %42.s[1] \n" "fmla v19.4s, v16.4s, %43.s[1] \n" "fmla v24.4s, v17.4s, %48.s[0] \n" "fmla v25.4s, v17.4s, %49.s[0] \n" "fmla v20.4s, v16.4s, %44.s[1] \n" "fmla v21.4s, v16.4s, %45.s[1] \n" "prfm pldl1keep, [%15, #128] \n" "ld1 {v17.4s}, [%15], #16 \n" "fmla v22.4s, v16.4s, %46.s[1] \n" "fmla v23.4s, v16.4s, %47.s[1] \n" "fmla v18.4s, v17.4s, %42.s[2] \n" "fmla v19.4s, v17.4s, %43.s[2] \n" "fmla v24.4s, v16.4s, %48.s[1] \n" "fmla v25.4s, v16.4s, %49.s[1] \n" "fmla v20.4s, v17.4s, %44.s[2] \n" "fmla v21.4s, v17.4s, %45.s[2] \n" "prfm pldl1keep, [%16, #128] \n" "ld1 {v16.4s}, [%16], #16 \n" "fmla v22.4s, v17.4s, %46.s[2] \n" "fmla v23.4s, v17.4s, %47.s[2] \n" "fmla v18.4s, v16.4s, %42.s[3] \n" "fmla v19.4s, v16.4s, %43.s[3] \n" "fmla v24.4s, v17.4s, %48.s[2] \n" "fmla v25.4s, v17.4s, %49.s[2] \n" "fmla v20.4s, v16.4s, %44.s[3] \n" "fmla v21.4s, v16.4s, %45.s[3] \n" "st1 {v18.4s}, [%1], #16 \n" "fmla v22.4s, v16.4s, %46.s[3] \n" "st1 {v19.4s}, [%2], #16 \n" "fmla v23.4s, v16.4s, %47.s[3] \n" "st1 {v20.4s}, [%3], #16 \n" "prfm pldl1keep, [%9, #128] \n" "ld1 {v17.4s}, [%9], #16 \n" "fmla v24.4s, v16.4s, %48.s[3] \n" "st1 {v21.4s}, [%4], #16 \n" "fmla v25.4s, v16.4s, %49.s[3] \n" "st1 {v22.4s}, [%5], #16 \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v18.4s}, [%1] \n" "st1 {v23.4s}, [%6], #16 \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v19.4s}, [%2] \n" "st1 {v24.4s}, [%7], #16 \n" "subs %w0, %w0, #1 \n" "st1 {v25.4s}, [%8], #16 \n" "bne 0b \n" "sub %9, %9, #16 \n" : "=r"(nn), // %0 "=r"(outptr0),// %1 "=r"(outptr1),// %2 "=r"(outptr2),// %3 "=r"(outptr3),// %4 "=r"(outptr4),// %5 "=r"(outptr5),// %6 "=r"(outptr6),// %7 "=r"(outptr7),// %8 "=r"(r0), // %9 "=r"(r1), // %10 "=r"(r2), // %11 "=r"(r3), // %12 "=r"(r4), // %13 "=r"(r5), // %14 "=r"(r6), // %15 "=r"(r7) // %16 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(outptr4), "6"(outptr5), "7"(outptr6), "8"(outptr7), "9"(r0), "10"(r1), "11"(r2), "12"(r3), "13"(r4), "14"(r5), "15"(r6), "16"(r7), "w"(_k0), // %34 "w"(_k1), // %35 "w"(_k2), // %36 "w"(_k3), // %37 "w"(_k4), // %38 "w"(_k5), // %39 "w"(_k6), // %40 "w"(_k7), // %41 "w"(_k0n), // %42 "w"(_k1n), // %43 "w"(_k2n), // %44 "w"(_k3n), // %45 "w"(_k4n), // %46 "w"(_k5n), // %47 "w"(_k6n), // %48 "w"(_k7n) // %49 : "cc", "memory", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25"//, "v26", "v27", "v28", "v29", "v30", "v31" ); } #else for (; nn>0; nn--) { float32x4_t _p = vld1q_f32(r0); float32x4_t _out0p = vld1q_f32(outptr0); float32x4_t _out1p = vld1q_f32(outptr1); float32x4_t _out2p = vld1q_f32(outptr2); float32x4_t _out3p = vld1q_f32(outptr3); float32x4_t _out4p = vld1q_f32(outptr4); float32x4_t _out5p = vld1q_f32(outptr5); float32x4_t _out6p = vld1q_f32(outptr6); float32x4_t _out7p = vld1q_f32(outptr7); _out0p = vfmaq_laneq_f32(_out0p, _p, _k0, 0); _out1p = vfmaq_laneq_f32(_out1p, _p, _k1, 0); _out2p = vfmaq_laneq_f32(_out2p, _p, _k2, 0); _out3p = vfmaq_laneq_f32(_out3p, _p, _k3, 0); _out4p = vfmaq_laneq_f32(_out4p, _p, _k4, 0); _out5p = vfmaq_laneq_f32(_out5p, _p, _k5, 0); _out6p = vfmaq_laneq_f32(_out6p, _p, _k6, 0); _out7p = vfmaq_laneq_f32(_out7p, _p, _k7, 0); float32x4_t _p1 = vld1q_f32(r1); _out0p = vfmaq_laneq_f32(_out0p, _p1, _k0, 1); _out1p = vfmaq_laneq_f32(_out1p, _p1, _k1, 1); _out2p = vfmaq_laneq_f32(_out2p, _p1, _k2, 1); _out3p = vfmaq_laneq_f32(_out3p, _p1, _k3, 1); _out4p = vfmaq_laneq_f32(_out4p, _p1, _k4, 1); _out5p = vfmaq_laneq_f32(_out5p, _p1, _k5, 1); _out6p = vfmaq_laneq_f32(_out6p, _p1, _k6, 1); _out7p = vfmaq_laneq_f32(_out7p, _p1, _k7, 1); float32x4_t _p2 = vld1q_f32(r2); _out0p = vfmaq_laneq_f32(_out0p, _p2, _k0, 2); _out1p = vfmaq_laneq_f32(_out1p, _p2, _k1, 2); _out2p = vfmaq_laneq_f32(_out2p, _p2, _k2, 2); _out3p = vfmaq_laneq_f32(_out3p, _p2, _k3, 2); _out4p = vfmaq_laneq_f32(_out4p, _p2, _k4, 2); _out5p = vfmaq_laneq_f32(_out5p, _p2, _k5, 2); _out6p = vfmaq_laneq_f32(_out6p, _p2, _k6, 2); _out7p = vfmaq_laneq_f32(_out7p, _p2, _k7, 2); float32x4_t _p3 = vld1q_f32(r3); _out0p = vfmaq_laneq_f32(_out0p, _p3, _k0, 3); _out1p = vfmaq_laneq_f32(_out1p, _p3, _k1, 3); _out2p = vfmaq_laneq_f32(_out2p, _p3, _k2, 3); _out3p = vfmaq_laneq_f32(_out3p, _p3, _k3, 3); _out4p = vfmaq_laneq_f32(_out4p, _p3, _k4, 3); _out5p = vfmaq_laneq_f32(_out5p, _p3, _k5, 3); _out6p = vfmaq_laneq_f32(_out6p, _p3, _k6, 3); _out7p = vfmaq_laneq_f32(_out7p, _p3, _k7, 3); float32x4_t _p4 = vld1q_f32(r4); _out0p = vfmaq_laneq_f32(_out0p, _p4, _k0n, 0); _out1p = vfmaq_laneq_f32(_out1p, _p4, _k1n, 0); _out2p = vfmaq_laneq_f32(_out2p, _p4, _k2n, 0); _out3p = vfmaq_laneq_f32(_out3p, _p4, _k3n, 0); _out4p = vfmaq_laneq_f32(_out4p, _p4, _k4n, 0); _out5p = vfmaq_laneq_f32(_out5p, _p4, _k5n, 0); _out6p = vfmaq_laneq_f32(_out6p, _p4, _k6n, 0); _out7p = vfmaq_laneq_f32(_out7p, _p4, _k7n, 0); float32x4_t _p5 = vld1q_f32(r5); _out0p = vfmaq_laneq_f32(_out0p, _p5, _k0n, 1); _out1p = vfmaq_laneq_f32(_out1p, _p5, _k1n, 1); _out2p = vfmaq_laneq_f32(_out2p, _p5, _k2n, 1); _out3p = vfmaq_laneq_f32(_out3p, _p5, _k3n, 1); _out4p = vfmaq_laneq_f32(_out4p, _p5, _k4n, 1); _out5p = vfmaq_laneq_f32(_out5p, _p5, _k5n, 1); _out6p = vfmaq_laneq_f32(_out6p, _p5, _k6n, 1); _out7p = vfmaq_laneq_f32(_out7p, _p5, _k7n, 1); float32x4_t _p6 = vld1q_f32(r6); _out0p = vfmaq_laneq_f32(_out0p, _p6, _k0n, 2); _out1p = vfmaq_laneq_f32(_out1p, _p6, _k1n, 2); _out2p = vfmaq_laneq_f32(_out2p, _p6, _k2n, 2); _out3p = vfmaq_laneq_f32(_out3p, _p6, _k3n, 2); _out4p = vfmaq_laneq_f32(_out4p, _p6, _k4n, 2); _out5p = vfmaq_laneq_f32(_out5p, _p6, _k5n, 2); _out6p = vfmaq_laneq_f32(_out6p, _p6, _k6n, 2); _out7p = vfmaq_laneq_f32(_out7p, _p6, _k7n, 2); float32x4_t _p7 = vld1q_f32(r7); _out0p = vfmaq_laneq_f32(_out0p, _p7, _k0n, 3); _out1p = vfmaq_laneq_f32(_out1p, _p7, _k1n, 3); _out2p = vfmaq_laneq_f32(_out2p, _p7, _k2n, 3); _out3p = vfmaq_laneq_f32(_out3p, _p7, _k3n, 3); _out4p = vfmaq_laneq_f32(_out4p, _p7, _k4n, 3); _out5p = vfmaq_laneq_f32(_out5p, _p7, _k5n, 3); _out6p = vfmaq_laneq_f32(_out6p, _p7, _k6n, 3); _out7p = vfmaq_laneq_f32(_out7p, _p7, _k7n, 3); vst1q_f32(outptr0, _out0p); vst1q_f32(outptr1, _out1p); vst1q_f32(outptr2, _out2p); vst1q_f32(outptr3, _out3p); vst1q_f32(outptr4, _out4p); vst1q_f32(outptr5, _out5p); vst1q_f32(outptr6, _out6p); vst1q_f32(outptr7, _out7p); r0 += 4; r1 += 4; r2 += 4; r3 += 4; r4 += 4; r5 += 4; r6 += 4; r7 += 4; outptr0 += 4; outptr1 += 4; outptr2 += 4; outptr3 += 4; outptr4 += 4; outptr5 += 4; outptr6 += 4; outptr7 += 4; } #endif for (; remain>0; remain--) { // TODO neon optimize float sum0 = *r0 * kernel0[0] + *r1 * kernel0[1] + *r2 * kernel0[2] + *r3 * kernel0[3] + *r4 * kernel0[4] + *r5 * kernel0[5] + *r6 * kernel0[6] + *r7 * kernel0[7]; float sum1 = *r0 * kernel1[0] + *r1 * kernel1[1] + *r2 * kernel1[2] + *r3 * kernel1[3] + *r4 * kernel1[4] + *r5 * kernel1[5] + *r6 * kernel1[6] + *r7 * kernel1[7]; float sum2 = *r0 * kernel2[0] + *r1 * kernel2[1] + *r2 * kernel2[2] + *r3 * kernel2[3] + *r4 * kernel2[4] + *r5 * kernel2[5] + *r6 * kernel2[6] + *r7 * kernel2[7]; float sum3 = *r0 * kernel3[0] + *r1 * kernel3[1] + *r2 * kernel3[2] + *r3 * kernel3[3] + *r4 * kernel3[4] + *r5 * kernel3[5] + *r6 * kernel3[6] + *r7 * kernel3[7]; float sum4 = *r0 * kernel4[0] + *r1 * kernel4[1] + *r2 * kernel4[2] + *r3 * kernel4[3] + *r4 * kernel4[4] + *r5 * kernel4[5] + *r6 * kernel4[6] + *r7 * kernel4[7]; float sum5 = *r0 * kernel5[0] + *r1 * kernel5[1] + *r2 * kernel5[2] + *r3 * kernel5[3] + *r4 * kernel5[4] + *r5 * kernel5[5] + *r6 * kernel5[6] + *r7 * kernel5[7]; float sum6 = *r0 * kernel6[0] + *r1 * kernel6[1] + *r2 * kernel6[2] + *r3 * kernel6[3] + *r4 * kernel6[4] + *r5 * kernel6[5] + *r6 * kernel6[6] + *r7 * kernel6[7]; float sum7 = *r0 * kernel7[0] + *r1 * kernel7[1] + *r2 * kernel7[2] + *r3 * kernel7[3] + *r4 * kernel7[4] + *r5 * kernel7[5] + *r6 * kernel7[6] + *r7 * kernel7[7]; *outptr0 += sum0; *outptr1 += sum1; *outptr2 += sum2; *outptr3 += sum3; *outptr4 += sum4; *outptr5 += sum5; *outptr6 += sum6; *outptr7 += sum7; r0++; r1++; r2++; r3++; r4++; r5++; r6++; r7++; outptr0++; outptr1++; outptr2++; outptr3++; outptr4++; outptr5++; outptr6++; outptr7++; } } for (; q<inch; q++) { float* outptr0 = out0; float* outptr1 = out1; float* outptr2 = out2; float* outptr3 = out3; float* outptr4 = out4; float* outptr5 = out5; float* outptr6 = out6; float* outptr7 = out7; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p*inch + q; const float* kernel1 = kernel + (p+1)*inch + q; const float* kernel2 = kernel + (p+2)*inch + q; const float* kernel3 = kernel + (p+3)*inch + q; const float* kernel4 = kernel + (p+4)*inch + q; const float* kernel5 = kernel + (p+5)*inch + q; const float* kernel6 = kernel + (p+6)*inch + q; const float* kernel7 = kernel + (p+7)*inch + q; const float k0 = kernel0[0]; const float k1 = kernel1[0]; const float k2 = kernel2[0]; const float k3 = kernel3[0]; const float k4 = kernel4[0]; const float k5 = kernel5[0]; const float k6 = kernel6[0]; const float k7 = kernel7[0]; const float* r0 = img0; int size = outw * outh; int nn = size >> 2; int remain = size & 3; float32x4_t _k0 = vdupq_n_f32(k0); float32x4_t _k1 = vdupq_n_f32(k1); float32x4_t _k2 = vdupq_n_f32(k2); float32x4_t _k3 = vdupq_n_f32(k3); float32x4_t _k4 = vdupq_n_f32(k4); float32x4_t _k5 = vdupq_n_f32(k5); float32x4_t _k6 = vdupq_n_f32(k6); float32x4_t _k7 = vdupq_n_f32(k7); for (; nn>0; nn--) { float32x4_t _p = vld1q_f32(r0); float32x4_t _out0p = vld1q_f32(outptr0); float32x4_t _out1p = vld1q_f32(outptr1); float32x4_t _out2p = vld1q_f32(outptr2); float32x4_t _out3p = vld1q_f32(outptr3); float32x4_t _out4p = vld1q_f32(outptr4); float32x4_t _out5p = vld1q_f32(outptr5); float32x4_t _out6p = vld1q_f32(outptr6); float32x4_t _out7p = vld1q_f32(outptr7); _out0p = vfmaq_f32(_out0p, _p, _k0); _out1p = vfmaq_f32(_out1p, _p, _k1); _out2p = vfmaq_f32(_out2p, _p, _k2); _out3p = vfmaq_f32(_out3p, _p, _k3); _out4p = vfmaq_f32(_out4p, _p, _k4); _out5p = vfmaq_f32(_out5p, _p, _k5); _out6p = vfmaq_f32(_out6p, _p, _k6); _out7p = vfmaq_f32(_out7p, _p, _k7); vst1q_f32(outptr0, _out0p); vst1q_f32(outptr1, _out1p); vst1q_f32(outptr2, _out2p); vst1q_f32(outptr3, _out3p); vst1q_f32(outptr4, _out4p); vst1q_f32(outptr5, _out5p); vst1q_f32(outptr6, _out6p); vst1q_f32(outptr7, _out7p); r0 += 4; outptr0 += 4; outptr1 += 4; outptr2 += 4; outptr3 += 4; outptr4 += 4; outptr5 += 4; outptr6 += 4; outptr7 += 4; } for (; remain>0; remain--) { // TODO neon optimize float sum0 = *r0 * k0; float sum1 = *r0 * k1; float sum2 = *r0 * k2; float sum3 = *r0 * k3; float sum4 = *r0 * k4; float sum5 = *r0 * k5; float sum6 = *r0 * k6; float sum7 = *r0 * k7; *outptr0 += sum0; *outptr1 += sum1; *outptr2 += sum2; *outptr3 += sum3; *outptr4 += sum4; *outptr5 += sum5; *outptr6 += sum6; *outptr7 += sum7; r0++; outptr0++; outptr1++; outptr2++; outptr3++; outptr4++; outptr5++; outptr6++; outptr7++; } } } #else nn_outch = outch / 6; remain_outch_start = nn_outch * 6; #pragma omp parallel for for (int pp=0; pp<nn_outch; pp++) { int p = pp * 6; Mat out0 = top_blob.channel(p); Mat out1 = top_blob.channel(p+1); Mat out2 = top_blob.channel(p+2); Mat out3 = top_blob.channel(p+3); Mat out4 = top_blob.channel(p+4); Mat out5 = top_blob.channel(p+5); const float bias0 = bias ? bias[p] : 0.f; const float bias1 = bias ? bias[p+1] : 0.f; const float bias2 = bias ? bias[p+2] : 0.f; const float bias3 = bias ? bias[p+3] : 0.f; const float bias4 = bias ? bias[p+4] : 0.f; const float bias5 = bias ? bias[p+5] : 0.f; out0.fill(bias0); out1.fill(bias1); out2.fill(bias2); out3.fill(bias3); out4.fill(bias4); out5.fill(bias5); int q = 0; for (; q+3<inch; q+=4) { float* outptr0 = out0; float* outptr1 = out1; float* outptr2 = out2; float* outptr3 = out3; float* outptr4 = out4; float* outptr5 = out5; const float* img0 = bottom_blob.channel(q); const float* img1 = bottom_blob.channel(q+1); const float* img2 = bottom_blob.channel(q+2); const float* img3 = bottom_blob.channel(q+3); const float* kernel0 = kernel + p*inch + q; const float* kernel1 = kernel + (p+1)*inch + q; const float* kernel2 = kernel + (p+2)*inch + q; const float* kernel3 = kernel + (p+3)*inch + q; const float* kernel4 = kernel + (p+4)*inch + q; const float* kernel5 = kernel + (p+5)*inch + q; const float* r0 = img0; const float* r1 = img1; const float* r2 = img2; const float* r3 = img3; int size = outw * outh; #if __ARM_NEON int nn = size >> 2; int remain = size & 3; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vld1q_f32(kernel0); float32x4_t _k1 = vld1q_f32(kernel1); float32x4_t _k2 = vld1q_f32(kernel2); float32x4_t _k3 = vld1q_f32(kernel3); float32x4_t _k4 = vld1q_f32(kernel4); float32x4_t _k5 = vld1q_f32(kernel5); if (nn > 0) { asm volatile( "pld [%7, #128] \n" "vld1.f32 {d24-d25}, [%7 :128]! \n"// q12 = r0 "pld [%1, #128] \n" "vld1.f32 {d12-d13}, [%1 :128] \n"// q6 = outptr0 "pld [%2, #128] \n" "vld1.f32 {d14-d15}, [%2 :128] \n"// q7 = outptr1 "vmla.f32 q6, q12, %e22[0] \n" "0: \n" "pld [%3, #128] \n" "vld1.f32 {d16-d17}, [%3 :128] \n"// q8 = outptr2 "vmla.f32 q7, q12, %e23[0] \n" "pld [%4, #128] \n" "vld1.f32 {d18-d19}, [%4 :128] \n"// q9 = outptr3 "vmla.f32 q8, q12, %e24[0] \n" "pld [%8, #128] \n" "vld1.f32 {d26-d27}, [%8 :128]! \n"// q13 = r1 "vmla.f32 q9, q12, %e25[0] \n" "pld [%5, #128] \n" "vld1.f32 {d20-d21}, [%5 :128] \n"// q10 = outptr4 "vmla.f32 q6, q13, %e22[1] \n" "vmla.f32 q7, q13, %e23[1] \n" "pld [%6, #128] \n" "vld1.f32 {d22-d23}, [%6 :128] \n"// q11 = outptr5 "vmla.f32 q10, q12, %e26[0] \n" "vmla.f32 q11, q12, %e27[0] \n" "vmla.f32 q8, q13, %e24[1] \n" "vmla.f32 q9, q13, %e25[1] \n" "pld [%9, #128] \n" "vld1.f32 {d28-d29}, [%9 :128]! \n"// q14 = r2 "vmla.f32 q10, q13, %e26[1] \n" "vmla.f32 q11, q13, %e27[1] \n" "vmla.f32 q6, q14, %f22[0] \n" "vmla.f32 q7, q14, %f23[0] \n" "vmla.f32 q8, q14, %f24[0] \n" "vmla.f32 q9, q14, %f25[0] \n" "pld [%10, #128] \n" "vld1.f32 {d30-d31}, [%10 :128]! \n"// q15 = r3 "vmla.f32 q10, q14, %f26[0] \n" "vmla.f32 q11, q14, %f27[0] \n" "vmla.f32 q6, q15, %f22[1] \n" "vmla.f32 q7, q15, %f23[1] \n" "vmla.f32 q8, q15, %f24[1] \n" "vmla.f32 q9, q15, %f25[1] \n" "pld [%7, #128] \n" "vld1.f32 {d24-d25}, [%7 :128]! \n"// q12 = r0 "vmla.f32 q10, q15, %f26[1] \n" "vmla.f32 q11, q15, %f27[1] \n" "vst1.f32 {d12-d13}, [%1 :128]! \n" "vst1.f32 {d14-d15}, [%2 :128]! \n" "pld [%1, #128] \n" "vld1.f32 {d12-d13}, [%1 :128] \n"// q6 = outptr0 "vst1.f32 {d16-d17}, [%3 :128]! \n" "vst1.f32 {d18-d19}, [%4 :128]! \n" "vmla.f32 q6, q12, %e22[0] \n" "pld [%2, #128] \n" "vld1.f32 {d14-d15}, [%2 :128] \n"// q7 = outptr1 "subs %0, #1 \n" "vst1.f32 {d20-d21}, [%5 :128]! \n" "vst1.f32 {d22-d23}, [%6 :128]! \n" "bne 0b \n" "sub %7, #16 \n" : "=r"(nn), // %0 "=r"(outptr0),// %1 "=r"(outptr1),// %2 "=r"(outptr2),// %3 "=r"(outptr3),// %4 "=r"(outptr4),// %5 "=r"(outptr5),// %6 "=r"(r0), // %7 "=r"(r1), // %8 "=r"(r2), // %9 "=r"(r3) // %10 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(outptr4), "6"(outptr5), "7"(r0), "8"(r1), "9"(r2), "10"(r3), "w"(_k0), // %22 "w"(_k1), // %23 "w"(_k2), // %24 "w"(_k3), // %25 "w"(_k4), // %26 "w"(_k5) // %27 : "cc", "memory", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __ARM_NEON for (; remain>0; remain--) { // TODO neon optimize float sum0 = *r0 * kernel0[0] + *r1 * kernel0[1] + *r2 * kernel0[2] + *r3 * kernel0[3]; float sum1 = *r0 * kernel1[0] + *r1 * kernel1[1] + *r2 * kernel1[2] + *r3 * kernel1[3]; float sum2 = *r0 * kernel2[0] + *r1 * kernel2[1] + *r2 * kernel2[2] + *r3 * kernel2[3]; float sum3 = *r0 * kernel3[0] + *r1 * kernel3[1] + *r2 * kernel3[2] + *r3 * kernel3[3]; float sum4 = *r0 * kernel4[0] + *r1 * kernel4[1] + *r2 * kernel4[2] + *r3 * kernel4[3]; float sum5 = *r0 * kernel5[0] + *r1 * kernel5[1] + *r2 * kernel5[2] + *r3 * kernel5[3]; *outptr0 += sum0; *outptr1 += sum1; *outptr2 += sum2; *outptr3 += sum3; *outptr4 += sum4; *outptr5 += sum5; r0++; r1++; r2++; r3++; outptr0++; outptr1++; outptr2++; outptr3++; outptr4++; outptr5++; } } for (; q<inch; q++) { float* outptr0 = out0; float* outptr1 = out1; float* outptr2 = out2; float* outptr3 = out3; float* outptr4 = out4; float* outptr5 = out5; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p*inch + q; const float* kernel1 = kernel + (p+1)*inch + q; const float* kernel2 = kernel + (p+2)*inch + q; const float* kernel3 = kernel + (p+3)*inch + q; const float* kernel4 = kernel + (p+4)*inch + q; const float* kernel5 = kernel + (p+5)*inch + q; const float k0 = kernel0[0]; const float k1 = kernel1[0]; const float k2 = kernel2[0]; const float k3 = kernel3[0]; const float k4 = kernel4[0]; const float k5 = kernel5[0]; const float* r0 = img0; int size = outw * outh; #if __ARM_NEON int nn = size >> 2; int remain = size & 3; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); float32x4_t _k1 = vdupq_n_f32(k1); float32x4_t _k2 = vdupq_n_f32(k2); float32x4_t _k3 = vdupq_n_f32(k3); float32x4_t _k4 = vdupq_n_f32(k4); float32x4_t _k5 = vdupq_n_f32(k5); if (nn > 0) { asm volatile( "pld [%7, #128] \n" "vld1.f32 {d24-d25}, [%7 :128]! \n"// q12 = r0 "pld [%1, #128] \n" "vld1.f32 {d12-d13}, [%1 :128] \n"// q6 = outptr0 "0: \n" "pld [%2, #128] \n" "vld1.f32 {d14-d15}, [%2 :128] \n"// q7 = outptr1 "vmla.f32 q6, q12, %q16 \n" "pld [%3, #128] \n" "vld1.f32 {d16-d17}, [%3 :128] \n"// q8 = outptr2 "vmla.f32 q7, q12, %q17 \n" "pld [%4, #128] \n" "vld1.f32 {d18-d19}, [%4 :128] \n"// q9 = outptr3 "vmla.f32 q8, q12, %q18 \n" "pld [%5, #128] \n" "vld1.f32 {d20-d21}, [%5 :128] \n"// q10 = outptr4 "vmla.f32 q9, q12, %q19 \n" "pld [%6, #128] \n" "vld1.f32 {d22-d23}, [%6 :128] \n"// q11 = outptr5 "vmla.f32 q10, q12, %q20 \n" "vmla.f32 q11, q12, %q21 \n" "pld [%7, #128] \n" "vld1.f32 {d24-d25}, [%7 :128]! \n"// q12 = r0 "vst1.f32 {d12-d13}, [%1 :128]! \n" "vst1.f32 {d14-d15}, [%2 :128]! \n" "pld [%1, #128] \n" "vld1.f32 {d12-d13}, [%1 :128] \n"// q6 = outptr0 "vst1.f32 {d16-d17}, [%3 :128]! \n" "vst1.f32 {d18-d19}, [%4 :128]! \n" "subs %0, #1 \n" "vst1.f32 {d20-d21}, [%5 :128]! \n" "vst1.f32 {d22-d23}, [%6 :128]! \n" "bne 0b \n" "sub %7, #16 \n" : "=r"(nn), // %0 "=r"(outptr0),// %1 "=r"(outptr1),// %2 "=r"(outptr2),// %3 "=r"(outptr3),// %4 "=r"(outptr4),// %5 "=r"(outptr5),// %6 "=r"(r0) // %7 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(outptr4), "6"(outptr5), "7"(r0), "w"(_k0), // %16 "w"(_k1), // %17 "w"(_k2), // %18 "w"(_k3), // %19 "w"(_k4), // %20 "w"(_k5) // %21 : "cc", "memory", "q6", "q7", "q8", "q9", "q10", "q11", "q12" ); } #endif // __ARM_NEON for (; remain>0; remain--) { // TODO neon optimize float sum0 = *r0 * k0; float sum1 = *r0 * k1; float sum2 = *r0 * k2; float sum3 = *r0 * k3; float sum4 = *r0 * k4; float sum5 = *r0 * k5; *outptr0 += sum0; *outptr1 += sum1; *outptr2 += sum2; *outptr3 += sum3; *outptr4 += sum4; *outptr5 += sum5; r0++; outptr0++; outptr1++; outptr2++; outptr3++; outptr4++; outptr5++; } } } #endif // __ARM_NEON && __aarch64__ nn_outch = (outch - remain_outch_start) >> 2; #pragma omp parallel for for (int pp=0; pp<nn_outch; pp++) { int p = remain_outch_start + pp * 4; Mat out0 = top_blob.channel(p); Mat out1 = top_blob.channel(p+1); Mat out2 = top_blob.channel(p+2); Mat out3 = top_blob.channel(p+3); const float bias0 = bias ? bias[p] : 0.f; const float bias1 = bias ? bias[p+1] : 0.f; const float bias2 = bias ? bias[p+2] : 0.f; const float bias3 = bias ? bias[p+3] : 0.f; out0.fill(bias0); out1.fill(bias1); out2.fill(bias2); out3.fill(bias3); int q = 0; for (; q+3<inch; q+=4) { float* outptr0 = out0; float* outptr1 = out1; float* outptr2 = out2; float* outptr3 = out3; const float* img0 = bottom_blob.channel(q); const float* img1 = bottom_blob.channel(q+1); const float* img2 = bottom_blob.channel(q+2); const float* img3 = bottom_blob.channel(q+3); const float* kernel0 = kernel + p*inch + q; const float* kernel1 = kernel + (p+1)*inch + q; const float* kernel2 = kernel + (p+2)*inch + q; const float* kernel3 = kernel + (p+3)*inch + q; const float* r0 = img0; const float* r1 = img1; const float* r2 = img2; const float* r3 = img3; int size = outw * outh; #if __ARM_NEON int nn = size >> 3; int remain = size & 7; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vld1q_f32(kernel0); float32x4_t _k1 = vld1q_f32(kernel1); float32x4_t _k2 = vld1q_f32(kernel2); float32x4_t _k3 = vld1q_f32(kernel3); #if __aarch64__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%5, #256] \n" "ld1 {v6.4s, v7.4s}, [%5], #32 \n" "prfm pldl1keep, [%1, #256] \n" "ld1 {v8.4s, v9.4s}, [%1] \n" "0: \n" "fmla v8.4s, v6.4s, %18.s[0] \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v10.4s, v11.4s}, [%2] \n" "fmla v9.4s, v7.4s, %18.s[0] \n" "fmla v10.4s, v6.4s, %19.s[0] \n" "prfm pldl1keep, [%3, #256] \n" "ld1 {v12.4s, v13.4s}, [%3] \n" "fmla v11.4s, v7.4s, %19.s[0] \n" "fmla v12.4s, v6.4s, %20.s[0] \n" "prfm pldl1keep, [%4, #256] \n" "ld1 {v14.4s, v15.4s}, [%4] \n" "fmla v13.4s, v7.4s, %20.s[0] \n" "prfm pldl1keep, [%6, #256] \n" "ld1 {v4.4s, v5.4s}, [%6], #32 \n" "fmla v14.4s, v6.4s, %21.s[0] \n" "fmla v15.4s, v7.4s, %21.s[0] \n" "fmla v8.4s, v4.4s, %18.s[1] \n" "fmla v9.4s, v5.4s, %18.s[1] \n" "fmla v10.4s, v4.4s, %19.s[1] \n" "fmla v11.4s, v5.4s, %19.s[1] \n" "fmla v12.4s, v4.4s, %20.s[1] \n" "fmla v13.4s, v5.4s, %20.s[1] \n" "prfm pldl1keep, [%7, #256] \n" "ld1 {v6.4s, v7.4s}, [%7], #32 \n" "fmla v14.4s, v4.4s, %21.s[1] \n" "fmla v15.4s, v5.4s, %21.s[1] \n" "fmla v8.4s, v6.4s, %18.s[2] \n" "fmla v9.4s, v7.4s, %18.s[2] \n" "fmla v10.4s, v6.4s, %19.s[2] \n" "fmla v11.4s, v7.4s, %19.s[2] \n" "fmla v12.4s, v6.4s, %20.s[2] \n" "fmla v13.4s, v7.4s, %20.s[2] \n" "prfm pldl1keep, [%8, #256] \n" "ld1 {v4.4s, v5.4s}, [%8], #32 \n" "fmla v14.4s, v6.4s, %21.s[2] \n" "fmla v15.4s, v7.4s, %21.s[2] \n" "fmla v8.4s, v4.4s, %18.s[3] \n" "fmla v9.4s, v5.4s, %18.s[3] \n" "fmla v10.4s, v4.4s, %19.s[3] \n" "fmla v11.4s, v5.4s, %19.s[3] \n" "st1 {v8.4s, v9.4s}, [%1], #32 \n" "fmla v12.4s, v4.4s, %20.s[3] \n" "fmla v13.4s, v5.4s, %20.s[3] \n" "st1 {v10.4s, v11.4s}, [%2], #32 \n" "prfm pldl1keep, [%5, #256] \n" "ld1 {v6.4s, v7.4s}, [%5], #32 \n" "fmla v14.4s, v4.4s, %21.s[3] \n" "fmla v15.4s, v5.4s, %21.s[3] \n" "st1 {v12.4s, v13.4s}, [%3], #32 \n" "prfm pldl1keep, [%1, #256] \n" "ld1 {v8.4s, v9.4s}, [%1] \n" "subs %w0, %w0, #1 \n" "st1 {v14.4s, v15.4s}, [%4], #32 \n" "bne 0b \n" "sub %5, %5, #32 \n" : "=r"(nn), // %0 "=r"(outptr0),// %1 "=r"(outptr1),// %2 "=r"(outptr2),// %3 "=r"(outptr3),// %4 "=r"(r0), // %5 "=r"(r1), // %6 "=r"(r2), // %7 "=r"(r3) // %8 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(r0), "6"(r1), "7"(r2), "8"(r3), "w"(_k0), // %18 "w"(_k1), // %19 "w"(_k2), // %20 "w"(_k3) // %21 : "cc", "memory", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15" ); } #else if (nn > 0) { asm volatile( "pld [%5, #256] \n" "vld1.f32 {d12-d15}, [%5 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128] \n" "0: \n" "vmla.f32 q8, q6, %e18[0] \n" "pld [%2, #256] \n" "vld1.f32 {d20-d23}, [%2 :128] \n" "vmla.f32 q9, q7, %e18[0] \n" "vmla.f32 q10, q6, %e19[0] \n" "pld [%3, #256] \n" "vld1.f32 {d24-d27}, [%3 :128] \n" "vmla.f32 q11, q7, %e19[0] \n" "vmla.f32 q12, q6, %e20[0] \n" "pld [%4, #256] \n" "vld1.f32 {d28-d31}, [%4 :128] \n" "vmla.f32 q13, q7, %e20[0] \n" "pld [%6, #256] \n" "vld1.f32 {d8-d11}, [%6 :128]! \n" "vmla.f32 q14, q6, %e21[0] \n" "vmla.f32 q15, q7, %e21[0] \n" "vmla.f32 q8, q4, %e18[1] \n" "vmla.f32 q9, q5, %e18[1] \n" "vmla.f32 q10, q4, %e19[1] \n" "vmla.f32 q11, q5, %e19[1] \n" "vmla.f32 q12, q4, %e20[1] \n" "vmla.f32 q13, q5, %e20[1] \n" "pld [%7, #256] \n" "vld1.f32 {d12-d15}, [%7 :128]! \n" "vmla.f32 q14, q4, %e21[1] \n" "vmla.f32 q15, q5, %e21[1] \n" "vmla.f32 q8, q6, %f18[0] \n" "vmla.f32 q9, q7, %f18[0] \n" "vmla.f32 q10, q6, %f19[0] \n" "vmla.f32 q11, q7, %f19[0] \n" "vmla.f32 q12, q6, %f20[0] \n" "vmla.f32 q13, q7, %f20[0] \n" "pld [%8, #256] \n" "vld1.f32 {d8-d11}, [%8 :128]! \n" "vmla.f32 q14, q6, %f21[0] \n" "vmla.f32 q15, q7, %f21[0] \n" "vmla.f32 q8, q4, %f18[1] \n" "vmla.f32 q9, q5, %f18[1] \n" "vmla.f32 q10, q4, %f19[1] \n" "vmla.f32 q11, q5, %f19[1] \n" "vmla.f32 q12, q4, %f20[1] \n" "vst1.f32 {d16-d19}, [%1 :128]! \n" "vmla.f32 q13, q5, %f20[1] \n" "vst1.f32 {d20-d23}, [%2 :128]! \n" "vmla.f32 q14, q4, %f21[1] \n" "pld [%5, #256] \n" "vld1.f32 {d12-d15}, [%5 :128]! \n" "vmla.f32 q15, q5, %f21[1] \n" "vst1.f32 {d24-d27}, [%3 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128] \n" "subs %0, #1 \n" "vst1.f32 {d28-d31}, [%4 :128]! \n" "bne 0b \n" "sub %5, #32 \n" : "=r"(nn), // %0 "=r"(outptr0),// %1 "=r"(outptr1),// %2 "=r"(outptr2),// %3 "=r"(outptr3),// %4 "=r"(r0), // %5 "=r"(r1), // %6 "=r"(r2), // %7 "=r"(r3) // %8 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(r0), "6"(r1), "7"(r2), "8"(r3), "w"(_k0), // %18 "w"(_k1), // %19 "w"(_k2), // %20 "w"(_k3) // %21 : "cc", "memory", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { // TODO neon optimize float sum0 = *r0 * kernel0[0] + *r1 * kernel0[1] + *r2 * kernel0[2] + *r3 * kernel0[3]; float sum1 = *r0 * kernel1[0] + *r1 * kernel1[1] + *r2 * kernel1[2] + *r3 * kernel1[3]; float sum2 = *r0 * kernel2[0] + *r1 * kernel2[1] + *r2 * kernel2[2] + *r3 * kernel2[3]; float sum3 = *r0 * kernel3[0] + *r1 * kernel3[1] + *r2 * kernel3[2] + *r3 * kernel3[3]; *outptr0 += sum0; *outptr1 += sum1; *outptr2 += sum2; *outptr3 += sum3; r0++; r1++; r2++; r3++; outptr0++; outptr1++; outptr2++; outptr3++; } } for (; q<inch; q++) { float* outptr0 = out0; float* outptr1 = out1; float* outptr2 = out2; float* outptr3 = out3; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p*inch + q; const float* kernel1 = kernel + (p+1)*inch + q; const float* kernel2 = kernel + (p+2)*inch + q; const float* kernel3 = kernel + (p+3)*inch + q; const float k0 = kernel0[0]; const float k1 = kernel1[0]; const float k2 = kernel2[0]; const float k3 = kernel3[0]; const float* r0 = img0; int size = outw * outh; #if __ARM_NEON int nn = size >> 3; int remain = size & 7; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); float32x4_t _k1 = vdupq_n_f32(k1); float32x4_t _k2 = vdupq_n_f32(k2); float32x4_t _k3 = vdupq_n_f32(k3); #if __aarch64__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%5, #256] \n" "ld1 {v6.4s, v7.4s}, [%5], #32 \n" "0: \n" "prfm pldl1keep, [%1, #256] \n" "ld1 {v8.4s, v9.4s}, [%1] \n" "fmla v8.4s, v6.4s, %12.4s \n" "fmla v9.4s, v7.4s, %12.4s \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v10.4s, v11.4s}, [%2] \n" "fmla v10.4s, v6.4s, %13.4s \n" "fmla v11.4s, v7.4s, %13.4s \n" "st1 {v8.4s, v9.4s}, [%1], #32 \n" "prfm pldl1keep, [%3, #256] \n" "ld1 {v12.4s, v13.4s}, [%3] \n" "fmla v12.4s, v6.4s, %14.4s \n" "fmla v13.4s, v7.4s, %14.4s \n" "st1 {v10.4s, v11.4s}, [%2], #32 \n" "prfm pldl1keep, [%4, #256] \n" "ld1 {v14.4s, v15.4s}, [%4] \n" "fmla v14.4s, v6.4s, %15.4s \n" "fmla v15.4s, v7.4s, %15.4s \n" "st1 {v12.4s, v13.4s}, [%3], #32 \n" "prfm pldl1keep, [%5, #256] \n" "ld1 {v6.4s, v7.4s}, [%5], #32 \n" "subs %w0, %w0, #1 \n" "st1 {v14.4s, v15.4s}, [%4], #32 \n" "bne 0b \n" "sub %5, %5, #32 \n" : "=r"(nn), // %0 "=r"(outptr0),// %1 "=r"(outptr1),// %2 "=r"(outptr2),// %3 "=r"(outptr3),// %4 "=r"(r0) // %5 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(r0), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15" ); } #else if (nn > 0) { asm volatile( "pld [%5, #256] \n" "vld1.f32 {d12-d15}, [%5 :128]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128] \n" "vmla.f32 q8, q6, %q12 \n" "vmla.f32 q9, q7, %q12 \n" "pld [%2, #256] \n" "vld1.f32 {d20-d23}, [%2 :128] \n" "vmla.f32 q10, q6, %q13 \n" "vmla.f32 q11, q7, %q13 \n" "vst1.f32 {d16-d19}, [%1 :128]! \n" "pld [%3, #256] \n" "vld1.f32 {d24-d27}, [%3 :128] \n" "vmla.f32 q12, q6, %q14 \n" "vmla.f32 q13, q7, %q14 \n" "vst1.f32 {d20-d23}, [%2 :128]! \n" "pld [%4, #256] \n" "vld1.f32 {d28-d31}, [%4 :128] \n" "vmla.f32 q14, q6, %q15 \n" "vmla.f32 q15, q7, %q15 \n" "vst1.f32 {d24-d27}, [%3 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d12-d15}, [%5 :128]! \n" "subs %0, #1 \n" "vst1.f32 {d28-d31}, [%4 :128]! \n" "bne 0b \n" "sub %5, #32 \n" : "=r"(nn), // %0 "=r"(outptr0),// %1 "=r"(outptr1),// %2 "=r"(outptr2),// %3 "=r"(outptr3),// %4 "=r"(r0) // %5 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(r0), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { // TODO neon optimize float sum0 = *r0 * k0; float sum1 = *r0 * k1; float sum2 = *r0 * k2; float sum3 = *r0 * k3; *outptr0 += sum0; *outptr1 += sum1; *outptr2 += sum2; *outptr3 += sum3; r0++; outptr0++; outptr1++; outptr2++; outptr3++; } } } remain_outch_start += nn_outch << 2; #pragma omp parallel for for (int p=remain_outch_start; p<outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); int q = 0; for (; q+3<inch; q+=4) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* img1 = bottom_blob.channel(q+1); const float* img2 = bottom_blob.channel(q+2); const float* img3 = bottom_blob.channel(q+3); const float* kernel0 = kernel + p*inch + q; const float k0 = kernel0[0]; const float k1 = kernel0[1]; const float k2 = kernel0[2]; const float k3 = kernel0[3]; const float* r0 = img0; const float* r1 = img1; const float* r2 = img2; const float* r3 = img3; int size = outw * outh; #if __ARM_NEON int nn = size >> 3; int remain = size & 7; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); float32x4_t _k1 = vdupq_n_f32(k1); float32x4_t _k2 = vdupq_n_f32(k2); float32x4_t _k3 = vdupq_n_f32(k3); #if __aarch64__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%2, #256] \n" "ld1 {v2.4s, v3.4s}, [%2], #32 \n" "0: \n" "prfm pldl1keep, [%1, #256] \n" "ld1 {v0.4s, v1.4s}, [%1] \n" "fmla v0.4s, v2.4s, %12.4s \n" "fmla v1.4s, v3.4s, %12.4s \n" "prfm pldl1keep, [%3, #256] \n" "ld1 {v2.4s, v3.4s}, [%3], #32 \n" "fmla v0.4s, v2.4s, %13.4s \n" "fmla v1.4s, v3.4s, %13.4s \n" "prfm pldl1keep, [%4, #256] \n" "ld1 {v2.4s, v3.4s}, [%4], #32 \n" "fmla v0.4s, v2.4s, %14.4s \n" "fmla v1.4s, v3.4s, %14.4s \n" "prfm pldl1keep, [%5, #256] \n" "ld1 {v2.4s, v3.4s}, [%5], #32 \n" "fmla v0.4s, v2.4s, %15.4s \n" "fmla v1.4s, v3.4s, %15.4s \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v2.4s, v3.4s}, [%2], #32 \n" "subs %w0, %w0, #1 \n" "st1 {v0.4s, v1.4s}, [%1], #32 \n" "bne 0b \n" "sub %2, %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2), // %4 "=r"(r3) // %5 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "5"(r3), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "v0", "v1", "v2", "v3" ); } #else if (nn > 0) { asm volatile( "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2 :128]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128] \n" "vmla.f32 q0, q2, %q12 \n" "vmla.f32 q1, q3, %q12 \n" "pld [%3, #256] \n" "vld1.f32 {d4-d7}, [%3 :128]! \n" "vmla.f32 q0, q2, %q13 \n" "vmla.f32 q1, q3, %q13 \n" "pld [%4, #256] \n" "vld1.f32 {d4-d7}, [%4 :128]! \n" "vmla.f32 q0, q2, %q14 \n" "vmla.f32 q1, q3, %q14 \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q0, q2, %q15 \n" "vmla.f32 q1, q3, %q15 \n" "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2 :128]! \n" "subs %0, #1 \n" "vst1.f32 {d0-d3}, [%1 :128]! \n" "bne 0b \n" "sub %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2), // %4 "=r"(r3) // %5 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "5"(r3), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "q0", "q1", "q2", "q3" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { float sum = *r0 * k0; float sum1 = *r1 * k1; float sum2 = *r2 * k2; float sum3 = *r3 * k3; *outptr += sum + sum1 + sum2 + sum3; r0++; r1++; r2++; r3++; outptr++; } } for (; q<inch; q++) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p*inch + q; const float k0 = kernel0[0]; const float* r0 = img0; int size = outw * outh; #if __ARM_NEON int nn = size >> 3; int remain = size & 7; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); #if __aarch64__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%2, #256] \n" "ld1 {v2.4s, v3.4s}, [%2], #32 \n" "0: \n" "prfm pldl1keep, [%1, #256] \n" "ld1 {v0.4s, v1.4s}, [%1] \n" "fmla v0.4s, v2.4s, %6.4s \n" "fmla v1.4s, v3.4s, %6.4s \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v2.4s, v3.4s}, [%2], #32 \n" "subs %w0, %w0, #1 \n" "st1 {v0.4s, v1.4s}, [%1], #32 \n" "bne 0b \n" "sub %2, %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0) // %2 : "0"(nn), "1"(outptr), "2"(r0), "w"(_k0) // %6 : "cc", "memory", "v0", "v1", "v2", "v3" ); } #else if (nn > 0) { asm volatile( "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2 :128]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128] \n" "vmla.f32 q0, q2, %q6 \n" "vmla.f32 q1, q3, %q6 \n" "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2 :128]! \n" "subs %0, #1 \n" "vst1.f32 {d0-d3}, [%1 :128]! \n" "bne 0b \n" "sub %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0) // %2 : "0"(nn), "1"(outptr), "2"(r0), "w"(_k0) // %6 : "cc", "memory", "q0", "q1", "q2", "q3" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { float sum = *r0 * k0; *outptr += sum; r0++; outptr++; } } } } static void conv1x1s2_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2*outw + w; const float* kernel = _kernel; const float* bias = _bias; int nn_outch = outch >> 2; int remain_outch_start = nn_outch << 2; #pragma omp parallel for for (int pp=0; pp<nn_outch; pp++) { int p = pp * 4; Mat out0 = top_blob.channel(p); Mat out1 = top_blob.channel(p+1); Mat out2 = top_blob.channel(p+2); Mat out3 = top_blob.channel(p+3); const float bias0 = bias ? bias[p] : 0.f; const float bias1 = bias ? bias[p+1] : 0.f; const float bias2 = bias ? bias[p+2] : 0.f; const float bias3 = bias ? bias[p+3] : 0.f; out0.fill(bias0); out1.fill(bias1); out2.fill(bias2); out3.fill(bias3); int q = 0; for (; q+3<inch; q+=4) { float* outptr0 = out0; float* outptr1 = out1; float* outptr2 = out2; float* outptr3 = out3; const float* img0 = bottom_blob.channel(q); const float* img1 = bottom_blob.channel(q+1); const float* img2 = bottom_blob.channel(q+2); const float* img3 = bottom_blob.channel(q+3); const float* kernel0 = kernel + p*inch + q; const float* kernel1 = kernel + (p+1)*inch + q; const float* kernel2 = kernel + (p+2)*inch + q; const float* kernel3 = kernel + (p+3)*inch + q; const float* r0 = img0; const float* r1 = img1; const float* r2 = img2; const float* r3 = img3; for (int i = 0; i < outh; i++) { int size = outw; #if __ARM_NEON int nn = size >> 3; int remain = size & 7; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vld1q_f32(kernel0); float32x4_t _k1 = vld1q_f32(kernel1); float32x4_t _k2 = vld1q_f32(kernel2); float32x4_t _k3 = vld1q_f32(kernel3); #if __aarch64__ if (nn > 0) { asm volatile( "0: \n" "prfm pldl1keep, [%5, #512] \n" "ld2 {v4.4s, v5.4s}, [%5], #32 \n" "ld2 {v6.4s, v7.4s}, [%5], #32 \n" "and v5.16b, v6.16b, v6.16b \n"// v4 v5 "prfm pldl1keep, [%1, #256] \n" "ld1 {v8.4s, v9.4s}, [%1] \n" "fmla v8.4s, v4.4s, %18.s[0] \n" "fmla v9.4s, v5.4s, %18.s[0] \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v10.4s, v11.4s}, [%2] \n" "fmla v10.4s, v4.4s, %19.s[0] \n" "fmla v11.4s, v5.4s, %19.s[0] \n" "prfm pldl1keep, [%3, #256] \n" "ld1 {v12.4s, v13.4s}, [%3] \n" "fmla v12.4s, v4.4s, %20.s[0] \n" "fmla v13.4s, v5.4s, %20.s[0] \n" "prfm pldl1keep, [%4, #256] \n" "ld1 {v14.4s, v15.4s}, [%4] \n" "prfm pldl1keep, [%6, #512] \n" "ld2 {v6.4s, v7.4s}, [%6], #32 \n" "fmla v14.4s, v4.4s, %21.s[0] \n" "fmla v15.4s, v5.4s, %21.s[0] \n" "ld2 {v4.4s, v5.4s}, [%6], #32 \n" "and v7.16b, v4.16b, v4.16b \n"// v6 v7 "fmla v8.4s, v6.4s, %18.s[1] \n" "fmla v9.4s, v7.4s, %18.s[1] \n" "fmla v10.4s, v6.4s, %19.s[1] \n" "fmla v11.4s, v7.4s, %19.s[1] \n" "fmla v12.4s, v6.4s, %20.s[1] \n" "fmla v13.4s, v7.4s, %20.s[1] \n" "prfm pldl1keep, [%7, #512] \n" "ld2 {v4.4s, v5.4s}, [%7], #32 \n" "fmla v14.4s, v6.4s, %21.s[1] \n" "fmla v15.4s, v7.4s, %21.s[1] \n" "ld2 {v6.4s, v7.4s}, [%7], #32 \n" "and v5.16b, v6.16b, v6.16b \n"// v4 v5 "fmla v8.4s, v4.4s, %18.s[2] \n" "fmla v9.4s, v5.4s, %18.s[2] \n" "fmla v10.4s, v4.4s, %19.s[2] \n" "fmla v11.4s, v5.4s, %19.s[2] \n" "fmla v12.4s, v4.4s, %20.s[2] \n" "fmla v13.4s, v5.4s, %20.s[2] \n" "prfm pldl1keep, [%8, #512] \n" "ld2 {v6.4s, v7.4s}, [%8], #32 \n" "fmla v14.4s, v4.4s, %21.s[2] \n" "fmla v15.4s, v5.4s, %21.s[2] \n" "ld2 {v4.4s, v5.4s}, [%8], #32 \n" "and v7.16b, v4.16b, v4.16b \n"// v6 v7 "fmla v8.4s, v6.4s, %18.s[3] \n" "fmla v9.4s, v7.4s, %18.s[3] \n" "fmla v10.4s, v6.4s, %19.s[3] \n" "fmla v11.4s, v7.4s, %19.s[3] \n" "st1 {v8.4s, v9.4s}, [%1], #32 \n" "fmla v12.4s, v6.4s, %20.s[3] \n" "fmla v13.4s, v7.4s, %20.s[3] \n" "st1 {v10.4s, v11.4s}, [%2], #32 \n" "fmla v14.4s, v6.4s, %21.s[3] \n" "fmla v15.4s, v7.4s, %21.s[3] \n" "st1 {v12.4s, v13.4s}, [%3], #32 \n" "subs %w0, %w0, #1 \n" "st1 {v14.4s, v15.4s}, [%4], #32 \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr0),// %1 "=r"(outptr1),// %2 "=r"(outptr2),// %3 "=r"(outptr3),// %4 "=r"(r0), // %5 "=r"(r1), // %6 "=r"(r2), // %7 "=r"(r3) // %8 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(r0), "6"(r1), "7"(r2), "8"(r3), "w"(_k0), // %18 "w"(_k1), // %19 "w"(_k2), // %20 "w"(_k3) // %21 : "cc", "memory", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15" ); } #else if (nn > 0) { asm volatile( "0: \n" "pld [%5, #512] \n" "vld2.f32 {d8-d11}, [%5]! \n" "vld2.f32 {d12-d15}, [%5]! \n" "vand q5, q6, q6 \n"// q4 q5 "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1] \n" "vmla.f32 q8, q4, %e18[0] \n" "vmla.f32 q9, q5, %e18[0] \n" "pld [%2, #256] \n" "vld1.f32 {d20-d23}, [%2] \n" "vmla.f32 q10, q4, %e19[0] \n" "vmla.f32 q11, q5, %e19[0] \n" "pld [%3, #256] \n" "vld1.f32 {d24-d27}, [%3] \n" "vmla.f32 q12, q4, %e20[0] \n" "vmla.f32 q13, q5, %e20[0] \n" "pld [%4, #256] \n" "vld1.f32 {d28-d31}, [%4] \n" "pld [%6, #512] \n" "vld2.f32 {d12-d15}, [%6]! \n" "vmla.f32 q14, q4, %e21[0] \n" "vmla.f32 q15, q5, %e21[0] \n" "vld2.f32 {d8-d11}, [%6]! \n" "vand q7, q4, q4 \n"// q6 q7 "vmla.f32 q8, q6, %e18[1] \n" "vmla.f32 q9, q7, %e18[1] \n" "vmla.f32 q10, q6, %e19[1] \n" "vmla.f32 q11, q7, %e19[1] \n" "vmla.f32 q12, q6, %e20[1] \n" "vmla.f32 q13, q7, %e20[1] \n" "pld [%7, #512] \n" "vld2.f32 {d8-d11}, [%7]! \n" "vmla.f32 q14, q6, %e21[1] \n" "vmla.f32 q15, q7, %e21[1] \n" "vld2.f32 {d12-d15}, [%7]! \n" "vand q5, q6, q6 \n"// q4 q5 "vmla.f32 q8, q4, %f18[0] \n" "vmla.f32 q9, q5, %f18[0] \n" "vmla.f32 q10, q4, %f19[0] \n" "vmla.f32 q11, q5, %f19[0] \n" "vmla.f32 q12, q4, %f20[0] \n" "vmla.f32 q13, q5, %f20[0] \n" "pld [%8, #512] \n" "vld2.f32 {d12-d15}, [%8]! \n" "vmla.f32 q14, q4, %f21[0] \n" "vmla.f32 q15, q5, %f21[0] \n" "vld2.f32 {d8-d11}, [%8]! \n" "vand q7, q4, q4 \n"// q6 q7 "vmla.f32 q8, q6, %f18[1] \n" "vmla.f32 q9, q7, %f18[1] \n" "vmla.f32 q10, q6, %f19[1] \n" "vmla.f32 q11, q7, %f19[1] \n" "vst1.f32 {d16-d19}, [%1]! \n" "vmla.f32 q12, q6, %f20[1] \n" "vmla.f32 q13, q7, %f20[1] \n" "vst1.f32 {d20-d23}, [%2]! \n" "vmla.f32 q14, q6, %f21[1] \n" "vmla.f32 q15, q7, %f21[1] \n" "vst1.f32 {d24-d27}, [%3]! \n" "subs %0, #1 \n" "vst1.f32 {d28-d31}, [%4]! \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr0),// %1 "=r"(outptr1),// %2 "=r"(outptr2),// %3 "=r"(outptr3),// %4 "=r"(r0), // %5 "=r"(r1), // %6 "=r"(r2), // %7 "=r"(r3) // %8 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(r0), "6"(r1), "7"(r2), "8"(r3), "w"(_k0), // %18 "w"(_k1), // %19 "w"(_k2), // %20 "w"(_k3) // %21 : "cc", "memory", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { // TODO neon optimize float sum0 = *r0 * kernel0[0] + *r1 * kernel0[1] + *r2 * kernel0[2] + *r3 * kernel0[3]; float sum1 = *r0 * kernel1[0] + *r1 * kernel1[1] + *r2 * kernel1[2] + *r3 * kernel1[3]; float sum2 = *r0 * kernel2[0] + *r1 * kernel2[1] + *r2 * kernel2[2] + *r3 * kernel2[3]; float sum3 = *r0 * kernel3[0] + *r1 * kernel3[1] + *r2 * kernel3[2] + *r3 * kernel3[3]; *outptr0 += sum0; *outptr1 += sum1; *outptr2 += sum2; *outptr3 += sum3; r0 += 2; r1 += 2; r2 += 2; r3 += 2; outptr0++; outptr1++; outptr2++; outptr3++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; r3 += tailstep; } } for (; q<inch; q++) { float* outptr0 = out0; float* outptr1 = out1; float* outptr2 = out2; float* outptr3 = out3; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p*inch + q; const float* kernel1 = kernel + (p+1)*inch + q; const float* kernel2 = kernel + (p+2)*inch + q; const float* kernel3 = kernel + (p+3)*inch + q; const float k0 = kernel0[0]; const float k1 = kernel1[0]; const float k2 = kernel2[0]; const float k3 = kernel3[0]; const float* r0 = img0; for (int i = 0; i < outh; i++) { int size = outw; #if __ARM_NEON int nn = size >> 3; int remain = size & 7; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); float32x4_t _k1 = vdupq_n_f32(k1); float32x4_t _k2 = vdupq_n_f32(k2); float32x4_t _k3 = vdupq_n_f32(k3); #if __aarch64__ if (nn > 0) { asm volatile( "0: \n" "prfm pldl1keep, [%5, #512] \n" "ld2 {v4.4s, v5.4s}, [%5], #32 \n" "ld2 {v6.4s, v7.4s}, [%5], #32 \n" "and v5.16b, v6.16b, v6.16b \n" "prfm pldl1keep, [%1, #256] \n" "ld1 {v8.4s, v9.4s}, [%1] \n" "fmla v8.4s, v4.4s, %12.4s \n" "fmla v9.4s, v5.4s, %12.4s \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v10.4s, v11.4s}, [%2] \n" "fmla v10.4s, v4.4s, %13.4s \n" "fmla v11.4s, v5.4s, %13.4s \n" "prfm pldl1keep, [%3, #256] \n" "ld1 {v12.4s, v13.4s}, [%3] \n" "st1 {v8.4s, v9.4s}, [%1], #32 \n" "fmla v12.4s, v4.4s, %14.4s \n" "fmla v13.4s, v5.4s, %14.4s \n" "prfm pldl1keep, [%4, #256] \n" "ld1 {v14.4s, v15.4s}, [%4] \n" "st1 {v10.4s, v11.4s}, [%2], #32 \n" "fmla v14.4s, v4.4s, %15.4s \n" "fmla v15.4s, v5.4s, %15.4s \n" "st1 {v12.4s, v13.4s}, [%3], #32 \n" "subs %w0, %w0, #1 \n" "st1 {v14.4s, v15.4s}, [%4], #32 \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr0),// %1 "=r"(outptr1),// %2 "=r"(outptr2),// %3 "=r"(outptr3),// %4 "=r"(r0) // %5 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(r0), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15" ); } #else if (nn > 0) { asm volatile( "0: \n" "pld [%5, #512] \n" "vld2.f32 {d8-d11}, [%5]! \n" "vld2.f32 {d12-d15}, [%5]! \n" "vand q5, q6, q6 \n"// q4 q5 "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1] \n" "vmla.f32 q8, q4, %q12 \n" "vmla.f32 q9, q5, %q12 \n" "pld [%2, #256] \n" "vld1.f32 {d20-d23}, [%2] \n" "vmla.f32 q10, q4, %q13 \n" "vmla.f32 q11, q5, %q13 \n" "pld [%3, #256] \n" "vld1.f32 {d24-d27}, [%3] \n" "vst1.f32 {d16-d19}, [%1]! \n" "vmla.f32 q12, q4, %q14 \n" "vmla.f32 q13, q5, %q14 \n" "pld [%4, #256] \n" "vld1.f32 {d28-d31}, [%4] \n" "vst1.f32 {d20-d23}, [%2]! \n" "vmla.f32 q14, q4, %q15 \n" "vmla.f32 q15, q5, %q15 \n" "vst1.f32 {d24-d27}, [%3]! \n" "subs %0, #1 \n" "vst1.f32 {d28-d31}, [%4]! \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr0),// %1 "=r"(outptr1),// %2 "=r"(outptr2),// %3 "=r"(outptr3),// %4 "=r"(r0) // %5 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(r0), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { // TODO neon optimize float sum0 = *r0 * k0; float sum1 = *r0 * k1; float sum2 = *r0 * k2; float sum3 = *r0 * k3; *outptr0 += sum0; *outptr1 += sum1; *outptr2 += sum2; *outptr3 += sum3; r0 += 2; outptr0++; outptr1++; outptr2++; outptr3++; } r0 += tailstep; } } } #pragma omp parallel for for (int p=remain_outch_start; p<outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); int q = 0; for (; q+3<inch; q+=4) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* img1 = bottom_blob.channel(q+1); const float* img2 = bottom_blob.channel(q+2); const float* img3 = bottom_blob.channel(q+3); const float* kernel0 = kernel + p*inch + q; const float k0 = kernel0[0]; const float k1 = kernel0[1]; const float k2 = kernel0[2]; const float k3 = kernel0[3]; const float* r0 = img0; const float* r1 = img1; const float* r2 = img2; const float* r3 = img3; for (int i = 0; i < outh; i++) { #if __ARM_NEON int nn = outw >> 3; int remain = outw & 7; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); float32x4_t _k1 = vdupq_n_f32(k1); float32x4_t _k2 = vdupq_n_f32(k2); float32x4_t _k3 = vdupq_n_f32(k3); #if __aarch64__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%2, #512] \n" "ld2 {v2.4s, v3.4s}, [%2], #32 \n" "ld2 {v8.4s, v9.4s}, [%2], #32 \n" "0: \n" "prfm pldl1keep, [%1, #256] \n" "ld1 {v0.4s, v1.4s}, [%1] \n" "fmla v0.4s, v2.4s, %12.4s \n" "fmla v1.4s, v8.4s, %12.4s \n" "prfm pldl1keep, [%3, #512] \n" "ld2 {v2.4s, v3.4s}, [%3], #32 \n" "ld2 {v8.4s, v9.4s}, [%3], #32 \n" "fmla v0.4s, v2.4s, %13.4s \n" "fmla v1.4s, v8.4s, %13.4s \n" "prfm pldl1keep, [%4, #512] \n" "ld2 {v2.4s, v3.4s}, [%4], #32 \n" "ld2 {v8.4s, v9.4s}, [%4], #32 \n" "fmla v0.4s, v2.4s, %14.4s \n" "fmla v1.4s, v8.4s, %14.4s \n" "prfm pldl1keep, [%5, #512] \n" "ld2 {v2.4s, v3.4s}, [%5], #32 \n" "ld2 {v8.4s, v9.4s}, [%5], #32 \n" "fmla v0.4s, v2.4s, %15.4s \n" "fmla v1.4s, v8.4s, %15.4s \n" "prfm pldl1keep, [%2, #512] \n" "ld2 {v2.4s, v3.4s}, [%2], #32 \n" "ld2 {v8.4s, v9.4s}, [%2], #32 \n" "subs %w0, %w0, #1 \n" "st1 {v0.4s, v1.4s}, [%1], #32 \n" "bne 0b \n" "sub %2, %2, #64 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2), // %4 "=r"(r3) // %5 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "5"(r3), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "v0", "v1", "v2", "v3", "v8", "v9" ); } #else if (nn > 0) { asm volatile( "pld [%2, #512] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vld2.f32 {d16-d19}, [%2]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1] \n" "vmla.f32 q0, q2, %q12 \n" "vmla.f32 q1, q8, %q12 \n" "pld [%3, #512] \n" "vld2.f32 {d4-d7}, [%3]! \n" "vld2.f32 {d16-d19}, [%3]! \n" "vmla.f32 q0, q2, %q13 \n" "vmla.f32 q1, q8, %q13 \n" "pld [%4, #512] \n" "vld2.f32 {d4-d7}, [%4]! \n" "vld2.f32 {d16-d19}, [%4]! \n" "vmla.f32 q0, q2, %q14 \n" "vmla.f32 q1, q8, %q14 \n" "pld [%5, #512] \n" "vld2.f32 {d4-d7}, [%5]! \n" "vld2.f32 {d16-d19}, [%5]! \n" "vmla.f32 q0, q2, %q15 \n" "vmla.f32 q1, q8, %q15 \n" "pld [%2, #512] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vld2.f32 {d16-d19}, [%2]! \n" "subs %0, #1 \n" "vst1.f32 {d0-d3}, [%1]! \n" "bne 0b \n" "sub %2, #64 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2), // %4 "=r"(r3) // %5 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "5"(r3), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "q0", "q1", "q2", "q3", "q8", "q9" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { float sum = *r0 * k0; float sum1 = *r1 * k1; float sum2 = *r2 * k2; float sum3 = *r3 * k3; *outptr += sum + sum1 + sum2 + sum3; r0 += 2; r1 += 2; r2 += 2; r3 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; r3 += tailstep; } } for (; q<inch; q++) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p*inch + q; const float k0 = kernel0[0]; const float* r0 = img0; for (int i = 0; i < outh; i++) { #if __ARM_NEON int nn = outw >> 3; int remain = outw & 7; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); #if __aarch64__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%2, #512] \n" "ld2 {v2.4s, v3.4s}, [%2], #32 \n" "ld2 {v8.4s, v9.4s}, [%2], #32 \n" "0: \n" "prfm pldl1keep, [%1, #256] \n" "ld1 {v0.4s, v1.4s}, [%1] \n" "fmla v0.4s, v2.4s, %6.4s \n" "fmla v1.4s, v8.4s, %6.4s \n" "prfm pldl1keep, [%2, #512] \n" "ld2 {v2.4s, v3.4s}, [%2], #32 \n" "ld2 {v8.4s, v9.4s}, [%2], #32 \n" "subs %w0, %w0, #1 \n" "st1 {v0.4s, v1.4s}, [%1], #32 \n" "bne 0b \n" "sub %2, %2, #64 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0) // %2 : "0"(nn), "1"(outptr), "2"(r0), "w"(_k0) // %6 : "cc", "memory", "v0", "v1", "v2", "v3", "v8", "v9" ); } #else if (nn > 0) { asm volatile( "pld [%2, #512] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vld2.f32 {d16-d19}, [%2]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1] \n" "vmla.f32 q0, q2, %q6 \n" "vmla.f32 q1, q8, %q6 \n" "pld [%2, #512] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vld2.f32 {d16-d19}, [%2]! \n" "subs %0, #1 \n" "vst1.f32 {d0-d3}, [%1]! \n" "bne 0b \n" "sub %2, #64 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0) // %2 : "0"(nn), "1"(outptr), "2"(r0), "w"(_k0) // %6 : "cc", "memory", "q0", "q1", "q2", "q3", "q8", "q9" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { float sum = *r0 * k0; *outptr += sum; r0 += 2; outptr++; } r0 += tailstep; } } } }
Psatd.h
#pragma once #include "Constants.h" #include "FieldSolver.h" #include "Grid.h" #include "Vectors.h" #include "PmlPsatd.h" //#include <chrono> #include <omp.h> namespace pfc { template <bool ifPoisson> class PSATDTimeStraggeredT : public SpectralFieldSolver<PSATDTimeStraggeredGridType> { public: PSATDTimeStraggeredT(PSATDTimeStraggeredGrid * grid, FP dt); void updateFields(); void updateHalfB(); void updateE(); void setPML(int sizePMLx, int sizePMLy, int sizePMLz); void setTimeStep(FP dt); void convertFieldsPoissonEquation(); ScalarField<complexFP> tmpJx, tmpJy, tmpJz; bool ifCourantConditionSatisfied(FP dt) { return true; } protected: PmlSpectral<GridTypes::PSATDTimeStraggeredGridType>* getPml() { return (PmlSpectral<GridTypes::PSATDTimeStraggeredGridType>*)pml.get(); } void saveJ(); void assignJ(ScalarField<complexFP>& J, ScalarField<complexFP>& tmpJ); }; template <bool ifPoisson> inline PSATDTimeStraggeredT<ifPoisson>::PSATDTimeStraggeredT(PSATDTimeStraggeredGrid* _grid, FP dt) : SpectralFieldSolver<GridTypes::PSATDTimeStraggeredGridType>(_grid, dt, 0.0, 0.5*dt, 0.5*dt), tmpJx(complexGrid->sizeStorage), tmpJy(complexGrid->sizeStorage), tmpJz(complexGrid->sizeStorage) { updateDims(); updateInternalDims(); } template <bool ifPoisson> inline void PSATDTimeStraggeredT<ifPoisson>::setPML(int sizePMLx, int sizePMLy, int sizePMLz) { pml.reset(new PmlPsatdTimeStraggered(this, Int3(sizePMLx, sizePMLy, sizePMLz))); updateInternalDims(); } template <bool ifPoisson> inline void PSATDTimeStraggeredT<ifPoisson>::setTimeStep(FP dt) { this->dt = dt; this->timeShiftB = 0.5*dt; this->timeShiftJ = 0.5*dt; if (pml.get()) pml.reset(new PmlPsatdTimeStraggered(this, pml->sizePML)); } template <bool ifPoisson> inline void PSATDTimeStraggeredT<ifPoisson>::assignJ(ScalarField<complexFP>& J, ScalarField<complexFP>& tmpJ) { const complexFP * const ptrJ = J.getData(); complexFP * const ptrTmpJ = tmpJ.getData(); const int n = J.getSize().volume(); #pragma omp parallel for for (int i = 0; i < n; i++) ptrTmpJ[i] = ptrJ[i]; } template <bool ifPoisson> inline void PSATDTimeStraggeredT<ifPoisson>::saveJ() { assignJ(complexGrid->Jx, tmpJx); assignJ(complexGrid->Jy, tmpJy); assignJ(complexGrid->Jz, tmpJz); } template <bool ifPoisson> inline void PSATDTimeStraggeredT<ifPoisson>::updateFields() { doFourierTransform(fourier_transform::Direction::RtoC); if (pml.get()) getPml()->updateBSplit(); updateHalfB(); if (pml.get()) getPml()->updateESplit(); updateE(); if (pml.get()) getPml()->updateBSplit(); updateHalfB(); saveJ(); doFourierTransform(fourier_transform::Direction::CtoR); if (pml.get()) getPml()->doSecondStep(); globalTime += dt; } template <bool ifPoisson> inline void PSATDTimeStraggeredT<ifPoisson>::convertFieldsPoissonEquation() { doFourierTransform(fourier_transform::Direction::RtoC); const Int3 begin = updateComplexBAreaBegin; const Int3 end = updateComplexBAreaEnd; double dt = this->dt * 0.5; #pragma omp parallel for collapse(2) for (int i = begin.x; i < end.x; i++) for (int j = begin.y; j < end.y; j++) { //#pragma omp simd for (int k = begin.z; k < end.z; k++) { FP3 K = getWaveVector(Int3(i, j, k)); FP normK = K.norm(); if (normK == 0) { continue; } K = K / normK; ComplexFP3 E(complexGrid->Ex(i, j, k), complexGrid->Ey(i, j, k), complexGrid->Ez(i, j, k)); ComplexFP3 El = (ComplexFP3)K * dot((ComplexFP3)K, E); complexGrid->Ex(i, j, k) -= El.x; complexGrid->Ey(i, j, k) -= El.y; complexGrid->Ez(i, j, k) -= El.z; } } doFourierTransform(fourier_transform::Direction::CtoR); } template <bool ifPoisson> inline void PSATDTimeStraggeredT<ifPoisson>::updateHalfB() { const Int3 begin = updateComplexBAreaBegin; const Int3 end = updateComplexBAreaEnd; double dt = 0.5 * this->dt; #pragma omp parallel for collapse(2) for (int i = begin.x; i < end.x; i++) for (int j = begin.y; j < end.y; j++) { //#pragma omp simd for (int k = begin.z; k < end.z; k++) { FP3 K = getWaveVector(Int3(i, j, k)); FP normK = K.norm(); if (normK == 0) { continue; } K = K / normK; ComplexFP3 E(complexGrid->Ex(i, j, k), complexGrid->Ey(i, j, k), complexGrid->Ez(i, j, k)); ComplexFP3 J(complexGrid->Jx(i, j, k), complexGrid->Jy(i, j, k), complexGrid->Jz(i, j, k)), prevJ(tmpJx(i, j, k), tmpJy(i, j, k), tmpJz(i, j, k)); ComplexFP3 crossKE = cross((ComplexFP3)K, E); ComplexFP3 crossKJ = cross((ComplexFP3)K, J - prevJ); FP S = sin(normK*constants::c*dt*0.5), C = cos(normK*constants::c*dt*0.5); complexFP coeff1 = 2 * complexFP::i()*S, coeff2 = complexFP::i() * ((1 - C) / (normK*constants::c)); complexGrid->Bx(i, j, k) += -coeff1 * crossKE.x + coeff2 * crossKJ.x; complexGrid->By(i, j, k) += -coeff1 * crossKE.y + coeff2 * crossKJ.y; complexGrid->Bz(i, j, k) += -coeff1 * crossKE.z + coeff2 * crossKJ.z; } } } template <bool ifPoisson> inline void PSATDTimeStraggeredT<ifPoisson>::updateE() { const Int3 begin = updateComplexEAreaBegin; const Int3 end = updateComplexEAreaEnd; #pragma omp parallel for collapse(2) for (int i = begin.x; i < end.x; i++) for (int j = begin.y; j < end.y; j++) { //#pragma omp simd for (int k = begin.z; k < end.z; k++) { FP3 K = getWaveVector(Int3(i, j, k)); FP normK = K.norm(); if (normK == 0) { complexGrid->Ex(i, j, k) += dt * complexGrid->Jx(i, j, k); complexGrid->Ey(i, j, k) += dt * complexGrid->Jy(i, j, k); complexGrid->Ez(i, j, k) += dt * complexGrid->Jz(i, j, k); continue; } K = K / normK; ComplexFP3 B(complexGrid->Bx(i, j, k), complexGrid->By(i, j, k), complexGrid->Bz(i, j, k)); ComplexFP3 J(complexGrid->Jx(i, j, k), complexGrid->Jy(i, j, k), complexGrid->Jz(i, j, k)); ComplexFP3 crossKB = cross((ComplexFP3)K, B); ComplexFP3 Jl = (ComplexFP3)K * dot((ComplexFP3)K, J); FP S = sin(normK*constants::c*dt*0.5); complexFP coeff1 = 2 * complexFP::i()*S, coeff2 = 2 * S / (normK*constants::c), coeff3 = coeff2 - dt; complexGrid->Ex(i, j, k) += coeff1 * crossKB.x - coeff2 * J.x + coeff3 * Jl.x; complexGrid->Ey(i, j, k) += coeff1 * crossKB.y - coeff2 * J.y + coeff3 * Jl.y; complexGrid->Ez(i, j, k) += coeff1 * crossKB.z - coeff2 * J.z + coeff3 * Jl.z; } } } // provides k \cdot E = 0 always (k \cdot J = 0 too) template <> inline void PSATDTimeStraggeredT<true>::updateE() { const Int3 begin = updateComplexEAreaBegin; const Int3 end = updateComplexEAreaEnd; #pragma omp parallel for collapse(2) for (int i = begin.x; i < end.x; i++) for (int j = begin.y; j < end.y; j++) { //#pragma omp simd for (int k = begin.z; k < end.z; k++) { FP3 K = getWaveVector(Int3(i, j, k)); FP normK = K.norm(); if (normK == 0) { complexGrid->Ex(i, j, k) += dt * complexGrid->Jx(i, j, k); complexGrid->Ey(i, j, k) += dt * complexGrid->Jy(i, j, k); complexGrid->Ez(i, j, k) += dt * complexGrid->Jz(i, j, k); continue; } K = K / normK; ComplexFP3 E(complexGrid->Ex(i, j, k), complexGrid->Ey(i, j, k), complexGrid->Ez(i, j, k)); ComplexFP3 B(complexGrid->Bx(i, j, k), complexGrid->By(i, j, k), complexGrid->Bz(i, j, k)); ComplexFP3 J(complexGrid->Jx(i, j, k), complexGrid->Jy(i, j, k), complexGrid->Jz(i, j, k)); ComplexFP3 crossKB = cross((ComplexFP3)K, B); ComplexFP3 El = (ComplexFP3)K * dot((ComplexFP3)K, E); ComplexFP3 Jl = (ComplexFP3)K * dot((ComplexFP3)K, J); FP S = sin(normK*constants::c*dt*0.5); complexFP coeff1 = 2 * complexFP::i()*S, coeff2 = 2 * S / (normK*constants::c), coeff3 = coeff2 - dt; complexGrid->Ex(i, j, k) += -El.x + coeff1 * crossKB.x - coeff2 * (J.x - Jl.x); complexGrid->Ey(i, j, k) += -El.y + coeff1 * crossKB.y - coeff2 * (J.y - Jl.y); complexGrid->Ez(i, j, k) += -El.z + coeff1 * crossKB.z - coeff2 * (J.z - Jl.z); } } } template <bool ifPoisson> class PSATDT : public SpectralFieldSolver<PSATDGridType> { public: PSATDT(PSATDGrid* grid, FP dt); void updateFields(); virtual void updateEB(); void setPML(int sizePMLx, int sizePMLy, int sizePMLz); void setTimeStep(FP dt); void convertFieldsPoissonEquation(); bool ifCourantConditionSatisfied(FP dt) { return true; } private: PmlSpectralTimeStraggered<GridTypes::PSATDGridType>* getPml() { return (PmlSpectralTimeStraggered<GridTypes::PSATDGridType>*)pml.get(); } }; template <bool ifPoisson> inline PSATDT<ifPoisson>::PSATDT(PSATDGrid* _grid, FP dt) : SpectralFieldSolver<GridTypes::PSATDGridType>(_grid, dt, 0.0, 0.0, 0.5*dt) { updateDims(); updateInternalDims(); } template <bool ifPoisson> inline void PSATDT<ifPoisson>::setPML(int sizePMLx, int sizePMLy, int sizePMLz) { pml.reset(new PmlPsatd(this, Int3(sizePMLx, sizePMLy, sizePMLz))); updateInternalDims(); } template <bool ifPoisson> inline void PSATDT<ifPoisson>::setTimeStep(FP dt) { this->dt = dt; this->timeShiftJ = 0.5*dt; if (pml.get()) pml.reset(new PmlPsatd(this, pml->sizePML)); } template <bool ifPoisson> inline void PSATDT<ifPoisson>::updateFields() { // std::chrono::steady_clock::time_point t1 = std::chrono::steady_clock::now(); doFourierTransform(fourier_transform::Direction::RtoC); //std::chrono::steady_clock::time_point t2 = std::chrono::steady_clock::now(); //std::chrono::milliseconds timeRtoC = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1); //std::chrono::steady_clock::time_point t3 = std::chrono::steady_clock::now(); if (pml.get()) getPml()->updateBSplit(); updateEB(); if (pml.get()) getPml()->updateESplit(); updateEB(); if (pml.get()) getPml()->updateBSplit(); //std::chrono::steady_clock::time_point t4 = std::chrono::steady_clock::now(); //std::chrono::milliseconds timeSolver = std::chrono::duration_cast<std::chrono::milliseconds>(t4 - t3); //std::chrono::steady_clock::time_point t5 = std::chrono::steady_clock::now(); doFourierTransform(fourier_transform::Direction::CtoR); //std::chrono::steady_clock::time_point t6 = std::chrono::steady_clock::now(); //std::chrono::milliseconds timeCtoR = std::chrono::duration_cast<std::chrono::milliseconds>(t6 - t5); if (pml.get()) getPml()->doSecondStep(); globalTime += dt; //std::string strRtoC = "Time RtoC: " + std::to_string(timeRtoC.count()) + "\n"; //std::string strSolver = "Time PSATDT: " + std::to_string(timeSolver.count()) + "\n"; //std::string strCtoR = "Time CtoR: " + std::to_string(timeCtoR.count()) + "\n"; //std::cout << strRtoC << strSolver << strCtoR << std::endl; } template <bool ifPoisson> inline void PSATDT<ifPoisson>::convertFieldsPoissonEquation() { doFourierTransform(fourier_transform::Direction::RtoC); const Int3 begin = updateComplexBAreaBegin; const Int3 end = updateComplexBAreaEnd; double dt = this->dt *0.5; #pragma omp parallel for collapse(2) for (int i = begin.x; i < end.x; i++) for (int j = begin.y; j < end.y; j++) { //#pragma omp simd for (int k = begin.z; k < end.z; k++) { FP3 K = getWaveVector(Int3(i, j, k)); FP normK = K.norm(); if (normK == 0) { continue; } K = K / normK; ComplexFP3 E(complexGrid->Ex(i, j, k), complexGrid->Ey(i, j, k), complexGrid->Ez(i, j, k)); ComplexFP3 El = (ComplexFP3)K * dot((ComplexFP3)K, E); complexGrid->Ex(i, j, k) -= El.x; complexGrid->Ey(i, j, k) -= El.y; complexGrid->Ez(i, j, k) -= El.z; } } doFourierTransform(fourier_transform::Direction::CtoR); } template <bool ifPoisson> inline void PSATDT<ifPoisson>::updateEB() { const Int3 begin = updateComplexBAreaBegin; const Int3 end = updateComplexBAreaEnd; double dt = 0.5 * this->dt; #pragma omp parallel for collapse(2) for (int i = begin.x; i < end.x; i++) for (int j = begin.y; j < end.y; j++) { //#pragma omp simd for (int k = begin.z; k < end.z; k++) { FP3 K = getWaveVector(Int3(i, j, k)); FP normK = K.norm(); ComplexFP3 E(complexGrid->Ex(i, j, k), complexGrid->Ey(i, j, k), complexGrid->Ez(i, j, k)); ComplexFP3 B(complexGrid->Bx(i, j, k), complexGrid->By(i, j, k), complexGrid->Bz(i, j, k)); ComplexFP3 J(complexGrid->Jx(i, j, k), complexGrid->Jy(i, j, k), complexGrid->Jz(i, j, k)); J = complexFP(4 * constants::pi) * J; if (normK == 0) { complexGrid->Ex(i, j, k) += -J.x; complexGrid->Ey(i, j, k) += -J.y; complexGrid->Ez(i, j, k) += -J.z; continue; } K = K / normK; ComplexFP3 kEcross = cross((ComplexFP3)K, E), kBcross = cross((ComplexFP3)K, B), kJcross = cross((ComplexFP3)K, J); ComplexFP3 Jl = (ComplexFP3)K * dot((ComplexFP3)K, J), El = (ComplexFP3)K * dot((ComplexFP3)K, E); FP S = sin(normK*constants::c*dt), C = cos(normK*constants::c*dt); complexFP coef1E = S * complexFP::i(), coef2E = -S / (normK*constants::c), coef3E = S / (normK*constants::c) - dt; complexGrid->Ex(i, j, k) = C * E.x + coef1E * kBcross.x + (1 - C) * El.x + coef2E * J.x + coef3E * Jl.x; complexGrid->Ey(i, j, k) = C * E.y + coef1E * kBcross.y + (1 - C) * El.y + coef2E * J.y + coef3E * Jl.y; complexGrid->Ez(i, j, k) = C * E.z + coef1E * kBcross.z + (1 - C) * El.z + coef2E * J.z + coef3E * Jl.z; complexFP coef1B = -S * complexFP::i(), coef2B = ((1 - C) / (normK*constants::c))*complexFP::i(); complexGrid->Bx(i, j, k) = C * B.x + coef1B * kEcross.x + coef2B * kJcross.x; complexGrid->By(i, j, k) = C * B.y + coef1B * kEcross.y + coef2B * kJcross.y; complexGrid->Bz(i, j, k) = C * B.z + coef1B * kEcross.z + coef2B * kJcross.z; } } } // provides k \cdot E = 0 always (k \cdot J = 0 too) template <> inline void PSATDT<true>::updateEB() { const Int3 begin = updateComplexBAreaBegin; const Int3 end = updateComplexBAreaEnd; double dt = 0.5 * this->dt; #pragma omp parallel for collapse(2) for (int i = begin.x; i < end.x; i++) for (int j = begin.y; j < end.y; j++) { //#pragma omp simd for (int k = begin.z; k < end.z; k++) { FP3 K = getWaveVector(Int3(i, j, k)); FP normK = K.norm(); ComplexFP3 E(complexGrid->Ex(i, j, k), complexGrid->Ey(i, j, k), complexGrid->Ez(i, j, k)); ComplexFP3 B(complexGrid->Bx(i, j, k), complexGrid->By(i, j, k), complexGrid->Bz(i, j, k)); ComplexFP3 J(complexGrid->Jx(i, j, k), complexGrid->Jy(i, j, k), complexGrid->Jz(i, j, k)); J = complexFP(4 * constants::pi) * J; if (normK == 0) { complexGrid->Ex(i, j, k) += -J.x; complexGrid->Ey(i, j, k) += -J.y; complexGrid->Ez(i, j, k) += -J.z; continue; } K = K / normK; ComplexFP3 kEcross = cross((ComplexFP3)K, E), kBcross = cross((ComplexFP3)K, B), kJcross = cross((ComplexFP3)K, J); ComplexFP3 Jl = (ComplexFP3)K * dot((ComplexFP3)K, J), El = (ComplexFP3)K * dot((ComplexFP3)K, E); FP S = sin(normK*constants::c*dt), C = cos(normK*constants::c*dt); complexFP coef1E = S * complexFP::i(), coef2E = -S / (normK*constants::c), coef3E = S / (normK*constants::c) - dt; complexGrid->Ex(i, j, k) = C * (E.x - El.x) + coef1E * kBcross.x + coef2E * (J.x - Jl.x); complexGrid->Ey(i, j, k) = C * (E.y - El.y) + coef1E * kBcross.y + coef2E * (J.y - Jl.y); complexGrid->Ez(i, j, k) = C * (E.z - El.z) + coef1E * kBcross.z + coef2E * (J.z - Jl.z); complexFP coef1B = -S * complexFP::i(), coef2B = ((1 - C) / (normK*constants::c))*complexFP::i(); complexGrid->Bx(i, j, k) = C * B.x + coef1B * kEcross.x + coef2B * kJcross.x; complexGrid->By(i, j, k) = C * B.y + coef1B * kEcross.y + coef2B * kJcross.y; complexGrid->Bz(i, j, k) = C * B.z + coef1B * kEcross.z + coef2B * kJcross.z; } } } typedef PSATDT<true> PSATDPoisson; typedef PSATDT<false> PSATD; typedef PSATDTimeStraggeredT<true> PSATDTimeStraggeredPoisson; typedef PSATDTimeStraggeredT<false> PSATDTimeStraggered; }
Pattern.h
/***************************************************************************** * * Copyright (c) 2003-2018 by The University of Queensland * http://www.uq.edu.au * * Primary Business: Queensland, Australia * Licensed under the Apache License, version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 * * Development until 2012 by Earth Systems Science Computational Center (ESSCC) * Development 2012-2013 by School of Earth Sciences * Development from 2014 by Centre for Geoscience Computing (GeoComp) * *****************************************************************************/ /****************************************************************************/ /* Paso: CSC/CSR sparse matrix pattern */ /****************************************************************************/ /* Author: Lutz Gross, l.gross@uq.edu.au */ /****************************************************************************/ #ifndef __PASO_PATTERN_H__ #define __PASO_PATTERN_H__ #include "Paso.h" #include <escript/IndexList.h> namespace paso { struct Pattern; typedef boost::shared_ptr<Pattern> Pattern_ptr; typedef boost::shared_ptr<const Pattern> const_Pattern_ptr; struct Pattern : boost::enable_shared_from_this<Pattern> { Pattern(int type, dim_t numOutput, dim_t numInput, index_t* ptr, index_t* index); ~Pattern(); Pattern_ptr unrollBlocks(int newType, dim_t outputBlockSize, dim_t inputBlockSize); Pattern_ptr getSubpattern(dim_t newNumRows, dim_t newNumCols, const index_t* rowList, const index_t* newColIndex) const; /// Searches for a maximal independent set MIS in the matrix pattern void mis(index_t* mis_marker) const; void reduceBandwidth(index_t* oldToNew); Pattern_ptr multiply(int type, const_Pattern_ptr other) const; Pattern_ptr binop(int type, const_Pattern_ptr other) const; index_t* borrowMainDiagonalPointer(); static Pattern_ptr fromIndexListArray(dim_t n0, dim_t n, const escript::IndexList* index_list_array, index_t range_min, index_t range_max, index_t index_offset); index_t* borrowColoringPointer(); dim_t getBandwidth(index_t* label) const; inline bool isEmpty() const { return (!ptr && !index); } inline dim_t getNumColors() { // make sure numColors is defined borrowColoringPointer(); return numColors; } inline dim_t maxDeg() const { dim_t deg = 0; #pragma omp parallel { dim_t loc_deg=0; #pragma omp for for (dim_t i = 0; i < numInput; ++i) { loc_deg=std::max(loc_deg, ptr[i+1]-ptr[i]); } #pragma omp critical { deg = std::max(deg, loc_deg); } } return deg; } int type; // Number of rows in the ptr array [CSR] / number of cols for CSC dim_t numOutput; // Number of cols [CSR] dim_t numInput; // number of non-zeros dim_t len; // ptr[n] to ptr[n+1] lists indices (in index) of non-zeros in row n index_t* ptr; // Non-major indices of non-zeros (in CSR this will be col numbers) index_t* index; // pointer to main diagonal entry index_t* main_iptr; // number of colors dim_t numColors; // coloring index: inputs with the same color are not connected index_t* coloring; }; } // namespace paso #endif // __PASO_PATTERN_H__
sortc.c
#include <stdlib.h> #include <stdio.h> #include <math.h> typedef struct { float val; int index; } THEFIT; THEFIT *work; THEFIT *a; #pragma omp threadprivate (work,a) void RecMergeSort(int left, int right); void Sort(THEFIT *Ain, int n); void Merge(int s, int n, int m); void merge2(THEFIT *d1,int n,THEFIT *d2,int m,THEFIT *out); THEFIT *vector(int nl, int nh); void free_vector(THEFIT *v, int nl); int main() { THEFIT *data,*output; int i,j,k,k1,k2,k3,k4; printf("sort in c\n"); i=32; data=vector(1,i); for(j=1;j<=i;j++) { data[j].index=j; data[j].val=(float)rand()/(float)RAND_MAX; printf("%d %g\n",data[j].index,data[j].val); } printf("\n\n"); k=i/2; k1=k+1; k2=(i-k1)+1; #pragma omp sections { #pragma omp section Sort(&data[1],k); #pragma omp section Sort(&data[k1],k2); } for(j=1;j<=k;j++) { printf("%d %g\n",data[j].index,data[j].val); } printf("\n\n"); printf("\n\n"); for(j=k1;j<=i;j++) { printf("%d %g\n",data[j].index,data[j].val); } printf("\n\n"); printf("\n\n"); output=vector(1,i); merge2(&data[1],k,&data[k1],k2,&output[1]); for(j=1;j<=i;j++) { printf("%2d %10.7f\n",output[j].index,output[j].val); } return 0; } void Sort(THEFIT *Ain, int n){ work=vector(1,n); a=Ain-1; RecMergeSort(1,n); free_vector(work,1); } void RecMergeSort(int left, int right) { int middle; if (left < right) { middle = (left + right) / 2; RecMergeSort(left,middle); RecMergeSort(middle+1,right); Merge(left,middle-left+1,right-middle); } } void Merge(int s, int n, int m) { int i, j, k, t, u; k = 1; t = s + n; u = t + m; i = s; j = t; if ((i < t) && (j < u)){ while ((i < t) && (j < u)){ if (a[i].val >= a[j].val){ work[k] = a[i]; i = i + 1; k = k + 1; } else { work[k] = a[j]; j = j + 1; k = k + 1; } } } if(i < t ){ while (i < t ) { work[k] = a[i]; i = i + 1; k = k + 1; } } if(j < u){ while (j < u ) { work[k] = a[j]; j = j + 1; k = k + 1; } } i = s; k=k-1; for( j = 1; j<= k; j++) { a[i] = work[j]; i = i + 1; } } /* ! this subroutine takes two sorted lists of type(THEFIT) and merges them ! input d1(1:n) , d2(1:m) ! output out(1:n+m) */ void merge2(THEFIT *d1,int n,THEFIT *d2,int m,THEFIT *out) { int i,j,k; i=1; j=1; d1--; d2--; out--; for( k=1; k<=n+m;k++) { if(i > n){ out[k]=d2[j]; j=j+1; } else if(j > m){ out[k]=d1[i]; i=i+1; } else { if(d1[i].val > d2[j].val){ out[k]=d1[i]; i=i+1; } else { out[k]=d2[j]; j=j+1; } } } } THEFIT *vector(int nl, int nh) { THEFIT *v; v=(THEFIT *)malloc((unsigned) (nh-nl+1)*sizeof(THEFIT)); if (!v) { printf("allocation failure in ivector()\n"); exit(1); } return v-nl; } void free_vector(THEFIT *v, int nl) { free((char*) (v+nl)); }
utils.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /*! * Copyright (c) 2015 by Contributors * \file utils.h * \brief Basic utilility functions. */ #ifndef MXNET_COMMON_UTILS_H_ #define MXNET_COMMON_UTILS_H_ #include <dmlc/logging.h> #include <dmlc/omp.h> #include <nnvm/graph.h> #include <nnvm/node.h> #include <mxnet/engine.h> #include <mxnet/ndarray.h> #include <mxnet/op_attr_types.h> #include <mxnet/graph_attr_types.h> #include <nnvm/graph_attr_types.h> #include <memory> #include <vector> #include <type_traits> #include <utility> #include <random> #include <string> #include <thread> #include <algorithm> #include <functional> #include <limits> #include "../operator/mxnet_op.h" #if MXNET_USE_MKLDNN == 1 #include "../operator/nn/mkldnn/mkldnn_base-inl.h" #endif #if defined(_WIN32) || defined(_WIN64) || defined(__WINDOWS__) #include <windows.h> #else #include <unistd.h> #endif namespace mxnet { namespace common { #if defined(_WIN32) || defined(_WIN64) || defined(__WINDOWS__) inline size_t current_process_id() { return ::GetCurrentProcessId(); } #else inline size_t current_process_id() { return getpid(); } #endif /*! * \brief IndPtr should be non-negative, in non-decreasing order, start with 0 * and end with value equal with size of indices. */ struct csr_indptr_check { template<typename DType, typename IType> MSHADOW_XINLINE static void Map(int i, DType* out, const IType* indptr, const nnvm::dim_t end, const nnvm::dim_t idx_size) { if (indptr[i+1] < 0 || indptr[i+1] < indptr[i] || (i == 0 && indptr[i] != 0) || (i == end - 1 && indptr[end] != idx_size)) *out = kCSRIndPtrErr; } }; /*! * \brief Indices should be non-negative, less than the number of columns * and in ascending order per row. */ struct csr_idx_check { template<typename DType, typename IType, typename RType> MSHADOW_XINLINE static void Map(int i, DType* out, const IType* idx, const RType* indptr, const nnvm::dim_t ncols) { for (RType j = indptr[i]; j < indptr[i+1]; j++) { if (idx[j] >= ncols || idx[j] < 0 || (j < indptr[i+1] - 1 && idx[j] >= idx[j+1])) { *out = kCSRIdxErr; break; } } } }; /*! * \brief Indices of RSPNDArray should be non-negative, * less than the size of first dimension and in ascending order */ struct rsp_idx_check { template<typename DType, typename IType> MSHADOW_XINLINE static void Map(int i, DType* out, const IType* idx, const nnvm::dim_t end, const nnvm::dim_t nrows) { if ((i < end && idx[i+1] <= idx[i]) || idx[i] < 0 || idx[i] >= nrows) *out = kRSPIdxErr; } }; template<typename xpu> void CheckFormatWrapper(const RunContext &rctx, const NDArray &input, const TBlob &err_cpu, const bool full_check); /*! * \brief Check the validity of CSRNDArray. * \param rctx Execution context. * \param input Input NDArray of CSRStorage. * \param err_cpu Error number on cpu. * \param full_check If true, rigorous check, O(N) operations, * otherwise basic check, O(1) operations. */ template<typename xpu> void CheckFormatCSRImpl(const RunContext &rctx, const NDArray &input, const TBlob &err_cpu, const bool full_check) { using namespace op::mxnet_op; CHECK_EQ(input.storage_type(), kCSRStorage) << "CheckFormatCSRImpl is for CSRNDArray"; const mxnet::TShape shape = input.shape(); const mxnet::TShape idx_shape = input.aux_shape(csr::kIdx); const mxnet::TShape indptr_shape = input.aux_shape(csr::kIndPtr); const mxnet::TShape storage_shape = input.storage_shape(); if ((shape.ndim() != 2) || (idx_shape.ndim() != 1 || indptr_shape.ndim() != 1 || storage_shape.ndim() != 1) || (indptr_shape[0] != shape[0] + 1) || (idx_shape[0] != storage_shape[0])) { MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, { DType* err = err_cpu.dptr<DType>(); *err = kCSRShapeErr; }); return; } if (full_check) { MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, { MSHADOW_IDX_TYPE_SWITCH(input.aux_type(csr::kIndPtr), RType, { MSHADOW_IDX_TYPE_SWITCH(input.aux_type(csr::kIdx), IType, { mshadow::Stream<xpu> *s = rctx.get_stream<xpu>(); NDArray ret_xpu = NDArray(mshadow::Shape1(1), rctx.get_ctx(), false, err_cpu.type_flag_); TBlob val_xpu = ret_xpu.data(); Kernel<set_to_int<kNormalErr>, xpu>::Launch(s, val_xpu.Size(), val_xpu.dptr<DType>()); Kernel<csr_indptr_check, xpu>::Launch(s, indptr_shape[0] - 1, val_xpu.dptr<DType>(), input.aux_data(csr::kIndPtr).dptr<RType>(), indptr_shape[0] - 1, idx_shape[0]); // no need to check indices if indices are empty if (idx_shape[0] != 0) { Kernel<csr_idx_check, xpu>::Launch(s, indptr_shape[0] - 1, val_xpu.dptr<DType>(), input.aux_data(csr::kIdx).dptr<IType>(), input.aux_data(csr::kIndPtr).dptr<RType>(), shape[1]); } mshadow::Copy(err_cpu.get<cpu, 1, DType>(), val_xpu.get<xpu, 1, DType>(s), s); }); }); }); } } /*! * \brief Check the validity of RowSparseNDArray. * \param rctx Execution context. * \param input Input NDArray of RowSparseStorage. * \param err_cpu Error number on cpu. * \param full_check If true, rigorous check, O(N) operations, * otherwise basic check, O(1) operations. */ template<typename xpu> void CheckFormatRSPImpl(const RunContext &rctx, const NDArray &input, const TBlob &err_cpu, const bool full_check) { using namespace op::mxnet_op; CHECK_EQ(input.storage_type(), kRowSparseStorage) << "CheckFormatRSPImpl is for RSPNDArray"; const mxnet::TShape idx_shape = input.aux_shape(rowsparse::kIdx); if (idx_shape[0] != input.storage_shape()[0]) { MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, { DType* err = err_cpu.dptr<DType>(); *err = kRSPShapeErr; }); return; } if (idx_shape[0] == 0) { return; } if (full_check) { MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, { MSHADOW_IDX_TYPE_SWITCH(input.aux_type(rowsparse::kIdx), IType, { mshadow::Stream<xpu> *s = rctx.get_stream<xpu>(); NDArray ret_xpu = NDArray(mshadow::Shape1(1), rctx.get_ctx(), false, err_cpu.type_flag_); TBlob val_xpu = ret_xpu.data(); Kernel<set_to_int<kNormalErr>, xpu>::Launch(s, val_xpu.Size(), val_xpu.dptr<DType>()); Kernel<rsp_idx_check, xpu>::Launch(s, idx_shape[0], val_xpu.dptr<DType>(), input.aux_data(rowsparse::kIdx).dptr<IType>(), idx_shape[0] - 1, input.shape()[0]); mshadow::Copy(err_cpu.get<cpu, 1, DType>(), val_xpu.get<xpu, 1, DType>(s), s); }); }); } } template<typename xpu> void CheckFormatImpl(const RunContext &rctx, const NDArray &input, const TBlob &err_cpu, const bool full_check) { int stype = input.storage_type(); if (stype == kCSRStorage) { CheckFormatCSRImpl<xpu>(rctx, input, err_cpu, full_check); } else if (stype == kRowSparseStorage) { CheckFormatRSPImpl<xpu>(rctx, input, err_cpu, full_check); } else if (stype == kDefaultStorage) { // no-op for default storage } else { LOG(FATAL) << "Unknown storage type " << stype; } } /*! \brief Pick rows specified by user input index array from a row sparse ndarray * and save them in the output sparse ndarray. */ template<typename xpu> void SparseRetainOpForwardRspWrapper(mshadow::Stream<xpu> *s, const NDArray& input_nd, const TBlob& idx_data, const OpReqType req, NDArray* output_nd); /* \brief Casts tensor storage type to the new type. */ template<typename xpu> void CastStorageDispatch(const OpContext& ctx, const NDArray& input, const NDArray& output); /*! \brief returns true if all storage types in `vstorage` are the same as target `stype`. * false is returned for empty inputs. */ inline bool ContainsOnlyStorage(const StorageTypeVector& vstorage, const NDArrayStorageType stype) { if (!vstorage.empty()) { for (const auto& i : vstorage) { if (i != stype) return false; } return true; } return false; } /*! \brief returns true if all storage types in `vstorage` are the same as target `stype1` * or `stype2'. Sets boolean if both found. * false is returned for empty inputs. */ inline bool ContainsOnlyStorage(const StorageTypeVector& vstorage, const NDArrayStorageType stype1, const NDArrayStorageType stype2, bool *has_both) { if (has_both) { *has_both = false; } if (!vstorage.empty()) { uint8_t has = 0; for (const auto i : vstorage) { if (i == stype1) { has |= 1; } else if (i == stype2) { has |= 2; } else { return false; } } if (has_both) { *has_both = has == 3; } return true; } return false; } /*! \brief returns true if the storage types of arrays in `ndarrays` * are the same as target `stype`. false is returned for empty inputs. */ inline bool ContainsOnlyStorage(const std::vector<NDArray>& ndarrays, const NDArrayStorageType stype) { if (!ndarrays.empty()) { for (const auto& nd : ndarrays) { if (nd.storage_type() != stype) { return false; } } return true; } return false; } /*! \brief returns true if the storage types of arrays in `ndarrays` * are the same as targets `stype1` or `stype2`. false is returned for empty inputs. */ inline bool ContainsOnlyStorage(const std::vector<NDArray>& ndarrays, const NDArrayStorageType stype1, const NDArrayStorageType stype2, bool *has_both) { if (has_both) { *has_both = false; } if (!ndarrays.empty()) { uint8_t has = 0; for (const auto& nd : ndarrays) { const NDArrayStorageType stype = nd.storage_type(); if (stype == stype1) { has |= 1; } else if (stype == stype2) { has |= 2; } else { return false; } } if (has_both) { *has_both = has == 3; } return true; } return false; } /*! \brief returns true if storage type of any array in `ndarrays` * is the same as the target `stype`. false is returned for empty inputs. */ inline bool ContainsStorageType(const std::vector<NDArray>& ndarrays, const NDArrayStorageType stype) { if (!ndarrays.empty()) { for (const auto& nd : ndarrays) { if (nd.storage_type() == stype) { return true; } } } return false; } /*! \brief returns true if any storage type `ndstype` in `ndstypes` * is the same as the target `stype`. false is returned for empty inputs. */ inline bool ContainsStorageType(const std::vector<int>& ndstypes, const NDArrayStorageType stype) { if (!ndstypes.empty()) { for (const auto& ndstype : ndstypes) { if (ndstype == stype) { return true; } } } return false; } /*! \brief get string representation of dispatch_mode */ inline std::string dispatch_mode_string(const DispatchMode x) { switch (x) { case DispatchMode::kFCompute: return "fcompute"; case DispatchMode::kFComputeEx: return "fcompute_ex"; case DispatchMode::kFComputeFallback: return "fcompute_fallback"; case DispatchMode::kVariable: return "variable"; case DispatchMode::kUndefined: return "undefined"; } return "unknown"; } /*! \brief get string representation of storage_type */ inline std::string stype_string(const int x) { switch (x) { case kDefaultStorage: return "default"; case kCSRStorage: return "csr"; case kRowSparseStorage: return "row_sparse"; } return "unknown"; } /*! \brief get string representation of device type */ inline std::string dev_type_string(const int dev_type) { switch (dev_type) { case Context::kCPU: return "cpu"; case Context::kGPU: return "gpu"; case Context::kCPUPinned: return "cpu_pinned"; case Context::kCPUShared: return "cpu_shared"; } return "unknown"; } /*! \brief get string representation of the operator stypes */ inline std::string operator_stype_string(const nnvm::NodeAttrs& attrs, const int dev_mask, const std::vector<int>& in_attrs, const std::vector<int>& out_attrs) { std::ostringstream os; os << "operator = " << attrs.op->name << "\ninput storage types = ["; for (const int attr : in_attrs) { os << stype_string(attr) << ", "; } os << "]\n" << "output storage types = ["; for (const int attr : out_attrs) { os << stype_string(attr) << ", "; } os << "]\n" << "params = {"; for (auto kv : attrs.dict) { os << "\"" << kv.first << "\" : " << kv.second << ", "; } os << "}\n" << "context.dev_mask = " << dev_type_string(dev_mask); return os.str(); } /*! \brief get string representation of the operator */ inline std::string operator_string(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<NDArray>& inputs, const std::vector<OpReqType>& req, const std::vector<NDArray>& outputs) { std::string result = ""; std::vector<int> in_stypes; std::vector<int> out_stypes; in_stypes.reserve(inputs.size()); out_stypes.reserve(outputs.size()); auto xform = [](const NDArray arr) -> int { return arr.storage_type(); }; std::transform(inputs.begin(), inputs.end(), std::back_inserter(in_stypes), xform); std::transform(outputs.begin(), outputs.end(), std::back_inserter(out_stypes), xform); result += operator_stype_string(attrs, ctx.run_ctx.ctx.dev_mask(), in_stypes, out_stypes); return result; } /*! \brief log message once. Intended for storage fallback warning messages. */ inline void LogOnce(const std::string& message) { typedef dmlc::ThreadLocalStore<std::unordered_set<std::string>> LogStore; auto log_store = LogStore::Get(); if (log_store->find(message) == log_store->end()) { LOG(INFO) << message; log_store->insert(message); } } /*! \brief log storage fallback event */ inline void LogStorageFallback(const nnvm::NodeAttrs& attrs, const int dev_mask, const std::vector<int>* in_attrs, const std::vector<int>* out_attrs) { static bool log = dmlc::GetEnv("MXNET_STORAGE_FALLBACK_LOG_VERBOSE", true); if (!log) return; const std::string op_str = operator_stype_string(attrs, dev_mask, *in_attrs, *out_attrs); std::ostringstream os; const char* warning = "\nThe operator with default storage type will be dispatched " "for execution. You're seeing this warning message because the operator above is unable " "to process the given ndarrays with specified storage types, context and parameter. " "Temporary dense ndarrays are generated in order to execute the operator. " "This does not affect the correctness of the programme. " "You can set environment variable MXNET_STORAGE_FALLBACK_LOG_VERBOSE to " "0 to suppress this warning."; os << "\nStorage type fallback detected:\n" << op_str << warning; LogOnce(os.str()); #if MXNET_USE_MKLDNN == 1 if (!MKLDNNEnvSet()) common::LogOnce("MXNET_MKLDNN_ENABLED flag is off. " "You can re-enable by setting MXNET_MKLDNN_ENABLED=1"); if (GetMKLDNNCacheSize() != -1) common::LogOnce("MXNET_MKLDNN_CACHE_NUM is set." "Should only be set if " "your model has variable input shapes, " "as cache size may grow unbounded"); #endif } // heuristic to dermine number of threads per GPU inline int GetNumThreadsPerGPU() { // This is resource efficient option. return dmlc::GetEnv("MXNET_GPU_WORKER_NTHREADS", 2); } // heuristic to get number of matching colors. // this decides how much parallelism we can get in each GPU. inline int GetExecNumMatchColor() { // This is resource efficient option. int num_match_color = dmlc::GetEnv("MXNET_EXEC_NUM_TEMP", 1); return std::min(num_match_color, GetNumThreadsPerGPU()); } template<typename T, typename V> V ParallelAccumulate(const T* a, const int n, V start) { V sum = start; #pragma omp parallel for reduction(+:sum) for (int i = 0; i < n; ++i) { sum += a[i]; } return sum; } /*! * \brief * Helper function for ParallelSort. * DO NOT call this function directly. * Use the interface ParallelSort instead. * Ref: https://github.com/dmlc/difacto/blob/master/src/common/parallel_sort.h */ template<typename RandomIt, typename Compare> void ParallelSortHelper(RandomIt first, size_t len, size_t grainsize, const Compare& comp) { if (len < grainsize) { std::sort(first, first+len, comp); } else { std::thread thr(ParallelSortHelper<RandomIt, Compare>, first, len/2, grainsize, comp); ParallelSortHelper(first+len/2, len - len/2, grainsize, comp); thr.join(); std::inplace_merge(first, first+len/2, first+len, comp); } } /*! * \brief * Sort the elements in the range [first, last) into the ascending order defined by * the comparator comp. * If the length of the range [first, last) is greater than a certain threshold, * the range will be recursively divided into two and assign two threads * to sort each half range. * Ref: https://github.com/dmlc/difacto/blob/master/src/common/parallel_sort.h */ template<typename RandomIt, typename Compare> void ParallelSort(RandomIt first, RandomIt last, size_t num_threads, Compare comp) { const auto num = std::distance(first, last); size_t grainsize = std::max(num / num_threads + 5, static_cast<size_t>(1024*16)); ParallelSortHelper(first, num, grainsize, comp); } /*! * \brief * Sort the elements in the range [first, last) into ascending order. * The elements are compared using the default < operator. * If the length of the range [first, last) is greater than a certain threshold, * the range will be recursively divided into two and assign two threads * to sort each half range. * Ref: https://github.com/dmlc/difacto/blob/master/src/common/parallel_sort.h */ template<typename RandomIt> void ParallelSort(RandomIt first, RandomIt last, size_t num_threads) { ParallelSort(first, last, num_threads, std::less<typename std::iterator_traits<RandomIt>::value_type>()); } /*! * \brief Random Engine */ typedef std::mt19937 RANDOM_ENGINE; /*! * \brief Helper functions. */ namespace helper { /*! * \brief Helper for non-array type `T`. */ template <class T> struct UniqueIf { /*! * \brief Type of `T`. */ using SingleObject = std::unique_ptr<T>; }; /*! * \brief Helper for an array of unknown bound `T`. */ template <class T> struct UniqueIf<T[]> { /*! * \brief Type of `T`. */ using UnknownBound = std::unique_ptr<T[]>; }; /*! * \brief Helper for an array of known bound `T`. */ template <class T, size_t kSize> struct UniqueIf<T[kSize]> { /*! * \brief Type of `T`. */ using KnownBound = void; }; } // namespace helper /*! * \brief Constructs an object of type `T` and wraps it in a * `std``::``unique_ptr`. * \param args List of arguments with which an instance of `T` will be * constructed. * \return `std``::``unique_ptr` of an instance of type `T`. * * Constructs a non-array type `T`. The arguments `args` are passed to the * constructor of `T`. The function does not participate in the overload * resolution if `T` is an array type. */ template <class T, class... Args> typename helper::UniqueIf<T>::SingleObject MakeUnique(Args&&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } /*! * \brief Constructs an object of type `T` and wraps it in a * `std``::``unique_ptr`. * \param n The size of the array to construct. * \return `std``::``unique_ptr` of an instance of type `T`. * * Constructs an array of unknown bound `T`. The function does not participate * in the overload resolution unless `T` is an array of unknown bound. */ template <class T> typename helper::UniqueIf<T>::UnknownBound MakeUnique(size_t n) { using U = typename std::remove_extent<T>::type; return std::unique_ptr<T>(new U[n]{}); } /*! * \brief Constructs an object of type `T` and wraps it in a * `std``::``unique_ptr`. * \param args List of arguments with which an instance of `T` will be * constructed. * * Constructs an arrays of known bound is disallowed. */ template <class T, class... Args> typename helper::UniqueIf<T>::KnownBound MakeUnique(Args&&... args) = delete; template<typename FCompType> FCompType GetFCompute(const nnvm::Op* op, const std::string& name, const Context& ctx) { static auto& fcompute_cpu = nnvm::Op::GetAttr<FCompType>(name + "<cpu>"); static auto& fcompute_gpu = nnvm::Op::GetAttr<FCompType>(name + "<gpu>"); if (ctx.dev_mask() == cpu::kDevMask) { return fcompute_cpu.get(op, nullptr); } else if (ctx.dev_mask() == gpu::kDevMask) { return fcompute_gpu.get(op, nullptr); } else { LOG(FATAL) << "Unknown device mask " << ctx.dev_mask(); return nullptr; } } /*! * \brief Return the max integer value representable in the type `T` without loss of precision. */ template <typename T> constexpr size_t MaxIntegerValue() { return std::is_integral<T>::value ? std::numeric_limits<T>::max(): size_t(2) << (std::numeric_limits<T>::digits - 1); } template <> constexpr size_t MaxIntegerValue<mshadow::half::half_t>() { return size_t(2) << 10; } MSHADOW_XINLINE int ilog2ul(size_t a) { int k = 1; while (a >>= 1) ++k; return k; } MSHADOW_XINLINE int ilog2ui(unsigned int a) { int k = 1; while (a >>= 1) ++k; return k; } /*! * \brief Return an NDArray of all zeros. */ inline NDArray InitZeros(const NDArrayStorageType stype, const mxnet::TShape &shape, const Context &ctx, const int dtype) { // NDArray with default storage if (stype == kDefaultStorage) { NDArray ret(shape, ctx, false, dtype); ret = 0; return ret; } // NDArray with non-default storage. Storage allocation is always delayed. return NDArray(stype, shape, ctx, true, dtype); } /*! * \brief Helper to add a NDArray of zeros to a std::vector. */ inline void EmplaceBackZeros(const NDArrayStorageType stype, const mxnet::TShape &shape, const Context &ctx, const int dtype, std::vector<NDArray> *vec) { // NDArray with default storage if (stype == kDefaultStorage) { vec->emplace_back(shape, ctx, false, dtype); vec->back() = 0; } else { // NDArray with non-default storage. Storage allocation is always delayed. vec->emplace_back(stype, shape, ctx, true, dtype); } } /*! * \brief parallelize copy by OpenMP. */ template<typename DType> inline void ParallelCopy(DType* dst, const DType* src, index_t size) { static index_t copy_block_size = dmlc::GetEnv("MXNET_CPU_PARALLEL_COPY_SIZE", 200000); if (size >= copy_block_size) { #pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount()) for (index_t i = 0; i < size; ++i) { dst[i] = src[i]; } } else { std::memcpy(dst, src, sizeof(DType) * size); } } /*! * \brief If numpy compatibility is turned off (default), the shapes passed in * by users follow the legacy shape definition: * 1. 0 ndim means the shape is completely unknown. * 2. 0 dim size means the dim size is unknown. * We need to convert those shapes to use the numpy shape definition: * 1. 0 ndim means it's a scalar tensor. * 2. -1 ndim means the shape is unknown. * 3. 0 dim size means no elements in that dimension. * 4. -1 dim size means the dimension's size is unknown. * so that operator's infer shape function can work in backend. * \param shape to be converted. * Note: It is possible that the shape to be converted is already * numpy compatible. For example, when a subgraph operator's infer * shape function is called from the infer shape pass of the whole * graph, its input/output shapes have been converted to numpy * compatible shapes. */ inline void ConvertToNumpyShape(mxnet::TShape* shape) { if (shape->ndim() == 0) { // legacy shape ndim = 0 means unknown *shape = mxnet::TShape(); // unknown shape ndim = -1 } else { for (int j = 0; j < shape->ndim(); ++j) { if ((*shape)[j] == 0) { // legacy shape dim_size = 0 means unknown (*shape)[j] = -1; // unknown dim size = -1 } } } } inline void ConvertToNumpyShape(mxnet::ShapeVector* shapes) { for (size_t i = 0; i < shapes->size(); ++i) { ConvertToNumpyShape(&(shapes->at(i))); } } /*! * \brief This is function is used to convert shapes returned by * the infer shape functions/pass to the legacy shape definition. */ inline void ConvertToLegacyShape(mxnet::TShape* shape) { if (!mxnet::ndim_is_known(*shape)) { *shape = mxnet::TShape(0, -1); } else { for (int j = 0; j < shape->ndim(); ++j) { if (!mxnet::dim_size_is_known(*shape, j)) { (*shape)[j] = 0; } } } } inline void ConvertToLegacyShape(mxnet::ShapeVector* shapes) { for (size_t i = 0; i < shapes->size(); ++i) { ConvertToLegacyShape(&(shapes->at(i))); } } void ExecuteMonInputCallback( const nnvm::IndexedGraph &idx, const std::vector<NDArray *> &state_arrays, size_t nid, const std::function<void(const char *, const char *, void *)> &monitor_callback); void ExecuteMonOutputCallback( const nnvm::IndexedGraph &idx, const std::vector<NDArray *> &state_arrays, size_t nid, const std::function<void(const char *, const char *, void *)> &monitor_callback); /*! * \brief This is function can return the output names of a NodeEntry. */ static inline std::string GetOutputName(const nnvm::NodeEntry& e) { nnvm::Symbol sym; sym.outputs.push_back(e); return sym.ListOutputNames()[0]; } inline mxnet::TShape CanonicalizeAxes(const mxnet::TShape& src) { // convert negative axes to positive values const int ndim = src.ndim(); mxnet::TShape axes = src; for (int i = 0; i < ndim; ++i) { if (axes[i] < 0) { axes[i] += ndim; } CHECK(axes[i] >= 0 && axes[i] < ndim) << "axes[" << i << "]=" << axes[i] << " exceeds the range [" << 0 << ", " << ndim << ")"; } return axes; } inline bool is_float(const int dtype) { return dtype == mshadow::kFloat32 || dtype == mshadow::kFloat64 || dtype == mshadow::kFloat16; } inline int more_precise_type(const int type1, const int type2) { if (type1 == type2) return type1; if (is_float(type1) && is_float(type2)) { if (type1 == mshadow::kFloat64 || type2 == mshadow::kFloat64) { return mshadow::kFloat64; } if (type1 == mshadow::kFloat32 || type2 == mshadow::kFloat32) { return mshadow::kFloat32; } return mshadow::kFloat16; } else if (is_float(type1) || is_float(type2)) { return is_float(type1) ? type1 : type2; } if (type1 == mshadow::kInt64 || type2 == mshadow::kInt64) { return mshadow::kInt64; } if (type1 == mshadow::kInt32 || type2 == mshadow::kInt32) { return mshadow::kInt32; } CHECK(!((type1 == mshadow::kUint8 && type2 == mshadow::kInt8) || (type1 == mshadow::kInt8 && type2 == mshadow::kUint8))) << "1 is UInt8 and 1 is Int8 should not get here"; if (type1 == mshadow::kUint8 || type2 == mshadow::kUint8) { return mshadow::kUint8; } return mshadow::kInt8; } inline int np_binary_out_type(const int type1, const int type2) { if ((type1 == mshadow::kUint8 && type2 == mshadow::kInt8) || (type1 == mshadow::kInt8 && type2 == mshadow::kUint8)) { return mshadow::kInt32; } return more_precise_type(type1, type2); } } // namespace common } // namespace mxnet #endif // MXNET_COMMON_UTILS_H_
GB_unop__lnot_int32_int32.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__lnot_int32_int32) // op(A') function: GB (_unop_tran__lnot_int32_int32) // C type: int32_t // A type: int32_t // cast: int32_t cij = aij // unaryop: cij = !(aij != 0) #define GB_ATYPE \ int32_t #define GB_CTYPE \ int32_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 != 0) ; // casting #define GB_CAST(z, aij) \ int32_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ int32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int32_t z = aij ; \ Cx [pC] = !(z != 0) ; \ } // 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_LNOT || GxB_NO_INT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__lnot_int32_int32) ( int32_t *Cx, // Cx and Ax may be aliased const int32_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 (int32_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int32_t aij = Ax [p] ; int32_t z = aij ; Cx [p] = !(z != 0) ; } #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 ; int32_t aij = Ax [p] ; int32_t z = aij ; Cx [p] = !(z != 0) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__lnot_int32_int32) ( 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
ast-dump-openmp-teams-distribute-simd.c
// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fopenmp -ast-dump %s | FileCheck --match-full-lines -implicit-check-not=openmp_structured_block %s void test_one(int x) { #pragma omp target #pragma omp teams distribute simd for (int i = 0; i < x; i++) ; } void test_two(int x, int y) { #pragma omp target #pragma omp teams distribute simd for (int i = 0; i < x; i++) for (int i = 0; i < y; i++) ; } void test_three(int x, int y) { #pragma omp target #pragma omp teams distribute simd collapse(1) for (int i = 0; i < x; i++) for (int i = 0; i < y; i++) ; } void test_four(int x, int y) { #pragma omp target #pragma omp teams distribute simd collapse(2) for (int i = 0; i < x; i++) for (int i = 0; i < y; i++) ; } void test_five(int x, int y, int z) { #pragma omp target #pragma omp teams distribute simd collapse(2) for (int i = 0; i < x; i++) for (int i = 0; i < y; i++) for (int i = 0; i < z; i++) ; } // CHECK: TranslationUnitDecl {{.*}} <<invalid sloc>> <invalid sloc> // CHECK: |-FunctionDecl {{.*}} <{{.*}}ast-dump-openmp-teams-distribute-simd.c:3:1, line:8:1> line:3:6 test_one 'void (int)' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:15, col:19> col:19 used x 'int' // CHECK-NEXT: | `-CompoundStmt {{.*}} <col:22, line:8:1> // CHECK-NEXT: | `-OMPTargetDirective {{.*}} <line:4:9, col:19> // CHECK-NEXT: | |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit> // CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:6:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | `-CapturedStmt {{.*}} <line:5:9, col:34> // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-CapturedStmt {{.*}} <col:9, col:34> // CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-OMPTeamsDistributeSimdDirective {{.*}} <col:9, col:34> openmp_structured_block // CHECK-NEXT: | | | | | `-CapturedStmt {{.*}} <line:6:3, line:7:5> // CHECK-NEXT: | | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | | | |-ForStmt {{.*}} <line:6:3, line:7:5> // CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:6:8, col:17> // CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-NullStmt {{.*}} <line:7:5> openmp_structured_block // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <line:5:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:5:9) *const restrict' // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <line:6:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:4:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:4:9) *const restrict' // CHECK-NEXT: | | | | |-RecordDecl {{.*}} <line:5:9> col:9 implicit struct definition // CHECK-NEXT: | | | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | | | `-FieldDecl {{.*}} <line:6:23> col:23 implicit 'int &' // CHECK-NEXT: | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | | |-ForStmt {{.*}} <col:3, line:7:5> // CHECK-NEXT: | | | | | | |-DeclStmt {{.*}} <line:6:8, col:17> // CHECK-NEXT: | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-NullStmt {{.*}} <line:7:5> openmp_structured_block // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <line:5:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:5:9) *const restrict' // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <line:6:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | |-OMPCapturedExprDecl {{.*}} <col:23> col:23 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | `-OMPCapturedExprDecl {{.*}} <col:3, <invalid sloc>> col:3 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | | `-BinaryOperator {{.*}} <col:3, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:3, col:26> 'int' '/' // CHECK-NEXT: | | | | | |-ParenExpr {{.*}} <col:3> 'int' // CHECK-NEXT: | | | | | | `-BinaryOperator {{.*}} <col:23, col:26> 'int' '+' // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:23, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:23, col:16> 'int' '-' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue OMPCapturedExpr {{.*}} '.capture_expr.' 'int' // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:4:9> col:9 implicit .global_tid. 'const int' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .part_id. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .privates. 'void *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .task_t. 'void *const' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:4:9) *const restrict' // CHECK-NEXT: | | |-RecordDecl {{.*}} <col:9> col:9 implicit struct definition // CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:6:23> col:23 implicit 'int' // CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-OMPTeamsDistributeSimdDirective {{.*}} <line:5:9, col:34> openmp_structured_block // CHECK-NEXT: | | | `-CapturedStmt {{.*}} <line:6:3, line:7:5> // CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:6:3, line:7:5> // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:6:8, col:17> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:7:5> openmp_structured_block // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:5:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:5:9) *const restrict' // CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:6:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:4:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:4:9) *const restrict' // CHECK-NEXT: | | |-RecordDecl {{.*}} <line:5:9> col:9 implicit struct definition // CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:6:23> col:23 implicit 'int &' // CHECK-NEXT: | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | |-ForStmt {{.*}} <col:3, line:7:5> // CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:6:8, col:17> // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-NullStmt {{.*}} <line:7:5> openmp_structured_block // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <line:5:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:5:9) *const restrict' // CHECK-NEXT: | | | `-VarDecl {{.*}} <line:6:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | |-OMPCapturedExprDecl {{.*}} <col:23> col:23 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | `-OMPCapturedExprDecl {{.*}} <col:3, <invalid sloc>> col:3 implicit used .capture_expr. 'int' // CHECK-NEXT: | | `-BinaryOperator {{.*}} <col:3, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | |-BinaryOperator {{.*}} <col:3, col:26> 'int' '/' // CHECK-NEXT: | | | |-ParenExpr {{.*}} <col:3> 'int' // CHECK-NEXT: | | | | `-BinaryOperator {{.*}} <col:23, col:26> 'int' '+' // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:23, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:23, col:16> 'int' '-' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue OMPCapturedExpr {{.*}} '.capture_expr.' 'int' // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: |-FunctionDecl {{.*}} <line:10:1, line:16:1> line:10:6 test_two 'void (int, int)' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:15, col:19> col:19 used x 'int' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:22, col:26> col:26 used y 'int' // CHECK-NEXT: | `-CompoundStmt {{.*}} <col:29, line:16:1> // CHECK-NEXT: | `-OMPTargetDirective {{.*}} <line:11:9, col:19> // CHECK-NEXT: | |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit> // CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:13:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:14:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | `-CapturedStmt {{.*}} <line:12:9, col:34> // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-CapturedStmt {{.*}} <col:9, col:34> // CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-OMPTeamsDistributeSimdDirective {{.*}} <col:9, col:34> openmp_structured_block // CHECK-NEXT: | | | | | `-CapturedStmt {{.*}} <line:13:3, line:15:7> // CHECK-NEXT: | | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | | | |-ForStmt {{.*}} <line:13:3, line:15:7> // CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:13:8, col:17> // CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ForStmt {{.*}} <line:14:5, line:15:7> openmp_structured_block // CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:14:10, col:19> // CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-NullStmt {{.*}} <line:15:7> // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <line:12:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:12:9) *const restrict' // CHECK-NEXT: | | | | | | |-VarDecl {{.*}} <line:13:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <line:14:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | |-DeclRefExpr {{.*}} <line:13:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <line:14:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:11:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:11:9) *const restrict' // CHECK-NEXT: | | | | |-RecordDecl {{.*}} <line:12:9> col:9 implicit struct definition // CHECK-NEXT: | | | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | | | |-FieldDecl {{.*}} <line:13:23> col:23 implicit 'int &' // CHECK-NEXT: | | | | | `-FieldDecl {{.*}} <line:14:25> col:25 implicit 'int &' // CHECK-NEXT: | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | | |-ForStmt {{.*}} <line:13:3, line:15:7> // CHECK-NEXT: | | | | | | |-DeclStmt {{.*}} <line:13:8, col:17> // CHECK-NEXT: | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ForStmt {{.*}} <line:14:5, line:15:7> openmp_structured_block // CHECK-NEXT: | | | | | | |-DeclStmt {{.*}} <line:14:10, col:19> // CHECK-NEXT: | | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-NullStmt {{.*}} <line:15:7> // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <line:12:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:12:9) *const restrict' // CHECK-NEXT: | | | | | |-VarDecl {{.*}} <line:13:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <line:14:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | |-OMPCapturedExprDecl {{.*}} <line:13:23> col:23 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | `-OMPCapturedExprDecl {{.*}} <col:3, <invalid sloc>> col:3 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | | `-BinaryOperator {{.*}} <col:3, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:3, col:26> 'int' '/' // CHECK-NEXT: | | | | | |-ParenExpr {{.*}} <col:3> 'int' // CHECK-NEXT: | | | | | | `-BinaryOperator {{.*}} <col:23, col:26> 'int' '+' // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:23, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:23, col:16> 'int' '-' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue OMPCapturedExpr {{.*}} '.capture_expr.' 'int' // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:14:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:11:9> col:9 implicit .global_tid. 'const int' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .part_id. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .privates. 'void *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .task_t. 'void *const' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:11:9) *const restrict' // CHECK-NEXT: | | |-RecordDecl {{.*}} <col:9> col:9 implicit struct definition // CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:13:23> col:23 implicit 'int' // CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:14:25> col:25 implicit 'int' // CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-OMPTeamsDistributeSimdDirective {{.*}} <line:12:9, col:34> openmp_structured_block // CHECK-NEXT: | | | `-CapturedStmt {{.*}} <line:13:3, line:15:7> // CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:13:3, line:15:7> // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:13:8, col:17> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:14:5, line:15:7> openmp_structured_block // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:14:10, col:19> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:15:7> // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:12:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:12:9) *const restrict' // CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:13:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:14:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <line:13:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:14:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:11:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:11:9) *const restrict' // CHECK-NEXT: | | |-RecordDecl {{.*}} <line:12:9> col:9 implicit struct definition // CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:13:23> col:23 implicit 'int &' // CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:14:25> col:25 implicit 'int &' // CHECK-NEXT: | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | |-ForStmt {{.*}} <line:13:3, line:15:7> // CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:13:8, col:17> // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ForStmt {{.*}} <line:14:5, line:15:7> openmp_structured_block // CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:14:10, col:19> // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-NullStmt {{.*}} <line:15:7> // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <line:12:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:12:9) *const restrict' // CHECK-NEXT: | | | |-VarDecl {{.*}} <line:13:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | `-VarDecl {{.*}} <line:14:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | |-OMPCapturedExprDecl {{.*}} <line:13:23> col:23 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | `-OMPCapturedExprDecl {{.*}} <col:3, <invalid sloc>> col:3 implicit used .capture_expr. 'int' // CHECK-NEXT: | | `-BinaryOperator {{.*}} <col:3, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | |-BinaryOperator {{.*}} <col:3, col:26> 'int' '/' // CHECK-NEXT: | | | |-ParenExpr {{.*}} <col:3> 'int' // CHECK-NEXT: | | | | `-BinaryOperator {{.*}} <col:23, col:26> 'int' '+' // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:23, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:23, col:16> 'int' '-' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue OMPCapturedExpr {{.*}} '.capture_expr.' 'int' // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | |-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:14:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: |-FunctionDecl {{.*}} <line:18:1, line:24:1> line:18:6 test_three 'void (int, int)' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:17, col:21> col:21 used x 'int' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:24, col:28> col:28 used y 'int' // CHECK-NEXT: | `-CompoundStmt {{.*}} <col:31, line:24:1> // CHECK-NEXT: | `-OMPTargetDirective {{.*}} <line:19:9, col:19> // CHECK-NEXT: | |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit> // CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:21:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:22:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | `-CapturedStmt {{.*}} <line:20:9, col:46> // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-CapturedStmt {{.*}} <col:9, col:46> // CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-OMPTeamsDistributeSimdDirective {{.*}} <col:9, col:46> openmp_structured_block // CHECK-NEXT: | | | | | |-OMPCollapseClause {{.*}} <col:35, col:45> // CHECK-NEXT: | | | | | | `-ConstantExpr {{.*}} <col:44> 'int' // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:44> 'int' 1 // CHECK-NEXT: | | | | | `-CapturedStmt {{.*}} <line:21:3, line:23:7> // CHECK-NEXT: | | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | | | |-ForStmt {{.*}} <line:21:3, line:23:7> // CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:21:8, col:17> // CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ForStmt {{.*}} <line:22:5, line:23:7> openmp_structured_block // CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:22:10, col:19> // CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-NullStmt {{.*}} <line:23:7> // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <line:20:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:20:9) *const restrict' // CHECK-NEXT: | | | | | | |-VarDecl {{.*}} <line:21:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <line:22:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | |-DeclRefExpr {{.*}} <line:21:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <line:22:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:19:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:19:9) *const restrict' // CHECK-NEXT: | | | | |-RecordDecl {{.*}} <line:20:9> col:9 implicit struct definition // CHECK-NEXT: | | | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | | | |-FieldDecl {{.*}} <line:21:23> col:23 implicit 'int &' // CHECK-NEXT: | | | | | `-FieldDecl {{.*}} <line:22:25> col:25 implicit 'int &' // CHECK-NEXT: | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | | |-ForStmt {{.*}} <line:21:3, line:23:7> // CHECK-NEXT: | | | | | | |-DeclStmt {{.*}} <line:21:8, col:17> // CHECK-NEXT: | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ForStmt {{.*}} <line:22:5, line:23:7> openmp_structured_block // CHECK-NEXT: | | | | | | |-DeclStmt {{.*}} <line:22:10, col:19> // CHECK-NEXT: | | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-NullStmt {{.*}} <line:23:7> // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <line:20:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:20:9) *const restrict' // CHECK-NEXT: | | | | | |-VarDecl {{.*}} <line:21:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <line:22:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | |-OMPCapturedExprDecl {{.*}} <line:21:23> col:23 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | `-OMPCapturedExprDecl {{.*}} <col:3, <invalid sloc>> col:3 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | | `-BinaryOperator {{.*}} <col:3, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:3, col:26> 'int' '/' // CHECK-NEXT: | | | | | |-ParenExpr {{.*}} <col:3> 'int' // CHECK-NEXT: | | | | | | `-BinaryOperator {{.*}} <col:23, col:26> 'int' '+' // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:23, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:23, col:16> 'int' '-' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue OMPCapturedExpr {{.*}} '.capture_expr.' 'int' // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:22:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:19:9> col:9 implicit .global_tid. 'const int' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .part_id. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .privates. 'void *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .task_t. 'void *const' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:19:9) *const restrict' // CHECK-NEXT: | | |-RecordDecl {{.*}} <col:9> col:9 implicit struct definition // CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:21:23> col:23 implicit 'int' // CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:22:25> col:25 implicit 'int' // CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-OMPTeamsDistributeSimdDirective {{.*}} <line:20:9, col:46> openmp_structured_block // CHECK-NEXT: | | | |-OMPCollapseClause {{.*}} <col:35, col:45> // CHECK-NEXT: | | | | `-ConstantExpr {{.*}} <col:44> 'int' // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:44> 'int' 1 // CHECK-NEXT: | | | `-CapturedStmt {{.*}} <line:21:3, line:23:7> // CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:21:3, line:23:7> // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:21:8, col:17> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:22:5, line:23:7> openmp_structured_block // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:22:10, col:19> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:23:7> // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:20:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:20:9) *const restrict' // CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:21:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:22:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <line:21:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:22:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:19:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:19:9) *const restrict' // CHECK-NEXT: | | |-RecordDecl {{.*}} <line:20:9> col:9 implicit struct definition // CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:21:23> col:23 implicit 'int &' // CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:22:25> col:25 implicit 'int &' // CHECK-NEXT: | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | |-ForStmt {{.*}} <line:21:3, line:23:7> // CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:21:8, col:17> // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ForStmt {{.*}} <line:22:5, line:23:7> openmp_structured_block // CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:22:10, col:19> // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-NullStmt {{.*}} <line:23:7> // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <line:20:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:20:9) *const restrict' // CHECK-NEXT: | | | |-VarDecl {{.*}} <line:21:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | `-VarDecl {{.*}} <line:22:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | |-OMPCapturedExprDecl {{.*}} <line:21:23> col:23 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | `-OMPCapturedExprDecl {{.*}} <col:3, <invalid sloc>> col:3 implicit used .capture_expr. 'int' // CHECK-NEXT: | | `-BinaryOperator {{.*}} <col:3, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | |-BinaryOperator {{.*}} <col:3, col:26> 'int' '/' // CHECK-NEXT: | | | |-ParenExpr {{.*}} <col:3> 'int' // CHECK-NEXT: | | | | `-BinaryOperator {{.*}} <col:23, col:26> 'int' '+' // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:23, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:23, col:16> 'int' '-' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue OMPCapturedExpr {{.*}} '.capture_expr.' 'int' // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | |-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:22:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: |-FunctionDecl {{.*}} <line:26:1, line:32:1> line:26:6 test_four 'void (int, int)' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:16, col:20> col:20 used x 'int' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:23, col:27> col:27 used y 'int' // CHECK-NEXT: | `-CompoundStmt {{.*}} <col:30, line:32:1> // CHECK-NEXT: | `-OMPTargetDirective {{.*}} <line:27:9, col:19> // CHECK-NEXT: | |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit> // CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:29:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:30:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | `-CapturedStmt {{.*}} <line:28:9, col:46> // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-CapturedStmt {{.*}} <col:9, col:46> // CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-OMPTeamsDistributeSimdDirective {{.*}} <col:9, col:46> openmp_structured_block // CHECK-NEXT: | | | | | |-OMPCollapseClause {{.*}} <col:35, col:45> // CHECK-NEXT: | | | | | | `-ConstantExpr {{.*}} <col:44> 'int' // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:44> 'int' 2 // CHECK-NEXT: | | | | | `-CapturedStmt {{.*}} <line:29:3, line:31:7> // CHECK-NEXT: | | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | | | |-ForStmt {{.*}} <line:29:3, line:31:7> // CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:29:8, col:17> // CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ForStmt {{.*}} <line:30:5, line:31:7> // CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:30:10, col:19> // CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-NullStmt {{.*}} <line:31:7> openmp_structured_block // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <line:28:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:28:9) *const restrict' // CHECK-NEXT: | | | | | | |-VarDecl {{.*}} <line:29:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <line:30:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | |-DeclRefExpr {{.*}} <line:29:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <line:30:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:27:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:27:9) *const restrict' // CHECK-NEXT: | | | | |-RecordDecl {{.*}} <line:28:9> col:9 implicit struct definition // CHECK-NEXT: | | | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | | | |-FieldDecl {{.*}} <line:29:23> col:23 implicit 'int &' // CHECK-NEXT: | | | | | `-FieldDecl {{.*}} <line:30:25> col:25 implicit 'int &' // CHECK-NEXT: | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | | |-ForStmt {{.*}} <line:29:3, line:31:7> // CHECK-NEXT: | | | | | | |-DeclStmt {{.*}} <line:29:8, col:17> // CHECK-NEXT: | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ForStmt {{.*}} <line:30:5, line:31:7> // CHECK-NEXT: | | | | | | |-DeclStmt {{.*}} <line:30:10, col:19> // CHECK-NEXT: | | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-NullStmt {{.*}} <line:31:7> openmp_structured_block // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <line:28:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:28:9) *const restrict' // CHECK-NEXT: | | | | | |-VarDecl {{.*}} <line:29:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <line:30:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | |-OMPCapturedExprDecl {{.*}} <line:29:23> col:23 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | |-OMPCapturedExprDecl {{.*}} <line:30:25> col:25 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | `-OMPCapturedExprDecl {{.*}} <line:29:3, <invalid sloc>> col:3 implicit used .capture_expr. 'long' // CHECK-NEXT: | | | | `-BinaryOperator {{.*}} <col:3, <invalid sloc>> 'long' '-' // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:3, line:30:28> 'long' '*' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <line:29:3, col:26> 'long' <IntegralCast> // CHECK-NEXT: | | | | | | `-BinaryOperator {{.*}} <col:3, col:26> 'int' '/' // CHECK-NEXT: | | | | | | |-ParenExpr {{.*}} <col:3> 'int' // CHECK-NEXT: | | | | | | | `-BinaryOperator {{.*}} <col:23, col:26> 'int' '+' // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:23, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | | | | | |-BinaryOperator {{.*}} <col:23, col:16> 'int' '-' // CHECK-NEXT: | | | | | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue OMPCapturedExpr {{.*}} '.capture_expr.' 'int' // CHECK-NEXT: | | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <line:30:5, col:28> 'long' <IntegralCast> // CHECK-NEXT: | | | | | `-BinaryOperator {{.*}} <col:5, col:28> 'int' '/' // CHECK-NEXT: | | | | | |-ParenExpr {{.*}} <col:5> 'int' // CHECK-NEXT: | | | | | | `-BinaryOperator {{.*}} <col:25, col:28> 'int' '+' // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:25, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:25, col:18> 'int' '-' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue OMPCapturedExpr {{.*}} '.capture_expr.' 'int' // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:28> 'int' 1 // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:28> 'int' 1 // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <<invalid sloc>> 'long' <IntegralCast> // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <line:29:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:30:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:27:9> col:9 implicit .global_tid. 'const int' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .part_id. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .privates. 'void *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .task_t. 'void *const' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:27:9) *const restrict' // CHECK-NEXT: | | |-RecordDecl {{.*}} <col:9> col:9 implicit struct definition // CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:29:23> col:23 implicit 'int' // CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:30:25> col:25 implicit 'int' // CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-OMPTeamsDistributeSimdDirective {{.*}} <line:28:9, col:46> openmp_structured_block // CHECK-NEXT: | | | |-OMPCollapseClause {{.*}} <col:35, col:45> // CHECK-NEXT: | | | | `-ConstantExpr {{.*}} <col:44> 'int' // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:44> 'int' 2 // CHECK-NEXT: | | | `-CapturedStmt {{.*}} <line:29:3, line:31:7> // CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:29:3, line:31:7> // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:29:8, col:17> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:30:5, line:31:7> // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:30:10, col:19> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:31:7> openmp_structured_block // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:28:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:28:9) *const restrict' // CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:29:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:30:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <line:29:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:30:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:27:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:27:9) *const restrict' // CHECK-NEXT: | | |-RecordDecl {{.*}} <line:28:9> col:9 implicit struct definition // CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:29:23> col:23 implicit 'int &' // CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:30:25> col:25 implicit 'int &' // CHECK-NEXT: | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | |-ForStmt {{.*}} <line:29:3, line:31:7> // CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:29:8, col:17> // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ForStmt {{.*}} <line:30:5, line:31:7> // CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:30:10, col:19> // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-NullStmt {{.*}} <line:31:7> openmp_structured_block // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <line:28:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:28:9) *const restrict' // CHECK-NEXT: | | | |-VarDecl {{.*}} <line:29:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | `-VarDecl {{.*}} <line:30:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | |-OMPCapturedExprDecl {{.*}} <line:29:23> col:23 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | |-OMPCapturedExprDecl {{.*}} <line:30:25> col:25 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | `-OMPCapturedExprDecl {{.*}} <line:29:3, <invalid sloc>> col:3 implicit used .capture_expr. 'long' // CHECK-NEXT: | | `-BinaryOperator {{.*}} <col:3, <invalid sloc>> 'long' '-' // CHECK-NEXT: | | |-BinaryOperator {{.*}} <col:3, line:30:28> 'long' '*' // CHECK-NEXT: | | | |-ImplicitCastExpr {{.*}} <line:29:3, col:26> 'long' <IntegralCast> // CHECK-NEXT: | | | | `-BinaryOperator {{.*}} <col:3, col:26> 'int' '/' // CHECK-NEXT: | | | | |-ParenExpr {{.*}} <col:3> 'int' // CHECK-NEXT: | | | | | `-BinaryOperator {{.*}} <col:23, col:26> 'int' '+' // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:23, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:23, col:16> 'int' '-' // CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue OMPCapturedExpr {{.*}} '.capture_expr.' 'int' // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <line:30:5, col:28> 'long' <IntegralCast> // CHECK-NEXT: | | | `-BinaryOperator {{.*}} <col:5, col:28> 'int' '/' // CHECK-NEXT: | | | |-ParenExpr {{.*}} <col:5> 'int' // CHECK-NEXT: | | | | `-BinaryOperator {{.*}} <col:25, col:28> 'int' '+' // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:25, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:25, col:18> 'int' '-' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue OMPCapturedExpr {{.*}} '.capture_expr.' 'int' // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:28> 'int' 1 // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:28> 'int' 1 // CHECK-NEXT: | | `-ImplicitCastExpr {{.*}} <<invalid sloc>> 'long' <IntegralCast> // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:29:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:30:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: `-FunctionDecl {{.*}} <line:34:1, line:41:1> line:34:6 test_five 'void (int, int, int)' // CHECK-NEXT: |-ParmVarDecl {{.*}} <col:16, col:20> col:20 used x 'int' // CHECK-NEXT: |-ParmVarDecl {{.*}} <col:23, col:27> col:27 used y 'int' // CHECK-NEXT: |-ParmVarDecl {{.*}} <col:30, col:34> col:34 used z 'int' // CHECK-NEXT: `-CompoundStmt {{.*}} <col:37, line:41:1> // CHECK-NEXT: `-OMPTargetDirective {{.*}} <line:35:9, col:19> // CHECK-NEXT: |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit> // CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:37:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:38:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:39:27> 'int' lvalue ParmVar {{.*}} 'z' 'int' // CHECK-NEXT: `-CapturedStmt {{.*}} <line:36:9, col:46> // CHECK-NEXT: |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | |-CapturedStmt {{.*}} <col:9, col:46> // CHECK-NEXT: | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | |-OMPTeamsDistributeSimdDirective {{.*}} <col:9, col:46> openmp_structured_block // CHECK-NEXT: | | | | |-OMPCollapseClause {{.*}} <col:35, col:45> // CHECK-NEXT: | | | | | `-ConstantExpr {{.*}} <col:44> 'int' // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:44> 'int' 2 // CHECK-NEXT: | | | | `-CapturedStmt {{.*}} <line:37:3, line:40:9> // CHECK-NEXT: | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | | |-ForStmt {{.*}} <line:37:3, line:40:9> // CHECK-NEXT: | | | | | | |-DeclStmt {{.*}} <line:37:8, col:17> // CHECK-NEXT: | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ForStmt {{.*}} <line:38:5, line:40:9> // CHECK-NEXT: | | | | | | |-DeclStmt {{.*}} <line:38:10, col:19> // CHECK-NEXT: | | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ForStmt {{.*}} <line:39:7, line:40:9> openmp_structured_block // CHECK-NEXT: | | | | | | |-DeclStmt {{.*}} <line:39:12, col:21> // CHECK-NEXT: | | | | | | | `-VarDecl {{.*}} <col:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:23, col:27> 'int' '<' // CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ImplicitCastExpr {{.*}} <col:27> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:27> 'int' lvalue ParmVar {{.*}} 'z' 'int' // CHECK-NEXT: | | | | | | |-UnaryOperator {{.*}} <col:30, col:31> 'int' postfix '++' // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:30> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-NullStmt {{.*}} <line:40:9> // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <line:36:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:36:9) *const restrict' // CHECK-NEXT: | | | | | |-VarDecl {{.*}} <line:37:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | |-VarDecl {{.*}} <line:38:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <line:39:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: | | | | |-DeclRefExpr {{.*}} <line:37:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | |-DeclRefExpr {{.*}} <line:38:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <line:39:27> 'int' lvalue ParmVar {{.*}} 'z' 'int' // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <line:35:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:35:9) *const restrict' // CHECK-NEXT: | | | |-RecordDecl {{.*}} <line:36:9> col:9 implicit struct definition // CHECK-NEXT: | | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | | |-FieldDecl {{.*}} <line:37:23> col:23 implicit 'int &' // CHECK-NEXT: | | | | |-FieldDecl {{.*}} <line:38:25> col:25 implicit 'int &' // CHECK-NEXT: | | | | `-FieldDecl {{.*}} <line:39:27> col:27 implicit 'int &' // CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:37:3, line:40:9> // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:37:8, col:17> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:38:5, line:40:9> // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:38:10, col:19> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:39:7, line:40:9> openmp_structured_block // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:39:12, col:21> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:23, col:27> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:27> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:27> 'int' lvalue ParmVar {{.*}} 'z' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:30, col:31> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:30> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:40:9> // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:36:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:36:9) *const restrict' // CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:37:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:38:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:39:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: | | | |-OMPCapturedExprDecl {{.*}} <line:37:23> col:23 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | |-OMPCapturedExprDecl {{.*}} <line:38:25> col:25 implicit used .capture_expr. 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | `-OMPCapturedExprDecl {{.*}} <line:37:3, <invalid sloc>> col:3 implicit used .capture_expr. 'long' // CHECK-NEXT: | | | `-BinaryOperator {{.*}} <col:3, <invalid sloc>> 'long' '-' // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:3, line:38:28> 'long' '*' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <line:37:3, col:26> 'long' <IntegralCast> // CHECK-NEXT: | | | | | `-BinaryOperator {{.*}} <col:3, col:26> 'int' '/' // CHECK-NEXT: | | | | | |-ParenExpr {{.*}} <col:3> 'int' // CHECK-NEXT: | | | | | | `-BinaryOperator {{.*}} <col:23, col:26> 'int' '+' // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:23, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:23, col:16> 'int' '-' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue OMPCapturedExpr {{.*}} '.capture_expr.' 'int' // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <line:38:5, col:28> 'long' <IntegralCast> // CHECK-NEXT: | | | | `-BinaryOperator {{.*}} <col:5, col:28> 'int' '/' // CHECK-NEXT: | | | | |-ParenExpr {{.*}} <col:5> 'int' // CHECK-NEXT: | | | | | `-BinaryOperator {{.*}} <col:25, col:28> 'int' '+' // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:25, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:25, col:18> 'int' '-' // CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue OMPCapturedExpr {{.*}} '.capture_expr.' 'int' // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:28> 'int' 1 // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:28> 'int' 1 // CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <<invalid sloc>> 'long' <IntegralCast> // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:37:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:38:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:39:27> 'int' lvalue ParmVar {{.*}} 'z' 'int' // CHECK-NEXT: | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <line:35:9> col:9 implicit .global_tid. 'const int' // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .part_id. 'const int *const restrict' // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .privates. 'void *const restrict' // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)' // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .task_t. 'void *const' // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:35:9) *const restrict' // CHECK-NEXT: | |-RecordDecl {{.*}} <col:9> col:9 implicit struct definition // CHECK-NEXT: | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | |-FieldDecl {{.*}} <line:37:23> col:23 implicit 'int' // CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | |-FieldDecl {{.*}} <line:38:25> col:25 implicit 'int' // CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | `-FieldDecl {{.*}} <line:39:27> col:27 implicit 'int' // CHECK-NEXT: | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | |-OMPTeamsDistributeSimdDirective {{.*}} <line:36:9, col:46> openmp_structured_block // CHECK-NEXT: | | |-OMPCollapseClause {{.*}} <col:35, col:45> // CHECK-NEXT: | | | `-ConstantExpr {{.*}} <col:44> 'int' // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:44> 'int' 2 // CHECK-NEXT: | | `-CapturedStmt {{.*}} <line:37:3, line:40:9> // CHECK-NEXT: | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | |-ForStmt {{.*}} <line:37:3, line:40:9> // CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:37:8, col:17> // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ForStmt {{.*}} <line:38:5, line:40:9> // CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:38:10, col:19> // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ForStmt {{.*}} <line:39:7, line:40:9> openmp_structured_block // CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:39:12, col:21> // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:23, col:27> 'int' '<' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:27> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:27> 'int' lvalue ParmVar {{.*}} 'z' 'int' // CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:30, col:31> 'int' postfix '++' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:30> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-NullStmt {{.*}} <line:40:9> // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <line:36:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:36:9) *const restrict' // CHECK-NEXT: | | | |-VarDecl {{.*}} <line:37:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | |-VarDecl {{.*}} <line:38:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | `-VarDecl {{.*}} <line:39:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:37:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:38:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:39:27> 'int' lvalue ParmVar {{.*}} 'z' 'int' // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <line:35:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:35:9) *const restrict' // CHECK-NEXT: | |-RecordDecl {{.*}} <line:36:9> col:9 implicit struct definition // CHECK-NEXT: | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | |-FieldDecl {{.*}} <line:37:23> col:23 implicit 'int &' // CHECK-NEXT: | | |-FieldDecl {{.*}} <line:38:25> col:25 implicit 'int &' // CHECK-NEXT: | | `-FieldDecl {{.*}} <line:39:27> col:27 implicit 'int &' // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-ForStmt {{.*}} <line:37:3, line:40:9> // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:37:8, col:17> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-ForStmt {{.*}} <line:38:5, line:40:9> // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:38:10, col:19> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-ForStmt {{.*}} <line:39:7, line:40:9> openmp_structured_block // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:39:12, col:21> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:23, col:27> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:27> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:27> 'int' lvalue ParmVar {{.*}} 'z' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:30, col:31> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:30> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-NullStmt {{.*}} <line:40:9> // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:36:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-teams-distribute-simd.c:36:9) *const restrict' // CHECK-NEXT: | | |-VarDecl {{.*}} <line:37:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | |-VarDecl {{.*}} <line:38:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | `-VarDecl {{.*}} <line:39:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: | |-OMPCapturedExprDecl {{.*}} <line:37:23> col:23 implicit used .capture_expr. 'int' // CHECK-NEXT: | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | |-OMPCapturedExprDecl {{.*}} <line:38:25> col:25 implicit used .capture_expr. 'int' // CHECK-NEXT: | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | `-OMPCapturedExprDecl {{.*}} <line:37:3, <invalid sloc>> col:3 implicit used .capture_expr. 'long' // CHECK-NEXT: | `-BinaryOperator {{.*}} <col:3, <invalid sloc>> 'long' '-' // CHECK-NEXT: | |-BinaryOperator {{.*}} <col:3, line:38:28> 'long' '*' // CHECK-NEXT: | | |-ImplicitCastExpr {{.*}} <line:37:3, col:26> 'long' <IntegralCast> // CHECK-NEXT: | | | `-BinaryOperator {{.*}} <col:3, col:26> 'int' '/' // CHECK-NEXT: | | | |-ParenExpr {{.*}} <col:3> 'int' // CHECK-NEXT: | | | | `-BinaryOperator {{.*}} <col:23, col:26> 'int' '+' // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:23, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:23, col:16> 'int' '-' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue OMPCapturedExpr {{.*}} '.capture_expr.' 'int' // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:26> 'int' 1 // CHECK-NEXT: | | `-ImplicitCastExpr {{.*}} <line:38:5, col:28> 'long' <IntegralCast> // CHECK-NEXT: | | `-BinaryOperator {{.*}} <col:5, col:28> 'int' '/' // CHECK-NEXT: | | |-ParenExpr {{.*}} <col:5> 'int' // CHECK-NEXT: | | | `-BinaryOperator {{.*}} <col:25, col:28> 'int' '+' // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:25, <invalid sloc>> 'int' '-' // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:25, col:18> 'int' '-' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue OMPCapturedExpr {{.*}} '.capture_expr.' 'int' // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:28> 'int' 1 // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:28> 'int' 1 // CHECK-NEXT: | `-ImplicitCastExpr {{.*}} <<invalid sloc>> 'long' <IntegralCast> // CHECK-NEXT: | `-IntegerLiteral {{.*}} <<invalid sloc>> 'int' 1 // CHECK-NEXT: |-DeclRefExpr {{.*}} <line:37:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: |-DeclRefExpr {{.*}} <line:38:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: `-DeclRefExpr {{.*}} <line:39:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
GB_unaryop__minv_uint16_uint8.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_uint16_uint8 // op(A') function: GB_tran__minv_uint16_uint8 // C type: uint16_t // A type: uint8_t // cast: uint16_t cij = (uint16_t) aij // unaryop: cij = GB_IMINV_UNSIGNED (aij, 16) #define GB_ATYPE \ uint8_t #define GB_CTYPE \ uint16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_IMINV_UNSIGNED (x, 16) ; // casting #define GB_CASTING(z, x) \ uint16_t z = (uint16_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MINV || GxB_NO_UINT16 || GxB_NO_UINT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_uint16_uint8 ( uint16_t *restrict Cx, const uint8_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__minv_uint16_uint8 ( 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
GB_AxB_dot3_template.c
//------------------------------------------------------------------------------ // GB_AxB_dot3_template: C<M>=A'*B via dot productes //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ #ifndef GB_DOT3 #define GB_DOT3 #endif { //-------------------------------------------------------------------------- // get M, A, B, and C //-------------------------------------------------------------------------- const int64_t *restrict Cp = C->p ; const int64_t *restrict Ch = C->h ; int64_t *restrict Ci = C->i ; GB_CTYPE *restrict Cx = C->x ; const int64_t *restrict Bp = B->p ; const int64_t *restrict Bh = B->h ; const int64_t *restrict Bi = B->i ; const GB_BTYPE *restrict Bx = B_is_pattern ? NULL : B->x ; const int64_t bvlen = B->vlen ; const int64_t bnvec = B->nvec ; const bool B_is_hyper = B->is_hyper ; const int64_t *restrict Mi = M->i ; const GB_void *restrict Mx = M->x ; GB_cast_function cast_M = GB_cast_factory (GB_BOOL_code, M->type->code) ; const size_t msize = M->type->size ; const int64_t *restrict Ah = A->h ; const int64_t *restrict Ap = A->p ; const int64_t *restrict Ai = A->i ; const int64_t anvec = A->nvec ; const bool A_is_hyper = GB_IS_HYPER (A) ; const GB_ATYPE *restrict Ax = A_is_pattern ? NULL : A->x ; //-------------------------------------------------------------------------- // C<M> = A'*B //-------------------------------------------------------------------------- // C and M have the same pattern, except some entries of C may become // zombies. int64_t nzombies = 0 ; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \ reduction(+:nzombies) for (int taskid = 0 ; taskid < ntasks ; taskid++) { //---------------------------------------------------------------------- // get the task descriptor //---------------------------------------------------------------------- int64_t kfirst = TaskList [taskid].kfirst ; int64_t klast = TaskList [taskid].klast ; int64_t pC_first = TaskList [taskid].pC ; int64_t pC_last = TaskList [taskid].pC_end ; int64_t task_nzombies = 0 ; int64_t bpleft = 0 ; //---------------------------------------------------------------------- // compute all vectors in this task //---------------------------------------------------------------------- for (int64_t k = kfirst ; k <= klast ; k++) { //------------------------------------------------------------------ // get C(:,k) and M(:k) //------------------------------------------------------------------ int64_t j = (Ch == NULL) ? k : Ch [k] ; int64_t pC_start, pC_end ; if (k == kfirst) { // First vector for task; may only be partially owned. pC_start = pC_first ; pC_end = GB_IMIN (Cp [k+1], pC_last) ; } else if (k == klast) { // Last vector for task; may only be partially owned. pC_start = Cp [k] ; pC_end = pC_last ; } else { // task fully owns this vector C(:,k). pC_start = Cp [k] ; pC_end = Cp [k+1] ; } //------------------------------------------------------------------ // get B(:,j) //------------------------------------------------------------------ int64_t pB_start, pB_end ; GB_lookup (B_is_hyper, Bh, Bp, &bpleft, bnvec-1, j, &pB_start, &pB_end) ; int64_t bjnz = pB_end - pB_start ; //------------------------------------------------------------------ // C(:,j)<M(:,j)> = A(:,i)'*B(:,j) //------------------------------------------------------------------ if (bjnz == 0) { //-------------------------------------------------------------- // C(:,j) is empty if B(:,j) is empty //-------------------------------------------------------------- task_nzombies += (pC_end - pC_start) ; for (int64_t pC = pC_start ; pC < pC_end ; pC++) { // C(i,j) is a zombie Ci [pC] = GB_FLIP (Mi [pC]) ; } } else { //-------------------------------------------------------------- // B(:,j) not empty //-------------------------------------------------------------- int64_t ib_first = Bi [pB_start] ; int64_t ib_last = Bi [pB_end-1] ; int64_t apleft = 0 ; for (int64_t pC = pC_start ; pC < pC_end ; pC++) { //---------------------------------------------------------- // compute C(i,j) //---------------------------------------------------------- // get the value of M(i,j) int64_t i = Mi [pC] ; bool mij ; cast_M (&mij, Mx +(pC*msize), 0) ; if (mij) { //------------------------------------------------------ // M(i,j) is true, so compute C(i,j) //------------------------------------------------------ // get A(:,i), if it exists int64_t pA, pA_end ; GB_lookup (A_is_hyper, Ah, Ap, &apleft, anvec-1, i, &pA, &pA_end) ; // C(i,j) = A(:,i)'*B(:,j) #include "GB_AxB_dot_cij.c" } else { //------------------------------------------------------ // M(i,j) is false, so C(i,j) is a zombie //------------------------------------------------------ task_nzombies++ ; Ci [pC] = GB_FLIP (i) ; } } } } //---------------------------------------------------------------------- // sum up the zombies found by this task //---------------------------------------------------------------------- nzombies += task_nzombies ; } //-------------------------------------------------------------------------- // finalize the zombie count for C //-------------------------------------------------------------------------- C->nzombies = nzombies ; } #undef GB_DOT3
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-2018 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/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; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register 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*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; register 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 critical (MagickCore_CompositeImage) #endif 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); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); (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; 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; register const Quantum *p; register Quantum *q; register 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++) { register 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(image); i++) { 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) SetPixelChannel(image,channel,p[i],q); else if (channel == AlphaPixelChannel) SetPixelChannel(image,channel,OpaqueAlpha,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; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_CompositeImage) #endif 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; register const Quantum *p; register Quantum *q; register 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; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_CompositeImage) #endif 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; MagickRealType angle_range, angle_start, height, width; PixelInfo pixel; ResampleFilter *resample_filter; SegmentInfo blur; /* Blur Image by resampling. Blur Image 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=height=geometry_info.rho*2.0; if ((flags & HeightValue) != 0 ) height=geometry_info.sigma*2.0; /* Default the unrotated ellipse width and height axis vectors. */ blur.x1=width; blur.x2=0.0; blur.y1=0.0; blur.y2=height; /* rotate vectors if a rotation angle is given */ if ((flags & XValue) != 0 ) { MagickRealType angle; 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); } /* Otherwise lets set a angle range and calculate in the loop */ angle_start=0.0; angle_range=0.0; if ((flags & YValue) != 0 ) { 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, then restore them afterwards. */ resample_filter=AcquireResampleFilter(image,exception); SetResampleFilter(resample_filter,GaussianFilter); /* do 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; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register 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((double) 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); } #if 0 if ( x == 10 && y == 60 ) { (void) fprintf(stderr, "blur.x=%lf,%lf, blur.y=%lf,%lf\n",blur.x1, blur.x2,blur.y1, blur.y2); (void) fprintf(stderr, "scaled by=%lf,%lf\n",QuantumScale* GetPixelRed(p),QuantumScale*GetPixelGreen(p)); #endif 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; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register 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; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register 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*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; register 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 HardLightCompositeOp: case HardMixCompositeOp: case LinearBurnCompositeOp: case LinearDodgeCompositeOp: case LinearLightCompositeOp: case LightenCompositeOp: case MathematicsCompositeOp: case MinusDstCompositeOp: case MinusSrcCompositeOp: case ModulusAddCompositeOp: case ModulusSubtractCompositeOp: case MultiplyCompositeOp: case OverlayCompositeOp: case PegtopLightCompositeOp: case PinLightCompositeOp: case ScreenCompositeOp: case SoftLightCompositeOp: 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; } default: { alpha=1.0; break; } } switch (compose) { case ColorizeCompositeOp: case HueCompositeOp: case LuminizeCompositeOp: case ModulateCompositeOp: 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 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 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 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 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 BlurCompositeOp: case CopyCompositeOp: case ReplaceCompositeOp: case SrcCompositeOp: { pixel=QuantumRange*Sca; break; } 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) (QuantumRange- 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*(Dca*Sa); break; } case DstOutCompositeOp: { pixel=QuantumRange*(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 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 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: { pixel=Sc+Dc; while (pixel > QuantumRange) pixel-=QuantumRange; while (pixel < 0.0) pixel+=QuantumRange; pixel=(Sa*Da*pixel+Sa*Sc*(1.0-Da)+Da*Dc*(1.0-Sa)); break; } case ModulusSubtractCompositeOp: { pixel=Sc-Dc; while (pixel > QuantumRange) pixel-=QuantumRange; while (pixel < 0.0) pixel+=QuantumRange; pixel=(Sa*Da*pixel+Sa*Sc*(1.0-Da)+Da*Dc*(1.0-Sa)); break; } case MultiplyCompositeOp: { pixel=QuantumRange*gamma*(Sca*Dca+Sca*(1.0-Da)+Dca*(1.0-Sa)); 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 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 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 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 critical (MagickCore_CompositeImage) #endif 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) { register 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; register const Quantum *p, *pixels; register ssize_t x; register 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) { register 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++) { register 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); }
convolution_5x5.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2017 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 __ARM_NEON #include <arm_neon.h> #endif // __ARM_NEON static void conv5x5s1_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for for (int p=0; p<outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); for (int q=0; q<inch; q++) { float* outptr = out; float* outptr2 = outptr + outw; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p*inch*25 + q*25; const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w*2; const float* r3 = img0 + w*3; const float* r4 = img0 + w*4; const float* r5 = img0 + w*5; const float* k0 = kernel0; const float* k1 = kernel0 + 5; const float* k2 = kernel0 + 10; const float* k3 = kernel0 + 15; const float* k4 = kernel0 + 20; #if __ARM_NEON float32x4_t _k0123 = vld1q_f32(kernel0); float32x4_t _k4567 = vld1q_f32(kernel0+4); float32x4_t _k891011 = vld1q_f32(kernel0+8); float32x4_t _k12131415 = vld1q_f32(kernel0+12); float32x4_t _k16171819 = vld1q_f32(kernel0+16); float32x4_t _k20212223 = vld1q_f32(kernel0+20); float32x4_t _k24242424 = vdupq_n_f32(kernel0[24]); #endif // __ARM_NEON int i = 0; for (; i+1 < outh; i+=2) { #if __ARM_NEON int nn = outw >> 2; int remain = outw - (nn << 2); #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ if (nn > 0) { asm volatile( // v11 = rx1 / rx3 // v12 = rx2 // v13 v14 = intermediate sum register "prfm pldl1keep, [%1, #128] \n" "ld1 {v7.4s}, [%1] \n"// v7 = out "0: \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v8.4s}, [%2] \n"// v8 = out2 // r1 "prfm pldl1keep, [%4, #256] \n" "ld1 {v9.4s, v10.4s}, [%4] \n"// v9 v10 = r10 r14 "add %4, %4, #16 \n" "ext v11.16b, v9.16b, v10.16b, #4 \n" //r11 "fmul v13.4s, v9.4s, %19.s[1] \n" "fmla v8.4s, v9.4s, %18.s[0] \n" "ext v12.16b, v9.16b, v10.16b, #8 \n" //r12 "fmla v7.4s, v11.4s, %19.s[2] \n" "fmul v14.4s, v11.4s, %18.s[1] \n" "ext v11.16b, v9.16b, v10.16b, #12 \n" //r13 "fmla v13.4s, v12.4s, %19.s[3] \n" "fmla v8.4s, v12.4s, %18.s[2] \n" "fmla v7.4s, v11.4s, %20.s[0] \n" "fmla v14.4s, v11.4s, %18.s[3] \n" "prfm pldl1keep, [%5, #256] \n" "fmla v13.4s, v10.4s, %20.s[1] \n" "fmla v8.4s, v10.4s, %19.s[0] \n" // r2 "ld1 {v9.4s, v10.4s}, [%5] \n"// v9 v10 = r20 r24 "add %5, %5, #16 \n" "ext v11.16b, v9.16b, v10.16b, #4 \n" //r21 "fmla v7.4s, v9.4s, %20.s[2] \n" "fmla v14.4s, v9.4s, %19.s[1] \n" "ext v12.16b, v9.16b, v10.16b, #8 \n" //r22 "fmla v13.4s, v11.4s, %20.s[3] \n" "fmla v8.4s, v11.4s, %19.s[2] \n" "ext v11.16b, v9.16b, v10.16b, #12 \n" //r23 "fmla v7.4s, v12.4s, %21.s[0] \n" "fmla v14.4s, v12.4s, %19.s[3] \n" "fmla v13.4s, v11.4s, %21.s[1] \n" "fmla v8.4s, v11.4s, %20.s[0] \n" "prfm pldl1keep, [%6, #256] \n" "fmla v7.4s, v10.4s, %21.s[2] \n" "fmla v14.4s, v10.4s, %20.s[1] \n" // r3 "ld1 {v9.4s, v10.4s}, [%6] \n"// v9 v10 = r30 r34 "add %6, %6, #16 \n" "ext v11.16b, v9.16b, v10.16b, #4 \n" //r31 "fmla v13.4s, v9.4s, %21.s[3] \n" "fmla v8.4s, v9.4s, %20.s[2] \n" "ext v12.16b, v9.16b, v10.16b, #8 \n" //r32 "fmla v7.4s, v11.4s, %22.s[0] \n" "fmla v14.4s, v11.4s, %20.s[3] \n" "ext v11.16b, v9.16b, v10.16b, #12 \n" //r33 "fmla v13.4s, v12.4s, %22.s[1] \n" "fmla v8.4s, v12.4s, %21.s[0] \n" "fmla v7.4s, v11.4s, %22.s[2] \n" "fmla v14.4s, v11.4s, %21.s[1] \n" "prfm pldl1keep, [%7, #256] \n" "fmla v13.4s, v10.4s, %22.s[3] \n" "fmla v8.4s, v10.4s, %21.s[2] \n" // r4 "ld1 {v9.4s, v10.4s}, [%7] \n"// v9 v10 = r40 r44 "add %7, %7, #16 \n" "ext v11.16b, v9.16b, v10.16b, #4 \n" //r41 "fmla v7.4s, v9.4s, %23.s[0] \n" "fmla v14.4s, v9.4s, %21.s[3] \n" "ext v12.16b, v9.16b, v10.16b, #8 \n" //r41 "fmla v13.4s, v11.4s, %23.s[1] \n" "fmla v8.4s, v11.4s, %22.s[0] \n" "ext v11.16b, v9.16b, v10.16b, #12 \n" //r41 "fmla v7.4s, v12.4s, %23.s[2] \n" "fmla v14.4s, v12.4s, %22.s[1] \n" "fmla v13.4s, v11.4s, %23.s[3] \n" "fmla v8.4s, v11.4s, %22.s[2] \n" "prfm pldl1keep, [%3, #256] \n" "fmla v7.4s, v10.4s, %24.s[0] \n" "fmla v14.4s, v10.4s, %22.s[3] \n" // r0 and r5 "ld1 {v9.4s, v10.4s}, [%3] \n"// v9 v10 = r00 r04 "add %3, %3, #16 \n" "ext v11.16b, v9.16b, v10.16b, #4 \n" //r01 "fmla v13.4s, v11.4s, %18.s[1] \n" "ext v12.16b, v9.16b, v10.16b, #8 \n" //r02 "fmla v7.4s, v12.4s, %18.s[2] \n" "ext v11.16b, v9.16b, v10.16b, #12 \n" //r03 "prfm pldl1keep, [%8, #256] \n" "fmla v13.4s, v11.4s, %18.s[3] \n" // r5 "ld1 {v11.4s, v12.4s}, [%8] \n"// v11 v12 = r50 r54 "add %8, %8, #16 \n" "fmla v8.4s, v11.4s, %23.s[0] \n" "fmla v14.4s, v12.4s, %24.s[0] \n" "fmla v7.4s, v9.4s, %18.s[0] \n" "fmla v13.4s, v10.4s, %19.s[0] \n" "ext v9.16b, v11.16b, v12.16b, #4 \n" //r51 "ext v10.16b, v11.16b, v12.16b, #8 \n" //r52 "fmla v14.4s, v9.4s, %23.s[1] \n" "ext v9.16b, v11.16b, v12.16b, #12 \n" //r53 "fmla v8.4s, v10.4s, %23.s[2] \n" "fmla v14.4s, v9.4s, %23.s[3] \n" "fadd v7.4s, v7.4s, v13.4s \n" "st1 {v7.4s}, [%1], #16 \n" "fadd v8.4s, v8.4s, v14.4s \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v7.4s}, [%1] \n"// v7 = out "st1 {v8.4s}, [%2], #16 \n" "subs %w0, %w0, #1 \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(outptr2), // %2 "=r"(r0), // %3 "=r"(r1), // %4 "=r"(r2), // %5 "=r"(r3), // %6 "=r"(r4), // %7 "=r"(r5) // %8 : "0"(nn), "1"(outptr), "2"(outptr2), "3"(r0), "4"(r1), "5"(r2), "6"(r3), "7"(r4), "8"(r5), "w"(_k0123), // %18 "w"(_k4567), // %19 "w"(_k891011), // %20 "w"(_k12131415), // %21 "w"(_k16171819), // %22 "w"(_k20212223), // %23 "w"(_k24242424) // %24 : "cc", "memory", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15" ); } #else if (nn > 0) { asm volatile( // "veor q13, q13 \n" // "veor q14, q14 \n" "pld [%1, #128] \n" "vld1.f32 {d14-d15}, [%1] \n"// q7 = out "0: \n" // q11 = rx1 / rx3 // q12 = rx2 // q13 q14 = intermediate sum register "pld [%2, #128] \n" "vld1.f32 {d16-d17}, [%2] \n"// q8 = out2 "pld [%4, #256] \n" // r1 "vld1.f32 {d18-d21}, [%4] \n"// q9 q10 = r10 r14 "add %4, #16 \n" "vext.32 q11, q9, q10, #1 \n"// r11 "vmul.f32 q13, q9, %e19[1] \n" "vmla.f32 q8, q9, %e18[0] \n" "vext.32 q12, q9, q10, #2 \n"// r12 "vmla.f32 q7, q11, %f19[0] \n" "vmul.f32 q14, q11, %e18[1] \n" "vext.32 q11, q9, q10, #3 \n"// r13 "vmla.f32 q13, q12, %f19[1] \n" "vmla.f32 q8, q12, %f18[0] \n" "vmla.f32 q7, q11, %e20[0] \n" "vmla.f32 q14, q11, %f18[1] \n" "pld [%5, #256] \n" "vmla.f32 q13, q10, %e20[1] \n" "vmla.f32 q8, q10, %e19[0] \n" // r2 "vld1.f32 {d18-d21}, [%5] \n"// q9 q10 = r20 r24 "add %5, #16 \n" "vext.32 q11, q9, q10, #1 \n"// r21 "vmla.f32 q7, q9, %f20[0] \n" "vmla.f32 q14, q9, %e19[1] \n" "vext.32 q12, q9, q10, #2 \n"// r22 "vmla.f32 q13, q11, %f20[1] \n" "vmla.f32 q8, q11, %f19[0] \n" "vext.32 q11, q9, q10, #3 \n"// r23 "vmla.f32 q7, q12, %e21[0] \n" "vmla.f32 q14, q12, %f19[1] \n" "vmla.f32 q13, q11, %e21[1] \n" "vmla.f32 q8, q11, %e20[0] \n" "pld [%6, #256] \n" "vmla.f32 q7, q10, %f21[0] \n" "vmla.f32 q14, q10, %e20[1] \n" // r3 "vld1.f32 {d18-d21}, [%6] \n"// q9 q10 = r30 r34 "add %6, #16 \n" "vext.32 q11, q9, q10, #1 \n"// r31 "vmla.f32 q13, q9, %f21[1] \n" "vmla.f32 q8, q9, %f20[0] \n" "vext.32 q12, q9, q10, #2 \n"// r32 "vmla.f32 q7, q11, %e22[0] \n" "vmla.f32 q14, q11, %f20[1] \n" "vext.32 q11, q9, q10, #3 \n"// r33 "vmla.f32 q13, q12, %e22[1] \n" "vmla.f32 q8, q12, %e21[0] \n" "vmla.f32 q7, q11, %f22[0] \n" "vmla.f32 q14, q11, %e21[1] \n" "pld [%7, #256] \n" "vmla.f32 q13, q10, %f22[1] \n" "vmla.f32 q8, q10, %f21[0] \n" // r4 "vld1.f32 {d18-d21}, [%7] \n"// q9 q10 = r40 r44 "add %7, #16 \n" "vext.32 q11, q9, q10, #1 \n"// r41 "vmla.f32 q7, q9, %e23[0] \n" "vmla.f32 q14, q9, %f21[1] \n" "vext.32 q12, q9, q10, #2 \n"// r42 "vmla.f32 q13, q11, %e23[1] \n" "vmla.f32 q8, q11, %e22[0] \n" "vext.32 q11, q9, q10, #3 \n"// r43 "vmla.f32 q7, q12, %f23[0] \n" "vmla.f32 q14, q12, %e22[1] \n" "vmla.f32 q13, q11, %f23[1] \n" "vmla.f32 q8, q11, %f22[0] \n" "pld [%3, #256] \n" "vmla.f32 q7, q10, %e24[0] \n" "vmla.f32 q14, q10, %f22[1] \n" // r0 and r5 "vld1.f32 {d18-d21}, [%3] \n"// q9 q10 = r00 r04 "add %3, #16 \n" "vext.32 q11, q9, q10, #1 \n"// r01 "vmla.f32 q13, q11, %e18[1] \n" "vext.32 q12, q9, q10, #2 \n"// r02 "vmla.f32 q7, q12, %f18[0] \n" "vext.32 q11, q9, q10, #3 \n"// r03 "pld [%8, #256] \n" "vmla.f32 q13, q11, %f18[1] \n" // r5 "vld1.f32 {d22-d25}, [%8] \n"// q11 q12 = r50 r54 "add %8, #16 \n" "vmla.f32 q8, q11, %e23[0] \n" "vmla.f32 q14, q12, %e24[0] \n" "vmla.f32 q7, q9, %e18[0] \n" "vmla.f32 q13, q10, %e19[0] \n" "vext.32 q9, q11, q12, #1 \n"// r51 "vext.32 q10, q11, q12, #2 \n"// r52 "vmla.f32 q14, q9, %e23[1] \n" "vext.32 q9, q11, q12, #3 \n"// r53 "vmla.f32 q8, q10, %f23[0] \n" "vmla.f32 q14, q9, %f23[1] \n" "vadd.f32 q7, q7, q13 \n" // "veor q13, q13 \n" "vst1.f32 {d14-d15}, [%1]! \n" "vadd.f32 q8, q8, q14 \n" "pld [%1, #128] \n" "vld1.f32 {d14-d15}, [%1] \n"// q7 = out // "veor q14, q14 \n" "vst1.f32 {d16-d17}, [%2]! \n" "subs %0, #1 \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(outptr2), // %2 "=r"(r0), // %3 "=r"(r1), // %4 "=r"(r2), // %5 "=r"(r3), // %6 "=r"(r4), // %7 "=r"(r5) // %8 : "0"(nn), "1"(outptr), "2"(outptr2), "3"(r0), "4"(r1), "5"(r2), "6"(r3), "7"(r4), "8"(r5), "w"(_k0123), // %18 "w"(_k4567), // %19 "w"(_k891011), // %20 "w"(_k12131415), // %21 "w"(_k16171819), // %22 "w"(_k20212223), // %23 "w"(_k24242424) // %24 : "cc", "memory", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { float sum = 0; float sum2 = 0; #if __ARM_NEON float32x4_t _r1 = vld1q_f32(r1); float32x4_t _k1 = vld1q_f32(k1); float32x4_t _sum = vmulq_f32(_r1, _k1); float32x4_t _sum2 = vmulq_f32(_r1, _k0123); float32x4_t _r2 = vld1q_f32(r2); float32x4_t _k2 = vld1q_f32(k2); _sum = vmlaq_f32(_sum, _r2, _k2); _sum2 = vmlaq_f32(_sum2, _r2, _k1); float32x4_t _r3 = vld1q_f32(r3); float32x4_t _k3 = vld1q_f32(k3); _sum = vmlaq_f32(_sum, _r3, _k3); _sum2 = vmlaq_f32(_sum2, _r3, _k2); float32x4_t _r4 = vld1q_f32(r4); _sum = vmlaq_f32(_sum, _r4, _k20212223); _sum2 = vmlaq_f32(_sum2, _r4, _k3); float32x4_t _r0 = vld1q_f32(r0); _sum = vmlaq_f32(_sum, _r0, _k0123); float32x4_t _r5 = vld1q_f32(r5); _sum2 = vmlaq_f32(_sum2, _r5, _k20212223); float32x4_t _k_t4; _k_t4 = vsetq_lane_f32(k0[4], _k_t4, 0); _k_t4 = vsetq_lane_f32(k1[4], _k_t4, 1); _k_t4 = vsetq_lane_f32(k2[4], _k_t4, 2); _k_t4 = vsetq_lane_f32(k3[4], _k_t4, 3); float32x4_t _r_t4; _r_t4 = vsetq_lane_f32(r0[4], _r_t4, 0); _r_t4 = vsetq_lane_f32(r1[4], _r_t4, 1); _r_t4 = vsetq_lane_f32(r2[4], _r_t4, 2); _r_t4 = vsetq_lane_f32(r3[4], _r_t4, 3); _sum = vmlaq_f32(_sum, _r_t4, _k_t4); sum = r4[4] * k4[4]; _r_t4 = vextq_f32(_r_t4, _r_t4, 1); _r_t4 = vsetq_lane_f32(r4[4], _r_t4, 3); _sum2 = vmlaq_f32(_sum2, _r_t4, _k_t4); sum2 = r5[4] * k4[4]; float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum)); float32x2_t _ss2 = vadd_f32(vget_low_f32(_sum2), vget_high_f32(_sum2)); float32x2_t _ss_ss2 = vpadd_f32(_ss, _ss2); sum += vget_lane_f32(_ss_ss2, 0); sum2 += vget_lane_f32(_ss_ss2, 1); #else sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r0[3] * k0[3]; sum += r0[4] * k0[4]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r1[3] * k1[3]; sum += r1[4] * k1[4]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; sum += r2[3] * k2[3]; sum += r2[4] * k2[4]; sum += r3[0] * k3[0]; sum += r3[1] * k3[1]; sum += r3[2] * k3[2]; sum += r3[3] * k3[3]; sum += r3[4] * k3[4]; sum += r4[0] * k4[0]; sum += r4[1] * k4[1]; sum += r4[2] * k4[2]; sum += r4[3] * k4[3]; sum += r4[4] * k4[4]; sum2 += r1[0] * k0[0]; sum2 += r1[1] * k0[1]; sum2 += r1[2] * k0[2]; sum2 += r1[3] * k0[3]; sum2 += r1[4] * k0[4]; sum2 += r2[0] * k1[0]; sum2 += r2[1] * k1[1]; sum2 += r2[2] * k1[2]; sum2 += r2[3] * k1[3]; sum2 += r2[4] * k1[4]; sum2 += r3[0] * k2[0]; sum2 += r3[1] * k2[1]; sum2 += r3[2] * k2[2]; sum2 += r3[3] * k2[3]; sum2 += r3[4] * k2[4]; sum2 += r4[0] * k3[0]; sum2 += r4[1] * k3[1]; sum2 += r4[2] * k3[2]; sum2 += r4[3] * k3[3]; sum2 += r4[4] * k3[4]; sum2 += r5[0] * k4[0]; sum2 += r5[1] * k4[1]; sum2 += r5[2] * k4[2]; sum2 += r5[3] * k4[3]; sum2 += r5[4] * k4[4]; #endif // __ARM_NEON *outptr += sum; *outptr2 += sum2; r0++; r1++; r2++; r3++; r4++; r5++; outptr++; outptr2++; } r0 += 4 + w; r1 += 4 + w; r2 += 4 + w; r3 += 4 + w; r4 += 4 + w; r5 += 4 + w; outptr += outw; outptr2 += outw; } for (; i < outh; i++) { #if __ARM_NEON int nn = outw >> 2; int remain = outw - (nn << 2); #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%1, #128] \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v8.4s, v9.4s}, [%2] \n"// _r00 = vld1q_f32(r0+j); "add %2, %2, #16 \n" "0: \n" "ld1 {v7.4s}, [%1] \n"// _sum = vld1q_f32(outptr+j); "ext v10.16b, v8.16b, v9.16b, #4 \n" //_r01 "ext v11.16b, v8.16b, v9.16b, #8 \n" //_r02 "ext v12.16b, v8.16b, v9.16b, #12 \n" //_r03 "fmla v7.4s, v8.4s, %14.s[0] \n" "fmul v13.4s, v10.4s, %14.s[1] \n" "prfm pldl1keep, [%3, #256] \n" "fmul v14.4s, v11.4s, %14.s[2] \n" "fmul v15.4s, v12.4s, %14.s[3] \n" "fmla v7.4s, v9.4s, %15.s[0] \n" "ld1 {v8.4s, v9.4s}, [%3] \n" "add %3, %3, #16 \n" "ext v10.16b, v8.16b, v9.16b, #4 \n" //_r11 "ext v11.16b, v8.16b, v9.16b, #8 \n" //_r12 "ext v12.16b, v8.16b, v9.16b, #12 \n" //_r13 "fmla v7.4s, v8.4s, %15.s[1] \n" "fmla v13.4s, v10.4s, %15.s[2] \n" "prfm pldl1keep, [%4, #256] \n" "fmla v14.4s, v11.4s, %15.s[3] \n" "fmla v15.4s, v12.4s, %16.s[0] \n" "fmla v7.4s, v9.4s, %16.s[1] \n" "ld1 {v8.4s, v9.4s}, [%4] \n" "add %4, %4, #16 \n" "ext v10.16b, v8.16b, v9.16b, #4 \n" //_r21 "ext v11.16b, v8.16b, v9.16b, #8 \n" //_r22 "ext v12.16b, v8.16b, v9.16b, #12 \n" //_r23 "fmla v7.4s, v8.4s, %16.s[2] \n" "fmla v13.4s, v10.4s, %16.s[3] \n" "prfm pldl1keep, [%5, #256] \n" "fmla v14.4s, v11.4s, %17.s[0] \n" "fmla v15.4s, v12.4s, %17.s[1] \n" "fmla v7.4s, v9.4s, %17.s[2] \n" "ld1 {v8.4s, v9.4s}, [%5] \n" "add %5, %5, #16 \n" "ext v10.16b, v8.16b, v9.16b, #4 \n" //_r31 "ext v11.16b, v8.16b, v9.16b, #8 \n" //_r32 "ext v12.16b, v8.16b, v9.16b, #12 \n" //_r33 "fmla v7.4s, v8.4s, %17.s[3] \n" "fmla v13.4s, v10.4s, %18.s[0] \n" "prfm pldl1keep, [%6, #256] \n" "fmla v14.4s, v11.4s, %18.s[1] \n" "fmla v15.4s, v12.4s, %18.s[2] \n" "fmla v7.4s, v9.4s, %18.s[3] \n" "ld1 {v8.4s, v9.4s}, [%6] \n" "add %6, %6, #16 \n" "ext v10.16b, v8.16b, v9.16b, #4 \n" //_r41 "ext v11.16b, v8.16b, v9.16b, #8 \n" //_r42 "ext v12.16b, v8.16b, v9.16b, #12 \n" //_r43 "fmla v7.4s, v8.4s, %19.s[0] \n" "fmla v13.4s, v10.4s, %19.s[1] \n" "fmla v14.4s, v11.4s, %19.s[2] \n" "fmla v15.4s, v12.4s, %19.s[3] \n" "fmla v7.4s, v9.4s, %20.s[0] \n" "fadd v14.4s, v14.4s, v15.4s \n" "fadd v7.4s, v7.4s, v13.4s \n" "prfm pldl1keep, [%2, #256] \n" "fadd v7.4s, v7.4s, v14.4s \n" "ld1 {v8.4s, v9.4s}, [%2] \n" "add %2, %2, #16 \n" "st1 {v7.4s}, [%1], #16 \n" "prfm pldl1keep, [%1, #128] \n" "subs %w0, %w0, #1 \n" "bne 0b \n" "sub %2, %2, #16 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2), // %4 "=r"(r3), // %5 "=r"(r4) // %6 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "5"(r3), "6"(r4), "w"(_k0123), // %14 "w"(_k4567), // %15 "w"(_k891011), // %16 "w"(_k12131415), // %17 "w"(_k16171819), // %18 "w"(_k20212223), // %19 "w"(_k24242424) // %20 : "cc", "memory", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15" ); } #else if (nn > 0) { asm volatile( // "veor q15, q15 \n"// _sum3 = 0; "pld [%1, #128] \n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2] \n"// _r00 = vld1q_f32(r0+j); "add %2, #16 \n" "0: \n" "vld1.f32 {d14-d15}, [%1] \n"// _sum = vld1q_f32(outptr+j); // "veor q13, q13 \n"// _sum2 = 0; // "veor q14, q14 \n"// _sum3 = 0; "vext.32 q10, q8, q9, #1 \n"// _r01 "vext.32 q11, q8, q9, #2 \n"// _r02 "vext.32 q12, q8, q9, #3 \n"// _r03 "vmla.f32 q7, q8, %e14[0] \n" "vmul.f32 q13, q10, %e14[1] \n" "pld [%3, #256] \n" "vmul.f32 q14, q11, %f14[0] \n" "vmul.f32 q15, q12, %f14[1] \n" "vmla.f32 q7, q9, %e15[0] \n" "vld1.f32 {d16-d19}, [%3] \n" "add %3, #16 \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vext.32 q12, q8, q9, #3 \n" "vmla.f32 q7, q8, %e15[1] \n" "vmla.f32 q13, q10, %f15[0] \n" "pld [%4, #256] \n" "vmla.f32 q14, q11, %f15[1] \n" "vmla.f32 q15, q12, %e16[0] \n" "vmla.f32 q7, q9, %e16[1] \n" "vld1.f32 {d16-d19}, [%4] \n" "add %4, #16 \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vext.32 q12, q8, q9, #3 \n" "vmla.f32 q7, q8, %f16[0] \n" "vmla.f32 q13, q10, %f16[1] \n" "pld [%5, #256] \n" "vmla.f32 q14, q11, %e17[0] \n" "vmla.f32 q15, q12, %e17[1] \n" "vmla.f32 q7, q9, %f17[0] \n" "vld1.f32 {d16-d19}, [%5] \n" "add %5, #16 \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vext.32 q12, q8, q9, #3 \n" "vmla.f32 q7, q8, %f17[1] \n" "vmla.f32 q13, q10, %e18[0] \n" "pld [%6, #256] \n" "vmla.f32 q14, q11, %e18[1] \n" "vmla.f32 q15, q12, %f18[0] \n" "vmla.f32 q7, q9, %f18[1] \n" "vld1.f32 {d16-d19}, [%6] \n" "add %6, #16 \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vext.32 q12, q8, q9, #3 \n" "vmla.f32 q7, q8, %e19[0] \n" "vmla.f32 q13, q10, %e19[1] \n" "vmla.f32 q14, q11, %f19[0] \n" "vmla.f32 q15, q12, %f19[1] \n" "vmla.f32 q7, q9, %e20[0] \n" "vadd.f32 q14, q14, q15 \n" "vadd.f32 q7, q7, q13 \n" // "veor q15, q15 \n"// _sum3 = 0; "pld [%2, #256] \n" "vadd.f32 q7, q7, q14 \n" "vld1.f32 {d16-d19}, [%2] \n"// _r00 = vld1q_f32(r0+j); "add %2, #16 \n" "vst1.f32 {d14-d15}, [%1]! \n" "pld [%1, #128] \n" "subs %0, #1 \n" "bne 0b \n" "sub %2, #16 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2), // %4 "=r"(r3), // %5 "=r"(r4) // %6 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "5"(r3), "6"(r4), "w"(_k0123), // %14 "w"(_k4567), // %15 "w"(_k891011), // %16 "w"(_k12131415), // %17 "w"(_k16171819), // %18 "w"(_k20212223), // %19 "w"(_k24242424) // %20 : "cc", "memory", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { float sum = 0; #if __ARM_NEON float32x4_t _r0 = vld1q_f32(r0); float32x4_t _sum = vmulq_f32(_r0, _k0123); float32x4_t _r1 = vld1q_f32(r1); _sum = vmlaq_f32(_sum, _r1, vld1q_f32(k1)); float32x4_t _r2 = vld1q_f32(r2); _sum = vmlaq_f32(_sum, _r2, vld1q_f32(k2)); float32x4_t _r3 = vld1q_f32(r3); _sum = vmlaq_f32(_sum, _r3, vld1q_f32(k3)); float32x4_t _r4 = vld1q_f32(r4); _sum = vmlaq_f32(_sum, _r4, _k20212223); float32x4_t _k_t4; _k_t4 = vsetq_lane_f32(k0[4], _k_t4, 0); _k_t4 = vsetq_lane_f32(k1[4], _k_t4, 1); _k_t4 = vsetq_lane_f32(k2[4], _k_t4, 2); _k_t4 = vsetq_lane_f32(k3[4], _k_t4, 3); float32x4_t _r_t4; _r_t4 = vsetq_lane_f32(r0[4], _r_t4, 0); _r_t4 = vsetq_lane_f32(r1[4], _r_t4, 1); _r_t4 = vsetq_lane_f32(r2[4], _r_t4, 2); _r_t4 = vsetq_lane_f32(r3[4], _r_t4, 3); _sum = vmlaq_f32(_sum, _r_t4, _k_t4); sum = r4[4] * k4[4]; float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum)); _ss = vpadd_f32(_ss, _ss); sum += vget_lane_f32(_ss, 0); #else sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r0[3] * k0[3]; sum += r0[4] * k0[4]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r1[3] * k1[3]; sum += r1[4] * k1[4]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; sum += r2[3] * k2[3]; sum += r2[4] * k2[4]; sum += r3[0] * k3[0]; sum += r3[1] * k3[1]; sum += r3[2] * k3[2]; sum += r3[3] * k3[3]; sum += r3[4] * k3[4]; sum += r4[0] * k4[0]; sum += r4[1] * k4[1]; sum += r4[2] * k4[2]; sum += r4[3] * k4[3]; sum += r4[4] * k4[4]; #endif *outptr += sum; r0++; r1++; r2++; r3++; r4++; outptr++; } r0 += 4; r1 += 4; r2 += 4; r3 += 4; r4 += 4; } } } } static void conv5x5s2_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2*outw + w; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for for (int p=0; p<outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); for (int q=0; q<inch; q++) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p*inch*25 + q*25; const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w*2; const float* r3 = img0 + w*3; const float* r4 = img0 + w*4; const float* k0 = kernel0; const float* k1 = kernel0 + 5; const float* k2 = kernel0 + 10; const float* k3 = kernel0 + 15; const float* k4 = kernel0 + 20; #if __ARM_NEON float32x4_t _k0123 = vld1q_f32(kernel0); float32x4_t _k4567 = vld1q_f32(kernel0+4); float32x4_t _k891011 = vld1q_f32(kernel0+8); float32x4_t _k12131415 = vld1q_f32(kernel0+12); float32x4_t _k16171819 = vld1q_f32(kernel0+16); float32x4_t _k20212223 = vld1q_f32(kernel0+20); float32x4_t _k24242424 = vdupq_n_f32(kernel0[24]); #endif // __ARM_NEON for (int i = 0; i < outh; i++) { #if __ARM_NEON int nn = outw >> 2; int remain = outw - (nn << 2); #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%2, #256] \n" "ld2 {v8.4s, v9.4s}, [%2], #32 \n"// v8 = 0 2 4 6 q9 = 1 3 5 7 "prfm pldl1keep, [%2, #256] \n" "ld2 {v10.4s, v11.4s}, [%2] \n"// v10 = 8 10 12 14 v11 = 9 11 13 15 "prfm pldl1keep, [%1, #128] \n" "0: \n" "ld1 {v7.4s}, [%1] \n" // v7 = outptr "ext v12.16b, v8.16b, v10.16b, #4 \n" // v12 = 2 4 6 8 "ext v11.16b, v9.16b, v11.16b, #4 \n" // v11 = 3 5 7 9 "ext v10.16b, v8.16b, v10.16b, #8 \n" // v10 = 4 6 8 10 "fmla v7.4s, v8.4s, %14.s[0] \n" "fmul v13.4s, v9.4s, %14.s[1] \n" "prfm pldl1keep, [%3, #256] \n" "fmul v14.4s, v12.4s, %14.s[2] \n" "fmul v15.4s, v11.4s, %14.s[3] \n" "fmla v7.4s, v10.4s, %15.s[0] \n" "ld2 {v8.4s, v9.4s}, [%3], #32 \n" "prfm pldl1keep, [%3, #256] \n" "ld2 {v10.4s, v11.4s}, [%3] \n" "ext v12.16b, v8.16b, v10.16b, #4 \n" "ext v11.16b, v9.16b, v11.16b, #4 \n" "ext v10.16b, v8.16b, v10.16b, #8 \n" "fmla v7.4s, v8.4s, %15.s[1] \n" "fmla v13.4s, v9.4s, %15.s[2] \n" "prfm pldl1keep, [%4, #256] \n" "fmla v14.4s, v12.4s, %15.s[3] \n" "fmla v15.4s, v11.4s, %16.s[0] \n" "fmla v7.4s, v10.4s, %16.s[1] \n" "ld2 {v8.4s, v9.4s}, [%4], #32 \n" "prfm pldl1keep, [%4, #256] \n" "ld2 {v10.4s, v11.4s}, [%4] \n" "ext v12.16b, v8.16b, v10.16b, #4 \n" "ext v11.16b, v9.16b, v11.16b, #4 \n" "ext v10.16b, v8.16b, v10.16b, #8 \n" "fmla v7.4s, v8.4s, %16.s[2] \n" "fmla v13.4s, v9.4s, %16.s[3] \n" "prfm pldl1keep, [%5, #256] \n" "fmla v14.4s, v12.4s, %17.s[0] \n" "fmla v15.4s, v11.4s, %17.s[1] \n" "fmla v7.4s, v10.4s, %17.s[2] \n" "ld2 {v8.4s, v9.4s}, [%5], #32 \n" "prfm pldl1keep, [%5, #256] \n" "ld2 {v10.4s, v11.4s}, [%5] \n" "ext v12.16b, v8.16b, v10.16b, #4 \n" "ext v11.16b, v9.16b, v11.16b, #4 \n" "ext v10.16b, v8.16b, v10.16b, #8 \n" "fmla v7.4s, v8.4s, %17.s[3] \n" "fmla v13.4s, v9.4s, %18.s[0] \n" "prfm pldl1keep, [%6, #256] \n" "fmla v14.4s, v12.4s, %18.s[1] \n" "fmla v15.4s, v11.4s, %18.s[2] \n" "fmla v7.4s, v10.4s, %18.s[3] \n" "ld2 {v8.4s, v9.4s}, [%6], #32 \n" "prfm pldl1keep, [%6, #256] \n" "ld2 {v10.4s, v11.4s}, [%6] \n" "ext v12.16b, v8.16b, v10.16b, #4 \n" "ext v11.16b, v9.16b, v11.16b, #4 \n" "ext v10.16b, v8.16b, v10.16b, #8 \n" "fmla v7.4s, v8.4s, %19.s[0] \n" "fmla v13.4s, v9.4s, %19.s[1] \n" "fmla v14.4s, v12.4s, %19.s[2] \n" "fmla v15.4s, v11.4s, %19.s[3] \n" "fmla v7.4s, v10.4s, %20.s[0] \n" "prfm pldl1keep, [%2, #256] \n" "ld2 {v8.4s, v9.4s}, [%2], #32 \n" "fadd v14.4s, v14.4s, v15.4s \n" "fadd v7.4s, v7.4s, v13.4s \n" "prfm pldl1keep, [%2, #256] \n" "fadd v7.4s, v7.4s, v14.4s \n" "ld2 {v10.4s, v11.4s}, [%2] \n" "st1 {v7.4s}, [%1], #16 \n" "prfm pldl1keep, [%1, #128] \n" "subs %w0, %w0, #1 \n" "bne 0b \n" "sub %2, %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2), // %4 "=r"(r3), // %5 "=r"(r4) // %6 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "5"(r3), "6"(r4), "w"(_k0123), // %14 "w"(_k4567), // %15 "w"(_k891011), // %16 "w"(_k12131415), // %17 "w"(_k16171819), // %18 "w"(_k20212223), // %19 "w"(_k24242424) // %20 : "cc", "memory", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15" ); } #else if (nn > 0) { asm volatile( // "veor q15, q15 \n"// _sump3 = 0; // "veor q13, q13 \n"// _sump2 = 0; // "veor q14, q14 \n"// _sump3 = 0; "pld [%2, #256] \n" "vld2.f32 {d16-d19}, [%2]! \n"// q8 = 0 2 4 6 q9 = 1 3 5 7 "pld [%2, #256] \n" "vld2.f32 {d20-d23}, [%2] \n"// q10 = 8 10 12 14 q11 = 9 11 13 15 "pld [%1, #128] \n" "0: \n" "vld1.f32 {d14-d15}, [%1] \n"// q7 = outptr "vext.32 q12, q8, q10, #1 \n"// q12 = 2 4 6 8 "vext.32 q11, q9, q11, #1 \n"// q11 = 3 5 7 9 "vext.32 q10, q8, q10, #2 \n"// q10 = 4 6 8 10 "vmla.f32 q7, q8, %e14[0] \n" "vmul.f32 q13, q9, %e14[1] \n" "pld [%3, #256] \n" "vmul.f32 q14, q12, %f14[0] \n" "vmul.f32 q15, q11, %f14[1] \n" "vmla.f32 q7, q10, %e15[0] \n" "vld2.f32 {d16-d19}, [%3]! \n" "pld [%3, #256] \n" "vld2.f32 {d20-d23}, [%3] \n" "vext.32 q12, q8, q10, #1 \n" "vext.32 q11, q9, q11, #1 \n" "vext.32 q10, q8, q10, #2 \n" "vmla.f32 q7, q8, %e15[1] \n" "vmla.f32 q13, q9, %f15[0] \n" "pld [%4, #256] \n" "vmla.f32 q14, q12, %f15[1] \n" "vmla.f32 q15, q11, %e16[0] \n" "vmla.f32 q7, q10, %e16[1] \n" "vld2.f32 {d16-d19}, [%4]! \n" "pld [%4, #256] \n" "vld2.f32 {d20-d23}, [%4] \n" "vext.32 q12, q8, q10, #1 \n" "vext.32 q11, q9, q11, #1 \n" "vext.32 q10, q8, q10, #2 \n" "vmla.f32 q7, q8, %f16[0] \n" "vmla.f32 q13, q9, %f16[1] \n" "pld [%5, #256] \n" "vmla.f32 q14, q12, %e17[0] \n" "vmla.f32 q15, q11, %e17[1] \n" "vmla.f32 q7, q10, %f17[0] \n" "vld2.f32 {d16-d19}, [%5]! \n" "pld [%5, #256] \n" "vld2.f32 {d20-d23}, [%5] \n" "vext.32 q12, q8, q10, #1 \n" "vext.32 q11, q9, q11, #1 \n" "vext.32 q10, q8, q10, #2 \n" "vmla.f32 q7, q8, %f17[1] \n" "vmla.f32 q13, q9, %e18[0] \n" "pld [%6, #256] \n" "vmla.f32 q14, q12, %e18[1] \n" "vmla.f32 q15, q11, %f18[0] \n" "vmla.f32 q7, q10, %f18[1] \n" "vld2.f32 {d16-d19}, [%6]! \n" "pld [%6, #256] \n" "vld2.f32 {d20-d23}, [%6] \n" "vext.32 q12, q8, q10, #1 \n" "vext.32 q11, q9, q11, #1 \n" "vext.32 q10, q8, q10, #2 \n" "vmla.f32 q7, q8, %e19[0] \n" "vmla.f32 q13, q9, %e19[1] \n" "vmla.f32 q14, q12, %f19[0] \n" "vmla.f32 q15, q11, %f19[1] \n" "vmla.f32 q7, q10, %e20[0] \n" "pld [%2, #256] \n" "vld2.f32 {d16-d19}, [%2]! \n"// q8 = 0 2 4 6 q9 = 1 3 5 7 "vadd.f32 q14, q14, q15 \n" "vadd.f32 q7, q7, q13 \n" // "veor q15, q15 \n"// _sump3 = 0; // "veor q13, q13 \n"// _sump2 = 0; "pld [%2, #256] \n" "vadd.f32 q7, q7, q14 \n" "vld2.f32 {d20-d23}, [%2] \n"// q10 = 8 10 12 14 q11 = 9 11 13 15 // "veor q14, q14 \n"// _sump3 = 0; "vst1.f32 {d14-d15}, [%1]! \n" "pld [%1, #128] \n" "subs %0, #1 \n" "bne 0b \n" "sub %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2), // %4 "=r"(r3), // %5 "=r"(r4) // %6 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "5"(r3), "6"(r4), "w"(_k0123), // %14 "w"(_k4567), // %15 "w"(_k891011), // %16 "w"(_k12131415), // %17 "w"(_k16171819), // %18 "w"(_k20212223), // %19 "w"(_k24242424) // %20 : "cc", "memory", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { float sum = 0; #if __ARM_NEON float32x4_t _r0 = vld1q_f32(r0); float32x4_t _sum = vmulq_f32(_r0, _k0123); float32x4_t _r1 = vld1q_f32(r1); _sum = vmlaq_f32(_sum, _r1, vld1q_f32(k1)); float32x4_t _r2 = vld1q_f32(r2); _sum = vmlaq_f32(_sum, _r2, vld1q_f32(k2)); float32x4_t _r3 = vld1q_f32(r3); _sum = vmlaq_f32(_sum, _r3, vld1q_f32(k3)); float32x4_t _r4 = vld1q_f32(r4); _sum = vmlaq_f32(_sum, _r4, _k20212223); sum += r0[4] * k0[4]; sum += r1[4] * k1[4]; sum += r2[4] * k2[4]; sum += r3[4] * k3[4]; sum += r4[4] * k4[4]; float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum)); _ss = vpadd_f32(_ss, _ss); sum += vget_lane_f32(_ss, 0); #else sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r0[3] * k0[3]; sum += r0[4] * k0[4]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r1[3] * k1[3]; sum += r1[4] * k1[4]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; sum += r2[3] * k2[3]; sum += r2[4] * k2[4]; sum += r3[0] * k3[0]; sum += r3[1] * k3[1]; sum += r3[2] * k3[2]; sum += r3[3] * k3[3]; sum += r3[4] * k3[4]; sum += r4[0] * k4[0]; sum += r4[1] * k4[1]; sum += r4[2] * k4[2]; sum += r4[3] * k4[3]; sum += r4[4] * k4[4]; #endif *outptr += sum; r0 += 2; r1 += 2; r2 += 2; r3 += 2; r4 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; r3 += tailstep; r4 += tailstep; } } } }
grade.h
#ifndef __GRADE_H__ #define __GRADE_H__ #include <stdio.h> #include <sstream> #include <iomanip> #include <chrono> #include <type_traits> #include <utility> #include <float.h> #include <omp.h> #include "mic.h" #include "graph.h" #include "graph_internal.h" #include "parse_args.h" #include "contracts.h" // Epsilon for approximate float comparisons #define EPSILON 0.001f // Output column size #define COL_SIZE 15 // Number of points for each runtime matching the original ref runtime. #define EXTRA_CREDIT 0.3 /* * Reference times on the phi * For grading student performance when the reference is not run. * Indexed by [APP][graph][number of threads (64, 128, 236)] */ // TODO(kku): Ugly hard-coded size // Adjusted reference time static double refTimeTable[4][4][3] = { // BFS { // com-orkut_117m.graph { 0.2235 , 0.1637 , 0.2415 }, // soc-livejournal1_68m { 0.3734 , 0.3135 , 0.4057 }, // rmat_200m { 2.1021 , 1.6171 , 1.5956 }, // soc-pokec_30m { 0.2081 , 0.1939 , 0.2924 } }, // PAGERANK { // com-orkut_117m.graph { 3.8533 , 2.2470 , 1.5512 }, // soc-livejournal1_68m { 2.2999 , 1.3957 , 1.0575 }, // rmat_200m { 13.5453 , 8.3121 , 6.1407 }, // soc-pokec_30m { 1.2403 , 0.7041 , 0.4984 } }, // KBFS { // com-orkut_117m.graph { 41.7699 , 26.3132 , 19.4586 }, // soc-livejournal1_68m { 10.3742 , 8.3289 , 8.0807 }, // rmat_200m { 67.6248 , 52.2105 , 47.1388 }, // soc-pokec_30m { 4.5007 , 3.5232 , 3.2306 } }, // DECOMP { // com-orkut_117m.graph { 3.0258 , 2.4040 , 2.1483 }, // soc-livejournal1_68m { 3.0444 , 2.7236 , 2.6725 }, // rmat_200m { 21.8837 , 18.8862 , 17.9954 }, // soc-pokec_30m { 1.2287 , 1.0783 , 1.0672 } } }; // Original reference time used for extra credit. static double refExtraTimeTable[4][4][3] = { // BFS { // com-orkut_117m.graph {0.2078, 0.1357, 0.2209}, // adjusted // soc-livejournal1_68m {0.2347, 0.2123, 0.2704}, // rmat_200m {1.5444, 1.0811, 1.0658}, // soc-pokec_30m {0.1962, 0.1760, 0.2879} // adjusted }, // PAGERANK { // com-orkut_117m.graph {3.5203, 2.0160, 1.3421}, // adjusted // soc-livejournal1_68m {1.9369, 1.1051, 0.7757}, // rmat_200m {11.3733, 6.3221, 4.3275}, // soc-pokec_30m {1.1019, 0.6059, 0.4016} // adjusted }, // KBFS { // com-orkut_117m.graph {39.9503, 25.5576, 18.8067}, // adjusted // soc-livejournal1_68m {9.8073, 7.9282, 7.6994}, // adjusted // rmat_200m {66.0763, 49.6047, 44.6521}, // soc-pokec_30m {4.3053, 3.4722, 3.1474} }, // DECOMP { // com-orkut_117m.graph {2.9623, 2.3680, 2.1731}, // soc-livejournal1_68m {2.9650, 2.6828, 2.6310}, // rmat_200m {20.4276, 18.0206, 17.2282}, // soc-pokec_30m {1.1637, 1.0159, 1.0074} } }; // Get index into refTimeTable for a given number of threads. static int getThreadIndex(int numThreads) { if (numThreads == 64) return 0; else if (numThreads == 128) return 1; return 2; } // Get index into refTimeTable for a given graph. static int getGraphIndex(Graph g) { // com-orkut_117m.graph if (num_nodes(g) == 3072441) return 0; // soc-livejournal1_68m if (num_nodes(g) == 4847571) return 1; // rmat_200m if (num_nodes(g) == 33554432) return 2; // soc-pokec_30m if (num_nodes(g) == 1632803) return 3; // Should not get here. ENSURES(false); return -1; } /* * Printing functions */ static void sep(std::ostream& out, char separator = '-', int length = 78) { for (int i = 0; i < length; i++) out << separator; out << std::endl; } static void printTimingApp(std::ostream& timing, const char* appName) { std::cout << std::endl; std::cout << "Timing results for " << appName << ":" << std::endl; sep(std::cout, '=', 75); timing << std::endl; timing << "Timing results for " << appName << ":" << std::endl; sep(timing, '=', 75); } /* * Correctness checkers */ template <class T> bool compareArrays(Graph graph, T* ref, T* stu) { for (int i = 0; i < graph->num_nodes; i++) { if (ref[i] != stu[i]) { std::cerr << "*** Results disagree at " << i << " expected " << ref[i] << " found " << stu[i] << std::endl; return false; } } return true; } template <class T> bool compareApprox(Graph graph, T* ref, T* stu) { for (int i = 0; i < graph->num_nodes; i++) { if (fabs(ref[i] - stu[i]) > EPSILON) { std::cerr << "*** Results disagree at " << i << " expected " << ref[i] << " found " << stu[i] << std::endl; return false; } } return true; } template <class T> bool compareArraysAndDisplay(Graph graph, T* ref, T*stu) { printf("\n----------------------------------\n"); printf("Visualization of student results"); printf("\n----------------------------------\n\n"); int grid_dim = (int)sqrt(graph->num_nodes); for (int j=0; j<grid_dim; j++) { for (int i=0; i<grid_dim; i++) { printf("%02d ", stu[j*grid_dim + i]); } printf("\n"); } printf("\n----------------------------------\n"); printf("Visualization of reference results"); printf("\n----------------------------------\n\n"); grid_dim = (int)sqrt(graph->num_nodes); for (int j=0; j<grid_dim; j++) { for (int i=0; i<grid_dim; i++) { printf("%02d ", ref[j*grid_dim + i]); } printf("\n"); } return compareArrays<T>(graph, ref, stu); } template <class T> bool compareArraysAndRadiiEst(Graph graph, T* ref, T* stu) { bool isCorrect = true; for (int i = 0; i < graph->num_nodes; i++) { if (ref[i] != stu[i]) { std::cerr << "*** Results disagree at " << i << " expected " << ref[i] << " found " << stu[i] << std::endl; isCorrect = false; } } int stuMaxVal = -1; int refMaxVal = -1; #pragma omp parallel for schedule(dynamic, 512) reduction(max: stuMaxVal) for (int i = 0; i < graph->num_nodes; i++) { if (stu[i] > stuMaxVal) stuMaxVal = stu[i]; } #pragma omp parallel for schedule(dynamic, 512) reduction(max: refMaxVal) for (int i = 0; i < graph->num_nodes; i++) { if (ref[i] > refMaxVal) refMaxVal = ref[i]; } if (refMaxVal != stuMaxVal) { std::cerr << "*** Radius estimates differ. Expected: " << refMaxVal << " Got: " << stuMaxVal << std::endl; isCorrect = false; } return isCorrect; } /* * Time and score an app */ // Returns score for the app. template<typename T, App APP> double timeApp(Graph g, int device, int numTrials, double maxPoints, int minThreadCount, int maxThreadCount, void (*ref)(Graph, T*), void (*stu)(Graph, T*), bool (*check)(Graph, T*, T*), bool runRef, bool runStu, std::ostream& timing) { timing << std::left << std::setw(COL_SIZE) << "Threads"; timing << std::left << std::setw(COL_SIZE) << "Ref. Time"; timing << std::left << std::setw(COL_SIZE) << "Ref. Speedup"; if (runStu) { timing << std::left << std::setw(COL_SIZE) << "Your Time"; timing << std::left << std::setw(COL_SIZE) << "Your Speedup"; } timing << std::endl; sep(timing, '-', 75); std::cout << std::left << std::setw(COL_SIZE) << "Threads"; std::cout << std::left << std::setw(COL_SIZE) << "Ref. Time"; std::cout << std::left << std::setw(COL_SIZE) << "Ref. Speedup"; if (runStu) { std::cout << std::left << std::setw(COL_SIZE) << "Your Time"; std::cout << std::left << std::setw(COL_SIZE) << "Your Speedup"; } std::cout << std::endl; sep(std::cout, '-', 75); using namespace std::chrono; typedef std::chrono::high_resolution_clock Clock; typedef std::chrono::duration<double> dsec; int precision = 4; T* refSolution = new T [g->num_nodes]; T* stuSolution = new T [g->num_nodes]; bool firstTimeDone = false; double refOneThreadTime = 0; double stuOneThreadTime = 0; bool correct = true; double refBestTime = DBL_MAX; double stuBestTime = DBL_MAX; int threads = minThreadCount; while (true) { double refTime = 0; double stuTime = 0; for (int i = 0; i < numTrials; i++) { #pragma offload target(mic: device) omp_set_num_threads(threads); if (runRef) { auto refStart = Clock::now(); ref(g, refSolution); refTime += duration_cast<dsec>(Clock::now() - refStart).count(); } else { refTime += refTimeTable[APP][getGraphIndex(g)][getThreadIndex(threads)]; } if (runStu) { auto stuStart = Clock::now(); stu(g, stuSolution); stuTime += duration_cast<dsec>(Clock::now() - stuStart).count(); } else { stuTime += 1; } if (runRef && runStu) { correct = correct && check(g, refSolution, stuSolution); if (!correct) break; } } refTime /= numTrials; stuTime /= numTrials; if (!firstTimeDone) { firstTimeDone = true; refOneThreadTime = refTime; stuOneThreadTime = stuTime; } refBestTime = std::min(refBestTime, refTime); stuBestTime = std::min(stuBestTime, stuTime); double refSpeedup = refOneThreadTime / refTime; double stuSpeedup = stuOneThreadTime / stuTime; timing << std::right << std::setw(7) << threads; timing << std::left << std::setw(COL_SIZE - 7) << ""; timing << std::setprecision(precision) << std::fixed; timing << std::left << std::setw(COL_SIZE) << refTime; timing << std::setprecision(precision) << std::fixed; timing << std::left << std::setw(COL_SIZE) << refSpeedup; if (runStu) { timing << std::setprecision(precision) << std::fixed; timing << std::left << std::setw(COL_SIZE) << stuTime; timing << std::setprecision(precision) << std::fixed; timing << std::left << std::setw(COL_SIZE) << stuSpeedup; } timing << std::endl; std::cout << std::right << std::setw(7) << threads; std::cout << std::left << std::setw(COL_SIZE - 7) << ""; std::cout << std::setprecision(precision) << std::fixed; std::cout << std::left << std::setw(COL_SIZE) << refTime; std::cout << std::setprecision(precision) << std::fixed; std::cout << std::left << std::setw(COL_SIZE) << refSpeedup; if (runStu) { std::cout << std::setprecision(precision) << std::fixed; std::cout << std::left << std::setw(COL_SIZE) << stuTime; std::cout << std::setprecision(precision) << std::fixed; std::cout << std::left << std::setw(COL_SIZE) << stuSpeedup; } std::cout << std::endl; if (threads == maxThreadCount) break; threads = std::min(maxThreadCount, threads * 2); } delete[] refSolution; delete[] stuSolution; /* Print and return grade */ double fraction = stuBestTime / refBestTime * 100.0; double curve = 4.0 / 3.0 * (refBestTime / stuBestTime) - (1.0 / 3.0); double points = std::min(maxPoints, std::max(maxPoints * curve, 0.0)); points = (correct) ? points : 0.0; // Calculate extra credit double refExtraBestTime = DBL_MAX; if (!runRef) { for (int i = minThreadCount; i <= maxThreadCount; i = std::min(maxThreadCount, i * 2)) { refExtraBestTime = std::min(refExtraBestTime, refExtraTimeTable[APP][getGraphIndex(g)][getThreadIndex(i)]); if (i == maxThreadCount) break; } } else { refExtraBestTime = refBestTime; } if (correct && stuBestTime <= refExtraBestTime) points += EXTRA_CREDIT; sep(timing, '-', 75); timing << "Time: " << std::setprecision(2) << std::fixed << fraction << '%' << " of reference solution."; if (correct) { timing << " Grade: " << std::fixed << std::setprecision(2) << points << std::endl; if (stuBestTime <= refExtraBestTime) timing << "EXTRA CREDIT" << std::endl; } else { timing << " Grade: " << std::fixed << std::setprecision(2) << "INCORRECT" << std::endl; } sep(timing, '-', 75); sep(std::cout, '-', 75); std::cout << "Time: " << std::setprecision(2) << std::fixed << fraction << '%' << " of reference solution."; if (correct) { std::cout << " Grade: " << std::fixed << std::setprecision(2) << points << std::endl; if (stuBestTime <= refExtraBestTime) std::cout << "EXTRA CREDIT" << std::endl; } else { std::cout << " Grade: " << std::fixed << std::setprecision(2) << "INCORRECT" << std::endl; } sep(std::cout, '-', 75); #ifndef RUN_MIC if (!runRef) { timing << "WARNING: Reference time is based on MIC execution." << std::endl; std::cout << "WARNING: Reference time is based on MIC execution." << std::endl; } #endif return points; } #endif /* __GRADE_H__ */
3d7pt_var.c
/* * Order-1, 3D 7 point stencil with variable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*7); for(m=0; m<7;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 32; tile_size[1] = 32; tile_size[2] = 8; 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; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<7; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt-1; t++) { for (i = 1; i < Nz-1; i++) { for (j = 1; j < Ny-1; j++) { for (k = 1; k < Nx-1; k++) { A[(t+1)%2][i][j][k] = coef[0][i][j][k] * A[t%2][i ][j ][k ] + coef[1][i][j][k] * A[t%2][i-1][j ][k ] + coef[2][i][j][k] * A[t%2][i ][j-1][k ] + coef[3][i][j][k] * A[t%2][i ][j ][k-1] + coef[4][i][j][k] * A[t%2][i+1][j ][k ] + coef[5][i][j][k] * A[t%2][i ][j+1][k ] + coef[6][i][j][k] * A[t%2][i ][j ][k+1]; } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "variable no-symmetry") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<7;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
sampler.h
// Copyright (c) 2015-2017 Contibutors. // Author: Yafei Zhang (zhangyafeikimi@gmail.com) // // sampler and inference // #ifndef SAMPLER_H_ #define SAMPLER_H_ #include <math.h> #include <string> #include <vector> #include "alias.h" #include "model.h" #include "table.h" #include "x.h" /************************************************************************/ /* Sampler */ /************************************************************************/ template <class Tables> class Sampler : public Model<Tables> { protected: typedef Model<Tables> BaseType; using BaseType::docs_; using BaseType::words_; using BaseType::M_; using BaseType::V_; using BaseType::K_; using BaseType::topics_count_; using BaseType::docs_topics_count_; using BaseType::words_topics_count_; using BaseType::hp_alpha_; using BaseType::hp_sum_alpha_; using BaseType::hp_beta_; using BaseType::hp_sum_beta_; using BaseType::random_; using BaseType::Init; // hyper parameters optimizations int hp_opt_; int hp_opt_interval_; double hp_opt_alpha_shape_; double hp_opt_alpha_scale_; int hp_opt_alpha_iteration_; int hp_opt_beta_iteration_; // hp_opt_docs_topic_count_hist_[k][n]: // # of documents in which topic "k" occurs "n" times. std::vector<std::vector<int> > hp_opt_docs_topic_count_hist_; // hp_opt_doc_len_hist_[n]: // # of documents whose length are "n". std::vector<int> hp_opt_doc_len_hist_; // hp_opt_word_topic_count_hist_[n]: // # of words which are assigned to a topic "n" times. std::vector<int> hp_opt_word_topic_count_hist_; // hp_opt_topic_len_hist_a[n]: // # of topics which occurs "n" times. std::vector<int> hp_opt_topic_len_hist_a; // iteration variables int total_iteration_; int burnin_iteration_; int log_likelihood_interval_; int iteration_; public: typedef Tables TablesType; typedef typename TablesType::TableType TableType; Sampler() : hp_opt_(0), hp_opt_interval_(0), hp_opt_alpha_shape_(0.0), hp_opt_alpha_scale_(0.0), hp_opt_alpha_iteration_(0), hp_opt_beta_iteration_(0), total_iteration_(0), burnin_iteration_(0), log_likelihood_interval_(0), iteration_(0) {} int& hp_opt() { return hp_opt_; } int& hp_opt_interval() { return hp_opt_interval_; } double& hp_opt_alpha_shape() { return hp_opt_alpha_shape_; } double& hp_opt_alpha_scale() { return hp_opt_alpha_scale_; } int& hp_opt_alpha_iteration() { return hp_opt_alpha_iteration_; } int& hp_opt_beta_iteration() { return hp_opt_beta_iteration_; } int& total_iteration() { return total_iteration_; } int& burnin_iteration() { return burnin_iteration_; } int& log_likelihood_interval() { return log_likelihood_interval_; } virtual double LogLikelihood() const; virtual void Train(); virtual void PreSampleCorpus(); virtual void PostSampleCorpus(); virtual void SampleCorpus(); virtual void PreSampleDocument(int m); virtual void PostSampleDocument(int m); virtual void SampleDocument(int m); virtual void SampleDocument(Word* word, int doc_length, TableType* doc_topics_count); void HPOpt_Init(); void HPOpt_Optimize(); void HPOpt_OptimizeAlpha(); void HPOpt_PrepareOptimizeBeta(); void HPOpt_OptimizeBeta(); void HPOpt_PostSampleDocument(int m); bool HPOpt_Enabled() const { if (hp_opt_ && iteration_ > burnin_iteration_ && (iteration_ % hp_opt_interval_) == 0) { return true; } return false; } }; template <class Tables> double Sampler<Tables>::LogLikelihood() const { double sum = 0.0; #if defined _OPENMP #pragma omp parallel for schedule(static) reduction(+ : sum) #endif for (int m = 0; m < M_; m++) { const int N = docs_[m + 1] - docs_[m]; const Word* word = &words_[docs_[m]]; const auto& doc_topics_count = docs_topics_count_[m]; for (int n = 0; n < N; n++, word++) { const int v = word->v; const auto& word_topics_count = words_topics_count_[v]; double word_sum = 0.0; for (int k = 0; k < K_; k++) { const double phi_kv = (word_topics_count[k] + hp_beta_) / (topics_count_[k] + hp_sum_beta_); word_sum += (doc_topics_count[k] + hp_alpha_[k]) * phi_kv; } word_sum /= (N + hp_sum_alpha_); sum += log(word_sum); } } return sum; } template <class Tables> void Sampler<Tables>::Train() { INFO("Training begins."); Init(); for (iteration_ = 1; iteration_ <= total_iteration_; iteration_++) { INFO("Iteration %d begins.", iteration_); PreSampleCorpus(); SampleCorpus(); PostSampleCorpus(); if ((iteration_ > burnin_iteration_) && (iteration_ % log_likelihood_interval_ == 0)) { INFO("Calculating LogLikelihood."); const double llh = LogLikelihood(); INFO("LogLikelihood(total/word)=%lg/%lg.", llh, llh / words_.size()); } } INFO("Training ended."); } template <class Tables> void Sampler<Tables>::PreSampleCorpus() { HPOpt_Init(); } template <class Tables> void Sampler<Tables>::PostSampleCorpus() { HPOpt_Optimize(); } template <class Tables> void Sampler<Tables>::SampleCorpus() { for (int m = 0; m < M_; m++) { PreSampleDocument(m); SampleDocument(m); PostSampleDocument(m); } } template <class Tables> void Sampler<Tables>::PreSampleDocument(int m) {} template <class Tables> void Sampler<Tables>::PostSampleDocument(int m) { HPOpt_PostSampleDocument(m); } template <class Tables> void Sampler<Tables>::SampleDocument(int m) { const int N = docs_[m + 1] - docs_[m]; Word* word = &words_[docs_[m]]; auto& doc_topics_count = docs_topics_count_[m]; SampleDocument(word, N, &doc_topics_count); } template <class Tables> void Sampler<Tables>::SampleDocument(Word* word, int doc_length, TableType* doc_topics_count) {} template <class Tables> void Sampler<Tables>::HPOpt_Init() { if (!HPOpt_Enabled()) { return; } INFO("Hyper optimization will be carried out in this iteration."); hp_opt_docs_topic_count_hist_.clear(); hp_opt_docs_topic_count_hist_.resize(K_); hp_opt_doc_len_hist_.clear(); hp_opt_word_topic_count_hist_.clear(); hp_opt_topic_len_hist_a.clear(); } template <class Tables> void Sampler<Tables>::HPOpt_Optimize() { if (!HPOpt_Enabled()) { return; } if (hp_opt_alpha_iteration_ > 0) { INFO("Hyper optimizing alpha."); HPOpt_OptimizeAlpha(); } if (hp_opt_beta_iteration_ > 0) { INFO("Hyper optimizing beta."); HPOpt_PrepareOptimizeBeta(); HPOpt_OptimizeBeta(); } } template <class Tables> void Sampler<Tables>::HPOpt_OptimizeAlpha() { for (int i = 0; i < hp_opt_alpha_iteration_; i++) { double denom = 0; double diff_digamma = 0; for (int j = 1, size = static_cast<int>(hp_opt_doc_len_hist_.size()); j < size; j++) { diff_digamma += 1.0 / (j - 1 + hp_sum_alpha_); denom += hp_opt_doc_len_hist_[j] * diff_digamma; } denom -= 1.0 / hp_opt_alpha_scale_; hp_sum_alpha_ = 0; for (int k = 0, size = static_cast<int>(hp_opt_docs_topic_count_hist_.size()); k < size; k++) { double num = 0; double alpha_k = hp_alpha_[k]; const auto& docs_topic_k_count_hist = hp_opt_docs_topic_count_hist_[k]; diff_digamma = 0; for (int j = 1, size = static_cast<int>(hp_opt_docs_topic_count_hist_[k].size()); j < size; j++) { diff_digamma += 1.0 / (j - 1 + alpha_k); num += docs_topic_k_count_hist[j] * diff_digamma; } alpha_k = (alpha_k * num + hp_opt_alpha_shape_) / denom; hp_alpha_[k] = alpha_k; hp_sum_alpha_ += alpha_k; } } } template <class Tables> void Sampler<Tables>::HPOpt_PrepareOptimizeBeta() { for (int m = 0; m < M_; m++) { const auto& doc_topics_count = docs_topics_count_[m]; for (int k = 0; k < K_; k++) { const int count = doc_topics_count[k]; if (count == 0) { continue; } if (static_cast<int>(hp_opt_word_topic_count_hist_.size()) <= count) { hp_opt_word_topic_count_hist_.resize(count + 1); } hp_opt_word_topic_count_hist_[count]++; } } for (int k = 0; k < K_; k++) { const int count = topics_count_[k]; if (count == 0) { continue; } if (static_cast<int>(hp_opt_topic_len_hist_a.size()) <= count) { hp_opt_topic_len_hist_a.resize(count + 1); } hp_opt_topic_len_hist_a[count]++; } } template <class Tables> void Sampler<Tables>::HPOpt_OptimizeBeta() { for (int i = 0; i < hp_opt_beta_iteration_; i++) { double num = 0; double diff_digamma = 0; for (int j = 1, size = static_cast<int>(hp_opt_word_topic_count_hist_.size()); j < size; j++) { diff_digamma += 1.0 / (j - 1 + hp_beta_); num += diff_digamma * hp_opt_word_topic_count_hist_[j]; } double denom = 0; diff_digamma = 0; for (int j = 1, size = static_cast<int>(hp_opt_topic_len_hist_a.size()); j < size; j++) { diff_digamma += 1.0 / (j - 1 + hp_sum_beta_); denom += diff_digamma * hp_opt_topic_len_hist_a[j]; } hp_sum_beta_ = hp_beta_ * num / denom; hp_beta_ = hp_sum_beta_ / V_; } } template <class Tables> void Sampler<Tables>::HPOpt_PostSampleDocument(int m) { if (!HPOpt_Enabled()) { return; } if (hp_opt_alpha_iteration_ > 0) { const int N = docs_[m + 1] - docs_[m]; const auto& doc_topics_count = docs_topics_count_[m]; for (int k = 0; k < K_; k++) { const int count = doc_topics_count[k]; if (count == 0) { continue; } auto& docs_topic_k_count_hist = hp_opt_docs_topic_count_hist_[k]; if (static_cast<int>(docs_topic_k_count_hist.size()) <= count) { docs_topic_k_count_hist.resize(count + 1); } docs_topic_k_count_hist[count]++; } if (N > 0) { if (static_cast<int>(hp_opt_doc_len_hist_.size()) <= N) { hp_opt_doc_len_hist_.resize(N + 1); } hp_opt_doc_len_hist_[N]++; } } } /************************************************************************/ /* GibbsSampler */ /************************************************************************/ class GibbsSampler : public Sampler<HashTables> { private: std::vector<double> word_topic_cdf_; // cached public: GibbsSampler() {} virtual void Init() override; virtual void SampleDocument(Word* word, int doc_length, TableType* doc_topics_count) override; }; /************************************************************************/ /* SparseLDASampler */ /************************************************************************/ class SparseLDASampler : public Sampler<SparseTables> { private: double smooth_sum_; double doc_sum_; double word_sum_; std::vector<double> smooth_pdf_; std::vector<double> doc_pdf_; std::vector<double> word_pdf_; std::vector<double> cache_; public: SparseLDASampler() {} virtual void Init() override; virtual void PostSampleCorpus() override; virtual void PostSampleDocument(int m) override; virtual void SampleDocument(int m) override; private: void RemoveOrAddWordTopic(int m, int v, int k, int remove); int SampleDocumentWord(int m, int v); void PrepareSmoothBucket(); void PrepareDocBucket(int m); void PrepareWordBucket(int v); }; /************************************************************************/ /* AliasLDASampler */ /************************************************************************/ class AliasLDASampler : public Sampler<HashTables> { private: std::vector<double> p_pdf_; std::vector<double> q_sums_; // for each word v std::vector<std::vector<int> > q_samples_; // for each word v std::vector<double> q_pdf_; AliasBuilder q_alias_table_; AliasD q_alias_; int mh_step_; public: AliasLDASampler() : mh_step_(0) {} int& mh_step() { return mh_step_; } virtual void Init() override; virtual void SampleDocument(Word* word, int doc_length, TableType* doc_topics_count) override; }; /************************************************************************/ /* LightLDASampler */ /************************************************************************/ class LightLDASampler : public Sampler<HashTables> { private: AliasBuilder hp_alpha_alias_table_; AliasD hp_alpha_alias_; AliasBuilder word_alias_table_; AliasD word_alias_; std::vector<double> word_topics_pdf_; std::vector<std::vector<int> > words_topic_samples_; int mh_step_; int enable_word_proposal_; int enable_doc_proposal_; public: LightLDASampler() : mh_step_(0), enable_word_proposal_(1), enable_doc_proposal_(1) {} int& mh_step() { return mh_step_; } int& enable_word_proposal() { return enable_word_proposal_; } int& enable_doc_proposal() { return enable_doc_proposal_; } virtual void Init() override; virtual void PostSampleCorpus() override; virtual void SampleDocument(Word* word, int doc_length, TableType* doc_topics_count) override; private: int SampleWithWord(int v); int SampleWithDoc(Word* word, int doc_length, int v); }; #endif // SAMPLER_H_
GB_binop__lt_uint8.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the 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__lt_uint8) // A.*B function (eWiseMult): GB (_AemultB) // A.*B function (eWiseMult): GB (_AemultB_02__lt_uint8) // A.*B function (eWiseMult): GB (_AemultB_03__lt_uint8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__lt_uint8) // A*D function (colscale): GB (_AxD__lt_uint8) // D*A function (rowscale): GB (_DxB__lt_uint8) // C+=B function (dense accum): GB (_Cdense_accumB__lt_uint8) // C+=b function (dense accum): GB (_Cdense_accumb__lt_uint8) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__lt_uint8) // C=scalar+B GB (_bind1st__lt_uint8) // C=scalar+B' GB (_bind1st_tran__lt_uint8) // C=A+scalar GB (_bind2nd__lt_uint8) // C=A'+scalar GB (_bind2nd_tran__lt_uint8) // C type: bool // A type: uint8_t // B,b type: uint8_t // BinaryOp: cij = (aij < bij) #define GB_ATYPE \ uint8_t #define GB_BTYPE \ uint8_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) \ uint8_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ uint8_t bij = Bx [pB] // 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) \ 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 = (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_UINT8 || GxB_NO_LT_UINT8) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__lt_uint8) ( 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_uint8) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #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_uint8) ( 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 uint8_t uint8_t bwork = (*((uint8_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_uint8) ( 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_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__lt_uint8) ( 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_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__lt_uint8) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool 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_uint8) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_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_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__lt_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_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_uint8) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__lt_uint8) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *Cx = (bool *) Cx_output ; uint8_t x = (*((uint8_t *) x_input)) ; uint8_t *Bx = (uint8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; uint8_t bij = Bx [p] ; 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_uint8) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; bool *Cx = (bool *) Cx_output ; uint8_t *Ax = (uint8_t *) Ax_input ; uint8_t y = (*((uint8_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint8_t aij = Ax [p] ; 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) \ { \ uint8_t aij = Ax [pA] ; \ Cx [pC] = (x < aij) ; \ } GrB_Info GB (_bind1st_tran__lt_uint8) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t x = (*((const uint8_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint8_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint8_t aij = Ax [pA] ; \ Cx [pC] = (aij < y) ; \ } GrB_Info GB (_bind2nd_tran__lt_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t y = (*((const uint8_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
polybench.c
#define _POSIX_C_SOURCE 200809L #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <assert.h> #include <time.h> #include <sys/time.h> #include <sys/resource.h> #include <sched.h> #include <math.h> #ifdef _OPENMP # include <omp.h> #endif /* By default, collect PAPI counters on thread 0. */ #ifndef POLYBENCH_THREAD_MONITOR # define POLYBENCH_THREAD_MONITOR 0 #endif /* Total LLC cache size. By default 32+MB.. */ #ifndef POLYBENCH_CACHE_SIZE_KB # define POLYBENCH_CACHE_SIZE_KB 32770 #endif int polybench_papi_counters_threadid = POLYBENCH_THREAD_MONITOR; double polybench_program_total_flops = 0; #ifdef POLYBENCH_PAPI # include <papi.h> # define POLYBENCH_MAX_NB_PAPI_COUNTERS 96 char* _polybench_papi_eventlist[] = { #include "papi_counters.list" NULL }; int polybench_papi_eventset; int polybench_papi_eventlist[POLYBENCH_MAX_NB_PAPI_COUNTERS]; long_long polybench_papi_values[POLYBENCH_MAX_NB_PAPI_COUNTERS]; #endif /* Timer code (gettimeofday). */ double polybench_t_start, polybench_t_end; /* Timer code (RDTSC). */ unsigned long long int polybench_c_start, polybench_c_end; static double rtclock() { #if defined(POLYBENCH_TIME) || defined(POLYBENCH_GFLOPS) struct timeval Tp; int stat; stat = gettimeofday (&Tp, NULL); if (stat != 0) printf ("Error return from gettimeofday: %d", stat); return (Tp.tv_sec + Tp.tv_usec * 1.0e-6); #else return 0; #endif } #ifdef POLYBENCH_CYCLE_ACCURATE_TIMER static unsigned long long int rdtsc() { unsigned long long int ret = 0; unsigned int cycles_lo; unsigned int cycles_hi; __asm__ volatile ("RDTSC" : "=a" (cycles_lo), "=d" (cycles_hi)); ret = (unsigned long long int)cycles_hi << 32 | cycles_lo; return ret; } #endif void polybench_flush_cache() { int cs = POLYBENCH_CACHE_SIZE_KB * 1024 / sizeof(double); double* flush = (double*) calloc (cs, sizeof(double)); int i; double tmp = 0.0; #ifdef _OPENMP #pragma omp parallel for reduction(+:tmp) private(i) #endif for (i = 0; i < cs; i++) tmp += flush[i]; assert (tmp <= 10.0); free (flush); } #ifdef POLYBENCH_LINUX_FIFO_SCHEDULER void polybench_linux_fifo_scheduler() { /* Use FIFO scheduler to limit OS interference. Program must be run as root, and this works only for Linux kernels. */ struct sched_param schedParam; schedParam.sched_priority = sched_get_priority_max (SCHED_FIFO); sched_setscheduler (0, SCHED_FIFO, &schedParam); } void polybench_linux_standard_scheduler() { /* Restore to standard scheduler policy. */ struct sched_param schedParam; schedParam.sched_priority = sched_get_priority_max (SCHED_OTHER); sched_setscheduler (0, SCHED_OTHER, &schedParam); } #endif #ifdef POLYBENCH_PAPI static void test_fail(char *file, int line, char *call, int retval) { char buf[128]; memset(buf, '\0', sizeof(buf)); if (retval != 0) fprintf (stdout,"%-40s FAILED\nLine # %d\n", file, line); else { fprintf (stdout,"%-40s SKIPPED\n", file); fprintf (stdout,"Line # %d\n", line); } if (retval == PAPI_ESYS) { sprintf (buf, "System error in %s", call); perror (buf); } else if (retval > 0) fprintf (stdout,"Error: %s\n", call); else if (retval == 0) fprintf (stdout,"Error: %s\n", call); else { char errstring[PAPI_MAX_STR_LEN]; PAPI_perror (retval, errstring, PAPI_MAX_STR_LEN); fprintf (stdout,"Error in %s: %s\n", call, errstring); } fprintf (stdout,"\n"); if (PAPI_is_initialized ()) PAPI_shutdown (); exit (1); } void polybench_papi_init() { # ifdef _OPENMP #pragma omp parallel { #pragma omp master { if (omp_get_max_threads () < polybench_papi_counters_threadid) polybench_papi_counters_threadid = omp_get_max_threads () - 1; } #pragma omp barrier if (omp_get_thread_num () == polybench_papi_counters_threadid) { # endif int retval; polybench_papi_eventset = PAPI_NULL; if ((retval = PAPI_library_init (PAPI_VER_CURRENT)) != PAPI_VER_CURRENT) test_fail (__FILE__, __LINE__, "PAPI_library_init", retval); if ((retval = PAPI_create_eventset (&polybench_papi_eventset)) != PAPI_OK) test_fail (__FILE__, __LINE__, "PAPI_create_eventset", retval); int k; for (k = 0; _polybench_papi_eventlist[k]; ++k) { if ((retval = PAPI_event_name_to_code (_polybench_papi_eventlist[k], &(polybench_papi_eventlist[k]))) != PAPI_OK) test_fail (__FILE__, __LINE__, "PAPI_event_name_to_code", retval); } polybench_papi_eventlist[k] = 0; # ifdef _OPENMP } } #pragma omp barrier # endif } void polybench_papi_close() { # ifdef _OPENMP #pragma omp parallel { if (omp_get_thread_num () == polybench_papi_counters_threadid) { # endif int retval; if ((retval = PAPI_destroy_eventset (&polybench_papi_eventset)) != PAPI_OK) test_fail (__FILE__, __LINE__, "PAPI_destroy_eventset", retval); if (PAPI_is_initialized ()) PAPI_shutdown (); # ifdef _OPENMP } } #pragma omp barrier # endif } int polybench_papi_start_counter(int evid) { # ifndef POLYBENCH_NO_FLUSH_CACHE polybench_flush_cache(); # endif # ifdef _OPENMP # pragma omp parallel { if (omp_get_thread_num () == polybench_papi_counters_threadid) { # endif int retval = 1; char descr[PAPI_MAX_STR_LEN]; PAPI_event_info_t evinfo; PAPI_event_code_to_name (polybench_papi_eventlist[evid], descr); if (PAPI_add_event (polybench_papi_eventset, polybench_papi_eventlist[evid]) != PAPI_OK) test_fail (__FILE__, __LINE__, "PAPI_add_event", 1); if (PAPI_get_event_info (polybench_papi_eventlist[evid], &evinfo) != PAPI_OK) test_fail (__FILE__, __LINE__, "PAPI_get_event_info", retval); if ((retval = PAPI_start (polybench_papi_eventset)) != PAPI_OK) test_fail (__FILE__, __LINE__, "PAPI_start", retval); # ifdef _OPENMP } } #pragma omp barrier # endif return 0; } void polybench_papi_stop_counter(int evid) { # ifdef _OPENMP # pragma omp parallel { if (omp_get_thread_num () == polybench_papi_counters_threadid) { # endif int retval; long_long values[1]; values[0] = 0; if ((retval = PAPI_read (polybench_papi_eventset, &values[0])) != PAPI_OK) test_fail (__FILE__, __LINE__, "PAPI_read", retval); if ((retval = PAPI_stop (polybench_papi_eventset, NULL)) != PAPI_OK) test_fail (__FILE__, __LINE__, "PAPI_stop", retval); polybench_papi_values[evid] = values[0]; if ((retval = PAPI_remove_event (polybench_papi_eventset, polybench_papi_eventlist[evid])) != PAPI_OK) test_fail (__FILE__, __LINE__, "PAPI_remove_event", retval); # ifdef _OPENMP } } #pragma omp barrier # endif } void polybench_papi_print() { int verbose = 0; # ifdef _OPENMP # pragma omp parallel { if (omp_get_thread_num() == polybench_papi_counters_threadid) { #ifdef POLYBENCH_PAPI_VERBOSE verbose = 1; #endif if (verbose) printf ("On thread %d:\n", polybench_papi_counters_threadid); #endif int evid; for (evid = 0; polybench_papi_eventlist[evid] != 0; ++evid) { if (verbose) printf ("%s=", _polybench_papi_eventlist[evid]); printf ("%llu ", polybench_papi_values[evid]); if (verbose) printf ("\n"); } printf ("\n"); # ifdef _OPENMP } } #pragma omp barrier # endif } #endif /* ! POLYBENCH_PAPI */ void polybench_prepare_instruments() { #ifndef POLYBENCH_NO_FLUSH_CACHE polybench_flush_cache (); #endif #ifdef POLYBENCH_LINUX_FIFO_SCHEDULER polybench_linux_fifo_scheduler (); #endif } void polybench_timer_start() { polybench_prepare_instruments (); #ifndef POLYBENCH_CYCLE_ACCURATE_TIMER polybench_t_start = rtclock (); #else polybench_c_start = rdtsc (); #endif } void polybench_timer_stop() { #ifndef POLYBENCH_CYCLE_ACCURATE_TIMER polybench_t_end = rtclock (); #else polybench_c_end = rdtsc (); #endif #ifdef POLYBENCH_LINUX_FIFO_SCHEDULER polybench_linux_standard_scheduler (); #endif } void polybench_timer_print() { #ifdef POLYBENCH_GFLOPS if (polybench_program_total_flops == 0) { printf ("[PolyBench][WARNING] Program flops not defined, use polybench_set_program_flops(value)\n"); printf ("%0.6lf\n", polybench_t_end - polybench_t_start); } else printf ("%0.2lf\n", (polybench_program_total_flops / (double)(polybench_t_end - polybench_t_start)) / 1000000000); #else # ifndef POLYBENCH_CYCLE_ACCURATE_TIMER printf ("%0.6f\n", polybench_t_end - polybench_t_start); # else printf ("%Ld\n", polybench_c_end - polybench_c_start); # endif #endif } static void * xmalloc (size_t num) { void* cur = NULL; int ret = posix_memalign (&cur, 32, num); if (! cur || ret) { fprintf (stderr, "[PolyBench] posix_memalign: cannot allocate memory"); exit (1); } return cur; } void* polybench_alloc_data(unsigned long long int n, int elt_size) { /// FIXME: detect overflow! size_t val = n; val *= elt_size; void* ret = xmalloc (val); return ret; }
declare_variant_device_isa_codegen_1.c
// RUN: %clang_cc1 -verify -fopenmp -x c -triple %itanium_abi_triple -emit-llvm %s -o - -fopenmp-version=50 | FileCheck %s --check-prefix=GENERIC // RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple %itanium_abi_triple -fexceptions -fcxx-exceptions -emit-pch -o %t -fopenmp-version=50 %s // RUN: %clang_cc1 -fopenmp -x c++ -triple %itanium_abi_triple -fexceptions -fcxx-exceptions -std=c++11 -include-pch %t -verify %s -emit-llvm -o - -fopenmp-version=50 | FileCheck %s --check-prefix=GENERIC // RUN: %clang_cc1 -target-feature +avx512f -verify -fopenmp -x c -triple %itanium_abi_triple -emit-llvm %s -o - -fopenmp-version=50 | FileCheck %s --check-prefix=WITHFEATURE // RUN: %clang_cc1 -target-feature +avx512f -fopenmp -x c++ -std=c++11 -triple %itanium_abi_triple -fexceptions -fcxx-exceptions -emit-pch -o %t -fopenmp-version=50 %s // RUN: %clang_cc1 -target-feature +avx512f -fopenmp -x c++ -triple %itanium_abi_triple -fexceptions -fcxx-exceptions -std=c++11 -include-pch %t -verify %s -emit-llvm -o - -fopenmp-version=50 | FileCheck %s --check-prefix=WITHFEATURE // expected-no-diagnostics // Test taken from PR46338 (by linna su) #ifndef HEADER #define HEADER void base_saxpy(int, float, float *, float *); void avx512_saxpy(int, float, float *, float *); #pragma omp declare variant(avx512_saxpy) \ match(device = {isa(avx512f)}) void base_saxpy(int n, float s, float *x, float *y) { #pragma omp parallel for for (int i = 0; i < n; i++) y[i] = s * x[i] + y[i]; } void avx512_saxpy(int n, float s, float *x, float *y) { #pragma omp parallel for simd simdlen(16) aligned(x, y : 64) for (int i = 0; i < n; i++) y[i] = s * x[i] + y[i]; } void caller(int n, float s, float *x, float *y) { // GENERIC: define {{.*}}void @{{.*}}caller // GENERIC: call void @{{.*}}base_saxpy // WITHFEATURE: define {{.*}}void @{{.*}}caller // WITHFEATURE: call void @{{.*}}avx512_saxpy base_saxpy(n, s, x, y); } __attribute__((target("avx512f"))) void variant_caller(int n, float s, float *x, float *y) { // GENERIC: define {{.*}}void @{{.*}}variant_caller // GENERIC: call void @{{.*}}avx512_saxpy // WITHFEATURE: define {{.*}}void @{{.*}}variant_caller // WITHFEATURE: call void @{{.*}}avx512_saxpy base_saxpy(n, s, x, y); } #endif
lbfgsbsolver.h
// CppNumericalSolver #include <iostream> #include <list> #include <Eigen/LU> #include "isolver.h" #include "../boundedproblem.h" #include "../linesearch/morethuente.h" #ifndef LBFGSBSOLVER_H #define LBFGSBSOLVER_H namespace cppoptlib { template<typename TProblem> class LbfgsbSolver : public ISolver<TProblem, 1> { public: using Superclass = ISolver<TProblem, 1>; using typename Superclass::Scalar; using typename Superclass::TVector; using MatrixType = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>; using VariableTVector = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>; protected: // workspace matrices MatrixType W, M; Scalar theta; int DIM; int m_historySize = 5; /** * @brief sort pairs (k,v) according v ascending * @details [long description] * * @param v [description] * @return [description] */ std::vector<int> sort_indexes(const std::vector< std::pair<int, Scalar> > &v) { std::vector<int> idx(v.size()); for (size_t i = 0; i != idx.size(); ++i) idx[i] = v[i].first; sort(idx.begin(), idx.end(), [&v](size_t i1, size_t i2) { return v[i1].second < v[i2].second; }); return idx; } /** * @brief Algorithm CP: Computation of the generalized Cauchy point * @details PAGE 8 * * @param c [description] */ void getGeneralizedCauchyPoint(const TProblem &problem, const TVector &x, const TVector &g, TVector &x_cauchy, VariableTVector &c) { const int DIM = x.rows(); // Given x,l,u,g, and B = \theta I-WMW // {all t_i} = { (idx,value), ... } // TODO: use "std::set" ? std::vector<std::pair<int, Scalar> > SetOfT; // the feasible set is implicitly given by "SetOfT - {t_i==0}" TVector d = -g; // n operations for (int j = 0; j < DIM; j++) { if (g(j) == 0) { SetOfT.push_back(std::make_pair(j, std::numeric_limits<Scalar>::max())); } else { Scalar tmp = 0; if (g(j) < 0) { tmp = (x(j) - problem.upperBound()(j)) / g(j); } else { tmp = (x(j) - problem.lowerBound()(j)) / g(j); } SetOfT.push_back(std::make_pair(j, tmp)); if (tmp == 0) d(j) = 0; } } // sortedindices [1,0,2] means the minimal element is on the 1-st entry std::vector<int> sortedIndices = sort_indexes(SetOfT); x_cauchy = x; // Initialize // p := W^Scalar*p VariableTVector p = (W.transpose() * d); // (2mn operations) // c := 0 c = VariableTVector::Zero(W.cols()); // f' := g^Scalar*d = -d^Td Scalar f_prime = -d.dot(d); // (n operations) // f'' := \theta*d^Scalar*d-d^Scalar*W*M*W^Scalar*d = -\theta*f' - p^Scalar*M*p Scalar f_doubleprime = (Scalar)(-1.0 * theta) * f_prime - p.dot(M * p); // (O(m^2) operations) f_doubleprime = std::max(std::numeric_limits<Scalar>::epsilon(), f_doubleprime); Scalar f_dp_orig = f_doubleprime; // \delta t_min := -f'/f'' Scalar dt_min = -f_prime / f_doubleprime; // t_old := 0 Scalar t_old = 0; // b := argmin {t_i , t_i >0} int i = 0; for (int j = 0; j < DIM; j++) { i = j; if (SetOfT[sortedIndices[j]].second > 0) break; } int b = sortedIndices[i]; // see below // t := min{t_i : i in F} Scalar t = SetOfT[b].second; // \delta Scalar := t - 0 Scalar dt = t ; // examination of subsequent segments while ((dt_min >= dt) && (i < DIM)) { if (d(b) > 0) x_cauchy(b) = problem.upperBound()(b); else if (d(b) < 0) x_cauchy(b) = problem.lowerBound()(b); // z_b = x_p^{cp} - x_b Scalar zb = x_cauchy(b) - x(b); // c := c +\delta t*p c += dt * p; // cache VariableTVector wbt = W.row(b); f_prime += dt * f_doubleprime + (Scalar) g(b) * g(b) + (Scalar) theta * g(b) * zb - (Scalar) g(b) * wbt.transpose() * (M * c); f_doubleprime += (Scalar) - 1.0 * theta * g(b) * g(b) - (Scalar) 2.0 * (g(b) * (wbt.dot(M * p))) - (Scalar) g(b) * g(b) * wbt.transpose() * (M * wbt); f_doubleprime = std::max(std::numeric_limits<Scalar>::epsilon() * f_dp_orig, f_doubleprime); p += g(b) * wbt.transpose(); d(b) = 0; dt_min = -f_prime / f_doubleprime; t_old = t; ++i; if (i < DIM) { b = sortedIndices[i]; t = SetOfT[b].second; dt = t - t_old; } } dt_min = std::max(dt_min, (Scalar)0.0); t_old += dt_min; #pragma omp parallel for for (int ii = i; ii < x_cauchy.rows(); ii++) { x_cauchy(sortedIndices[ii]) = x(sortedIndices[ii]) + t_old * d(sortedIndices[ii]); } c += dt_min * p; } /** * @brief find alpha* = max {a : a <= 1 and l_i-xc_i <= a*d_i <= u_i-xc_i} * @details [long description] * * @param FreeVariables [description] * @return [description] */ Scalar findAlpha(const TProblem &problem, TVector &x_cp, VariableTVector &du, std::vector<int> &FreeVariables) { Scalar alphastar = 1; const unsigned int n = FreeVariables.size(); assert(du.rows() == n); for (unsigned int i = 0; i < n; i++) { if (du(i) > 0) { alphastar = std::min(alphastar, (problem.upperBound()(FreeVariables[i]) - x_cp(FreeVariables[i])) / du(i)); } else { alphastar = std::min(alphastar, (problem.lowerBound()(FreeVariables[i]) - x_cp(FreeVariables[i])) / du(i)); } } return alphastar; } /** * @brief solving unbounded probelm * @details [long description] * * @param SubspaceMin [description] */ void SubspaceMinimization(const TProblem &problem, TVector &x_cauchy, TVector &x, VariableTVector &c, TVector &g, TVector &SubspaceMin) { Scalar theta_inverse = 1 / theta; std::vector<int> FreeVariablesIndex; for (int i = 0; i < x_cauchy.rows(); i++) { if ((x_cauchy(i) != problem.upperBound()(i)) && (x_cauchy(i) != problem.lowerBound()(i))) { FreeVariablesIndex.push_back(i); } } const int FreeVarCount = FreeVariablesIndex.size(); MatrixType WZ = MatrixType::Zero(W.cols(), FreeVarCount); for (int i = 0; i < FreeVarCount; i++) WZ.col(i) = W.row(FreeVariablesIndex[i]); TVector rr = (g + theta * (x_cauchy - x) - W * (M * c)); // r=r(FreeVariables); MatrixType r = MatrixType::Zero(FreeVarCount, 1); for (int i = 0; i < FreeVarCount; i++) r.row(i) = rr.row(FreeVariablesIndex[i]); // STEP 2: "v = w^T*Z*r" and STEP 3: "v = M*v" VariableTVector v = M * (WZ * r); // STEP 4: N = 1/theta*W^T*Z*(W^T*Z)^T MatrixType N = theta_inverse * WZ * WZ.transpose(); // N = I - MN N = MatrixType::Identity(N.rows(), N.rows()) - M * N; // STEP: 5 // v = N^{-1}*v if (v.size() > 0) v = N.lu().solve(v); // STEP: 6 // HERE IS A MISTAKE IN THE ORIGINAL PAPER! VariableTVector du = -theta_inverse * r - theta_inverse * theta_inverse * WZ.transpose() * v; // STEP: 7 Scalar alpha_star = findAlpha(problem, x_cauchy, du, FreeVariablesIndex); // STEP: 8 VariableTVector dStar = alpha_star * du; SubspaceMin = x_cauchy; for (int i = 0; i < FreeVarCount; i++) { SubspaceMin(FreeVariablesIndex[i]) = SubspaceMin(FreeVariablesIndex[i]) + dStar(i); } } public: void setHistorySize(const int hs) { m_historySize = hs; } void minimize(TProblem &problem, TVector &x0) { if(!problem.isValid(x0)) std::cerr << "start with invalid x0" << std::endl; DIM = x0.rows(); theta = 1.0; W = MatrixType::Zero(DIM, 0); M = MatrixType::Zero(0, 0); MatrixType yHistory = MatrixType::Zero(DIM, 0); MatrixType sHistory = MatrixType::Zero(DIM, 0); TVector x = x0, g = x0; Scalar f = problem.value(x); problem.gradient(x, g); // conv. crit. auto noConvergence = [&](TVector &x, TVector &g)->bool { return (((x - g).cwiseMax(problem.lowerBound()).cwiseMin(problem.upperBound()) - x).template lpNorm<Eigen::Infinity>() >= 1e-4); }; this->m_current.reset(); this->m_status = Status::Continue; while (problem.callback(this->m_current, x) && noConvergence(x, g) && (this->m_status == Status::Continue)) { Scalar f_old = f; TVector x_old = x; TVector g_old = g; // STEP 2: compute the cauchy point TVector CauchyPoint = TVector::Zero(DIM); VariableTVector c = VariableTVector::Zero(W.cols()); getGeneralizedCauchyPoint(problem, x, g, CauchyPoint, c); // STEP 3: compute a search direction d_k by the primal method for the sub-problem TVector SubspaceMin; SubspaceMinimization(problem, CauchyPoint, x, c, g, SubspaceMin); // STEP 4: perform linesearch and STEP 5: compute gradient Scalar alpha_init = 1.0; const Scalar rate = MoreThuente<TProblem, 1>::linesearch(x, SubspaceMin-x , problem, alpha_init); // update current guess and function information x = x - rate*(x-SubspaceMin); f = problem.value(x); problem.gradient(x, g); // prepare for next iteration TVector newY = g - g_old; TVector newS = x - x_old; // STEP 6: Scalar test = newS.dot(newY); test = (test < 0) ? -1.0 * test : test; if (test > 1e-7 * newY.squaredNorm()) { if (yHistory.cols() < m_historySize) { yHistory.conservativeResize(DIM, yHistory.cols() + 1); sHistory.conservativeResize(DIM, sHistory.cols() + 1); } else { yHistory.leftCols(m_historySize - 1) = yHistory.rightCols(m_historySize - 1).eval(); sHistory.leftCols(m_historySize - 1) = sHistory.rightCols(m_historySize - 1).eval(); } yHistory.rightCols(1) = newY; sHistory.rightCols(1) = newS; // STEP 7: theta = (Scalar)(newY.transpose() * newY) / (newY.transpose() * newS); W = MatrixType::Zero(yHistory.rows(), yHistory.cols() + sHistory.cols()); W << yHistory, (theta * sHistory); MatrixType A = sHistory.transpose() * yHistory; MatrixType L = A.template triangularView<Eigen::StrictlyLower>(); MatrixType MM(A.rows() + L.rows(), A.rows() + L.cols()); MatrixType D = -1 * A.diagonal().asDiagonal(); MM << D, L.transpose(), L, ((sHistory.transpose() * sHistory) * theta); M = MM.inverse(); } if (fabs(f_old - f) < 1e-8) { // successive function values too similar break; } ++this->m_current.iterations; this->m_current.gradNorm = g.norm(); this->m_status = checkConvergence(this->m_stop, this->m_current); } x0 = x; if (this->m_debug > DebugLevel::None) { std::cout << "Stop status was: " << this->m_status << std::endl; std::cout << "Stop criteria were: " << std::endl << this->m_stop << std::endl; std::cout << "Current values are: " << std::endl << this->m_current << std::endl; } } }; } /* namespace cppoptlib */ #endif /* LBFGSBSOLVER_H_ */
openmp_imp.c
#include "imp.h" #ifdef CT_OPENMP void ct_openmp_init(const ct_env_var* env) { (void)env; } void ct_openmp_fini(void) { } void ct_openmp_for(int n, ct_ind_func f, void* context, ct_canceller* c) { int i; int cancelled = 0; #pragma omp parallel for schedule(dynamic,1) for(i=0; i<n; ++i) { if(!cancelled && !c->cancelled) { f(i, context); cancelled = c->cancelled; } } } ct_imp g_ct_openmp_imp = { "openmp", &ct_openmp_init, &ct_openmp_fini, &ct_openmp_for, 0, 0, 0, /* cancelling functions */ }; #else ct_imp g_ct_openmp_imp; #endif
GB_binop__land_int32.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__land_int32) // A.*B function (eWiseMult): GB (_AemultB_08__land_int32) // A.*B function (eWiseMult): GB (_AemultB_02__land_int32) // A.*B function (eWiseMult): GB (_AemultB_04__land_int32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__land_int32) // A*D function (colscale): GB (_AxD__land_int32) // D*A function (rowscale): GB (_DxB__land_int32) // C+=B function (dense accum): GB (_Cdense_accumB__land_int32) // C+=b function (dense accum): GB (_Cdense_accumb__land_int32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__land_int32) // C=scalar+B GB (_bind1st__land_int32) // C=scalar+B' GB (_bind1st_tran__land_int32) // C=A+scalar GB (_bind2nd__land_int32) // C=A'+scalar GB (_bind2nd_tran__land_int32) // C type: int32_t // A type: int32_t // A pattern? 0 // B type: int32_t // B pattern? 0 // BinaryOp: cij = ((aij != 0) && (bij != 0)) #define GB_ATYPE \ int32_t #define GB_BTYPE \ int32_t #define GB_CTYPE \ int32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int32_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int32_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = ((x != 0) && (y != 0)) ; // 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_LAND || GxB_NO_INT32 || GxB_NO_LAND_INT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__land_int32) ( 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__land_int32) ( 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__land_int32) ( 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 int32_t int32_t bwork = (*((int32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__land_int32) ( 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 int32_t *restrict Cx = (int32_t *) 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__land_int32) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *restrict Cx = (int32_t *) 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__land_int32) ( 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) ; int32_t alpha_scalar ; int32_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((int32_t *) alpha_scalar_in)) ; beta_scalar = (*((int32_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__land_int32) ( 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__land_int32) ( 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__land_int32) ( 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__land_int32) ( 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__land_int32) ( 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 int32_t *Cx = (int32_t *) Cx_output ; int32_t x = (*((int32_t *) x_input)) ; int32_t *Bx = (int32_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 ; int32_t bij = GBX (Bx, p, false) ; Cx [p] = ((x != 0) && (bij != 0)) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__land_int32) ( 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 ; int32_t *Cx = (int32_t *) Cx_output ; int32_t *Ax = (int32_t *) Ax_input ; int32_t y = (*((int32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int32_t aij = GBX (Ax, p, false) ; Cx [p] = ((aij != 0) && (y != 0)) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = ((x != 0) && (aij != 0)) ; \ } GrB_Info GB (_bind1st_tran__land_int32) ( 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 \ int32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t x = (*((const int32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int32_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) \ { \ int32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = ((aij != 0) && (y != 0)) ; \ } GrB_Info GB (_bind2nd_tran__land_int32) ( 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 int32_t y = (*((const int32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
nonnegcg.c
/* Non-negative conjugate gradient optimizer Minimizes a function subject to non-negativity constraints on all the variables, using a modified Polak-Ribiere-Polyak conjugate gradient method. Implementation is based on the paper: Li, C. (2013). A conjugate gradient type method for the nonnegative constraints optimization problems. Journal of Applied Mathematics, 2013. BSD 2-Clause License Copyright (c) 2019, David Cortes All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <math.h> #include <stdlib.h> #include <stddef.h> #include <limits.h> #ifndef _FOR_R #include <stdio.h> #else #include <R_ext/Print.h> #define printf Rprintf #define fprintf(f, message) REprintf(message) #endif #ifdef _OPENMP #include <omp.h> #endif #ifdef _FOR_PYTHON #include "findblas.h" #elif defined(_FOR_R) #include <R_ext/BLAS.h> double cblas_ddot(int n, double *x, int incx, double *y, int incy) { return ddot_(&n, x, &incx, y, &incy); } void cblas_daxpy(int n, double a, double *x, int incx, double *y, int incy) { daxpy_(&n, &a, x, &incx, y, &incy); } void cblas_dscal(int n, double alpha, double *x, int incx) { dscal_(&n, &alpha, x, &incx); } #else #include "blasfuns.h" #endif /* Aliasing for compiler optimizations */ #ifdef __cplusplus #if defined(__GNUG__) || defined(__GNUC__) || defined(_MSC_VER) || defined(__clang__) || defined(__INTEL_COMPILER) #define restrict __restrict #else #define restrict #endif #elif defined(_MSC_VER) #define restrict __restrict #elif !defined(__STDC_VERSION__) || (__STDC_VERSION__ < 199901L) #define restrict #endif /* OpenMP < 3.0 (e.g. MSVC as of 2019) does not support parallel for's with unsigned iterators, and does not support declaring the iterator type in the loop itself */ #ifdef _OPENMP #if (_OPENMP > 200801) && !defined(_WIN32) && !defined(_WIN64) /* OpenMP < 3.0 */ #define size_t_for size_t #else #define size_t_for #endif #else #define size_t_for size_t #endif #ifndef isnan #ifdef _isnan #define isnan _isnan #else #define isnan(x) ( (x) != (x) ) #endif #endif #ifndef isinf #ifdef _finite #define isinf(x) (!_finite(x)) #else #define isinf(x) ( (x) >= HUGE_VAL || (x) <= -HUGE_VAL ) #endif #endif #define get_curr_ix_rotation(ix, n) ( ((ix) == 0) ? 0 : (n) ) #define incr_ix_rotation(ix) ( ((ix) == 0)? 1 : 0 ) #define square(x) ( (x) * (x) ) #define nonneg(x) ((x) > 0)? (x) : 0 typedef void fun_eval(double x[], int n, double *f, void *data); typedef void grad_eval(double x[], int n, double grad[], void *data); typedef void callback(double x[], int n, double f, size_t iter, void *data); typedef enum cg_result {tol_achieved = 0, stop_maxnfeval = 1, stop_maxiter = 2, out_of_mem = 3} cg_result; /* Non-negative conjugate gradient optimizer Minimizes a function subject to non-negativity constraints on all the variables, using a modified Polak-Rubiere-Polyak conjugate gradient method. Implementation is based on the paper: Li, C. (2013). A conjugate gradient type method for the nonnegative constraints optimization problems. Journal of Applied Mathematics, 2013. x (in, out) : At input, starting point (must be a feasible point). At output, optimal values calculated by the optimizer. n : Number of variables in the optimization problem fun_val (out) : Value of the function achieved at the end of the procedure obj_fun : function that calculates the objective value (must be written into the *f pointer passed to it) grad_fun : function that calculates the gradient (must be written into the grad[] array passed to it) cb : callback function to execute at the end of each iteration data : Extra data to pass to the functions that evaluate objective, gradient, and callback (must be cast to void pointer) tol : Tolerance for <gradient, direction> (Recommended: <1e-3) maxnfeval : Maximum number of function evaluations (Recommended: >1000) maxiter : Maximum number of CG iterations to run (Recommended: >100, but note that steps are always feasible descent directions) niter (out) : Number of CG iterations performed nfeval (out) : Number of function evaluations performed decr_lnsrch : Number by which to decrease the step size after each unsuccessful line search (Recommended: 0.5) lnsrch_const : Acceptance parameter for the line search procedure (Recommended: 0.01) max_ls : Maximum number of line search trials per iteration (Recommended: 20) extra_nonneg_tol: Ensure extra non-negative tolerance by explicitly setting elements that are <=0 to zero at each iteration (Recommended: 0) buffer_arr : Array of dimensions (4*n). Will allocate it and then free it if passing NULL. nthreads : Number of parallel threads to use verbose : Whether to print convergence messages */ int minimize_nonneg_cg(double *restrict x, int n, double *fun_val, fun_eval *obj_fun, grad_eval *grad_fun, callback *cb, void *data, double tol, size_t maxnfeval, size_t maxiter, size_t *niter, size_t *nfeval, double decr_lnsrch, double lnsrch_const, size_t max_ls, int extra_nonneg_tol, double *buffer_arr, int nthreads, int verbose) { double max_step; double direction_norm_sq; double grad_prev_norm_sq; double prod_grad_dir; double theta; double beta; double curr_fun_val; double new_fun_val; obj_fun(x, n, &curr_fun_val, data); *nfeval = 1; int dealloc_buffer = 0; int revert_x = 0; size_t ls; cg_result return_value = stop_maxiter; if ( maxiter <= 0 ) { maxiter = INT_MAX;} if ( maxnfeval <= 0 ) { maxnfeval = INT_MAX;} #if defined(_OPENMP) && ((_OPENMP < 200801) || defined(_WIN32) || defined(_WIN64)) /* OpenMP < 3.0 */ long i; long n_szt = n; #else size_t n_szt = (size_t) n; #endif /* algorithm requires current and previous gradient and search direction, so the index at which they are written in the array is rotated each iteration to avoid unnecessary copies */ int ix_rotation = 0; if (buffer_arr == NULL) { buffer_arr = (double*) malloc(sizeof(double) * n * 4); dealloc_buffer = 1; if (buffer_arr == NULL) { fprintf(stderr, "Could not allocate memory for optimization procedure\n"); return out_of_mem; } } double *grad_curr_n_prev = buffer_arr; double *direction_curr_n_prev = buffer_arr + 2 * n; double *restrict direction_curr = direction_curr_n_prev; double *restrict grad_curr = grad_curr_n_prev; double *restrict direction_prev; double *restrict grad_prev; /* set number of BLAS threads */ #if defined(_MKL_H_) mkl_set_num_threads_local(nthreads); #elif defined(CBLAS_H) openblas_set_num_threads(nthreads); #endif if (verbose) { printf("********************************************\n"); printf("Non-negative Conjugate Gradient Optimization\n\n"); printf("Number of variables to optimize: %d\n", n); if (maxiter == INT_MAX && maxnfeval == INT_MAX) {printf("[Warning: no limit on iterations and function evaluations passed]");} printf("Initial function value: %10.4f\n\n", curr_fun_val); } for (*niter = 0; *niter < maxiter; (*niter)++) { /* get gradient */ grad_fun(x, n, grad_curr, data); /* determine search direction - this requires 3 passess over 'x' */ /* first pass: get a capped gradient */ #pragma omp parallel for schedule(static) firstprivate(x, direction_curr, grad_curr) num_threads(nthreads) for (size_t_for i = 0; i < n_szt; i++) { direction_curr[i] = (x[i] <= 0 && grad_curr[i] >= 0)? 0 : -grad_curr[i]; } /* at first iteration, stop with that */ if (*niter > 0) { /* second pass: calculate beta and theta constants */ theta = 0; beta = 0; #if !defined(_WIN32) && !defined(_WIN64) #pragma omp parallel for schedule(static) firstprivate(x, direction_prev, grad_curr, grad_prev, n_szt) reduction(+:theta, beta) num_threads(nthreads) #endif for (size_t_for i = 0; i < n_szt; i++) { theta += ( x[i] <= 0 )? 0 : grad_curr[i] * direction_prev[i]; beta += ( x[i] <= 0 )? 0 : grad_curr[i] * (grad_curr[i] - grad_prev[i]); } theta /= grad_prev_norm_sq; beta /= grad_prev_norm_sq; /* third pass: add to direction info on previous direction and gradient differences */ #pragma omp parallel for schedule(static) firstprivate(x, direction_curr, direction_prev, grad_curr, grad_prev, n_szt, theta, beta) num_threads(nthreads) for (size_t_for i = 0; i < n_szt; i++) { direction_curr[i] += ( x[i] <= 0 )? 0 : beta * direction_prev[i] - theta * (grad_curr[i] - grad_prev[i]); } } /* check if stop criterion is satisfied */ prod_grad_dir = cblas_ddot(n, grad_curr, 1, direction_curr, 1); if ( fabs(prod_grad_dir) <= tol ) { return_value = tol_achieved; goto terminate_procedure; } /* determine maximum step size */ max_step = 1.0; #if defined(_OPENMP) #if !defined(_WIN32) && !defined(_WIN64) #pragma omp parallel for schedule(static) firstprivate(x, direction_curr, n_szt) reduction(min: max_step) num_threads(nthreads) #endif for (size_t_for i = 0; i < n_szt; i++) { max_step = (direction_curr[i] < 0)? -x[i] / direction_curr[i] : 1.0; } max_step = fmin(max_step, 1.0); #else for (size_t i = 0; i < n_szt; i++) { if (direction_curr[i] < 0) { max_step = fmin(max_step, -x[i] / direction_curr[i]); } } #endif /* perform line search */ cblas_daxpy(n, max_step, direction_curr, 1, x, 1); direction_norm_sq = cblas_ddot(n, direction_curr, 1, direction_curr, 1); for (ls = 0; ls < max_ls; ls++) { if (extra_nonneg_tol) { #pragma omp parallel for schedule(static) firstprivate(x, n_szt) num_threads(nthreads) for (size_t_for i = 0; i < n_szt; i++){x[i] = nonneg(x[i]);} } obj_fun(x, n, &new_fun_val, data); if ( !isinf(new_fun_val) && !isnan(new_fun_val) ) { if (new_fun_val <= curr_fun_val - lnsrch_const * square(max_step * pow(decr_lnsrch, ls)) * direction_norm_sq) { break; } } (*nfeval)++; if (*nfeval >= maxnfeval) { revert_x = 1; return_value = stop_maxnfeval; goto terminate_procedure; } /* go to new step size by modifying x in-place */ cblas_daxpy(n, max_step * ( pow(decr_lnsrch, ls + 1) - pow(decr_lnsrch, ls) ), direction_curr, 1, x, 1); } curr_fun_val = new_fun_val; if ( cb != NULL) { cb(x, n, curr_fun_val, *niter, data); } /* update norm of gradient */ grad_prev_norm_sq = cblas_ddot(n, grad_curr, 1, grad_curr, 1); /* next time, write to the other side of grad and dir arrays */ direction_prev = direction_curr; grad_prev = grad_curr; ix_rotation = incr_ix_rotation(ix_rotation); direction_curr = direction_curr_n_prev + get_curr_ix_rotation(ix_rotation, n); grad_curr = grad_curr_n_prev + get_curr_ix_rotation(ix_rotation, n); if (verbose) { printf("Iteration %3d : f(x) = %10.4f, |<g(x), d(x)>| = %12.4f, nfev = %3d, ls = %2d\n", (int) *niter + 1, curr_fun_val, fabs(prod_grad_dir), (int) *nfeval, (int) ls +1 ); } } terminate_procedure: if (dealloc_buffer) { free(buffer_arr); } if (revert_x) { cblas_daxpy(n, -max_step * pow(decr_lnsrch, ls), direction_curr, 1, x, 1); if (extra_nonneg_tol) { #pragma omp parallel for schedule(static) firstprivate(x, n_szt) num_threads(nthreads) for (size_t_for i = 0; i < n_szt; i++){x[i] = nonneg(x[i]);} } } if (verbose) { if (return_value == tol_achieved) { printf("\nTerminated: |<g(x), d(x)>| driven below tol.\n"); } if (return_value == stop_maxnfeval) { printf("\nTerminated: reached maximum number of function evaluations\n"); } if (return_value == stop_maxiter) { printf("\nTerminated: reached maximum number of iterations\n"); } printf("Last f(x) = %10.4f\n\n", curr_fun_val); } *fun_val = curr_fun_val; return (int) return_value; }
GB_binop__isge_uint16.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__isge_uint16) // A.*B function (eWiseMult): GB (_AemultB_08__isge_uint16) // A.*B function (eWiseMult): GB (_AemultB_02__isge_uint16) // A.*B function (eWiseMult): GB (_AemultB_04__isge_uint16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__isge_uint16) // A*D function (colscale): GB (_AxD__isge_uint16) // D*A function (rowscale): GB (_DxB__isge_uint16) // C+=B function (dense accum): GB (_Cdense_accumB__isge_uint16) // C+=b function (dense accum): GB (_Cdense_accumb__isge_uint16) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__isge_uint16) // C=scalar+B GB (_bind1st__isge_uint16) // C=scalar+B' GB (_bind1st_tran__isge_uint16) // C=A+scalar GB (_bind2nd__isge_uint16) // C=A'+scalar GB (_bind2nd_tran__isge_uint16) // C type: uint16_t // A type: uint16_t // A pattern? 0 // B type: uint16_t // B pattern? 0 // BinaryOp: cij = (aij >= bij) #define GB_ATYPE \ uint16_t #define GB_BTYPE \ uint16_t #define GB_CTYPE \ uint16_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint16_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint16_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint16_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (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_ISGE || GxB_NO_UINT16 || GxB_NO_ISGE_UINT16) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__isge_uint16) ( 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__isge_uint16) ( 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__isge_uint16) ( 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 uint16_t uint16_t bwork = (*((uint16_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__isge_uint16) ( 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 uint16_t *restrict Cx = (uint16_t *) 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__isge_uint16) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t *restrict Cx = (uint16_t *) 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__isge_uint16) ( 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) ; uint16_t alpha_scalar ; uint16_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint16_t *) alpha_scalar_in)) ; beta_scalar = (*((uint16_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__isge_uint16) ( 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__isge_uint16) ( 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__isge_uint16) ( 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__isge_uint16) ( 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__isge_uint16) ( 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 uint16_t *Cx = (uint16_t *) Cx_output ; uint16_t x = (*((uint16_t *) x_input)) ; uint16_t *Bx = (uint16_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 ; uint16_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__isge_uint16) ( 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 ; uint16_t *Cx = (uint16_t *) Cx_output ; uint16_t *Ax = (uint16_t *) Ax_input ; uint16_t y = (*((uint16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint16_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) \ { \ uint16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x >= aij) ; \ } GrB_Info GB (_bind1st_tran__isge_uint16) ( 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 \ uint16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t x = (*((const uint16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint16_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) \ { \ uint16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij >= y) ; \ } GrB_Info GB (_bind2nd_tran__isge_uint16) ( 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 uint16_t y = (*((const uint16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
Vec.h
#ifndef VEC_H #define VEC_H /* Szymon Rusinkiewicz Princeton University Vec.h Class for a constant-length vector Supports the following operations: vec v1; // Initialized to (0,0,0) vec v2(1,2,3); // Initialized to (1,2,3) vec v3(v2); // Copy constructor float farray[3]; vec v4 = vec(farray); // Explicit: "v4 = farray" won't work Vec<3,double> vd; // The "vec" used above is Vec<3,float> point p1, p2, p3; // Same as vec v3 = v1 + v2; // Also -, *, / (all componentwise) v3 = 3.5f * v1; // Also vec * scalar, vec / scalar // NOTE: scalar has to be the same type: // it won't work to do double * vec<float> v1 = min(v2,v3); // Componentwise min/max v1 = sin(v2); // Componentwise - all the usual functions... swap(v1,v2); // In-place swap v3 = v1 DOT v2; // Actually operator^ v3 = v1 CROSS v2; // Actually operator% float f = v1[0]; // Subscript float *fp = v1; // Implicit conversion to float * f = len(v1); // Length (also len2 == squared length) f = dist(p1, p2); // Distance (also dist2 == squared distance) normalize(v1); // Normalize (i.e., make it unit length) // normalize(vec(0,0,0)) => vec(1,0,0) v1 = trinorm(p1,p2,p3); // Normal of triangle cout << v1 << endl; // iostream output in the form (1,2,3) cin >> v2; // iostream input using the same syntax Also defines the utility functions sqr, cube, sgn, fract, clamp, mix, step, smoothstep, faceforward, reflect, and refract */ // Windows defines these as macros, which prevents us from using the // type-safe versions from std::, as well as interfering with method defns #undef min #undef max #include <cmath> #include <iostream> #include <algorithm> using std::min; using std::max; using std::swap; using std::sqrt; // Let gcc optimize conditional branches a bit better... #ifndef likely # if !defined(__GNUC__) || (__GNUC__ == 2 && __GNUC_MINOR__ < 96) # define likely(x) (x) # define unlikely(x) (x) # else # define likely(x) (__builtin_expect((x), 1)) # define unlikely(x) (__builtin_expect((x), 0)) # endif #endif // Boost-like compile-time assertion checking template <bool X> struct VEC_STATIC_ASSERTION_FAILURE; template <> struct VEC_STATIC_ASSERTION_FAILURE<true> { void operator () () {} }; #define VEC_STATIC_CHECK(expr) VEC_STATIC_ASSERTION_FAILURE<bool(expr)>() template <int D, class T = float> class Vec { protected: T v[D]; public: // Constructor for no arguments. Everything initialized to 0. Vec() { for (int i = 0; i < D; i++) v[i] = T(0); } // Uninitialized constructor - meant mostly for internal use #define VEC_UNINITIALIZED ((void *) 0) Vec(void *) {} // Constructors for 2-4 arguments Vec(T x, T y) { VEC_STATIC_CHECK(D == 2); v[0] = x; v[1] = y; } Vec(T x, T y, T z) { VEC_STATIC_CHECK(D == 3); v[0] = x; v[1] = y; v[2] = z; } Vec(T x, T y, T z, T w) { VEC_STATIC_CHECK(D == 4); v[0] = x; v[1] = y; v[2] = z; v[3] = w; } // Constructor from anything that can be accessed using [] // Pretty aggressive, so marked as explicit. template <class S> explicit Vec(const S &x) { for (int i = 0; i < D; i++) v[i] = T(x[i]); } // No destructor or assignment operator needed // Array reference and conversion to pointer - no bounds checking const T &operator [] (int i) const { return v[i]; } T &operator [] (int i) { return v[i]; } operator const T * () const { return v; } operator const T * () { return v; } operator T * () { return v; } // Member operators Vec<D,T> &operator += (const Vec<D,T> &x) { for (int i = 0; i < D; i++) #pragma omp atomic v[i] += x[i]; return *this; } Vec<D,T> &operator -= (const Vec<D,T> &x) { for (int i = 0; i < D; i++) #pragma omp atomic v[i] -= x[i]; return *this; } Vec<D,T> &operator *= (const Vec<D,T> &x) { for (int i = 0; i < D; i++) #pragma omp atomic v[i] *= x[i]; return *this; } Vec<D,T> &operator *= (const T &x) { for (int i = 0; i < D; i++) #pragma omp atomic v[i] *= x; return *this; } Vec<D,T> &operator /= (const Vec<D,T> &x) { for (int i = 0; i < D; i++) #pragma omp atomic v[i] /= x[i]; return *this; } Vec<D,T> &operator /= (const T &x) { for (int i = 0; i < D; i++) #pragma omp atomic v[i] /= x; return *this; } // Set each component to min/max of this and the other vector Vec<D,T> &min(const Vec<D,T> &x) { #pragma omp critical for (int i = 0; i < D; i++) if (x[i] < v[i]) v[i] = x[i]; return *this; } Vec<D,T> &max(const Vec<D,T> &x) { #pragma omp critical for (int i = 0; i < D; i++) if (x[i] > v[i]) v[i] = x[i]; return *this; } // Outside of class: + - * / % ^ << >> // Some partial compatibility with valarrays and vectors typedef T value_type; size_t size() const { return D; } T sum() const { T total = v[0]; for (int i = 1; i < D; i++) total += v[i]; return total; } T avg() const { return sum() / D; } T product() const { T total = v[0]; for (int i = 1; i < D; i++) total *= v[i]; return total; } T min() const { T m = v[0]; for (int i = 1; i < D; i++) if (v[i] < m) m = v[i]; return m; } T max() const { T m = v[0]; for (int i = 1; i < D; i++) if (v[i] > m) m = v[i]; return m; } T *begin() { return &(v[0]); } const T *begin() const { return &(v[0]); } T *end() { return begin() + D; } const T *end() const { return begin() + D; } void clear() { for (int i = 0; i < D; i++) v[i] = T(0); } bool empty() const { for (int i = 0; i < D; i++) if (v[i]) return false; return true; } Vec<D,T> apply(T func(T)) const { Vec<D,T> result(VEC_UNINITIALIZED); for (int i = 0; i < D; i++) result[i] = func(v[i]); return result; } Vec<D,T> apply(T func(const T&)) const { Vec<D,T> result(VEC_UNINITIALIZED); for (int i = 0; i < D; i++) result[i] = func(v[i]); return result; } }; typedef Vec<3,float> vec; typedef Vec<3,float> point; typedef Vec<2,float> vec2; typedef Vec<3,float> vec3; typedef Vec<4,float> vec4; typedef Vec<2,int> ivec2; typedef Vec<3,int> ivec3; typedef Vec<4,int> ivec4; // Nonmember operators that take two Vecs template <int D, class T> static inline const Vec<D,T> operator + (const Vec<D,T> &v1, const Vec<D,T> &v2) { Vec<D,T> result(VEC_UNINITIALIZED); for (int i = 0; i < D; i++) result[i] = v1[i] + v2[i]; return result; } template <int D, class T> static inline const Vec<D,T> operator - (const Vec<D,T> &v1, const Vec<D,T> &v2) { Vec<D,T> result(VEC_UNINITIALIZED); for (int i = 0; i < D; i++) result[i] = v1[i] - v2[i]; return result; } template <int D, class T> static inline const Vec<D,T> operator * (const Vec<D,T> &v1, const Vec<D,T> &v2) { Vec<D,T> result(VEC_UNINITIALIZED); for (int i = 0; i < D; i++) result[i] = v1[i] * v2[i]; return result; } template <int D, class T> static inline const Vec<D,T> operator / (const Vec<D,T> &v1, const Vec<D,T> &v2) { Vec<D,T> result(VEC_UNINITIALIZED); for (int i = 0; i < D; i++) result[i] = v1[i] / v2[i]; return result; } // Dot product in any dimension template <int D, class T> static inline const T operator ^ (const Vec<D,T> &v1, const Vec<D,T> &v2) { T sum = v1[0] * v2[0]; for (int i = 1; i < D; i++) sum += v1[i] * v2[i]; return sum; } #define DOT ^ // Cross product - only in 3 dimensions template <class T> static inline const Vec<3,T> operator % (const Vec<3,T> &v1, const Vec<3,T> &v2) { return Vec<3,T>(v1[1]*v2[2] - v1[2]*v2[1], v1[2]*v2[0] - v1[0]*v2[2], v1[0]*v2[1] - v1[1]*v2[0]); } #define CROSS % // Component-wise equality and inequality (#include the usual caveats // about comparing floats for equality...) template <int D, class T> static inline bool operator == (const Vec<D,T> &v1, const Vec<D,T> &v2) { for (int i = 0; i < D; i++) if (v1[i] != v2[i]) return false; return true; } template <int D, class T> static inline bool operator != (const Vec<D,T> &v1, const Vec<D,T> &v2) { for (int i = 0; i < D; i++) if (v1[i] != v2[i]) return true; return false; } // Unary operators template <int D, class T> static inline const Vec<D,T> &operator + (const Vec<D,T> &v) { return v; } template <int D, class T> static inline const Vec<D,T> operator - (const Vec<D,T> &v) { Vec<D,T> result(VEC_UNINITIALIZED); for (int i = 0; i < D; i++) result[i] = -v[i]; return result; } template <int D, class T> static inline bool operator ! (const Vec<D,T> &v) { return v.empty(); } // Vec/scalar operators template <int D, class T> static inline const Vec<D,T> operator * (const T &x, const Vec<D,T> &v) { Vec<D,T> result(VEC_UNINITIALIZED); for (int i = 0; i < D; i++) result[i] = x * v[i]; return result; } template <int D, class T> static inline const Vec<D,T> operator * (const Vec<D,T> &v, const T &x) { Vec<D,T> result(VEC_UNINITIALIZED); for (int i = 0; i < D; i++) result[i] = v[i] * x; return result; } template <int D, class T> static inline const Vec<D,T> operator / (const T &x, const Vec<D,T> &v) { Vec<D,T> result(VEC_UNINITIALIZED); for (int i = 0; i < D; i++) result[i] = x / v[i]; return result; } template <int D, class T> static inline const Vec<D,T> operator / (const Vec<D,T> &v, const T &x) { Vec<D,T> result(VEC_UNINITIALIZED); for (int i = 0; i < D; i++) result[i] = v[i] / x; return result; } // iostream operators template <int D, class T> static inline std::ostream &operator << (std::ostream &os, const Vec<D,T> &v) { os << "("; for (int i = 0; i < D-1; i++) os << v[i] << ", "; return os << v[D-1] << ")"; } template <int D, class T> static inline std::istream &operator >> (std::istream &is, Vec<D,T> &v) { char c1 = 0, c2 = 0; is >> c1; if (c1 == '(' || c1 == '[') { is >> v[0] >> std::ws >> c2; for (int i = 1; i < D; i++) { if (c2 == ',') is >> v[i] >> std::ws >> c2; else is.setstate(std::ios::failbit); } } if (c1 == '(' && c2 != ')') is.setstate(std::ios::failbit); else if (c1 == '[' && c2 != ']') is.setstate(std::ios::failbit); return is; } // Utility functions for square and cube, to go along with sqrt and cbrt template <class T> static inline T sqr(const T &x) { return x*x; } // Functions on Vecs template <int D, class T> static inline void swap(const Vec<D,T> &v1, const Vec<D,T> &v2) { for (int i = 0; i < D; i++) swap(v1[i], v2[i]); } template <int D, class T> static inline const T len2(const Vec<D,T> &v) { T l2 = v[0] * v[0]; for (int i = 1; i < D; i++) l2 += v[i] * v[i]; return l2; } template <int D, class T> static inline const T len(const Vec<D,T> &v) { return sqrt(len2(v)); } template <int D, class T> static inline const T dist2(const Vec<D,T> &v1, const Vec<D,T> &v2) { T d2 = sqr(v2[0]-v1[0]); for (int i = 1; i < D; i++) d2 += sqr(v2[i]-v1[i]); return d2; } template <int D, class T> static inline const T dist(const Vec<D,T> &v1, const Vec<D,T> &v2) { return sqrt(dist2(v1,v2)); } template <int D, class T> static inline Vec<D,T> normalize(Vec<D,T> &v) { T l = len(v); if (unlikely(l <= T(0))) { v[0] = T(1); for (int i = 1; i < D; i++) v[i] = T(0); return v; } l = T(1) / l; for (int i = 0; i < D; i++) v[i] *= l; return v; } // Area-weighted triangle face normal template <class T> static inline T trinorm(const T &v0, const T &v1, const T &v2) { return (typename T::value_type) 0.5 * ((v1 - v0) CROSS (v2 - v0)); } // Square function moved up -- pm template <class T> static inline T cube(const T &x) { return x*x*x; } // Sign of a scalar template <class T> static inline T sgn(const T &x) { return (x < T(0)) ? T(-1) : T(1); } // Utility functions based on GLSL template <class T> static inline T fract(const T &x) { return x - floor(x); } template <class T> static inline T clamp(const T &x, const T &a, const T &b) { return x > a ? x < b ? x : b : a; // returns a on NaN } template <class T, class S> static inline T mix(const T &x, const T &y, const S &a) { return (S(1)-a) * x + a * y; } template <class T> static inline T step(const T &x, const T &a) { return x < a ? T(0) : T(1); } template <class T> static inline T smoothstep(const T &x, const T &a, const T &b) { if (b <= a) return step(x,a); T t = (x - a) / (b - a); return t <= T(0) ? T(0) : t >= T(1) ? T(1) : t * t * (T(3) - T(2) * t); } template <int D, class T> static inline T faceforward(const Vec<D,T> &N, const Vec<D,T> &I, const Vec<D,T> &Nref) { return ((Nref DOT I) < T(0)) ? N : -N; } template <int D, class T> static inline T reflect(const Vec<D,T> &I, const Vec<D,T> &N) { return I - (T(2) * (N DOT I)) * N; } template <int D, class T> static inline T refract(const Vec<D,T> &I, const Vec<D,T> &N, const T &eta) { T NdotI = N DOT I; T k = T(1) - sqr(eta) * (T(1) - sqr(NdotI)); return (k < T(0)) ? T(0) : eta * I - (eta * NdotI * sqrt(k)) * N; } // Generic macros for declaring 1-, 2-, and 3- argument // componentwise functions on vecs #define VEC_DECLARE_ONEARG(name) \ template <int D, class T> \ static inline Vec<D,T> name(const Vec<D,T> &v) \ { \ Vec<D,T> result(VEC_UNINITIALIZED); \ for (int i = 0; i < D; i++) \ result[i] = name(v[i]); \ return result; \ } #define VEC_DECLARE_TWOARG(name) \ template <int D, class T> \ static inline Vec<D,T> name(const Vec<D,T> &v, const T &w) \ { \ Vec<D,T> result(VEC_UNINITIALIZED); \ for (int i = 0; i < D; i++) \ result[i] = name(v[i], w); \ return result; \ } \ template <int D, class T> \ static inline Vec<D,T> name(const Vec<D,T> &v, const Vec<D,T> &w) \ { \ Vec<D,T> result(VEC_UNINITIALIZED); \ for (int i = 0; i < D; i++) \ result[i] = name(v[i], w[i]); \ return result; \ } #define VEC_DECLARE_THREEARG(name) \ template <int D, class T> \ static inline Vec<D,T> name(const Vec<D,T> &v, const T &w, const T &x) \ { \ Vec<D,T> result(VEC_UNINITIALIZED); \ for (int i = 0; i < D; i++) \ result[i] = name(v[i], w, x); \ return result; \ } \ template <int D, class T> \ static inline Vec<D,T> name(const Vec<D,T> &v, const Vec<D,T> &w, const Vec<D,T> &x) \ { \ Vec<D,T> result(VEC_UNINITIALIZED); \ for (int i = 0; i < D; i++) \ result[i] = name(v[i], w[i], x[i]); \ return result; \ } VEC_DECLARE_ONEARG(fabs) VEC_DECLARE_ONEARG(floor) VEC_DECLARE_ONEARG(ceil) VEC_DECLARE_ONEARG(round) VEC_DECLARE_ONEARG(trunc) VEC_DECLARE_ONEARG(sin) VEC_DECLARE_ONEARG(asin) VEC_DECLARE_ONEARG(cos) VEC_DECLARE_ONEARG(acos) VEC_DECLARE_ONEARG(tan) VEC_DECLARE_ONEARG(atan) VEC_DECLARE_ONEARG(exp) VEC_DECLARE_ONEARG(log) VEC_DECLARE_ONEARG(sqrt) VEC_DECLARE_ONEARG(sqr) VEC_DECLARE_ONEARG(cbrt) VEC_DECLARE_ONEARG(cube) VEC_DECLARE_ONEARG(sgn) VEC_DECLARE_TWOARG(min) VEC_DECLARE_TWOARG(max) VEC_DECLARE_TWOARG(atan2) VEC_DECLARE_TWOARG(pow) VEC_DECLARE_TWOARG(fmod) VEC_DECLARE_TWOARG(step) VEC_DECLARE_THREEARG(smoothstep) VEC_DECLARE_THREEARG(clamp) #undef VEC_DECLARE_ONEARG #undef VEC_DECLARE_TWOARG #undef VEC_DECLARE_THREEARG // Both valarrays and GLSL use abs() on a vector to mean fabs(). // Let's be compatible... template <int D, class T> static inline Vec<D,T> abs(const Vec<D,T> &v) { return fabs(v); } #endif
communication.h
/*! @brief Flag for checking if this header has already been included. */ #ifndef YGGCOMMUNICATION_H_ #define YGGCOMMUNICATION_H_ #include "../tools.h" #include "../datatypes/datatypes.h" #include "CommBase.h" #include "IPCComm.h" #include "ZMQComm.h" #include "ServerComm.h" #include "ClientComm.h" #include "AsciiFileComm.h" #include "AsciiTableComm.h" #include "DefaultComm.h" #ifdef __cplusplus /* If this is a C++ compiler, use C linkage */ extern "C" { #endif /*! @brief Memory to keep track of comms to clean up at exit. */ static void **vcomms2clean = NULL; static size_t ncomms2clean = 0; static size_t clean_registered = 0; static size_t clean_in_progress = 0; static size_t clean_called = 0; #ifdef _OPENMP #pragma omp threadprivate(clean_in_progress) #endif /*! @brief Memory to keep track of global scope comms. */ #ifdef _OPENMP static size_t global_scope_comm = 1; #define WITH_GLOBAL_SCOPE(COMM) global_scope_comm = 1; COMM #pragma omp threadprivate(global_scope_comm) #else static size_t global_scope_comm = 0; #define WITH_GLOBAL_SCOPE(COMM) global_scope_comm = 1; COMM; global_scope_comm = 0 #endif /*! @brief Check if EOF should be sent for a comm being used on multiple threads. @param[in] x const comm_t* Comm to check. @returns int 1 if EOF has been sent for all but this comm and 0 otherwise. */ static int check_threaded_eof(const comm_t* x) { int out = 1; #ifdef _OPENMP #pragma omp critical (comms) { size_t i; comm_t* icomm = NULL; int nthreads = 1; for (i = 0; i < ncomms2clean; i++) { if ((out == 1) && (vcomms2clean[i] != NULL)) { icomm = (comm_t*)(vcomms2clean[i]); if ((strcmp(icomm->name, x->name) == 0) && (icomm->thread_id != x->thread_id)) { nthreads++; #pragma omp critical (sent_eof) { if ((x->const_flags != NULL) && (!(x->const_flags[0] & COMM_EOF_SENT))) out = 0; } } } } if (nthreads < omp_get_num_threads()) out = 0; // all threads havn't initialized a comm } #endif return out; }; /*! @brief Set the sent_eof flag on the comm. @param[in] x comm_t* Comm to set the flag for. */ static void set_sent_eof(const comm_t* x) { #ifdef _OPENMP #pragma omp critical (sent_eof) { #endif x->const_flags[0] = x->const_flags[0] | COMM_EOF_SENT; if (x->type == CLIENT_COMM) { comm_t *req_comm = (comm_t*)(x->handle); // Don't recurse to prevent block w/ omp critical recursion req_comm->const_flags[0] = req_comm->const_flags[0] | COMM_EOF_SENT; } #ifdef _OPENMP } #endif }; /*! @brief Retrieve a registered global comm if it exists. @param[in] const char* name Name that comm might be registered under. @returns comm_t* Pointer to registered comm. NULL if one does not exist with the specified name. */ static comm_t* get_global_scope_comm(const char *name) { comm_t* out = NULL; #ifdef _OPENMP #pragma omp critical (comms) { #endif if (global_scope_comm) { size_t i; comm_t* icomm = NULL; int current_thread = get_thread_id(); for (i = 0; i < ncomms2clean; i++) { if (vcomms2clean[i] != NULL) { icomm = (comm_t*)(vcomms2clean[i]); if ((strcmp(icomm->name, name) == 0) && (icomm->thread_id == current_thread)) { out = icomm; break; } else { const char* YGG_MODEL_NAME = getenv("YGG_MODEL_NAME"); char alt_name[100]; sprintf(alt_name, "%s:%s", YGG_MODEL_NAME, name); if ((strcmp(icomm->name, alt_name) == 0) && (icomm->thread_id == current_thread)) { out = icomm; break; } } } } } #ifdef _OPENMP } #endif return out; }; // Forward declaration of eof static int comm_send_eof(const comm_t *x); static int comm_nmsg(const comm_t *x); /*! @brief Determine if a channel has a format type associated with it. @param[in] x comm_t * Pointer to communicator to check. @returns int 1 if format type, 0 otherwise. */ static int is_comm_format_array_type(const comm_t *x) { dtype_t *datatype = x->datatype; return is_dtype_format_array(datatype); }; /*! @brief Determine if the current thread can use a comm registered by another. @param[in] int Thread that created the comm. @returns int 1 if the current thread can use the comm, 0 otherwise. */ static int thread_can_use(int thread_id) { int current_thread_id = get_thread_id(); if ((clean_in_progress) && (current_thread_id == 0)) return 1; if (thread_id == current_thread_id) return 1; return 0; }; /*! @brief Perform deallocation for type specific communicator. @param[in] x comm_t * Pointer to communicator to deallocate. @returns int 1 if there is an error, 0 otherwise. */ static int free_comm_type(comm_t *x) { comm_type t = x->type; int ret = 1; if (!(thread_can_use(x->thread_id))) { ygglog_error("free_comm_type: Thread is attempting to use a comm it did not initialize"); return ret; } if (t == IPC_COMM) ret = free_ipc_comm(x); else if (t == ZMQ_COMM) ret = free_zmq_comm(x); else if (t == SERVER_COMM) ret = free_server_comm(x); else if (t == CLIENT_COMM) ret = free_client_comm(x); else if (t == ASCII_FILE_COMM) ret = free_ascii_file_comm(x); else if ((t == ASCII_TABLE_COMM) || (t == ASCII_TABLE_ARRAY_COMM)) ret = free_ascii_table_comm(x); else { ygglog_error("free_comm_type: Unsupported comm_type %d", t); } return ret; }; /*! @brief Perform deallocation for generic communicator. @param[in] x comm_t * Pointer to communicator to deallocate. @returns int 1 if there is an error, 0 otherwise. */ static int free_comm(comm_t *x) { int ret = 0; if (x == NULL) return ret; ygglog_debug("free_comm(%s)", x->name); // Send EOF for output comms and then wait for messages to be recv'd if ((is_send(x->direction)) && (x->flags & COMM_FLAG_VALID)) { if (_ygg_error_flag == 0) { ygglog_debug("free_comm(%s): Sending EOF", x->name); comm_send_eof(x); while (comm_nmsg(x) > 0) { ygglog_debug("free_comm(%s): draining %d messages", x->name, comm_nmsg(x)); usleep(YGG_SLEEP_TIME); } } else { ygglog_error("free_comm(%s): Error registered", x->name); } } #ifdef _OPENMP #pragma omp critical (comms) { #endif ret = free_comm_type(x); int idx = x->index_in_register; free_comm_base(x); if (idx >= 0) { if (vcomms2clean[idx] != NULL) { free(vcomms2clean[idx]); vcomms2clean[idx] = NULL; } } ygglog_debug("free_comm: Finished"); #ifdef _OPENMP } #endif return ret; }; /*! @brief Free comms created that were not freed. */ static void clean_comms(void) { #ifdef _OPENMP #pragma omp critical (clean) { #endif size_t i; if (!(clean_called)) { clean_in_progress = 1; ygglog_debug("atexit begin"); if (vcomms2clean != NULL) { for (i = 0; i < ncomms2clean; i++) { if (vcomms2clean[i] != NULL) { free_comm((comm_t*)(vcomms2clean[i])); } } } #ifdef _OPENMP #pragma omp critical (comms) { #endif if (vcomms2clean != NULL) { free(vcomms2clean); vcomms2clean = NULL; } ncomms2clean = 0; ygglog_debug("atexit finished cleaning comms, in final shutdown"); #if defined(ZMQINSTALLED) // #if defined(_MSC_VER) && defined(ZMQINSTALLED) ygg_zsys_shutdown(); #endif if (Py_IsInitialized()) { Py_Finalize(); } /* printf(""); */ clean_called = 1; #ifdef _OPENMP } #endif } #ifdef _OPENMP } #endif ygglog_debug("atexit done"); if (_ygg_error_flag != 0) { _exit(_ygg_error_flag); } }; /*! @brief Initialize yggdrasil in a thread-safe way */ static inline int ygg_init() { int out = 0; #ifdef _OPENMP #pragma omp critical (init) { #endif ygglog_debug("ygg_init: clean_registered = %d", clean_registered); if (clean_registered == 0) { #if defined(ZMQINSTALLED) if (!(ygg_zsys_init())) { out = -1; } #endif if (out == 0) { ygglog_debug("ygg_init: Registering cleanup"); atexit(clean_comms); clean_registered = 1; } } #ifdef _OPENMP } #endif return out; }; /*! @brief Register a comm so that it can be cleaned up later if not done explicitly. @param[in] x comm_t* Address of communicator structure that should be registered. @returns int -1 if there is an error, 0 otherwise. */ static int register_comm(comm_t *x) { if (x == NULL) { return 0; } int error_flag = 0; #ifdef _OPENMP #pragma omp critical (comms) { #endif if (ygg_init()) { error_flag = 1; } else { void **t_vcomms2clean = (void**)realloc(vcomms2clean, sizeof(void*)*(ncomms2clean + 1)); if (t_vcomms2clean == NULL) { ygglog_error("register_comm(%s): Failed to realloc the comm list.", x->name); error_flag = -1; } else { vcomms2clean = t_vcomms2clean; x->index_in_register = (int)ncomms2clean; vcomms2clean[ncomms2clean++] = (void*)x; } } #ifdef _OPENMP } #endif return error_flag; }; /*! @brief Initialize a new communicator based on its type. @param[in] x comm_t * Pointer to communicator structure initialized with new_base_comm; @returns int -1 if the comm could not be initialized. */ static int new_comm_type(comm_t *x) { comm_type t = x->type; int flag; if (t == IPC_COMM) flag = new_ipc_address(x); else if (t == ZMQ_COMM) flag = new_zmq_address(x); else if (t == SERVER_COMM) flag = new_server_address(x); else if (t == CLIENT_COMM) flag = new_client_address(x); else if (t == ASCII_FILE_COMM) flag = new_ascii_file_address(x); else if (t == ASCII_TABLE_COMM) flag = new_ascii_table_address(x); else if (t == ASCII_TABLE_ARRAY_COMM) flag = new_ascii_table_array_address(x); else { ygglog_error("new_comm_type: Unsupported comm_type %d", t); flag = -1; } return flag; }; /*! @brief Initialize the communicator based on its type. @param[in] x comm_t * Pointer to communicator structure initialized with init_base_comm; @returns int -1 if the comm could not be initialized. */ static int init_comm_type(comm_t *x) { comm_type t = x->type; int flag; if (t == IPC_COMM) flag = init_ipc_comm(x); else if (t == ZMQ_COMM) flag = init_zmq_comm(x); else if (t == SERVER_COMM) flag = init_server_comm(x); else if (t == CLIENT_COMM) flag = init_client_comm(x); else if (t == ASCII_FILE_COMM) flag = init_ascii_file_comm(x); else if (t == ASCII_TABLE_COMM) flag = init_ascii_table_comm(x); else if (t == ASCII_TABLE_ARRAY_COMM) flag = init_ascii_table_array_comm(x); else { ygglog_error("init_comm_type: Unsupported comm_type %d", t); flag = -1; } ygglog_debug("init_comm_type(%s): Done, flag = %d", x->name, flag); return flag; }; /*! @brief Initialize comm from the address. @param[in] address char * Address for new comm. If NULL, a new address is generated. @param[in] direction Direction that messages will go through the comm. Values include "recv" and "send". @param[in] t comm_type Type of comm that should be created. @param[in] datatype dtype_t* Pointer to data type structure. @returns comm_t* Pointer to comm structure. */ static comm_t* new_comm(char *address, const char *direction, const comm_type t, dtype_t* datatype) { comm_t *ret = new_comm_base(address, direction, t, datatype); if (ret == NULL) { ygglog_error("new_comm: Could not initialize base."); return ret; } int flag; if (address == NULL) { flag = new_comm_type(ret); } else { flag = init_comm_type(ret); } if (flag < 0) { ygglog_error("new_comm: Failed to initialize new comm address."); ret->flags = ret->flags & ~COMM_FLAG_VALID; } else { if (strlen(ret->name) == 0) { sprintf(ret->name, "temp.%s", ret->address); } flag = register_comm(ret); if (flag < 0) { ygglog_error("new_comm: Failed to register new comm."); ret->flags = ret->flags & ~COMM_FLAG_VALID; } } return ret; }; /*! @brief Initialize a generic communicator. The name is used to locate the comm address stored in the associated environment variable. @param[in] name Name of environment variable that the queue address is stored in. @param[in] direction Direction that messages will go through the comm. Values include "recv" and "send". @param[in] t comm_type Type of comm that should be created. @param[in] datatype dtype_t* Pointer to data type structure. @returns comm_t* Comm structure. */ static comm_t* init_comm(const char *name, const char *direction, const comm_type t, dtype_t *datatype) { ygglog_debug("init_comm: Initializing comm."); #ifdef _MSC_VER SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); _set_abort_behavior(0,_WRITE_ABORT_MSG); #endif comm_t *ret = get_global_scope_comm(name); if (ret != NULL) { destroy_dtype(&datatype); return ret; } if ((datatype == NULL) && (strcmp(direction, "send") == 0)) { datatype = create_dtype_scalar("bytes", 0, "", false); } ret = init_comm_base(name, direction, t, datatype); if (ret == NULL) { ygglog_error("init_comm(%s): Could not initialize base.", name); return ret; } int flag = init_comm_type(ret); if (flag < 0) { ygglog_error("init_comm(%s): Could not initialize comm.", name); ret->flags = ret->flags & ~COMM_FLAG_VALID; } else { flag = register_comm(ret); if (flag < 0) { ygglog_error("init_comm(%s): Failed to register new comm.", name); ret->flags = ret->flags & ~COMM_FLAG_VALID; } } if (ret->flags & COMM_FLAG_VALID) { if (global_scope_comm) { ret->flags = ret->flags | COMM_FLAG_GLOBAL; ygglog_debug("init_comm(%s): Global comm!", name); } ygglog_debug("init_comm(%s): Initialized comm.", name); } return ret; }; /*! @brief Convert a format string to a datatype. @param[in] format_str char* Format string. @param[in] as_array int If 1, inputs/outputs are processed as arrays. @returns dtype_t* Pointer to datatype structure. */ static dtype_t* formatstr2datatype(const char *format_str, const int as_array) { dtype_t* datatype = NULL; if (format_str != NULL) { datatype = create_dtype_format(format_str, as_array, false); } return datatype; }; /*! @brief Initialize a generic communicator using a format string to determine the type. The name is used to locate the comm address stored in the associated environment variable. @param[in] name Name of environment variable that the queue address is stored in. @param[in] direction Direction that messages will go through the comm. Values include "recv" and "send". @param[in] t comm_type Type of comm that should be created. @param[in] format_str char* Format string. @param[in] as_array int If 1, inputs/outputs are processed as arrays. @returns comm_t* Pointer to comm structure. */ static comm_t* init_comm_format(const char *name, const char *direction, const comm_type t, const char *format_str, const int as_array) { dtype_t* datatype = formatstr2datatype(format_str, as_array); comm_t* out = init_comm(name, direction, t, datatype); if ((format_str != NULL) && (datatype == NULL)) { ygglog_error("init_comm_format: Failed to create type from format_str."); if (out != NULL) { out->flags = out->flags & ~COMM_FLAG_VALID; } } return out; }; /*! @brief Get number of messages in the comm. @param[in] x comm_t Communicator to check. @returns int Number of messages. */ static int comm_nmsg(const comm_t *x) { int ret = -1; if ((x == NULL) || (!(x->flags & COMM_FLAG_VALID))) { ygglog_error("comm_nmsg: Invalid comm"); return ret; } comm_type t = x->type; if (t == IPC_COMM) ret = ipc_comm_nmsg(x); else if (t == ZMQ_COMM) ret = zmq_comm_nmsg(x); else if (t == SERVER_COMM) ret = server_comm_nmsg(x); else if (t == CLIENT_COMM) ret = client_comm_nmsg(x); else if (t == ASCII_FILE_COMM) ret = ascii_file_comm_nmsg(x); else if ((t == ASCII_TABLE_COMM) || (t == ASCII_TABLE_ARRAY_COMM)) ret = ascii_table_comm_nmsg(x); else { ygglog_error("comm_nmsg: Unsupported comm_type %d", t); } return ret; }; /*! @brief Send a single message to the comm. Send a message smaller than YGG_MSG_MAX bytes to an output comm. If the message is larger, it will not be sent. @param[in] x comm_t* structure that comm should be sent to. @param[in] data character pointer to message that should be sent. @param[in] len size_t length of message to be sent. @returns int 0 if send succesfull, -1 if send unsuccessful. */ static int comm_send_single(const comm_t *x, const char *data, const size_t len) { ygglog_debug("Sending %d bytes: '%s'\n", len, data); int ret = -1; if ((x == NULL) || (!(x->flags & COMM_FLAG_VALID))) { ygglog_error("comm_send_single: Invalid comm"); return ret; } if (!(thread_can_use(x->thread_id))) { ygglog_error("comm_send_single: Thread is attempting to use a comm it did not initialize"); return ret; } comm_type t = x->type; if (t == IPC_COMM) ret = ipc_comm_send(x, data, len); else if (t == ZMQ_COMM) ret = zmq_comm_send(x, data, len); else if (t == SERVER_COMM) ret = server_comm_send(x, data, len); else if (t == CLIENT_COMM) ret = client_comm_send(x, data, len); else if (t == ASCII_FILE_COMM) ret = ascii_file_comm_send(x, data, len); else if ((t == ASCII_TABLE_COMM) || (t == ASCII_TABLE_ARRAY_COMM)) ret = ascii_table_comm_send(x, data, len); else { ygglog_error("comm_send_single: Unsupported comm_type %d", t); } if (ret >= 0) { time(x->last_send); /* time_t now; */ /* time(&now); */ /* x->last_send[0] = now; */ } return ret; }; /*! @brief Create header for multipart message. @param[in] x comm_t* structure that header will be sent to. @param[in] data const char * Message to be sent. @param[in] len size_t Size of message body. @returns comm_head_t Header info that should be sent before the message body. */ static comm_head_t comm_send_multipart_header(const comm_t *x, const char * data, const size_t len) { comm_head_t head = init_header(len, NULL, NULL); sprintf(head.id, "%d", rand()); char *model_name = getenv("YGG_MODEL_NAME"); if (model_name != NULL) { strcpy(head.model, model_name); } head.flags = head.flags | HEAD_FLAG_VALID | HEAD_FLAG_MULTIPART; // Add datatype information to header if (!(x->flags & COMM_FLAG_FILE)) { dtype_t *datatype; if (x->type == CLIENT_COMM) { comm_t *req_comm = (comm_t*)(x->handle); datatype = req_comm->datatype; } else { datatype = x->datatype; } head.dtype = datatype; } const comm_t *x0; if (x->type == SERVER_COMM) { if (!(is_eof(data))) { head = server_response_header(x, head); } x0 = server_get_comm((requests_t*)(x->info), 0); if (x0 == NULL) { ygglog_error("comm_send_multipart_header(%s): no response comm registered", x->name); head.flags = head.flags & ~HEAD_FLAG_VALID; return head; } // This gives the server access to the ID of the message last received strcpy(head.id, x->address); } else if (x->type == CLIENT_COMM) { if (!(is_eof(data))) { head = client_response_header(x, head); } x0 = (comm_t*)(x->handle); } else { x0 = x; } // Get ZMQ header info if (x0->type == ZMQ_COMM) { char *reply_address = set_reply_send(x0); if (reply_address == NULL) { ygglog_error("comm_send_multipart_header: Could not set reply address."); head.flags = head.flags & ~HEAD_FLAG_VALID; return head; } strcpy(head.zmq_reply, reply_address); ygglog_debug("reply_address = %s\n", head.zmq_reply); } return head; }; /*! @brief Send a large message in multiple parts via a new comm. @param[in] x comm_t* Structure that message should be sent to. @param[in] data const char * Message that should be sent. @param[in] len size_t Size of data. @returns: int 0 if send successfull, -1 if send unsuccessful. */ static int comm_send_multipart(const comm_t *x, const char *data, const size_t len) { //char headbuf[YGG_MSG_BUF]; size_t headbuf_len = YGG_MSG_BUF; int headlen = 0, ret = -1; comm_t* xmulti = NULL; int no_type = is_eof(data); if ((x == NULL) || (!(x->flags & COMM_FLAG_VALID))) { ygglog_error("comm_send_multipart: Invalid comm"); return ret; } // Get header comm_head_t head = comm_send_multipart_header(x, data, len); if (!(head.flags & HEAD_FLAG_VALID)) { ygglog_error("comm_send_multipart: Invalid header generated."); return -1; } char *headbuf = (char*)malloc(headbuf_len); if (headbuf == NULL) { ygglog_error("comm_send_multipart: Failed to malloc headbuf."); return -1; } // Try to send body in header if (len < (x->maxMsgSize - x->msgBufSize)) { headlen = format_comm_header(&head, &headbuf, headbuf_len, x->maxMsgSize - x->msgBufSize, no_type); if (headlen < 0) { ygglog_error("comm_send_multipart: Failed to format header."); free(headbuf); return -1; } if (((size_t)headlen + len) < (x->maxMsgSize - x->msgBufSize)) { if (((size_t)headlen + len + 1) > headbuf_len) { char *t_headbuf = (char*)realloc(headbuf, (size_t)headlen + len + 1); if (t_headbuf == NULL) { ygglog_error("comm_send_multipart: Failed to realloc headbuf."); free(headbuf); return -1; } headbuf = t_headbuf; headbuf_len = (size_t)headlen + len + 1; } head.flags = head.flags & ~HEAD_FLAG_MULTIPART; memcpy(headbuf + headlen, data, len); headlen += (int)len; headbuf[headlen] = '\0'; } } // Get head string if (head.flags & HEAD_FLAG_MULTIPART) { // Get address for new comm and add to header xmulti = new_comm(NULL, "send", x->type, NULL); if ((xmulti == NULL) || (!(xmulti->flags & COMM_FLAG_VALID))) { ygglog_error("comm_send_multipart: Failed to initialize a new comm."); free(headbuf); return -1; } xmulti->const_flags[0] = xmulti->const_flags[0] | COMM_EOF_SENT | COMM_EOF_RECV; xmulti->flags = xmulti->flags | COMM_FLAG_WORKER; strcpy(head.address, xmulti->address); if (xmulti->type == ZMQ_COMM) { char *reply_address = set_reply_send(xmulti); if (reply_address == NULL) { ygglog_error("comm_send_multipart: Could not set worker reply address."); return -1; } strcpy(head.zmq_reply_worker, reply_address); ygglog_debug("comm_send_multipart: zmq worker reply address is '%s'", head.zmq_reply_worker); } headlen = format_comm_header(&head, &headbuf, headbuf_len, x->maxMsgSize - x->msgBufSize, no_type); if (headlen < 0) { ygglog_error("comm_send_multipart: Failed to format header."); free(headbuf); if (xmulti != NULL) { free_comm(xmulti); } return -1; } } // Send header size_t data_in_header = 0; if ((head.flags & HEAD_TYPE_IN_DATA) && ((size_t)headlen > (x->maxMsgSize - x->msgBufSize))) { ret = comm_send_single(x, headbuf, x->maxMsgSize - x->msgBufSize); data_in_header = headlen - (x->maxMsgSize - x->msgBufSize); } else { ret = comm_send_single(x, headbuf, headlen); } if (ret < 0) { ygglog_error("comm_send_multipart: Failed to send header."); if (xmulti != NULL) { free_comm(xmulti); } free(headbuf); return -1; } if (!(head.flags & HEAD_FLAG_MULTIPART)) { ygglog_debug("comm_send_multipart(%s): %d bytes completed", x->name, head.size); free(headbuf); return ret; } // Send data stored in header size_t msgsiz; size_t prev = headlen - data_in_header; while (prev < (size_t)headlen) { if ((headlen - prev) > (xmulti->maxMsgSize - xmulti->msgBufSize)) { msgsiz = xmulti->maxMsgSize - xmulti->msgBufSize; } else { msgsiz = headlen - prev; } ret = comm_send_single(xmulti, headbuf + prev, msgsiz); if (ret < 0) { ygglog_debug("comm_send_multipart(%s): send of data in header interupted at %d of %d bytes.", x->name, prev - (headlen - data_in_header), data_in_header); break; } prev += msgsiz; ygglog_debug("comm_send_multipart(%s): %d of %d bytes sent from data in header", x->name, prev - (headlen - data_in_header), data_in_header); } head.size = head.size - data_in_header; if (ret < 0) { ygglog_error("comm_send_multipart: Failed to send data from header."); if (xmulti != NULL) { free_comm(xmulti); } free(headbuf); return -1; } // Send multipart prev = 0; while (prev < head.size) { if ((head.size - prev) > (xmulti->maxMsgSize - xmulti->msgBufSize)) { msgsiz = xmulti->maxMsgSize - xmulti->msgBufSize; } else { msgsiz = head.size - prev; } ret = comm_send_single(xmulti, data + prev, msgsiz); if (ret < 0) { ygglog_debug("comm_send_multipart(%s): send interupted at %d of %d bytes.", x->name, prev, head.size); break; } prev += msgsiz; ygglog_debug("comm_send_multipart(%s): %d of %d bytes sent", x->name, prev, head.size); } if (ret == 0) ygglog_debug("comm_send_multipart(%s): %d bytes completed", x->name, head.size); // Free multipart if (xmulti != NULL) { free_comm(xmulti); } free(headbuf); if (ret >= 0) x->const_flags[0] = x->const_flags[0] | COMM_FLAGS_USED; return ret; }; /*! @brief Send a message to the comm. Send a message smaller than YGG_MSG_MAX bytes to an output comm. If the message is larger, it will not be sent. @param[in] x comm_t* structure that comm should be sent to. @param[in] data character pointer to message that should be sent. @param[in] len size_t length of message to be sent. @returns int 0 if send succesfull, -1 if send unsuccessful. */ static int comm_send(const comm_t *x, const char *data, const size_t len) { int ret = -1; if ((x == NULL) || (!(x->flags & COMM_FLAG_VALID))) { ygglog_error("comm_send: Invalid comm"); return ret; } if (x->const_flags == NULL) { ygglog_error("comm_send(%s): const_flags not initialized.", x->name); return ret; } int sending_eof = 0; if (is_eof(data)) { if (x->const_flags[0] & COMM_EOF_SENT) { ygglog_debug("comm_send(%s): EOF already sent", x->name); return ret; } else if (!(check_threaded_eof(x))) { ygglog_debug("comm_send(%s): EOF not sent on other threads", x->name); set_sent_eof(x); return 0; } else { set_sent_eof(x); sending_eof = 1; ygglog_debug("comm_send(%s): Sending EOF", x->name); } } if (((len > x->maxMsgSize) && (x->maxMsgSize > 0)) || (((x->flags & COMM_ALWAYS_SEND_HEADER) || (!(x->const_flags[0] & COMM_FLAGS_USED))))) { ygglog_debug("comm_send(%s): Sending as one or more messages with a header.", x->name); ret = comm_send_multipart(x, data, len); } else { ygglog_debug("comm_send(%s): Sending as single message without a header.", x->name); ret = comm_send_single(x, data, len); } if (sending_eof) { ygglog_debug("comm_send(%s): sent EOF, ret = %d", x->name, ret); } if (ret >= 0) x->const_flags[0] = x->const_flags[0] | COMM_FLAGS_USED; return ret; }; /*! @brief Send EOF message to the comm. @param[in] x comm_t structure that message should be sent to. @returns int 0 if send successfull, -1 otherwise. */ static int comm_send_eof(const comm_t *x) { int ret = -1; char buf[100] = YGG_MSG_EOF; ret = comm_send(x, buf, strlen(buf)); return ret; }; /*! @brief Receive a message from an input comm. Receive a message smaller than YGG_MSG_MAX bytes from an input comm. @param[in] x comm_t* structure that message should be sent to. @param[out] data char ** pointer to allocated buffer where the message should be saved. This should be a malloc'd buffer if allow_realloc is 1. @param[in] len const size_t length of the allocated message buffer in bytes. @param[in] allow_realloc const int If 1, the buffer will be realloced if it is not large enought. Otherwise an error will be returned. @returns int -1 if message could not be received, otherwise the length of the received message. */ static int comm_recv_single(comm_t *x, char **data, const size_t len, const int allow_realloc) { int ret = -1; if ((x == NULL) || (!(x->flags & COMM_FLAG_VALID))) { ygglog_error("comm_recv_single: Invalid comm"); return ret; } if (!(thread_can_use(x->thread_id))) { ygglog_error("comm_recv_single: Thread is attempting to use a comm it did not initialize"); return ret; } comm_type t = x->type; if (t == IPC_COMM) ret = ipc_comm_recv(x, data, len, allow_realloc); else if (t == ZMQ_COMM) ret = zmq_comm_recv(x, data, len, allow_realloc); else if (t == SERVER_COMM) ret = server_comm_recv(x, data, len, allow_realloc); else if (t == CLIENT_COMM) ret = client_comm_recv(x, data, len, allow_realloc); else if (t == ASCII_FILE_COMM) ret = ascii_file_comm_recv(x, data, len, allow_realloc); else if ((t == ASCII_TABLE_COMM) || (t == ASCII_TABLE_ARRAY_COMM)) ret = ascii_table_comm_recv(x, data, len, allow_realloc); else { ygglog_error("comm_recv: Unsupported comm_type %d", t); } return ret; }; /*! @brief Receive a message in multiple parts. @param[in] x comm_t* Comm that message should be recieved from. @param[in] data char ** Pointer to buffer where message should be stored. @param[in] len size_t Size of data buffer. @param[in] headlen size_t Size of header in data buffer. @param[in] allow_realloc int If 1, data will be realloced if the incoming message is larger than the buffer. Otherwise, an error will be returned. @returns int -1 if unsucessful, size of message received otherwise. */ static int comm_recv_multipart(comm_t *x, char **data, const size_t len, const size_t headlen, const int allow_realloc) { int ret = -1; if ((x == NULL) || (!(x->flags & COMM_FLAG_VALID))) { ygglog_error("comm_recv_multipart: Invalid comm"); return ret; } usleep(100); comm_head_t head = parse_comm_header(*data, headlen); if (!(head.flags & HEAD_FLAG_VALID)) { ygglog_error("comm_recv_multipart(%s): Error parsing header.", x->name); ret = -1; } else { // Move body to front of data and return if EOF memmove(*data, *data + head.bodybeg, head.bodysiz); (*data)[head.bodysiz] = '\0'; if (is_eof(*data)) { ygglog_debug("comm_recv_multipart(%s): EOF received.", x->name); x->const_flags[0] = x->const_flags[0] | COMM_EOF_RECV; destroy_header(&head); return -2; } // Get datatype information from header on first recv dtype_t *updtype; if (x->type == SERVER_COMM) { comm_t *handle = (comm_t*)(x->handle); updtype = handle->datatype; } else { updtype = x->datatype; } if ((!(x->const_flags[0] & COMM_FLAGS_USED)) && (!(x->flags & COMM_FLAG_FILE)) && (updtype->obj == NULL) && (!(head.flags & HEAD_TYPE_IN_DATA))) { ygglog_debug("comm_recv_multipart(%s): Updating datatype to '%s'", x->name, head.dtype->type); ret = update_dtype(updtype, head.dtype); if (ret != 0) { ygglog_error("comm_recv_multipart(%s): Error updating datatype.", x->name); destroy_header(&head); return -1; } } else if ((!(x->flags & COMM_FLAG_FILE)) && (head.dtype != NULL)) { ret = update_dtype(updtype, head.dtype); if (ret != 0) { ygglog_error("comm_recv_multipart(%s): Error updating existing datatype.", x->name); destroy_header(&head); return -1; } } if (head.flags & HEAD_FLAG_MULTIPART) { // Return early if header contained entire message if (head.size == head.bodysiz) { x->const_flags[0] = x->const_flags[0] | COMM_FLAGS_USED; destroy_header(&head); return (int)(head.bodysiz); } // Get address for new comm comm_t* xmulti = new_comm(head.address, "recv", x->type, NULL); if ((xmulti == NULL) || (!(xmulti->flags & COMM_FLAG_VALID))) { ygglog_error("comm_recv_multipart: Failed to initialize a new comm."); destroy_header(&head); return -1; } xmulti->const_flags[0] = xmulti->const_flags[0] | COMM_EOF_SENT | COMM_EOF_RECV; xmulti->flags = xmulti->flags | COMM_FLAG_WORKER; if (xmulti->type == ZMQ_COMM) { int reply_socket = set_reply_recv(xmulti, head.zmq_reply_worker); if (reply_socket < 0) { ygglog_error("comm_recv_multipart: Failed to set worker reply address."); destroy_header(&head); return -1; } } // Receive parts of message size_t prev = head.bodysiz; size_t msgsiz = 0; // Reallocate data if necessary if ((head.size + 1) > len) { if (allow_realloc) { char *t_data = (char*)realloc(*data, head.size + 1); if (t_data == NULL) { ygglog_error("comm_recv_multipart(%s): Failed to realloc buffer", x->name); free(*data); free_comm(xmulti); destroy_header(&head); return -1; } *data = t_data; } else { ygglog_error("comm_recv_multipart(%s): buffer is not large enough", x->name); free_comm(xmulti); destroy_header(&head); return -1; } } ret = -1; char *pos = (*data) + prev; while (prev < head.size) { msgsiz = head.size - prev + 1; ret = comm_recv_single(xmulti, &pos, msgsiz, 0); if (ret < 0) { ygglog_debug("comm_recv_multipart(%s): recv interupted at %d of %d bytes.", x->name, prev, head.size); break; } prev += ret; pos += ret; ygglog_debug("comm_recv_multipart(%s): %d of %d bytes received", x->name, prev, head.size); } if ((ret > 0) && (head.flags & HEAD_TYPE_IN_DATA)) { ygglog_debug("comm_recv_multipart(%s): Extracting type from data."); ret = parse_type_in_data(data, prev, &head); if (ret > 0) { prev = ret; ret = update_dtype(updtype, head.dtype); if (ret != 0) { ygglog_error("comm_recv_multipart(%s): Error updating existing datatype.", x->name); destroy_header(&head); return -1; } else { ret = (int)prev; } } } if (ret > 0) { ygglog_debug("comm_recv_multipart(%s): %d bytes completed", x->name, prev); ret = (int)prev; } free_comm(xmulti); } else { ret = (int)(head.bodysiz); } } if (ret >= 0) x->const_flags[0] = x->const_flags[0] | COMM_FLAGS_USED; destroy_header(&head); return ret; }; /*! @brief Receive a message from an input comm. An error will be returned if the buffer is not large enough. @param[in] x comm_t* structure that message should be sent to. @param[out] data character pointer to allocated buffer where the message should be saved. @param[in] len const size_t length of the allocated message buffer in bytes. @returns int -1 if message could not be received and -2 if EOF is received. Length of the received message otherwise. */ static int comm_recv(comm_t *x, char *data, const size_t len) { int ret = comm_recv_single(x, &data, len, 0); if (ret > 0) { if (is_eof(data)) { ygglog_debug("comm_recv(%s): EOF received.", x->name); x->const_flags[0] = x->const_flags[0] | COMM_EOF_RECV; ret = -2; } else { ret = comm_recv_multipart(x, &data, len, ret, 0); } } else { ygglog_error("comm_recv(%s): Failed to receive header or message.", x->name); } return ret; }; /*! @brief Receive a message from an input comm, reallocating as necessary. @param[in] x comm_t* structure that message should be sent to. @param[out] data character pointer to pointer to allocated buffer where the message should be saved. @param[in] len const size_t length of the allocated message buffer in bytes. @returns int -1 if message could not be received and -2 if EOF is received. Length of the received message otherwise. */ static int comm_recv_realloc(comm_t *x, char **data, const size_t len) { int ret = comm_recv_single(x, data, len, 1); if (ret > 0) { if (is_eof(*data)) { ygglog_debug("comm_recv_realloc(%s): EOF received.", x->name); x->const_flags[0] = x->const_flags[0] | COMM_EOF_RECV; ret = -2; } else { ret = comm_recv_multipart(x, data, len, ret, 1); } } else { ygglog_error("comm_recv_realloc(%s): Failed to receive header or message.", x->name); } return ret; }; /*! @brief alias for comm_send. */ static int comm_send_nolimit(const comm_t *x, const char *data, const size_t len) { return comm_send(x, data, len); }; /*! @brief Send EOF message to the comm. @param[in] x comm_t* structure that message should be sent to. @returns int 0 if send successfull, -1 otherwise. */ static int comm_send_nolimit_eof(const comm_t *x) { int ret = -1; if ((x == NULL) || (!(x->flags & COMM_FLAG_VALID))) { ygglog_error("comm_send_nolimit_eof: Invalid comm"); return ret; } if (x->const_flags == NULL) { ygglog_error("comm_send_nolimit_eof(%s): const_flags not initialized.", x->name); return ret; } if (!(x->const_flags[0] & COMM_EOF_SENT)) { char buf[2048] = YGG_MSG_EOF; ret = comm_send_nolimit(x, buf, strlen(buf)); set_sent_eof(x); } else { ygglog_debug("comm_send_nolimit_eof(%s): EOF already sent", x->name); } return ret; }; /*! @brief Receive a large message from an input comm. Receive a message larger than YGG_MSG_MAX bytes from an input comm by receiving it in parts. This expects the first message to be the size of the total message. @param[in] x comm_t structure that message should be sent to. @param[out] data character pointer to pointer for allocated buffer where the message should be stored. A pointer to a pointer is used so that the buffer may be reallocated as necessary for the incoming message. @param[in] len size_t length of the initial allocated message buffer in bytes. @returns int -1 if message could not be received and -2 if EOF is received. Length of the received message otherwise. */ static int comm_recv_nolimit(comm_t *x, char **data, const size_t len) { return comm_recv_realloc(x, data, len); }; /*! @brief Send arguments as a small formatted message to an output comm. Use the format string to create a message from the input arguments that is then sent to the specified output comm. If the message is larger than YGG_MSG_MAX or cannot be encoded, it will not be sent. @param[in] x comm_t* structure for comm that message should be sent to. @param[in] nargs size_t Number of arguments in the variable argument list. @param[in] ap va_list arguments to be formatted into a message using sprintf. @returns int Number of arguments formatted if send succesfull, -1 if send unsuccessful. */ static int vcommSend(const comm_t *x, size_t nargs, va_list_t ap) { ygglog_debug("vcommSend: Formatting %lu arguments.", nargs); int ret = -1; if ((x == NULL) || (!(x->flags & COMM_FLAG_VALID))) { ygglog_error("vcommSend: Invalid comm"); return ret; } size_t buf_siz = YGG_MSG_BUF; // char *buf = NULL; char *buf = (char*)malloc(buf_siz); if (buf == NULL) { ygglog_error("vcommSend(%s): Failed to alloc buffer", x->name); return -1; } dtype_t *datatype = x->datatype; if (x->type == CLIENT_COMM) { comm_t *handle = (comm_t*)(x->handle); datatype = handle->datatype; } // Update datatype if not yet set and object being sent includes type if (update_dtype_from_generic_ap(datatype, nargs, ap) < 0) { return -1; } size_t nargs_orig = nargs; ret = serialize_dtype(datatype, &buf, &buf_siz, 1, &nargs, ap); if (ret < 0) { ygglog_error("vcommSend(%s): serialization error", x->name); free(buf); return -1; } ret = comm_send(x, buf, ret); ygglog_debug("vcommSend(%s): comm_send returns %d, nargs (remaining) = %d", x->name, ret, nargs); free(buf); if (ret < 0) { return ret; } else { return (int)(nargs_orig - nargs); } }; /*! @brief Send arguments as a formatted message to an output comm. Use the format string to create a message from the input arguments that is then sent to the specified output comm. @param[in] x comm_t structure for comm that message should be sent to. @param[in] nargs size_t Number of variable arguments provided. @param[in] ... Arguments to be formatted into a message using sprintf. @returns int Number of arguments formatted if send succesfull, -1 if send unsuccessful. */ static int ncommSend(const comm_t *x, size_t nargs, ...) { va_list_t ap = init_va_list(); va_start(ap.va, nargs); ygglog_debug("ncommSend: nargs = %d", nargs); int ret = vcommSend(x, nargs, ap); va_end(ap.va); return ret; }; #define commSend(x, ...) ncommSend(x, COUNT_VARARGS(__VA_ARGS__), __VA_ARGS__) /*! @brief Assign arguments by receiving and parsing a message from an input comm. Receive a message smaller than YGG_MSG_MAX bytes from an input comm and parse it using the associated format string. @param[in] x comm_t structure for comm that message should be sent to. @param[in] allow_realloc int If 1, variables being filled are assumed to be pointers to pointers for heap memory. If 0, variables are assumed to be pointers to stack memory. If allow_realloc is set to 1, but stack variables are passed, a segfault can occur. @param[in] nargs size_t Number of arguments in the variable argument list. @param[out] ap va_list arguments that should be assigned by parsing the received message using sscanf. As these are being assigned, they should be pointers to memory that has already been allocated. @returns int -1 if message could not be received or could not be parsed. Length of the received message if message was received and parsed. -2 is returned if EOF is received. */ static int vcommRecv(comm_t *x, const int allow_realloc, size_t nargs, va_list_t ap) { int ret = -1; ygglog_debug("vcommRecv: Parsing %lu arguments.", nargs); if ((x == NULL) || (!(x->flags & COMM_FLAG_VALID))) { ygglog_error("vcommRecv: Invalid comm"); return ret; } // Receive message size_t buf_siz = YGG_MSG_BUF; /* char *buf = NULL; */ char *buf = (char*)malloc(buf_siz); if (buf == NULL) { ygglog_error("vcommRecv(%s): Failed to alloc buffer", x->name); return -1; } ret = comm_recv_nolimit(x, &buf, buf_siz); if (ret < 0) { // ygglog_error("vcommRecv(%s): Error receiving.", x->name); free(buf); return ret; } ygglog_debug("vcommRecv(%s): comm_recv returns %d: %.10s...", x->name, ret, buf); // Deserialize message dtype_t *datatype = x->datatype; if (x->type == SERVER_COMM) { comm_t *handle = (comm_t*)(x->handle); datatype = handle->datatype; } ret = deserialize_dtype(datatype, buf, ret, allow_realloc, &nargs, ap); if (ret < 0) { ygglog_error("vcommRecv(%s): error deserializing message (ret=%d)", x->name, ret); free(buf); return -1; } ygglog_debug("vcommRecv(%s): deserialize_format returns %d", x->name, ret); free(buf); return ret; }; /*! @brief Assign arguments by receiving and parsing a message from an input comm. Receive a message from an input comm and parse it using the associated type. @param[in] x comm_t* structure for comm that message should be sent to. @param[in] allow_realloc int If 1, variables being filled are assumed to be pointers to pointers for heap memory. If 0, variables are assumed to be pointers to stack memory. If allow_realloc is set to 1, but stack variables are passed, a segfault can occur. @param[in] nargs size_t Number of variable arguments provided. @param[out] ... arguments that should be assigned by parsing the received message using sscanf. As these are being assigned, they should be pointers to memory that has already been allocated. @returns int -1 if message could not be received or could not be parsed. Length of the received message if message was received and parsed. -2 is returned if EOF is received. */ static int ncommRecv(comm_t *x, const int allow_realloc, size_t nargs, ...) { va_list_t ap = init_va_list(); va_start(ap.va, nargs); ygglog_debug("ncommRecv: nargs = %d", nargs); int ret = vcommRecv(x, allow_realloc, nargs, ap); va_end(ap.va); return ret; }; #define commRecvStack(x, ...) ncommRecv(x, 0, COUNT_VARARGS(__VA_ARGS__), __VA_ARGS__) #define commRecvHeap(x, ...) ncommRecv(x, 1, COUNT_VARARGS(__VA_ARGS__), __VA_ARGS__) #define commRecv commRecvStack #define commRecvRealloc commRecvHeap #define vcommSend_nolimit vcommSend #define vcommRecv_nolimit vcommRecv #ifdef __cplusplus /* If this is a C++ compiler, end C linkage */ } #endif #endif /*YGGCOMMUNICATION_H_*/
data.h
/*! * Copyright (c) 2015 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 <rabit/rabit.h> #include <cstring> #include <memory> #include <numeric> #include <algorithm> #include <string> #include <vector> #include "./base.h" #include "../../src/common/span.h" #include "../../src/common/group_data.h" #include "../../src/common/host_device_vector.h" namespace xgboost { // forward declare learner. class LearnerImpl; /*! \brief data type accepted by xgboost interface */ enum DataType { kFloat32 = 1, kDouble = 2, kUInt32 = 3, kUInt64 = 4 }; /*! * \brief Meta information about dataset, always sit in memory. */ class MetaInfo { public: /*! \brief number of rows in the data */ uint64_t num_row_{0}; /*! \brief number of columns in the data */ uint64_t num_col_{0}; /*! \brief number of nonzero entries in the data */ uint64_t num_nonzero_{0}; /*! \brief label of each instance */ HostDeviceVector<bst_float> labels_; /*! * \brief specified root index of each instance, * can be used for multi task setting */ std::vector<bst_uint> root_index_; /*! * \brief the index of begin and end of a group * needed when the learning task is ranking. */ std::vector<bst_uint> group_ptr_; /*! \brief weights of each instance, optional */ HostDeviceVector<bst_float> weights_; /*! \brief session-id of each instance, optional */ std::vector<uint64_t> qids_; /*! * \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_; /*! \brief version flag, used to check version of this info */ static const int kVersion = 2; /*! \brief version that introduced qid field */ static const int kVersionQidAdded = 2; /*! \brief default constructor */ MetaInfo() = default; /*! * \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 the root index of i-th instance. * \param i Instance index. * \return The pre-defined root index of i-th instance. */ inline unsigned GetRoot(size_t i) const { return root_index_.size() != 0 ? root_index_[i] : 0U; } /*! \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); 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_uint 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. */ Entry(bst_uint 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 In-memory storage unit of sparse batch, stored in CSR format. */ class SparsePage { public: // Offset for each row. HostDeviceVector<size_t> offset; /*! \brief the data of the segments */ HostDeviceVector<Entry> data; size_t base_rowid; /*! \brief an instance of sparse vector in the batch */ using Inst = common::Span<Entry const>; /*! \brief get i-th row from the batch */ inline Inst operator[](size_t i) const { const auto& data_vec = data.HostVector(); const auto& offset_vec = offset.HostVector(); size_t size; // in distributed mode, some partitions may not get any instance for a feature. Therefore // we should set the size as zero if (rabit::IsDistributed() && i + 1 >= offset_vec.size()) { size = 0; } else { size = offset_vec[i + 1] - offset_vec[i]; } return {data_vec.data() + offset_vec[i], static_cast<Inst::index_type>(size)}; } /*! \brief constructor */ SparsePage() { this->Clear(); } /*! \return number of instance in the page */ inline size_t Size() const { return 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(); } SparsePage GetTranspose(int num_columns) const { SparsePage transpose; common::ParallelGroupBuilder<Entry> builder(&transpose.offset.HostVector(), &transpose.data.HostVector()); const int nthread = omp_get_max_threads(); builder.InitBudget(num_columns, nthread); long batch_size = static_cast<long>(this->Size()); // NOLINT(*) #pragma omp parallel for schedule(static) for (long i = 0; i < batch_size; ++i) { // NOLINT(*) int tid = omp_get_thread_num(); auto inst = (*this)[i]; for (bst_uint j = 0; j < inst.size(); ++j) { builder.AddBudget(inst[j].index, tid); } } builder.InitStorage(); #pragma omp parallel for schedule(static) for (long i = 0; i < batch_size; ++i) { // NOLINT(*) int tid = omp_get_thread_num(); auto inst = (*this)[i]; for (bst_uint j = 0; j < inst.size(); ++j) { builder.Push( inst[j].index, Entry(static_cast<bst_uint>(this->base_rowid + i), inst[j].fvalue), tid); } } return transpose; } void SortRows() { auto ncol = static_cast<bst_omp_uint>(this->Size()); #pragma omp parallel for schedule(dynamic, 1) for (bst_omp_uint i = 0; i < ncol; ++i) { 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); } } } /*! * \brief Push row block into the page. * \param batch the row batch. */ void Push(const dmlc::RowBlock<uint32_t>& batch); /*! * \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); /*! * \brief Push one instance into page * \param inst an instance row */ inline void Push(const Inst &inst) { auto& data_vec = data.HostVector(); auto& offset_vec = offset.HostVector(); offset_vec.push_back(offset_vec.back() + inst.size()); size_t begin = data_vec.size(); data_vec.resize(begin + inst.size()); if (inst.size() != 0) { std::memcpy(dmlc::BeginPtr(data_vec) + begin, inst.data(), sizeof(Entry) * inst.size()); } } size_t Size() { return offset.Size() - 1; } }; class BatchIteratorImpl { public: virtual ~BatchIteratorImpl() {} virtual BatchIteratorImpl* Clone() = 0; virtual const SparsePage& operator*() const = 0; virtual void operator++() = 0; virtual bool AtEnd() const = 0; }; class BatchIterator { public: using iterator_category = std::forward_iterator_tag; explicit BatchIterator(BatchIteratorImpl* impl) { impl_.reset(impl); } BatchIterator(const BatchIterator& other) { if (other.impl_) { impl_.reset(other.impl_->Clone()); } else { impl_.reset(); } } void operator++() { CHECK(impl_ != nullptr); ++(*impl_); } const SparsePage& operator*() const { CHECK(impl_ != nullptr); return *(*impl_); } bool operator!=(const BatchIterator& rhs) const { CHECK(impl_ != nullptr); return !impl_->AtEnd(); } bool AtEnd() const { CHECK(impl_ != nullptr); return impl_->AtEnd(); } private: std::unique_ptr<BatchIteratorImpl> impl_; }; class BatchSet { public: explicit BatchSet(BatchIterator begin_iter) : begin_iter_(begin_iter) {} BatchIterator begin() { return begin_iter_; } BatchIterator end() { return BatchIterator(nullptr); } private: BatchIterator begin_iter_; }; /*! * \brief This is data structure that user can pass to DMatrix::Create * to create a DMatrix for training, user can create this data structure * for customized Data Loading on single machine. * * On distributed setting, usually an customized dmlc::Parser is needed instead. */ class DataSource : public dmlc::DataIter<SparsePage> { public: /*! * \brief Meta information about the dataset * The subclass need to be able to load this correctly from data. */ MetaInfo info; }; /*! * \brief A vector-like structure to represent set of rows. * But saves the memory when all rows are in the set (common case in xgb) */ class RowSet { public: /*! \return i-th row index */ inline bst_uint operator[](size_t i) const; /*! \return the size of the set. */ inline size_t Size() const; /*! \brief push the index back to the set */ inline void PushBack(bst_uint i); /*! \brief clear the set */ inline void Clear(); /*! * \brief save rowset to file. * \param fo The file to be saved. */ inline void Save(dmlc::Stream* fo) const; /*! * \brief Load rowset from file. * \param fi The file to be loaded. * \return if read is successful. */ inline bool Load(dmlc::Stream* fi); /*! \brief constructor */ RowSet() = default; private: /*! \brief The internal data structure of size */ uint64_t size_{0}; /*! \brief The internal data structure of row set if not all*/ std::vector<bst_uint> rows_; }; /*! * \brief Internal data structured used by XGBoost during training. * There are two ways to create a customized DMatrix that reads in user defined-format. * * - Provide a dmlc::Parser and pass into the DMatrix::Create * - Alternatively, if data can be represented by an URL, define a new dmlc::Parser and register by DMLC_REGISTER_DATA_PARSER; * - This works best for user defined data input source, such as data-base, filesystem. * - Provide a DataSource, that can be passed to DMatrix::Create * This can be used to re-use inmemory data structure into DMatrix. */ class DMatrix { public: /*! \brief default constructor */ DMatrix() = default; /*! \brief meta information of the dataset */ virtual MetaInfo& Info() = 0; /*! \brief meta information of the dataset */ virtual const MetaInfo& Info() const = 0; /** * \brief Gets row batches. Use range based for loop over BatchSet to access individual batches. */ virtual BatchSet GetRowBatches() = 0; virtual BatchSet GetSortedColumnBatches() = 0; virtual BatchSet GetColumnBatches() = 0; // 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 get column density */ virtual float GetColDensity(size_t cidx) = 0; /*! \brief virtual destructor */ virtual ~DMatrix() = default; /*! * \brief Save DMatrix to local file. * The saved file only works for non-sharded dataset(single machine training). * This API is deprecated and dis-encouraged to use. * \param fname The file name to be saved. * \return The created DMatrix. */ virtual void SaveToLocalFile(const std::string& fname); /*! * \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", const size_t page_size = kPageSize); /*! * \brief create a new DMatrix, by wrapping a row_iterator, and meta info. * \param source The source iterator of the data, the create function takes ownership of the source. * \param cache_prefix The path to prefix of temporary cache file of the DMatrix when used in external memory mode. * This can be nullptr for common cases, and in-memory mode will be used. * \return a Created DMatrix. */ static DMatrix* Create(std::unique_ptr<DataSource>&& source, const std::string& cache_prefix = ""); /*! * \brief Create a DMatrix by loading data from parser. * Parser can later be deleted after the DMatrix i created. * \param parser The input data parser * \param cache_prefix The path to prefix of temporary cache file of the DMatrix when used in external memory mode. * This can be nullptr for common cases, and in-memory mode will be used. * \param page_size Page size for external memory. * \sa dmlc::Parser * \note dmlc-core provides efficient distributed data parser for libsvm format. * User can create and register customized parser to load their own format using DMLC_REGISTER_DATA_PARSER. * See "dmlc-core/include/dmlc/data.h" for detail. * \return A created DMatrix. */ static DMatrix* Create(dmlc::Parser<uint32_t>* parser, const std::string& cache_prefix = "", const size_t page_size = kPageSize); /*! \brief page size 32 MB */ static const size_t kPageSize = 32UL << 20UL; }; // implementation of inline functions inline bst_uint RowSet::operator[](size_t i) const { return rows_.size() == 0 ? static_cast<bst_uint>(i) : rows_[i]; } inline size_t RowSet::Size() const { return size_; } inline void RowSet::Clear() { rows_.clear(); size_ = 0; } inline void RowSet::PushBack(bst_uint i) { if (rows_.size() == 0) { if (i == size_) { ++size_; return; } else { rows_.resize(size_); for (size_t i = 0; i < size_; ++i) { rows_[i] = static_cast<bst_uint>(i); } } } rows_.push_back(i); ++size_; } inline void RowSet::Save(dmlc::Stream* fo) const { fo->Write(rows_); fo->Write(&size_, sizeof(size_)); } inline bool RowSet::Load(dmlc::Stream* fi) { if (!fi->Read(&rows_)) return false; if (rows_.size() != 0) return true; return fi->Read(&size_, sizeof(size_)) == sizeof(size_); } } // namespace xgboost namespace dmlc { DMLC_DECLARE_TRAITS(is_pod, xgboost::Entry, true); DMLC_DECLARE_TRAITS(has_saveload, xgboost::RowSet, true); } #endif // XGBOOST_DATA_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] = 4; tile_size[1] = 4; tile_size[2] = 32; tile_size[3] = 2048; 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,2);t1++) { lbp=max(ceild(t1,2),ceild(4*t1-Nt+3,4)); ubp=min(floord(Nt+Nz-4,4),floord(2*t1+Nz-1,4)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(0,ceild(t1-15,16)),ceild(4*t2-Nz-28,32));t3<=min(min(min(floord(4*t2+Ny,32),floord(Nt+Ny-4,32)),floord(2*t1+Ny+1,32)),floord(4*t1-4*t2+Nz+Ny-1,32));t3++) { for (t4=max(max(max(0,ceild(t1-1023,1024)),ceild(4*t2-Nz-2044,2048)),ceild(32*t3-Ny-2044,2048));t4<=min(min(min(min(floord(4*t2+Nx,2048),floord(Nt+Nx-4,2048)),floord(2*t1+Nx+1,2048)),floord(32*t3+Nx+28,2048)),floord(4*t1-4*t2+Nz+Nx-1,2048));t4++) { for (t5=max(max(max(max(max(0,2*t1),4*t1-4*t2+1),4*t2-Nz+2),32*t3-Ny+2),2048*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,2*t1+3),4*t2+2),32*t3+30),2048*t4+2046),4*t1-4*t2+Nz+1);t5++) { for (t6=max(max(4*t2,t5+1),-4*t1+4*t2+2*t5-3);t6<=min(min(4*t2+3,-4*t1+4*t2+2*t5),t5+Nz-2);t6++) { for (t7=max(32*t3,t5+1);t7<=min(32*t3+31,t5+Ny-2);t7++) { lbv=max(2048*t4,t5+1); ubv=min(2048*t4+2047,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; }
Stmt.h
//===--- Stmt.h - Classes for representing statements -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the Stmt interface and subclasses. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_STMT_H #define LLVM_CLANG_AST_STMT_H #include "clang/AST/DeclGroup.h" #include "clang/AST/StmtIterator.h" #include "clang/Basic/CapturedStmt.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/LLVM.h" #include "clang/Basic/SourceLocation.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/PointerIntPair.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/ErrorHandling.h" #include <string> namespace llvm { class FoldingSetNodeID; } namespace clang { class ASTContext; class Attr; class CapturedDecl; class Decl; class Expr; class IdentifierInfo; class LabelDecl; class ParmVarDecl; class PrinterHelper; struct PrintingPolicy; class QualType; class RecordDecl; class SourceManager; class StringLiteral; class SwitchStmt; class Token; class VarDecl; //===--------------------------------------------------------------------===// // ExprIterator - Iterators for iterating over Stmt* arrays that contain // only Expr*. This is needed because AST nodes use Stmt* arrays to store // references to children (to be compatible with StmtIterator). //===--------------------------------------------------------------------===// class Stmt; class Expr; class ExprIterator { Stmt** I; public: ExprIterator(Stmt** i) : I(i) {} ExprIterator() : I(0) {} ExprIterator& operator++() { ++I; return *this; } ExprIterator operator-(size_t i) { return I-i; } ExprIterator operator+(size_t i) { return I+i; } Expr* operator[](size_t idx); // FIXME: Verify that this will correctly return a signed distance. signed operator-(const ExprIterator& R) const { return I - R.I; } Expr* operator*() const; Expr* operator->() const; bool operator==(const ExprIterator& R) const { return I == R.I; } bool operator!=(const ExprIterator& R) const { return I != R.I; } bool operator>(const ExprIterator& R) const { return I > R.I; } bool operator>=(const ExprIterator& R) const { return I >= R.I; } }; class ConstExprIterator { const Stmt * const *I; public: ConstExprIterator(const Stmt * const *i) : I(i) {} ConstExprIterator() : I(0) {} ConstExprIterator& operator++() { ++I; return *this; } ConstExprIterator operator+(size_t i) const { return I+i; } ConstExprIterator operator-(size_t i) const { return I-i; } const Expr * operator[](size_t idx) const; signed operator-(const ConstExprIterator& R) const { return I - R.I; } const Expr * operator*() const; const Expr * operator->() const; bool operator==(const ConstExprIterator& R) const { return I == R.I; } bool operator!=(const ConstExprIterator& R) const { return I != R.I; } bool operator>(const ConstExprIterator& R) const { return I > R.I; } bool operator>=(const ConstExprIterator& R) const { return I >= R.I; } }; //===----------------------------------------------------------------------===// // AST classes for statements. //===----------------------------------------------------------------------===// /// Stmt - This represents one statement. /// class Stmt { public: enum StmtClass { NoStmtClass = 0, #define STMT(CLASS, PARENT) CLASS##Class, #define STMT_RANGE(BASE, FIRST, LAST) \ first##BASE##Constant=FIRST##Class, last##BASE##Constant=LAST##Class, #define LAST_STMT_RANGE(BASE, FIRST, LAST) \ first##BASE##Constant=FIRST##Class, last##BASE##Constant=LAST##Class #define ABSTRACT_STMT(STMT) #include "clang/AST/StmtNodes.inc" }; // Make vanilla 'new' and 'delete' illegal for Stmts. protected: void* operator new(size_t bytes) throw() { llvm_unreachable("Stmts cannot be allocated with regular 'new'."); } void operator delete(void* data) throw() { llvm_unreachable("Stmts cannot be released with regular 'delete'."); } class StmtBitfields { friend class Stmt; /// \brief The statement class. unsigned sClass : 8; }; enum { NumStmtBits = 8 }; class CompoundStmtBitfields { friend class CompoundStmt; unsigned : NumStmtBits; unsigned NumStmts : 32 - NumStmtBits; }; class ExprBitfields { friend class Expr; friend class DeclRefExpr; // computeDependence friend class InitListExpr; // ctor friend class DesignatedInitExpr; // ctor friend class BlockDeclRefExpr; // ctor friend class ASTStmtReader; // deserialization friend class CXXNewExpr; // ctor friend class DependentScopeDeclRefExpr; // ctor friend class CXXConstructExpr; // ctor friend class CallExpr; // ctor friend class OffsetOfExpr; // ctor friend class ObjCMessageExpr; // ctor friend class ObjCArrayLiteral; // ctor friend class ObjCDictionaryLiteral; // ctor friend class ShuffleVectorExpr; // ctor friend class ParenListExpr; // ctor friend class CXXUnresolvedConstructExpr; // ctor friend class CXXDependentScopeMemberExpr; // ctor friend class OverloadExpr; // ctor friend class PseudoObjectExpr; // ctor friend class AtomicExpr; // ctor unsigned : NumStmtBits; unsigned ValueKind : 2; unsigned ObjectKind : 2; unsigned TypeDependent : 1; unsigned ValueDependent : 1; unsigned InstantiationDependent : 1; unsigned ContainsUnexpandedParameterPack : 1; }; enum { NumExprBits = 16 }; class CharacterLiteralBitfields { friend class CharacterLiteral; unsigned : NumExprBits; unsigned Kind : 2; }; enum APFloatSemantics { IEEEhalf, IEEEsingle, IEEEdouble, x87DoubleExtended, IEEEquad, PPCDoubleDouble }; class FloatingLiteralBitfields { friend class FloatingLiteral; unsigned : NumExprBits; unsigned Semantics : 3; // Provides semantics for APFloat construction unsigned IsExact : 1; }; class UnaryExprOrTypeTraitExprBitfields { friend class UnaryExprOrTypeTraitExpr; unsigned : NumExprBits; unsigned Kind : 2; unsigned IsType : 1; // true if operand is a type, false if an expression. }; class DeclRefExprBitfields { friend class DeclRefExpr; friend class ASTStmtReader; // deserialization unsigned : NumExprBits; unsigned HasQualifier : 1; unsigned HasTemplateKWAndArgsInfo : 1; unsigned HasFoundDecl : 1; unsigned HadMultipleCandidates : 1; unsigned RefersToEnclosingLocal : 1; }; class CastExprBitfields { friend class CastExpr; unsigned : NumExprBits; unsigned Kind : 6; unsigned BasePathSize : 32 - 6 - NumExprBits; }; class CallExprBitfields { friend class CallExpr; unsigned : NumExprBits; unsigned NumPreArgs : 1; }; class ExprWithCleanupsBitfields { friend class ExprWithCleanups; friend class ASTStmtReader; // deserialization unsigned : NumExprBits; unsigned NumObjects : 32 - NumExprBits; }; class PseudoObjectExprBitfields { friend class PseudoObjectExpr; friend class ASTStmtReader; // deserialization unsigned : NumExprBits; // These don't need to be particularly wide, because they're // strictly limited by the forms of expressions we permit. unsigned NumSubExprs : 8; unsigned ResultIndex : 32 - 8 - NumExprBits; }; class ObjCIndirectCopyRestoreExprBitfields { friend class ObjCIndirectCopyRestoreExpr; unsigned : NumExprBits; unsigned ShouldCopy : 1; }; class InitListExprBitfields { friend class InitListExpr; unsigned : NumExprBits; /// Whether this initializer list originally had a GNU array-range /// designator in it. This is a temporary marker used by CodeGen. unsigned HadArrayRangeDesignator : 1; /// Whether this initializer list initializes a std::initializer_list /// object. unsigned InitializesStdInitializerList : 1; }; class TypeTraitExprBitfields { friend class TypeTraitExpr; friend class ASTStmtReader; friend class ASTStmtWriter; unsigned : NumExprBits; /// \brief The kind of type trait, which is a value of a TypeTrait enumerator. unsigned Kind : 8; /// \brief If this expression is not value-dependent, this indicates whether /// the trait evaluated true or false. unsigned Value : 1; /// \brief The number of arguments to this type trait. unsigned NumArgs : 32 - 8 - 1 - NumExprBits; }; union { // FIXME: this is wasteful on 64-bit platforms. void *Aligner; StmtBitfields StmtBits; CompoundStmtBitfields CompoundStmtBits; ExprBitfields ExprBits; CharacterLiteralBitfields CharacterLiteralBits; FloatingLiteralBitfields FloatingLiteralBits; UnaryExprOrTypeTraitExprBitfields UnaryExprOrTypeTraitExprBits; DeclRefExprBitfields DeclRefExprBits; CastExprBitfields CastExprBits; CallExprBitfields CallExprBits; ExprWithCleanupsBitfields ExprWithCleanupsBits; PseudoObjectExprBitfields PseudoObjectExprBits; ObjCIndirectCopyRestoreExprBitfields ObjCIndirectCopyRestoreExprBits; InitListExprBitfields InitListExprBits; TypeTraitExprBitfields TypeTraitExprBits; }; friend class ASTStmtReader; friend class ASTStmtWriter; public: // Only allow allocation of Stmts using the allocator in ASTContext // or by doing a placement new. void* operator new(size_t bytes, ASTContext& C, unsigned alignment = 8) throw(); void* operator new(size_t bytes, ASTContext* C, unsigned alignment = 8) throw(); void* operator new(size_t bytes, void* mem) throw() { return mem; } void operator delete(void*, ASTContext&, unsigned) throw() { } void operator delete(void*, ASTContext*, unsigned) throw() { } void operator delete(void*, std::size_t) throw() { } void operator delete(void*, void*) throw() { } public: /// \brief A placeholder type used to construct an empty shell of a /// type, that will be filled in later (e.g., by some /// de-serialization). struct EmptyShell { }; private: /// \brief Whether statistic collection is enabled. static bool StatisticsEnabled; protected: /// \brief Construct an empty statement. explicit Stmt(StmtClass SC, EmptyShell) { StmtBits.sClass = SC; if (StatisticsEnabled) Stmt::addStmtClass(SC); } public: Stmt(StmtClass SC) { StmtBits.sClass = SC; if (StatisticsEnabled) Stmt::addStmtClass(SC); } StmtClass getStmtClass() const { return static_cast<StmtClass>(StmtBits.sClass); } const char *getStmtClassName() const; /// SourceLocation tokens are not useful in isolation - they are low level /// value objects created/interpreted by SourceManager. We assume AST /// clients will have a pointer to the respective SourceManager. SourceRange getSourceRange() const LLVM_READONLY; SourceLocation getLocStart() const LLVM_READONLY; SourceLocation getLocEnd() const LLVM_READONLY; // global temp stats (until we have a per-module visitor) static void addStmtClass(const StmtClass s); static void EnableStatistics(); static void PrintStats(); /// \brief Dumps the specified AST fragment and all subtrees to /// \c llvm::errs(). LLVM_ATTRIBUTE_USED void dump() const; LLVM_ATTRIBUTE_USED void dump(SourceManager &SM) const; void dump(raw_ostream &OS, SourceManager &SM) const; /// dumpColor - same as dump(), but forces color highlighting. LLVM_ATTRIBUTE_USED void dumpColor() const; /// dumpPretty/printPretty - These two methods do a "pretty print" of the AST /// back to its original source language syntax. void dumpPretty(ASTContext &Context) const; void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation = 0) const; /// viewAST - Visualize an AST rooted at this Stmt* using GraphViz. Only /// works on systems with GraphViz (Mac OS X) or dot+gv installed. void viewAST() const; /// Skip past any implicit AST nodes which might surround this /// statement, such as ExprWithCleanups or ImplicitCastExpr nodes. Stmt *IgnoreImplicit(); const Stmt *stripLabelLikeStatements() const; Stmt *stripLabelLikeStatements() { return const_cast<Stmt*>( const_cast<const Stmt*>(this)->stripLabelLikeStatements()); } /// hasImplicitControlFlow - Some statements (e.g. short circuited operations) /// contain implicit control-flow in the order their subexpressions /// are evaluated. This predicate returns true if this statement has /// such implicit control-flow. Such statements are also specially handled /// within CFGs. bool hasImplicitControlFlow() const; /// Child Iterators: All subclasses must implement 'children' /// to permit easy iteration over the substatements/subexpessions of an /// AST node. This permits easy iteration over all nodes in the AST. typedef StmtIterator child_iterator; typedef ConstStmtIterator const_child_iterator; typedef StmtRange child_range; typedef ConstStmtRange const_child_range; child_range children(); const_child_range children() const { return const_cast<Stmt*>(this)->children(); } child_iterator child_begin() { return children().first; } child_iterator child_end() { return children().second; } const_child_iterator child_begin() const { return children().first; } const_child_iterator child_end() const { return children().second; } /// \brief Produce a unique representation of the given statement. /// /// \param ID once the profiling operation is complete, will contain /// the unique representation of the given statement. /// /// \param Context the AST context in which the statement resides /// /// \param Canonical whether the profile should be based on the canonical /// representation of this statement (e.g., where non-type template /// parameters are identified by index/level rather than their /// declaration pointers) or the exact representation of the statement as /// written in the source. void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical) const; }; /// DeclStmt - Adaptor class for mixing declarations with statements and /// expressions. For example, CompoundStmt mixes statements, expressions /// and declarations (variables, types). Another example is ForStmt, where /// the first statement can be an expression or a declaration. /// class DeclStmt : public Stmt { DeclGroupRef DG; SourceLocation StartLoc, EndLoc; public: DeclStmt(DeclGroupRef dg, SourceLocation startLoc, SourceLocation endLoc) : Stmt(DeclStmtClass), DG(dg), StartLoc(startLoc), EndLoc(endLoc) {} /// \brief Build an empty declaration statement. explicit DeclStmt(EmptyShell Empty) : Stmt(DeclStmtClass, Empty) { } /// isSingleDecl - This method returns true if this DeclStmt refers /// to a single Decl. bool isSingleDecl() const { return DG.isSingleDecl(); } const Decl *getSingleDecl() const { return DG.getSingleDecl(); } Decl *getSingleDecl() { return DG.getSingleDecl(); } const DeclGroupRef getDeclGroup() const { return DG; } DeclGroupRef getDeclGroup() { return DG; } void setDeclGroup(DeclGroupRef DGR) { DG = DGR; } SourceLocation getStartLoc() const { return StartLoc; } void setStartLoc(SourceLocation L) { StartLoc = L; } SourceLocation getEndLoc() const { return EndLoc; } void setEndLoc(SourceLocation L) { EndLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return StartLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return EndLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == DeclStmtClass; } // Iterators over subexpressions. child_range children() { return child_range(child_iterator(DG.begin(), DG.end()), child_iterator(DG.end(), DG.end())); } typedef DeclGroupRef::iterator decl_iterator; typedef DeclGroupRef::const_iterator const_decl_iterator; decl_iterator decl_begin() { return DG.begin(); } decl_iterator decl_end() { return DG.end(); } const_decl_iterator decl_begin() const { return DG.begin(); } const_decl_iterator decl_end() const { return DG.end(); } typedef std::reverse_iterator<decl_iterator> reverse_decl_iterator; reverse_decl_iterator decl_rbegin() { return reverse_decl_iterator(decl_end()); } reverse_decl_iterator decl_rend() { return reverse_decl_iterator(decl_begin()); } }; /// NullStmt - This is the null statement ";": C99 6.8.3p3. /// class NullStmt : public Stmt { SourceLocation SemiLoc; /// \brief True if the null statement was preceded by an empty macro, e.g: /// @code /// #define CALL(x) /// CALL(0); /// @endcode bool HasLeadingEmptyMacro; public: NullStmt(SourceLocation L, bool hasLeadingEmptyMacro = false) : Stmt(NullStmtClass), SemiLoc(L), HasLeadingEmptyMacro(hasLeadingEmptyMacro) {} /// \brief Build an empty null statement. explicit NullStmt(EmptyShell Empty) : Stmt(NullStmtClass, Empty), HasLeadingEmptyMacro(false) { } SourceLocation getSemiLoc() const { return SemiLoc; } void setSemiLoc(SourceLocation L) { SemiLoc = L; } bool hasLeadingEmptyMacro() const { return HasLeadingEmptyMacro; } SourceLocation getLocStart() const LLVM_READONLY { return SemiLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return SemiLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == NullStmtClass; } child_range children() { return child_range(); } friend class ASTStmtReader; friend class ASTStmtWriter; }; /// CompoundStmt - This represents a group of statements like { stmt stmt }. /// class CompoundStmt : public Stmt { Stmt** Body; SourceLocation LBracLoc, RBracLoc; public: CompoundStmt(ASTContext &C, ArrayRef<Stmt*> Stmts, SourceLocation LB, SourceLocation RB); // \brief Build an empty compound statment with a location. explicit CompoundStmt(SourceLocation Loc) : Stmt(CompoundStmtClass), Body(0), LBracLoc(Loc), RBracLoc(Loc) { CompoundStmtBits.NumStmts = 0; } // \brief Build an empty compound statement. explicit CompoundStmt(EmptyShell Empty) : Stmt(CompoundStmtClass, Empty), Body(0) { CompoundStmtBits.NumStmts = 0; } void setStmts(ASTContext &C, Stmt **Stmts, unsigned NumStmts); bool body_empty() const { return CompoundStmtBits.NumStmts == 0; } unsigned size() const { return CompoundStmtBits.NumStmts; } typedef Stmt** body_iterator; body_iterator body_begin() { return Body; } body_iterator body_end() { return Body + size(); } Stmt *body_back() { return !body_empty() ? Body[size()-1] : 0; } void setLastStmt(Stmt *S) { assert(!body_empty() && "setLastStmt"); Body[size()-1] = S; } typedef Stmt* const * const_body_iterator; const_body_iterator body_begin() const { return Body; } const_body_iterator body_end() const { return Body + size(); } const Stmt *body_back() const { return !body_empty() ? Body[size()-1] : 0; } typedef std::reverse_iterator<body_iterator> reverse_body_iterator; reverse_body_iterator body_rbegin() { return reverse_body_iterator(body_end()); } reverse_body_iterator body_rend() { return reverse_body_iterator(body_begin()); } typedef std::reverse_iterator<const_body_iterator> const_reverse_body_iterator; const_reverse_body_iterator body_rbegin() const { return const_reverse_body_iterator(body_end()); } const_reverse_body_iterator body_rend() const { return const_reverse_body_iterator(body_begin()); } SourceLocation getLocStart() const LLVM_READONLY { return LBracLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return RBracLoc; } SourceLocation getLBracLoc() const { return LBracLoc; } void setLBracLoc(SourceLocation L) { LBracLoc = L; } SourceLocation getRBracLoc() const { return RBracLoc; } void setRBracLoc(SourceLocation L) { RBracLoc = L; } static bool classof(const Stmt *T) { return T->getStmtClass() == CompoundStmtClass; } // Iterators child_range children() { return child_range(&Body[0], &Body[0]+CompoundStmtBits.NumStmts); } const_child_range children() const { return child_range(&Body[0], &Body[0]+CompoundStmtBits.NumStmts); } }; // SwitchCase is the base class for CaseStmt and DefaultStmt, class SwitchCase : public Stmt { protected: // A pointer to the following CaseStmt or DefaultStmt class, // used by SwitchStmt. SwitchCase *NextSwitchCase; SourceLocation KeywordLoc; SourceLocation ColonLoc; SwitchCase(StmtClass SC, SourceLocation KWLoc, SourceLocation ColonLoc) : Stmt(SC), NextSwitchCase(0), KeywordLoc(KWLoc), ColonLoc(ColonLoc) {} SwitchCase(StmtClass SC, EmptyShell) : Stmt(SC), NextSwitchCase(0) {} public: const SwitchCase *getNextSwitchCase() const { return NextSwitchCase; } SwitchCase *getNextSwitchCase() { return NextSwitchCase; } void setNextSwitchCase(SwitchCase *SC) { NextSwitchCase = SC; } SourceLocation getKeywordLoc() const { return KeywordLoc; } void setKeywordLoc(SourceLocation L) { KeywordLoc = L; } SourceLocation getColonLoc() const { return ColonLoc; } void setColonLoc(SourceLocation L) { ColonLoc = L; } Stmt *getSubStmt(); const Stmt *getSubStmt() const { return const_cast<SwitchCase*>(this)->getSubStmt(); } SourceLocation getLocStart() const LLVM_READONLY { return KeywordLoc; } SourceLocation getLocEnd() const LLVM_READONLY; static bool classof(const Stmt *T) { return T->getStmtClass() == CaseStmtClass || T->getStmtClass() == DefaultStmtClass; } }; class CaseStmt : public SwitchCase { enum { LHS, RHS, SUBSTMT, END_EXPR }; Stmt* SubExprs[END_EXPR]; // The expression for the RHS is Non-null for // GNU "case 1 ... 4" extension SourceLocation EllipsisLoc; public: CaseStmt(Expr *lhs, Expr *rhs, SourceLocation caseLoc, SourceLocation ellipsisLoc, SourceLocation colonLoc) : SwitchCase(CaseStmtClass, caseLoc, colonLoc) { SubExprs[SUBSTMT] = 0; SubExprs[LHS] = reinterpret_cast<Stmt*>(lhs); SubExprs[RHS] = reinterpret_cast<Stmt*>(rhs); EllipsisLoc = ellipsisLoc; } /// \brief Build an empty switch case statement. explicit CaseStmt(EmptyShell Empty) : SwitchCase(CaseStmtClass, Empty) { } SourceLocation getCaseLoc() const { return KeywordLoc; } void setCaseLoc(SourceLocation L) { KeywordLoc = L; } SourceLocation getEllipsisLoc() const { return EllipsisLoc; } void setEllipsisLoc(SourceLocation L) { EllipsisLoc = L; } SourceLocation getColonLoc() const { return ColonLoc; } void setColonLoc(SourceLocation L) { ColonLoc = L; } Expr *getLHS() { return reinterpret_cast<Expr*>(SubExprs[LHS]); } Expr *getRHS() { return reinterpret_cast<Expr*>(SubExprs[RHS]); } Stmt *getSubStmt() { return SubExprs[SUBSTMT]; } const Expr *getLHS() const { return reinterpret_cast<const Expr*>(SubExprs[LHS]); } const Expr *getRHS() const { return reinterpret_cast<const Expr*>(SubExprs[RHS]); } const Stmt *getSubStmt() const { return SubExprs[SUBSTMT]; } void setSubStmt(Stmt *S) { SubExprs[SUBSTMT] = S; } void setLHS(Expr *Val) { SubExprs[LHS] = reinterpret_cast<Stmt*>(Val); } void setRHS(Expr *Val) { SubExprs[RHS] = reinterpret_cast<Stmt*>(Val); } SourceLocation getLocStart() const LLVM_READONLY { return KeywordLoc; } SourceLocation getLocEnd() const LLVM_READONLY { // Handle deeply nested case statements with iteration instead of recursion. const CaseStmt *CS = this; while (const CaseStmt *CS2 = dyn_cast<CaseStmt>(CS->getSubStmt())) CS = CS2; return CS->getSubStmt()->getLocEnd(); } static bool classof(const Stmt *T) { return T->getStmtClass() == CaseStmtClass; } // Iterators child_range children() { return child_range(&SubExprs[0], &SubExprs[END_EXPR]); } }; class DefaultStmt : public SwitchCase { Stmt* SubStmt; public: DefaultStmt(SourceLocation DL, SourceLocation CL, Stmt *substmt) : SwitchCase(DefaultStmtClass, DL, CL), SubStmt(substmt) {} /// \brief Build an empty default statement. explicit DefaultStmt(EmptyShell Empty) : SwitchCase(DefaultStmtClass, Empty) { } Stmt *getSubStmt() { return SubStmt; } const Stmt *getSubStmt() const { return SubStmt; } void setSubStmt(Stmt *S) { SubStmt = S; } SourceLocation getDefaultLoc() const { return KeywordLoc; } void setDefaultLoc(SourceLocation L) { KeywordLoc = L; } SourceLocation getColonLoc() const { return ColonLoc; } void setColonLoc(SourceLocation L) { ColonLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return KeywordLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return SubStmt->getLocEnd();} static bool classof(const Stmt *T) { return T->getStmtClass() == DefaultStmtClass; } // Iterators child_range children() { return child_range(&SubStmt, &SubStmt+1); } }; inline SourceLocation SwitchCase::getLocEnd() const { if (const CaseStmt *CS = dyn_cast<CaseStmt>(this)) return CS->getLocEnd(); return cast<DefaultStmt>(this)->getLocEnd(); } /// LabelStmt - Represents a label, which has a substatement. For example: /// foo: return; /// class LabelStmt : public Stmt { LabelDecl *TheDecl; Stmt *SubStmt; SourceLocation IdentLoc; public: LabelStmt(SourceLocation IL, LabelDecl *D, Stmt *substmt) : Stmt(LabelStmtClass), TheDecl(D), SubStmt(substmt), IdentLoc(IL) { } // \brief Build an empty label statement. explicit LabelStmt(EmptyShell Empty) : Stmt(LabelStmtClass, Empty) { } SourceLocation getIdentLoc() const { return IdentLoc; } LabelDecl *getDecl() const { return TheDecl; } void setDecl(LabelDecl *D) { TheDecl = D; } const char *getName() const; Stmt *getSubStmt() { return SubStmt; } const Stmt *getSubStmt() const { return SubStmt; } void setIdentLoc(SourceLocation L) { IdentLoc = L; } void setSubStmt(Stmt *SS) { SubStmt = SS; } SourceLocation getLocStart() const LLVM_READONLY { return IdentLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return SubStmt->getLocEnd();} child_range children() { return child_range(&SubStmt, &SubStmt+1); } static bool classof(const Stmt *T) { return T->getStmtClass() == LabelStmtClass; } }; /// \brief Represents an attribute applied to a statement. /// /// Represents an attribute applied to a statement. For example: /// [[omp::for(...)]] for (...) { ... } /// class AttributedStmt : public Stmt { Stmt *SubStmt; SourceLocation AttrLoc; unsigned NumAttrs; const Attr *Attrs[1]; friend class ASTStmtReader; AttributedStmt(SourceLocation Loc, ArrayRef<const Attr*> Attrs, Stmt *SubStmt) : Stmt(AttributedStmtClass), SubStmt(SubStmt), AttrLoc(Loc), NumAttrs(Attrs.size()) { memcpy(this->Attrs, Attrs.data(), Attrs.size() * sizeof(Attr*)); } explicit AttributedStmt(EmptyShell Empty, unsigned NumAttrs) : Stmt(AttributedStmtClass, Empty), NumAttrs(NumAttrs) { memset(Attrs, 0, NumAttrs * sizeof(Attr*)); } public: static AttributedStmt *Create(ASTContext &C, SourceLocation Loc, ArrayRef<const Attr*> Attrs, Stmt *SubStmt); // \brief Build an empty attributed statement. static AttributedStmt *CreateEmpty(ASTContext &C, unsigned NumAttrs); SourceLocation getAttrLoc() const { return AttrLoc; } ArrayRef<const Attr*> getAttrs() const { return ArrayRef<const Attr*>(Attrs, NumAttrs); } Stmt *getSubStmt() { return SubStmt; } const Stmt *getSubStmt() const { return SubStmt; } SourceLocation getLocStart() const LLVM_READONLY { return AttrLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return SubStmt->getLocEnd();} child_range children() { return child_range(&SubStmt, &SubStmt + 1); } static bool classof(const Stmt *T) { return T->getStmtClass() == AttributedStmtClass; } }; /// IfStmt - This represents an if/then/else. /// class IfStmt : public Stmt { enum { VAR, COND, THEN, ELSE, END_EXPR }; Stmt* SubExprs[END_EXPR]; SourceLocation IfLoc; SourceLocation ElseLoc; public: IfStmt(ASTContext &C, SourceLocation IL, VarDecl *var, Expr *cond, Stmt *then, SourceLocation EL = SourceLocation(), Stmt *elsev = 0); /// \brief Build an empty if/then/else statement explicit IfStmt(EmptyShell Empty) : Stmt(IfStmtClass, Empty) { } /// \brief Retrieve the variable declared in this "if" statement, if any. /// /// In the following example, "x" is the condition variable. /// \code /// if (int x = foo()) { /// printf("x is %d", x); /// } /// \endcode VarDecl *getConditionVariable() const; void setConditionVariable(ASTContext &C, VarDecl *V); /// If this IfStmt has a condition variable, return the faux DeclStmt /// associated with the creation of that condition variable. const DeclStmt *getConditionVariableDeclStmt() const { return reinterpret_cast<DeclStmt*>(SubExprs[VAR]); } const Expr *getCond() const { return reinterpret_cast<Expr*>(SubExprs[COND]);} void setCond(Expr *E) { SubExprs[COND] = reinterpret_cast<Stmt *>(E); } const Stmt *getThen() const { return SubExprs[THEN]; } void setThen(Stmt *S) { SubExprs[THEN] = S; } const Stmt *getElse() const { return SubExprs[ELSE]; } void setElse(Stmt *S) { SubExprs[ELSE] = S; } Expr *getCond() { return reinterpret_cast<Expr*>(SubExprs[COND]); } Stmt *getThen() { return SubExprs[THEN]; } Stmt *getElse() { return SubExprs[ELSE]; } SourceLocation getIfLoc() const { return IfLoc; } void setIfLoc(SourceLocation L) { IfLoc = L; } SourceLocation getElseLoc() const { return ElseLoc; } void setElseLoc(SourceLocation L) { ElseLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return IfLoc; } SourceLocation getLocEnd() const LLVM_READONLY { if (SubExprs[ELSE]) return SubExprs[ELSE]->getLocEnd(); else return SubExprs[THEN]->getLocEnd(); } // Iterators over subexpressions. The iterators will include iterating // over the initialization expression referenced by the condition variable. child_range children() { return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); } static bool classof(const Stmt *T) { return T->getStmtClass() == IfStmtClass; } }; /// SwitchStmt - This represents a 'switch' stmt. /// class SwitchStmt : public Stmt { enum { VAR, COND, BODY, END_EXPR }; Stmt* SubExprs[END_EXPR]; // This points to a linked list of case and default statements. SwitchCase *FirstCase; SourceLocation SwitchLoc; /// If the SwitchStmt is a switch on an enum value, this records whether /// all the enum values were covered by CaseStmts. This value is meant to /// be a hint for possible clients. unsigned AllEnumCasesCovered : 1; public: SwitchStmt(ASTContext &C, VarDecl *Var, Expr *cond); /// \brief Build a empty switch statement. explicit SwitchStmt(EmptyShell Empty) : Stmt(SwitchStmtClass, Empty) { } /// \brief Retrieve the variable declared in this "switch" statement, if any. /// /// In the following example, "x" is the condition variable. /// \code /// switch (int x = foo()) { /// case 0: break; /// // ... /// } /// \endcode VarDecl *getConditionVariable() const; void setConditionVariable(ASTContext &C, VarDecl *V); /// If this SwitchStmt has a condition variable, return the faux DeclStmt /// associated with the creation of that condition variable. const DeclStmt *getConditionVariableDeclStmt() const { return reinterpret_cast<DeclStmt*>(SubExprs[VAR]); } const Expr *getCond() const { return reinterpret_cast<Expr*>(SubExprs[COND]);} const Stmt *getBody() const { return SubExprs[BODY]; } const SwitchCase *getSwitchCaseList() const { return FirstCase; } Expr *getCond() { return reinterpret_cast<Expr*>(SubExprs[COND]);} void setCond(Expr *E) { SubExprs[COND] = reinterpret_cast<Stmt *>(E); } Stmt *getBody() { return SubExprs[BODY]; } void setBody(Stmt *S) { SubExprs[BODY] = S; } SwitchCase *getSwitchCaseList() { return FirstCase; } /// \brief Set the case list for this switch statement. /// /// The caller is responsible for incrementing the retain counts on /// all of the SwitchCase statements in this list. void setSwitchCaseList(SwitchCase *SC) { FirstCase = SC; } SourceLocation getSwitchLoc() const { return SwitchLoc; } void setSwitchLoc(SourceLocation L) { SwitchLoc = L; } void setBody(Stmt *S, SourceLocation SL) { SubExprs[BODY] = S; SwitchLoc = SL; } void addSwitchCase(SwitchCase *SC) { assert(!SC->getNextSwitchCase() && "case/default already added to a switch"); SC->setNextSwitchCase(FirstCase); FirstCase = SC; } /// Set a flag in the SwitchStmt indicating that if the 'switch (X)' is a /// switch over an enum value then all cases have been explicitly covered. void setAllEnumCasesCovered() { AllEnumCasesCovered = 1; } /// Returns true if the SwitchStmt is a switch of an enum value and all cases /// have been explicitly covered. bool isAllEnumCasesCovered() const { return (bool) AllEnumCasesCovered; } SourceLocation getLocStart() const LLVM_READONLY { return SwitchLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return SubExprs[BODY]->getLocEnd(); } // Iterators child_range children() { return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); } static bool classof(const Stmt *T) { return T->getStmtClass() == SwitchStmtClass; } }; /// WhileStmt - This represents a 'while' stmt. /// class WhileStmt : public Stmt { enum { VAR, COND, BODY, END_EXPR }; Stmt* SubExprs[END_EXPR]; SourceLocation WhileLoc; public: WhileStmt(ASTContext &C, VarDecl *Var, Expr *cond, Stmt *body, SourceLocation WL); /// \brief Build an empty while statement. explicit WhileStmt(EmptyShell Empty) : Stmt(WhileStmtClass, Empty) { } /// \brief Retrieve the variable declared in this "while" statement, if any. /// /// In the following example, "x" is the condition variable. /// \code /// while (int x = random()) { /// // ... /// } /// \endcode VarDecl *getConditionVariable() const; void setConditionVariable(ASTContext &C, VarDecl *V); /// If this WhileStmt has a condition variable, return the faux DeclStmt /// associated with the creation of that condition variable. const DeclStmt *getConditionVariableDeclStmt() const { return reinterpret_cast<DeclStmt*>(SubExprs[VAR]); } Expr *getCond() { return reinterpret_cast<Expr*>(SubExprs[COND]); } const Expr *getCond() const { return reinterpret_cast<Expr*>(SubExprs[COND]);} void setCond(Expr *E) { SubExprs[COND] = reinterpret_cast<Stmt*>(E); } Stmt *getBody() { return SubExprs[BODY]; } const Stmt *getBody() const { return SubExprs[BODY]; } void setBody(Stmt *S) { SubExprs[BODY] = S; } SourceLocation getWhileLoc() const { return WhileLoc; } void setWhileLoc(SourceLocation L) { WhileLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return WhileLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return SubExprs[BODY]->getLocEnd(); } static bool classof(const Stmt *T) { return T->getStmtClass() == WhileStmtClass; } // Iterators child_range children() { return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); } }; /// DoStmt - This represents a 'do/while' stmt. /// class DoStmt : public Stmt { enum { BODY, COND, END_EXPR }; Stmt* SubExprs[END_EXPR]; SourceLocation DoLoc; SourceLocation WhileLoc; SourceLocation RParenLoc; // Location of final ')' in do stmt condition. public: DoStmt(Stmt *body, Expr *cond, SourceLocation DL, SourceLocation WL, SourceLocation RP) : Stmt(DoStmtClass), DoLoc(DL), WhileLoc(WL), RParenLoc(RP) { SubExprs[COND] = reinterpret_cast<Stmt*>(cond); SubExprs[BODY] = body; } /// \brief Build an empty do-while statement. explicit DoStmt(EmptyShell Empty) : Stmt(DoStmtClass, Empty) { } Expr *getCond() { return reinterpret_cast<Expr*>(SubExprs[COND]); } const Expr *getCond() const { return reinterpret_cast<Expr*>(SubExprs[COND]);} void setCond(Expr *E) { SubExprs[COND] = reinterpret_cast<Stmt*>(E); } Stmt *getBody() { return SubExprs[BODY]; } const Stmt *getBody() const { return SubExprs[BODY]; } void setBody(Stmt *S) { SubExprs[BODY] = S; } SourceLocation getDoLoc() const { return DoLoc; } void setDoLoc(SourceLocation L) { DoLoc = L; } SourceLocation getWhileLoc() const { return WhileLoc; } void setWhileLoc(SourceLocation L) { WhileLoc = L; } SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return DoLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == DoStmtClass; } // Iterators child_range children() { return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); } }; /// ForStmt - This represents a 'for (init;cond;inc)' stmt. Note that any of /// the init/cond/inc parts of the ForStmt will be null if they were not /// specified in the source. /// class ForStmt : public Stmt { enum { INIT, CONDVAR, COND, INC, BODY, END_EXPR }; Stmt* SubExprs[END_EXPR]; // SubExprs[INIT] is an expression or declstmt. SourceLocation ForLoc; SourceLocation LParenLoc, RParenLoc; public: ForStmt(ASTContext &C, Stmt *Init, Expr *Cond, VarDecl *condVar, Expr *Inc, Stmt *Body, SourceLocation FL, SourceLocation LP, SourceLocation RP); /// \brief Build an empty for statement. explicit ForStmt(EmptyShell Empty) : Stmt(ForStmtClass, Empty) { } Stmt *getInit() { return SubExprs[INIT]; } /// \brief Retrieve the variable declared in this "for" statement, if any. /// /// In the following example, "y" is the condition variable. /// \code /// for (int x = random(); int y = mangle(x); ++x) { /// // ... /// } /// \endcode VarDecl *getConditionVariable() const; void setConditionVariable(ASTContext &C, VarDecl *V); /// If this ForStmt has a condition variable, return the faux DeclStmt /// associated with the creation of that condition variable. const DeclStmt *getConditionVariableDeclStmt() const { return reinterpret_cast<DeclStmt*>(SubExprs[CONDVAR]); } Expr *getCond() { return reinterpret_cast<Expr*>(SubExprs[COND]); } Expr *getInc() { return reinterpret_cast<Expr*>(SubExprs[INC]); } Stmt *getBody() { return SubExprs[BODY]; } const Stmt *getInit() const { return SubExprs[INIT]; } const Expr *getCond() const { return reinterpret_cast<Expr*>(SubExprs[COND]);} const Expr *getInc() const { return reinterpret_cast<Expr*>(SubExprs[INC]); } const Stmt *getBody() const { return SubExprs[BODY]; } void setInit(Stmt *S) { SubExprs[INIT] = S; } void setCond(Expr *E) { SubExprs[COND] = reinterpret_cast<Stmt*>(E); } void setInc(Expr *E) { SubExprs[INC] = reinterpret_cast<Stmt*>(E); } void setBody(Stmt *S) { SubExprs[BODY] = S; } SourceLocation getForLoc() const { return ForLoc; } void setForLoc(SourceLocation L) { ForLoc = L; } SourceLocation getLParenLoc() const { return LParenLoc; } void setLParenLoc(SourceLocation L) { LParenLoc = L; } SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return ForLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return SubExprs[BODY]->getLocEnd(); } static bool classof(const Stmt *T) { return T->getStmtClass() == ForStmtClass; } // Iterators child_range children() { return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); } }; /// GotoStmt - This represents a direct goto. /// class GotoStmt : public Stmt { LabelDecl *Label; SourceLocation GotoLoc; SourceLocation LabelLoc; public: GotoStmt(LabelDecl *label, SourceLocation GL, SourceLocation LL) : Stmt(GotoStmtClass), Label(label), GotoLoc(GL), LabelLoc(LL) {} /// \brief Build an empty goto statement. explicit GotoStmt(EmptyShell Empty) : Stmt(GotoStmtClass, Empty) { } LabelDecl *getLabel() const { return Label; } void setLabel(LabelDecl *D) { Label = D; } SourceLocation getGotoLoc() const { return GotoLoc; } void setGotoLoc(SourceLocation L) { GotoLoc = L; } SourceLocation getLabelLoc() const { return LabelLoc; } void setLabelLoc(SourceLocation L) { LabelLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return GotoLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return LabelLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == GotoStmtClass; } // Iterators child_range children() { return child_range(); } }; /// IndirectGotoStmt - This represents an indirect goto. /// class IndirectGotoStmt : public Stmt { SourceLocation GotoLoc; SourceLocation StarLoc; Stmt *Target; public: IndirectGotoStmt(SourceLocation gotoLoc, SourceLocation starLoc, Expr *target) : Stmt(IndirectGotoStmtClass), GotoLoc(gotoLoc), StarLoc(starLoc), Target((Stmt*)target) {} /// \brief Build an empty indirect goto statement. explicit IndirectGotoStmt(EmptyShell Empty) : Stmt(IndirectGotoStmtClass, Empty) { } void setGotoLoc(SourceLocation L) { GotoLoc = L; } SourceLocation getGotoLoc() const { return GotoLoc; } void setStarLoc(SourceLocation L) { StarLoc = L; } SourceLocation getStarLoc() const { return StarLoc; } Expr *getTarget() { return reinterpret_cast<Expr*>(Target); } const Expr *getTarget() const {return reinterpret_cast<const Expr*>(Target);} void setTarget(Expr *E) { Target = reinterpret_cast<Stmt*>(E); } /// getConstantTarget - Returns the fixed target of this indirect /// goto, if one exists. LabelDecl *getConstantTarget(); const LabelDecl *getConstantTarget() const { return const_cast<IndirectGotoStmt*>(this)->getConstantTarget(); } SourceLocation getLocStart() const LLVM_READONLY { return GotoLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return Target->getLocEnd(); } static bool classof(const Stmt *T) { return T->getStmtClass() == IndirectGotoStmtClass; } // Iterators child_range children() { return child_range(&Target, &Target+1); } }; /// ContinueStmt - This represents a continue. /// class ContinueStmt : public Stmt { SourceLocation ContinueLoc; public: ContinueStmt(SourceLocation CL) : Stmt(ContinueStmtClass), ContinueLoc(CL) {} /// \brief Build an empty continue statement. explicit ContinueStmt(EmptyShell Empty) : Stmt(ContinueStmtClass, Empty) { } SourceLocation getContinueLoc() const { return ContinueLoc; } void setContinueLoc(SourceLocation L) { ContinueLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return ContinueLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return ContinueLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == ContinueStmtClass; } // Iterators child_range children() { return child_range(); } }; /// BreakStmt - This represents a break. /// class BreakStmt : public Stmt { SourceLocation BreakLoc; public: BreakStmt(SourceLocation BL) : Stmt(BreakStmtClass), BreakLoc(BL) {} /// \brief Build an empty break statement. explicit BreakStmt(EmptyShell Empty) : Stmt(BreakStmtClass, Empty) { } SourceLocation getBreakLoc() const { return BreakLoc; } void setBreakLoc(SourceLocation L) { BreakLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return BreakLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return BreakLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == BreakStmtClass; } // Iterators child_range children() { return child_range(); } }; /// ReturnStmt - This represents a return, optionally of an expression: /// return; /// return 4; /// /// Note that GCC allows return with no argument in a function declared to /// return a value, and it allows returning a value in functions declared to /// return void. We explicitly model this in the AST, which means you can't /// depend on the return type of the function and the presence of an argument. /// class ReturnStmt : public Stmt { Stmt *RetExpr; SourceLocation RetLoc; const VarDecl *NRVOCandidate; public: ReturnStmt(SourceLocation RL) : Stmt(ReturnStmtClass), RetExpr(0), RetLoc(RL), NRVOCandidate(0) { } ReturnStmt(SourceLocation RL, Expr *E, const VarDecl *NRVOCandidate) : Stmt(ReturnStmtClass), RetExpr((Stmt*) E), RetLoc(RL), NRVOCandidate(NRVOCandidate) {} /// \brief Build an empty return expression. explicit ReturnStmt(EmptyShell Empty) : Stmt(ReturnStmtClass, Empty) { } const Expr *getRetValue() const; Expr *getRetValue(); void setRetValue(Expr *E) { RetExpr = reinterpret_cast<Stmt*>(E); } SourceLocation getReturnLoc() const { return RetLoc; } void setReturnLoc(SourceLocation L) { RetLoc = L; } /// \brief Retrieve the variable that might be used for the named return /// value optimization. /// /// The optimization itself can only be performed if the variable is /// also marked as an NRVO object. const VarDecl *getNRVOCandidate() const { return NRVOCandidate; } void setNRVOCandidate(const VarDecl *Var) { NRVOCandidate = Var; } SourceLocation getLocStart() const LLVM_READONLY { return RetLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return RetExpr ? RetExpr->getLocEnd() : RetLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == ReturnStmtClass; } // Iterators child_range children() { if (RetExpr) return child_range(&RetExpr, &RetExpr+1); return child_range(); } }; /// AsmStmt is the base class for GCCAsmStmt and MSAsmStmt. /// class AsmStmt : public Stmt { protected: SourceLocation AsmLoc; /// \brief True if the assembly statement does not have any input or output /// operands. bool IsSimple; /// \brief If true, treat this inline assembly as having side effects. /// This assembly statement should not be optimized, deleted or moved. bool IsVolatile; unsigned NumOutputs; unsigned NumInputs; unsigned NumClobbers; Stmt **Exprs; AsmStmt(StmtClass SC, SourceLocation asmloc, bool issimple, bool isvolatile, unsigned numoutputs, unsigned numinputs, unsigned numclobbers) : Stmt (SC), AsmLoc(asmloc), IsSimple(issimple), IsVolatile(isvolatile), NumOutputs(numoutputs), NumInputs(numinputs), NumClobbers(numclobbers) { } friend class ASTStmtReader; public: /// \brief Build an empty inline-assembly statement. explicit AsmStmt(StmtClass SC, EmptyShell Empty) : Stmt(SC, Empty), Exprs(0) { } SourceLocation getAsmLoc() const { return AsmLoc; } void setAsmLoc(SourceLocation L) { AsmLoc = L; } bool isSimple() const { return IsSimple; } void setSimple(bool V) { IsSimple = V; } bool isVolatile() const { return IsVolatile; } void setVolatile(bool V) { IsVolatile = V; } SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); } SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); } //===--- Asm String Analysis ---===// /// Assemble final IR asm string. std::string generateAsmString(ASTContext &C) const; //===--- Output operands ---===// unsigned getNumOutputs() const { return NumOutputs; } /// getOutputConstraint - Return the constraint string for the specified /// output operand. All output constraints are known to be non-empty (either /// '=' or '+'). StringRef getOutputConstraint(unsigned i) const; /// isOutputPlusConstraint - Return true if the specified output constraint /// is a "+" constraint (which is both an input and an output) or false if it /// is an "=" constraint (just an output). bool isOutputPlusConstraint(unsigned i) const { return getOutputConstraint(i)[0] == '+'; } const Expr *getOutputExpr(unsigned i) const; /// getNumPlusOperands - Return the number of output operands that have a "+" /// constraint. unsigned getNumPlusOperands() const; //===--- Input operands ---===// unsigned getNumInputs() const { return NumInputs; } /// getInputConstraint - Return the specified input constraint. Unlike output /// constraints, these can be empty. StringRef getInputConstraint(unsigned i) const; const Expr *getInputExpr(unsigned i) const; //===--- Other ---===// unsigned getNumClobbers() const { return NumClobbers; } StringRef getClobber(unsigned i) const; static bool classof(const Stmt *T) { return T->getStmtClass() == GCCAsmStmtClass || T->getStmtClass() == MSAsmStmtClass; } // Input expr iterators. typedef ExprIterator inputs_iterator; typedef ConstExprIterator const_inputs_iterator; inputs_iterator begin_inputs() { return &Exprs[0] + NumOutputs; } inputs_iterator end_inputs() { return &Exprs[0] + NumOutputs + NumInputs; } const_inputs_iterator begin_inputs() const { return &Exprs[0] + NumOutputs; } const_inputs_iterator end_inputs() const { return &Exprs[0] + NumOutputs + NumInputs; } // Output expr iterators. typedef ExprIterator outputs_iterator; typedef ConstExprIterator const_outputs_iterator; outputs_iterator begin_outputs() { return &Exprs[0]; } outputs_iterator end_outputs() { return &Exprs[0] + NumOutputs; } const_outputs_iterator begin_outputs() const { return &Exprs[0]; } const_outputs_iterator end_outputs() const { return &Exprs[0] + NumOutputs; } child_range children() { return child_range(&Exprs[0], &Exprs[0] + NumOutputs + NumInputs); } }; /// This represents a GCC inline-assembly statement extension. /// class GCCAsmStmt : public AsmStmt { SourceLocation RParenLoc; StringLiteral *AsmStr; // FIXME: If we wanted to, we could allocate all of these in one big array. StringLiteral **Constraints; StringLiteral **Clobbers; IdentifierInfo **Names; friend class ASTStmtReader; public: GCCAsmStmt(ASTContext &C, SourceLocation asmloc, bool issimple, bool isvolatile, unsigned numoutputs, unsigned numinputs, IdentifierInfo **names, StringLiteral **constraints, Expr **exprs, StringLiteral *asmstr, unsigned numclobbers, StringLiteral **clobbers, SourceLocation rparenloc); /// \brief Build an empty inline-assembly statement. explicit GCCAsmStmt(EmptyShell Empty) : AsmStmt(GCCAsmStmtClass, Empty), Constraints(0), Clobbers(0), Names(0) { } SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } //===--- Asm String Analysis ---===// const StringLiteral *getAsmString() const { return AsmStr; } StringLiteral *getAsmString() { return AsmStr; } void setAsmString(StringLiteral *E) { AsmStr = E; } /// AsmStringPiece - this is part of a decomposed asm string specification /// (for use with the AnalyzeAsmString function below). An asm string is /// considered to be a concatenation of these parts. class AsmStringPiece { public: enum Kind { String, // String in .ll asm string form, "$" -> "$$" and "%%" -> "%". Operand // Operand reference, with optional modifier %c4. }; private: Kind MyKind; std::string Str; unsigned OperandNo; public: AsmStringPiece(const std::string &S) : MyKind(String), Str(S) {} AsmStringPiece(unsigned OpNo, char Modifier) : MyKind(Operand), Str(), OperandNo(OpNo) { Str += Modifier; } bool isString() const { return MyKind == String; } bool isOperand() const { return MyKind == Operand; } const std::string &getString() const { assert(isString()); return Str; } unsigned getOperandNo() const { assert(isOperand()); return OperandNo; } /// getModifier - Get the modifier for this operand, if present. This /// returns '\0' if there was no modifier. char getModifier() const { assert(isOperand()); return Str[0]; } }; /// AnalyzeAsmString - Analyze the asm string of the current asm, decomposing /// it into pieces. If the asm string is erroneous, emit errors and return /// true, otherwise return false. This handles canonicalization and /// translation of strings from GCC syntax to LLVM IR syntax, and handles //// flattening of named references like %[foo] to Operand AsmStringPiece's. unsigned AnalyzeAsmString(SmallVectorImpl<AsmStringPiece> &Pieces, ASTContext &C, unsigned &DiagOffs) const; /// Assemble final IR asm string. std::string generateAsmString(ASTContext &C) const; //===--- Output operands ---===// IdentifierInfo *getOutputIdentifier(unsigned i) const { return Names[i]; } StringRef getOutputName(unsigned i) const { if (IdentifierInfo *II = getOutputIdentifier(i)) return II->getName(); return StringRef(); } StringRef getOutputConstraint(unsigned i) const; const StringLiteral *getOutputConstraintLiteral(unsigned i) const { return Constraints[i]; } StringLiteral *getOutputConstraintLiteral(unsigned i) { return Constraints[i]; } Expr *getOutputExpr(unsigned i); const Expr *getOutputExpr(unsigned i) const { return const_cast<GCCAsmStmt*>(this)->getOutputExpr(i); } //===--- Input operands ---===// IdentifierInfo *getInputIdentifier(unsigned i) const { return Names[i + NumOutputs]; } StringRef getInputName(unsigned i) const { if (IdentifierInfo *II = getInputIdentifier(i)) return II->getName(); return StringRef(); } StringRef getInputConstraint(unsigned i) const; const StringLiteral *getInputConstraintLiteral(unsigned i) const { return Constraints[i + NumOutputs]; } StringLiteral *getInputConstraintLiteral(unsigned i) { return Constraints[i + NumOutputs]; } Expr *getInputExpr(unsigned i); void setInputExpr(unsigned i, Expr *E); const Expr *getInputExpr(unsigned i) const { return const_cast<GCCAsmStmt*>(this)->getInputExpr(i); } private: void setOutputsAndInputsAndClobbers(ASTContext &C, IdentifierInfo **Names, StringLiteral **Constraints, Stmt **Exprs, unsigned NumOutputs, unsigned NumInputs, StringLiteral **Clobbers, unsigned NumClobbers); public: //===--- Other ---===// /// getNamedOperand - Given a symbolic operand reference like %[foo], /// translate this into a numeric value needed to reference the same operand. /// This returns -1 if the operand name is invalid. int getNamedOperand(StringRef SymbolicName) const; StringRef getClobber(unsigned i) const; StringLiteral *getClobberStringLiteral(unsigned i) { return Clobbers[i]; } const StringLiteral *getClobberStringLiteral(unsigned i) const { return Clobbers[i]; } SourceLocation getLocStart() const LLVM_READONLY { return AsmLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == GCCAsmStmtClass; } }; /// This represents a Microsoft inline-assembly statement extension. /// class MSAsmStmt : public AsmStmt { SourceLocation LBraceLoc, EndLoc; StringRef AsmStr; unsigned NumAsmToks; Token *AsmToks; StringRef *Constraints; StringRef *Clobbers; friend class ASTStmtReader; public: MSAsmStmt(ASTContext &C, SourceLocation asmloc, SourceLocation lbraceloc, bool issimple, bool isvolatile, ArrayRef<Token> asmtoks, unsigned numoutputs, unsigned numinputs, ArrayRef<StringRef> constraints, ArrayRef<Expr*> exprs, StringRef asmstr, ArrayRef<StringRef> clobbers, SourceLocation endloc); /// \brief Build an empty MS-style inline-assembly statement. explicit MSAsmStmt(EmptyShell Empty) : AsmStmt(MSAsmStmtClass, Empty), NumAsmToks(0), AsmToks(0), Constraints(0), Clobbers(0) { } SourceLocation getLBraceLoc() const { return LBraceLoc; } void setLBraceLoc(SourceLocation L) { LBraceLoc = L; } SourceLocation getEndLoc() const { return EndLoc; } void setEndLoc(SourceLocation L) { EndLoc = L; } bool hasBraces() const { return LBraceLoc.isValid(); } unsigned getNumAsmToks() { return NumAsmToks; } Token *getAsmToks() { return AsmToks; } //===--- Asm String Analysis ---===// StringRef getAsmString() const { return AsmStr; } /// Assemble final IR asm string. std::string generateAsmString(ASTContext &C) const; //===--- Output operands ---===// StringRef getOutputConstraint(unsigned i) const { assert(i < NumOutputs); return Constraints[i]; } Expr *getOutputExpr(unsigned i); const Expr *getOutputExpr(unsigned i) const { return const_cast<MSAsmStmt*>(this)->getOutputExpr(i); } //===--- Input operands ---===// StringRef getInputConstraint(unsigned i) const { assert(i < NumInputs); return Constraints[i + NumOutputs]; } Expr *getInputExpr(unsigned i); void setInputExpr(unsigned i, Expr *E); const Expr *getInputExpr(unsigned i) const { return const_cast<MSAsmStmt*>(this)->getInputExpr(i); } //===--- Other ---===// ArrayRef<StringRef> getAllConstraints() const { return ArrayRef<StringRef>(Constraints, NumInputs + NumOutputs); } ArrayRef<StringRef> getClobbers() const { return ArrayRef<StringRef>(Clobbers, NumClobbers); } ArrayRef<Expr*> getAllExprs() const { return ArrayRef<Expr*>(reinterpret_cast<Expr**>(Exprs), NumInputs + NumOutputs); } StringRef getClobber(unsigned i) const { return getClobbers()[i]; } private: void initialize(ASTContext &C, StringRef AsmString, ArrayRef<Token> AsmToks, ArrayRef<StringRef> Constraints, ArrayRef<Expr*> Exprs, ArrayRef<StringRef> Clobbers); public: SourceLocation getLocStart() const LLVM_READONLY { return AsmLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return EndLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == MSAsmStmtClass; } child_range children() { return child_range(&Exprs[0], &Exprs[0]); } }; class SEHExceptStmt : public Stmt { SourceLocation Loc; Stmt *Children[2]; enum { FILTER_EXPR, BLOCK }; SEHExceptStmt(SourceLocation Loc, Expr *FilterExpr, Stmt *Block); friend class ASTReader; friend class ASTStmtReader; explicit SEHExceptStmt(EmptyShell E) : Stmt(SEHExceptStmtClass, E) { } public: static SEHExceptStmt* Create(ASTContext &C, SourceLocation ExceptLoc, Expr *FilterExpr, Stmt *Block); SourceLocation getLocStart() const LLVM_READONLY { return getExceptLoc(); } SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); } SourceLocation getExceptLoc() const { return Loc; } SourceLocation getEndLoc() const { return getBlock()->getLocEnd(); } Expr *getFilterExpr() const { return reinterpret_cast<Expr*>(Children[FILTER_EXPR]); } CompoundStmt *getBlock() const { return cast<CompoundStmt>(Children[BLOCK]); } child_range children() { return child_range(Children,Children+2); } static bool classof(const Stmt *T) { return T->getStmtClass() == SEHExceptStmtClass; } }; class SEHFinallyStmt : public Stmt { SourceLocation Loc; Stmt *Block; SEHFinallyStmt(SourceLocation Loc, Stmt *Block); friend class ASTReader; friend class ASTStmtReader; explicit SEHFinallyStmt(EmptyShell E) : Stmt(SEHFinallyStmtClass, E) { } public: static SEHFinallyStmt* Create(ASTContext &C, SourceLocation FinallyLoc, Stmt *Block); SourceLocation getLocStart() const LLVM_READONLY { return getFinallyLoc(); } SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); } SourceLocation getFinallyLoc() const { return Loc; } SourceLocation getEndLoc() const { return Block->getLocEnd(); } CompoundStmt *getBlock() const { return cast<CompoundStmt>(Block); } child_range children() { return child_range(&Block,&Block+1); } static bool classof(const Stmt *T) { return T->getStmtClass() == SEHFinallyStmtClass; } }; class SEHTryStmt : public Stmt { bool IsCXXTry; SourceLocation TryLoc; Stmt *Children[2]; enum { TRY = 0, HANDLER = 1 }; SEHTryStmt(bool isCXXTry, // true if 'try' otherwise '__try' SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler); friend class ASTReader; friend class ASTStmtReader; explicit SEHTryStmt(EmptyShell E) : Stmt(SEHTryStmtClass, E) { } public: static SEHTryStmt* Create(ASTContext &C, bool isCXXTry, SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler); SourceLocation getLocStart() const LLVM_READONLY { return getTryLoc(); } SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); } SourceLocation getTryLoc() const { return TryLoc; } SourceLocation getEndLoc() const { return Children[HANDLER]->getLocEnd(); } bool getIsCXXTry() const { return IsCXXTry; } CompoundStmt* getTryBlock() const { return cast<CompoundStmt>(Children[TRY]); } Stmt *getHandler() const { return Children[HANDLER]; } /// Returns 0 if not defined SEHExceptStmt *getExceptHandler() const; SEHFinallyStmt *getFinallyHandler() const; child_range children() { return child_range(Children,Children+2); } static bool classof(const Stmt *T) { return T->getStmtClass() == SEHTryStmtClass; } }; /// \brief This captures a statement into a function. For example, the following /// pragma annotated compound statement can be represented as a CapturedStmt, /// and this compound statement is the body of an anonymous outlined function. /// @code /// #pragma omp parallel /// { /// compute(); /// } /// @endcode class CapturedStmt : public Stmt { public: /// \brief The different capture forms: by 'this' or by reference, etc. enum VariableCaptureKind { VCK_This, VCK_ByRef }; /// \brief Describes the capture of either a variable or 'this'. class Capture { llvm::PointerIntPair<VarDecl *, 1, VariableCaptureKind> VarAndKind; SourceLocation Loc; public: /// \brief Create a new capture. /// /// \param Loc The source location associated with this capture. /// /// \param Kind The kind of capture (this, ByRef, ...). /// /// \param Var The variable being captured, or null if capturing this. /// Capture(SourceLocation Loc, VariableCaptureKind Kind, VarDecl *Var = 0) : VarAndKind(Var, Kind), Loc(Loc) { switch (Kind) { case VCK_This: assert(Var == 0 && "'this' capture cannot have a variable!"); break; case VCK_ByRef: assert(Var && "capturing by reference must have a variable!"); break; } } /// \brief Determine the kind of capture. VariableCaptureKind getCaptureKind() const { return VarAndKind.getInt(); } /// \brief Retrieve the source location at which the variable or 'this' was /// first used. SourceLocation getLocation() const { return Loc; } /// \brief Determine whether this capture handles the C++ 'this' pointer. bool capturesThis() const { return getCaptureKind() == VCK_This; } /// \brief Determine whether this capture handles a variable. bool capturesVariable() const { return getCaptureKind() != VCK_This; } /// \brief Retrieve the declaration of the variable being captured. /// /// This operation is only valid if this capture does not capture 'this'. VarDecl *getCapturedVar() const { assert(!capturesThis() && "No variable available for 'this' capture"); return VarAndKind.getPointer(); } friend class ASTStmtReader; }; private: /// \brief The number of variable captured, including 'this'. unsigned NumCaptures; /// \brief The pointer part is the implicit the outlined function and the /// int part is the captured region kind, 'CR_Default' etc. llvm::PointerIntPair<CapturedDecl *, 1, CapturedRegionKind> CapDeclAndKind; /// \brief The record for captured variables, a RecordDecl or CXXRecordDecl. RecordDecl *TheRecordDecl; /// \brief Construct a captured statement. CapturedStmt(Stmt *S, CapturedRegionKind Kind, ArrayRef<Capture> Captures, ArrayRef<Expr *> CaptureInits, CapturedDecl *CD, RecordDecl *RD); /// \brief Construct an empty captured statement. CapturedStmt(EmptyShell Empty, unsigned NumCaptures); Stmt **getStoredStmts() const { return reinterpret_cast<Stmt **>(const_cast<CapturedStmt *>(this) + 1); } Capture *getStoredCaptures() const; void setCapturedStmt(Stmt *S) { getStoredStmts()[NumCaptures] = S; } public: static CapturedStmt *Create(ASTContext &Context, Stmt *S, CapturedRegionKind Kind, ArrayRef<Capture> Captures, ArrayRef<Expr *> CaptureInits, CapturedDecl *CD, RecordDecl *RD); static CapturedStmt *CreateDeserialized(ASTContext &Context, unsigned NumCaptures); /// \brief Retrieve the statement being captured. Stmt *getCapturedStmt() { return getStoredStmts()[NumCaptures]; } const Stmt *getCapturedStmt() const { return const_cast<CapturedStmt *>(this)->getCapturedStmt(); } /// \brief Retrieve the outlined function declaration. CapturedDecl *getCapturedDecl() { return CapDeclAndKind.getPointer(); } const CapturedDecl *getCapturedDecl() const { return const_cast<CapturedStmt *>(this)->getCapturedDecl(); } /// \brief Set the outlined function declaration. void setCapturedDecl(CapturedDecl *D) { assert(D && "null CapturedDecl"); CapDeclAndKind.setPointer(D); } /// \brief Retrieve the captured region kind. CapturedRegionKind getCapturedRegionKind() const { return CapDeclAndKind.getInt(); } /// \brief Set the captured region kind. void setCapturedRegionKind(CapturedRegionKind Kind) { CapDeclAndKind.setInt(Kind); } /// \brief Retrieve the record declaration for captured variables. const RecordDecl *getCapturedRecordDecl() const { return TheRecordDecl; } /// \brief Set the record declaration for captured variables. void setCapturedRecordDecl(RecordDecl *D) { assert(D && "null RecordDecl"); TheRecordDecl = D; } /// \brief True if this variable has been captured. bool capturesVariable(const VarDecl *Var) const; /// \brief An iterator that walks over the captures. typedef Capture *capture_iterator; typedef const Capture *const_capture_iterator; /// \brief Retrieve an iterator pointing to the first capture. capture_iterator capture_begin() { return getStoredCaptures(); } const_capture_iterator capture_begin() const { return getStoredCaptures(); } /// \brief Retrieve an iterator pointing past the end of the sequence of /// captures. capture_iterator capture_end() const { return getStoredCaptures() + NumCaptures; } /// \brief Retrieve the number of captures, including 'this'. unsigned capture_size() const { return NumCaptures; } /// \brief Iterator that walks over the capture initialization arguments. typedef Expr **capture_init_iterator; /// \brief Retrieve the first initialization argument. capture_init_iterator capture_init_begin() const { return reinterpret_cast<Expr **>(getStoredStmts()); } /// \brief Retrieve the iterator pointing one past the last initialization /// argument. capture_init_iterator capture_init_end() const { return capture_init_begin() + NumCaptures; } SourceLocation getLocStart() const LLVM_READONLY { return getCapturedStmt()->getLocStart(); } SourceLocation getLocEnd() const LLVM_READONLY { return getCapturedStmt()->getLocEnd(); } SourceRange getSourceRange() const LLVM_READONLY { return getCapturedStmt()->getSourceRange(); } static bool classof(const Stmt *T) { return T->getStmtClass() == CapturedStmtClass; } child_range children(); friend class ASTStmtReader; }; } // end namespace clang #endif
openmp.c
#include <stdio.h> #include <omp.h> int main() { int i; #pragma omp parallel for for(i=0; i < 8; i++) { printf("Thread %d says hello.\n", omp_get_thread_num() ); } return 0; } // compile with gcc -fopenmp openmp.c
GB_AxB_dot4_template.c
//------------------------------------------------------------------------------ // GB_AxB_dot4_template: C+=A'*B via dot products, where C is full //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // C+=A'*B where C is full and computed in-place. The monoid of the semiring // matches the accum operator, and the type of C matches the ztype of accum. // The PAIR and FIRSTJ multiplicative operators are important special cases. // The matrix C is the user input matrix. C is not iso on output, but might // iso on input, in which case the input iso scalar is cinput, and C->x has // been expanded to non-iso, and initialized if A and/or B are hypersparse. // A and/or B can be iso. // MIN_FIRSTJ or MIN_FIRSTJ1 semirings: #define GB_IS_MIN_FIRSTJ_SEMIRING (GB_IS_IMIN_MONOID && GB_IS_FIRSTJ_MULTIPLIER) // MAX_FIRSTJ or MAX_FIRSTJ1 semirings: #define GB_IS_MAX_FIRSTJ_SEMIRING (GB_IS_IMAX_MONOID && GB_IS_FIRSTJ_MULTIPLIER) // GB_OFFSET is 1 for the MIN/MAX_FIRSTJ1 semirings, and 0 otherwise. #if GB_IS_ANY_MONOID #error "dot4 is not used for the ANY monoid" #endif #undef GB_GET4C #define GB_GET4C(cij,p) cij = (C_in_iso) ? cinput : Cx [p] #if ((GB_A_IS_BITMAP || GB_A_IS_FULL) && (GB_B_IS_BITMAP || GB_B_IS_FULL )) { //-------------------------------------------------------------------------- // C += A'*B where A and B are both bitmap/full //-------------------------------------------------------------------------- // FUTURE: This method is not particularly efficient when both A and B are // bitmap/full. A better method would use tiles to reduce memory traffic. int tid ; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (tid = 0 ; tid < ntasks ; tid++) { //---------------------------------------------------------------------- // get the task descriptor //---------------------------------------------------------------------- const int a_tid = tid / nbslice ; const int b_tid = tid % nbslice ; const int64_t kA_start = A_slice [a_tid] ; const int64_t kA_end = A_slice [a_tid+1] ; const int64_t kB_start = B_slice [b_tid] ; const int64_t kB_end = B_slice [b_tid+1] ; for (int64_t j = kB_start ; j < kB_end ; j++) { //------------------------------------------------------------------ // get B(:,j) and C(:,j) //------------------------------------------------------------------ const int64_t pC_start = j * cvlen ; const int64_t pB_start = j * vlen ; //------------------------------------------------------------------ // C(:,j) += A'*B(:,j) //------------------------------------------------------------------ for (int64_t i = kA_start ; i < kA_end ; i++) { //-------------------------------------------------------------- // get A(:,i) //-------------------------------------------------------------- const int64_t pA = i * vlen ; //-------------------------------------------------------------- // get C(i,j) //-------------------------------------------------------------- int64_t pC = i + pC_start ; // C(i,j) is at Cx [pC] GB_CTYPE GB_GET4C (cij, pC) ; // cij = Cx [pC] //-------------------------------------------------------------- // C(i,j) += A (:,i)*B(:,j): a single dot product //-------------------------------------------------------------- int64_t pB = pB_start ; #if ( GB_A_IS_FULL && GB_B_IS_FULL ) { //---------------------------------------------------------- // both A and B are full //---------------------------------------------------------- #if GB_IS_PAIR_MULTIPLIER { #if GB_IS_EQ_MONOID // EQ_PAIR semiring cij = (cij == 1) ; #elif (GB_CTYPE_BITS > 0) // PLUS, XOR monoids: A(:,i)'*B(:,j) is nnz(A(:,i)), // for bool, 8-bit, 16-bit, or 32-bit integer uint64_t t = ((uint64_t) cij) + vlen ; cij = (GB_CTYPE) (t & GB_CTYPE_BITS) ; #elif GB_IS_PLUS_FC32_MONOID // PLUS monoid for float complex cij = GxB_CMPLXF (crealf (cij) + (float) vlen, 0) ; #elif GB_IS_PLUS_FC64_MONOID // PLUS monoid for double complex cij = GxB_CMPLX (creal (cij) + (double) vlen, 0) ; #else // PLUS monoid for float, double, or 64-bit integers cij += (GB_CTYPE) vlen ; #endif } #elif GB_IS_MIN_FIRSTJ_SEMIRING { // MIN_FIRSTJ semiring: take the first entry if (vlen > 0) { int64_t k = GB_OFFSET ; cij = GB_IMIN (cij, k) ; } } #elif GB_IS_MAX_FIRSTJ_SEMIRING { // MAX_FIRSTJ semiring: take the last entry if (vlen > 0) { int64_t k = vlen-1 + GB_OFFSET ; cij = GB_IMAX (cij, k) ; } } #else { GB_PRAGMA_SIMD_DOT (cij) for (int64_t k = 0 ; k < vlen ; k++) { GB_DOT (k, pA+k, pB+k) ; // cij += A(k,i)*B(k,j) } } #endif } #elif ( GB_A_IS_FULL && GB_B_IS_BITMAP ) { //---------------------------------------------------------- // A is full and B is bitmap //---------------------------------------------------------- #if GB_IS_MIN_FIRSTJ_SEMIRING { // MIN_FIRSTJ semiring: take the first entry in B(:,j) for (int64_t k = 0 ; k < vlen ; k++) { if (Bb [pB+k]) { cij = GB_IMIN (cij, k + GB_OFFSET) ; break ; } } } #elif GB_IS_MAX_FIRSTJ_SEMIRING { // MAX_FIRSTJ semiring: take the last entry in B(:,j) for (int64_t k = vlen-1 ; k >= 0 ; k--) { if (Bb [pB+k]) { cij = GB_IMAX (cij, k + GB_OFFSET) ; break ; } } } #else { GB_PRAGMA_SIMD_DOT (cij) for (int64_t k = 0 ; k < vlen ; k++) { if (Bb [pB+k]) { GB_DOT (k, pA+k, pB+k) ; // cij += A(k,i)*B(k,j) } } } #endif } #elif ( GB_A_IS_BITMAP && GB_B_IS_FULL ) { //---------------------------------------------------------- // A is bitmap and B is full //---------------------------------------------------------- #if GB_IS_MIN_FIRSTJ_SEMIRING { // MIN_FIRSTJ semiring: take the first entry in A(:,i) for (int64_t k = 0 ; k < vlen ; k++) { if (Ab [pA+k]) { cij = GB_IMIN (cij, k + GB_OFFSET) ; break ; } } } #elif GB_IS_MAX_FIRSTJ_SEMIRING { // MAX_FIRSTJ semiring: take the last entry in A(:,i) for (int64_t k = vlen-1 ; k >= 0 ; k--) { if (Ab [pA+k]) { cij = GB_IMAX (cij, k + GB_OFFSET) ; break ; } } } #else { GB_PRAGMA_SIMD_DOT (cij) for (int64_t k = 0 ; k < vlen ; k++) { if (Ab [pA+k]) { GB_DOT (k, pA+k, pB+k) ; // cij += A(k,i)*B(k,j) } } } #endif } #elif ( GB_A_IS_BITMAP && GB_B_IS_BITMAP ) { //---------------------------------------------------------- // both A and B are bitmap //---------------------------------------------------------- #if GB_IS_MIN_FIRSTJ_SEMIRING { // MIN_FIRSTJ semiring: take the first entry for (int64_t k = 0 ; k < vlen ; k++) { if (Ab [pA+k] && Bb [pB+k]) { cij = GB_IMIN (cij, k + GB_OFFSET) ; break ; } } } #elif GB_IS_MAX_FIRSTJ_SEMIRING { // MAX_FIRSTJ semiring: take the last entry for (int64_t k = vlen-1 ; k >= 0 ; k--) { if (Ab [pA+k] && Bb [pB+k]) { cij = GB_IMAX (cij, k + GB_OFFSET) ; break ; } } } #else { GB_PRAGMA_SIMD_DOT (cij) for (int64_t k = 0 ; k < vlen ; k++) { if (Ab [pA+k] && Bb [pB+k]) { GB_DOT (k, pA+k, pB+k) ; // cij += A(k,i)*B(k,j) } } } #endif } #endif //-------------------------------------------------------------- // save C(i,j) //-------------------------------------------------------------- Cx [pC] = cij ; } } } } #elif ((GB_A_IS_SPARSE || GB_A_IS_HYPER) && (GB_B_IS_BITMAP || GB_B_IS_FULL )) { //-------------------------------------------------------------------------- // C += A'*B when A is sparse/hyper and B is bitmap/full //-------------------------------------------------------------------------- // special cases: these methods are very fast, but cannot do not need // to be unrolled. #undef GB_SPECIAL_CASE_OR_TERMINAL #define GB_SPECIAL_CASE_OR_TERMINAL \ ( GB_IS_PAIR_MULTIPLIER /* the multiply op is PAIR */ \ || GB_IS_MIN_FIRSTJ_SEMIRING /* min_firstj semiring */ \ || GB_IS_MAX_FIRSTJ_SEMIRING /* max_firstj semiring */ \ || GB_MONOID_IS_TERMINAL /* monoid has a terminal value */ \ || GB_B_IS_PATTERN ) /* B is pattern-only */ // Transpose B and unroll the innermost loop if this condition holds: A // must be sparse, B must be full, and no special semirings or operators // can be used. The monoid must not be terminal. These conditions are // known at compile time. #undef GB_UNROLL #define GB_UNROLL \ ( GB_A_IS_SPARSE && GB_B_IS_FULL && !( GB_SPECIAL_CASE_OR_TERMINAL ) ) // If GB_UNROLL is true at compile-time, the simpler variant can still be // used, without unrolling, for any of these conditions: (1) A is very // sparse (fewer entries than the size of the W workspace) or (2) B is iso. // The unrolled method does not allow B to be iso or pattern-only (such as // for the FIRST multiplicative operator. If B is iso or pattern-only, the // dense matrix G = B' would be a single scalar, or its values would not be // accessed at all, so there is no benefit to computing G. #if GB_UNROLL const int64_t wp = (bvdim == 1) ? 0 : GB_IMIN (bvdim, 4) ; const int64_t anz = GB_nnz (A) ; if (anz < wp * vlen || B_iso) #endif { //---------------------------------------------------------------------- // C += A'*B without workspace //---------------------------------------------------------------------- int tid ; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (tid = 0 ; tid < ntasks ; tid++) { //------------------------------------------------------------------ // get the task descriptor //------------------------------------------------------------------ const int64_t kA_start = A_slice [tid] ; const int64_t kA_end = A_slice [tid+1] ; //------------------------------------------------------------------ // C+=A'*B where A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------ for (int64_t kA = kA_start ; kA < kA_end ; kA++) { // get A(:,i) #if GB_A_IS_HYPER const int64_t i = Ah [kA] ; #else const int64_t i = kA ; #endif int64_t pA = Ap [kA] ; const int64_t pA_end = Ap [kA+1] ; // TODO skip if ainz is zero, but be careful of iso expansion const int64_t ainz = pA_end - pA ; //-------------------------------------------------------------- // C(i,:) = A(:,i)'*B //-------------------------------------------------------------- for (int64_t j = 0 ; j < bvdim ; j++) { // get B(:,j) and C(:,j) const int64_t pC_start = j * cvlen ; const int64_t pB = j * vlen ; //---------------------------------------------------------- // get C(i,j) //---------------------------------------------------------- const int64_t pC = i + pC_start ; // C(i,j) is at Cx [pC] GB_CTYPE GB_GET4C (cij, pC) ; // cij = Cx [pC] //---------------------------------------------------------- // C(i,j) += A (:,i)*B(:,j): a single dot product //---------------------------------------------------------- #if ( GB_B_IS_FULL ) { //------------------------------------------------------ // A is sparse/hyper and B is full //------------------------------------------------------ #if GB_IS_PAIR_MULTIPLIER { #if GB_IS_EQ_MONOID // EQ_PAIR semiring cij = (cij == 1) ; #elif (GB_CTYPE_BITS > 0) // PLUS, XOR monoids: A(:,i)'*B(:,j) is nnz(A(:,i)), // for bool, 8-bit, 16-bit, or 32-bit integer uint64_t t = ((uint64_t) cij) + ainz ; cij = (GB_CTYPE) (t & GB_CTYPE_BITS) ; #elif GB_IS_PLUS_FC32_MONOID // PLUS monoid for float complex cij = GxB_CMPLXF (crealf (cij) + (float) ainz, 0) ; #elif GB_IS_PLUS_FC64_MONOID // PLUS monoid for double complex cij = GxB_CMPLX (creal (cij) + (double) ainz, 0) ; #else // PLUS monoid for float, double, or 64-bit integers cij += (GB_CTYPE) ainz ; #endif } #elif GB_IS_MIN_FIRSTJ_SEMIRING { // MIN_FIRSTJ semiring: take the 1st entry in A(:,i) if (ainz > 0) { int64_t k = Ai [pA] + GB_OFFSET ; cij = GB_IMIN (cij, k) ; } } #elif GB_IS_MAX_FIRSTJ_SEMIRING { // MAX_FIRSTJ semiring: take last entry in A(:,i) if (ainz > 0) { int64_t k = Ai [pA_end-1] + GB_OFFSET ; cij = GB_IMAX (cij, k) ; } } #else { GB_PRAGMA_SIMD_DOT (cij) for (int64_t p = pA ; p < pA_end ; p++) { int64_t k = Ai [p] ; GB_DOT (k, p, pB+k) ; // cij += A(k,i)*B(k,j) } } #endif } #else { //------------------------------------------------------ // A is sparse/hyper and B is bitmap //------------------------------------------------------ #if GB_IS_MIN_FIRSTJ_SEMIRING { // MIN_FIRSTJ semiring: take the first entry for (int64_t p = pA ; p < pA_end ; p++) { int64_t k = Ai [p] ; if (Bb [pB+k]) { cij = GB_IMIN (cij, k + GB_OFFSET) ; break ; } } } #elif GB_IS_MAX_FIRSTJ_SEMIRING { // MAX_FIRSTJ semiring: take the last entry for (int64_t p = pA_end-1 ; p >= pA ; p--) { int64_t k = Ai [p] ; if (Bb [pB+k]) { cij = GB_IMAX (cij, k + GB_OFFSET) ; break ; } } } #else { GB_PRAGMA_SIMD_DOT (cij) for (int64_t p = pA ; p < pA_end ; p++) { int64_t k = Ai [p] ; if (Bb [pB+k]) { GB_DOT (k, p, pB+k) ; // cij+=A(k,i)*B(k,j) } } } #endif } #endif //---------------------------------------------------------- // save C(i,j) //---------------------------------------------------------- Cx [pC] = cij ; } } } } #if GB_UNROLL else { //---------------------------------------------------------------------- // C += A'*B: with workspace W for transposing B, one panel at a time //---------------------------------------------------------------------- size_t W_size = 0 ; GB_BTYPE *restrict W = NULL ; if (bvdim > 1) { W = GB_MALLOC_WORK (wp * vlen, GB_BTYPE, &W_size) ; if (W == NULL) { // out of memory return (GrB_OUT_OF_MEMORY) ; } } for (int64_t j1 = 0 ; j1 < bvdim ; j1 += 4) { //------------------------------------------------------------------ // C(:,j1:j2-1) += A * B (:,j1:j2-1) for a single panel //------------------------------------------------------------------ const int64_t j2 = GB_IMIN (j1 + 4, bvdim) ; switch (j2 - j1) { default : case 1 : { //---------------------------------------------------------- // C(:,j1:j2-1) is a single vector; use B(:,j1) in place //---------------------------------------------------------- const GB_BTYPE *restrict G = Bx + j1 * vlen ; int tid ; #pragma omp parallel for num_threads(nthreads) \ schedule(dynamic,1) for (tid = 0 ; tid < ntasks ; tid++) { // get the task descriptor const int64_t kA_start = A_slice [tid] ; const int64_t kA_end = A_slice [tid+1] ; for (int64_t i = kA_start ; i < kA_end ; i++) { // get A(:,i) const int64_t pA = Ap [i] ; const int64_t pA_end = Ap [i+1] ; // cx [0] = C(i,j1) GB_CTYPE cx [1] ; GB_GET4C (cx [0], i + j1*cvlen) ; // cx [0] += A (:,i)'*G for (int64_t p = pA ; p < pA_end ; p++) { // aki = A(k,i) const int64_t k = Ai [p] ; GB_GETA (aki, Ax, p, A_iso) ; // cx [0] += A(k,i)*G(k,0) GB_MULTADD (cx [0], aki, G [k], i, k, j1) ; } // C(i,j1) = cx [0] Cx [i + j1*cvlen] = cx [0] ; } } } break ; case 2 : { //---------------------------------------------------------- // G = B(:,j1:j1+1) and convert to row-form //---------------------------------------------------------- GB_BTYPE *restrict G = W ; int64_t k ; #pragma omp parallel for num_threads(nthreads) \ schedule(static) for (k = 0 ; k < vlen ; k++) { // G (k,0:1) = B (k,j1:j1+1) const int64_t k2 = k << 1 ; G [k2 ] = Bx [k + (j1 ) * vlen] ; G [k2 + 1] = Bx [k + (j1 + 1) * vlen] ; } //---------------------------------------------------------- // C += A'*G where G is vlen-by-2 in row-form //---------------------------------------------------------- int tid ; #pragma omp parallel for num_threads(nthreads) \ schedule(dynamic,1) for (tid = 0 ; tid < ntasks ; tid++) { // get the task descriptor const int64_t kA_start = A_slice [tid] ; const int64_t kA_end = A_slice [tid+1] ; for (int64_t i = kA_start ; i < kA_end ; i++) { // get A(:,i) const int64_t pA = Ap [i] ; const int64_t pA_end = Ap [i+1] ; // cx [0:1] = C(i,j1:j1+1) GB_CTYPE cx [2] ; GB_GET4C (cx [0], i + (j1 )*cvlen) ; GB_GET4C (cx [1], i + (j1+1)*cvlen) ; // cx [0:1] += A (:,i)'*G for (int64_t p = pA ; p < pA_end ; p++) { // aki = A(k,i) const int64_t k = Ai [p] ; GB_GETA (aki, Ax, p, A_iso) ; const int64_t k2 = k << 1 ; // cx [0:1] += A(k,i)*G(k,0:1) GB_MULTADD (cx [0], aki, G [k2], i, k, j1) ; GB_MULTADD (cx [1], aki, G [k2+1], i, k, j1+1) ; } // C(i,j1:j1+1) = cx [0:1] Cx [i + (j1 )*cvlen] = cx [0] ; Cx [i + (j1+1)*cvlen] = cx [1] ; } } } break ; case 3 : { //---------------------------------------------------------- // G = B(:,j1:j1+2) and convert to row-form //---------------------------------------------------------- GB_BTYPE *restrict G = W ; int64_t k ; #pragma omp parallel for num_threads(nthreads) \ schedule(static) for (k = 0 ; k < vlen ; k++) { // G (k,0:2) = B (k,j1:j1+2) const int64_t k3 = k * 3 ; G [k3 ] = Bx [k + (j1 ) * vlen] ; G [k3 + 1] = Bx [k + (j1 + 1) * vlen] ; G [k3 + 2] = Bx [k + (j1 + 2) * vlen] ; } //---------------------------------------------------------- // C += A'*G where G is vlen-by-3 in row-form //---------------------------------------------------------- int tid ; #pragma omp parallel for num_threads(nthreads) \ schedule(dynamic,1) for (tid = 0 ; tid < ntasks ; tid++) { // get the task descriptor const int64_t kA_start = A_slice [tid] ; const int64_t kA_end = A_slice [tid+1] ; for (int64_t i = kA_start ; i < kA_end ; i++) { // get A(:,i) const int64_t pA = Ap [i] ; const int64_t pA_end = Ap [i+1] ; // cx [0:2] = C(i,j1:j1+2) GB_CTYPE cx [3] ; GB_GET4C (cx [0], i + (j1 )*cvlen) ; GB_GET4C (cx [1], i + (j1+1)*cvlen) ; GB_GET4C (cx [2], i + (j1+2)*cvlen) ; // cx [0:2] += A (:,i)'*G for (int64_t p = pA ; p < pA_end ; p++) { // aki = A(k,i) const int64_t k = Ai [p] ; GB_GETA (aki, Ax, p, A_iso) ; const int64_t k3 = k * 3 ; // cx [0:2] += A(k,i)*G(k,0:2) GB_MULTADD (cx [0], aki, G [k3 ], i, k, j1) ; GB_MULTADD (cx [1], aki, G [k3+1], i, k, j1+1) ; GB_MULTADD (cx [2], aki, G [k3+2], i, k, j1+2) ; } // C(i,j1:j1+2) = cx [0:2] Cx [i + (j1 )*cvlen] = cx [0] ; Cx [i + (j1+1)*cvlen] = cx [1] ; Cx [i + (j1+2)*cvlen] = cx [2] ; } } } break ; case 4 : { //---------------------------------------------------------- // G = B(:,j1:j1+3) and convert to row-form //---------------------------------------------------------- GB_BTYPE *restrict G = W ; int64_t k ; #pragma omp parallel for num_threads(nthreads) \ schedule(static) for (k = 0 ; k < vlen ; k++) { // G (k,0:3) = B (k,j1:j1+3) const int64_t k4 = k << 2 ; G [k4 ] = Bx [k + (j1 ) * vlen] ; G [k4 + 1] = Bx [k + (j1 + 1) * vlen] ; G [k4 + 2] = Bx [k + (j1 + 2) * vlen] ; G [k4 + 3] = Bx [k + (j1 + 3) * vlen] ; } //---------------------------------------------------------- // C += A'*G where G is vlen-by-4 in row-form //---------------------------------------------------------- int tid ; #pragma omp parallel for num_threads(nthreads) \ schedule(dynamic,1) for (tid = 0 ; tid < ntasks ; tid++) { // get the task descriptor const int64_t kA_start = A_slice [tid] ; const int64_t kA_end = A_slice [tid+1] ; for (int64_t i = kA_start ; i < kA_end ; i++) { // get A(:,i) const int64_t pA = Ap [i] ; const int64_t pA_end = Ap [i+1] ; // cx [0:3] = C(i,j1:j1+3) GB_CTYPE cx [4] ; GB_GET4C (cx [0], i + (j1 )*cvlen) ; GB_GET4C (cx [1], i + (j1+1)*cvlen) ; GB_GET4C (cx [2], i + (j1+2)*cvlen) ; GB_GET4C (cx [3], i + (j1+3)*cvlen) ; // cx [0:3] += A (:,i)'*G for (int64_t p = pA ; p < pA_end ; p++) { // aki = A(k,i) const int64_t k = Ai [p] ; GB_GETA (aki, Ax, p, A_iso) ; const int64_t k4 = k << 2 ; // cx [0:3] += A(k,i)*G(k,0:3) GB_MULTADD (cx [0], aki, G [k4 ], i, k, j1) ; GB_MULTADD (cx [1], aki, G [k4+1], i, k, j1+1) ; GB_MULTADD (cx [2], aki, G [k4+2], i, k, j1+2) ; GB_MULTADD (cx [3], aki, G [k4+3], i, k, j1+3) ; } // C(i,j1:j1+3) = cx [0:3] Cx [i + (j1 )*cvlen] = cx [0] ; Cx [i + (j1+1)*cvlen] = cx [1] ; Cx [i + (j1+2)*cvlen] = cx [2] ; Cx [i + (j1+3)*cvlen] = cx [3] ; } } } break ; } } // free workspace GB_FREE_WORK (&W, W_size) ; } #endif } #elif ( (GB_A_IS_BITMAP || GB_A_IS_FULL) && (GB_B_IS_SPARSE || GB_B_IS_HYPER)) { //-------------------------------------------------------------------------- // C += A'*B where A is bitmap/full and B is sparse/hyper //-------------------------------------------------------------------------- // FUTURE: this can be unrolled, like the case above int tid ; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (tid = 0 ; tid < ntasks ; tid++) { //---------------------------------------------------------------------- // get the task descriptor //---------------------------------------------------------------------- const int64_t kB_start = B_slice [tid] ; const int64_t kB_end = B_slice [tid+1] ; // TODO: reverse the order of this for loop and the for-i loop below for (int64_t kB = kB_start ; kB < kB_end ; kB++) { //------------------------------------------------------------------ // get B(:,j) and C(:,j) //------------------------------------------------------------------ #if GB_B_IS_HYPER const int64_t j = Bh [kB] ; #else const int64_t j = kB ; #endif const int64_t pC_start = j * cvlen ; const int64_t pB_start = Bp [kB] ; const int64_t pB_end = Bp [kB+1] ; const int64_t bjnz = pB_end - pB_start ; //------------------------------------------------------------------ // C(:,j) += A'*B(:,j) //------------------------------------------------------------------ for (int64_t i = 0 ; i < avdim ; i++) { //-------------------------------------------------------------- // get A(:,i) //-------------------------------------------------------------- const int64_t pA = i * vlen ; //-------------------------------------------------------------- // get C(i,j) //-------------------------------------------------------------- int64_t pC = i + pC_start ; // C(i,j) is at Cx [pC] GB_CTYPE GB_GET4C (cij, pC) ; // cij = Cx [pC] //-------------------------------------------------------------- // C(i,j) += A (:,i)*B(:,j): a single dot product //-------------------------------------------------------------- int64_t pB = pB_start ; #if ( GB_A_IS_FULL ) { //---------------------------------------------------------- // A is full and B is sparse/hyper //---------------------------------------------------------- #if GB_IS_PAIR_MULTIPLIER { #if GB_IS_EQ_MONOID // EQ_PAIR semiring cij = (cij == 1) ; #elif (GB_CTYPE_BITS > 0) // PLUS, XOR monoids: A(:,i)'*B(:,j) is nnz(A(:,i)), // for bool, 8-bit, 16-bit, or 32-bit integer uint64_t t = ((uint64_t) cij) + bjnz ; cij = (GB_CTYPE) (t & GB_CTYPE_BITS) ; #elif GB_IS_PLUS_FC32_MONOID // PLUS monoid for float complex cij = GxB_CMPLXF (crealf (cij) + (float) bjnz, 0) ; #elif GB_IS_PLUS_FC64_MONOID // PLUS monoid for double complex cij = GxB_CMPLX (creal (cij) + (double) bjnz, 0) ; #else // PLUS monoid for float, double, or 64-bit integers cij += (GB_CTYPE) bjnz ; #endif } #elif GB_IS_MIN_FIRSTJ_SEMIRING { // MIN_FIRSTJ semiring: take the first entry in B(:,j) if (bjnz > 0) { int64_t k = Bi [pB] + GB_OFFSET ; cij = GB_IMIN (cij, k) ; } } #elif GB_IS_MAX_FIRSTJ_SEMIRING { // MAX_FIRSTJ semiring: take the last entry in B(:,j) if (bjnz > 0) { int64_t k = Bi [pB_end-1] + GB_OFFSET ; cij = GB_IMAX (cij, k) ; } } #else { GB_PRAGMA_SIMD_DOT (cij) for (int64_t p = pB ; p < pB_end ; p++) { int64_t k = Bi [p] ; GB_DOT (k, pA+k, p) ; // cij += A(k,i)*B(k,j) } } #endif } #else { //---------------------------------------------------------- // A is bitmap and B is sparse/hyper //---------------------------------------------------------- #if GB_IS_MIN_FIRSTJ_SEMIRING { // MIN_FIRSTJ semiring: take the first entry for (int64_t p = pB ; p < pB_end ; p++) { int64_t k = Bi [p] ; if (Ab [pA+k]) { cij = GB_IMIN (cij, k + GB_OFFSET) ; break ; } } } #elif GB_IS_MAX_FIRSTJ_SEMIRING { // MAX_FIRSTJ semiring: take the last entry for (int64_t p = pB_end-1 ; p >= pB ; p--) { int64_t k = Bi [p] ; if (Ab [pA+k]) { cij = GB_IMAX (cij, k + GB_OFFSET) ; break ; } } } #else { GB_PRAGMA_SIMD_DOT (cij) for (int64_t p = pB ; p < pB_end ; p++) { int64_t k = Bi [p] ; if (Ab [pA+k]) { GB_DOT (k, pA+k, p) ; // cij += A(k,i)*B(k,j) } } } #endif } #endif //-------------------------------------------------------------- // save C(i,j) //-------------------------------------------------------------- Cx [pC] = cij ; } } } } #elif ( (GB_A_IS_SPARSE || GB_A_IS_HYPER) && (GB_B_IS_SPARSE || GB_B_IS_HYPER)) { //-------------------------------------------------------------------------- // C+=A'*B where A and B are both sparse/hyper //-------------------------------------------------------------------------- int tid ; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (tid = 0 ; tid < ntasks ; tid++) { //---------------------------------------------------------------------- // get the task descriptor //---------------------------------------------------------------------- const int a_tid = tid / nbslice ; const int b_tid = tid % nbslice ; const int64_t kA_start = A_slice [a_tid] ; const int64_t kA_end = A_slice [a_tid+1] ; const int64_t kB_start = B_slice [b_tid] ; const int64_t kB_end = B_slice [b_tid+1] ; //---------------------------------------------------------------------- // C+=A'*B via dot products //---------------------------------------------------------------------- for (int64_t kB = kB_start ; kB < kB_end ; kB++) { //------------------------------------------------------------------ // get B(:,j) and C(:,j) //------------------------------------------------------------------ #if GB_B_IS_HYPER const int64_t j = Bh [kB] ; #else const int64_t j = kB ; #endif const int64_t pC_start = j * cvlen ; const int64_t pB_start = Bp [kB] ; const int64_t pB_end = Bp [kB+1] ; const int64_t bjnz = pB_end - pB_start ; //------------------------------------------------------------------ // C(:,j) += A'*B(:,j) where C is full //------------------------------------------------------------------ for (int64_t kA = kA_start ; kA < kA_end ; kA++) { //-------------------------------------------------------------- // get A(:,i) //-------------------------------------------------------------- #if GB_A_IS_HYPER const int64_t i = Ah [kA] ; #else const int64_t i = kA ; #endif int64_t pA = Ap [kA] ; const int64_t pA_end = Ap [kA+1] ; const int64_t ainz = pA_end - pA ; //-------------------------------------------------------------- // get C(i,j) //-------------------------------------------------------------- int64_t pC = i + pC_start ; // C(i,j) is at Cx [pC] GB_CTYPE GB_GET4C (cij, pC) ; // cij = Cx [pC] //-------------------------------------------------------------- // C(i,j) += A (:,i)*B(:,j): a single dot product //-------------------------------------------------------------- int64_t pB = pB_start ; //---------------------------------------------------------- // both A and B are sparse/hyper //---------------------------------------------------------- // The MIN_FIRSTJ semirings are exploited, by terminating as // soon as any entry is found. The MAX_FIRSTJ semirings are // not treated specially here. They could be done with a // backwards traversal of the sparse vectors A(:,i) and // B(:,j). if (ainz == 0 || bjnz == 0 || Ai [pA_end-1] < Bi [pB_start] || Bi [pB_end-1] < Ai [pA]) { //------------------------------------------------------ // A(:,i) and B(:,j) don't overlap, or are empty //------------------------------------------------------ } else if (ainz > 8 * bjnz) { //------------------------------------------------------ // B(:,j) is very sparse compared to A(:,i) //------------------------------------------------------ while (pA < pA_end && pB < pB_end) { int64_t ia = Ai [pA] ; int64_t ib = Bi [pB] ; if (ia < ib) { // A(ia,i) appears before B(ib,j) // discard all entries A(ia:ib-1,i) int64_t pleft = pA + 1 ; int64_t pright = pA_end - 1 ; GB_TRIM_BINARY_SEARCH (ib, Ai, pleft, pright) ; ASSERT (pleft > pA) ; pA = pleft ; } else if (ib < ia) { // B(ib,j) appears before A(ia,i) pB++ ; } else // ia == ib == k { // A(k,i) and B(k,j) are next entries to merge GB_DOT (ia, pA, pB) ; // cij += A(k,i)*B(k,j) #if GB_IS_MIN_FIRSTJ_SEMIRING break ; #endif pA++ ; pB++ ; } } } else if (bjnz > 8 * ainz) { //------------------------------------------------------ // A(:,i) is very sparse compared to B(:,j) //------------------------------------------------------ while (pA < pA_end && pB < pB_end) { int64_t ia = Ai [pA] ; int64_t ib = Bi [pB] ; if (ia < ib) { // A(ia,i) appears before B(ib,j) pA++ ; } else if (ib < ia) { // B(ib,j) appears before A(ia,i) // discard all entries B(ib:ia-1,j) int64_t pleft = pB + 1 ; int64_t pright = pB_end - 1 ; GB_TRIM_BINARY_SEARCH (ia, Bi, pleft, pright) ; ASSERT (pleft > pB) ; pB = pleft ; } else // ia == ib == k { // A(k,i) and B(k,j) are next entries to merge GB_DOT (ia, pA, pB) ; // cij += A(k,i)*B(k,j) #if GB_IS_MIN_FIRSTJ_SEMIRING break ; #endif pA++ ; pB++ ; } } } else { //------------------------------------------------------ // A(:,i) and B(:,j) have about the same sparsity //------------------------------------------------------ while (pA < pA_end && pB < pB_end) { int64_t ia = Ai [pA] ; int64_t ib = Bi [pB] ; if (ia < ib) { // A(ia,i) appears before B(ib,j) pA++ ; } else if (ib < ia) { // B(ib,j) appears before A(ia,i) pB++ ; } else // ia == ib == k { // A(k,i) and B(k,j) are the entries to merge GB_DOT (ia, pA, pB) ; // cij += A(k,i)*B(k,j) #if GB_IS_MIN_FIRSTJ_SEMIRING break ; #endif pA++ ; pB++ ; } } } //-------------------------------------------------------------- // save C(i,j) //-------------------------------------------------------------- Cx [pC] = cij ; } } } } #endif #undef GB_IS_MIN_FIRSTJ_SEMIRING #undef GB_IS_MAX_FIRSTJ_SEMIRING #undef GB_GET4C #undef GB_SPECIAL_CASE_OR_TERMINAL #undef GB_UNROLL
3d7pt_var.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-1, 3D 7 point stencil with variable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*7); for(m=0; m<7;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 4; tile_size[1] = 4; tile_size[2] = 4; tile_size[3] = 32; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<7; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 2) && (Nx >= 3) && (Ny >= 3) && (Nz >= 3)) { for (t1=-1;t1<=floord(Nt-2,2);t1++) { lbp=max(ceild(t1,2),ceild(4*t1-Nt+3,4)); ubp=min(floord(Nt+Nz-4,4),floord(2*t1+Nz-1,4)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(0,ceild(t1-1,2)),ceild(4*t2-Nz,4));t3<=min(min(min(floord(4*t2+Ny,4),floord(Nt+Ny-4,4)),floord(2*t1+Ny+1,4)),floord(4*t1-4*t2+Nz+Ny-1,4));t3++) { for (t4=max(max(max(0,ceild(t1-15,16)),ceild(4*t2-Nz-28,32)),ceild(4*t3-Ny-28,32));t4<=min(min(min(min(floord(4*t2+Nx,32),floord(4*t3+Nx,32)),floord(Nt+Nx-4,32)),floord(2*t1+Nx+1,32)),floord(4*t1-4*t2+Nz+Nx-1,32));t4++) { for (t5=max(max(max(max(max(0,2*t1),4*t1-4*t2+1),4*t2-Nz+2),4*t3-Ny+2),32*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,2*t1+3),4*t2+2),4*t3+2),32*t4+30),4*t1-4*t2+Nz+1);t5++) { for (t6=max(max(4*t2,t5+1),-4*t1+4*t2+2*t5-3);t6<=min(min(4*t2+3,-4*t1+4*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(32*t4,t5+1); ubv=min(32*t4+31,t5+Nx-2); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = (((((((coef[0][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)]) + (coef[1][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6) - 1][ (-t5+t7)][ (-t5+t8)])) + (coef[2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7) - 1][ (-t5+t8)])) + (coef[3][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) - 1])) + (coef[4][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6) + 1][ (-t5+t7)][ (-t5+t8)])) + (coef[5][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7) + 1][ (-t5+t8)])) + (coef[6][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) + 1]));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "variable no-symmetry") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<7;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
3d25pt_var.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-1, 3D 25 point stencil with axis-symmetric ariable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*13); for(m=0; m<13;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 16; tile_size[1] = 16; tile_size[2] = 24; tile_size[3] = 1024; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<13; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) { for (t1=-1;t1<=floord(Nt-1,2);t1++) { lbp=max(ceild(t1,2),ceild(4*t1-Nt+2,4)); ubp=min(floord(4*Nt+Nz-9,16),floord(8*t1+Nz+2,16)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(max(0,ceild(t1-2,3)),ceild(2*t1-2*t2-1,3)),ceild(16*t2-Nz-11,24));t3<=min(min(min(floord(4*Nt+Ny-9,24),floord(8*t1+Ny+7,24)),floord(16*t2+Ny+3,24)),floord(16*t1-16*t2+Nz+Ny+5,24));t3++) { for (t4=max(max(max(0,ceild(t1-127,128)),ceild(16*t2-Nz-1011,1024)),ceild(24*t3-Ny-1011,1024));t4<=min(min(min(min(floord(4*Nt+Nx-9,1024),floord(8*t1+Nx+7,1024)),floord(16*t2+Nx+3,1024)),floord(24*t3+Nx+11,1024)),floord(16*t1-16*t2+Nz+Nx+5,1024));t4++) { for (t5=max(max(max(max(max(0,ceild(16*t2-Nz+5,4)),ceild(24*t3-Ny+5,4)),ceild(1024*t4-Nx+5,4)),2*t1),4*t1-4*t2+1);t5<=min(min(min(min(min(floord(16*t1-16*t2+Nz+10,4),Nt-1),2*t1+3),4*t2+2),6*t3+4),256*t4+254);t5++) { for (t6=max(max(16*t2,4*t5+4),-16*t1+16*t2+8*t5-15);t6<=min(min(16*t2+15,-16*t1+16*t2+8*t5),4*t5+Nz-5);t6++) { for (t7=max(24*t3,4*t5+4);t7<=min(24*t3+23,4*t5+Ny-5);t7++) { lbv=max(1024*t4,4*t5+4); ubv=min(1024*t4+1023,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)] = (((((((((((((coef[0][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef[1][ (-4*t5+t6)][ (-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) + 1][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[2][ (-4*t5+t6)][ (-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)]))) + (coef[3][ (-4*t5+t6)][ (-4*t5+t7)][ (-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]))) + (coef[4][ (-4*t5+t6)][ (-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) + 2][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[5][ (-4*t5+t6)][ (-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)]))) + (coef[6][ (-4*t5+t6)][ (-4*t5+t7)][ (-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]))) + (coef[7][ (-4*t5+t6)][ (-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) + 3][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[8][ (-4*t5+t6)][ (-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)]))) + (coef[9][ (-4*t5+t6)][ (-4*t5+t7)][ (-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]))) + (coef[10][ (-4*t5+t6)][ (-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][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[11][ (-4*t5+t6)][ (-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)]))) + (coef[12][ (-4*t5+t6)][ (-4*t5+t7)][ (-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, "variable axis-symmetric") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<13;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
omp_nested.c
<ompts:test> <ompts:testdescription>Test which checks the omp_nested function.</ompts:testdescription> <ompts:ompversion>2.0</ompts:ompversion> <ompts:directive>omp_nested</ompts:directive> <ompts:dependences>omp critical</ompts:dependences> <ompts:testcode> /* * Test if the compiler supports nested parallelism * By Chunhua Liao, University of Houston * Oct. 2005 */ #include <stdio.h> #include "omp_testsuite.h" int <ompts:testcode:functionname>omp_nested</ompts:testcode:functionname>(FILE * logFile) { <ompts:orphan:vars> int counter = 0; </ompts:orphan:vars> #ifdef _OPENMP <ompts:check>omp_set_nested(1);</ompts:check> <ompts:crosscheck>omp_set_nested(0);</ompts:crosscheck> #endif #pragma omp parallel shared(counter) { <ompts:orphan> #pragma omp critical counter ++; #pragma omp parallel { #pragma omp critical counter --; } </ompts:orphan> } return (counter != 0); } </ompts:testcode> </ompts:test>
openmp.c
/* This file is part of CMake-easytest. * * Copyright (c) 2017 RWTH Aachen University, Federal Republic of Germany * * See the LICENSE file in the package base directory for details * * Written by Alexander Haase, alexander.haase@rwth-aachen.de */ #include <stdio.h> #include <omp.h> int main() { #pragma omp parallel { printf("%d of %d\n", omp_get_thread_num() + 1, omp_get_num_threads()); } return 0; } /* CMake-easytest configuration. * * CONFIGS: sort env * * COMPILE_FLAGS: @OpenMP_C_FLAGS@ * LINK: @OpenMP_C_FLAGS@ * * * ENVIRONMENT-sort: OMP_NUM_THREADS=4 * RUN-sort: @BINARY@ | @sort@ * PASS-sort: 1.*2.*3.*4 * * ENVIRONMENT-env: OMP_NUM_THREADS=1 * FAIL-env: 2 */
GB_unop__identity_int8_uint32.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_int8_uint32) // op(A') function: GB (_unop_tran__identity_int8_uint32) // C type: int8_t // A type: uint32_t // cast: int8_t cij = (int8_t) aij // unaryop: cij = aij #define GB_ATYPE \ uint32_t #define GB_CTYPE \ int8_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_CAST(z, aij) \ int8_t z = (int8_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int8_t z = (int8_t) aij ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT8 || GxB_NO_UINT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_int8_uint32) ( int8_t *Cx, // Cx and Ax may be aliased const uint32_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++) { uint32_t aij = Ax [p] ; int8_t z = (int8_t) 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 ; uint32_t aij = Ax [p] ; int8_t z = (int8_t) 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_int8_uint32) ( 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
bt.c
/*-------------------------------------------------------------------- NAS Parallel Benchmarks 3.0 structured OpenMP C versions - BT This benchmark is an OpenMP C version of the NPB BT 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: R. Van der Wijngaart T. Harris M. Yarrow OpenMP C version: S. Satoh 3.0 structure translation: M. Popov --------------------------------------------------------------------*/ #include "../common/npb-C.h" /* global variables */ #include "header.h" /* function declarations */ static void add(void); static void adi(void); static void error_norm(double rms[5]); static void rhs_norm(double rms[5]); static void exact_rhs(void); static void exact_solution(double xi, double eta, double zeta, double dtemp[5]); static void initialize(void); static void lhsinit(void); static void lhsx(void); static void lhsy(void); static void lhsz(void); static void compute_rhs(void); static void set_constants(void); static void verify(int no_time_steps, char *class, boolean *verified); static void x_solve(void); static void x_backsubstitute(void); static void x_solve_cell(void); static void matvec_sub(double ablock[5][5], double avec[5], double bvec[5]); static void matmul_sub(double ablock[5][5], double bblock[5][5], double cblock[5][5]); static void binvcrhs(double lhs[5][5], double c[5][5], double r[5]); static void binvrhs(double lhs[5][5], double r[5]); static void y_solve(void); static void y_backsubstitute(void); static void y_solve_cell(void); static void z_solve(void); static void z_backsubstitute(void); static void z_solve_cell(void); /*-------------------------------------------------------------------- program BT c-------------------------------------------------------------------*/ int main(int argc, char **argv) { int niter, step, n3; int nthreads = 1; double navg, mflops; double tmax; boolean verified; char class; FILE *fp; /*-------------------------------------------------------------------- c Root node reads input file (if it exists) else takes c defaults from parameters c-------------------------------------------------------------------*/ printf("\n\n NAS Parallel Benchmarks 3.0 structured OpenMP C version" " - BT Benchmark\n\n"); fp = fopen("inputbt.data", "r"); if (fp != NULL) { printf(" Reading from input file inputbt.data"); fscanf(fp, "%d", &niter); while (fgetc(fp) != '\n'); fscanf(fp, "%lg", &dt); while (fgetc(fp) != '\n'); fscanf(fp, "%d%d%d", &grid_points[0], &grid_points[1], &grid_points[2]); fclose(fp); } else { printf(" No input file inputbt.data. Using compiled defaults\n"); niter = NITER_DEFAULT; dt = DT_DEFAULT; grid_points[0] = PROBLEM_SIZE; grid_points[1] = PROBLEM_SIZE; grid_points[2] = PROBLEM_SIZE; } printf(" Size: %3dx%3dx%3d\n", grid_points[0], grid_points[1], grid_points[2]); printf(" Iterations: %3d dt: %10.6f\n", niter, dt); if (grid_points[0] > IMAX || grid_points[1] > JMAX || grid_points[2] > KMAX) { printf(" %dx%dx%d\n", grid_points[0], grid_points[1], grid_points[2]); printf(" Problem size too big for compiled array sizes\n"); exit(1); } set_constants(); initialize(); lhsinit(); exact_rhs(); /*-------------------------------------------------------------------- c do one time step to touch all code, and reinitialize c-------------------------------------------------------------------*/ adi(); initialize(); timer_clear(1); timer_start(1); for (step = 1; step <= niter; step++) { if (step%20 == 0 || step == 1) { printf(" Time step %4d\n", step); } adi(); } { #if defined(_OPENMP) nthreads = omp_get_num_threads(); #endif /* _OPENMP */ } /* end parallel */ timer_stop(1); tmax = timer_read(1); verify(niter, &class, &verified); n3 = grid_points[0]*grid_points[1]*grid_points[2]; navg = (grid_points[0]+grid_points[1]+grid_points[2])/3.0; if ( tmax != 0.0 ) { mflops = 1.0e-6*(double)niter* (3478.8*(double)n3-17655.7*pow2(navg)+28023.7*navg) / tmax; } else { mflops = 0.0; } c_print_results("BT", class, grid_points[0], grid_points[1], grid_points[2], niter, nthreads, tmax, mflops, " floating point", verified, NPBVERSION,COMPILETIME, CS1, CS2, CS3, CS4, CS5, CS6, "(none)"); } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void add(void) { /*-------------------------------------------------------------------- c addition of update to the vector u c-------------------------------------------------------------------*/ int i, j, k, m; #pragma omp parallel for private(j ,k ,m ,i ) for (i = 1; i < grid_points[0]-1; i++) { #pragma omp parallel for private(j ,k ,m ,i ) for (j = 1; j < grid_points[1]-1; j++) { #pragma omp parallel for private(j ,k ,m ,i ) for (k = 1; k < grid_points[2]-1; k++) { #pragma omp parallel for private(j ,k ,m ,i ) for (m = 0; m < 5; m++) { u[i][j][k][m] = u[i][j][k][m] + rhs[i][j][k][m]; } } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void adi(void) { compute_rhs(); x_solve(); y_solve(); z_solve(); add(); } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void error_norm(double rms[5]) { /*-------------------------------------------------------------------- c this function computes the norm of the difference between the c computed solution and the exact solution c-------------------------------------------------------------------*/ int i, j, k, m, d; double xi, eta, zeta, u_exact[5], add; #pragma omp parallel for private(m ) for (m = 0; m < 5; m++) { rms[m] = 0.0; } for (i = 0; i < grid_points[0]; i++) { xi = (double)i * dnxm1; for (j = 0; j < grid_points[1]; j++) { eta = (double)j * dnym1; for (k = 0; k < grid_points[2]; k++) { zeta = (double)k * dnzm1; exact_solution(xi, eta, zeta, u_exact); #pragma omp parallel for private(add ,m) firstprivate(k ,j ,i ) for (m = 0; m < 5; m++) { add = u[i][j][k][m] - u_exact[m]; rms[m] = rms[m] + add*add; } } } } #pragma omp parallel for private(d ,m ) for (m = 0; m < 5; m++) { #pragma omp parallel for firstprivate(m ) for (d = 0; d <= 2; d++) { rms[m] = rms[m] / (double)(grid_points[d]-2); } rms[m] = sqrt(rms[m]); } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void rhs_norm(double rms[5]) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ int i, j, k, d, m; double add; #pragma omp parallel for private(m ) for (m = 0; m < 5; m++) { rms[m] = 0.0; } for (i = 1; i < grid_points[0]-1; i++) { for (j = 1; j < grid_points[1]-1; j++) { for (k = 1; k < grid_points[2]-1; k++) { #pragma omp parallel for private(add, m) firstprivate(k ,j ,i ) for (m = 0; m < 5; m++) { add = rhs[i][j][k][m]; rms[m] = rms[m] + add*add; } } } } #pragma omp parallel for private(d ,m ) for (m = 0; m < 5; m++) { #pragma omp parallel for firstprivate(m ) for (d = 0; d <= 2; d++) { rms[m] = rms[m] / (double)(grid_points[d]-2); } rms[m] = sqrt(rms[m]); } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void exact_rhs(void) { { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c compute the right hand side based on exact solution c-------------------------------------------------------------------*/ double dtemp[5], xi, eta, zeta, dtpp; int m, i, j, k, ip1, im1, jp1, jm1, km1, kp1; /*-------------------------------------------------------------------- c initialize c-------------------------------------------------------------------*/ #pragma omp parallel for private(j ,k ,m ,i ) for (i = 0; i < grid_points[0]; i++) { #pragma omp parallel for private(j, k, m) firstprivate(i ) for (j = 0; j < grid_points[1]; j++) { #pragma omp parallel for private(k, m) firstprivate(j ,i ) for (k = 0; k < grid_points[2]; k++) { #pragma omp parallel for private(j, k, i) firstprivate(m ) for (m = 0; m < 5; m++) { forcing[i][j][k][m] = 0.0; } } } } /*-------------------------------------------------------------------- c xi-direction flux differences c-------------------------------------------------------------------*/ #pragma omp parallel for private(m, i, k, j) for (j = 1; j < grid_points[1]-1; j++) { eta = (double)j * dnym1; for (k = 1; k < grid_points[2]-1; k++) { zeta = (double)k * dnzm1; for (i = 0; i < grid_points[0]; i++) { xi = (double)i * dnxm1; exact_solution(xi, eta, zeta, dtemp); #pragma omp parallel for firstprivate(i ,k ,j ) private(m) for (m = 0; m < 5; m++) { ue[i][m] = dtemp[m]; } dtpp = 1.0 / dtemp[0]; #pragma omp parallel for firstprivate(dtpp ,i ,k ,j ) private(m) for (m = 1; m <= 4; m++) { buf[i][m] = dtpp * dtemp[m]; } cuf[i] = buf[i][1] * buf[i][1]; buf[i][0] = cuf[i] + buf[i][2] * buf[i][2] + buf[i][3] * buf[i][3]; q[i] = 0.5*(buf[i][1]*ue[i][1] + buf[i][2]*ue[i][2] + buf[i][3]*ue[i][3]); } #pragma omp parallel for private(i) firstprivate(dx1tx1 ,tx2 ,dx2tx1 ,xxcon1 ,c2 ,dx3tx1 ,xxcon2 ,dx4tx1 ,dx5tx1 ,xxcon5 ,xxcon4 ,xxcon3 ,c1 ,k ,j ) for (i = 1; i < grid_points[0]-1; i++) { im1 = i-1; ip1 = i+1; forcing[i][j][k][0] = forcing[i][j][k][0] - tx2*(ue[ip1][1]-ue[im1][1])+ dx1tx1*(ue[ip1][0]-2.0*ue[i][0]+ue[im1][0]); forcing[i][j][k][1] = forcing[i][j][k][1] - tx2 * ((ue[ip1][1]*buf[ip1][1]+c2*(ue[ip1][4]-q[ip1]))- (ue[im1][1]*buf[im1][1]+c2*(ue[im1][4]-q[im1])))+ xxcon1*(buf[ip1][1]-2.0*buf[i][1]+buf[im1][1])+ dx2tx1*( ue[ip1][1]-2.0* ue[i][1]+ ue[im1][1]); forcing[i][j][k][2] = forcing[i][j][k][2] - tx2 * (ue[ip1][2]*buf[ip1][1]-ue[im1][2]*buf[im1][1])+ xxcon2*(buf[ip1][2]-2.0*buf[i][2]+buf[im1][2])+ dx3tx1*( ue[ip1][2]-2.0* ue[i][2]+ ue[im1][2]); forcing[i][j][k][3] = forcing[i][j][k][3] - tx2*(ue[ip1][3]*buf[ip1][1]-ue[im1][3]*buf[im1][1])+ xxcon2*(buf[ip1][3]-2.0*buf[i][3]+buf[im1][3])+ dx4tx1*( ue[ip1][3]-2.0* ue[i][3]+ ue[im1][3]); forcing[i][j][k][4] = forcing[i][j][k][4] - tx2*(buf[ip1][1]*(c1*ue[ip1][4]-c2*q[ip1])- buf[im1][1]*(c1*ue[im1][4]-c2*q[im1]))+ 0.5*xxcon3*(buf[ip1][0]-2.0*buf[i][0]+buf[im1][0])+ xxcon4*(cuf[ip1]-2.0*cuf[i]+cuf[im1])+ xxcon5*(buf[ip1][4]-2.0*buf[i][4]+buf[im1][4])+ dx5tx1*( ue[ip1][4]-2.0* ue[i][4]+ ue[im1][4]); } /*-------------------------------------------------------------------- c Fourth-order dissipation c-------------------------------------------------------------------*/ #pragma omp parallel for private(m) firstprivate(dssp ,k ,j ) for (m = 0; m < 5; m++) { i = 1; forcing[i][j][k][m] = forcing[i][j][k][m] - dssp * (5.0*ue[i][m] - 4.0*ue[i+1][m] +ue[i+2][m]); i = 2; forcing[i][j][k][m] = forcing[i][j][k][m] - dssp * (-4.0*ue[i-1][m] + 6.0*ue[i][m] - 4.0*ue[i+1][m] + ue[i+2][m]); } #pragma omp parallel for private(m) firstprivate(dssp ,k ,j ) for (m = 0; m < 5; m++) { #pragma omp parallel for private(i) firstprivate(dssp ,m ,k ,j ) for (i = 1*3; i <= grid_points[0]-3*1-1; i++) { forcing[i][j][k][m] = forcing[i][j][k][m] - dssp* (ue[i-2][m] - 4.0*ue[i-1][m] + 6.0*ue[i][m] - 4.0*ue[i+1][m] + ue[i+2][m]); } } #pragma omp parallel for private(m, i) firstprivate(dssp ,k ,j ) for (m = 0; m < 5; m++) { i = grid_points[0]-3; forcing[i][j][k][m] = forcing[i][j][k][m] - dssp * (ue[i-2][m] - 4.0*ue[i-1][m] + 6.0*ue[i][m] - 4.0*ue[i+1][m]); i = grid_points[0]-2; forcing[i][j][k][m] = forcing[i][j][k][m] - dssp * (ue[i-2][m] - 4.0*ue[i-1][m] + 5.0*ue[i][m]); } } } /*-------------------------------------------------------------------- c eta-direction flux differences c-------------------------------------------------------------------*/ #pragma omp parallel for private(m, j, k, i) for (i = 1; i < grid_points[0]-1; i++) { xi = (double)i * dnxm1; for (k = 1; k < grid_points[2]-1; k++) { zeta = (double)k * dnzm1; for (j = 0; j < grid_points[1]; j++) { eta = (double)j * dnym1; exact_solution(xi, eta, zeta, dtemp); #pragma omp parallel for private(i, k, j) firstprivate(m) for (m = 0; m < 5; m++) { ue[j][m] = dtemp[m]; } dtpp = 1.0/dtemp[0]; #pragma omp parallel for private(m) firstprivate(dtpp ,j ,k ,i ) for (m = 1; m <= 4; m++) { buf[j][m] = dtpp * dtemp[m]; } cuf[j] = buf[j][2] * buf[j][2]; buf[j][0] = cuf[j] + buf[j][1] * buf[j][1] + buf[j][3] * buf[j][3]; q[j] = 0.5*(buf[j][1]*ue[j][1] + buf[j][2]*ue[j][2] + buf[j][3]*ue[j][3]); } #pragma omp parallel for private(j) firstprivate(dy1ty1 ,ty2 ,dy2ty1 ,yycon2 ,dy3ty1 ,yycon1 ,c2 ,dy4ty1 ,dy5ty1 ,yycon5 ,yycon4 ,yycon3 ,c1 ,k ,i ) for (j = 1; j < grid_points[1]-1; j++) { jm1 = j-1; jp1 = j+1; forcing[i][j][k][0] = forcing[i][j][k][0] - ty2*( ue[jp1][2]-ue[jm1][2] )+ dy1ty1*(ue[jp1][0]-2.0*ue[j][0]+ue[jm1][0]); forcing[i][j][k][1] = forcing[i][j][k][1] - ty2*(ue[jp1][1]*buf[jp1][2]-ue[jm1][1]*buf[jm1][2])+ yycon2*(buf[jp1][1]-2.0*buf[j][1]+buf[jm1][1])+ dy2ty1*( ue[jp1][1]-2.0* ue[j][1]+ ue[jm1][1]); forcing[i][j][k][2] = forcing[i][j][k][2] - ty2*((ue[jp1][2]*buf[jp1][2]+c2*(ue[jp1][4]-q[jp1]))- (ue[jm1][2]*buf[jm1][2]+c2*(ue[jm1][4]-q[jm1])))+ yycon1*(buf[jp1][2]-2.0*buf[j][2]+buf[jm1][2])+ dy3ty1*( ue[jp1][2]-2.0*ue[j][2] +ue[jm1][2]); forcing[i][j][k][3] = forcing[i][j][k][3] - ty2*(ue[jp1][3]*buf[jp1][2]-ue[jm1][3]*buf[jm1][2])+ yycon2*(buf[jp1][3]-2.0*buf[j][3]+buf[jm1][3])+ dy4ty1*( ue[jp1][3]-2.0*ue[j][3]+ ue[jm1][3]); forcing[i][j][k][4] = forcing[i][j][k][4] - ty2*(buf[jp1][2]*(c1*ue[jp1][4]-c2*q[jp1])- buf[jm1][2]*(c1*ue[jm1][4]-c2*q[jm1]))+ 0.5*yycon3*(buf[jp1][0]-2.0*buf[j][0]+ buf[jm1][0])+ yycon4*(cuf[jp1]-2.0*cuf[j]+cuf[jm1])+ yycon5*(buf[jp1][4]-2.0*buf[j][4]+buf[jm1][4])+ dy5ty1*(ue[jp1][4]-2.0*ue[j][4]+ue[jm1][4]); } /*-------------------------------------------------------------------- c Fourth-order dissipation c-------------------------------------------------------------------*/ #pragma omp parallel for private(m) firstprivate(dssp ,k ,i ) for (m = 0; m < 5; m++) { j = 1; forcing[i][j][k][m] = forcing[i][j][k][m] - dssp * (5.0*ue[j][m] - 4.0*ue[j+1][m] +ue[j+2][m]); j = 2; forcing[i][j][k][m] = forcing[i][j][k][m] - dssp * (-4.0*ue[j-1][m] + 6.0*ue[j][m] - 4.0*ue[j+1][m] + ue[j+2][m]); } #pragma omp parallel for firstprivate(dssp ,m ,k ,i ) for (m = 0; m < 5; m++) { #pragma omp parallel for firstprivate(j ,dssp ,m ,k ,i ) for (j = 1*3; j <= grid_points[1]-3*1-1; j++) { forcing[i][j][k][m] = forcing[i][j][k][m] - dssp* (ue[j-2][m] - 4.0*ue[j-1][m] + 6.0*ue[j][m] - 4.0*ue[j+1][m] + ue[j+2][m]); } } #pragma omp parallel for firstprivate(dssp ,j ,m ,k ,i ) for (m = 0; m < 5; m++) { j = grid_points[1]-3; forcing[i][j][k][m] = forcing[i][j][k][m] - dssp * (ue[j-2][m] - 4.0*ue[j-1][m] + 6.0*ue[j][m] - 4.0*ue[j+1][m]); j = grid_points[1]-2; forcing[i][j][k][m] = forcing[i][j][k][m] - dssp * (ue[j-2][m] - 4.0*ue[j-1][m] + 5.0*ue[j][m]); } } } /*-------------------------------------------------------------------- c zeta-direction flux differences c-------------------------------------------------------------------*/ #pragma omp parallel for for (i = 1; i < grid_points[0]-1; i++) { xi = (double)i * dnxm1; for (j = 1; j < grid_points[1]-1; j++) { eta = (double)j * dnym1; for (k = 0; k < grid_points[2]; k++) { zeta = (double)k * dnzm1; exact_solution(xi, eta, zeta, dtemp); #pragma omp parallel for firstprivate(m ,k ,j ,i ) for (m = 0; m < 5; m++) { ue[k][m] = dtemp[m]; } dtpp = 1.0/dtemp[0]; #pragma omp parallel for firstprivate(dtpp ,m ,k ,j ,i ) for (m = 1; m <= 4; m++) { buf[k][m] = dtpp * dtemp[m]; } cuf[k] = buf[k][3] * buf[k][3]; buf[k][0] = cuf[k] + buf[k][1] * buf[k][1] + buf[k][2] * buf[k][2]; q[k] = 0.5*(buf[k][1]*ue[k][1] + buf[k][2]*ue[k][2] + buf[k][3]*ue[k][3]); } #pragma omp parallel for firstprivate(dz1tz1 ,tz2 ,dz2tz1 ,zzcon2 ,dz3tz1 ,dz4tz1 ,zzcon1 ,c2 ,dz5tz1 ,zzcon5 ,zzcon4 ,zzcon3 ,c1 ,k ,j ,i ) for (k = 1; k < grid_points[2]-1; k++) { km1 = k-1; kp1 = k+1; forcing[i][j][k][0] = forcing[i][j][k][0] - tz2*( ue[kp1][3]-ue[km1][3] )+ dz1tz1*(ue[kp1][0]-2.0*ue[k][0]+ue[km1][0]); forcing[i][j][k][1] = forcing[i][j][k][1] - tz2 * (ue[kp1][1]*buf[kp1][3]-ue[km1][1]*buf[km1][3])+ zzcon2*(buf[kp1][1]-2.0*buf[k][1]+buf[km1][1])+ dz2tz1*( ue[kp1][1]-2.0* ue[k][1]+ ue[km1][1]); forcing[i][j][k][2] = forcing[i][j][k][2] - tz2 * (ue[kp1][2]*buf[kp1][3]-ue[km1][2]*buf[km1][3])+ zzcon2*(buf[kp1][2]-2.0*buf[k][2]+buf[km1][2])+ dz3tz1*(ue[kp1][2]-2.0*ue[k][2]+ue[km1][2]); forcing[i][j][k][3] = forcing[i][j][k][3] - tz2 * ((ue[kp1][3]*buf[kp1][3]+c2*(ue[kp1][4]-q[kp1]))- (ue[km1][3]*buf[km1][3]+c2*(ue[km1][4]-q[km1])))+ zzcon1*(buf[kp1][3]-2.0*buf[k][3]+buf[km1][3])+ dz4tz1*( ue[kp1][3]-2.0*ue[k][3] +ue[km1][3]); forcing[i][j][k][4] = forcing[i][j][k][4] - tz2 * (buf[kp1][3]*(c1*ue[kp1][4]-c2*q[kp1])- buf[km1][3]*(c1*ue[km1][4]-c2*q[km1]))+ 0.5*zzcon3*(buf[kp1][0]-2.0*buf[k][0] +buf[km1][0])+ zzcon4*(cuf[kp1]-2.0*cuf[k]+cuf[km1])+ zzcon5*(buf[kp1][4]-2.0*buf[k][4]+buf[km1][4])+ dz5tz1*( ue[kp1][4]-2.0*ue[k][4]+ ue[km1][4]); } /*-------------------------------------------------------------------- c Fourth-order dissipation c-------------------------------------------------------------------*/ #pragma omp parallel for firstprivate(dssp ,m ,j ,i ) for (m = 0; m < 5; m++) { k = 1; forcing[i][j][k][m] = forcing[i][j][k][m] - dssp * (5.0*ue[k][m] - 4.0*ue[k+1][m] +ue[k+2][m]); k = 2; forcing[i][j][k][m] = forcing[i][j][k][m] - dssp * (-4.0*ue[k-1][m] + 6.0*ue[k][m] - 4.0*ue[k+1][m] + ue[k+2][m]); } #pragma omp parallel for firstprivate(dssp ,m ,j ,i ) for (m = 0; m < 5; m++) { #pragma omp parallel for firstprivate(k ,dssp ,m ,j ,i ) for (k = 1*3; k <= grid_points[2]-3*1-1; k++) { forcing[i][j][k][m] = forcing[i][j][k][m] - dssp* (ue[k-2][m] - 4.0*ue[k-1][m] + 6.0*ue[k][m] - 4.0*ue[k+1][m] + ue[k+2][m]); } } #pragma omp parallel for firstprivate(dssp ,k ,m ,j ,i ) for (m = 0; m < 5; m++) { k = grid_points[2]-3; forcing[i][j][k][m] = forcing[i][j][k][m] - dssp * (ue[k-2][m] - 4.0*ue[k-1][m] + 6.0*ue[k][m] - 4.0*ue[k+1][m]); k = grid_points[2]-2; forcing[i][j][k][m] = forcing[i][j][k][m] - dssp * (ue[k-2][m] - 4.0*ue[k-1][m] + 5.0*ue[k][m]); } } } /*-------------------------------------------------------------------- c now change the sign of the forcing function, c-------------------------------------------------------------------*/ #pragma omp parallel for for (i = 1; i < grid_points[0]-1; i++) { #pragma omp parallel for firstprivate(j ,k ,m ,i ) for (j = 1; j < grid_points[1]-1; j++) { #pragma omp parallel for firstprivate(j ,k ,m ,i ) for (k = 1; k < grid_points[2]-1; k++) { #pragma omp parallel for firstprivate(j ,k ,m ,i ) for (m = 0; m < 5; m++) { forcing[i][j][k][m] = -1.0 * forcing[i][j][k][m]; } } } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void exact_solution(double xi, double eta, double zeta, double dtemp[5]) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c this function returns the exact solution at point xi, eta, zeta c-------------------------------------------------------------------*/ int m; #pragma omp parallel for firstprivate(zeta ,eta ,xi ,dtemp ,m ) for (m = 0; m < 5; m++) { dtemp[m] = ce[m][0] + xi*(ce[m][1] + xi*(ce[m][4] + xi*(ce[m][7] + xi*ce[m][10]))) + eta*(ce[m][2] + eta*(ce[m][5] + eta*(ce[m][8] + eta*ce[m][11])))+ zeta*(ce[m][3] + zeta*(ce[m][6] + zeta*(ce[m][9] + zeta*ce[m][12]))); } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void initialize(void) { { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c This subroutine initializes the field variable u using c tri-linear transfinite interpolation of the boundary values c-------------------------------------------------------------------*/ int i, j, k, m, ix, iy, iz; double xi, eta, zeta, Pface[2][3][5], Pxi, Peta, Pzeta, temp[5]; /*-------------------------------------------------------------------- c Later (in compute_rhs) we compute 1/u for every element. A few of c the corner elements are not used, but it convenient (and faster) c to compute the whole thing with a simple loop. Make sure those c values are nonzero by initializing the whole thing here. c-------------------------------------------------------------------*/ #pragma omp parallel for for (i = 0; i < IMAX; i++) { #pragma omp parallel for firstprivate(j ,k ,m ,i ) for (j = 0; j < IMAX; j++) { #pragma omp parallel for firstprivate(j ,k ,m ,i ) for (k = 0; k < IMAX; k++) { #pragma omp parallel for firstprivate(j ,k ,m ,i ) for (m = 0; m < 5; m++) { u[i][j][k][m] = 1.0; } } } } /*-------------------------------------------------------------------- c first store the "interpolated" values everywhere on the grid c-------------------------------------------------------------------*/ for (i = 0; i < grid_points[0]; i++) { xi = (double)i * dnxm1; for (j = 0; j < grid_points[1]; j++) { eta = (double)j * dnym1; for (k = 0; k < grid_points[2]; k++) { zeta = (double)k * dnzm1; #pragma omp parallel for for (ix = 0; ix < 2; ix++) { exact_solution((double)ix, eta, zeta, &(Pface[ix][0][0])); } for (iy = 0; iy < 2; iy++) { exact_solution(xi, (double)iy , zeta, &Pface[iy][1][0]); } for (iz = 0; iz < 2; iz++) { exact_solution(xi, eta, (double)iz, &Pface[iz][2][0]); } #pragma omp parallel for for (m = 0; m < 5; m++) { Pxi = xi * Pface[1][0][m] + (1.0-xi) * Pface[0][0][m]; Peta = eta * Pface[1][1][m] + (1.0-eta) * Pface[0][1][m]; Pzeta = zeta * Pface[1][2][m] + (1.0-zeta) * Pface[0][2][m]; u[i][j][k][m] = Pxi + Peta + Pzeta - Pxi*Peta - Pxi*Pzeta - Peta*Pzeta + Pxi*Peta*Pzeta; } } } } /*-------------------------------------------------------------------- c now store the exact values on the boundaries c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c west face c-------------------------------------------------------------------*/ i = 0; xi = 0.0; for (j = 0; j < grid_points[1]; j++) { eta = (double)j * dnym1; for (k = 0; k < grid_points[2]; k++) { zeta = (double)k * dnzm1; exact_solution(xi, eta, zeta, temp); #pragma omp parallel for for (m = 0; m < 5; m++) { u[i][j][k][m] = temp[m]; } } } /*-------------------------------------------------------------------- c east face c-------------------------------------------------------------------*/ i = grid_points[0]-1; xi = 1.0; for (j = 0; j < grid_points[1]; j++) { eta = (double)j * dnym1; for (k = 0; k < grid_points[2]; k++) { zeta = (double)k * dnzm1; exact_solution(xi, eta, zeta, temp); #pragma omp parallel for for (m = 0; m < 5; m++) { u[i][j][k][m] = temp[m]; } } } /*-------------------------------------------------------------------- c south face c-------------------------------------------------------------------*/ j = 0; eta = 0.0; for (i = 0; i < grid_points[0]; i++) { xi = (double)i * dnxm1; for (k = 0; k < grid_points[2]; k++) { zeta = (double)k * dnzm1; exact_solution(xi, eta, zeta, temp); #pragma omp parallel for for (m = 0; m < 5; m++) { u[i][j][k][m] = temp[m]; } } } /*-------------------------------------------------------------------- c north face c-------------------------------------------------------------------*/ j = grid_points[1]-1; eta = 1.0; for (i = 0; i < grid_points[0]; i++) { xi = (double)i * dnxm1; for (k = 0; k < grid_points[2]; k++) { zeta = (double)k * dnzm1; exact_solution(xi, eta, zeta, temp); #pragma omp parallel for for (m = 0; m < 5; m++) { u[i][j][k][m] = temp[m]; } } } /*-------------------------------------------------------------------- c bottom face c-------------------------------------------------------------------*/ k = 0; zeta = 0.0; for (i = 0; i < grid_points[0]; i++) { xi = (double)i *dnxm1; for (j = 0; j < grid_points[1]; j++) { eta = (double)j * dnym1; exact_solution(xi, eta, zeta, temp); for (m = 0; m < 5; m++) { u[i][j][k][m] = temp[m]; } } } /*-------------------------------------------------------------------- c top face c-------------------------------------------------------------------*/ k = grid_points[2]-1; zeta = 1.0; for (i = 0; i < grid_points[0]; i++) { xi = (double)i * dnxm1; for (j = 0; j < grid_points[1]; j++) { eta = (double)j * dnym1; exact_solution(xi, eta, zeta, temp); for (m = 0; m < 5; m++) { u[i][j][k][m] = temp[m]; } } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void lhsinit(void) { { int i, j, k, m, n; /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c zero the whole left hand side for starters c-------------------------------------------------------------------*/ #pragma omp parallel for for (i = 0; i < grid_points[0]; i++) { #pragma omp parallel for firstprivate(j ,k ,m ,n ,i ) for (j = 0; j < grid_points[1]; j++) { #pragma omp parallel for firstprivate(j ,k ,m ,n ,i ) for (k = 0; k < grid_points[2]; k++) { #pragma omp parallel for firstprivate(j ,k ,m ,n ,i ) for (m = 0; m < 5; m++) { #pragma omp parallel for firstprivate(j ,k ,m ,n ,i ) for (n = 0; n < 5; n++) { lhs[i][j][k][0][m][n] = 0.0; lhs[i][j][k][1][m][n] = 0.0; lhs[i][j][k][2][m][n] = 0.0; } } } } } /*-------------------------------------------------------------------- c next, set all diagonal values to 1. This is overkill, but convenient c-------------------------------------------------------------------*/ #pragma omp parallel for for (i = 0; i < grid_points[0]; i++) { #pragma omp parallel for firstprivate(j ,k ,m ,i ) for (j = 0; j < grid_points[1]; j++) { #pragma omp parallel for firstprivate(j ,k ,m ,i ) for (k = 0; k < grid_points[2]; k++) { #pragma omp parallel for firstprivate(j ,k ,m ,i ) for (m = 0; m < 5; m++) { lhs[i][j][k][1][m][m] = 1.0; } } } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void lhsx(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c This function computes the left hand side in the xi-direction c-------------------------------------------------------------------*/ int i, j, k; /*-------------------------------------------------------------------- c determine a (labeled f) and n jacobians c-------------------------------------------------------------------*/ #pragma omp for for (j = 1; j < grid_points[1]-1; j++) { for (k = 1; k < grid_points[2]-1; k++) { #pragma omp parallel for firstprivate(c2 ,c1 ,c3c4 ,con43 ,c1345 ,i ,k ,j ,tmp1 ,tmp2 ,tmp3 ) lastprivate(tmp1 ,tmp2 ,tmp3 ) for (i = 0; i < grid_points[0]; i++) { tmp1 = 1.0 / u[i][j][k][0]; tmp2 = tmp1 * tmp1; tmp3 = tmp1 * tmp2; /*-------------------------------------------------------------------- c c-------------------------------------------------------------------*/ fjac[ i][ j][ k][0][0] = 0.0; fjac[ i][ j][ k][0][1] = 1.0; fjac[ i][ j][ k][0][2] = 0.0; fjac[ i][ j][ k][0][3] = 0.0; fjac[ i][ j][ k][0][4] = 0.0; fjac[ i][ j][ k][1][0] = -(u[i][j][k][1] * tmp2 * u[i][j][k][1]) + c2 * 0.50 * (u[i][j][k][1] * u[i][j][k][1] + u[i][j][k][2] * u[i][j][k][2] + u[i][j][k][3] * u[i][j][k][3] ) * tmp2; fjac[i][j][k][1][1] = ( 2.0 - c2 ) * ( u[i][j][k][1] / u[i][j][k][0] ); fjac[i][j][k][1][2] = - c2 * ( u[i][j][k][2] * tmp1 ); fjac[i][j][k][1][3] = - c2 * ( u[i][j][k][3] * tmp1 ); fjac[i][j][k][1][4] = c2; fjac[i][j][k][2][0] = - ( u[i][j][k][1]*u[i][j][k][2] ) * tmp2; fjac[i][j][k][2][1] = u[i][j][k][2] * tmp1; fjac[i][j][k][2][2] = u[i][j][k][1] * tmp1; fjac[i][j][k][2][3] = 0.0; fjac[i][j][k][2][4] = 0.0; fjac[i][j][k][3][0] = - ( u[i][j][k][1]*u[i][j][k][3] ) * tmp2; fjac[i][j][k][3][1] = u[i][j][k][3] * tmp1; fjac[i][j][k][3][2] = 0.0; fjac[i][j][k][3][3] = u[i][j][k][1] * tmp1; fjac[i][j][k][3][4] = 0.0; fjac[i][j][k][4][0] = ( c2 * ( u[i][j][k][1] * u[i][j][k][1] + u[i][j][k][2] * u[i][j][k][2] + u[i][j][k][3] * u[i][j][k][3] ) * tmp2 - c1 * ( u[i][j][k][4] * tmp1 ) ) * ( u[i][j][k][1] * tmp1 ); fjac[i][j][k][4][1] = c1 * u[i][j][k][4] * tmp1 - 0.50 * c2 * ( 3.0*u[i][j][k][1]*u[i][j][k][1] + u[i][j][k][2]*u[i][j][k][2] + u[i][j][k][3]*u[i][j][k][3] ) * tmp2; fjac[i][j][k][4][2] = - c2 * ( u[i][j][k][2]*u[i][j][k][1] ) * tmp2; fjac[i][j][k][4][3] = - c2 * ( u[i][j][k][3]*u[i][j][k][1] ) * tmp2; fjac[i][j][k][4][4] = c1 * ( u[i][j][k][1] * tmp1 ); njac[i][j][k][0][0] = 0.0; njac[i][j][k][0][1] = 0.0; njac[i][j][k][0][2] = 0.0; njac[i][j][k][0][3] = 0.0; njac[i][j][k][0][4] = 0.0; njac[i][j][k][1][0] = - con43 * c3c4 * tmp2 * u[i][j][k][1]; njac[i][j][k][1][1] = con43 * c3c4 * tmp1; njac[i][j][k][1][2] = 0.0; njac[i][j][k][1][3] = 0.0; njac[i][j][k][1][4] = 0.0; njac[i][j][k][2][0] = - c3c4 * tmp2 * u[i][j][k][2]; njac[i][j][k][2][1] = 0.0; njac[i][j][k][2][2] = c3c4 * tmp1; njac[i][j][k][2][3] = 0.0; njac[i][j][k][2][4] = 0.0; njac[i][j][k][3][0] = - c3c4 * tmp2 * u[i][j][k][3]; njac[i][j][k][3][1] = 0.0; njac[i][j][k][3][2] = 0.0; njac[i][j][k][3][3] = c3c4 * tmp1; njac[i][j][k][3][4] = 0.0; njac[i][j][k][4][0] = - ( con43 * c3c4 - c1345 ) * tmp3 * (pow2(u[i][j][k][1])) - ( c3c4 - c1345 ) * tmp3 * (pow2(u[i][j][k][2])) - ( c3c4 - c1345 ) * tmp3 * (pow2(u[i][j][k][3])) - c1345 * tmp2 * u[i][j][k][4]; njac[i][j][k][4][1] = ( con43 * c3c4 - c1345 ) * tmp2 * u[i][j][k][1]; njac[i][j][k][4][2] = ( c3c4 - c1345 ) * tmp2 * u[i][j][k][2]; njac[i][j][k][4][3] = ( c3c4 - c1345 ) * tmp2 * u[i][j][k][3]; njac[i][j][k][4][4] = ( c1345 ) * tmp1; } /*-------------------------------------------------------------------- c now jacobians set, so form left hand side in x direction c-------------------------------------------------------------------*/ #pragma omp parallel for firstprivate(c2 ,c1 ,c3c4 ,con43 ,c1345 ,i ,k ,j ,tmp1 ,tmp2 ,tmp3 ) lastprivate(tmp1 ,tmp2 ,tmp3 ) for (i = 1; i < grid_points[0]-1; i++) { tmp1 = dt * tx1; tmp2 = dt * tx2; lhs[i][j][k][AA][0][0] = - tmp2 * fjac[i-1][j][k][0][0] - tmp1 * njac[i-1][j][k][0][0] - tmp1 * dx1; lhs[i][j][k][AA][0][1] = - tmp2 * fjac[i-1][j][k][0][1] - tmp1 * njac[i-1][j][k][0][1]; lhs[i][j][k][AA][0][2] = - tmp2 * fjac[i-1][j][k][0][2] - tmp1 * njac[i-1][j][k][0][2]; lhs[i][j][k][AA][0][3] = - tmp2 * fjac[i-1][j][k][0][3] - tmp1 * njac[i-1][j][k][0][3]; lhs[i][j][k][AA][0][4] = - tmp2 * fjac[i-1][j][k][0][4] - tmp1 * njac[i-1][j][k][0][4]; lhs[i][j][k][AA][1][0] = - tmp2 * fjac[i-1][j][k][1][0] - tmp1 * njac[i-1][j][k][1][0]; lhs[i][j][k][AA][1][1] = - tmp2 * fjac[i-1][j][k][1][1] - tmp1 * njac[i-1][j][k][1][1] - tmp1 * dx2; lhs[i][j][k][AA][1][2] = - tmp2 * fjac[i-1][j][k][1][2] - tmp1 * njac[i-1][j][k][1][2]; lhs[i][j][k][AA][1][3] = - tmp2 * fjac[i-1][j][k][1][3] - tmp1 * njac[i-1][j][k][1][3]; lhs[i][j][k][AA][1][4] = - tmp2 * fjac[i-1][j][k][1][4] - tmp1 * njac[i-1][j][k][1][4]; lhs[i][j][k][AA][2][0] = - tmp2 * fjac[i-1][j][k][2][0] - tmp1 * njac[i-1][j][k][2][0]; lhs[i][j][k][AA][2][1] = - tmp2 * fjac[i-1][j][k][2][1] - tmp1 * njac[i-1][j][k][2][1]; lhs[i][j][k][AA][2][2] = - tmp2 * fjac[i-1][j][k][2][2] - tmp1 * njac[i-1][j][k][2][2] - tmp1 * dx3; lhs[i][j][k][AA][2][3] = - tmp2 * fjac[i-1][j][k][2][3] - tmp1 * njac[i-1][j][k][2][3]; lhs[i][j][k][AA][2][4] = - tmp2 * fjac[i-1][j][k][2][4] - tmp1 * njac[i-1][j][k][2][4]; lhs[i][j][k][AA][3][0] = - tmp2 * fjac[i-1][j][k][3][0] - tmp1 * njac[i-1][j][k][3][0]; lhs[i][j][k][AA][3][1] = - tmp2 * fjac[i-1][j][k][3][1] - tmp1 * njac[i-1][j][k][3][1]; lhs[i][j][k][AA][3][2] = - tmp2 * fjac[i-1][j][k][3][2] - tmp1 * njac[i-1][j][k][3][2]; lhs[i][j][k][AA][3][3] = - tmp2 * fjac[i-1][j][k][3][3] - tmp1 * njac[i-1][j][k][3][3] - tmp1 * dx4; lhs[i][j][k][AA][3][4] = - tmp2 * fjac[i-1][j][k][3][4] - tmp1 * njac[i-1][j][k][3][4]; lhs[i][j][k][AA][4][0] = - tmp2 * fjac[i-1][j][k][4][0] - tmp1 * njac[i-1][j][k][4][0]; lhs[i][j][k][AA][4][1] = - tmp2 * fjac[i-1][j][k][4][1] - tmp1 * njac[i-1][j][k][4][1]; lhs[i][j][k][AA][4][2] = - tmp2 * fjac[i-1][j][k][4][2] - tmp1 * njac[i-1][j][k][4][2]; lhs[i][j][k][AA][4][3] = - tmp2 * fjac[i-1][j][k][4][3] - tmp1 * njac[i-1][j][k][4][3]; lhs[i][j][k][AA][4][4] = - tmp2 * fjac[i-1][j][k][4][4] - tmp1 * njac[i-1][j][k][4][4] - tmp1 * dx5; lhs[i][j][k][BB][0][0] = 1.0 + tmp1 * 2.0 * njac[i][j][k][0][0] + tmp1 * 2.0 * dx1; lhs[i][j][k][BB][0][1] = tmp1 * 2.0 * njac[i][j][k][0][1]; lhs[i][j][k][BB][0][2] = tmp1 * 2.0 * njac[i][j][k][0][2]; lhs[i][j][k][BB][0][3] = tmp1 * 2.0 * njac[i][j][k][0][3]; lhs[i][j][k][BB][0][4] = tmp1 * 2.0 * njac[i][j][k][0][4]; lhs[i][j][k][BB][1][0] = tmp1 * 2.0 * njac[i][j][k][1][0]; lhs[i][j][k][BB][1][1] = 1.0 + tmp1 * 2.0 * njac[i][j][k][1][1] + tmp1 * 2.0 * dx2; lhs[i][j][k][BB][1][2] = tmp1 * 2.0 * njac[i][j][k][1][2]; lhs[i][j][k][BB][1][3] = tmp1 * 2.0 * njac[i][j][k][1][3]; lhs[i][j][k][BB][1][4] = tmp1 * 2.0 * njac[i][j][k][1][4]; lhs[i][j][k][BB][2][0] = tmp1 * 2.0 * njac[i][j][k][2][0]; lhs[i][j][k][BB][2][1] = tmp1 * 2.0 * njac[i][j][k][2][1]; lhs[i][j][k][BB][2][2] = 1.0 + tmp1 * 2.0 * njac[i][j][k][2][2] + tmp1 * 2.0 * dx3; lhs[i][j][k][BB][2][3] = tmp1 * 2.0 * njac[i][j][k][2][3]; lhs[i][j][k][BB][2][4] = tmp1 * 2.0 * njac[i][j][k][2][4]; lhs[i][j][k][BB][3][0] = tmp1 * 2.0 * njac[i][j][k][3][0]; lhs[i][j][k][BB][3][1] = tmp1 * 2.0 * njac[i][j][k][3][1]; lhs[i][j][k][BB][3][2] = tmp1 * 2.0 * njac[i][j][k][3][2]; lhs[i][j][k][BB][3][3] = 1.0 + tmp1 * 2.0 * njac[i][j][k][3][3] + tmp1 * 2.0 * dx4; lhs[i][j][k][BB][3][4] = tmp1 * 2.0 * njac[i][j][k][3][4]; lhs[i][j][k][BB][4][0] = tmp1 * 2.0 * njac[i][j][k][4][0]; lhs[i][j][k][BB][4][1] = tmp1 * 2.0 * njac[i][j][k][4][1]; lhs[i][j][k][BB][4][2] = tmp1 * 2.0 * njac[i][j][k][4][2]; lhs[i][j][k][BB][4][3] = tmp1 * 2.0 * njac[i][j][k][4][3]; lhs[i][j][k][BB][4][4] = 1.0 + tmp1 * 2.0 * njac[i][j][k][4][4] + tmp1 * 2.0 * dx5; lhs[i][j][k][CC][0][0] = tmp2 * fjac[i+1][j][k][0][0] - tmp1 * njac[i+1][j][k][0][0] - tmp1 * dx1; lhs[i][j][k][CC][0][1] = tmp2 * fjac[i+1][j][k][0][1] - tmp1 * njac[i+1][j][k][0][1]; lhs[i][j][k][CC][0][2] = tmp2 * fjac[i+1][j][k][0][2] - tmp1 * njac[i+1][j][k][0][2]; lhs[i][j][k][CC][0][3] = tmp2 * fjac[i+1][j][k][0][3] - tmp1 * njac[i+1][j][k][0][3]; lhs[i][j][k][CC][0][4] = tmp2 * fjac[i+1][j][k][0][4] - tmp1 * njac[i+1][j][k][0][4]; lhs[i][j][k][CC][1][0] = tmp2 * fjac[i+1][j][k][1][0] - tmp1 * njac[i+1][j][k][1][0]; lhs[i][j][k][CC][1][1] = tmp2 * fjac[i+1][j][k][1][1] - tmp1 * njac[i+1][j][k][1][1] - tmp1 * dx2; lhs[i][j][k][CC][1][2] = tmp2 * fjac[i+1][j][k][1][2] - tmp1 * njac[i+1][j][k][1][2]; lhs[i][j][k][CC][1][3] = tmp2 * fjac[i+1][j][k][1][3] - tmp1 * njac[i+1][j][k][1][3]; lhs[i][j][k][CC][1][4] = tmp2 * fjac[i+1][j][k][1][4] - tmp1 * njac[i+1][j][k][1][4]; lhs[i][j][k][CC][2][0] = tmp2 * fjac[i+1][j][k][2][0] - tmp1 * njac[i+1][j][k][2][0]; lhs[i][j][k][CC][2][1] = tmp2 * fjac[i+1][j][k][2][1] - tmp1 * njac[i+1][j][k][2][1]; lhs[i][j][k][CC][2][2] = tmp2 * fjac[i+1][j][k][2][2] - tmp1 * njac[i+1][j][k][2][2] - tmp1 * dx3; lhs[i][j][k][CC][2][3] = tmp2 * fjac[i+1][j][k][2][3] - tmp1 * njac[i+1][j][k][2][3]; lhs[i][j][k][CC][2][4] = tmp2 * fjac[i+1][j][k][2][4] - tmp1 * njac[i+1][j][k][2][4]; lhs[i][j][k][CC][3][0] = tmp2 * fjac[i+1][j][k][3][0] - tmp1 * njac[i+1][j][k][3][0]; lhs[i][j][k][CC][3][1] = tmp2 * fjac[i+1][j][k][3][1] - tmp1 * njac[i+1][j][k][3][1]; lhs[i][j][k][CC][3][2] = tmp2 * fjac[i+1][j][k][3][2] - tmp1 * njac[i+1][j][k][3][2]; lhs[i][j][k][CC][3][3] = tmp2 * fjac[i+1][j][k][3][3] - tmp1 * njac[i+1][j][k][3][3] - tmp1 * dx4; lhs[i][j][k][CC][3][4] = tmp2 * fjac[i+1][j][k][3][4] - tmp1 * njac[i+1][j][k][3][4]; lhs[i][j][k][CC][4][0] = tmp2 * fjac[i+1][j][k][4][0] - tmp1 * njac[i+1][j][k][4][0]; lhs[i][j][k][CC][4][1] = tmp2 * fjac[i+1][j][k][4][1] - tmp1 * njac[i+1][j][k][4][1]; lhs[i][j][k][CC][4][2] = tmp2 * fjac[i+1][j][k][4][2] - tmp1 * njac[i+1][j][k][4][2]; lhs[i][j][k][CC][4][3] = tmp2 * fjac[i+1][j][k][4][3] - tmp1 * njac[i+1][j][k][4][3]; lhs[i][j][k][CC][4][4] = tmp2 * fjac[i+1][j][k][4][4] - tmp1 * njac[i+1][j][k][4][4] - tmp1 * dx5; } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void lhsy(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c This function computes the left hand side for the three y-factors c-------------------------------------------------------------------*/ int i, j, k; /*-------------------------------------------------------------------- c Compute the indices for storing the tri-diagonal matrix; c determine a (labeled f) and n jacobians for cell c c-------------------------------------------------------------------*/ #pragma omp for for (i = 1; i < grid_points[0]-1; i++) { for (j = 0; j < grid_points[1]; j++) { #pragma omp parallel for firstprivate(c2 ,c1 ,c3c4 ,con43 ,c1345 ,k ,j ,i ,tmp1 ,tmp2 ,tmp3 ) lastprivate(tmp1 ,tmp2 ,tmp3 ) for (k = 1; k < grid_points[2]-1; k++) { tmp1 = 1.0 / u[i][j][k][0]; tmp2 = tmp1 * tmp1; tmp3 = tmp1 * tmp2; fjac[ i][ j][ k][0][0] = 0.0; fjac[ i][ j][ k][0][1] = 0.0; fjac[ i][ j][ k][0][2] = 1.0; fjac[ i][ j][ k][0][3] = 0.0; fjac[ i][ j][ k][0][4] = 0.0; fjac[i][j][k][1][0] = - ( u[i][j][k][1]*u[i][j][k][2] ) * tmp2; fjac[i][j][k][1][1] = u[i][j][k][2] * tmp1; fjac[i][j][k][1][2] = u[i][j][k][1] * tmp1; fjac[i][j][k][1][3] = 0.0; fjac[i][j][k][1][4] = 0.0; fjac[i][j][k][2][0] = - ( u[i][j][k][2]*u[i][j][k][2]*tmp2) + 0.50 * c2 * ( ( u[i][j][k][1] * u[i][j][k][1] + u[i][j][k][2] * u[i][j][k][2] + u[i][j][k][3] * u[i][j][k][3] ) * tmp2 ); fjac[i][j][k][2][1] = - c2 * u[i][j][k][1] * tmp1; fjac[i][j][k][2][2] = ( 2.0 - c2 ) * u[i][j][k][2] * tmp1; fjac[i][j][k][2][3] = - c2 * u[i][j][k][3] * tmp1; fjac[i][j][k][2][4] = c2; fjac[i][j][k][3][0] = - ( u[i][j][k][2]*u[i][j][k][3] ) * tmp2; fjac[i][j][k][3][1] = 0.0; fjac[i][j][k][3][2] = u[i][j][k][3] * tmp1; fjac[i][j][k][3][3] = u[i][j][k][2] * tmp1; fjac[i][j][k][3][4] = 0.0; fjac[i][j][k][4][0] = ( c2 * ( u[i][j][k][1] * u[i][j][k][1] + u[i][j][k][2] * u[i][j][k][2] + u[i][j][k][3] * u[i][j][k][3] ) * tmp2 - c1 * u[i][j][k][4] * tmp1 ) * u[i][j][k][2] * tmp1; fjac[i][j][k][4][1] = - c2 * u[i][j][k][1]*u[i][j][k][2] * tmp2; fjac[i][j][k][4][2] = c1 * u[i][j][k][4] * tmp1 - 0.50 * c2 * ( ( u[i][j][k][1]*u[i][j][k][1] + 3.0 * u[i][j][k][2]*u[i][j][k][2] + u[i][j][k][3]*u[i][j][k][3] ) * tmp2 ); fjac[i][j][k][4][3] = - c2 * ( u[i][j][k][2]*u[i][j][k][3] ) * tmp2; fjac[i][j][k][4][4] = c1 * u[i][j][k][2] * tmp1; njac[i][j][k][0][0] = 0.0; njac[i][j][k][0][1] = 0.0; njac[i][j][k][0][2] = 0.0; njac[i][j][k][0][3] = 0.0; njac[i][j][k][0][4] = 0.0; njac[i][j][k][1][0] = - c3c4 * tmp2 * u[i][j][k][1]; njac[i][j][k][1][1] = c3c4 * tmp1; njac[i][j][k][1][2] = 0.0; njac[i][j][k][1][3] = 0.0; njac[i][j][k][1][4] = 0.0; njac[i][j][k][2][0] = - con43 * c3c4 * tmp2 * u[i][j][k][2]; njac[i][j][k][2][1] = 0.0; njac[i][j][k][2][2] = con43 * c3c4 * tmp1; njac[i][j][k][2][3] = 0.0; njac[i][j][k][2][4] = 0.0; njac[i][j][k][3][0] = - c3c4 * tmp2 * u[i][j][k][3]; njac[i][j][k][3][1] = 0.0; njac[i][j][k][3][2] = 0.0; njac[i][j][k][3][3] = c3c4 * tmp1; njac[i][j][k][3][4] = 0.0; njac[i][j][k][4][0] = - ( c3c4 - c1345 ) * tmp3 * (pow2(u[i][j][k][1])) - ( con43 * c3c4 - c1345 ) * tmp3 * (pow2(u[i][j][k][2])) - ( c3c4 - c1345 ) * tmp3 * (pow2(u[i][j][k][3])) - c1345 * tmp2 * u[i][j][k][4]; njac[i][j][k][4][1] = ( c3c4 - c1345 ) * tmp2 * u[i][j][k][1]; njac[i][j][k][4][2] = ( con43 * c3c4 - c1345 ) * tmp2 * u[i][j][k][2]; njac[i][j][k][4][3] = ( c3c4 - c1345 ) * tmp2 * u[i][j][k][3]; njac[i][j][k][4][4] = ( c1345 ) * tmp1; } } } /*-------------------------------------------------------------------- c now joacobians set, so form left hand side in y direction c-------------------------------------------------------------------*/ #pragma omp for for (i = 1; i < grid_points[0]-1; i++) { #pragma omp parallel for firstprivate(c2 ,c1 ,c3c4 ,con43 ,c1345 ,k ,j ,i ,tmp1 ,tmp2 ,tmp3 ) lastprivate(tmp1 ,tmp2 ,tmp3 ) for (j = 1; j < grid_points[1]-1; j++) { for (k = 1; k < grid_points[2]-1; k++) { tmp1 = dt * ty1; tmp2 = dt * ty2; lhs[i][j][k][AA][0][0] = - tmp2 * fjac[i][j-1][k][0][0] - tmp1 * njac[i][j-1][k][0][0] - tmp1 * dy1; lhs[i][j][k][AA][0][1] = - tmp2 * fjac[i][j-1][k][0][1] - tmp1 * njac[i][j-1][k][0][1]; lhs[i][j][k][AA][0][2] = - tmp2 * fjac[i][j-1][k][0][2] - tmp1 * njac[i][j-1][k][0][2]; lhs[i][j][k][AA][0][3] = - tmp2 * fjac[i][j-1][k][0][3] - tmp1 * njac[i][j-1][k][0][3]; lhs[i][j][k][AA][0][4] = - tmp2 * fjac[i][j-1][k][0][4] - tmp1 * njac[i][j-1][k][0][4]; lhs[i][j][k][AA][1][0] = - tmp2 * fjac[i][j-1][k][1][0] - tmp1 * njac[i][j-1][k][1][0]; lhs[i][j][k][AA][1][1] = - tmp2 * fjac[i][j-1][k][1][1] - tmp1 * njac[i][j-1][k][1][1] - tmp1 * dy2; lhs[i][j][k][AA][1][2] = - tmp2 * fjac[i][j-1][k][1][2] - tmp1 * njac[i][j-1][k][1][2]; lhs[i][j][k][AA][1][3] = - tmp2 * fjac[i][j-1][k][1][3] - tmp1 * njac[i][j-1][k][1][3]; lhs[i][j][k][AA][1][4] = - tmp2 * fjac[i][j-1][k][1][4] - tmp1 * njac[i][j-1][k][1][4]; lhs[i][j][k][AA][2][0] = - tmp2 * fjac[i][j-1][k][2][0] - tmp1 * njac[i][j-1][k][2][0]; lhs[i][j][k][AA][2][1] = - tmp2 * fjac[i][j-1][k][2][1] - tmp1 * njac[i][j-1][k][2][1]; lhs[i][j][k][AA][2][2] = - tmp2 * fjac[i][j-1][k][2][2] - tmp1 * njac[i][j-1][k][2][2] - tmp1 * dy3; lhs[i][j][k][AA][2][3] = - tmp2 * fjac[i][j-1][k][2][3] - tmp1 * njac[i][j-1][k][2][3]; lhs[i][j][k][AA][2][4] = - tmp2 * fjac[i][j-1][k][2][4] - tmp1 * njac[i][j-1][k][2][4]; lhs[i][j][k][AA][3][0] = - tmp2 * fjac[i][j-1][k][3][0] - tmp1 * njac[i][j-1][k][3][0]; lhs[i][j][k][AA][3][1] = - tmp2 * fjac[i][j-1][k][3][1] - tmp1 * njac[i][j-1][k][3][1]; lhs[i][j][k][AA][3][2] = - tmp2 * fjac[i][j-1][k][3][2] - tmp1 * njac[i][j-1][k][3][2]; lhs[i][j][k][AA][3][3] = - tmp2 * fjac[i][j-1][k][3][3] - tmp1 * njac[i][j-1][k][3][3] - tmp1 * dy4; lhs[i][j][k][AA][3][4] = - tmp2 * fjac[i][j-1][k][3][4] - tmp1 * njac[i][j-1][k][3][4]; lhs[i][j][k][AA][4][0] = - tmp2 * fjac[i][j-1][k][4][0] - tmp1 * njac[i][j-1][k][4][0]; lhs[i][j][k][AA][4][1] = - tmp2 * fjac[i][j-1][k][4][1] - tmp1 * njac[i][j-1][k][4][1]; lhs[i][j][k][AA][4][2] = - tmp2 * fjac[i][j-1][k][4][2] - tmp1 * njac[i][j-1][k][4][2]; lhs[i][j][k][AA][4][3] = - tmp2 * fjac[i][j-1][k][4][3] - tmp1 * njac[i][j-1][k][4][3]; lhs[i][j][k][AA][4][4] = - tmp2 * fjac[i][j-1][k][4][4] - tmp1 * njac[i][j-1][k][4][4] - tmp1 * dy5; lhs[i][j][k][BB][0][0] = 1.0 + tmp1 * 2.0 * njac[i][j][k][0][0] + tmp1 * 2.0 * dy1; lhs[i][j][k][BB][0][1] = tmp1 * 2.0 * njac[i][j][k][0][1]; lhs[i][j][k][BB][0][2] = tmp1 * 2.0 * njac[i][j][k][0][2]; lhs[i][j][k][BB][0][3] = tmp1 * 2.0 * njac[i][j][k][0][3]; lhs[i][j][k][BB][0][4] = tmp1 * 2.0 * njac[i][j][k][0][4]; lhs[i][j][k][BB][1][0] = tmp1 * 2.0 * njac[i][j][k][1][0]; lhs[i][j][k][BB][1][1] = 1.0 + tmp1 * 2.0 * njac[i][j][k][1][1] + tmp1 * 2.0 * dy2; lhs[i][j][k][BB][1][2] = tmp1 * 2.0 * njac[i][j][k][1][2]; lhs[i][j][k][BB][1][3] = tmp1 * 2.0 * njac[i][j][k][1][3]; lhs[i][j][k][BB][1][4] = tmp1 * 2.0 * njac[i][j][k][1][4]; lhs[i][j][k][BB][2][0] = tmp1 * 2.0 * njac[i][j][k][2][0]; lhs[i][j][k][BB][2][1] = tmp1 * 2.0 * njac[i][j][k][2][1]; lhs[i][j][k][BB][2][2] = 1.0 + tmp1 * 2.0 * njac[i][j][k][2][2] + tmp1 * 2.0 * dy3; lhs[i][j][k][BB][2][3] = tmp1 * 2.0 * njac[i][j][k][2][3]; lhs[i][j][k][BB][2][4] = tmp1 * 2.0 * njac[i][j][k][2][4]; lhs[i][j][k][BB][3][0] = tmp1 * 2.0 * njac[i][j][k][3][0]; lhs[i][j][k][BB][3][1] = tmp1 * 2.0 * njac[i][j][k][3][1]; lhs[i][j][k][BB][3][2] = tmp1 * 2.0 * njac[i][j][k][3][2]; lhs[i][j][k][BB][3][3] = 1.0 + tmp1 * 2.0 * njac[i][j][k][3][3] + tmp1 * 2.0 * dy4; lhs[i][j][k][BB][3][4] = tmp1 * 2.0 * njac[i][j][k][3][4]; lhs[i][j][k][BB][4][0] = tmp1 * 2.0 * njac[i][j][k][4][0]; lhs[i][j][k][BB][4][1] = tmp1 * 2.0 * njac[i][j][k][4][1]; lhs[i][j][k][BB][4][2] = tmp1 * 2.0 * njac[i][j][k][4][2]; lhs[i][j][k][BB][4][3] = tmp1 * 2.0 * njac[i][j][k][4][3]; lhs[i][j][k][BB][4][4] = 1.0 + tmp1 * 2.0 * njac[i][j][k][4][4] + tmp1 * 2.0 * dy5; lhs[i][j][k][CC][0][0] = tmp2 * fjac[i][j+1][k][0][0] - tmp1 * njac[i][j+1][k][0][0] - tmp1 * dy1; lhs[i][j][k][CC][0][1] = tmp2 * fjac[i][j+1][k][0][1] - tmp1 * njac[i][j+1][k][0][1]; lhs[i][j][k][CC][0][2] = tmp2 * fjac[i][j+1][k][0][2] - tmp1 * njac[i][j+1][k][0][2]; lhs[i][j][k][CC][0][3] = tmp2 * fjac[i][j+1][k][0][3] - tmp1 * njac[i][j+1][k][0][3]; lhs[i][j][k][CC][0][4] = tmp2 * fjac[i][j+1][k][0][4] - tmp1 * njac[i][j+1][k][0][4]; lhs[i][j][k][CC][1][0] = tmp2 * fjac[i][j+1][k][1][0] - tmp1 * njac[i][j+1][k][1][0]; lhs[i][j][k][CC][1][1] = tmp2 * fjac[i][j+1][k][1][1] - tmp1 * njac[i][j+1][k][1][1] - tmp1 * dy2; lhs[i][j][k][CC][1][2] = tmp2 * fjac[i][j+1][k][1][2] - tmp1 * njac[i][j+1][k][1][2]; lhs[i][j][k][CC][1][3] = tmp2 * fjac[i][j+1][k][1][3] - tmp1 * njac[i][j+1][k][1][3]; lhs[i][j][k][CC][1][4] = tmp2 * fjac[i][j+1][k][1][4] - tmp1 * njac[i][j+1][k][1][4]; lhs[i][j][k][CC][2][0] = tmp2 * fjac[i][j+1][k][2][0] - tmp1 * njac[i][j+1][k][2][0]; lhs[i][j][k][CC][2][1] = tmp2 * fjac[i][j+1][k][2][1] - tmp1 * njac[i][j+1][k][2][1]; lhs[i][j][k][CC][2][2] = tmp2 * fjac[i][j+1][k][2][2] - tmp1 * njac[i][j+1][k][2][2] - tmp1 * dy3; lhs[i][j][k][CC][2][3] = tmp2 * fjac[i][j+1][k][2][3] - tmp1 * njac[i][j+1][k][2][3]; lhs[i][j][k][CC][2][4] = tmp2 * fjac[i][j+1][k][2][4] - tmp1 * njac[i][j+1][k][2][4]; lhs[i][j][k][CC][3][0] = tmp2 * fjac[i][j+1][k][3][0] - tmp1 * njac[i][j+1][k][3][0]; lhs[i][j][k][CC][3][1] = tmp2 * fjac[i][j+1][k][3][1] - tmp1 * njac[i][j+1][k][3][1]; lhs[i][j][k][CC][3][2] = tmp2 * fjac[i][j+1][k][3][2] - tmp1 * njac[i][j+1][k][3][2]; lhs[i][j][k][CC][3][3] = tmp2 * fjac[i][j+1][k][3][3] - tmp1 * njac[i][j+1][k][3][3] - tmp1 * dy4; lhs[i][j][k][CC][3][4] = tmp2 * fjac[i][j+1][k][3][4] - tmp1 * njac[i][j+1][k][3][4]; lhs[i][j][k][CC][4][0] = tmp2 * fjac[i][j+1][k][4][0] - tmp1 * njac[i][j+1][k][4][0]; lhs[i][j][k][CC][4][1] = tmp2 * fjac[i][j+1][k][4][1] - tmp1 * njac[i][j+1][k][4][1]; lhs[i][j][k][CC][4][2] = tmp2 * fjac[i][j+1][k][4][2] - tmp1 * njac[i][j+1][k][4][2]; lhs[i][j][k][CC][4][3] = tmp2 * fjac[i][j+1][k][4][3] - tmp1 * njac[i][j+1][k][4][3]; lhs[i][j][k][CC][4][4] = tmp2 * fjac[i][j+1][k][4][4] - tmp1 * njac[i][j+1][k][4][4] - tmp1 * dy5; } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void lhsz(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c This function computes the left hand side for the three z-factors c-------------------------------------------------------------------*/ int i, j, k; /*-------------------------------------------------------------------- c Compute the indices for storing the block-diagonal matrix; c determine c (labeled f) and s jacobians c---------------------------------------------------------------------*/ #pragma omp for for (i = 1; i < grid_points[0]-1; i++) { for (j = 1; j < grid_points[1]-1; j++) { #pragma omp parallel for firstprivate(c2 ,c1 ,c3c4 ,con43 ,c4 ,c3 ,c1345 ,k ,j ,i ,tmp1 ,tmp2 ,tmp3 ) lastprivate(tmp1 ,tmp2 ,tmp3 ) for (k = 0; k < grid_points[2]; k++) { tmp1 = 1.0 / u[i][j][k][0]; tmp2 = tmp1 * tmp1; tmp3 = tmp1 * tmp2; fjac[i][j][k][0][0] = 0.0; fjac[i][j][k][0][1] = 0.0; fjac[i][j][k][0][2] = 0.0; fjac[i][j][k][0][3] = 1.0; fjac[i][j][k][0][4] = 0.0; fjac[i][j][k][1][0] = - ( u[i][j][k][1]*u[i][j][k][3] ) * tmp2; fjac[i][j][k][1][1] = u[i][j][k][3] * tmp1; fjac[i][j][k][1][2] = 0.0; fjac[i][j][k][1][3] = u[i][j][k][1] * tmp1; fjac[i][j][k][1][4] = 0.0; fjac[i][j][k][2][0] = - ( u[i][j][k][2]*u[i][j][k][3] ) * tmp2; fjac[i][j][k][2][1] = 0.0; fjac[i][j][k][2][2] = u[i][j][k][3] * tmp1; fjac[i][j][k][2][3] = u[i][j][k][2] * tmp1; fjac[i][j][k][2][4] = 0.0; fjac[i][j][k][3][0] = - (u[i][j][k][3]*u[i][j][k][3] * tmp2 ) + 0.50 * c2 * ( ( u[i][j][k][1] * u[i][j][k][1] + u[i][j][k][2] * u[i][j][k][2] + u[i][j][k][3] * u[i][j][k][3] ) * tmp2 ); fjac[i][j][k][3][1] = - c2 * u[i][j][k][1] * tmp1; fjac[i][j][k][3][2] = - c2 * u[i][j][k][2] * tmp1; fjac[i][j][k][3][3] = ( 2.0 - c2 ) * u[i][j][k][3] * tmp1; fjac[i][j][k][3][4] = c2; fjac[i][j][k][4][0] = ( c2 * ( u[i][j][k][1] * u[i][j][k][1] + u[i][j][k][2] * u[i][j][k][2] + u[i][j][k][3] * u[i][j][k][3] ) * tmp2 - c1 * ( u[i][j][k][4] * tmp1 ) ) * ( u[i][j][k][3] * tmp1 ); fjac[i][j][k][4][1] = - c2 * ( u[i][j][k][1]*u[i][j][k][3] ) * tmp2; fjac[i][j][k][4][2] = - c2 * ( u[i][j][k][2]*u[i][j][k][3] ) * tmp2; fjac[i][j][k][4][3] = c1 * ( u[i][j][k][4] * tmp1 ) - 0.50 * c2 * ( ( u[i][j][k][1]*u[i][j][k][1] + u[i][j][k][2]*u[i][j][k][2] + 3.0*u[i][j][k][3]*u[i][j][k][3] ) * tmp2 ); fjac[i][j][k][4][4] = c1 * u[i][j][k][3] * tmp1; njac[i][j][k][0][0] = 0.0; njac[i][j][k][0][1] = 0.0; njac[i][j][k][0][2] = 0.0; njac[i][j][k][0][3] = 0.0; njac[i][j][k][0][4] = 0.0; njac[i][j][k][1][0] = - c3c4 * tmp2 * u[i][j][k][1]; njac[i][j][k][1][1] = c3c4 * tmp1; njac[i][j][k][1][2] = 0.0; njac[i][j][k][1][3] = 0.0; njac[i][j][k][1][4] = 0.0; njac[i][j][k][2][0] = - c3c4 * tmp2 * u[i][j][k][2]; njac[i][j][k][2][1] = 0.0; njac[i][j][k][2][2] = c3c4 * tmp1; njac[i][j][k][2][3] = 0.0; njac[i][j][k][2][4] = 0.0; njac[i][j][k][3][0] = - con43 * c3c4 * tmp2 * u[i][j][k][3]; njac[i][j][k][3][1] = 0.0; njac[i][j][k][3][2] = 0.0; njac[i][j][k][3][3] = con43 * c3 * c4 * tmp1; njac[i][j][k][3][4] = 0.0; njac[i][j][k][4][0] = - ( c3c4 - c1345 ) * tmp3 * (pow2(u[i][j][k][1])) - ( c3c4 - c1345 ) * tmp3 * (pow2(u[i][j][k][2])) - ( con43 * c3c4 - c1345 ) * tmp3 * (pow2(u[i][j][k][3])) - c1345 * tmp2 * u[i][j][k][4]; njac[i][j][k][4][1] = ( c3c4 - c1345 ) * tmp2 * u[i][j][k][1]; njac[i][j][k][4][2] = ( c3c4 - c1345 ) * tmp2 * u[i][j][k][2]; njac[i][j][k][4][3] = ( con43 * c3c4 - c1345 ) * tmp2 * u[i][j][k][3]; njac[i][j][k][4][4] = ( c1345 )* tmp1; } } } /*-------------------------------------------------------------------- c now jacobians set, so form left hand side in z direction c-------------------------------------------------------------------*/ #pragma omp for for (i = 1; i < grid_points[0]-1; i++) { #pragma omp parallel for firstprivate(c2 ,c1 ,c3c4 ,con43 ,c4 ,c3 ,c1345 ,k ,j ,i ,tmp1 ,tmp2 ,tmp3 ) lastprivate(tmp1 ,tmp2 ,tmp3 ) for (j = 1; j < grid_points[1]-1; j++) { for (k = 1; k < grid_points[2]-1; k++) { tmp1 = dt * tz1; tmp2 = dt * tz2; lhs[i][j][k][AA][0][0] = - tmp2 * fjac[i][j][k-1][0][0] - tmp1 * njac[i][j][k-1][0][0] - tmp1 * dz1; lhs[i][j][k][AA][0][1] = - tmp2 * fjac[i][j][k-1][0][1] - tmp1 * njac[i][j][k-1][0][1]; lhs[i][j][k][AA][0][2] = - tmp2 * fjac[i][j][k-1][0][2] - tmp1 * njac[i][j][k-1][0][2]; lhs[i][j][k][AA][0][3] = - tmp2 * fjac[i][j][k-1][0][3] - tmp1 * njac[i][j][k-1][0][3]; lhs[i][j][k][AA][0][4] = - tmp2 * fjac[i][j][k-1][0][4] - tmp1 * njac[i][j][k-1][0][4]; lhs[i][j][k][AA][1][0] = - tmp2 * fjac[i][j][k-1][1][0] - tmp1 * njac[i][j][k-1][1][0]; lhs[i][j][k][AA][1][1] = - tmp2 * fjac[i][j][k-1][1][1] - tmp1 * njac[i][j][k-1][1][1] - tmp1 * dz2; lhs[i][j][k][AA][1][2] = - tmp2 * fjac[i][j][k-1][1][2] - tmp1 * njac[i][j][k-1][1][2]; lhs[i][j][k][AA][1][3] = - tmp2 * fjac[i][j][k-1][1][3] - tmp1 * njac[i][j][k-1][1][3]; lhs[i][j][k][AA][1][4] = - tmp2 * fjac[i][j][k-1][1][4] - tmp1 * njac[i][j][k-1][1][4]; lhs[i][j][k][AA][2][0] = - tmp2 * fjac[i][j][k-1][2][0] - tmp1 * njac[i][j][k-1][2][0]; lhs[i][j][k][AA][2][1] = - tmp2 * fjac[i][j][k-1][2][1] - tmp1 * njac[i][j][k-1][2][1]; lhs[i][j][k][AA][2][2] = - tmp2 * fjac[i][j][k-1][2][2] - tmp1 * njac[i][j][k-1][2][2] - tmp1 * dz3; lhs[i][j][k][AA][2][3] = - tmp2 * fjac[i][j][k-1][2][3] - tmp1 * njac[i][j][k-1][2][3]; lhs[i][j][k][AA][2][4] = - tmp2 * fjac[i][j][k-1][2][4] - tmp1 * njac[i][j][k-1][2][4]; lhs[i][j][k][AA][3][0] = - tmp2 * fjac[i][j][k-1][3][0] - tmp1 * njac[i][j][k-1][3][0]; lhs[i][j][k][AA][3][1] = - tmp2 * fjac[i][j][k-1][3][1] - tmp1 * njac[i][j][k-1][3][1]; lhs[i][j][k][AA][3][2] = - tmp2 * fjac[i][j][k-1][3][2] - tmp1 * njac[i][j][k-1][3][2]; lhs[i][j][k][AA][3][3] = - tmp2 * fjac[i][j][k-1][3][3] - tmp1 * njac[i][j][k-1][3][3] - tmp1 * dz4; lhs[i][j][k][AA][3][4] = - tmp2 * fjac[i][j][k-1][3][4] - tmp1 * njac[i][j][k-1][3][4]; lhs[i][j][k][AA][4][0] = - tmp2 * fjac[i][j][k-1][4][0] - tmp1 * njac[i][j][k-1][4][0]; lhs[i][j][k][AA][4][1] = - tmp2 * fjac[i][j][k-1][4][1] - tmp1 * njac[i][j][k-1][4][1]; lhs[i][j][k][AA][4][2] = - tmp2 * fjac[i][j][k-1][4][2] - tmp1 * njac[i][j][k-1][4][2]; lhs[i][j][k][AA][4][3] = - tmp2 * fjac[i][j][k-1][4][3] - tmp1 * njac[i][j][k-1][4][3]; lhs[i][j][k][AA][4][4] = - tmp2 * fjac[i][j][k-1][4][4] - tmp1 * njac[i][j][k-1][4][4] - tmp1 * dz5; lhs[i][j][k][BB][0][0] = 1.0 + tmp1 * 2.0 * njac[i][j][k][0][0] + tmp1 * 2.0 * dz1; lhs[i][j][k][BB][0][1] = tmp1 * 2.0 * njac[i][j][k][0][1]; lhs[i][j][k][BB][0][2] = tmp1 * 2.0 * njac[i][j][k][0][2]; lhs[i][j][k][BB][0][3] = tmp1 * 2.0 * njac[i][j][k][0][3]; lhs[i][j][k][BB][0][4] = tmp1 * 2.0 * njac[i][j][k][0][4]; lhs[i][j][k][BB][1][0] = tmp1 * 2.0 * njac[i][j][k][1][0]; lhs[i][j][k][BB][1][1] = 1.0 + tmp1 * 2.0 * njac[i][j][k][1][1] + tmp1 * 2.0 * dz2; lhs[i][j][k][BB][1][2] = tmp1 * 2.0 * njac[i][j][k][1][2]; lhs[i][j][k][BB][1][3] = tmp1 * 2.0 * njac[i][j][k][1][3]; lhs[i][j][k][BB][1][4] = tmp1 * 2.0 * njac[i][j][k][1][4]; lhs[i][j][k][BB][2][0] = tmp1 * 2.0 * njac[i][j][k][2][0]; lhs[i][j][k][BB][2][1] = tmp1 * 2.0 * njac[i][j][k][2][1]; lhs[i][j][k][BB][2][2] = 1.0 + tmp1 * 2.0 * njac[i][j][k][2][2] + tmp1 * 2.0 * dz3; lhs[i][j][k][BB][2][3] = tmp1 * 2.0 * njac[i][j][k][2][3]; lhs[i][j][k][BB][2][4] = tmp1 * 2.0 * njac[i][j][k][2][4]; lhs[i][j][k][BB][3][0] = tmp1 * 2.0 * njac[i][j][k][3][0]; lhs[i][j][k][BB][3][1] = tmp1 * 2.0 * njac[i][j][k][3][1]; lhs[i][j][k][BB][3][2] = tmp1 * 2.0 * njac[i][j][k][3][2]; lhs[i][j][k][BB][3][3] = 1.0 + tmp1 * 2.0 * njac[i][j][k][3][3] + tmp1 * 2.0 * dz4; lhs[i][j][k][BB][3][4] = tmp1 * 2.0 * njac[i][j][k][3][4]; lhs[i][j][k][BB][4][0] = tmp1 * 2.0 * njac[i][j][k][4][0]; lhs[i][j][k][BB][4][1] = tmp1 * 2.0 * njac[i][j][k][4][1]; lhs[i][j][k][BB][4][2] = tmp1 * 2.0 * njac[i][j][k][4][2]; lhs[i][j][k][BB][4][3] = tmp1 * 2.0 * njac[i][j][k][4][3]; lhs[i][j][k][BB][4][4] = 1.0 + tmp1 * 2.0 * njac[i][j][k][4][4] + tmp1 * 2.0 * dz5; lhs[i][j][k][CC][0][0] = tmp2 * fjac[i][j][k+1][0][0] - tmp1 * njac[i][j][k+1][0][0] - tmp1 * dz1; lhs[i][j][k][CC][0][1] = tmp2 * fjac[i][j][k+1][0][1] - tmp1 * njac[i][j][k+1][0][1]; lhs[i][j][k][CC][0][2] = tmp2 * fjac[i][j][k+1][0][2] - tmp1 * njac[i][j][k+1][0][2]; lhs[i][j][k][CC][0][3] = tmp2 * fjac[i][j][k+1][0][3] - tmp1 * njac[i][j][k+1][0][3]; lhs[i][j][k][CC][0][4] = tmp2 * fjac[i][j][k+1][0][4] - tmp1 * njac[i][j][k+1][0][4]; lhs[i][j][k][CC][1][0] = tmp2 * fjac[i][j][k+1][1][0] - tmp1 * njac[i][j][k+1][1][0]; lhs[i][j][k][CC][1][1] = tmp2 * fjac[i][j][k+1][1][1] - tmp1 * njac[i][j][k+1][1][1] - tmp1 * dz2; lhs[i][j][k][CC][1][2] = tmp2 * fjac[i][j][k+1][1][2] - tmp1 * njac[i][j][k+1][1][2]; lhs[i][j][k][CC][1][3] = tmp2 * fjac[i][j][k+1][1][3] - tmp1 * njac[i][j][k+1][1][3]; lhs[i][j][k][CC][1][4] = tmp2 * fjac[i][j][k+1][1][4] - tmp1 * njac[i][j][k+1][1][4]; lhs[i][j][k][CC][2][0] = tmp2 * fjac[i][j][k+1][2][0] - tmp1 * njac[i][j][k+1][2][0]; lhs[i][j][k][CC][2][1] = tmp2 * fjac[i][j][k+1][2][1] - tmp1 * njac[i][j][k+1][2][1]; lhs[i][j][k][CC][2][2] = tmp2 * fjac[i][j][k+1][2][2] - tmp1 * njac[i][j][k+1][2][2] - tmp1 * dz3; lhs[i][j][k][CC][2][3] = tmp2 * fjac[i][j][k+1][2][3] - tmp1 * njac[i][j][k+1][2][3]; lhs[i][j][k][CC][2][4] = tmp2 * fjac[i][j][k+1][2][4] - tmp1 * njac[i][j][k+1][2][4]; lhs[i][j][k][CC][3][0] = tmp2 * fjac[i][j][k+1][3][0] - tmp1 * njac[i][j][k+1][3][0]; lhs[i][j][k][CC][3][1] = tmp2 * fjac[i][j][k+1][3][1] - tmp1 * njac[i][j][k+1][3][1]; lhs[i][j][k][CC][3][2] = tmp2 * fjac[i][j][k+1][3][2] - tmp1 * njac[i][j][k+1][3][2]; lhs[i][j][k][CC][3][3] = tmp2 * fjac[i][j][k+1][3][3] - tmp1 * njac[i][j][k+1][3][3] - tmp1 * dz4; lhs[i][j][k][CC][3][4] = tmp2 * fjac[i][j][k+1][3][4] - tmp1 * njac[i][j][k+1][3][4]; lhs[i][j][k][CC][4][0] = tmp2 * fjac[i][j][k+1][4][0] - tmp1 * njac[i][j][k+1][4][0]; lhs[i][j][k][CC][4][1] = tmp2 * fjac[i][j][k+1][4][1] - tmp1 * njac[i][j][k+1][4][1]; lhs[i][j][k][CC][4][2] = tmp2 * fjac[i][j][k+1][4][2] - tmp1 * njac[i][j][k+1][4][2]; lhs[i][j][k][CC][4][3] = tmp2 * fjac[i][j][k+1][4][3] - tmp1 * njac[i][j][k+1][4][3]; lhs[i][j][k][CC][4][4] = tmp2 * fjac[i][j][k+1][4][4] - tmp1 * njac[i][j][k+1][4][4] - tmp1 * dz5; } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void compute_rhs(void) { int i, j, k, m; double rho_inv, uijk, up1, um1, vijk, vp1, vm1, wijk, wp1, wm1; /*-------------------------------------------------------------------- c compute the reciprocal of density, and the kinetic energy, c and the speed of sound. c-------------------------------------------------------------------*/ #pragma omp for for (i = 0; i < grid_points[0]; i++) { #pragma omp parallel for firstprivate(j ,k ,rho_inv ,i ) for (j = 0; j < grid_points[1]; j++) { #pragma omp parallel for firstprivate(j ,k ,rho_inv ,i ) for (k = 0; k < grid_points[2]; k++) { rho_inv = 1.0/u[i][j][k][0]; rho_i[i][j][k] = rho_inv; us[i][j][k] = u[i][j][k][1] * rho_inv; vs[i][j][k] = u[i][j][k][2] * rho_inv; ws[i][j][k] = u[i][j][k][3] * rho_inv; square[i][j][k] = 0.5 * (u[i][j][k][1]*u[i][j][k][1] + u[i][j][k][2]*u[i][j][k][2] + u[i][j][k][3]*u[i][j][k][3] ) * rho_inv; qs[i][j][k] = square[i][j][k] * rho_inv; } } } /*-------------------------------------------------------------------- c copy the exact forcing term to the right hand side; because c this forcing term is known, we can store it on the whole grid c including the boundary c-------------------------------------------------------------------*/ #pragma omp for for (i = 0; i < grid_points[0]; i++) { #pragma omp parallel for firstprivate(j ,k ,m ,i ) for (j = 0; j < grid_points[1]; j++) { #pragma omp parallel for firstprivate(j ,k ,m ,i ) for (k = 0; k < grid_points[2]; k++) { #pragma omp parallel for firstprivate(j ,k ,m ,i ) for (m = 0; m < 5; m++) { rhs[i][j][k][m] = forcing[i][j][k][m]; } } } } /*-------------------------------------------------------------------- c compute xi-direction fluxes c-------------------------------------------------------------------*/ #pragma omp for for (i = 1; i < grid_points[0]-1; i++) { #pragma omp parallel for firstprivate(j ,k ,uijk ,up1 ,um1 ,tx2 ,dx1tx1 ,c2 ,dx2tx1 ,con43 ,xxcon2 ,dx3tx1 ,dx4tx1 ,c1 ,xxcon5 ,xxcon3 ,dx5tx1 ,xxcon4 ,i ) for (j = 1; j < grid_points[1]-1; j++) { #pragma omp parallel for firstprivate(j ,k ,uijk ,up1 ,um1 ,tx2 ,dx1tx1 ,c2 ,dx2tx1 ,con43 ,xxcon2 ,dx3tx1 ,dx4tx1 ,c1 ,xxcon5 ,xxcon3 ,dx5tx1 ,xxcon4 ,i ) for (k = 1; k < grid_points[2]-1; k++) { uijk = us[i][j][k]; up1 = us[i+1][j][k]; um1 = us[i-1][j][k]; rhs[i][j][k][0] = rhs[i][j][k][0] + dx1tx1 * (u[i+1][j][k][0] - 2.0*u[i][j][k][0] + u[i-1][j][k][0]) - tx2 * (u[i+1][j][k][1] - u[i-1][j][k][1]); rhs[i][j][k][1] = rhs[i][j][k][1] + dx2tx1 * (u[i+1][j][k][1] - 2.0*u[i][j][k][1] + u[i-1][j][k][1]) + xxcon2*con43 * (up1 - 2.0*uijk + um1) - tx2 * (u[i+1][j][k][1]*up1 - u[i-1][j][k][1]*um1 + (u[i+1][j][k][4]- square[i+1][j][k]- u[i-1][j][k][4]+ square[i-1][j][k])* c2); rhs[i][j][k][2] = rhs[i][j][k][2] + dx3tx1 * (u[i+1][j][k][2] - 2.0*u[i][j][k][2] + u[i-1][j][k][2]) + xxcon2 * (vs[i+1][j][k] - 2.0*vs[i][j][k] + vs[i-1][j][k]) - tx2 * (u[i+1][j][k][2]*up1 - u[i-1][j][k][2]*um1); rhs[i][j][k][3] = rhs[i][j][k][3] + dx4tx1 * (u[i+1][j][k][3] - 2.0*u[i][j][k][3] + u[i-1][j][k][3]) + xxcon2 * (ws[i+1][j][k] - 2.0*ws[i][j][k] + ws[i-1][j][k]) - tx2 * (u[i+1][j][k][3]*up1 - u[i-1][j][k][3]*um1); rhs[i][j][k][4] = rhs[i][j][k][4] + dx5tx1 * (u[i+1][j][k][4] - 2.0*u[i][j][k][4] + u[i-1][j][k][4]) + xxcon3 * (qs[i+1][j][k] - 2.0*qs[i][j][k] + qs[i-1][j][k]) + xxcon4 * (up1*up1 - 2.0*uijk*uijk + um1*um1) + xxcon5 * (u[i+1][j][k][4]*rho_i[i+1][j][k] - 2.0*u[i][j][k][4]*rho_i[i][j][k] + u[i-1][j][k][4]*rho_i[i-1][j][k]) - tx2 * ( (c1*u[i+1][j][k][4] - c2*square[i+1][j][k])*up1 - (c1*u[i-1][j][k][4] - c2*square[i-1][j][k])*um1 ); } } } /*-------------------------------------------------------------------- c add fourth order xi-direction dissipation c-------------------------------------------------------------------*/ i = 1; #pragma omp for for (j = 1; j < grid_points[1]-1; j++) { #pragma omp parallel for firstprivate(k ,m ,dssp ,j ) for (k = 1; k < grid_points[2]-1; k++) { #pragma omp parallel for firstprivate(k ,m ,dssp ,j ) for (m = 0; m < 5; m++) { rhs[i][j][k][m] = rhs[i][j][k][m]- dssp * ( 5.0*u[i][j][k][m] - 4.0*u[i+1][j][k][m] + u[i+2][j][k][m]); } } } i = 2; #pragma omp for for (j = 1; j < grid_points[1]-1; j++) { #pragma omp parallel for firstprivate(k ,m ,dssp ,j ) for (k = 1; k < grid_points[2]-1; k++) { #pragma omp parallel for firstprivate(k ,m ,dssp ,j ) for (m = 0; m < 5; m++) { rhs[i][j][k][m] = rhs[i][j][k][m] - dssp * (-4.0*u[i-1][j][k][m] + 6.0*u[i][j][k][m] - 4.0*u[i+1][j][k][m] + u[i+2][j][k][m]); } } } #pragma omp for for (i = 3; i < grid_points[0]-3; i++) { #pragma omp parallel for firstprivate(j ,k ,m ,dssp ,i ) for (j = 1; j < grid_points[1]-1; j++) { #pragma omp parallel for firstprivate(j ,k ,m ,dssp ,i ) for (k = 1; k < grid_points[2]-1; k++) { #pragma omp parallel for firstprivate(j ,k ,m ,dssp ,i ) for (m = 0; m < 5; m++) { rhs[i][j][k][m] = rhs[i][j][k][m] - dssp * ( u[i-2][j][k][m] - 4.0*u[i-1][j][k][m] + 6.0*u[i][j][k][m] - 4.0*u[i+1][j][k][m] + u[i+2][j][k][m] ); } } } } i = grid_points[0]-3; #pragma omp for for (j = 1; j < grid_points[1]-1; j++) { #pragma omp parallel for firstprivate(k ,m ,i ,dssp ,j ) for (k = 1; k < grid_points[2]-1; k++) { #pragma omp parallel for firstprivate(k ,m ,i ,dssp ,j ) for (m = 0; m < 5; m++) { rhs[i][j][k][m] = rhs[i][j][k][m] - dssp * ( u[i-2][j][k][m] - 4.0*u[i-1][j][k][m] + 6.0*u[i][j][k][m] - 4.0*u[i+1][j][k][m] ); } } } i = grid_points[0]-2; #pragma omp for for (j = 1; j < grid_points[1]-1; j++) { #pragma omp parallel for firstprivate(k ,m ,i ,dssp ,j ) for (k = 1; k < grid_points[2]-1; k++) { #pragma omp parallel for firstprivate(k ,m ,i ,dssp ,j ) for (m = 0; m < 5; m++) { rhs[i][j][k][m] = rhs[i][j][k][m] - dssp * ( u[i-2][j][k][m] - 4.*u[i-1][j][k][m] + 5.0*u[i][j][k][m] ); } } } /*-------------------------------------------------------------------- c compute eta-direction fluxes c-------------------------------------------------------------------*/ #pragma omp for for (i = 1; i < grid_points[0]-1; i++) { #pragma omp parallel for firstprivate(j ,k ,vijk ,vp1 ,vm1 ,ty2 ,dy1ty1 ,yycon2 ,dy2ty1 ,c2 ,dy3ty1 ,con43 ,dy4ty1 ,c1 ,yycon5 ,yycon3 ,dy5ty1 ,yycon4 ,i ) for (j = 1; j < grid_points[1]-1; j++) { #pragma omp parallel for firstprivate(j ,k ,vijk ,vp1 ,vm1 ,ty2 ,dy1ty1 ,yycon2 ,dy2ty1 ,c2 ,dy3ty1 ,con43 ,dy4ty1 ,c1 ,yycon5 ,yycon3 ,dy5ty1 ,yycon4 ,i ) for (k = 1; k < grid_points[2]-1; k++) { vijk = vs[i][j][k]; vp1 = vs[i][j+1][k]; vm1 = vs[i][j-1][k]; rhs[i][j][k][0] = rhs[i][j][k][0] + dy1ty1 * (u[i][j+1][k][0] - 2.0*u[i][j][k][0] + u[i][j-1][k][0]) - ty2 * (u[i][j+1][k][2] - u[i][j-1][k][2]); rhs[i][j][k][1] = rhs[i][j][k][1] + dy2ty1 * (u[i][j+1][k][1] - 2.0*u[i][j][k][1] + u[i][j-1][k][1]) + yycon2 * (us[i][j+1][k] - 2.0*us[i][j][k] + us[i][j-1][k]) - ty2 * (u[i][j+1][k][1]*vp1 - u[i][j-1][k][1]*vm1); rhs[i][j][k][2] = rhs[i][j][k][2] + dy3ty1 * (u[i][j+1][k][2] - 2.0*u[i][j][k][2] + u[i][j-1][k][2]) + yycon2*con43 * (vp1 - 2.0*vijk + vm1) - ty2 * (u[i][j+1][k][2]*vp1 - u[i][j-1][k][2]*vm1 + (u[i][j+1][k][4] - square[i][j+1][k] - u[i][j-1][k][4] + square[i][j-1][k]) *c2); rhs[i][j][k][3] = rhs[i][j][k][3] + dy4ty1 * (u[i][j+1][k][3] - 2.0*u[i][j][k][3] + u[i][j-1][k][3]) + yycon2 * (ws[i][j+1][k] - 2.0*ws[i][j][k] + ws[i][j-1][k]) - ty2 * (u[i][j+1][k][3]*vp1 - u[i][j-1][k][3]*vm1); rhs[i][j][k][4] = rhs[i][j][k][4] + dy5ty1 * (u[i][j+1][k][4] - 2.0*u[i][j][k][4] + u[i][j-1][k][4]) + yycon3 * (qs[i][j+1][k] - 2.0*qs[i][j][k] + qs[i][j-1][k]) + yycon4 * (vp1*vp1 - 2.0*vijk*vijk + vm1*vm1) + yycon5 * (u[i][j+1][k][4]*rho_i[i][j+1][k] - 2.0*u[i][j][k][4]*rho_i[i][j][k] + u[i][j-1][k][4]*rho_i[i][j-1][k]) - ty2 * ((c1*u[i][j+1][k][4] - c2*square[i][j+1][k]) * vp1 - (c1*u[i][j-1][k][4] - c2*square[i][j-1][k]) * vm1); } } } /*-------------------------------------------------------------------- c add fourth order eta-direction dissipation c-------------------------------------------------------------------*/ j = 1; #pragma omp for for (i = 1; i < grid_points[0]-1; i++) { #pragma omp parallel for firstprivate(k ,m ,dssp ,i ) for (k = 1; k < grid_points[2]-1; k++) { #pragma omp parallel for firstprivate(k ,m ,dssp ,i ) for (m = 0; m < 5; m++) { rhs[i][j][k][m] = rhs[i][j][k][m]- dssp * ( 5.0*u[i][j][k][m] - 4.0*u[i][j+1][k][m] + u[i][j+2][k][m]); } } } j = 2; #pragma omp for for (i = 1; i < grid_points[0]-1; i++) { #pragma omp parallel for firstprivate(k ,m ,dssp ,i ) for (k = 1; k < grid_points[2]-1; k++) { #pragma omp parallel for firstprivate(k ,m ,dssp ,i ) for (m = 0; m < 5; m++) { rhs[i][j][k][m] = rhs[i][j][k][m] - dssp * (-4.0*u[i][j-1][k][m] + 6.0*u[i][j][k][m] - 4.0*u[i][j+1][k][m] + u[i][j+2][k][m]); } } } #pragma omp for for (i = 1; i < grid_points[0]-1; i++) { #pragma omp parallel for firstprivate(j ,k ,m ,dssp ,i ) for (j = 3; j < grid_points[1]-3; j++) { #pragma omp parallel for firstprivate(j ,k ,m ,dssp ,i ) for (k = 1; k < grid_points[2]-1; k++) { #pragma omp parallel for firstprivate(j ,k ,m ,dssp ,i ) for (m = 0; m < 5; m++) { rhs[i][j][k][m] = rhs[i][j][k][m] - dssp * ( u[i][j-2][k][m] - 4.0*u[i][j-1][k][m] + 6.0*u[i][j][k][m] - 4.0*u[i][j+1][k][m] + u[i][j+2][k][m] ); } } } } j = grid_points[1]-3; #pragma omp for for (i = 1; i < grid_points[0]-1; i++) { #pragma omp parallel for firstprivate(k ,m ,j ,dssp ,i ) for (k = 1; k < grid_points[2]-1; k++) { #pragma omp parallel for firstprivate(k ,m ,j ,dssp ,i ) for (m = 0; m < 5; m++) { rhs[i][j][k][m] = rhs[i][j][k][m] - dssp * ( u[i][j-2][k][m] - 4.0*u[i][j-1][k][m] + 6.0*u[i][j][k][m] - 4.0*u[i][j+1][k][m] ); } } } j = grid_points[1]-2; #pragma omp for for (i = 1; i < grid_points[0]-1; i++) { #pragma omp parallel for firstprivate(k ,m ,j ,dssp ,i ) for (k = 1; k < grid_points[2]-1; k++) { #pragma omp parallel for firstprivate(k ,m ,j ,dssp ,i ) for (m = 0; m < 5; m++) { rhs[i][j][k][m] = rhs[i][j][k][m] - dssp * ( u[i][j-2][k][m] - 4.*u[i][j-1][k][m] + 5.*u[i][j][k][m] ); } } } /*-------------------------------------------------------------------- c compute zeta-direction fluxes c-------------------------------------------------------------------*/ #pragma omp for for (i = 1; i < grid_points[0]-1; i++) { #pragma omp parallel for firstprivate(j ,k ,wijk ,wp1 ,wm1 ,tz2 ,dz1tz1 ,zzcon2 ,dz2tz1 ,dz3tz1 ,c2 ,dz4tz1 ,con43 ,c1 ,zzcon5 ,zzcon3 ,dz5tz1 ,zzcon4 ,i ) for (j = 1; j < grid_points[1]-1; j++) { #pragma omp parallel for firstprivate(j ,k ,wijk ,wp1 ,wm1 ,tz2 ,dz1tz1 ,zzcon2 ,dz2tz1 ,dz3tz1 ,c2 ,dz4tz1 ,con43 ,c1 ,zzcon5 ,zzcon3 ,dz5tz1 ,zzcon4 ,i ) for (k = 1; k < grid_points[2]-1; k++) { wijk = ws[i][j][k]; wp1 = ws[i][j][k+1]; wm1 = ws[i][j][k-1]; rhs[i][j][k][0] = rhs[i][j][k][0] + dz1tz1 * (u[i][j][k+1][0] - 2.0*u[i][j][k][0] + u[i][j][k-1][0]) - tz2 * (u[i][j][k+1][3] - u[i][j][k-1][3]); rhs[i][j][k][1] = rhs[i][j][k][1] + dz2tz1 * (u[i][j][k+1][1] - 2.0*u[i][j][k][1] + u[i][j][k-1][1]) + zzcon2 * (us[i][j][k+1] - 2.0*us[i][j][k] + us[i][j][k-1]) - tz2 * (u[i][j][k+1][1]*wp1 - u[i][j][k-1][1]*wm1); rhs[i][j][k][2] = rhs[i][j][k][2] + dz3tz1 * (u[i][j][k+1][2] - 2.0*u[i][j][k][2] + u[i][j][k-1][2]) + zzcon2 * (vs[i][j][k+1] - 2.0*vs[i][j][k] + vs[i][j][k-1]) - tz2 * (u[i][j][k+1][2]*wp1 - u[i][j][k-1][2]*wm1); rhs[i][j][k][3] = rhs[i][j][k][3] + dz4tz1 * (u[i][j][k+1][3] - 2.0*u[i][j][k][3] + u[i][j][k-1][3]) + zzcon2*con43 * (wp1 - 2.0*wijk + wm1) - tz2 * (u[i][j][k+1][3]*wp1 - u[i][j][k-1][3]*wm1 + (u[i][j][k+1][4] - square[i][j][k+1] - u[i][j][k-1][4] + square[i][j][k-1]) *c2); rhs[i][j][k][4] = rhs[i][j][k][4] + dz5tz1 * (u[i][j][k+1][4] - 2.0*u[i][j][k][4] + u[i][j][k-1][4]) + zzcon3 * (qs[i][j][k+1] - 2.0*qs[i][j][k] + qs[i][j][k-1]) + zzcon4 * (wp1*wp1 - 2.0*wijk*wijk + wm1*wm1) + zzcon5 * (u[i][j][k+1][4]*rho_i[i][j][k+1] - 2.0*u[i][j][k][4]*rho_i[i][j][k] + u[i][j][k-1][4]*rho_i[i][j][k-1]) - tz2 * ( (c1*u[i][j][k+1][4] - c2*square[i][j][k+1])*wp1 - (c1*u[i][j][k-1][4] - c2*square[i][j][k-1])*wm1); } } } /*-------------------------------------------------------------------- c add fourth order zeta-direction dissipation c-------------------------------------------------------------------*/ k = 1; #pragma omp for for (i = 1; i < grid_points[0]-1; i++) { #pragma omp parallel for firstprivate(j ,m ,dssp ,i ) for (j = 1; j < grid_points[1]-1; j++) { #pragma omp parallel for firstprivate(j ,m ,dssp ,i ) for (m = 0; m < 5; m++) { rhs[i][j][k][m] = rhs[i][j][k][m]- dssp * ( 5.0*u[i][j][k][m] - 4.0*u[i][j][k+1][m] + u[i][j][k+2][m]); } } } k = 2; #pragma omp for for (i = 1; i < grid_points[0]-1; i++) { #pragma omp parallel for firstprivate(j ,m ,dssp ,i ) for (j = 1; j < grid_points[1]-1; j++) { #pragma omp parallel for firstprivate(j ,m ,dssp ,i ) for (m = 0; m < 5; m++) { rhs[i][j][k][m] = rhs[i][j][k][m] - dssp * (-4.0*u[i][j][k-1][m] + 6.0*u[i][j][k][m] - 4.0*u[i][j][k+1][m] + u[i][j][k+2][m]); } } } #pragma omp for for (i = 1; i < grid_points[0]-1; i++) { #pragma omp parallel for firstprivate(j ,k ,m ,dssp ,i ) for (j = 1; j < grid_points[1]-1; j++) { #pragma omp parallel for firstprivate(j ,k ,m ,dssp ,i ) for (k = 3; k < grid_points[2]-3; k++) { #pragma omp parallel for firstprivate(j ,k ,m ,dssp ,i ) for (m = 0; m < 5; m++) { rhs[i][j][k][m] = rhs[i][j][k][m] - dssp * ( u[i][j][k-2][m] - 4.0*u[i][j][k-1][m] + 6.0*u[i][j][k][m] - 4.0*u[i][j][k+1][m] + u[i][j][k+2][m] ); } } } } k = grid_points[2]-3; #pragma omp for for (i = 1; i < grid_points[0]-1; i++) { #pragma omp parallel for firstprivate(j ,m ,k ,dssp ,i ) for (j = 1; j < grid_points[1]-1; j++) { #pragma omp parallel for firstprivate(j ,m ,k ,dssp ,i ) for (m = 0; m < 5; m++) { rhs[i][j][k][m] = rhs[i][j][k][m] - dssp * ( u[i][j][k-2][m] - 4.0*u[i][j][k-1][m] + 6.0*u[i][j][k][m] - 4.0*u[i][j][k+1][m] ); } } } k = grid_points[2]-2; #pragma omp for for (i = 1; i < grid_points[0]-1; i++) { #pragma omp parallel for firstprivate(j ,m ,k ,dssp ,i ) for (j = 1; j < grid_points[1]-1; j++) { #pragma omp parallel for firstprivate(j ,m ,k ,dssp ,i ) for (m = 0; m < 5; m++) { rhs[i][j][k][m] = rhs[i][j][k][m] - dssp * ( u[i][j][k-2][m] - 4.0*u[i][j][k-1][m] + 5.0*u[i][j][k][m] ); } } } #pragma omp for for (j = 1; j < grid_points[1]-1; j++) { for (k = 1; k < grid_points[2]-1; k++) { for (m = 0; m < 5; m++) { for (i = 1; i < grid_points[0]-1; i++) { rhs[i][j][k][m] = rhs[i][j][k][m] * dt; } } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void set_constants(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ ce[0][0] = 2.0; ce[0][1] = 0.0; ce[0][2] = 0.0; ce[0][3] = 4.0; ce[0][4] = 5.0; ce[0][5] = 3.0; ce[0][6] = 0.5; ce[0][7] = 0.02; ce[0][8] = 0.01; ce[0][9] = 0.03; ce[0][10] = 0.5; ce[0][11] = 0.4; ce[0][12] = 0.3; ce[1][0] = 1.0; ce[1][1] = 0.0; ce[1][2] = 0.0; ce[1][3] = 0.0; ce[1][4] = 1.0; ce[1][5] = 2.0; ce[1][6] = 3.0; ce[1][7] = 0.01; ce[1][8] = 0.03; ce[1][9] = 0.02; ce[1][10] = 0.4; ce[1][11] = 0.3; ce[1][12] = 0.5; ce[2][0] = 2.0; ce[2][1] = 2.0; ce[2][2] = 0.0; ce[2][3] = 0.0; ce[2][4] = 0.0; ce[2][5] = 2.0; ce[2][6] = 3.0; ce[2][7] = 0.04; ce[2][8] = 0.03; ce[2][9] = 0.05; ce[2][10] = 0.3; ce[2][11] = 0.5; ce[2][12] = 0.4; ce[3][0] = 2.0; ce[3][1] = 2.0; ce[3][2] = 0.0; ce[3][3] = 0.0; ce[3][4] = 0.0; ce[3][5] = 2.0; ce[3][6] = 3.0; ce[3][7] = 0.03; ce[3][8] = 0.05; ce[3][9] = 0.04; ce[3][10] = 0.2; ce[3][11] = 0.1; ce[3][12] = 0.3; ce[4][0] = 5.0; ce[4][1] = 4.0; ce[4][2] = 3.0; ce[4][3] = 2.0; ce[4][4] = 0.1; ce[4][5] = 0.4; ce[4][6] = 0.3; ce[4][7] = 0.05; ce[4][8] = 0.04; ce[4][9] = 0.03; ce[4][10] = 0.1; ce[4][11] = 0.3; ce[4][12] = 0.2; c1 = 1.4; c2 = 0.4; c3 = 0.1; c4 = 1.0; c5 = 1.4; dnxm1 = 1.0 / (double)(grid_points[0]-1); dnym1 = 1.0 / (double)(grid_points[1]-1); dnzm1 = 1.0 / (double)(grid_points[2]-1); c1c2 = c1 * c2; c1c5 = c1 * c5; c3c4 = c3 * c4; c1345 = c1c5 * c3c4; conz1 = (1.0-c1c5); tx1 = 1.0 / (dnxm1 * dnxm1); tx2 = 1.0 / (2.0 * dnxm1); tx3 = 1.0 / dnxm1; ty1 = 1.0 / (dnym1 * dnym1); ty2 = 1.0 / (2.0 * dnym1); ty3 = 1.0 / dnym1; tz1 = 1.0 / (dnzm1 * dnzm1); tz2 = 1.0 / (2.0 * dnzm1); tz3 = 1.0 / dnzm1; dx1 = 0.75; dx2 = 0.75; dx3 = 0.75; dx4 = 0.75; dx5 = 0.75; dy1 = 0.75; dy2 = 0.75; dy3 = 0.75; dy4 = 0.75; dy5 = 0.75; dz1 = 1.0; dz2 = 1.0; dz3 = 1.0; dz4 = 1.0; dz5 = 1.0; dxmax = max(dx3, dx4); dymax = max(dy2, dy4); dzmax = max(dz2, dz3); dssp = 0.25 * max(dx1, max(dy1, dz1) ); c4dssp = 4.0 * dssp; c5dssp = 5.0 * dssp; dttx1 = dt*tx1; dttx2 = dt*tx2; dtty1 = dt*ty1; dtty2 = dt*ty2; dttz1 = dt*tz1; dttz2 = dt*tz2; c2dttx1 = 2.0*dttx1; c2dtty1 = 2.0*dtty1; c2dttz1 = 2.0*dttz1; dtdssp = dt*dssp; comz1 = dtdssp; comz4 = 4.0*dtdssp; comz5 = 5.0*dtdssp; comz6 = 6.0*dtdssp; c3c4tx3 = c3c4*tx3; c3c4ty3 = c3c4*ty3; c3c4tz3 = c3c4*tz3; dx1tx1 = dx1*tx1; dx2tx1 = dx2*tx1; dx3tx1 = dx3*tx1; dx4tx1 = dx4*tx1; dx5tx1 = dx5*tx1; dy1ty1 = dy1*ty1; dy2ty1 = dy2*ty1; dy3ty1 = dy3*ty1; dy4ty1 = dy4*ty1; dy5ty1 = dy5*ty1; dz1tz1 = dz1*tz1; dz2tz1 = dz2*tz1; dz3tz1 = dz3*tz1; dz4tz1 = dz4*tz1; dz5tz1 = dz5*tz1; c2iv = 2.5; con43 = 4.0/3.0; con16 = 1.0/6.0; xxcon1 = c3c4tx3*con43*tx3; xxcon2 = c3c4tx3*tx3; xxcon3 = c3c4tx3*conz1*tx3; xxcon4 = c3c4tx3*con16*tx3; xxcon5 = c3c4tx3*c1c5*tx3; yycon1 = c3c4ty3*con43*ty3; yycon2 = c3c4ty3*ty3; yycon3 = c3c4ty3*conz1*ty3; yycon4 = c3c4ty3*con16*ty3; yycon5 = c3c4ty3*c1c5*ty3; zzcon1 = c3c4tz3*con43*tz3; zzcon2 = c3c4tz3*tz3; zzcon3 = c3c4tz3*conz1*tz3; zzcon4 = c3c4tz3*con16*tz3; zzcon5 = c3c4tz3*c1c5*tz3; } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void verify(int no_time_steps, char *class, boolean *verified) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c verification routine c-------------------------------------------------------------------*/ double xcrref[5],xceref[5],xcrdif[5],xcedif[5], epsilon, xce[5], xcr[5], dtref; int m; /*-------------------------------------------------------------------- c tolerance level c-------------------------------------------------------------------*/ epsilon = 1.0e-08; /*-------------------------------------------------------------------- c compute the error norm and the residual norm, and exit if not printing c-------------------------------------------------------------------*/ error_norm(xce); compute_rhs(); rhs_norm(xcr); #pragma omp parallel for firstprivate(dt ,m ) for (m = 0; m < 5; m++) { xcr[m] = xcr[m] / dt; } *class = 'U'; *verified = TRUE; #pragma omp parallel for firstprivate(m ) for (m = 0; m < 5; m++) { xcrref[m] = 1.0; xceref[m] = 1.0; } /*-------------------------------------------------------------------- c reference data for 12X12X12 grids after 100 time steps, with DT = 1.0d-02 c-------------------------------------------------------------------*/ if (grid_points[0] == 12 && grid_points[1] == 12 && grid_points[2] == 12 && no_time_steps == 60) { *class = 'S'; dtref = 1.0e-2; /*-------------------------------------------------------------------- c Reference values of RMS-norms of residual. c-------------------------------------------------------------------*/ xcrref[0] = 1.7034283709541311e-01; xcrref[1] = 1.2975252070034097e-02; xcrref[2] = 3.2527926989486055e-02; xcrref[3] = 2.6436421275166801e-02; xcrref[4] = 1.9211784131744430e-01; /*-------------------------------------------------------------------- c Reference values of RMS-norms of solution error. c-------------------------------------------------------------------*/ xceref[0] = 4.9976913345811579e-04; xceref[1] = 4.5195666782961927e-05; xceref[2] = 7.3973765172921357e-05; xceref[3] = 7.3821238632439731e-05; xceref[4] = 8.9269630987491446e-04; /*-------------------------------------------------------------------- c reference data for 24X24X24 grids after 200 time steps, with DT = 0.8d-3 c-------------------------------------------------------------------*/ } else if (grid_points[0] == 24 && grid_points[1] == 24 && grid_points[2] == 24 && no_time_steps == 200) { *class = 'W'; dtref = 0.8e-3; /*-------------------------------------------------------------------- c Reference values of RMS-norms of residual. c-------------------------------------------------------------------*/ xcrref[0] = 0.1125590409344e+03; xcrref[1] = 0.1180007595731e+02; xcrref[2] = 0.2710329767846e+02; xcrref[3] = 0.2469174937669e+02; xcrref[4] = 0.2638427874317e+03; /*-------------------------------------------------------------------- c Reference values of RMS-norms of solution error. c-------------------------------------------------------------------*/ xceref[0] = 0.4419655736008e+01; xceref[1] = 0.4638531260002e+00; xceref[2] = 0.1011551749967e+01; xceref[3] = 0.9235878729944e+00; xceref[4] = 0.1018045837718e+02; /*-------------------------------------------------------------------- c reference data for 64X64X64 grids after 200 time steps, with DT = 0.8d-3 c-------------------------------------------------------------------*/ } else if (grid_points[0] == 64 && grid_points[1] == 64 && grid_points[2] == 64 && no_time_steps == 200) { *class = 'A'; dtref = 0.8e-3; /*-------------------------------------------------------------------- c Reference values of RMS-norms of residual. c-------------------------------------------------------------------*/ xcrref[0] = 1.0806346714637264e+02; xcrref[1] = 1.1319730901220813e+01; xcrref[2] = 2.5974354511582465e+01; xcrref[3] = 2.3665622544678910e+01; xcrref[4] = 2.5278963211748344e+02; /*-------------------------------------------------------------------- c Reference values of RMS-norms of solution error. c-------------------------------------------------------------------*/ xceref[0] = 4.2348416040525025e+00; xceref[1] = 4.4390282496995698e-01; xceref[2] = 9.6692480136345650e-01; xceref[3] = 8.8302063039765474e-01; xceref[4] = 9.7379901770829278e+00; /*-------------------------------------------------------------------- c reference data for 102X102X102 grids after 200 time steps, c with DT = 3.0d-04 c-------------------------------------------------------------------*/ } else if (grid_points[0] == 102 && grid_points[1] == 102 && grid_points[2] == 102 && no_time_steps == 200) { *class = 'B'; dtref = 3.0e-4; /*-------------------------------------------------------------------- c Reference values of RMS-norms of residual. c-------------------------------------------------------------------*/ xcrref[0] = 1.4233597229287254e+03; xcrref[1] = 9.9330522590150238e+01; xcrref[2] = 3.5646025644535285e+02; xcrref[3] = 3.2485447959084092e+02; xcrref[4] = 3.2707541254659363e+03; /*-------------------------------------------------------------------- c Reference values of RMS-norms of solution error. c-------------------------------------------------------------------*/ xceref[0] = 5.2969847140936856e+01; xceref[1] = 4.4632896115670668e+00; xceref[2] = 1.3122573342210174e+01; xceref[3] = 1.2006925323559144e+01; xceref[4] = 1.2459576151035986e+02; /*-------------------------------------------------------------------- c reference data for 162X162X162 grids after 200 time steps, c with DT = 1.0d-04 c-------------------------------------------------------------------*/ } else if (grid_points[0] == 162 && grid_points[1] == 162 && grid_points[2] == 162 && no_time_steps == 200) { *class = 'C'; dtref = 1.0e-4; /*-------------------------------------------------------------------- c Reference values of RMS-norms of residual. c-------------------------------------------------------------------*/ xcrref[0] = 0.62398116551764615e+04; xcrref[1] = 0.50793239190423964e+03; xcrref[2] = 0.15423530093013596e+04; xcrref[3] = 0.13302387929291190e+04; xcrref[4] = 0.11604087428436455e+05; /*-------------------------------------------------------------------- c Reference values of RMS-norms of solution error. c-------------------------------------------------------------------*/ xceref[0] = 0.16462008369091265e+03; xceref[1] = 0.11497107903824313e+02; xceref[2] = 0.41207446207461508e+02; xceref[3] = 0.37087651059694167e+02; xceref[4] = 0.36211053051841265e+03; } else { *verified = FALSE; } /*-------------------------------------------------------------------- c verification test for residuals if gridsize is either 12X12X12 or c 64X64X64 or 102X102X102 or 162X162X162 c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c Compute the difference of solution values and the known reference values. c-------------------------------------------------------------------*/ #pragma omp parallel for firstprivate(m ) for (m = 0; m < 5; m++) { xcrdif[m] = fabs((xcr[m]-xcrref[m])/xcrref[m]); xcedif[m] = fabs((xce[m]-xceref[m])/xceref[m]); } /*-------------------------------------------------------------------- c Output the comparison of computed results to known cases. c-------------------------------------------------------------------*/ if (*class != 'U') { printf(" Verification being performed for class %1c\n", *class); printf(" accuracy setting for epsilon = %20.13e\n", epsilon); if (fabs(dt-dtref) > epsilon) { *verified = FALSE; *class = 'U'; printf(" DT does not match the reference value of %15.8e\n", dtref); } } else { printf(" Unknown class\n"); } if (*class != 'U') { printf(" Comparison of RMS-norms of residual\n"); } else { printf(" RMS-norms of residual\n"); } for (m = 0; m < 5; m++) { if (*class == 'U') { printf(" %2d%20.13e\n", m, xcr[m]); } else if (xcrdif[m] > epsilon) { *verified = FALSE; printf(" FAILURE: %2d%20.13e%20.13e%20.13e\n", m, xcr[m], xcrref[m], xcrdif[m]); } else { printf(" %2d%20.13e%20.13e%20.13e\n", m, xcr[m], xcrref[m], xcrdif[m]); } } if (*class != 'U') { printf(" Comparison of RMS-norms of solution error\n"); } else { printf(" RMS-norms of solution error\n"); } for (m = 0; m < 5; m++) { if (*class == 'U') { printf(" %2d%20.13e\n", m, xce[m]); } else if (xcedif[m] > epsilon) { *verified = FALSE; printf(" FAILURE: %2d%20.13e%20.13e%20.13e\n", m, xce[m], xceref[m], xcedif[m]); } else { printf(" %2d%20.13e%20.13e%20.13e\n", m, xce[m], xceref[m], xcedif[m]); } } if (*class == 'U') { printf(" No reference values provided\n"); printf(" No verification performed\n"); } else if (*verified == TRUE) { printf(" Verification Successful\n"); } else { printf(" Verification failed\n"); } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void x_solve(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c c Performs line solves in X direction by first factoring c the block-tridiagonal matrix into an upper triangular matrix, c and then performing back substitution to solve for the unknow c vectors of each line. c c Make sure we treat elements zero to cell_size in the direction c of the sweep. c c-------------------------------------------------------------------*/ lhsx(); x_solve_cell(); x_backsubstitute(); } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void x_backsubstitute(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c back solve: if last cell, then generate U(isize)=rhs[isize) c else assume U(isize) is loaded in un pack backsub_info c so just use it c after call u(istart) will be sent to next cell c-------------------------------------------------------------------*/ int i, j, k, m, n; for (i = grid_points[0]-2; i >= 0; i--) { #pragma omp for for (j = 1; j < grid_points[1]-1; j++) { #pragma omp parallel for firstprivate(m ,k ,n ,j ,i ) for (k = 1; k < grid_points[2]-1; k++) { #pragma omp parallel for firstprivate(m ,k ,n ,j ,i ) for (m = 0; m < BLOCK_SIZE; m++) { for (n = 0; n < BLOCK_SIZE; n++) { rhs[i][j][k][m] = rhs[i][j][k][m] - lhs[i][j][k][CC][m][n]*rhs[i+1][j][k][n]; } } } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void x_solve_cell(void) { /*-------------------------------------------------------------------- c performs guaussian elimination on this cell. c c assumes that unpacking routines for non-first cells c preload C' and rhs' from previous cell. c c assumed send happens outside this routine, but that c c'(IMAX) and rhs'(IMAX) will be sent to next cell c-------------------------------------------------------------------*/ int i,j,k,isize; isize = grid_points[0]-1; /*-------------------------------------------------------------------- c outer most do loops - sweeping in i direction c-------------------------------------------------------------------*/ #pragma omp for for (j = 1; j < grid_points[1]-1; j++) { for (k = 1; k < grid_points[2]-1; k++) { /*-------------------------------------------------------------------- c multiply c(0,j,k) by b_inverse and copy back to c c multiply rhs(0) by b_inverse(0) and copy to rhs c-------------------------------------------------------------------*/ binvcrhs( lhs[0][j][k][BB], lhs[0][j][k][CC], rhs[0][j][k] ); } } /*-------------------------------------------------------------------- c begin inner most do loop c do all the elements of the cell unless last c-------------------------------------------------------------------*/ for (i = 1; i < isize; i++) { #pragma omp for for (j = 1; j < grid_points[1]-1; j++) { for (k = 1; k < grid_points[2]-1; k++) { /*-------------------------------------------------------------------- c rhs(i) = rhs(i) - A*rhs(i-1) c-------------------------------------------------------------------*/ matvec_sub(lhs[i][j][k][AA], rhs[i-1][j][k], rhs[i][j][k]); /*-------------------------------------------------------------------- c B(i) = B(i) - C(i-1)*A(i) c-------------------------------------------------------------------*/ matmul_sub(lhs[i][j][k][AA], lhs[i-1][j][k][CC], lhs[i][j][k][BB]); /*-------------------------------------------------------------------- c multiply c(i,j,k) by b_inverse and copy back to c c multiply rhs(1,j,k) by b_inverse(1,j,k) and copy to rhs c-------------------------------------------------------------------*/ binvcrhs( lhs[i][j][k][BB], lhs[i][j][k][CC], rhs[i][j][k] ); } } } #pragma omp for for (j = 1; j < grid_points[1]-1; j++) { for (k = 1; k < grid_points[2]-1; k++) { /*-------------------------------------------------------------------- c rhs(isize) = rhs(isize) - A*rhs(isize-1) c-------------------------------------------------------------------*/ matvec_sub(lhs[isize][j][k][AA], rhs[isize-1][j][k], rhs[isize][j][k]); /*-------------------------------------------------------------------- c B(isize) = B(isize) - C(isize-1)*A(isize) c-------------------------------------------------------------------*/ matmul_sub(lhs[isize][j][k][AA], lhs[isize-1][j][k][CC], lhs[isize][j][k][BB]); /*-------------------------------------------------------------------- c multiply rhs() by b_inverse() and copy to rhs c-------------------------------------------------------------------*/ binvrhs( lhs[i][j][k][BB], rhs[i][j][k] ); } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void matvec_sub(double ablock[5][5], double avec[5], double bvec[5]) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c subtracts bvec=bvec - ablock*avec c-------------------------------------------------------------------*/ int i; for (i = 0; i < 5; i++) { /*-------------------------------------------------------------------- c rhs(i,ic,jc,kc,ccell) = rhs(i,ic,jc,kc,ccell) c $ - lhs[i,1,ablock,ia,ja,ka,acell)* c-------------------------------------------------------------------*/ bvec[i] = bvec[i] - ablock[i][0]*avec[0] - ablock[i][1]*avec[1] - ablock[i][2]*avec[2] - ablock[i][3]*avec[3] - ablock[i][4]*avec[4]; } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void matmul_sub(double ablock[5][5], double bblock[5][5], double cblock[5][5]) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c subtracts a(i,j,k) X b(i,j,k) from c(i,j,k) c-------------------------------------------------------------------*/ int j; for (j = 0; j < 5; j++) { cblock[0][j] = cblock[0][j] - ablock[0][0]*bblock[0][j] - ablock[0][1]*bblock[1][j] - ablock[0][2]*bblock[2][j] - ablock[0][3]*bblock[3][j] - ablock[0][4]*bblock[4][j]; cblock[1][j] = cblock[1][j] - ablock[1][0]*bblock[0][j] - ablock[1][1]*bblock[1][j] - ablock[1][2]*bblock[2][j] - ablock[1][3]*bblock[3][j] - ablock[1][4]*bblock[4][j]; cblock[2][j] = cblock[2][j] - ablock[2][0]*bblock[0][j] - ablock[2][1]*bblock[1][j] - ablock[2][2]*bblock[2][j] - ablock[2][3]*bblock[3][j] - ablock[2][4]*bblock[4][j]; cblock[3][j] = cblock[3][j] - ablock[3][0]*bblock[0][j] - ablock[3][1]*bblock[1][j] - ablock[3][2]*bblock[2][j] - ablock[3][3]*bblock[3][j] - ablock[3][4]*bblock[4][j]; cblock[4][j] = cblock[4][j] - ablock[4][0]*bblock[0][j] - ablock[4][1]*bblock[1][j] - ablock[4][2]*bblock[2][j] - ablock[4][3]*bblock[3][j] - ablock[4][4]*bblock[4][j]; } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void binvcrhs(double lhs[5][5], double c[5][5], double r[5]) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ double pivot, coeff; /*-------------------------------------------------------------------- c c-------------------------------------------------------------------*/ pivot = 1.00/lhs[0][0]; lhs[0][1] = lhs[0][1]*pivot; lhs[0][2] = lhs[0][2]*pivot; lhs[0][3] = lhs[0][3]*pivot; lhs[0][4] = lhs[0][4]*pivot; c[0][0] = c[0][0]*pivot; c[0][1] = c[0][1]*pivot; c[0][2] = c[0][2]*pivot; c[0][3] = c[0][3]*pivot; c[0][4] = c[0][4]*pivot; r[0] = r[0] *pivot; coeff = lhs[1][0]; lhs[1][1]= lhs[1][1] - coeff*lhs[0][1]; lhs[1][2]= lhs[1][2] - coeff*lhs[0][2]; lhs[1][3]= lhs[1][3] - coeff*lhs[0][3]; lhs[1][4]= lhs[1][4] - coeff*lhs[0][4]; c[1][0] = c[1][0] - coeff*c[0][0]; c[1][1] = c[1][1] - coeff*c[0][1]; c[1][2] = c[1][2] - coeff*c[0][2]; c[1][3] = c[1][3] - coeff*c[0][3]; c[1][4] = c[1][4] - coeff*c[0][4]; r[1] = r[1] - coeff*r[0]; coeff = lhs[2][0]; lhs[2][1]= lhs[2][1] - coeff*lhs[0][1]; lhs[2][2]= lhs[2][2] - coeff*lhs[0][2]; lhs[2][3]= lhs[2][3] - coeff*lhs[0][3]; lhs[2][4]= lhs[2][4] - coeff*lhs[0][4]; c[2][0] = c[2][0] - coeff*c[0][0]; c[2][1] = c[2][1] - coeff*c[0][1]; c[2][2] = c[2][2] - coeff*c[0][2]; c[2][3] = c[2][3] - coeff*c[0][3]; c[2][4] = c[2][4] - coeff*c[0][4]; r[2] = r[2] - coeff*r[0]; coeff = lhs[3][0]; lhs[3][1]= lhs[3][1] - coeff*lhs[0][1]; lhs[3][2]= lhs[3][2] - coeff*lhs[0][2]; lhs[3][3]= lhs[3][3] - coeff*lhs[0][3]; lhs[3][4]= lhs[3][4] - coeff*lhs[0][4]; c[3][0] = c[3][0] - coeff*c[0][0]; c[3][1] = c[3][1] - coeff*c[0][1]; c[3][2] = c[3][2] - coeff*c[0][2]; c[3][3] = c[3][3] - coeff*c[0][3]; c[3][4] = c[3][4] - coeff*c[0][4]; r[3] = r[3] - coeff*r[0]; coeff = lhs[4][0]; lhs[4][1]= lhs[4][1] - coeff*lhs[0][1]; lhs[4][2]= lhs[4][2] - coeff*lhs[0][2]; lhs[4][3]= lhs[4][3] - coeff*lhs[0][3]; lhs[4][4]= lhs[4][4] - coeff*lhs[0][4]; c[4][0] = c[4][0] - coeff*c[0][0]; c[4][1] = c[4][1] - coeff*c[0][1]; c[4][2] = c[4][2] - coeff*c[0][2]; c[4][3] = c[4][3] - coeff*c[0][3]; c[4][4] = c[4][4] - coeff*c[0][4]; r[4] = r[4] - coeff*r[0]; pivot = 1.00/lhs[1][1]; lhs[1][2] = lhs[1][2]*pivot; lhs[1][3] = lhs[1][3]*pivot; lhs[1][4] = lhs[1][4]*pivot; c[1][0] = c[1][0]*pivot; c[1][1] = c[1][1]*pivot; c[1][2] = c[1][2]*pivot; c[1][3] = c[1][3]*pivot; c[1][4] = c[1][4]*pivot; r[1] = r[1] *pivot; coeff = lhs[0][1]; lhs[0][2]= lhs[0][2] - coeff*lhs[1][2]; lhs[0][3]= lhs[0][3] - coeff*lhs[1][3]; lhs[0][4]= lhs[0][4] - coeff*lhs[1][4]; c[0][0] = c[0][0] - coeff*c[1][0]; c[0][1] = c[0][1] - coeff*c[1][1]; c[0][2] = c[0][2] - coeff*c[1][2]; c[0][3] = c[0][3] - coeff*c[1][3]; c[0][4] = c[0][4] - coeff*c[1][4]; r[0] = r[0] - coeff*r[1]; coeff = lhs[2][1]; lhs[2][2]= lhs[2][2] - coeff*lhs[1][2]; lhs[2][3]= lhs[2][3] - coeff*lhs[1][3]; lhs[2][4]= lhs[2][4] - coeff*lhs[1][4]; c[2][0] = c[2][0] - coeff*c[1][0]; c[2][1] = c[2][1] - coeff*c[1][1]; c[2][2] = c[2][2] - coeff*c[1][2]; c[2][3] = c[2][3] - coeff*c[1][3]; c[2][4] = c[2][4] - coeff*c[1][4]; r[2] = r[2] - coeff*r[1]; coeff = lhs[3][1]; lhs[3][2]= lhs[3][2] - coeff*lhs[1][2]; lhs[3][3]= lhs[3][3] - coeff*lhs[1][3]; lhs[3][4]= lhs[3][4] - coeff*lhs[1][4]; c[3][0] = c[3][0] - coeff*c[1][0]; c[3][1] = c[3][1] - coeff*c[1][1]; c[3][2] = c[3][2] - coeff*c[1][2]; c[3][3] = c[3][3] - coeff*c[1][3]; c[3][4] = c[3][4] - coeff*c[1][4]; r[3] = r[3] - coeff*r[1]; coeff = lhs[4][1]; lhs[4][2]= lhs[4][2] - coeff*lhs[1][2]; lhs[4][3]= lhs[4][3] - coeff*lhs[1][3]; lhs[4][4]= lhs[4][4] - coeff*lhs[1][4]; c[4][0] = c[4][0] - coeff*c[1][0]; c[4][1] = c[4][1] - coeff*c[1][1]; c[4][2] = c[4][2] - coeff*c[1][2]; c[4][3] = c[4][3] - coeff*c[1][3]; c[4][4] = c[4][4] - coeff*c[1][4]; r[4] = r[4] - coeff*r[1]; pivot = 1.00/lhs[2][2]; lhs[2][3] = lhs[2][3]*pivot; lhs[2][4] = lhs[2][4]*pivot; c[2][0] = c[2][0]*pivot; c[2][1] = c[2][1]*pivot; c[2][2] = c[2][2]*pivot; c[2][3] = c[2][3]*pivot; c[2][4] = c[2][4]*pivot; r[2] = r[2] *pivot; coeff = lhs[0][2]; lhs[0][3]= lhs[0][3] - coeff*lhs[2][3]; lhs[0][4]= lhs[0][4] - coeff*lhs[2][4]; c[0][0] = c[0][0] - coeff*c[2][0]; c[0][1] = c[0][1] - coeff*c[2][1]; c[0][2] = c[0][2] - coeff*c[2][2]; c[0][3] = c[0][3] - coeff*c[2][3]; c[0][4] = c[0][4] - coeff*c[2][4]; r[0] = r[0] - coeff*r[2]; coeff = lhs[1][2]; lhs[1][3]= lhs[1][3] - coeff*lhs[2][3]; lhs[1][4]= lhs[1][4] - coeff*lhs[2][4]; c[1][0] = c[1][0] - coeff*c[2][0]; c[1][1] = c[1][1] - coeff*c[2][1]; c[1][2] = c[1][2] - coeff*c[2][2]; c[1][3] = c[1][3] - coeff*c[2][3]; c[1][4] = c[1][4] - coeff*c[2][4]; r[1] = r[1] - coeff*r[2]; coeff = lhs[3][2]; lhs[3][3]= lhs[3][3] - coeff*lhs[2][3]; lhs[3][4]= lhs[3][4] - coeff*lhs[2][4]; c[3][0] = c[3][0] - coeff*c[2][0]; c[3][1] = c[3][1] - coeff*c[2][1]; c[3][2] = c[3][2] - coeff*c[2][2]; c[3][3] = c[3][3] - coeff*c[2][3]; c[3][4] = c[3][4] - coeff*c[2][4]; r[3] = r[3] - coeff*r[2]; coeff = lhs[4][2]; lhs[4][3]= lhs[4][3] - coeff*lhs[2][3]; lhs[4][4]= lhs[4][4] - coeff*lhs[2][4]; c[4][0] = c[4][0] - coeff*c[2][0]; c[4][1] = c[4][1] - coeff*c[2][1]; c[4][2] = c[4][2] - coeff*c[2][2]; c[4][3] = c[4][3] - coeff*c[2][3]; c[4][4] = c[4][4] - coeff*c[2][4]; r[4] = r[4] - coeff*r[2]; pivot = 1.00/lhs[3][3]; lhs[3][4] = lhs[3][4]*pivot; c[3][0] = c[3][0]*pivot; c[3][1] = c[3][1]*pivot; c[3][2] = c[3][2]*pivot; c[3][3] = c[3][3]*pivot; c[3][4] = c[3][4]*pivot; r[3] = r[3] *pivot; coeff = lhs[0][3]; lhs[0][4]= lhs[0][4] - coeff*lhs[3][4]; c[0][0] = c[0][0] - coeff*c[3][0]; c[0][1] = c[0][1] - coeff*c[3][1]; c[0][2] = c[0][2] - coeff*c[3][2]; c[0][3] = c[0][3] - coeff*c[3][3]; c[0][4] = c[0][4] - coeff*c[3][4]; r[0] = r[0] - coeff*r[3]; coeff = lhs[1][3]; lhs[1][4]= lhs[1][4] - coeff*lhs[3][4]; c[1][0] = c[1][0] - coeff*c[3][0]; c[1][1] = c[1][1] - coeff*c[3][1]; c[1][2] = c[1][2] - coeff*c[3][2]; c[1][3] = c[1][3] - coeff*c[3][3]; c[1][4] = c[1][4] - coeff*c[3][4]; r[1] = r[1] - coeff*r[3]; coeff = lhs[2][3]; lhs[2][4]= lhs[2][4] - coeff*lhs[3][4]; c[2][0] = c[2][0] - coeff*c[3][0]; c[2][1] = c[2][1] - coeff*c[3][1]; c[2][2] = c[2][2] - coeff*c[3][2]; c[2][3] = c[2][3] - coeff*c[3][3]; c[2][4] = c[2][4] - coeff*c[3][4]; r[2] = r[2] - coeff*r[3]; coeff = lhs[4][3]; lhs[4][4]= lhs[4][4] - coeff*lhs[3][4]; c[4][0] = c[4][0] - coeff*c[3][0]; c[4][1] = c[4][1] - coeff*c[3][1]; c[4][2] = c[4][2] - coeff*c[3][2]; c[4][3] = c[4][3] - coeff*c[3][3]; c[4][4] = c[4][4] - coeff*c[3][4]; r[4] = r[4] - coeff*r[3]; pivot = 1.00/lhs[4][4]; c[4][0] = c[4][0]*pivot; c[4][1] = c[4][1]*pivot; c[4][2] = c[4][2]*pivot; c[4][3] = c[4][3]*pivot; c[4][4] = c[4][4]*pivot; r[4] = r[4] *pivot; coeff = lhs[0][4]; c[0][0] = c[0][0] - coeff*c[4][0]; c[0][1] = c[0][1] - coeff*c[4][1]; c[0][2] = c[0][2] - coeff*c[4][2]; c[0][3] = c[0][3] - coeff*c[4][3]; c[0][4] = c[0][4] - coeff*c[4][4]; r[0] = r[0] - coeff*r[4]; coeff = lhs[1][4]; c[1][0] = c[1][0] - coeff*c[4][0]; c[1][1] = c[1][1] - coeff*c[4][1]; c[1][2] = c[1][2] - coeff*c[4][2]; c[1][3] = c[1][3] - coeff*c[4][3]; c[1][4] = c[1][4] - coeff*c[4][4]; r[1] = r[1] - coeff*r[4]; coeff = lhs[2][4]; c[2][0] = c[2][0] - coeff*c[4][0]; c[2][1] = c[2][1] - coeff*c[4][1]; c[2][2] = c[2][2] - coeff*c[4][2]; c[2][3] = c[2][3] - coeff*c[4][3]; c[2][4] = c[2][4] - coeff*c[4][4]; r[2] = r[2] - coeff*r[4]; coeff = lhs[3][4]; c[3][0] = c[3][0] - coeff*c[4][0]; c[3][1] = c[3][1] - coeff*c[4][1]; c[3][2] = c[3][2] - coeff*c[4][2]; c[3][3] = c[3][3] - coeff*c[4][3]; c[3][4] = c[3][4] - coeff*c[4][4]; r[3] = r[3] - coeff*r[4]; } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void binvrhs( double lhs[5][5], double r[5] ) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ double pivot, coeff; /*-------------------------------------------------------------------- c c-------------------------------------------------------------------*/ pivot = 1.00/lhs[0][0]; lhs[0][1] = lhs[0][1]*pivot; lhs[0][2] = lhs[0][2]*pivot; lhs[0][3] = lhs[0][3]*pivot; lhs[0][4] = lhs[0][4]*pivot; r[0] = r[0] *pivot; coeff = lhs[1][0]; lhs[1][1]= lhs[1][1] - coeff*lhs[0][1]; lhs[1][2]= lhs[1][2] - coeff*lhs[0][2]; lhs[1][3]= lhs[1][3] - coeff*lhs[0][3]; lhs[1][4]= lhs[1][4] - coeff*lhs[0][4]; r[1] = r[1] - coeff*r[0]; coeff = lhs[2][0]; lhs[2][1]= lhs[2][1] - coeff*lhs[0][1]; lhs[2][2]= lhs[2][2] - coeff*lhs[0][2]; lhs[2][3]= lhs[2][3] - coeff*lhs[0][3]; lhs[2][4]= lhs[2][4] - coeff*lhs[0][4]; r[2] = r[2] - coeff*r[0]; coeff = lhs[3][0]; lhs[3][1]= lhs[3][1] - coeff*lhs[0][1]; lhs[3][2]= lhs[3][2] - coeff*lhs[0][2]; lhs[3][3]= lhs[3][3] - coeff*lhs[0][3]; lhs[3][4]= lhs[3][4] - coeff*lhs[0][4]; r[3] = r[3] - coeff*r[0]; coeff = lhs[4][0]; lhs[4][1]= lhs[4][1] - coeff*lhs[0][1]; lhs[4][2]= lhs[4][2] - coeff*lhs[0][2]; lhs[4][3]= lhs[4][3] - coeff*lhs[0][3]; lhs[4][4]= lhs[4][4] - coeff*lhs[0][4]; r[4] = r[4] - coeff*r[0]; pivot = 1.00/lhs[1][1]; lhs[1][2] = lhs[1][2]*pivot; lhs[1][3] = lhs[1][3]*pivot; lhs[1][4] = lhs[1][4]*pivot; r[1] = r[1] *pivot; coeff = lhs[0][1]; lhs[0][2]= lhs[0][2] - coeff*lhs[1][2]; lhs[0][3]= lhs[0][3] - coeff*lhs[1][3]; lhs[0][4]= lhs[0][4] - coeff*lhs[1][4]; r[0] = r[0] - coeff*r[1]; coeff = lhs[2][1]; lhs[2][2]= lhs[2][2] - coeff*lhs[1][2]; lhs[2][3]= lhs[2][3] - coeff*lhs[1][3]; lhs[2][4]= lhs[2][4] - coeff*lhs[1][4]; r[2] = r[2] - coeff*r[1]; coeff = lhs[3][1]; lhs[3][2]= lhs[3][2] - coeff*lhs[1][2]; lhs[3][3]= lhs[3][3] - coeff*lhs[1][3]; lhs[3][4]= lhs[3][4] - coeff*lhs[1][4]; r[3] = r[3] - coeff*r[1]; coeff = lhs[4][1]; lhs[4][2]= lhs[4][2] - coeff*lhs[1][2]; lhs[4][3]= lhs[4][3] - coeff*lhs[1][3]; lhs[4][4]= lhs[4][4] - coeff*lhs[1][4]; r[4] = r[4] - coeff*r[1]; pivot = 1.00/lhs[2][2]; lhs[2][3] = lhs[2][3]*pivot; lhs[2][4] = lhs[2][4]*pivot; r[2] = r[2] *pivot; coeff = lhs[0][2]; lhs[0][3]= lhs[0][3] - coeff*lhs[2][3]; lhs[0][4]= lhs[0][4] - coeff*lhs[2][4]; r[0] = r[0] - coeff*r[2]; coeff = lhs[1][2]; lhs[1][3]= lhs[1][3] - coeff*lhs[2][3]; lhs[1][4]= lhs[1][4] - coeff*lhs[2][4]; r[1] = r[1] - coeff*r[2]; coeff = lhs[3][2]; lhs[3][3]= lhs[3][3] - coeff*lhs[2][3]; lhs[3][4]= lhs[3][4] - coeff*lhs[2][4]; r[3] = r[3] - coeff*r[2]; coeff = lhs[4][2]; lhs[4][3]= lhs[4][3] - coeff*lhs[2][3]; lhs[4][4]= lhs[4][4] - coeff*lhs[2][4]; r[4] = r[4] - coeff*r[2]; pivot = 1.00/lhs[3][3]; lhs[3][4] = lhs[3][4]*pivot; r[3] = r[3] *pivot; coeff = lhs[0][3]; lhs[0][4]= lhs[0][4] - coeff*lhs[3][4]; r[0] = r[0] - coeff*r[3]; coeff = lhs[1][3]; lhs[1][4]= lhs[1][4] - coeff*lhs[3][4]; r[1] = r[1] - coeff*r[3]; coeff = lhs[2][3]; lhs[2][4]= lhs[2][4] - coeff*lhs[3][4]; r[2] = r[2] - coeff*r[3]; coeff = lhs[4][3]; lhs[4][4]= lhs[4][4] - coeff*lhs[3][4]; r[4] = r[4] - coeff*r[3]; pivot = 1.00/lhs[4][4]; r[4] = r[4] *pivot; coeff = lhs[0][4]; r[0] = r[0] - coeff*r[4]; coeff = lhs[1][4]; r[1] = r[1] - coeff*r[4]; coeff = lhs[2][4]; r[2] = r[2] - coeff*r[4]; coeff = lhs[3][4]; r[3] = r[3] - coeff*r[4]; } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void y_solve(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c Performs line solves in Y direction by first factoring c the block-tridiagonal matrix into an upper triangular matrix][ c and then performing back substitution to solve for the unknow c vectors of each line. c c Make sure we treat elements zero to cell_size in the direction c of the sweep. c-------------------------------------------------------------------*/ lhsy(); y_solve_cell(); y_backsubstitute(); } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void y_backsubstitute(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c back solve: if last cell][ then generate U(jsize)=rhs(jsize) c else assume U(jsize) is loaded in un pack backsub_info c so just use it c after call u(jstart) will be sent to next cell c-------------------------------------------------------------------*/ int i, j, k, m, n; for (j = grid_points[1]-2; j >= 0; j--) { #pragma omp for for (i = 1; i < grid_points[0]-1; i++) { #pragma omp parallel for firstprivate(m ,k ,n ,i ,j ) for (k = 1; k < grid_points[2]-1; k++) { #pragma omp parallel for firstprivate(m ,k ,n ,i ,j ) for (m = 0; m < BLOCK_SIZE; m++) { for (n = 0; n < BLOCK_SIZE; n++) { rhs[i][j][k][m] = rhs[i][j][k][m] - lhs[i][j][k][CC][m][n]*rhs[i][j+1][k][n]; } } } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void y_solve_cell(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c performs guaussian elimination on this cell. c c assumes that unpacking routines for non-first cells c preload C' and rhs' from previous cell. c c assumed send happens outside this routine, but that c c'(JMAX) and rhs'(JMAX) will be sent to next cell c-------------------------------------------------------------------*/ int i, j, k, jsize; jsize = grid_points[1]-1; #pragma omp for for (i = 1; i < grid_points[0]-1; i++) { for (k = 1; k < grid_points[2]-1; k++) { /*-------------------------------------------------------------------- c multiply c(i,0,k) by b_inverse and copy back to c c multiply rhs(0) by b_inverse(0) and copy to rhs c-------------------------------------------------------------------*/ binvcrhs( lhs[i][0][k][BB], lhs[i][0][k][CC], rhs[i][0][k] ); } } /*-------------------------------------------------------------------- c begin inner most do loop c do all the elements of the cell unless last c-------------------------------------------------------------------*/ for (j = 1; j < jsize; j++) { #pragma omp for for (i = 1; i < grid_points[0]-1; i++) { for (k = 1; k < grid_points[2]-1; k++) { /*-------------------------------------------------------------------- c subtract A*lhs_vector(j-1) from lhs_vector(j) c c rhs(j) = rhs(j) - A*rhs(j-1) c-------------------------------------------------------------------*/ matvec_sub(lhs[i][j][k][AA], rhs[i][j-1][k], rhs[i][j][k]); /*-------------------------------------------------------------------- c B(j) = B(j) - C(j-1)*A(j) c-------------------------------------------------------------------*/ matmul_sub(lhs[i][j][k][AA], lhs[i][j-1][k][CC], lhs[i][j][k][BB]); /*-------------------------------------------------------------------- c multiply c(i,j,k) by b_inverse and copy back to c c multiply rhs(i,1,k) by b_inverse(i,1,k) and copy to rhs c-------------------------------------------------------------------*/ binvcrhs( lhs[i][j][k][BB], lhs[i][j][k][CC], rhs[i][j][k] ); } } } #pragma omp for for (i = 1; i < grid_points[0]-1; i++) { for (k = 1; k < grid_points[2]-1; k++) { /*-------------------------------------------------------------------- c rhs(jsize) = rhs(jsize) - A*rhs(jsize-1) c-------------------------------------------------------------------*/ matvec_sub(lhs[i][jsize][k][AA], rhs[i][jsize-1][k], rhs[i][jsize][k]); /*-------------------------------------------------------------------- c B(jsize) = B(jsize) - C(jsize-1)*A(jsize) c call matmul_sub(aa,i,jsize,k,c, c $ cc,i,jsize-1,k,c,BB,i,jsize,k) c-------------------------------------------------------------------*/ matmul_sub(lhs[i][jsize][k][AA], lhs[i][jsize-1][k][CC], lhs[i][jsize][k][BB]); /*-------------------------------------------------------------------- c multiply rhs(jsize) by b_inverse(jsize) and copy to rhs c-------------------------------------------------------------------*/ binvrhs( lhs[i][jsize][k][BB], rhs[i][jsize][k] ); } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void z_solve(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c Performs line solves in Z direction by first factoring c the block-tridiagonal matrix into an upper triangular matrix, c and then performing back substitution to solve for the unknow c vectors of each line. c c Make sure we treat elements zero to cell_size in the direction c of the sweep. c-------------------------------------------------------------------*/ lhsz(); z_solve_cell(); z_backsubstitute(); } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void z_backsubstitute(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c back solve: if last cell, then generate U(ksize)=rhs(ksize) c else assume U(ksize) is loaded in un pack backsub_info c so just use it c after call u(kstart) will be sent to next cell c-------------------------------------------------------------------*/ int i, j, k, m, n; #pragma omp for for (i = 1; i < grid_points[0]-1; i++) { #pragma omp parallel for firstprivate(m ,j ,k ,n ,i ) for (j = 1; j < grid_points[1]-1; j++) { for (k = grid_points[2]-2; k >= 0; k--) { for (m = 0; m < BLOCK_SIZE; m++) { for (n = 0; n < BLOCK_SIZE; n++) { rhs[i][j][k][m] = rhs[i][j][k][m] - lhs[i][j][k][CC][m][n]*rhs[i][j][k+1][n]; } } } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void z_solve_cell(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c performs guaussian elimination on this cell. c c assumes that unpacking routines for non-first cells c preload C' and rhs' from previous cell. c c assumed send happens outside this routine, but that c c'(KMAX) and rhs'(KMAX) will be sent to next cell. c-------------------------------------------------------------------*/ int i,j,k,ksize; ksize = grid_points[2]-1; /*-------------------------------------------------------------------- c outer most do loops - sweeping in i direction c-------------------------------------------------------------------*/ #pragma omp for for (i = 1; i < grid_points[0]-1; i++) { for (j = 1; j < grid_points[1]-1; j++) { /*-------------------------------------------------------------------- c multiply c(i,j,0) by b_inverse and copy back to c c multiply rhs(0) by b_inverse(0) and copy to rhs c-------------------------------------------------------------------*/ binvcrhs( lhs[i][j][0][BB], lhs[i][j][0][CC], rhs[i][j][0] ); } } /*-------------------------------------------------------------------- c begin inner most do loop c do all the elements of the cell unless last c-------------------------------------------------------------------*/ for (k = 1; k < ksize; k++) { #pragma omp for for (i = 1; i < grid_points[0]-1; i++) { for (j = 1; j < grid_points[1]-1; j++) { /*-------------------------------------------------------------------- c subtract A*lhs_vector(k-1) from lhs_vector(k) c c rhs(k) = rhs(k) - A*rhs(k-1) c-------------------------------------------------------------------*/ matvec_sub(lhs[i][j][k][AA], rhs[i][j][k-1], rhs[i][j][k]); /*-------------------------------------------------------------------- c B(k) = B(k) - C(k-1)*A(k) c call matmul_sub(aa,i,j,k,c,cc,i,j,k-1,c,BB,i,j,k) c-------------------------------------------------------------------*/ matmul_sub(lhs[i][j][k][AA], lhs[i][j][k-1][CC], lhs[i][j][k][BB]); /*-------------------------------------------------------------------- c multiply c(i,j,k) by b_inverse and copy back to c c multiply rhs(i,j,1) by b_inverse(i,j,1) and copy to rhs c-------------------------------------------------------------------*/ binvcrhs( lhs[i][j][k][BB], lhs[i][j][k][CC], rhs[i][j][k] ); } } } /*-------------------------------------------------------------------- c Now finish up special cases for last cell c-------------------------------------------------------------------*/ #pragma omp for for (i = 1; i < grid_points[0]-1; i++) { for (j = 1; j < grid_points[1]-1; j++) { /*-------------------------------------------------------------------- c rhs(ksize) = rhs(ksize) - A*rhs(ksize-1) c-------------------------------------------------------------------*/ matvec_sub(lhs[i][j][ksize][AA], rhs[i][j][ksize-1], rhs[i][j][ksize]); /*-------------------------------------------------------------------- c B(ksize) = B(ksize) - C(ksize-1)*A(ksize) c call matmul_sub(aa,i,j,ksize,c, c $ cc,i,j,ksize-1,c,BB,i,j,ksize) c-------------------------------------------------------------------*/ matmul_sub(lhs[i][j][ksize][AA], lhs[i][j][ksize-1][CC], lhs[i][j][ksize][BB]); /*-------------------------------------------------------------------- c multiply rhs(ksize) by b_inverse(ksize) and copy to rhs c-------------------------------------------------------------------*/ binvrhs( lhs[i][j][ksize][BB], rhs[i][j][ksize] ); } } }
benchmarking.c
/** * @brief find a number of points and measure how long it takes on the avaliable core * */ void run_benchmark( double *points_ratio, instance_t *instance, uint64_t target_number_of_points) { #ifdef RUN_ACTUAL_BENCHMARKING double total_time = 0.; double *benchmark; shared_state_t benchmark_S; #ifdef STORE_IN_DATABASE db_settings_t db_settings = load_db_settings(); #endif // Init a state from an instance, and set the number of threads to 1 benchmark_S = init_shared_state(instance #ifdef STORE_IN_DATABASE , &db_settings #endif ); benchmark_S.N_OF_CORES = 1; // Stop at a certain number of distinguished points! #if !(defined(VOW_SIKE) || defined(VOW_SIDH)) prng_state_t prng_state; init_prng(&prng_state, benchmark_S.PRNG_SEED); sample_prng(&prng_state, benchmark_S.image.bytes, (unsigned long)benchmark_S.NBYTES_STATE); fix_overflow(&benchmark_S.image, benchmark_S.NBYTES_STATE, benchmark_S.NBITS_OVERFLOW); #endif // Run benchmark // Explicitly disable dynamic teams omp_set_dynamic(0); // Allocate memory for benchmark benchmark = (double *)malloc(instance->N_OF_CORES * sizeof(double)); if (benchmark == NULL) { fprintf(stderr, "error: could not allocate memory for the benchmarks"); assert(0); } // run benchmark on each core #pragma omp parallel num_threads(instance->N_OF_CORES) { int thread_id = omp_get_thread_num(); bool success; private_state_t private_state = init_private_state(&benchmark_S); initialize_private_memory(&benchmark_S, &private_state); trip_t t = init_trip(private_state.NWORDS_STATE); double wall_time = omp_get_wtime(); for (uint64_t i = 0; i < target_number_of_points; i++) { (void)vOW_one_iteration(&benchmark_S, &private_state, &t, &success, 1.); } wall_time = omp_get_wtime() - wall_time; // Save result benchmark[thread_id] = wall_time; #pragma omp atomic total_time += wall_time; // Free memory free_trip(&t); cleanup_private_memory(&private_state); free_private_state(&private_state); } // Send benchmark information to database and recover ratios #ifdef STORE_IN_DATABASE fprintf(stderr, "error: rrprf_from_benchmark not implemented\n"); #else for (uint64_t i = 0; i < instance->N_OF_CORES; i++) { points_ratio[i] = benchmark[i] / total_time; } #endif // Free benchmark_S without freeing the buffers free(benchmark); free_shared_state(&benchmark_S); #else (void)target_number_of_points; for (uint64_t i = 0; i < instance->N_OF_CORES; i++) { points_ratio[i] = 1. / (double)instance->N_OF_CORES; } #endif }
omp_cgemm_batch.c
/** * @file omp_cgemm_batch.c * * @brief BBLAS gemm_batch float _Complex routine. * * BBLAS is a software package provided by Univ. of Manchester, * Univ. of Tennessee. * * @version 1.0.0 * @author Samuel D. Relton * @author Pedro V. Lara * @author Mawussi Zounon * @date 2016-02-20 * **/ #ifndef DOXYGEN_SHOULD_SKIP_THIS /** * Code generation * @generated from ./bblas_omp/omp_zgemm_batch.c normal z -> c, Mon Jun 6 09:44:14 2016 **/ #endif #include<cblas.h> #include "bblas_comp.h" #include "bblas.h" #include <omp.h> #define COMPLEX /** Purpose ------- <b>omp_cgemm_batch</b> is an OpenMP version of cgemm_batch. It performs the matrix-matrix operations arrayC[i] = alpha[i]*op( arrayA[i] )*op( arrayB[i] ) + beta[i]*arrayC[i], where op( X ) is one of op( X ) = X or op( X ) = X**T or op( X ) = X**H, alpha[i] and beta[i] are scalars, and arrayA[i], arrayB[i] and C are matrices, with op( arrayA[i] ) an m by k matrix, op( arrayB[i] ) a k by n matrix and arrayC[i] an m by n matrix. Fixed and Variable Batch Operations ----------------------------------- Two types of batch operation are supported depending upon the value of batch_opts. When <tt>batch_opts = BBLAS_VARIABLE</tt> - all parameters that are arrays must have length at least batch_count. - all parameters that are arrays must have all values set. When <tt>batch_opts = BBLAS_FIXED</tt> - all parameters that are arrays (except for arrayA, arrayB, arrayC, and info) must have length at least one. - all parameters that are arrays (except for arrayA, arrayB, arrayC, and info) need only to have their first value set. This means that for a <tt>BBLAS_FIXED</tt> batch, the values of transA[0], transB[0], M[0], N[0], K[0], alpha[0], beta[0], lda[0], ldb[0], and ldc[0] are used for all computations. Parameters ---------- @param[in] transA Array of <tt>enum BBLAS_TRANS</tt>. On entry, transA[i] specifies the form of op( arrayA[i] ) to be used in the matrix multiplication as follows: - = BblasNoTrans: op( arrayA[i] ) = arrayA[i]. - = BblasTrans: op( arrayA[i] ) = arrayA[i]**T. - = BblasConjTrans: op( arrayA[i] ) = arrayA[i]**H. @param[in] transB Array of <tt>enum BBLAS_TRANS</tt>. On entry, transB[i] specifies the form of op( arrayB[i] ) to be used in the matrix multiplication as follows: - = BblasNoTrans: op( arrayB[i] ) = arrayB[i]. - = BblasTrans: op( arrayB[i] ) = arrayB[i]**T. - = BblasConjTrans: op( arrayB[i] ) = arrayB[i]**H. @param[in] M Array of <tt>int</tt>. Each element M[i] specifies the number of rows of the matrix op( arrayA[i] ) and of the matrix arrayC[i]. M[i] must be greater than zero. @param[in] N Array of <tt>int</tt>. Each element N[i] specifies the number of columns of the matrix op( arrayB[i] ) and the number of columns of the matrix arrayC[i]. N[i] must be greater than zero. @param[in] K Array of <tt>int</tt>. Each element K[i] specifies the number of columns of the matrix op( arrayA[i] ) and the number of rows of the matrix op( arrayB[i] ). K[i] must be greater than zero. @param[in] alpha Array of <tt>complex_16</tt>. @param[in] arrayA Array of pointers. Each element arrayA[i] is a pointer to a COMPLEX matrix of dimension lda[i] by Ka[i], where Ka[i] is K[i] when transA[i] = BblasNoTrans, and is M[i] otherwise. When using transA[i] = BblasNoTrans the leading M[i] by K[i] part of arrayA[i] must contain the matrix elements, otherwise the leading K[i] by M[i] part of arrayA[i] must contain the matrix elements. @param[in] lda Array of <tt>int</tt>. Each element lda[i] specifies the first dimension of arrayA[i] as declared in the calling (sub) program. When transA[i] = BblasNoTrans then lda[i] must be at least max( 1, M[i] ), otherwise lda[i] must be at least max( 1, K[i] ). @param[in] arrayB Array of pointers. Each element arrayB[i] is a pointer to a COMPLEX matrix of dimension ldb[i] by Kb[i], where Kb[i] is N[i] when transB[i] = BblasNoTrans, and is K[i] otherwise. When using transB[i] = BblasNoTrans the leading K[i] by N[i] part of arrayB[i] must contain the matrix elements, otherwise the leading N[i] by K[i] part of arrayB[i] must contain the matrix elements. @param[in] ldb Array of <tt>int</tt>. Each element ldb[i] specifies the first dimension of arrayB[i] as declared in the calling (sub) program. When transB[i] = BblasNoTrans then ldb[i] must be at least max( 1, K[i] ), otherwise ldb[i] must be at least max( 1, N[i] ). @param[in] beta Array of <tt>complex_16</tt>. When beta[i] is set to zero arrayC[i] need not be set on input. @param[in,out] arrayC Array of pointers. Each element arrayC[i] is a pointer to a COMPLEX matrix of dimension ldc[i] by N[i]. Before entry, the leading M[i] by N[i] part of the arrayC[i] must contain a matrix C, except when beta is zero, in which case C need not be set on entry. On exit, the matrix arrayC[i] is overwritten by the M[i] by N[i] matrix ( alpha[i]*op( arrayA[i] )*op( arrayB[i] ) + beta[i]*arrayC[i] ). @param[in] ldc Array of <tt>int</tt>. Each element ldc[i] specifies the first dimension of arrayC[i] as declared in the calling (sub) program. The value ldc[i] must be at least max( 1, M[i] ) @param[in] batch_count <tt>int</tt> The number of matrices to operate on. @param[in] batch_opts <tt>enum BBLAS_OPTS</tt> One of BBLAS_FIXED or BBLAS_VARIABLE depending upon the type of batch operation required. @param[in,out] info Array of <tt>int</tt>. Each element info[i] is the error return code of the ith cgemm in the batch, these need not be set on entry. The error codes can be found in bblas_macros.h. **/ void omp_cgemm_batch( const enum BBLAS_TRANS *transA, const enum BBLAS_TRANS *transB, const int *M, const int *N, const int *K, const BBLAS_Complex32_t *alpha, const BBLAS_Complex32_t **arrayA, const int *lda, const BBLAS_Complex32_t **arrayB, const int *ldb, const BBLAS_Complex32_t *beta, BBLAS_Complex32_t **arrayC, const int *ldc, const int batch_count, enum BBLAS_OPTS batch_opts, int *info) { /*Local variables */ int first_index = 0; int LDA, LDB, batch_iter; char func_name[15] = "cgemm_batch"; /* Check input arguments */ if (batch_count < 0) { xerbla_batch(func_name, BBLAS_ERR_BATCH_COUNT, -1); } if (batch_opts == BBLAS_FIXED) { if ((transA[first_index] != BblasNoTrans) && (transA[first_index] != BblasTrans) && (transA[first_index] != BblasConjTrans)) { xerbla_batch(func_name, BBLAS_ERR_TRANSA, first_index); for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { info[batch_iter] = BBLAS_ERR_TRANSA; } return; } if ((transB[first_index] != BblasNoTrans) && (transB[first_index] != BblasTrans) && (transB[first_index] != BblasConjTrans)) { xerbla_batch(func_name, BBLAS_ERR_TRANSB, first_index); for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { info[batch_iter] = BBLAS_ERR_TRANSB; } return; } if ( transA[first_index] == BblasNoTrans ) { LDA = M[first_index]; } else { LDA = K[first_index]; } if ( transB[first_index] == BblasNoTrans ) { LDB = K[first_index]; } else { LDB = N[first_index]; } if (M[first_index] < 0) { xerbla_batch(func_name, BBLAS_ERR_M, first_index); for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { info[batch_iter] = BBLAS_ERR_M; } return; } if (N[first_index] < 0) { xerbla_batch(func_name, BBLAS_ERR_N, first_index); for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { info[batch_iter] = BBLAS_ERR_N; } return; } if (K[first_index] < 0) { xerbla_batch(func_name, BBLAS_ERR_K, first_index); for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { info[batch_iter] = BBLAS_ERR_K; } return; } if (lda[first_index] < max(1, LDA)) { xerbla_batch(func_name, BBLAS_ERR_LDA, first_index); for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { info[batch_iter] = BBLAS_ERR_LDA; } return; } if (ldb[first_index] < max(1, LDB)) { xerbla_batch(func_name, BBLAS_ERR_LDB, first_index); for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { info[batch_iter] = BBLAS_ERR_LDB; } return; } if (ldc[first_index] < max(1, M[first_index])) { xerbla_batch(func_name, BBLAS_ERR_LDC, first_index); for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { info[batch_iter] = BBLAS_ERR_LDC; } return; } /* particular case */ if (M[first_index] == 0 || N[first_index] == 0 || ((alpha[first_index] == (BBLAS_Complex32_t)0.0 || K[first_index] == 0) && beta[first_index] == (BBLAS_Complex32_t)1.0 )) { for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { info[batch_iter] = BBLAS_SUCCESS; } return; } #pragma omp parallel for for (int batch_iter_omp = 0; batch_iter_omp < batch_count; batch_iter_omp++) { /*Call to cblas_cgemm */ cblas_cgemm( BblasColMajor, transA[first_index], transB[first_index], M[first_index], N[first_index], K[first_index], CBLAS_SADDR(alpha[first_index]), arrayA[batch_iter_omp], lda[first_index], arrayB[batch_iter_omp], ldb[first_index], CBLAS_SADDR(beta[first_index]), arrayC[batch_iter_omp], ldc[first_index]); /* Successful */ info[batch_iter_omp] = BBLAS_SUCCESS; } /*END FIXED SIZE FOR LOOP */ }else if (batch_opts == BBLAS_VARIABLE) { #pragma omp parallel for private(LDA, LDB) for (int batch_iter_omp = 0; batch_iter_omp < batch_count; batch_iter_omp++) { /* Check input arguments */ if ((transA[batch_iter_omp] != BblasNoTrans) && (transA[batch_iter_omp] != BblasTrans) && (transA[batch_iter_omp] != BblasConjTrans)) { xerbla_batch(func_name, BBLAS_ERR_TRANSA, batch_iter_omp); info[batch_iter_omp] = BBLAS_ERR_TRANSA; continue; } if ((transB[batch_iter_omp] != BblasNoTrans) && (transB[batch_iter_omp] != BblasTrans) && (transB[batch_iter_omp] != BblasConjTrans)) { xerbla_batch(func_name, BBLAS_ERR_TRANSB, batch_iter_omp); info[batch_iter_omp] = BBLAS_ERR_TRANSB; continue; } if (transA[batch_iter_omp] == BblasNoTrans) { LDA = M[batch_iter_omp]; } else { LDA = K[batch_iter_omp]; } if (transB[batch_iter_omp] == BblasNoTrans) { LDB = K[batch_iter_omp]; } else { LDB = N[batch_iter_omp]; } if (M[batch_iter_omp] < 0) { xerbla_batch(func_name, BBLAS_ERR_M, batch_iter_omp); info[batch_iter_omp] = BBLAS_ERR_M; continue; } if (N[batch_iter_omp] < 0) { xerbla_batch(func_name, BBLAS_ERR_N, batch_iter_omp); info[batch_iter_omp] = BBLAS_ERR_N; continue; } if (K[batch_iter_omp] < 0) { xerbla_batch(func_name, BBLAS_ERR_K, batch_iter_omp); info[batch_iter_omp] = BBLAS_ERR_K; continue; } if (lda[batch_iter_omp] < max(1, LDA)) { xerbla_batch(func_name, BBLAS_ERR_LDA, batch_iter_omp); info[batch_iter_omp] = BBLAS_ERR_LDA; continue; } if (ldb[batch_iter_omp] < max(1, LDB)) { xerbla_batch(func_name, BBLAS_ERR_LDB, batch_iter_omp); info[batch_iter_omp] = BBLAS_ERR_LDB; continue; } if (ldc[batch_iter_omp] < max(1, M[batch_iter_omp])) { xerbla_batch(func_name, BBLAS_ERR_LDC, batch_iter_omp); info[batch_iter_omp] = BBLAS_ERR_LDC; continue; } /* particular case */ if (M[batch_iter_omp] == 0 || N[batch_iter_omp] == 0 || ((alpha[batch_iter_omp] == (BBLAS_Complex32_t)0.0 || K[batch_iter_omp] == 0) && beta[batch_iter_omp] == (BBLAS_Complex32_t)1.0)) { info[batch_iter_omp] = BBLAS_SUCCESS; continue; } cblas_cgemm( BblasColMajor, transA[batch_iter_omp], transB[batch_iter_omp], M[batch_iter_omp], N[batch_iter_omp], K[batch_iter_omp], CBLAS_SADDR(alpha[batch_iter_omp]), arrayA[batch_iter_omp], lda[batch_iter_omp], arrayB[batch_iter_omp], ldb[batch_iter_omp], CBLAS_SADDR(beta[batch_iter_omp]), arrayC[batch_iter_omp], ldc[batch_iter_omp]); /* Successful */ info[batch_iter_omp] = BBLAS_SUCCESS; } } else { xerbla_batch(func_name, BBLAS_ERR_BATCH_OPTS, -1); } } #undef COMPLEX
GB_unop__identity_int64_uint16.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__identity_int64_uint16) // op(A') function: GB (_unop_tran__identity_int64_uint16) // C type: int64_t // A type: uint16_t // cast: int64_t cij = (int64_t) aij // unaryop: cij = aij #define GB_ATYPE \ uint16_t #define GB_CTYPE \ int64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint16_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 = (int64_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint16_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int64_t z = (int64_t) aij ; \ Cx [pC] = z ; \ } // 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_IDENTITY || GxB_NO_INT64 || GxB_NO_UINT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_int64_uint16) ( int64_t *Cx, // Cx and Ax may be aliased const uint16_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 (uint16_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { uint16_t aij = Ax [p] ; int64_t z = (int64_t) aij ; Cx [p] = z ; } #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 ; uint16_t aij = Ax [p] ; int64_t z = (int64_t) 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_uint16) ( 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
hpgmg.c
//------------------------------------------------------------------------------------------------------------------------------ // Copyright Notice //------------------------------------------------------------------------------------------------------------------------------ // HPGMG, Copyright (c) 2014, The Regents of the University of // California, through Lawrence Berkeley National Laboratory (subject to // receipt of any required approvals from the U.S. Dept. of Energy). All // rights reserved. // // If you have questions about your rights to use or distribute this // software, please contact Berkeley Lab's Technology Transfer Department // at TTD@lbl.gov. // // NOTICE. This software is owned by the U.S. Department of Energy. As // such, the U.S. Government has been granted for itself and others // acting on its behalf a paid-up, nonexclusive, irrevocable, worldwide // license in the Software to reproduce, prepare derivative works, and // perform publicly and display publicly. Beginning five (5) years after // the date permission to assert copyright is obtained from the U.S. // Department of Energy, and subject to any subsequent five (5) year // renewals, the U.S. Government is granted for itself and others acting // on its behalf a paid-up, nonexclusive, irrevocable, worldwide license // in the Software to reproduce, prepare derivative works, distribute // copies to the public, perform publicly and display publicly, and to // permit others to do so. //------------------------------------------------------------------------------------------------------------------------------ // Samuel Williams // SWWilliams@lbl.gov // Lawrence Berkeley National Lab //------------------------------------------------------------------------------------------------------------------------------ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <math.h> //------------------------------------------------------------------------------------------------------------------------------ #include <omp.h> #ifdef USE_MPI #include <mpi.h> #endif //------------------------------------------------------------------------------------------------------------------------------ #include "defines.h" #include "level.h" #include "mg.h" #include "operators.h" #include "solvers.h" #include "marker_stub.h" //------------------------------------------------------------------------------------------------------------------------------ int main(int argc, char **argv){ int MPI_Rank=0; int MPI_Tasks=1; int OMP_Threads = 1; int OMP_Nested = 0; #pragma omp parallel { #pragma omp master { OMP_Threads = omp_get_num_threads(); OMP_Nested = omp_get_nested(); } } //omp_set_nested(1); #ifdef USE_MPI //#warning Compiling for MPI... //FIX... replace with ifdefs or env variables... int MPI_threadingModel = -1; //int MPI_threadingModelRequested = MPI_THREAD_SINGLE; //int MPI_threadingModelRequested = MPI_THREAD_SERIALIZED; int MPI_threadingModelRequested = MPI_THREAD_FUNNELED; //int MPI_threadingModelRequested = MPI_THREAD_MULTIPLE; MPI_Init_thread(&argc, &argv, MPI_threadingModelRequested, &MPI_threadingModel); MPI_Comm_size(MPI_COMM_WORLD, &MPI_Tasks); MPI_Comm_rank(MPI_COMM_WORLD, &MPI_Rank); #ifdef USE_HPM // IBM HPM counters for BGQ... HPM_Init(); #endif if(MPI_threadingModel>MPI_threadingModelRequested)MPI_threadingModel=MPI_threadingModelRequested; if(MPI_Rank==0){ MARKER_INIT; if(MPI_threadingModelRequested == MPI_THREAD_MULTIPLE )printf("Requested MPI_THREAD_MULTIPLE, "); else if(MPI_threadingModelRequested == MPI_THREAD_SINGLE )printf("Requested MPI_THREAD_SINGLE, "); else if(MPI_threadingModelRequested == MPI_THREAD_FUNNELED )printf("Requested MPI_THREAD_FUNNELED, "); else if(MPI_threadingModelRequested == MPI_THREAD_SERIALIZED)printf("Requested MPI_THREAD_SERIALIZED, "); else if(MPI_threadingModelRequested == MPI_THREAD_MULTIPLE )printf("Requested MPI_THREAD_MULTIPLE, "); else printf("Requested Unknown MPI Threading Model (%d), ",MPI_threadingModelRequested); if(MPI_threadingModel == MPI_THREAD_MULTIPLE )printf("got MPI_THREAD_MULTIPLE\n"); else if(MPI_threadingModel == MPI_THREAD_SINGLE )printf("got MPI_THREAD_SINGLE\n"); else if(MPI_threadingModel == MPI_THREAD_FUNNELED )printf("got MPI_THREAD_FUNNELED\n"); else if(MPI_threadingModel == MPI_THREAD_SERIALIZED)printf("got MPI_THREAD_SERIALIZED\n"); else if(MPI_threadingModel == MPI_THREAD_MULTIPLE )printf("got MPI_THREAD_MULTIPLE\n"); else printf("got Unknown MPI Threading Model (%d)\n",MPI_threadingModel); fflush(stdout); } #endif int log2_box_dim = 6; int target_boxes_per_rank = 1; if(argc==3){ log2_box_dim=atoi(argv[1]); target_boxes_per_rank=atoi(argv[2]); }else{ if(MPI_Rank==0){printf("usage: ./a.out [log2_box_dim] [target_boxes_per_rank]\n");} #ifdef USE_MPI MPI_Finalize(); #endif exit(0); } if(log2_box_dim<4){ if(MPI_Rank==0){printf("log2_box_dim must be at least 4\n");} #ifdef USE_MPI MPI_Finalize(); #endif exit(0); } if(target_boxes_per_rank<1){ if(MPI_Rank==0){printf("target_boxes_per_rank must be at least 1\n");} #ifdef USE_MPI MPI_Finalize(); #endif exit(0); } if(MPI_Rank==0)if(OMP_Nested)printf("%d MPI Tasks of %d threads (OMP_NESTED=TRUE)\n\n" ,MPI_Tasks,OMP_Threads); else printf("%d MPI Tasks of %d threads (OMP_NESTED=FALSE)\n\n",MPI_Tasks,OMP_Threads); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // calculate the problem size... int box_dim=1<<log2_box_dim; int target_boxes = target_boxes_per_rank*MPI_Tasks; int boxes_in_i = 1000; // FIX, int64_t? could we really have >2e9 boxes? int total_boxes = boxes_in_i*boxes_in_i*boxes_in_i; while(total_boxes>target_boxes){ boxes_in_i--; total_boxes = boxes_in_i*boxes_in_i*boxes_in_i; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // create the fine level... int ghosts=1; level_type fine_grid; //create_level(&fine_grid,boxes_in_i,box_dim,ghosts,VECTORS_RESERVED,BC_PERIODIC ,MPI_Rank,MPI_Tasks);double h0=1.0/( (double)boxes_in_i*(double)box_dim );double a=2.0;double b=1.0; // Helmholtz w/Periodic //create_level(&fine_grid,boxes_in_i,box_dim,ghosts,VECTORS_RESERVED,BC_PERIODIC ,MPI_Rank,MPI_Tasks);double h0=1.0/( (double)boxes_in_i*(double)box_dim );double a=0.0;double b=1.0; // Poisson w/Periodic //create_level(&fine_grid,boxes_in_i,box_dim,ghosts,VECTORS_RESERVED,BC_DIRICHLET,MPI_Rank,MPI_Tasks);double h0=1.0/( (double)boxes_in_i*(double)box_dim );double a=2.0;double b=1.0; // Helmholtz w/Dirichlet create_level(&fine_grid,boxes_in_i,box_dim,ghosts,VECTORS_RESERVED,BC_DIRICHLET,MPI_Rank,MPI_Tasks);double h0=1.0/( (double)boxes_in_i*(double)box_dim );double a=0.0;double b=1.0; // Poisson w/Dirichlet //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - initialize_problem(&fine_grid,h0,a,b); rebuild_operator(&fine_grid,NULL,a,b); // i.e. calculate Dinv and lambda_max //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mg_type all_grids; int minCoarseDim = 1; MGBuild(&all_grids,&fine_grid,a,b,minCoarseDim); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - MARKER_START(MPI_Rank); #if defined (USE_MPI) && defined(GEM5_MARKERS) MPI_Barrier(MPI_COMM_WORLD); #endif int doTiming;for(doTiming=0;doTiming<=0;doTiming++){ // first pass warms up, second times MGResetTimers(&all_grids); #ifdef USE_HPM // IBM performance counters for BGQ... if(doTiming)HPM_Start("FMGSolve()"); #endif #ifdef USE_FCYCLES int trial;for(trial=0;trial<3;trial++){zero_vector(all_grids.levels[0],VECTOR_U);FMGSolve(&all_grids,VECTOR_U,VECTOR_F,a,b,1e-15);} #else int trial;for(trial=0;trial<5;trial++){zero_vector(all_grids.levels[0],VECTOR_U); MGSolve(&all_grids,VECTOR_U,VECTOR_F,a,b,1e-15);} #endif #ifdef USE_HPM // IBM performance counters for BGQ... if(doTiming)HPM_Stop("FMGSolve()"); #endif } MARKER_STOP(MPI_Rank); MGPrintTiming(&all_grids); // don't include the error check in the timing results //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if(MPI_Rank==0){printf("calculating error...\n");} double fine_error = error(&fine_grid,VECTOR_U,VECTOR_UTRUE);if(MPI_Rank==0){printf(" h = %22.15e ||error|| = %22.15e\n\n",h0,fine_error);fflush(stdout);} //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // MGDestroy() //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #ifdef USE_MPI #ifdef USE_HPM // IBM performance counters for BGQ... HPM_Print(); #endif MPI_Finalize(); #endif //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - return(0); }
distance.h
#pragma once #include <utils.h> #ifdef _WINDOWS #include <immintrin.h> #include <smmintrin.h> #include <tmmintrin.h> #include <intrin.h> #else #include <immintrin.h> #endif #include <cosine_similarity.h> #include <iostream> namespace { static inline __m128 _mm_mulhi_epi8(__m128i X) { __m128i zero = _mm_setzero_si128(); __m128i sign_x = _mm_cmplt_epi8(X, zero); __m128i xhi = _mm_unpackhi_epi8(X, sign_x); return _mm_cvtepi32_ps( _mm_add_epi32(_mm_setzero_si128(), _mm_madd_epi16(xhi, xhi))); } static inline __m128 _mm_mulhi_epi8_shift32(__m128i X) { __m128i zero = _mm_setzero_si128(); X = _mm_srli_epi64(X, 32); __m128i sign_x = _mm_cmplt_epi8(X, zero); __m128i xhi = _mm_unpackhi_epi8(X, sign_x); return _mm_cvtepi32_ps( _mm_add_epi32(_mm_setzero_si128(), _mm_madd_epi16(xhi, xhi))); } static inline __m128 _mm_mul_epi8(__m128i X, __m128i Y) { __m128i zero = _mm_setzero_si128(); __m128i sign_x = _mm_cmplt_epi8(X, zero); __m128i sign_y = _mm_cmplt_epi8(Y, zero); __m128i xlo = _mm_unpacklo_epi8(X, sign_x); __m128i xhi = _mm_unpackhi_epi8(X, sign_x); __m128i ylo = _mm_unpacklo_epi8(Y, sign_y); __m128i yhi = _mm_unpackhi_epi8(Y, sign_y); return _mm_cvtepi32_ps( _mm_add_epi32(_mm_madd_epi16(xlo, ylo), _mm_madd_epi16(xhi, yhi))); } static inline __m128 _mm_mul_epi8(__m128i X) { __m128i zero = _mm_setzero_si128(); __m128i sign_x = _mm_cmplt_epi8(X, zero); __m128i xlo = _mm_unpacklo_epi8(X, sign_x); __m128i xhi = _mm_unpackhi_epi8(X, sign_x); return _mm_cvtepi32_ps( _mm_add_epi32(_mm_madd_epi16(xlo, xlo), _mm_madd_epi16(xhi, xhi))); } static inline __m128 _mm_mul32_pi8(__m128i X, __m128i Y) { __m128i xlo = _mm_cvtepi8_epi16(X), ylo = _mm_cvtepi8_epi16(Y); return _mm_cvtepi32_ps( _mm_unpacklo_epi32(_mm_madd_epi16(xlo, ylo), _mm_setzero_si128())); } static inline __m256 _mm256_mul_epi8(__m256i X, __m256i Y) { __m256i zero = _mm256_setzero_si256(); __m256i sign_x = _mm256_cmpgt_epi8(zero, X); __m256i sign_y = _mm256_cmpgt_epi8(zero, Y); __m256i xlo = _mm256_unpacklo_epi8(X, sign_x); __m256i xhi = _mm256_unpackhi_epi8(X, sign_x); __m256i ylo = _mm256_unpacklo_epi8(Y, sign_y); __m256i yhi = _mm256_unpackhi_epi8(Y, sign_y); return _mm256_cvtepi32_ps(_mm256_add_epi32(_mm256_madd_epi16(xlo, ylo), _mm256_madd_epi16(xhi, yhi))); } static inline __m256 _mm256_mul32_pi8(__m128i X, __m128i Y) { __m256i xlo = _mm256_cvtepi8_epi16(X), ylo = _mm256_cvtepi8_epi16(Y); return _mm256_blend_ps(_mm256_cvtepi32_ps(_mm256_madd_epi16(xlo, ylo)), _mm256_setzero_ps(), 252); } static inline float _mm256_reduce_add_ps(__m256 x) { /* ( x3+x7, x2+x6, x1+x5, x0+x4 ) */ const __m128 x128 = _mm_add_ps(_mm256_extractf128_ps(x, 1), _mm256_castps256_ps128(x)); /* ( -, -, x1+x3+x5+x7, x0+x2+x4+x6 ) */ const __m128 x64 = _mm_add_ps(x128, _mm_movehl_ps(x128, x128)); /* ( -, -, -, x0+x1+x2+x3+x4+x5+x6+x7 ) */ const __m128 x32 = _mm_add_ss(x64, _mm_shuffle_ps(x64, x64, 0x55)); /* Conversion to float is a no-op on x86-64 */ return _mm_cvtss_f32(x32); } } // namespace namespace diskann { // enum Metric { L2 = 0, INNER_PRODUCT = 1, FAST_L2 = 2, PQ = 3 }; template<typename T> class Distance { public: virtual float compare(const T *a, const T *b, unsigned length) const = 0; virtual ~Distance() { } }; template<typename T> class DistanceCosine : public Distance<T> { float compare(const T *a, const T *b, unsigned length) const { return diskann::compute_cosine_similarity<T>(a, b, length); } }; class DistanceL2Int8 : public Distance<int8_t> { public: float compare(const int8_t *a, const int8_t *b, unsigned size) const { int32_t result = 0; #ifdef _WINDOWS #ifdef USE_AVX2 __m256 r = _mm256_setzero_ps(); char * pX = (char *) a, *pY = (char *) b; while (size >= 32) { __m256i r1 = _mm256_subs_epi8(_mm256_loadu_si256((__m256i *) pX), _mm256_loadu_si256((__m256i *) pY)); r = _mm256_add_ps(r, _mm256_mul_epi8(r1, r1)); pX += 32; pY += 32; size -= 32; } while (size > 0) { __m128i r2 = _mm_subs_epi8(_mm_loadu_si128((__m128i *) pX), _mm_loadu_si128((__m128i *) pY)); r = _mm256_add_ps(r, _mm256_mul32_pi8(r2, r2)); pX += 4; pY += 4; size -= 4; } r = _mm256_hadd_ps(_mm256_hadd_ps(r, r), r); return r.m256_f32[0] + r.m256_f32[4]; #else #pragma omp simd reduction(+ : result) aligned(a, b : 8) for (_s32 i = 0; i < (_s32) size; i++) { result += ((int32_t)((int16_t) a[i] - (int16_t) b[i])) * ((int32_t)((int16_t) a[i] - (int16_t) b[i])); } return (float) result; #endif #else #pragma omp simd reduction(+ : result) aligned(a, b : 8) for (_s32 i = 0; i < (_s32) size; i++) { result += ((int32_t)((int16_t) a[i] - (int16_t) b[i])) * ((int32_t)((int16_t) a[i] - (int16_t) b[i])); } return (float) result; #endif } }; class DistanceL2UInt8 : public Distance<uint8_t> { public: float compare(const uint8_t *a, const uint8_t *b, unsigned size) const { uint32_t result = 0; #ifndef _WINDOWS #pragma omp simd reduction(+ : result) aligned(a, b : 8) #endif for (_s32 i = 0; i < (_s32) size; i++) { result += ((int32_t)((int16_t) a[i] - (int16_t) b[i])) * ((int32_t)((int16_t) a[i] - (int16_t) b[i])); } return (float) result; } }; class DistanceL2 : public Distance<float> { public: #ifndef _WINDOWS float compare(const float *a, const float *b, unsigned size) const __attribute__((hot)) { a = (const float *) __builtin_assume_aligned(a, 32); b = (const float *) __builtin_assume_aligned(b, 32); #else float compare(const float *a, const float *b, unsigned size) const { #endif float result = 0; #ifdef USE_AVX2 // assume size is divisible by 8 _u16 niters = size / 8; __m256 sum = _mm256_setzero_ps(); for (_u16 j = 0; j < niters; j++) { // scope is a[8j:8j+7], b[8j:8j+7] // load a_vec if (j < (niters - 1)) { _mm_prefetch((char *) (a + 8 * (j + 1)), _MM_HINT_T0); _mm_prefetch((char *) (b + 8 * (j + 1)), _MM_HINT_T0); } __m256 a_vec = _mm256_load_ps(a + 8 * j); // load b_vec __m256 b_vec = _mm256_load_ps(b + 8 * j); // a_vec - b_vec __m256 tmp_vec = _mm256_sub_ps(a_vec, b_vec); /* // (a_vec - b_vec)**2 __m256 tmp_vec2 = _mm256_mul_ps(tmp_vec, tmp_vec); // accumulate sum sum = _mm256_add_ps(sum, tmp_vec2); */ // sum = (tmp_vec**2) + sum sum = _mm256_fmadd_ps(tmp_vec, tmp_vec, sum); } // horizontal add sum result = _mm256_reduce_add_ps(sum); #else #ifndef _WINDOWS #pragma omp simd reduction(+ : result) aligned(a, b : 32) #endif for (_s32 i = 0; i < (_s32) size; i++) { result += (a[i] - b[i]) * (a[i] - b[i]); } #endif return result; } }; // Gopal. Slow implementations of the distance functions to get diskann to // work in v14 machines that do not have AVX2 support. Performance here is not // a concern, so we are using the simplest possible implementation. template<typename T> class SlowDistanceL2Int : public Distance<T> { virtual float compare(const T *a, const T *b, unsigned length) const { uint32_t result = 0; for (_u32 i = 0; i < length; i++) { result += ((int32_t)((int16_t) a[i] - (int16_t) b[i])) * ((int32_t)((int16_t) a[i] - (int16_t) b[i])); } return (float) result; } }; class SlowDistanceL2Float : public Distance<float> { virtual float compare(const float *a, const float *b, unsigned length) const { float result = 0.0f; for (_u32 i = 0; i < length; i++) { result += (a[i] - b[i]) * (a[i] - b[i]); } return result; } }; class AVXDistanceL2Int8 : public Distance<int8_t> { public: virtual float compare(const int8_t *a, const int8_t *b, unsigned int length) const { #ifndef _WINDOWS std::cout << "AVX only supported in Windows build."; return 0; } #else __m128 r = _mm_setzero_ps(); __m128i r1; while (length >= 16) { r1 = _mm_subs_epi8(_mm_load_si128((__m128i *) a), _mm_load_si128((__m128i *) b)); r = _mm_add_ps(r, _mm_mul_epi8(r1)); a += 16; b += 16; length -= 16; } r = _mm_hadd_ps(_mm_hadd_ps(r, r), r); float res = r.m128_f32[0]; if (length >= 8) { __m128 r2 = _mm_setzero_ps(); __m128i r3 = _mm_subs_epi8(_mm_load_si128((__m128i *) (a - 8)), _mm_load_si128((__m128i *) (b - 8))); r2 = _mm_add_ps(r2, _mm_mulhi_epi8(r3)); a += 8; b += 8; length -= 8; r2 = _mm_hadd_ps(_mm_hadd_ps(r2, r2), r2); res += r2.m128_f32[0]; } if (length >= 4) { __m128 r2 = _mm_setzero_ps(); __m128i r3 = _mm_subs_epi8(_mm_load_si128((__m128i *) (a - 12)), _mm_load_si128((__m128i *) (b - 12))); r2 = _mm_add_ps(r2, _mm_mulhi_epi8_shift32(r3)); res += r2.m128_f32[0] + r2.m128_f32[1]; } return res; } #endif }; class AVXDistanceL2Float : public Distance<float> { public: virtual float compare(const float *a, const float *b, unsigned int length) const { #ifndef _WINDOWS std::cout << "AVX only supported in Windows build."; return 0; } #else __m128 diff, v1, v2; __m128 sum = _mm_set1_ps(0); while (length >= 4) { v1 = _mm_loadu_ps(a); a += 4; v2 = _mm_loadu_ps(b); b += 4; diff = _mm_sub_ps(v1, v2); sum = _mm_add_ps(sum, _mm_mul_ps(diff, diff)); length -= 4; } return sum.m128_f32[0] + sum.m128_f32[1] + sum.m128_f32[2] + sum.m128_f32[3]; } #endif }; template<typename T> class DistanceInnerProduct : public Distance<T> { public: float compare(const T *a, const T *b, unsigned size) const { float result = 0; #ifdef __GNUC__ #ifdef __AVX__ #define AVX_DOT(addr1, addr2, dest, tmp1, tmp2) \ tmp1 = _mm256_loadu_ps(addr1); \ tmp2 = _mm256_loadu_ps(addr2); \ tmp1 = _mm256_mul_ps(tmp1, tmp2); \ dest = _mm256_add_ps(dest, tmp1); __m256 sum; __m256 l0, l1; __m256 r0, r1; unsigned D = (size + 7) & ~7U; unsigned DR = D % 16; unsigned DD = D - DR; const float *l = (float *) a; const float *r = (float *) b; const float *e_l = l + DD; const float *e_r = r + DD; float unpack[8] __attribute__((aligned(32))) = {0, 0, 0, 0, 0, 0, 0, 0}; sum = _mm256_loadu_ps(unpack); if (DR) { AVX_DOT(e_l, e_r, sum, l0, r0); } for (unsigned i = 0; i < DD; i += 16, l += 16, r += 16) { AVX_DOT(l, r, sum, l0, r0); AVX_DOT(l + 8, r + 8, sum, l1, r1); } _mm256_storeu_ps(unpack, sum); result = unpack[0] + unpack[1] + unpack[2] + unpack[3] + unpack[4] + unpack[5] + unpack[6] + unpack[7]; #else #ifdef __SSE2__ #define SSE_DOT(addr1, addr2, dest, tmp1, tmp2) \ tmp1 = _mm128_loadu_ps(addr1); \ tmp2 = _mm128_loadu_ps(addr2); \ tmp1 = _mm128_mul_ps(tmp1, tmp2); \ dest = _mm128_add_ps(dest, tmp1); __m128 sum; __m128 l0, l1, l2, l3; __m128 r0, r1, r2, r3; unsigned D = (size + 3) & ~3U; unsigned DR = D % 16; unsigned DD = D - DR; const float *l = a; const float *r = b; const float *e_l = l + DD; const float *e_r = r + DD; float unpack[4] __attribute__((aligned(16))) = {0, 0, 0, 0}; sum = _mm_load_ps(unpack); switch (DR) { case 12: SSE_DOT(e_l + 8, e_r + 8, sum, l2, r2); case 8: SSE_DOT(e_l + 4, e_r + 4, sum, l1, r1); case 4: SSE_DOT(e_l, e_r, sum, l0, r0); default: break; } for (unsigned i = 0; i < DD; i += 16, l += 16, r += 16) { SSE_DOT(l, r, sum, l0, r0); SSE_DOT(l + 4, r + 4, sum, l1, r1); SSE_DOT(l + 8, r + 8, sum, l2, r2); SSE_DOT(l + 12, r + 12, sum, l3, r3); } _mm_storeu_ps(unpack, sum); result += unpack[0] + unpack[1] + unpack[2] + unpack[3]; #else float dot0, dot1, dot2, dot3; const float *last = a + size; const float *unroll_group = last - 3; /* Process 4 items with each loop for efficiency. */ while (a < unroll_group) { dot0 = a[0] * b[0]; dot1 = a[1] * b[1]; dot2 = a[2] * b[2]; dot3 = a[3] * b[3]; result += dot0 + dot1 + dot2 + dot3; a += 4; b += 4; } /* Process last 0-3 pixels. Not needed for standard vector lengths. */ while (a < last) { result += *a++ * *b++; } #endif #endif #endif return result; } }; template<typename T> class DistanceFastL2 : public DistanceInnerProduct<T> { public: float norm(const T *a, unsigned size) const { float result = 0; #ifdef __GNUC__ #ifdef __AVX__ #define AVX_L2NORM(addr, dest, tmp) \ tmp = _mm256_loadu_ps(addr); \ tmp = _mm256_mul_ps(tmp, tmp); \ dest = _mm256_add_ps(dest, tmp); __m256 sum; __m256 l0, l1; unsigned D = (size + 7) & ~7U; unsigned DR = D % 16; unsigned DD = D - DR; const float *l = (float *) a; const float *e_l = l + DD; float unpack[8] __attribute__((aligned(32))) = {0, 0, 0, 0, 0, 0, 0, 0}; sum = _mm256_loadu_ps(unpack); if (DR) { AVX_L2NORM(e_l, sum, l0); } for (unsigned i = 0; i < DD; i += 16, l += 16) { AVX_L2NORM(l, sum, l0); AVX_L2NORM(l + 8, sum, l1); } _mm256_storeu_ps(unpack, sum); result = unpack[0] + unpack[1] + unpack[2] + unpack[3] + unpack[4] + unpack[5] + unpack[6] + unpack[7]; #else #ifdef __SSE2__ #define SSE_L2NORM(addr, dest, tmp) \ tmp = _mm128_loadu_ps(addr); \ tmp = _mm128_mul_ps(tmp, tmp); \ dest = _mm128_add_ps(dest, tmp); __m128 sum; __m128 l0, l1, l2, l3; unsigned D = (size + 3) & ~3U; unsigned DR = D % 16; unsigned DD = D - DR; const float *l = a; const float *e_l = l + DD; float unpack[4] __attribute__((aligned(16))) = {0, 0, 0, 0}; sum = _mm_load_ps(unpack); switch (DR) { case 12: SSE_L2NORM(e_l + 8, sum, l2); case 8: SSE_L2NORM(e_l + 4, sum, l1); case 4: SSE_L2NORM(e_l, sum, l0); default: break; } for (unsigned i = 0; i < DD; i += 16, l += 16) { SSE_L2NORM(l, sum, l0); SSE_L2NORM(l + 4, sum, l1); SSE_L2NORM(l + 8, sum, l2); SSE_L2NORM(l + 12, sum, l3); } _mm_storeu_ps(unpack, sum); result += unpack[0] + unpack[1] + unpack[2] + unpack[3]; #else float dot0, dot1, dot2, dot3; const float *last = a + size; const float *unroll_group = last - 3; /* Process 4 items with each loop for efficiency. */ while (a < unroll_group) { dot0 = a[0] * a[0]; dot1 = a[1] * a[1]; dot2 = a[2] * a[2]; dot3 = a[3] * a[3]; result += dot0 + dot1 + dot2 + dot3; a += 4; } /* Process last 0-3 pixels. Not needed for standard vector lengths. */ while (a < last) { result += (*a) * (*a); a++; } #endif #endif #endif return result; } using DistanceInnerProduct<T>::compare; float compare(const T *a, const T *b, float norm, unsigned size) const { // not implement float result = -2 * DistanceInnerProduct<T>::compare(a, b, size); result += norm; return result; } }; } // namespace diskann
lgraph.h
#pragma once #include "global.h" #include "util.h" #ifdef __CUDACC__ #define CUDA_HOSTDEV __host__ __device__ #else #define CUDA_HOSTDEV #endif #ifdef ENABLE_GPU #define SUBGRAPH_SIZE (1024*128) #define RANGE_WIDTH (512) #else #define SUBGRAPH_SIZE (1024*128) #define RANGE_WIDTH (512) #endif class LearningGraph { protected: bool is_device; bool partitioned; index_t num_vertices_; index_t num_edges_; index_t max_degree; index_t vdata_size; index_t edata_size; index_t gpu_vsize; index_t gpu_esize; index_t *rowptr_; index_t *colidx_; vdata_t *vertex_data_; edata_t *edge_data_; // for GPU index_t* d_rowptr_; index_t* d_colidx_; vdata_t* d_vertex_data_; edata_t* d_edge_data_; edata_t* d_trans_edge_data_; //index_t* d_degrees_; // for CSR segmenting int num_subgraphs; int num_ranges; index_t* nvs_of_subgraphs; // nv of each subgraph index_t* nes_of_subgraphs; // ne of each subgraph index_t** rowptr_blocked; index_t** colidx_blocked; index_t** idx_map; index_t** range_indices; float*** partial_sums; edata_t** edge_data_blocked; public: typedef size_t iterator; LearningGraph(bool use_gpu) : is_device(use_gpu), partitioned(false), //max_size_(0), num_vertices_(0), num_edges_(0), //vertex_data_(NULL), edge_data_(NULL), vdata_size(0), edata_size(0), gpu_vsize(0), gpu_esize(0), rowptr_(NULL), colidx_(NULL), vertex_data_(NULL), edge_data_(NULL), d_rowptr_(NULL), d_colidx_(NULL), d_vertex_data_(NULL), d_edge_data_(NULL), d_trans_edge_data_(NULL) {} LearningGraph() : LearningGraph(false) {} //~LearningGraph() { dealloc(); } void alloc_on_device(); void alloc_on_device(index_t n); void dealloc(); size_t size() { return (size_t)num_vertices_; } size_t sizeEdges() { return (size_t)num_edges_; } bool on_device() { return is_device; } bool is_partitioned() { return partitioned; } index_t get_max_degree() { return max_degree; } //void init(index_t nv, index_t ne) { num_vertices_ = nv; num_edges_ = ne; } index_t get_degree(index_t v) { return rowptr_[v + 1] - rowptr_[v]; } iterator begin() const { return iterator(0); } iterator end() const { return iterator(num_vertices_); } //LearningGraph* generate_masked_graph(mask_t* masks); void copy_to_cpu(); void copy_to_gpu(); void compute_vertex_data(); void compute_edge_data(); //void degree_counting(); void degree_counting() { index_t* degrees_ = new index_t[num_vertices_]; #pragma omp parallel for for (size_t v = 0; v < num_vertices_; v++) degrees_[v] = rowptr_[v+1] - rowptr_[v]; max_degree = *(std::max_element(degrees_, degrees_+num_vertices_)); delete[] degrees_; } //void set_max_size(index_t max) { assert(max > 0); max_size_ = max; } // Graph reading related functions //void readGraph(std::string dataset, bool selfloop = false); //void allocateFrom(index_t nv, index_t ne); void fixEndEdge(index_t vid, index_t row_end) { rowptr_[vid + 1] = row_end; } void allocateFrom(index_t nv, index_t ne) { num_vertices_ = nv; num_edges_ = ne; rowptr_ = new index_t[num_vertices_ + 1]; colidx_ = new index_t[num_edges_]; rowptr_[0] = 0; } //void constructNodes() {} //void constructEdge(index_t eid, index_t dst, edata_t edata = 0); //void constructEdge(index_t eid, index_t dst, edata_t edata = 0) { void constructEdge(index_t eid, index_t dst) { assert(dst < num_vertices_); assert(eid < num_edges_); colidx_[eid] = dst; //if (edge_data_) edge_data_[eid] = edata; } index_t* row_start_host_ptr() { return &rowptr_[0]; } index_t* edge_dst_host_ptr() { return &colidx_[0]; } index_t getEdgeDstHost(index_t eid) { return colidx_[eid]; } index_t edge_begin_host(index_t vid) { return rowptr_[vid]; } index_t edge_end_host(index_t vid) { return rowptr_[vid + 1]; } // CSR segmenting void segmenting(size_t len); void update_feat_len(size_t len); index_t get_subgraph_size(int bid) { return nvs_of_subgraphs[bid]; } index_t get_subgraph_nedges(int bid) { return nes_of_subgraphs[bid]; } int get_num_subgraphs() { return num_subgraphs; } int get_num_ranges() { return num_ranges; } index_t edge_dst_blocked(int bid, index_t eid) { return colidx_blocked[bid][eid]; } index_t edge_begin_blocked(int bid, index_t vid) { return rowptr_blocked[bid][vid]; } index_t edge_end_blocked(int bid, index_t vid) { return rowptr_blocked[bid][vid+1]; } float* get_partial_feats(int bid, index_t vid) { return partial_sums[bid][vid]; } index_t get_global_vid(int bid, index_t vid) { return idx_map[bid][vid]; } index_t get_range_index(int bid, index_t vid) { return range_indices[bid][vid]; } #ifndef ENABLE_GPU index_t getEdgeDst(index_t eid) { return colidx_[eid]; } index_t edge_begin(index_t vid) { return rowptr_[vid]; } index_t edge_end(index_t vid) { return rowptr_[vid+1]; } vdata_t getData(index_t vid) { return vertex_data_[vid]; } //index_t getDegree(index_t vid) { return degrees_[vid]; } index_t* row_start_ptr() { return &rowptr_[0]; } const index_t* row_start_ptr() const { return &rowptr_[0]; } index_t* edge_dst_ptr() { return &colidx_[0]; } const index_t* edge_dst_ptr() const { return &colidx_[0]; } //index_t* degrees_ptr() { return &degrees_[0]; } edata_t* edge_data_ptr() { return &edge_data_[0]; } vdata_t* vertex_data_ptr() { return &vertex_data_[0]; } vdata_t get_vertex_data(index_t vid) { return vertex_data_[vid]; } edata_t get_edge_data(index_t eid) { return edge_data_[eid]; } #else CUDA_HOSTDEV index_t getEdgeDst(index_t edge) { return d_colidx_[edge]; } CUDA_HOSTDEV index_t edge_begin(index_t src) { return d_rowptr_[src]; } CUDA_HOSTDEV index_t edge_end(index_t src) { return d_rowptr_[src + 1]; } CUDA_HOSTDEV vdata_t getData(index_t vid) { return d_vertex_data_[vid]; } CUDA_HOSTDEV vdata_t get_vertex_data(index_t vid) { return d_vertex_data_[vid]; } CUDA_HOSTDEV edata_t get_edge_data(index_t eid) { return d_edge_data_[eid]; } CUDA_HOSTDEV void set_vertex_data(index_t vid, float value) { d_vertex_data_[vid] = value; } CUDA_HOSTDEV void set_edge_data(index_t eid, float value) { d_edge_data_[eid] = value; } CUDA_HOSTDEV void set_trans_edge_data(index_t eid, float value) { d_trans_edge_data_[eid] = value; } // CUDA_HOSTDEV index_t getDegree(index_t vid) { return d_degrees_[vid]; } // CUDA_HOSTDEV index_t getOutDegree(index_t vid) { return d_degrees_[vid]; } CUDA_HOSTDEV index_t getDegree(index_t vid) { return d_rowptr_[vid + 1] - d_rowptr_[vid]; } CUDA_HOSTDEV index_t getOutDegree(index_t vid) { return d_rowptr_[vid + 1] - d_rowptr_[vid]; } index_t* row_start_ptr() { return d_rowptr_; } const index_t* row_start_ptr() const { return d_rowptr_; } index_t* edge_dst_ptr() { return d_colidx_; } const index_t* edge_dst_ptr() const { return d_colidx_; } edata_t* edge_data_ptr() { return d_edge_data_; } edata_t* trans_edge_data_ptr() { return d_trans_edge_data_; } vdata_t* vertex_data_ptr() { return d_vertex_data_; } // const vdata_t *vertex_data_ptr() const { return d_vertex_data_; } // const edata_t *edge_data_ptr() const { return d_edge_data; } //index_t* degrees_ptr() { return d_degrees_; } void print_test(); #endif //void add_selfloop(); void add_selfloop() { //std::cout << "Adding selfloop in the graph...\n"; auto old_colidx_ = colidx_; colidx_ = new index_t[num_vertices_ + num_edges_]; for (index_t i = 0; i < num_vertices_; i++) { auto start = rowptr_[i]; auto end = rowptr_[i + 1]; bool selfloop_inserted = false; if (start == end) { colidx_[start + i] = i; continue; } for (auto e = start; e != end; e++) { auto dst = old_colidx_[e]; if (!selfloop_inserted) { if (i < dst) { selfloop_inserted = true; colidx_[e + i] = i; colidx_[e + i + 1] = dst; } else if (e + 1 == end) { selfloop_inserted = true; colidx_[e + i + 1] = i; colidx_[e + i] = dst; } else colidx_[e + i] = dst; } else colidx_[e + i + 1] = dst; } } for (index_t i = 0; i <= num_vertices_; i++) rowptr_[i] += i; num_edges_ += num_vertices_; //printf("Selfloop added: num_vertices %d num_edges %d\n", num_vertices_, num_edges_); } void print_graph() { std::cout << "Printing the graph: \n"; for (index_t n = 0; n < num_vertices_; n++) { std::cout << "vertex " << n << ": degree = " << get_degree(n) << " edgelist = [ "; for (auto e = edge_begin_host(n); e != edge_end_host(n); e++) std::cout << getEdgeDstHost(e) << " "; std::cout << "]\n"; } } LearningGraph* generate_masked_graph(mask_t* masks) { auto n = this->size(); LearningGraph *masked_graph = new LearningGraph(); std::vector<uint32_t> degrees(n, 0); // get degrees of nodes that will be in new graph #pragma omp parallel for for (size_t src = 0; src < n; src++) { if (masks[src] == 1) { auto begin = edge_begin_host(src); auto end = edge_end_host(src); for (auto e = begin; e != end; e++) { auto dst = getEdgeDstHost(e); if (masks[dst] == 1) degrees[src]++; } } } //auto offsets = parallel_prefix_sum(degrees); auto offsets = prefix_sum(degrees); auto ne = offsets[n]; masked_graph->allocateFrom(n, ne); // same as original graph, except keep only edges involved in masks #pragma omp parallel for for (size_t src = 0; src < n; src++) { masked_graph->fixEndEdge(src, offsets[src + 1]); if (masks[src] == 1) { auto idx = offsets[src]; auto begin = edge_begin_host(src); auto end = edge_end_host(src); for (auto e = begin; e != end; e++) { const auto dst = getEdgeDstHost(e); if (masks[dst] == 1) { masked_graph->constructEdge(idx++, dst); } } } } //masked_graph->degree_counting(); std::cout << "masked graph: num_vertices = " << masked_graph->size() << ", num_edges = " << masked_graph->sizeEdges() << "\n"; return masked_graph; } }; typedef LearningGraph Graph; typedef LearningGraph GraphCPU; typedef LearningGraph GraphGPU;
shear.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS H H EEEEE AAA RRRR % % SS H H E A A R R % % SSS HHHHH EEE AAAAA RRRR % % SS H H E A A R R % % SSSSS H H EEEEE A A R R % % % % % % MagickCore Methods to Shear or Rotate an Image by an Arbitrary Angle % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % The XShearImage() and YShearImage() methods are based on the paper "A Fast % Algorithm for General Raster Rotation" by Alan W. Paeth, Graphics % Interface '86 (Vancouver). ShearRotateImage() is adapted from a similar % method based on the Paeth paper written by Michael Halle of the Spatial % Imaging Group, MIT Media Lab. % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache-private.h" #include "MagickCore/channel.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/decorate.h" #include "MagickCore/distort.h" #include "MagickCore/draw.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/matrix.h" #include "MagickCore/memory_.h" #include "MagickCore/list.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/nt-base-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantum.h" #include "MagickCore/resource_.h" #include "MagickCore/shear.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" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C r o p T o F i t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CropToFitImage() crops the sheared image as determined by the bounding box % as defined by width and height and shearing angles. % % The format of the CropToFitImage method is: % % MagickBooleanType CropToFitImage(Image **image, % const double x_shear,const double x_shear, % const double width,const double height, % const MagickBooleanType rotate,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o x_shear, y_shear, width, height: Defines a region of the image to crop. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType CropToFitImage(Image **image, const double x_shear,const double y_shear, const double width,const double height, const MagickBooleanType rotate,ExceptionInfo *exception) { Image *crop_image; PointInfo extent[4], min, max; RectangleInfo geometry, page; register ssize_t i; /* Calculate the rotated image size. */ extent[0].x=(double) (-width/2.0); extent[0].y=(double) (-height/2.0); extent[1].x=(double) width/2.0; extent[1].y=(double) (-height/2.0); extent[2].x=(double) (-width/2.0); extent[2].y=(double) height/2.0; extent[3].x=(double) width/2.0; extent[3].y=(double) height/2.0; for (i=0; i < 4; i++) { extent[i].x+=x_shear*extent[i].y; extent[i].y+=y_shear*extent[i].x; if (rotate != MagickFalse) extent[i].x+=x_shear*extent[i].y; extent[i].x+=(double) (*image)->columns/2.0; extent[i].y+=(double) (*image)->rows/2.0; } 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; } geometry.x=(ssize_t) ceil(min.x-0.5); geometry.y=(ssize_t) ceil(min.y-0.5); geometry.width=(size_t) floor(max.x-min.x+0.5); geometry.height=(size_t) floor(max.y-min.y+0.5); page=(*image)->page; (void) ParseAbsoluteGeometry("0x0+0+0",&(*image)->page); crop_image=CropImage(*image,&geometry,exception); if (crop_image == (Image *) NULL) return(MagickFalse); crop_image->page=page; *image=DestroyImage(*image); *image=crop_image; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s k e w I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DeskewImage() removes skew from the image. Skew is an artifact that % occurs in scanned images because of the camera being misaligned, % imperfections in the scanning or surface, or simply because the paper was % not placed completely flat when scanned. % % The result will be auto-croped if the artifact "deskew:auto-crop" is % defined, while the amount the image is to be deskewed, in degrees is also % saved as the artifact "deskew:angle". % % The format of the DeskewImage method is: % % Image *DeskewImage(const Image *image,const double threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: separate background from foreground. % % o exception: return any errors or warnings in this structure. % */ static void RadonProjection(const Image *image,MatrixInfo *source_matrixs, MatrixInfo *destination_matrixs,const ssize_t sign,size_t *projection) { MatrixInfo *swap; register MatrixInfo *p, *q; register ssize_t x; size_t step; p=source_matrixs; q=destination_matrixs; for (step=1; step < GetMatrixColumns(p); step*=2) { for (x=0; x < (ssize_t) GetMatrixColumns(p); x+=2*(ssize_t) step) { register ssize_t i; ssize_t y; unsigned short element, neighbor; for (i=0; i < (ssize_t) step; i++) { for (y=0; y < (ssize_t) (GetMatrixRows(p)-i-1); y++) { if (GetMatrixElement(p,x+i,y,&element) == MagickFalse) continue; if (GetMatrixElement(p,x+i+step,y+i,&neighbor) == MagickFalse) continue; neighbor+=element; if (SetMatrixElement(q,x+2*i,y,&neighbor) == MagickFalse) continue; if (GetMatrixElement(p,x+i+step,y+i+1,&neighbor) == MagickFalse) continue; neighbor+=element; if (SetMatrixElement(q,x+2*i+1,y,&neighbor) == MagickFalse) continue; } for ( ; y < (ssize_t) (GetMatrixRows(p)-i); y++) { if (GetMatrixElement(p,x+i,y,&element) == MagickFalse) continue; if (GetMatrixElement(p,x+i+step,y+i,&neighbor) == MagickFalse) continue; neighbor+=element; if (SetMatrixElement(q,x+2*i,y,&neighbor) == MagickFalse) continue; if (SetMatrixElement(q,x+2*i+1,y,&element) == MagickFalse) continue; } for ( ; y < (ssize_t) GetMatrixRows(p); y++) { if (GetMatrixElement(p,x+i,y,&element) == MagickFalse) continue; if (SetMatrixElement(q,x+2*i,y,&element) == MagickFalse) continue; if (SetMatrixElement(q,x+2*i+1,y,&element) == MagickFalse) continue; } } } swap=p; p=q; q=swap; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) \ magick_threads(image,image,1,1) #endif for (x=0; x < (ssize_t) GetMatrixColumns(p); x++) { register ssize_t y; size_t sum; sum=0; for (y=0; y < (ssize_t) (GetMatrixRows(p)-1); y++) { ssize_t delta; unsigned short element, neighbor; if (GetMatrixElement(p,x,y,&element) == MagickFalse) continue; if (GetMatrixElement(p,x,y+1,&neighbor) == MagickFalse) continue; delta=(ssize_t) element-(ssize_t) neighbor; sum+=delta*delta; } projection[GetMatrixColumns(p)+sign*x-1]=sum; } } static MagickBooleanType RadonTransform(const Image *image, const double threshold,size_t *projection,ExceptionInfo *exception) { CacheView *image_view; MatrixInfo *destination_matrixs, *source_matrixs; MagickBooleanType status; size_t count, width; ssize_t j, y; unsigned char c; unsigned short bits[256]; for (width=1; width < ((image->columns+7)/8); width<<=1) ; source_matrixs=AcquireMatrixInfo(width,image->rows,sizeof(unsigned short), exception); destination_matrixs=AcquireMatrixInfo(width,image->rows, sizeof(unsigned short),exception); if ((source_matrixs == (MatrixInfo *) NULL) || (destination_matrixs == (MatrixInfo *) NULL)) { if (destination_matrixs != (MatrixInfo *) NULL) destination_matrixs=DestroyMatrixInfo(destination_matrixs); if (source_matrixs != (MatrixInfo *) NULL) source_matrixs=DestroyMatrixInfo(source_matrixs); return(MagickFalse); } if (NullMatrix(source_matrixs) == MagickFalse) { destination_matrixs=DestroyMatrixInfo(destination_matrixs); source_matrixs=DestroyMatrixInfo(source_matrixs); return(MagickFalse); } for (j=0; j < 256; j++) { c=(unsigned char) j; for (count=0; c != 0; c>>=1) count+=c & 0x01; bits[j]=(unsigned short) count; } status=MagickTrue; image_view=AcquireVirtualCacheView(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=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t i, x; size_t bit, byte; unsigned short value; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } bit=0; byte=0; i=(ssize_t) (image->columns+7)/8; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; if (((MagickRealType) GetPixelRed(image,p) < threshold) || ((MagickRealType) GetPixelGreen(image,p) < threshold) || ((MagickRealType) GetPixelBlue(image,p) < threshold)) byte|=0x01; bit++; if (bit == 8) { value=bits[byte]; (void) SetMatrixElement(source_matrixs,--i,y,&value); bit=0; byte=0; } p+=GetPixelChannels(image); } if (bit != 0) { byte<<=(8-bit); value=bits[byte]; (void) SetMatrixElement(source_matrixs,--i,y,&value); } } RadonProjection(image,source_matrixs,destination_matrixs,-1,projection); (void) NullMatrix(source_matrixs); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t i, x; size_t bit, byte; unsigned short value; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } bit=0; byte=0; i=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; if (((MagickRealType) GetPixelRed(image,p) < threshold) || ((MagickRealType) GetPixelGreen(image,p) < threshold) || ((MagickRealType) GetPixelBlue(image,p) < threshold)) byte|=0x01; bit++; if (bit == 8) { value=bits[byte]; (void) SetMatrixElement(source_matrixs,i++,y,&value); bit=0; byte=0; } p+=GetPixelChannels(image); } if (bit != 0) { byte<<=(8-bit); value=bits[byte]; (void) SetMatrixElement(source_matrixs,i++,y,&value); } } RadonProjection(image,source_matrixs,destination_matrixs,1,projection); image_view=DestroyCacheView(image_view); destination_matrixs=DestroyMatrixInfo(destination_matrixs); source_matrixs=DestroyMatrixInfo(source_matrixs); return(MagickTrue); } static void GetImageBackgroundColor(Image *image,const ssize_t offset, ExceptionInfo *exception) { CacheView *image_view; PixelInfo background; double count; ssize_t y; /* Compute average background color. */ if (offset <= 0) return; GetPixelInfo(image,&background); count=0.0; image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; if ((y >= offset) && (y < ((ssize_t) image->rows-offset))) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) continue; for (x=0; x < (ssize_t) image->columns; x++) { if ((x >= offset) && (x < ((ssize_t) image->columns-offset))) continue; background.red+=QuantumScale*GetPixelRed(image,p); background.green+=QuantumScale*GetPixelGreen(image,p); background.blue+=QuantumScale*GetPixelBlue(image,p); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) background.alpha+=QuantumScale*GetPixelAlpha(image,p); count++; p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); image->background_color.red=(double) ClampToQuantum(QuantumRange* background.red/count); image->background_color.green=(double) ClampToQuantum(QuantumRange* background.green/count); image->background_color.blue=(double) ClampToQuantum(QuantumRange* background.blue/count); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->background_color.alpha=(double) ClampToQuantum(QuantumRange* background.alpha/count); } MagickExport Image *DeskewImage(const Image *image,const double threshold, ExceptionInfo *exception) { AffineMatrix affine_matrix; const char *artifact; double degrees; Image *clone_image, *crop_image, *deskew_image, *median_image; MagickBooleanType status; RectangleInfo geometry; register ssize_t i; size_t max_projection, *projection, width; ssize_t skew; /* Compute deskew angle. */ for (width=1; width < ((image->columns+7)/8); width<<=1) ; projection=(size_t *) AcquireQuantumMemory((size_t) (2*width-1), sizeof(*projection)); if (projection == (size_t *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); status=RadonTransform(image,threshold,projection,exception); if (status == MagickFalse) { projection=(size_t *) RelinquishMagickMemory(projection); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } max_projection=0; skew=0; for (i=0; i < (ssize_t) (2*width-1); i++) { if (projection[i] > max_projection) { skew=i-(ssize_t) width+1; max_projection=projection[i]; } } projection=(size_t *) RelinquishMagickMemory(projection); degrees=RadiansToDegrees(-atan((double) skew/width/8)); if (image->debug != MagickFalse) (void) LogMagickEvent(TransformEvent,GetMagickModule(), " Deskew angle: %g",degrees); /* Deskew image. */ clone_image=CloneImage(image,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) return((Image *) NULL); { char angle[MagickPathExtent]; (void) FormatLocaleString(angle,MagickPathExtent,"%.20g",degrees); (void) SetImageArtifact(clone_image,"deskew:angle",angle); } (void) SetImageVirtualPixelMethod(clone_image,BackgroundVirtualPixelMethod, exception); affine_matrix.sx=cos(DegreesToRadians(fmod((double) degrees,360.0))); affine_matrix.rx=sin(DegreesToRadians(fmod((double) degrees,360.0))); affine_matrix.ry=(-sin(DegreesToRadians(fmod((double) degrees,360.0)))); affine_matrix.sy=cos(DegreesToRadians(fmod((double) degrees,360.0))); affine_matrix.tx=0.0; affine_matrix.ty=0.0; artifact=GetImageArtifact(image,"deskew:auto-crop"); if (IsStringTrue(artifact) == MagickFalse) { deskew_image=AffineTransformImage(clone_image,&affine_matrix,exception); clone_image=DestroyImage(clone_image); return(deskew_image); } /* Auto-crop image. */ GetImageBackgroundColor(clone_image,(ssize_t) StringToLong(artifact), exception); deskew_image=AffineTransformImage(clone_image,&affine_matrix,exception); clone_image=DestroyImage(clone_image); if (deskew_image == (Image *) NULL) return((Image *) NULL); median_image=StatisticImage(deskew_image,MedianStatistic,3,3,exception); if (median_image == (Image *) NULL) { deskew_image=DestroyImage(deskew_image); return((Image *) NULL); } geometry=GetImageBoundingBox(median_image,exception); median_image=DestroyImage(median_image); if (image->debug != MagickFalse) (void) LogMagickEvent(TransformEvent,GetMagickModule()," Deskew geometry: " "%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double) geometry.height,(double) geometry.x,(double) geometry.y); crop_image=CropImage(deskew_image,&geometry,exception); deskew_image=DestroyImage(deskew_image); return(crop_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n t e g r a l R o t a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IntegralRotateImage() rotates the image an integral of 90 degrees. It % allocates the memory necessary for the new Image structure and returns a % pointer to the rotated image. % % The format of the IntegralRotateImage method is: % % Image *IntegralRotateImage(const Image *image,size_t rotations, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o rotations: Specifies the number of 90 degree rotations. % */ MagickExport Image *IntegralRotateImage(const Image *image,size_t rotations, ExceptionInfo *exception) { #define RotateImageTag "Rotate/Image" CacheView *image_view, *rotate_view; Image *rotate_image; MagickBooleanType status; MagickOffsetType progress; RectangleInfo page; /* Initialize rotated image attributes. */ assert(image != (Image *) NULL); page=image->page; rotations%=4; if (rotations == 0) return(CloneImage(image,0,0,MagickTrue,exception)); if ((rotations == 1) || (rotations == 3)) rotate_image=CloneImage(image,image->rows,image->columns,MagickTrue, exception); else rotate_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); if (rotate_image == (Image *) NULL) return((Image *) NULL); /* Integral rotate the image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); rotate_view=AcquireAuthenticCacheView(rotate_image,exception); switch (rotations) { case 1: { size_t tile_height, tile_width; ssize_t tile_y; /* Rotate 90 degrees. */ GetPixelCacheTileSize(image,&tile_width,&tile_height); tile_width=image->columns; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,1,1) #endif for (tile_y=0; tile_y < (ssize_t) image->rows; tile_y+=(ssize_t) tile_height) { register ssize_t tile_x; if (status == MagickFalse) continue; tile_x=0; for ( ; tile_x < (ssize_t) image->columns; tile_x+=(ssize_t) tile_width) { MagickBooleanType sync; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t y; size_t height, width; width=tile_width; if ((tile_x+(ssize_t) tile_width) > (ssize_t) image->columns) width=(size_t) (tile_width-(tile_x+tile_width-image->columns)); height=tile_height; if ((tile_y+(ssize_t) tile_height) > (ssize_t) image->rows) height=(size_t) (tile_height-(tile_y+tile_height-image->rows)); p=GetCacheViewVirtualPixels(image_view,tile_x,tile_y,width,height, exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (y=0; y < (ssize_t) width; y++) { register const Quantum *magick_restrict tile_pixels; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(rotate_view,(ssize_t) (rotate_image->columns-(tile_y+height)),y+tile_x,height,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } tile_pixels=p+((height-1)*width+y)*GetPixelChannels(image); for (x=0; x < (ssize_t) height; x++) { register ssize_t i; if (GetPixelWriteMask(image,tile_pixels) == 0) { tile_pixels-=width*GetPixelChannels(image); q+=GetPixelChannels(rotate_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait rotate_traits=GetPixelChannelTraits(rotate_image, channel); if ((traits == UndefinedPixelTrait) || (rotate_traits == UndefinedPixelTrait)) continue; SetPixelChannel(rotate_image,channel,tile_pixels[i],q); } tile_pixels-=width*GetPixelChannels(image); q+=GetPixelChannels(rotate_image); } sync=SyncCacheViewAuthenticPixels(rotate_view,exception); if (sync == MagickFalse) status=MagickFalse; } } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_IntegralRotateImage) #endif proceed=SetImageProgress(image,RotateImageTag,progress+=tile_height, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } (void) SetImageProgress(image,RotateImageTag,(MagickOffsetType) image->rows-1,image->rows); Swap(page.width,page.height); Swap(page.x,page.y); if (page.width != 0) page.x=(ssize_t) (page.width-rotate_image->columns-page.x); break; } case 2: { register ssize_t y; /* Rotate 180 degrees. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,1,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; 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(rotate_view,0,(ssize_t) (image->rows-y- 1),image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } q+=GetPixelChannels(rotate_image)*image->columns; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; q-=GetPixelChannels(rotate_image); if (GetPixelWriteMask(image,p) == 0) { p+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait rotate_traits=GetPixelChannelTraits(rotate_image, channel); if ((traits == UndefinedPixelTrait) || (rotate_traits == UndefinedPixelTrait)) continue; SetPixelChannel(rotate_image,channel,p[i],q); } p+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(rotate_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_IntegralRotateImage) #endif proceed=SetImageProgress(image,RotateImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } (void) SetImageProgress(image,RotateImageTag,(MagickOffsetType) image->rows-1,image->rows); if (page.width != 0) page.x=(ssize_t) (page.width-rotate_image->columns-page.x); if (page.height != 0) page.y=(ssize_t) (page.height-rotate_image->rows-page.y); break; } case 3: { size_t tile_height, tile_width; ssize_t tile_y; /* Rotate 270 degrees. */ GetPixelCacheTileSize(image,&tile_width,&tile_height); tile_width=image->columns; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,1,1) #endif for (tile_y=0; tile_y < (ssize_t) image->rows; tile_y+=(ssize_t) tile_height) { register ssize_t tile_x; if (status == MagickFalse) continue; tile_x=0; for ( ; tile_x < (ssize_t) image->columns; tile_x+=(ssize_t) tile_width) { MagickBooleanType sync; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t y; size_t height, width; width=tile_width; if ((tile_x+(ssize_t) tile_width) > (ssize_t) image->columns) width=(size_t) (tile_width-(tile_x+tile_width-image->columns)); height=tile_height; if ((tile_y+(ssize_t) tile_height) > (ssize_t) image->rows) height=(size_t) (tile_height-(tile_y+tile_height-image->rows)); p=GetCacheViewVirtualPixels(image_view,tile_x,tile_y,width,height, exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (y=0; y < (ssize_t) width; y++) { register const Quantum *magick_restrict tile_pixels; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(rotate_view,tile_y,(ssize_t) (y+ rotate_image->rows-(tile_x+width)),height,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } tile_pixels=p+((width-1)-y)*GetPixelChannels(image); for (x=0; x < (ssize_t) height; x++) { register ssize_t i; if (GetPixelWriteMask(image,tile_pixels) == 0) { tile_pixels+=width*GetPixelChannels(image); q+=GetPixelChannels(rotate_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait rotate_traits=GetPixelChannelTraits(rotate_image, channel); if ((traits == UndefinedPixelTrait) || (rotate_traits == UndefinedPixelTrait)) continue; SetPixelChannel(rotate_image,channel,tile_pixels[i],q); } tile_pixels+=width*GetPixelChannels(image); q+=GetPixelChannels(rotate_image); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_IntegralRotateImage) #endif sync=SyncCacheViewAuthenticPixels(rotate_view,exception); if (sync == MagickFalse) status=MagickFalse; } } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,RotateImageTag,progress+=tile_height, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } (void) SetImageProgress(image,RotateImageTag,(MagickOffsetType) image->rows-1,image->rows); Swap(page.width,page.height); Swap(page.x,page.y); if (page.height != 0) page.y=(ssize_t) (page.height-rotate_image->rows-page.y); break; } default: break; } rotate_view=DestroyCacheView(rotate_view); image_view=DestroyCacheView(image_view); rotate_image->type=image->type; rotate_image->page=page; if (status == MagickFalse) rotate_image=DestroyImage(rotate_image); return(rotate_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + X S h e a r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % XShearImage() shears the image in the X direction with a shear angle of % 'degrees'. Positive angles shear counter-clockwise (right-hand rule), and % negative angles shear clockwise. Angles are measured relative to a vertical % Y-axis. X shears will widen an image creating 'empty' triangles on the left % and right sides of the source image. % % The format of the XShearImage method is: % % MagickBooleanType XShearImage(Image *image,const double degrees, % const size_t width,const size_t height, % const ssize_t x_offset,const ssize_t y_offset,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o degrees: A double representing the shearing angle along the X % axis. % % o width, height, x_offset, y_offset: Defines a region of the image % to shear. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType XShearImage(Image *image,const double degrees, const size_t width,const size_t height,const ssize_t x_offset, const ssize_t y_offset,ExceptionInfo *exception) { #define XShearImageTag "XShear/Image" typedef enum { LEFT, RIGHT } ShearDirection; CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; PixelInfo background; ssize_t y; /* X shear image. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=MagickTrue; background=image->background_color; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,height,1) #endif for (y=0; y < (ssize_t) height; y++) { PixelInfo pixel, source, destination; double area, displacement; register Quantum *magick_restrict p, *magick_restrict q; register ssize_t i; ShearDirection direction; ssize_t step; if (status == MagickFalse) continue; p=GetCacheViewAuthenticPixels(image_view,0,y_offset+y,image->columns,1, exception); if (p == (Quantum *) NULL) { status=MagickFalse; continue; } p+=x_offset*GetPixelChannels(image); displacement=degrees*(double) (y-height/2.0); if (displacement == 0.0) continue; if (displacement > 0.0) direction=RIGHT; else { displacement*=(-1.0); direction=LEFT; } step=(ssize_t) floor((double) displacement); area=(double) (displacement-step); step++; pixel=background; GetPixelInfo(image,&source); GetPixelInfo(image,&destination); switch (direction) { case LEFT: { /* Transfer pixels left-to-right. */ if (step > x_offset) break; q=p-step*GetPixelChannels(image); for (i=0; i < (ssize_t) width; i++) { if ((x_offset+i) < step) { p+=GetPixelChannels(image); GetPixelInfoPixel(image,p,&pixel); q+=GetPixelChannels(image); continue; } GetPixelInfoPixel(image,p,&source); CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &source,(double) GetPixelAlpha(image,p),area,&destination); SetPixelViaPixelInfo(image,&destination,q); GetPixelInfoPixel(image,p,&pixel); p+=GetPixelChannels(image); q+=GetPixelChannels(image); } CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &background,(double) background.alpha,area,&destination); SetPixelViaPixelInfo(image,&destination,q); q+=GetPixelChannels(image); for (i=0; i < (step-1); i++) { SetPixelViaPixelInfo(image,&background,q); q+=GetPixelChannels(image); } break; } case RIGHT: { /* Transfer pixels right-to-left. */ p+=width*GetPixelChannels(image); q=p+step*GetPixelChannels(image); for (i=0; i < (ssize_t) width; i++) { p-=GetPixelChannels(image); q-=GetPixelChannels(image); if ((size_t) (x_offset+width+step-i) > image->columns) continue; GetPixelInfoPixel(image,p,&source); CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &source,(double) GetPixelAlpha(image,p),area,&destination); SetPixelViaPixelInfo(image,&destination,q); GetPixelInfoPixel(image,p,&pixel); } CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &background,(double) background.alpha,area,&destination); q-=GetPixelChannels(image); SetPixelViaPixelInfo(image,&destination,q); for (i=0; i < (step-1); i++) { q-=GetPixelChannels(image); SetPixelViaPixelInfo(image,&background,q); } break; } } 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_XShearImage) #endif proceed=SetImageProgress(image,XShearImageTag,progress++,height); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Y S h e a r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % YShearImage shears the image in the Y direction with a shear angle of % 'degrees'. Positive angles shear counter-clockwise (right-hand rule), and % negative angles shear clockwise. Angles are measured relative to a % horizontal X-axis. Y shears will increase the height of an image creating % 'empty' triangles on the top and bottom of the source image. % % The format of the YShearImage method is: % % MagickBooleanType YShearImage(Image *image,const double degrees, % const size_t width,const size_t height, % const ssize_t x_offset,const ssize_t y_offset,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o degrees: A double representing the shearing angle along the Y % axis. % % o width, height, x_offset, y_offset: Defines a region of the image % to shear. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType YShearImage(Image *image,const double degrees, const size_t width,const size_t height,const ssize_t x_offset, const ssize_t y_offset,ExceptionInfo *exception) { #define YShearImageTag "YShear/Image" typedef enum { UP, DOWN } ShearDirection; CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; PixelInfo background; ssize_t x; /* Y Shear image. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=MagickTrue; progress=0; background=image->background_color; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,width,1) #endif for (x=0; x < (ssize_t) width; x++) { ssize_t step; double area, displacement; PixelInfo pixel, source, destination; register Quantum *magick_restrict p, *magick_restrict q; register ssize_t i; ShearDirection direction; if (status == MagickFalse) continue; p=GetCacheViewAuthenticPixels(image_view,x_offset+x,0,1,image->rows, exception); if (p == (Quantum *) NULL) { status=MagickFalse; continue; } p+=y_offset*GetPixelChannels(image); displacement=degrees*(double) (x-width/2.0); if (displacement == 0.0) continue; if (displacement > 0.0) direction=DOWN; else { displacement*=(-1.0); direction=UP; } step=(ssize_t) floor((double) displacement); area=(double) (displacement-step); step++; pixel=background; GetPixelInfo(image,&source); GetPixelInfo(image,&destination); switch (direction) { case UP: { /* Transfer pixels top-to-bottom. */ if (step > y_offset) break; q=p-step*GetPixelChannels(image); for (i=0; i < (ssize_t) height; i++) { if ((y_offset+i) < step) { p+=GetPixelChannels(image); GetPixelInfoPixel(image,p,&pixel); q+=GetPixelChannels(image); continue; } GetPixelInfoPixel(image,p,&source); CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &source,(double) GetPixelAlpha(image,p),area, &destination); SetPixelViaPixelInfo(image,&destination,q); GetPixelInfoPixel(image,p,&pixel); p+=GetPixelChannels(image); q+=GetPixelChannels(image); } CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &background,(double) background.alpha,area,&destination); SetPixelViaPixelInfo(image,&destination,q); q+=GetPixelChannels(image); for (i=0; i < (step-1); i++) { SetPixelViaPixelInfo(image,&background,q); q+=GetPixelChannels(image); } break; } case DOWN: { /* Transfer pixels bottom-to-top. */ p+=height*GetPixelChannels(image); q=p+step*GetPixelChannels(image); for (i=0; i < (ssize_t) height; i++) { p-=GetPixelChannels(image); q-=GetPixelChannels(image); if ((size_t) (y_offset+height+step-i) > image->rows) continue; GetPixelInfoPixel(image,p,&source); CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &source,(double) GetPixelAlpha(image,p),area, &destination); SetPixelViaPixelInfo(image,&destination,q); GetPixelInfoPixel(image,p,&pixel); } CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &background,(double) background.alpha,area,&destination); q-=GetPixelChannels(image); SetPixelViaPixelInfo(image,&destination,q); for (i=0; i < (step-1); i++) { q-=GetPixelChannels(image); SetPixelViaPixelInfo(image,&background,q); } break; } } 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_YShearImage) #endif proceed=SetImageProgress(image,YShearImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h e a r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShearImage() creates a new image that is a shear_image copy of an existing % one. Shearing slides one edge of an image along the X or Y axis, creating % a parallelogram. An X direction shear slides an edge along the X axis, % while a Y direction shear slides an edge along the Y axis. The amount of % the shear is controlled by a shear angle. For X direction shears, x_shear % is measured relative to the Y axis, and similarly, for Y direction shears % y_shear is measured relative to the X axis. Empty triangles left over from % shearing the image are filled with the background color defined by member % 'background_color' of the image.. ShearImage() allocates the memory % necessary for the new Image structure and returns a pointer to the new image. % % ShearImage() is based on the paper "A Fast Algorithm for General Raster % Rotatation" by Alan W. Paeth. % % The format of the ShearImage method is: % % Image *ShearImage(const Image *image,const double x_shear, % const double y_shear,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o x_shear, y_shear: Specifies the number of degrees to shear the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ShearImage(const Image *image,const double x_shear, const double y_shear,ExceptionInfo *exception) { Image *integral_image, *shear_image; MagickBooleanType status; PointInfo shear; RectangleInfo border_info, bounds; 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 ((x_shear != 0.0) && (fmod(x_shear,90.0) == 0.0)) ThrowImageException(ImageError,"AngleIsDiscontinuous"); if ((y_shear != 0.0) && (fmod(y_shear,90.0) == 0.0)) ThrowImageException(ImageError,"AngleIsDiscontinuous"); /* Initialize shear angle. */ integral_image=CloneImage(image,0,0,MagickTrue,exception); if (integral_image == (Image *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); shear.x=(-tan(DegreesToRadians(fmod(x_shear,360.0)))); shear.y=tan(DegreesToRadians(fmod(y_shear,360.0))); if ((shear.x == 0.0) && (shear.y == 0.0)) return(integral_image); if (SetImageStorageClass(integral_image,DirectClass,exception) == MagickFalse) { integral_image=DestroyImage(integral_image); return(integral_image); } if (integral_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(integral_image,OpaqueAlphaChannel,exception); /* Compute image size. */ bounds.width=image->columns+(ssize_t) floor(fabs(shear.x)*image->rows+0.5); bounds.x=(ssize_t) ceil((double) image->columns+((fabs(shear.x)*image->rows)- image->columns)/2.0-0.5); bounds.y=(ssize_t) ceil((double) image->rows+((fabs(shear.y)*bounds.width)- image->rows)/2.0-0.5); /* Surround image with border. */ integral_image->border_color=integral_image->background_color; integral_image->compose=CopyCompositeOp; border_info.width=(size_t) bounds.x; border_info.height=(size_t) bounds.y; shear_image=BorderImage(integral_image,&border_info,image->compose,exception); integral_image=DestroyImage(integral_image); if (shear_image == (Image *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); /* Shear the image. */ if (shear_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(shear_image,OpaqueAlphaChannel,exception); status=XShearImage(shear_image,shear.x,image->columns,image->rows,bounds.x, (ssize_t) (shear_image->rows-image->rows)/2,exception); if (status == MagickFalse) { shear_image=DestroyImage(shear_image); return((Image *) NULL); } status=YShearImage(shear_image,shear.y,bounds.width,image->rows,(ssize_t) (shear_image->columns-bounds.width)/2,bounds.y,exception); if (status == MagickFalse) { shear_image=DestroyImage(shear_image); return((Image *) NULL); } status=CropToFitImage(&shear_image,shear.x,shear.y,(MagickRealType) image->columns,(MagickRealType) image->rows,MagickFalse,exception); shear_image->alpha_trait=image->alpha_trait; shear_image->compose=image->compose; shear_image->page.width=0; shear_image->page.height=0; if (status == MagickFalse) shear_image=DestroyImage(shear_image); return(shear_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h e a r R o t a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShearRotateImage() creates a new image that is a rotated copy of an existing % one. Positive angles rotate counter-clockwise (right-hand rule), while % negative angles rotate clockwise. Rotated images are usually larger than % the originals and have 'empty' triangular corners. X axis. Empty % triangles left over from shearing the image are filled with the background % color defined by member 'background_color' of the image. ShearRotateImage % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % ShearRotateImage() is based on the paper "A Fast Algorithm for General % Raster Rotatation" by Alan W. Paeth. ShearRotateImage is adapted from a % similar method based on the Paeth paper written by Michael Halle of the % Spatial Imaging Group, MIT Media Lab. % % The format of the ShearRotateImage method is: % % Image *ShearRotateImage(const Image *image,const double degrees, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o degrees: Specifies the number of degrees to rotate the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ShearRotateImage(const Image *image,const double degrees, ExceptionInfo *exception) { Image *integral_image, *rotate_image; MagickBooleanType status; MagickRealType angle; PointInfo shear; RectangleInfo border_info, bounds; size_t height, rotations, shear_width, width; /* Adjust rotation angle. */ 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); angle=degrees; while (angle < -45.0) angle+=360.0; for (rotations=0; angle > 45.0; rotations++) angle-=90.0; rotations%=4; /* Calculate shear equations. */ integral_image=IntegralRotateImage(image,rotations,exception); if (integral_image == (Image *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); shear.x=(-tan((double) DegreesToRadians(angle)/2.0)); shear.y=sin((double) DegreesToRadians(angle)); if ((shear.x == 0.0) && (shear.y == 0.0)) return(integral_image); if (SetImageStorageClass(integral_image,DirectClass,exception) == MagickFalse) { integral_image=DestroyImage(integral_image); return(integral_image); } if (integral_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(integral_image,OpaqueAlphaChannel,exception); /* Compute maximum bounds for 3 shear operations. */ width=integral_image->columns; height=integral_image->rows; bounds.width=(size_t) floor(fabs((double) height*shear.x)+width+0.5); bounds.height=(size_t) floor(fabs((double) bounds.width*shear.y)+height+0.5); shear_width=(size_t) floor(fabs((double) bounds.height*shear.x)+ bounds.width+0.5); bounds.x=(ssize_t) floor((double) ((shear_width > bounds.width) ? width : bounds.width-shear_width+2)/2.0+0.5); bounds.y=(ssize_t) floor(((double) bounds.height-height+2)/2.0+0.5); /* Surround image with a border. */ integral_image->border_color=integral_image->background_color; integral_image->compose=CopyCompositeOp; border_info.width=(size_t) bounds.x; border_info.height=(size_t) bounds.y; rotate_image=BorderImage(integral_image,&border_info,image->compose, exception); integral_image=DestroyImage(integral_image); if (rotate_image == (Image *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); /* Rotate the image. */ status=XShearImage(rotate_image,shear.x,width,height,bounds.x,(ssize_t) (rotate_image->rows-height)/2,exception); if (status == MagickFalse) { rotate_image=DestroyImage(rotate_image); return((Image *) NULL); } status=YShearImage(rotate_image,shear.y,bounds.width,height,(ssize_t) (rotate_image->columns-bounds.width)/2,bounds.y,exception); if (status == MagickFalse) { rotate_image=DestroyImage(rotate_image); return((Image *) NULL); } status=XShearImage(rotate_image,shear.x,bounds.width,bounds.height,(ssize_t) (rotate_image->columns-bounds.width)/2,(ssize_t) (rotate_image->rows- bounds.height)/2,exception); if (status == MagickFalse) { rotate_image=DestroyImage(rotate_image); return((Image *) NULL); } status=CropToFitImage(&rotate_image,shear.x,shear.y,(MagickRealType) width, (MagickRealType) height,MagickTrue,exception); rotate_image->alpha_trait=image->alpha_trait; rotate_image->compose=image->compose; rotate_image->page.width=0; rotate_image->page.height=0; if (status == MagickFalse) rotate_image=DestroyImage(rotate_image); return(rotate_image); }
nbody-unroll.c
#include <math.h> #include <stdio.h> #include <stdlib.h> #include "timer.h" #define SOFTENING 1e-9f typedef struct { float x, y, z, vx, vy, vz; } Body; void randomizeBodies(float *data, int n) { for (int i = 0; i < n; i++) { data[i] = 2.0f * (rand() / (float)RAND_MAX) - 1.0f; } } void bodyForce(Body *p, float dt, int n) { #pragma omp parallel for schedule(dynamic) for (int i = 0; i < n; i++) { float Fx = 0.0f; float Fy = 0.0f; float Fz = 0.0f; #pragma unroll for (int j = 0; j < n; j++) { float dx = p[j].x - p[i].x; float dy = p[j].y - p[i].y; float dz = p[j].z - p[i].z; float distSqr = dx*dx + dy*dy + dz*dz + SOFTENING; float invDist = 1.0f / sqrtf(distSqr); float invDist3 = invDist * invDist * invDist; Fx += dx * invDist3; Fy += dy * invDist3; Fz += dz * invDist3; } p[i].vx += dt*Fx; p[i].vy += dt*Fy; p[i].vz += dt*Fz; } } int main(const int argc, const char** argv) { int nBodies = 32768; if (argc > 1) nBodies = atoi(argv[1]); const float dt = 0.01f; // time step const int nIters = 10; // simulation iterations int bytes = nBodies*sizeof(Body); float *buf = (float*)malloc(bytes); Body *p = (Body*)buf; randomizeBodies(buf, 6*nBodies); // Init pos / vel data double totalTime = 0.0; for (int iter = 1; iter <= nIters; iter++) { StartTimer(); bodyForce(p, dt, nBodies); // compute interbody forces for (int i = 0 ; i < nBodies; i++) { // integrate position p[i].x += p[i].vx*dt; p[i].y += p[i].vy*dt; p[i].z += p[i].vz*dt; } const double tElapsed = GetTimer() / 1000.0; if (iter > 1) { // First iter is warm up totalTime += tElapsed; } #ifndef SHMOO printf("Iteration %d: %.3f seconds\n", iter, tElapsed); #endif } double avgTime = totalTime / (double)(nIters-1); #ifdef SHMOO printf("%d, %0.3f\n", nBodies, 1e-9 * nBodies * nBodies / avgTime); #else printf("Average rate for iterations 2 through %d: %.3f steps per second.\n", nIters); printf("%d Bodies: average %0.3f Billion Interactions / second\n", nBodies, 1e-9 * nBodies * nBodies / avgTime); #endif free(buf); }
fox_floats_timer_caching_omp_fileIO_benchmark.c
/* fox_floats_timer_caching_omp_fileIO_benchmark.c -- uses Fox's algorithm to multiply two square matrices * * Implementation of parallel matrix multiplication: * LaTeX: $C_{i,j} = \sum_{k} A_{i,k}B_{k,j}$ * * Input: * Input Matrix file name: A.dat, B.dat * * Output: * Output Matrix file name: C.dat * Output Sub-matrices file name: SubMatrices.dat * * Notes: * 1. Assumes the number of processes is a perfect square * 2. The array member of the matrices is statically allocated * * See Chap 7, pp. 113 & ff and pp. 125 & ff in PPMPI */ /* Compiler command: * mpiicc -O3 -qopenmp -qopt-report-phase=vec -qopt-report=3 fox_floats_timer_caching_omp_fileIO_benchmark.c * -o fox_floats_timer_caching_omp_fileIO_benchmark * * Run command: * mpirun -n -4 ./fox_floats_timer_caching_omp */ /* Head files */ #include <stdio.h> #include <math.h> #include <stdlib.h> #include <mpi.h> #include <omp.h> // define problem scale, matrix row/col size #define PROBLEM_SCALE 512 // define whether or not Print Matices in the Command Line #define PRINT_A 0 #define PRINT_B 0 #define PRINT_C 0 #define PRINT_LOCAL_A 0 #define PRINT_LOCAL_B 0 #define PRINT_LOCAL_C 0 // define float precision, 4 byte single-precision float or 8 byte double-precision float #define FLOAT double #define FLOAT_MPI MPI_DOUBLE // Define threads speed-up affnity in the computing #define NUM_THREADS 16 // Define threads affinity "scatter" or "compact" #define AFFINITY "KMP_AFFINITY = compact" /* Type define structure of process grid */ typedef struct { int p; /* Total number of processes */ MPI_Comm comm; /* Communicator for entire grid */ MPI_Comm row_comm; /* Communicator for my row */ MPI_Comm col_comm; /* Communicator for my col */ int q; /* Order of grid */ int my_row; /* My row number */ int my_col; /* My column number */ int my_rank; /* My rank in the grid comm */ } GRID_INFO_T; /* Type define structure of local matrix */ #define MAX 2097152 // Maximum number of elements in the array that store the local matrix (2^21) typedef struct { int n_bar; #define Order(A) ((A)->n_bar) // defination with parameters FLOAT entries[MAX]; #define Entry(A,i,j) (*(((A)->entries) + ((A)->n_bar)*(i) + (j))) // defination with parameters, Array dereference } LOCAL_MATRIX_T; /* Function Declarations */ LOCAL_MATRIX_T* Local_matrix_allocate(int n_bar); void Free_local_matrix(LOCAL_MATRIX_T** local_A); void Read_matrix_A(char* prompt, LOCAL_MATRIX_T* local_A, GRID_INFO_T* grid, int n); // Read matrix A from a file void Read_matrix_B(char* prompt, LOCAL_MATRIX_T* local_B, // for continuous memory access, local A(i,k)*B(k,j) = A(i,k)*B^{T}(j,k) GRID_INFO_T* grid, int n); // Read matrix B from a file void Print_matrix_A(char* title, LOCAL_MATRIX_T* local_A, GRID_INFO_T* grid, int n); // Print matrix A in the command line void Print_matrix_B(char* title, LOCAL_MATRIX_T* local_B, // Speical print function for local matrix B^{T}(j,k) GRID_INFO_T* grid, int n); // Print matrix B in the command line void Print_matrix_C(char* title, LOCAL_MATRIX_T* local_C, GRID_INFO_T* grid, int n); // Print matrix C in the command line void Set_to_zero(LOCAL_MATRIX_T* local_A); void Local_matrix_multiply(LOCAL_MATRIX_T* local_A, LOCAL_MATRIX_T* local_B, LOCAL_MATRIX_T* local_C); void Build_matrix_type(LOCAL_MATRIX_T* local_A); MPI_Datatype local_matrix_mpi_t; LOCAL_MATRIX_T* temp_mat; // global LOCAL_MATRIX_T* type pointer void Print_local_matrices_A(char* title, LOCAL_MATRIX_T* local_A, GRID_INFO_T* grid); void Print_local_matrices_B(char* title, LOCAL_MATRIX_T* local_B, // Speical print function for local matrix B^{T}(j,k) GRID_INFO_T* grid); void Print_local_matrices_C(char* title, LOCAL_MATRIX_T* local_B, GRID_INFO_T* grid); void Write_matrix_C(char* title, LOCAL_MATRIX_T* local_C, GRID_INFO_T* grid, int n); // Write matrix multiplication to a file void Write_local_matrices_A(char* title, LOCAL_MATRIX_T* local_A, GRID_INFO_T* grid); // Write local matrix A to a file void Write_local_matrices_B(char* title, LOCAL_MATRIX_T* local_B, // Speical print function for local matrix B^{T}(j,k) GRID_INFO_T* grid); // Write local matrix B to a file void Write_local_matrices_C(char* title, LOCAL_MATRIX_T* local_A, GRID_INFO_T* grid); // Write local matrix C to a file /*********************************************************/ main(int argc, char* argv[]) { FILE *fp; int p; int my_rank; GRID_INFO_T grid; LOCAL_MATRIX_T* local_A; LOCAL_MATRIX_T* local_B; LOCAL_MATRIX_T* local_C; int n; int n_bar; double timer_start; double timer_end; int content; int i; int j; void Setup_grid(GRID_INFO_T* grid); void Fox(int n, GRID_INFO_T* grid, LOCAL_MATRIX_T* local_A, LOCAL_MATRIX_T* local_B, LOCAL_MATRIX_T* local_C); // Matrix Generator fp = fopen("A.dat", "w"); // Generate and print matrix A into a file for (i = 0; i < PROBLEM_SCALE; i++) { for (j = 0; j < PROBLEM_SCALE; j++) if(i == j){ fprintf(fp,"%d ", 1); } else { fprintf(fp,"%d ", 0); } fprintf(fp,"\n"); } fclose(fp); fp = fopen("B.dat", "w"); // Generate and print matrix B into a file for (i = 0; i < PROBLEM_SCALE; i++){ for (j = 0; j < PROBLEM_SCALE; j++) fprintf(fp,"%d ", (i*PROBLEM_SCALE)+j); fprintf(fp, "\n"); } fclose(fp); // SPMD Mode start from here (Processess fork from here) MPI_Init(&argc, &argv); // MPI initializing MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); // Get my process id in the MPI communicator // Initial OpenMP Environment omp_set_num_threads(NUM_THREADS); kmp_set_defaults(AFFINITY); Setup_grid(&grid); // Set up Processess grid if (my_rank == 0) { fp = fopen("A.dat","r"); n = 0; while((content = fgetc(fp)) != EOF) { //printf("fgetc = %d\n", content); if(content != 0x20 && content != 0x0A) n++; } fclose(fp); n = (int) sqrt((double) n); printf("We read the order of the matrices from A.dat is\n %d\n", n); // while(fgetc(fp) != EOF) n++; // printf("What's the order of the matrices?\n"); // scanf("%d", &n); // Overall Matrix's Order } MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD); // MPI broadcast the overall matrix's order n_bar = n/grid.q; // \bar n is the local matrix's order local_A = Local_matrix_allocate(n_bar); // Allocate local matrix A Order(local_A) = n_bar; // Local matrix A's order Read_matrix_A("Read A from A.dat", local_A, &grid, n); // Read local matrices A from process 0 by using stdin, and send them to each process (Procedure) if (PRINT_A == 1) Print_matrix_A("We read A =", local_A, &grid, n);// Print local matrices A from process 0 by using stdout, and send them to each process (Procedure) local_B = Local_matrix_allocate(n_bar); // Allocate local matrix Order(local_B) = n_bar; // Local matrix B's order Read_matrix_B("Read B from B.dat", local_B, &grid, n); // Read local matrix B as it's local transpose from process 0 by using stdin, and send them to each process (Procedure) if (PRINT_B == 1) Print_matrix_B("We read B =", local_B, &grid, n);// Print local matrix B as it's local transpose from process 0 by using stdout, and send them to each process (Procedure) Build_matrix_type(local_A); // Buid local_A's MPI matrix data type temp_mat = Local_matrix_allocate(n_bar); // Allocate temporary matrix of order n $\time$ n local_C = Local_matrix_allocate(n_bar); // Allocate matrix local_C Order(local_C) = n_bar; // Set matrix local_C's order MPI_Barrier(MPI_COMM_WORLD); // Set the MPI process barrier timer_start = MPI_Wtime(); // Get the MPI wall time Fox(n, &grid, local_A, local_B, local_C); // FOX parallel matrix multiplication Algorithm implement function timer_end = MPI_Wtime(); // Get the MPI wall time MPI_Barrier(MPI_COMM_WORLD); // Set the MPI process barrier Write_matrix_C("Write C into the C.dat", local_C, &grid, n); // Print matrix local_C (parallel matrix multiplication result) if (PRINT_C == 1) Print_matrix_C("The product is", local_C, &grid, n); // Print matrix local_C (parallel matrix multiplication result) Write_local_matrices_A("Write split of local matrix A into local_A.dat", local_A, &grid); // Write local matrix A into file if (PRINT_LOCAL_A == 1) Print_local_matrices_A("Split of local matrix A", local_A, &grid); // Print matrix A split in processess Write_local_matrices_B("Write split of local matrix B into local_B.dat", local_B, &grid); // Write local matrix B into file, special for row-major storage if (PRINT_LOCAL_B == 1) Print_local_matrices_B("Split of local matrix B", local_B, &grid); // Print matrix B split in processess, special for row-major storage Write_local_matrices_C("Write split of local matrix C into local_C.dat", local_C, &grid); // Print matrix C split in processess if (PRINT_LOCAL_C == 1) Print_local_matrices_C("Split of local matrix C", local_C, &grid); // Print matrix C split in processess Free_local_matrix(&local_A); // Free local matrix local_A Free_local_matrix(&local_B); // Free local matrix local_B Free_local_matrix(&local_C); // Free local matrix local_C if(my_rank == 0) printf("Parallel Fox Matrix Multiplication Elapsed time:\n %30.20E seconds\n", timer_end-timer_start); MPI_Finalize(); // MPI finalize, processes join and resource recycle } /* main */ /*********************************************************/ void Setup_grid( GRID_INFO_T* grid /* out */) { int old_rank; int dimensions[2]; int wrap_around[2]; int coordinates[2]; int free_coords[2]; /* Set up Global Grid Information */ MPI_Comm_size(MPI_COMM_WORLD, &(grid->p)); MPI_Comm_rank(MPI_COMM_WORLD, &old_rank); /* We assume p is a perfect square */ // but what if it's not a perfect square grid->q = (int) sqrt((double) grid->p); dimensions[0] = dimensions[1] = grid->q; /* We want a circular shift in second dimension. */ /* Don't care about first */ wrap_around[0] = wrap_around[1] = 1; MPI_Cart_create(MPI_COMM_WORLD, 2, dimensions, wrap_around, 1, &(grid->comm)); MPI_Comm_rank(grid->comm, &(grid->my_rank)); MPI_Cart_coords(grid->comm, grid->my_rank, 2, coordinates); grid->my_row = coordinates[0]; grid->my_col = coordinates[1]; /* Set up row communicators */ free_coords[0] = 0; free_coords[1] = 1; MPI_Cart_sub(grid->comm, free_coords, &(grid->row_comm)); /* Set up column communicators */ free_coords[0] = 1; free_coords[1] = 0; MPI_Cart_sub(grid->comm, free_coords, &(grid->col_comm)); } /* Setup_grid */ /*********************************************************/ void Fox( int n /* in */, GRID_INFO_T* grid /* in */, LOCAL_MATRIX_T* local_A /* in */, LOCAL_MATRIX_T* local_B /* in */, LOCAL_MATRIX_T* local_C /* out */) { LOCAL_MATRIX_T* temp_A; /* Storage for the sub- */ /* matrix of A used during */ /* the current stage */ int stage; int bcast_root; int n_bar; /* n/sqrt(p) */ int source; int dest; MPI_Status status; n_bar = n/grid->q; Set_to_zero(local_C); /* Calculate addresses for row circular shift of B */ source = (grid->my_row + 1) % grid->q; dest = (grid->my_row + grid->q - 1) % grid->q; /* Set aside storage for the broadcast block of A */ temp_A = Local_matrix_allocate(n_bar); for (stage = 0; stage < grid->q; stage++) { bcast_root = (grid->my_row + stage) % grid->q; if (bcast_root == grid->my_col) { // Process P_{ii} broadcast A_{ii} in process gird's row commnunicator MPI_Bcast(local_A, 1, local_matrix_mpi_t, bcast_root, grid->row_comm); Local_matrix_multiply(local_A, local_B, local_C); } else { // temp_A is a buffer for process P_{ij} to store A_{ij} MPI_Bcast(temp_A, 1, local_matrix_mpi_t, bcast_root, grid->row_comm); Local_matrix_multiply(temp_A, local_B, local_C); } MPI_Sendrecv_replace(local_B, 1, local_matrix_mpi_t, // MPI send and receive with single buffer dest, 0, source, 0, grid->col_comm, &status); // Circular shift of process grid B's row, after local multiplication operation } /* for */ } /* Fox */ /*********************************************************/ LOCAL_MATRIX_T* Local_matrix_allocate(int local_order) { LOCAL_MATRIX_T* temp; temp = (LOCAL_MATRIX_T*) malloc(sizeof(LOCAL_MATRIX_T)); return temp; } /* Local_matrix_allocate */ /*********************************************************/ void Free_local_matrix( LOCAL_MATRIX_T** local_A_ptr /* in/out */) { free(*local_A_ptr); } /* Free_local_matrix */ /*********************************************************/ /* Read and distribute matrix for matrix A: * foreach global row of the matrix, * foreach grid column * read a block of n_bar floats on process 0 * and send them to the appropriate process. */ void Read_matrix_A( char* prompt /* in */, LOCAL_MATRIX_T* local_A /* out */, GRID_INFO_T* grid /* in */, int n /* in */) { FILE *fp; int mat_row, mat_col; int grid_row, grid_col; int dest; int coords[2]; FLOAT* temp; MPI_Status status; if (grid->my_rank == 0) { // Process 0 read matrix input from stdin and send them to other processess fp = fopen("A.dat","r"); temp = (FLOAT*) malloc(Order(local_A)*sizeof(FLOAT)); printf("%s\n", prompt); fflush(stdout); for (mat_row = 0; mat_row < n; mat_row++) { grid_row = mat_row/Order(local_A); coords[0] = grid_row; for (grid_col = 0; grid_col < grid->q; grid_col++) { coords[1] = grid_col; MPI_Cart_rank(grid->comm, coords, &dest); if (dest == 0) { for (mat_col = 0; mat_col < Order(local_A); mat_col++) fscanf(fp, "%lf", (local_A->entries)+mat_row*Order(local_A)+mat_col); /* scanf("%lf", (local_A->entries)+mat_row*Order(local_A)+mat_col); */ } else { for(mat_col = 0; mat_col < Order(local_A); mat_col++) fscanf(fp,"%lf", temp + mat_col); // scanf("%lf", temp + mat_col); MPI_Send(temp, Order(local_A), FLOAT_MPI, dest, 0, grid->comm); } } } free(temp); fclose(fp); } else { // Other processess receive matrix from process 0 for (mat_row = 0; mat_row < Order(local_A); mat_row++) MPI_Recv(&Entry(local_A, mat_row, 0), Order(local_A), FLOAT_MPI, 0, 0, grid->comm, &status); } } /* Read_matrix */ /*********************************************************/ /* Read and distribute matrix for local matrix B's transpose: * foreach global row of the matrix, * foreach grid column * read a block of n_bar floats on process 0 * and send them to the appropriate process. */ void Read_matrix_B( char* prompt /* in */, LOCAL_MATRIX_T* local_B /* out */, GRID_INFO_T* grid /* in */, int n /* in */) { FILE *fp; int mat_row, mat_col; int grid_row, grid_col; int dest; int coords[2]; FLOAT *temp; MPI_Status status; if (grid->my_rank == 0) { // Process 0 read matrix input from stdin and send them to other processess fp = fopen("B.dat","r"); temp = (FLOAT*) malloc(Order(local_B)*sizeof(FLOAT)); printf("%s\n", prompt); fflush(stdout); for (mat_row = 0; mat_row < n; mat_row++) { grid_row = mat_row/Order(local_B); coords[0] = grid_row; for (grid_col = 0; grid_col < grid->q; grid_col++) { coords[1] = grid_col; MPI_Cart_rank(grid->comm, coords, &dest); if (dest == 0) { // process 0 (local) for (mat_col = 0; mat_col < Order(local_B); mat_col++) fscanf(fp, "%lf", (local_B->entries)+mat_col*Order(local_B)+mat_row); // switch rows and colums in local_B, for column major storage /* scanf("%lf", (local_B->entries)+mat_col*Order(local_B)+mat_row); // switch rows and colums in local_B, for column major storage */ /* scanf("%lf", (local_A->entries)+mat_row*Order(local_A)+mat_col); */ } else { for(mat_col = 0; mat_col < Order(local_B); mat_col++) fscanf(fp, "%lf", temp + mat_col); // scanf("%lf", temp + mat_col); MPI_Send(temp, Order(local_B), FLOAT_MPI, dest, 0, grid->comm); } } } free(temp); fclose(fp); } else { // Other processess receive matrix from process 0 temp = (FLOAT*) malloc(Order(local_B)*sizeof(FLOAT)); // switch rows and colums in local_B, for column major storage for (mat_col = 0; mat_col < Order(local_B); mat_col++) { MPI_Recv(temp, Order(local_B), FLOAT_MPI, 0, 0, grid->comm, &status); // switch rows and colums in local_B, for column major storage for(mat_row = 0; mat_row < Order(local_B); mat_row++) Entry(local_B, mat_row, mat_col) = *(temp + mat_row); // switch rows and colums in local_B, for column major storage /* MPI_Recv(&Entry(local_A, mat_row, 0), Order(local_A), FLOAT_MPI, 0, 0, grid->comm, &status); */ } free(temp); } } /* Read_matrix_B */ /*********************************************************/ /* Recive and Print Matrix A: * foreach global row of the matrix, * foreach grid column * send n_bar floats to process 0 from each other process * receive a block of n_bar floats on process 0 from other processes and print them */ void Print_matrix_A( char* title /* in */, LOCAL_MATRIX_T* local_A /* out */, GRID_INFO_T* grid /* in */, int n /* in */) { int mat_row, mat_col; int grid_row, grid_col; int source; int coords[2]; FLOAT* temp; MPI_Status status; if (grid->my_rank == 0) { temp = (FLOAT*) malloc(Order(local_A)*sizeof(FLOAT)); printf("%s\n", title); for (mat_row = 0; mat_row < n; mat_row++) { grid_row = mat_row/Order(local_A); coords[0] = grid_row; for (grid_col = 0; grid_col < grid->q; grid_col++) { coords[1] = grid_col; MPI_Cart_rank(grid->comm, coords, &source); if (source == 0) { for(mat_col = 0; mat_col < Order(local_A); mat_col++) printf("%20.15E ", Entry(local_A, mat_row, mat_col)); } else { MPI_Recv(temp, Order(local_A), FLOAT_MPI, source, 0, grid->comm, &status); for(mat_col = 0; mat_col < Order(local_A); mat_col++) printf("%20.15E ", temp[mat_col]); } } printf("\n"); } free(temp); } else { for (mat_row = 0; mat_row < Order(local_A); mat_row++) MPI_Send(&Entry(local_A, mat_row, 0), Order(local_A), FLOAT_MPI, 0, 0, grid->comm); } } /* Print_matrix_A */ /*********************************************************/ /* Recive and Print Matrix for local matrix B's transpose: * foreach global row of the matrix, * foreach grid column * send n_bar floats to process 0 from each other process * receive a block of n_bar floats on process 0 from other processes and print them */ void Print_matrix_B( char* title /* in */, LOCAL_MATRIX_T* local_B /* out */, GRID_INFO_T* grid /* in */, int n /* in */) { int mat_row, mat_col; int grid_row, grid_col; int source; int coords[2]; FLOAT* temp; MPI_Status status; if (grid->my_rank == 0) { temp = (FLOAT*) malloc(Order(local_B)*sizeof(FLOAT)); printf("%s\n", title); for (mat_row = 0; mat_row < n; mat_row++) { grid_row = mat_row/Order(local_B); coords[0] = grid_row; for (grid_col = 0; grid_col < grid->q; grid_col++) { coords[1] = grid_col; MPI_Cart_rank(grid->comm, coords, &source); if (source == 0) { for(mat_col = 0; mat_col < Order(local_B); mat_col++) printf("%20.15E ", Entry(local_B, mat_col, mat_row)); // switch rows and colums in local_B, for column major storage // printf("%20.15E ", Entry(local_A, mat_row, mat_col)); } else { MPI_Recv(temp, Order(local_B), FLOAT_MPI, source, 0, grid->comm, &status); for(mat_col = 0; mat_col < Order(local_B); mat_col++) printf("%20.15E ", temp[mat_col]); } } printf("\n"); } free(temp); } else { temp = (FLOAT*) malloc(Order(local_B)*sizeof(FLOAT)); for (mat_col = 0; mat_col < Order(local_B); mat_col++) { for(mat_row = 0; mat_row < Order(local_B); mat_row++) *(temp+mat_row) = Entry(local_B, mat_row, mat_col); // switch rows and colums in local_B, for column major storage MPI_Send(temp, Order(local_B), FLOAT_MPI, 0, 0, grid->comm); } free(temp); } } /* Print_matrix_B */ /*********************************************************/ /* Recive and Print Matrix A: * foreach global row of the matrix, * foreach grid column * send n_bar floats to process 0 from each other process * receive a block of n_bar floats on process 0 from other processes and print them */ void Print_matrix_C( char* title /* in */, LOCAL_MATRIX_T* local_C /* out */, GRID_INFO_T* grid /* in */, int n /* in */) { int mat_row, mat_col; int grid_row, grid_col; int source; int coords[2]; FLOAT* temp; MPI_Status status; if (grid->my_rank == 0) { temp = (FLOAT*) malloc(Order(local_C)*sizeof(FLOAT)); printf("%s\n", title); for (mat_row = 0; mat_row < n; mat_row++) { grid_row = mat_row/Order(local_C); coords[0] = grid_row; for (grid_col = 0; grid_col < grid->q; grid_col++) { coords[1] = grid_col; MPI_Cart_rank(grid->comm, coords, &source); if (source == 0) { for(mat_col = 0; mat_col < Order(local_C); mat_col++) printf("%20.15E ", Entry(local_C, mat_row, mat_col)); } else { MPI_Recv(temp, Order(local_C), FLOAT_MPI, source, 0, grid->comm, &status); for(mat_col = 0; mat_col < Order(local_C); mat_col++) printf("%20.15E ", temp[mat_col]); } } printf("\n"); } free(temp); } else { for (mat_row = 0; mat_row < Order(local_C); mat_row++) MPI_Send(&Entry(local_C, mat_row, 0), Order(local_C), FLOAT_MPI, 0, 0, grid->comm); } } /* Print_matrix_C */ /*********************************************************/ /* Recive and Write Matrix C into a file: * foreach global row of the matrix, * foreach grid column * send n_bar floats to process 0 from each other process * receive a block of n_bar floats on process 0 from other processes and print them */ void Write_matrix_C( char* title /* in */, LOCAL_MATRIX_T* local_C /* out */, GRID_INFO_T* grid /* in */, int n /* in */) { FILE *fp; int mat_row, mat_col; int grid_row, grid_col; int source; int coords[2]; FLOAT* temp; MPI_Status status; if (grid->my_rank == 0) { fp = fopen("C.dat", "w+"); temp = (FLOAT*) malloc(Order(local_C)*sizeof(FLOAT)); printf("%s\n", title); for (mat_row = 0; mat_row < n; mat_row++) { grid_row = mat_row/Order(local_C); coords[0] = grid_row; for (grid_col = 0; grid_col < grid->q; grid_col++) { coords[1] = grid_col; MPI_Cart_rank(grid->comm, coords, &source); if (source == 0) { for(mat_col = 0; mat_col < Order(local_C); mat_col++) fprintf(fp, "%20.15E ", Entry(local_C, mat_row, mat_col)); // printf("%20.15E ", Entry(local_A, mat_row, mat_col)); } else { MPI_Recv(temp, Order(local_C), FLOAT_MPI, source, 0, grid->comm, &status); for(mat_col = 0; mat_col < Order(local_C); mat_col++) fprintf(fp, "%20.15E ", temp[mat_col]); // printf("%20.15E ", temp[mat_col]); } } fprintf(fp,"\n"); } free(temp); fclose(fp); } else { for (mat_row = 0; mat_row < Order(local_C); mat_row++) MPI_Send(&Entry(local_C, mat_row, 0), Order(local_C), FLOAT_MPI, 0, 0, grid->comm); } } /* Write_matrix_C */ /*********************************************************/ /* * Set local matrix's element to zero */ void Set_to_zero( LOCAL_MATRIX_T* local_A /* out */) { int i, j; for (i = 0; i < Order(local_A); i++) for (j = 0; j < Order(local_A); j++) Entry(local_A,i,j) = 0.0E0; } /* Set_to_zero */ /*********************************************************/ void Build_matrix_type( LOCAL_MATRIX_T* local_A /* in */) { MPI_Datatype temp_mpi_t; int block_lengths[2]; MPI_Aint displacements[2]; MPI_Datatype typelist[2]; MPI_Aint start_address; MPI_Aint address; MPI_Type_contiguous(Order(local_A)*Order(local_A), FLOAT_MPI, &temp_mpi_t); // Creates a contiguous datatype /* Synopsis int MPI_Type_contiguous(int count, MPI_Datatype oldtype, MPI_Datatype *newtype) Input Parameters count replication count (nonnegative integer) oldtype old datatype (handle) */ block_lengths[0] = block_lengths[1] = 1; typelist[0] = MPI_INT; typelist[1] = temp_mpi_t; MPI_Address(local_A, &start_address); // Gets the address of a location in caller's memory MPI_Address(&(local_A->n_bar), &address); /* Synopsis int MPI_Address(const void *location, MPI_Aint *address) Input Parameters location location in caller memory (choice) Output Parameters address address of location (address integer) */ displacements[0] = address - start_address; MPI_Address(local_A->entries, &address); displacements[1] = address - start_address; MPI_Type_struct(2, block_lengths, displacements, typelist, &local_matrix_mpi_t); // Creates a struct datatype /* Synopsis int MPI_Type_struct(int count, const int *array_of_blocklengths, const MPI_Aint *array_of_displacements, const MPI_Datatype *array_of_types, MPI_Datatype *newtype) Input Parameters count number of blocks (integer) -- also number of entries in arrays array_of_types , array_of_displacements and array_of_blocklengths array_of_blocklengths number of elements in each block (array) array_of_displacements byte displacement of each block (array) array_of_types type of elements in each block (array of handles to datatype objects) Output Parameters newtype new datatype (handle) */ MPI_Type_commit(&local_matrix_mpi_t); // Commits the datatype /* Synopsis int MPI_Type_commit(MPI_Datatype *datatype) Input Parameters datatype datatype (handle) */ } /* Build_matrix_type */ /*********************************************************/ /* local matrix multiplication function * withing OpenMP Thread Acceleration */ void Local_matrix_multiply( LOCAL_MATRIX_T* local_A /* in */, LOCAL_MATRIX_T* local_B /* in */, LOCAL_MATRIX_T* local_C /* out */) { int i, j, k; // int my_rank; // MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); // Get my process id in the MPI communicator #pragma omp parallel for private(i, j, k) shared(local_A, local_B, local_C) num_threads(NUM_THREADS) // Threads acceleration upgrade, parallel task split for (i = 0; i < Order(local_A); i++) { // printf("Current in the Fox Kernel:\n my process id is %d, my thread id is %d\n",my_rank,omp_get_thread_num()); for (j = 0; j < Order(local_A); j++) for (k = 0; k < Order(local_B); k++) Entry(local_C,i,j) = Entry(local_C,i,j) // switch rows and colums in local_B, for column major storage + Entry(local_A,i,k)*Entry(local_B,j,k); // continuous memory access, local matrix multiplication A(i,k)*B^T(j,k) /* Entry(local_C,i,j) = Entry(local_C,i,j) + Entry(local_A,i,k)*Entry(local_B,k,j); // non-continuous memory access, A(i,k)*B^T(j,k) is more proper */ } } /* Local_matrix_multiply */ /*********************************************************/ /* Recive and Print Local Matrix A: * Process 0 print local matrix local_A * Other Processess send local matrix local_A to process 0 * And process 0 receive local matrix local_A from other processess */ void Print_local_matrices_A( char* title /* in */, LOCAL_MATRIX_T* local_A /* in */, GRID_INFO_T* grid /* in */) { int coords[2]; int i, j; int source; MPI_Status status; // print by process No.0 in process mesh if (grid->my_rank == 0) { printf("%s\n", title); printf("Process %d > grid_row = %d, grid_col = %d\n", grid->my_rank, grid->my_row, grid->my_col); for (i = 0; i < Order(local_A); i++) { for (j = 0; j < Order(local_A); j++) printf("%20.15E ", Entry(local_A,i,j)); printf("\n"); } for (source = 1; source < grid->p; source++) { MPI_Recv(temp_mat, 1, local_matrix_mpi_t, source, 0, grid->comm, &status); MPI_Cart_coords(grid->comm, source, 2, coords); printf("Process %d > grid_row = %d, grid_col = %d\n", source, coords[0], coords[1]); for (i = 0; i < Order(temp_mat); i++) { for (j = 0; j < Order(temp_mat); j++) printf("%20.15E ", Entry(temp_mat,i,j)); printf("\n"); } } fflush(stdout); } else { MPI_Send(local_A, 1, local_matrix_mpi_t, 0, 0, grid->comm); } } /* Print_local_matrices_A */ /*********************************************************/ /* Recive and Print Local Matrix for local matrix B's transpose: * Process 0 print local matrix local_A * Other Processess send local matrix local_A to process 0 * And process 0 receive local matrix local_A from other processess */ void Print_local_matrices_B( char* title /* in */, LOCAL_MATRIX_T* local_B /* in */, GRID_INFO_T* grid /* in */) { int coords[2]; int i, j; int source; MPI_Status status; // print by process No.0 in process mesh if (grid->my_rank == 0) { printf("%s\n", title); printf("Process %d > grid_row = %d, grid_col = %d\n", grid->my_rank, grid->my_row, grid->my_col); for (i = 0; i < Order(local_B); i++) { for (j = 0; j < Order(local_B); j++) printf("%20.15E ", Entry(local_B,j,i)); // switch rows and colums in local_B, for column major storage printf("\n"); } for (source = 1; source < grid->p; source++) { MPI_Recv(temp_mat, 1, local_matrix_mpi_t, source, 0, grid->comm, &status); MPI_Cart_coords(grid->comm, source, 2, coords); printf("Process %d > grid_row = %d, grid_col = %d\n", source, coords[0], coords[1]); for (i = 0; i < Order(temp_mat); i++) { for (j = 0; j < Order(temp_mat); j++) printf("%20.15E ", Entry(temp_mat,j,i)); // switch rows and colums in local_B, for column major storage printf("\n"); } } fflush(stdout); } else { MPI_Send(local_B, 1, local_matrix_mpi_t, 0, 0, grid->comm); } } /* Print_local_matrices_B */ /*********************************************************/ /* Recive and Print Local Matrix A: * Process 0 print local matrix local_A * Other Processess send local matrix local_A to process 0 * And process 0 receive local matrix local_A from other processess */ void Print_local_matrices_C( char* title /* in */, LOCAL_MATRIX_T* local_C /* in */, GRID_INFO_T* grid /* in */) { int coords[2]; int i, j; int source; MPI_Status status; // print by process No.0 in process mesh if (grid->my_rank == 0) { printf("%s\n", title); printf("Process %d > grid_row = %d, grid_col = %d\n", grid->my_rank, grid->my_row, grid->my_col); for (i = 0; i < Order(local_C); i++) { for (j = 0; j < Order(local_C); j++) printf("%20.15E ", Entry(local_C,i,j)); printf("\n"); } for (source = 1; source < grid->p; source++) { MPI_Recv(temp_mat, 1, local_matrix_mpi_t, source, 0, grid->comm, &status); MPI_Cart_coords(grid->comm, source, 2, coords); printf("Process %d > grid_row = %d, grid_col = %d\n", source, coords[0], coords[1]); for (i = 0; i < Order(temp_mat); i++) { for (j = 0; j < Order(temp_mat); j++) printf("%20.15E ", Entry(temp_mat,i,j)); printf("\n"); } } fflush(stdout); } else { MPI_Send(local_C, 1, local_matrix_mpi_t, 0, 0, grid->comm); } } /* Print_local_matrices_C */ /*********************************************************/ /* Recive and Write Local Matrix A: * Process 0 print local matrix local_A * Other Processess send local matrix local_A to process 0 * And process 0 receive local matrix local_A from other processess */ void Write_local_matrices_A( char* title /* in */, LOCAL_MATRIX_T* local_A /* in */, GRID_INFO_T* grid /* in */) { FILE *fp; int coords[2]; int i, j; int source; MPI_Status status; // print by process No.0 in process mesh if (grid->my_rank == 0) { fp = fopen("local_A.dat","w+"); printf("%s\n", title); fprintf(fp,"Process %d > grid_row = %d, grid_col = %d\n", grid->my_rank, grid->my_row, grid->my_col); for (i = 0; i < Order(local_A); i++) { for (j = 0; j < Order(local_A); j++) fprintf(fp,"%20.15E ", Entry(local_A,i,j)); fprintf(fp, "\n"); } for (source = 1; source < grid->p; source++) { MPI_Recv(temp_mat, 1, local_matrix_mpi_t, source, 0, grid->comm, &status); MPI_Cart_coords(grid->comm, source, 2, coords); fprintf(fp, "Process %d > grid_row = %d, grid_col = %d\n", source, coords[0], coords[1]); for (i = 0; i < Order(temp_mat); i++) { for (j = 0; j < Order(temp_mat); j++) fprintf(fp, "%20.15E ", Entry(temp_mat,i,j)); fprintf(fp, "\n"); } } fflush(stdout); fclose(fp); } else { MPI_Send(local_A, 1, local_matrix_mpi_t, 0, 0, grid->comm); } } /* Write_local_matrices_A */ /*********************************************************/ /* Recive and Write Local Matrix for local matrix B's transpose: * Process 0 print local matrix local_A * Other Processess send local matrix local_A to process 0 * And process 0 receive local matrix local_A from other processess */ void Write_local_matrices_B( char* title /* in */, LOCAL_MATRIX_T* local_B /* in */, GRID_INFO_T* grid /* in */) { FILE *fp; int coords[2]; int i, j; int source; MPI_Status status; // print by process No.0 in process mesh if (grid->my_rank == 0) { fp = fopen("local_B.dat","w+"); printf("%s\n", title); fprintf(fp, "Process %d > grid_row = %d, grid_col = %d\n", grid->my_rank, grid->my_row, grid->my_col); for (i = 0; i < Order(local_B); i++) { for (j = 0; j < Order(local_B); j++) fprintf(fp, "%20.15E ", Entry(local_B,j,i)); // switch rows and colums in local_B, for column major storage fprintf(fp, "\n"); } for (source = 1; source < grid->p; source++) { MPI_Recv(temp_mat, 1, local_matrix_mpi_t, source, 0, grid->comm, &status); MPI_Cart_coords(grid->comm, source, 2, coords); fprintf(fp, "Process %d > grid_row = %d, grid_col = %d\n", source, coords[0], coords[1]); for (i = 0; i < Order(temp_mat); i++) { for (j = 0; j < Order(temp_mat); j++) fprintf(fp, "%20.15E ", Entry(temp_mat,j,i)); // switch rows and colums in local_B, for column major storage fprintf(fp, "\n"); } } fflush(stdout); fclose(fp); } else { MPI_Send(local_B, 1, local_matrix_mpi_t, 0, 0, grid->comm); } } /* Write_local_matrices_B */ /*********************************************************/ /* Recive and Write Local Matrix C: * Process 0 print local matrix local_C * Other Processess send local matrix local_C to process 0 * And process 0 receive local matrix local_C from other processess */ void Write_local_matrices_C( char* title /* in */, LOCAL_MATRIX_T* local_C /* in */, GRID_INFO_T* grid /* in */) { FILE *fp; int coords[2]; int i, j; int source; MPI_Status status; // print by process No.0 in process mesh if (grid->my_rank == 0) { fp = fopen("local_C.dat","w+"); printf("%s\n", title); fprintf(fp, "Process %d > grid_row = %d, grid_col = %d\n", grid->my_rank, grid->my_row, grid->my_col); for (i = 0; i < Order(local_C); i++) { for (j = 0; j < Order(local_C); j++) fprintf(fp, "%20.15E ", Entry(local_C,i,j)); fprintf(fp, "\n"); } for (source = 1; source < grid->p; source++) { MPI_Recv(temp_mat, 1, local_matrix_mpi_t, source, 0, grid->comm, &status); MPI_Cart_coords(grid->comm, source, 2, coords); fprintf(fp, "Process %d > grid_row = %d, grid_col = %d\n", source, coords[0], coords[1]); for (i = 0; i < Order(temp_mat); i++) { for (j = 0; j < Order(temp_mat); j++) fprintf(fp, "%20.15E ", Entry(temp_mat,i,j)); fprintf(fp, "\n"); } } fflush(stdout); fclose(fp); } else { MPI_Send(local_C, 1, local_matrix_mpi_t, 0, 0, grid->comm); } } /* Write_local_matrices_C */
GB_binop__pair_uint64.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__pair_uint64) // A.*B function (eWiseMult): GB ((none)) // A.*B function (eWiseMult): GB ((none)) // A.*B function (eWiseMult): GB ((none)) // A.*B function (eWiseMult): GB ((none)) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__pair_uint64) // C+=b function (dense accum): GB (_Cdense_accumb__pair_uint64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__pair_uint64) // C=scalar+B GB ((none)) // C=scalar+B' GB ((none)) // C=A+scalar GB ((none)) // C=A'+scalar GB ((none)) // C type: uint64_t // A type: uint64_t // B,b type: uint64_t // BinaryOp: cij = 1 #define GB_ATYPE \ uint64_t #define GB_BTYPE \ uint64_t #define GB_CTYPE \ uint64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ ; // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ ; // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = 1 ; // 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_PAIR || GxB_NO_UINT64 || GxB_NO_PAIR_UINT64) //------------------------------------------------------------------------------ // 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__pair_uint64) ( 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__pair_uint64) ( 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__pair_uint64) ( 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 uint64_t uint64_t bwork = (*((uint64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, 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 uint64_t *restrict Cx = (uint64_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *restrict Cx = (uint64_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__pair_uint64) ( 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, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( 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 } #endif //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( 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 } #endif //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( 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 } #endif //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( 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 } #endif //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( 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 uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t x = (*((uint64_t *) x_input)) ; uint64_t *Bx = (uint64_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 ; ; ; Cx [p] = 1 ; } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( 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 ; uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t *Ax = (uint64_t *) Ax_input ; uint64_t y = (*((uint64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; ; ; Cx [p] = 1 ; } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ #if 0 // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ ; ; \ Cx [pC] = 1 ; \ } GrB_Info GB ((none)) ( 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 \ uint64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t x = (*((const uint64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint64_t } #endif //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ #if 0 // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ ; ; \ Cx [pC] = 1 ; \ } GrB_Info GB ((none)) ( 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 uint64_t y = (*((const uint64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif #endif
sample_sections_barrier_single_master.c
/* Andre Augusto Giannotti Scota (https://sites.google.com/view/a2gs/) */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <omp.h> #include "openmp_util.h" int main(int argc, char *argv[]) { /* #pragma omp parallel num_threads(3) */ /* omp_set_num_threads(2); */ dumpEnviroment(); printf("Starting...\n\n"); #pragma omp parallel { DEBUG(printf("Start section a\n");) function_a(0); DEBUG(printf("Start section a\n\n");) DEBUG(printf("Start section b (sleep)\n");) function_b(1); DEBUG(printf("End section b\n\n");) /* Explicit barrier */ #pragma omp barrier /* Only one thread will run this */ #pragma omp single printf("-----------------------------\n"); DEBUG(printf("Start section c\n");) function_c(0); DEBUG(printf("End section c\n\n");) #pragma omp single { DEBUG(printf("Start section d\n");) function_d(0); DEBUG(printf("End section d\n\n");) } /* Only master (0) thread will run this */ #pragma omp master { printf("Only master thread print this. Thread Id: [%d]\n", omp_get_thread_num()); sleep(1); } /* Implicit barrier here */ } printf("End.\n"); return(0); }
hypercube.h
#ifndef ANT_H #define ANT_H #include <new> #include <omp.h> #include <string> #include <random> #include <cstdio> #include <math.h> #include <vector> #include <numeric> #include <iomanip> #include <iostream> #include <algorithm> #include <nmmintrin.h> #define ARMA_WARN_LEVEL 1 #include <armadillo> namespace BMC { void no_memory () { printf("Sorry, we can't operate at this dimension - "); printf("too many wormholes and tears in space-time-continuum."); std::exit(1); } class HyperCube { public: int v; int dim; double* eta; HyperCube(int src, int dst, int n_threads=50, int n_dimensions=3){ dim = n_dimensions; v = 1 << std::max(n_dimensions,1); omp_set_num_threads(std::max(n_threads,1)); std::set_new_handler(no_memory); q = new double* [v-1]; l = new double* [v-1]; u = new double* [v-1]; eta = new double[v-1](); if (n_dimensions < 1 || n_threads < 1){ printf("Received invalid parameters.\n");return; } if (src == dst){printf("You're already here! (0s)\n");} else if (dst >= v){ printf("Oops, %d doesn't exist in this dimension (%d is max)", dst, v-1); printf(" (inf s - try going to a few dimensions up!)\n"); } else{ build_matrices(dst); fill_matrix(l); fill_matrix(u); decompose_lu(q); sanitize(u,0); // upper triangular sanitize(l,1); // lower triangular eta = solve_lu(); int t = avg_time(src); printf("The estimated travel time from %d (blue)", src); printf(" to %d (red) is currently %d s.\n", dst, t); } } ~HyperCube(){ delete[] q; delete[] l; delete[] u; delete[] eta; } void build_matrices(int dst){ #pragma omp parallel for shared(q,l,u) schedule(static) for (int i = 0; i < v; ++i){ q[i] = new double[v-1](); l[i] = new double[v-1](); u[i] = new double[v-1](); } #pragma omp parallel for schedule(static) for(int i = 0; i < v; ++i){ for(int s = 0; s < dim; ++s){ if (i == dst) {continue;} q[i][i^(1<<s)] = 1.0/dim; // printf("%d, %d\n", i, i^(1<<s)); } } #pragma omp parallel for schedule(static) for (int idx = 0; idx < v*v; ++idx){ int r = idx/v; int c = idx%v; q[r][c] = ((r == c) ? 1.0 : 0.0) - q[r][c]; } } void fill_matrix(double** mat, int diag=0){ std::random_device rd; std::default_random_engine gen(rd()); std::uniform_real_distribution<double> dist(0.1,1.0); #pragma omp parallel for schedule(static) for (int idx = 0; idx < v*v; ++idx){ if (diag && idx/v != idx%v) continue; mat[idx/v][idx%v] = dist(gen); } } double* fill_vec(double* vec, double val){ #pragma omp parallel for schedule(static) for (int i = 0; i < v; ++i){ vec[i] = val; } return vec; } void decompose_lu(double** mat){ int r = 0; int k = 0; omp_lock_t lock; omp_init_lock(&lock); for (int x = 0; x < v; ++x){ for (int y = 0; y < v; ++y){ if (y < x) l[y][x] = 0; else { l[y][x] = mat[y][x]; #pragma omp parallel for schedule(static) for (int z = 0; z < x; z++){ l[y][x] = l[y][x] - l[y][z] * u[z][x]; } } } for (int y = 0; y < v; ++y){ if (y < x) u[x][y] = 0; if (y == x) u[x][y] = 1; else{ u[x][y] = mat[x][y] / l[x][x]; #pragma omp parallel for schedule(static) for (int z = 0; z < x; z++){ u[x][y] = u[x][y] - ((l[x][z] * u[z][y])/l[x][x]); } } } } omp_destroy_lock(&lock); } void sanitize(double** mat, int wipe_upper){ #pragma omp parallel for schedule(static) for (int idx = 0; idx < v*v; ++idx){ int r = idx/v; int c = idx%v; if (wipe_upper == 1 && r < c) mat[r][c] = 0; else if (!wipe_upper && r > c) mat[r][c] = 0; } } void solver(double** mat, double* b){ omp_lock_t lock; omp_init_lock(&lock); #pragma omp parallel for collapse(3) schedule(static) for (int i = 0; i < v; i++){ for (int k = i; k < v; k++){ for (int j = 0; j < v; j++){ mat[k+1][j] -= (mat[k+1][i]/mat[i][i]) * mat[i][j]; } } } #pragma omp parallel for collapse(2) schedule(static) for (int i = v-1; i >= 0; --i){ for (int j = v-1; j > i; --j){ b[i] -= mat[i][j] * b[j]; } b[i] /= mat[i][i]; } omp_destroy_lock(&lock); } arma::mat _dpp2arma(double** mat, int n_rows, int n_cols){ arma::mat A(n_rows, n_cols, arma::fill::randu); #pragma omp parallel for schedule(static) for (int i = 0; i < n_rows; ++i){ for (int j = 0; j < n_cols; ++j){ A(i,j) = mat[i][j]; } } return A; } double** _arma2dpp(arma::mat A){ double** a = new double* [A.n_cols]; #pragma omp parallel for schedule(static) for (int i = 0; i < A.n_rows; ++i){ for (int j = 0; j < A.n_cols; ++j){ a[i][j] = A(i,j); } } #pragma omp parallel for schedule(static) for (int i = 0; i < A.n_cols; ++i){ a[i] = new double[A.n_rows](); } return a; } double* _arma2dp(arma::vec V){ double* a = new double[V.n_elem](); #pragma omp parallel for schedule(static) for (int i = 0; i < V.n_elem; ++i){ a[i] = V(i); } return a; } arma::vec _dp2arma(double* V, int n_elem){ arma::vec w(n_elem); #pragma omp parallel for schedule(static) for (int i = 0; i < n_elem; ++i){ w(i) = V[i]; } return w; } double* solve_lu(){ arma::mat L = _dpp2arma(l,v,v); arma::mat U = _dpp2arma(u,v,v); arma::vec y = arma::zeros(v); y = arma::solve(trimatl(L), arma::ones(v), \ arma::solve_opts::equilibrate + arma::solve_opts::allow_ugly + arma::solve_opts::refine); return _arma2dp(arma::solve(trimatu(U), y, \ arma::solve_opts::equilibrate + arma::solve_opts::allow_ugly + arma::solve_opts::refine)); } int avg_time(int src){ float sum = eta[src]; #pragma omp parallel for reduction(+:sum) schedule(static) for(int s = 0; s < dim; ++s){ sum += eta[src^(1<<s)]; } return rint((0.95*sum)/(dim+1)); // adjust for float carryover } private: double** q; double** l; double** u; }; } #endif
OffchainWithdrawalCircuit.h
#ifndef _OFFCHAINWITHDRAWALCIRCUIT_H_ #define _OFFCHAINWITHDRAWALCIRCUIT_H_ #include "Circuit.h" #include "../Utils/Constants.h" #include "../Utils/Data.h" #include "../Utils/Utils.h" #include "../Gadgets/AccountGadgets.h" #include "ethsnarks.hpp" #include "utils.hpp" #include "gadgets/subadd.hpp" using namespace ethsnarks; namespace Loopring { class OffchainWithdrawalGadget : public GadgetT { public: const Constants& constants; // User state // 用户可以指定支付费用的token,支付费用之前token的余额值 BalanceGadget balanceFBefore; BalanceGadget balanceBefore; AccountGadget accountBefore; // Operator state BalanceGadget balanceBefore_O; // Inputs DualVariableGadget accountID; DualVariableGadget tokenID; DualVariableGadget amountRequested; DualVariableGadget feeTokenID; DualVariableGadget fee; // Fee as float FloatGadget fFee; RequireAccuracyGadget requireAccuracyFee; // Fee payment from the user to the operator subadd_gadget feePayment; // Calculate how much can be withdrawn MinGadget amountToWithdraw; FloatGadget amountWithdrawn; RequireAccuracyGadget requireAccuracyAmountWithdrawn; // Calculate the new balance // 计算新的余额值 UnsafeSubGadget balance_after; // Increase the nonce of the user by 1 // nonce++ AddGadget nonce_after; // Update User UpdateBalanceGadget updateBalanceF_A; UpdateBalanceGadget updateBalance_A; UpdateAccountGadget updateAccount_A; // Update Operator UpdateBalanceGadget updateBalanceF_O; // Signature Poseidon_gadget_T<8, 1, 6, 53, 7, 1> hash; SignatureVerifier signatureVerifier; OffchainWithdrawalGadget( ProtoboardT& pb, const jubjub::Params& params, const Constants& _constants, const VariableT& accountsMerkleRoot, const VariableT& operatorBalancesRoot, const VariableT& blockExchangeID, const std::string& prefix ) : GadgetT(pb, prefix), constants(_constants), // User state // 用户之前的账户状态 balanceFBefore(pb, FMT(prefix, ".balanceFBefore")), balanceBefore(pb, FMT(prefix, ".balanceBefore")), accountBefore(pb, FMT(prefix, ".accountBefore")), // Operator state balanceBefore_O(pb, FMT(prefix, ".balanceBefore_O")), // Inputs accountID(pb, NUM_BITS_ACCOUNT, FMT(prefix, ".accountID")), tokenID(pb, NUM_BITS_TOKEN, FMT(prefix, ".tokenID")), amountRequested(pb, NUM_BITS_AMOUNT, FMT(prefix, ".amountRequested")), feeTokenID(pb, NUM_BITS_TOKEN, FMT(prefix, ".feeTokenID")), fee(pb, NUM_BITS_AMOUNT, FMT(prefix, ".fee")), // Fee as float fFee(pb, constants, Float16Encoding, FMT(prefix, ".fFee")), requireAccuracyFee(pb, fFee.value(), fee.packed, Float16Accuracy, NUM_BITS_AMOUNT, FMT(prefix, ".requireAccuracyFee")), // Fee payment from the user to the operator // 用户给操作员进行转账 feePayment(pb, NUM_BITS_AMOUNT, balanceFBefore.balance, balanceBefore_O.balance, fFee.value(), FMT(prefix, ".feePayment")), // Calculate how much can be withdrawn // 要求退款金额和账户当前金额取最小值 amountToWithdraw(pb, amountRequested.packed, balanceBefore.balance, NUM_BITS_AMOUNT, FMT(prefix, ".min(amountRequested, balance)")), // 退款数量 amountWithdrawn(pb, constants, Float24Encoding, FMT(prefix, ".amountWithdrawn")), // 获得指定精确的amountWithdrawn值 requireAccuracyAmountWithdrawn(pb, amountWithdrawn.value(), amountToWithdraw.result(), Float24Accuracy, NUM_BITS_AMOUNT, FMT(prefix, ".requireAccuracyAmountRequested")), // Calculate the new balance balance_after(pb, balanceBefore.balance, amountWithdrawn.value(), FMT(prefix, ".balance_after")), // Increase the nonce of the user by 1 nonce_after(pb, accountBefore.nonce, constants.one, NUM_BITS_NONCE, FMT(prefix, ".nonce_after")), // Update User // 更新用户费用账户的balance // 更新费用root updateBalanceF_A(pb, accountBefore.balancesRoot, feeTokenID.bits, {balanceFBefore.balance, balanceFBefore.tradingHistory}, {feePayment.X, balanceFBefore.tradingHistory}, FMT(prefix, ".updateBalanceF_A")), // 更新用户金额账户的balance // 更新金额root updateBalance_A(pb, updateBalanceF_A.result(), tokenID.bits, {balanceBefore.balance, balanceBefore.tradingHistory}, {balance_after.result(), balanceBefore.tradingHistory}, FMT(prefix, ".updateBalance_A")), // 更新account的根节点 updateAccount_A(pb, accountsMerkleRoot, accountID.bits, {accountBefore.publicKey.x, accountBefore.publicKey.y, accountBefore.nonce, accountBefore.balancesRoot}, {accountBefore.publicKey.x, accountBefore.publicKey.y, nonce_after.result(), updateBalance_A.result()}, FMT(prefix, ".updateAccount_A")), // Update Operator // operatorBalancesRoot为operator接收费用之前的根节点状态 updateBalanceF_O(pb, operatorBalancesRoot, feeTokenID.bits, {balanceBefore_O.balance, balanceBefore_O.tradingHistory}, {feePayment.Y, balanceBefore_O.tradingHistory}, FMT(prefix, ".updateBalanceF_O")), // Signature // 验证签名,哈希使用posedion哈希,签名算法使用EdDSA hash(pb, var_array({ blockExchangeID, accountID.packed, tokenID.packed, amountRequested.packed, feeTokenID.packed, fee.packed, accountBefore.nonce }), FMT(this->annotation_prefix, ".hash")), signatureVerifier(pb, params, constants, accountBefore.publicKey, hash.result(), FMT(prefix, ".signatureVerifier")) { } void generate_r1cs_witness(const OffchainWithdrawal& withdrawal) { // User state balanceFBefore.generate_r1cs_witness(withdrawal.balanceUpdateF_A.before); balanceBefore.generate_r1cs_witness(withdrawal.balanceUpdateW_A.before); accountBefore.generate_r1cs_witness(withdrawal.accountUpdate_A.before); // Operator state balanceBefore_O.generate_r1cs_witness(withdrawal.balanceUpdateF_O.before); // Inputs accountID.generate_r1cs_witness(pb, withdrawal.accountUpdate_A.accountID); tokenID.generate_r1cs_witness(pb, withdrawal.balanceUpdateW_A.tokenID); amountRequested.generate_r1cs_witness(pb, withdrawal.amountRequested); feeTokenID.generate_r1cs_witness(pb, withdrawal.balanceUpdateF_A.tokenID); fee.generate_r1cs_witness(pb, withdrawal.fee); // Fee as float fFee.generate_r1cs_witness(toFloat(withdrawal.fee, Float16Encoding)); requireAccuracyFee.generate_r1cs_witness(); // Fee payment from the user to the operator feePayment.generate_r1cs_witness(); // Calculate how much can be withdrawn amountToWithdraw.generate_r1cs_witness(); amountWithdrawn.generate_r1cs_witness(toFloat(pb.val(amountToWithdraw.result()), Float24Encoding)); requireAccuracyAmountWithdrawn.generate_r1cs_witness(); // Calculate the new balance balance_after.generate_r1cs_witness(); // Increase the nonce of the user by 1 nonce_after.generate_r1cs_witness(); // Update User updateBalanceF_A.generate_r1cs_witness(withdrawal.balanceUpdateF_A.proof); updateBalance_A.generate_r1cs_witness(withdrawal.balanceUpdateW_A.proof); updateAccount_A.generate_r1cs_witness(withdrawal.accountUpdate_A.proof); // Update Operator updateBalanceF_O.generate_r1cs_witness(withdrawal.balanceUpdateF_O.proof); // Check signature hash.generate_r1cs_witness(); signatureVerifier.generate_r1cs_witness(withdrawal.signature); } void generate_r1cs_constraints() { // Inputs accountID.generate_r1cs_constraints(true); tokenID.generate_r1cs_constraints(true); amountRequested.generate_r1cs_constraints(true); feeTokenID.generate_r1cs_constraints(true); fee.generate_r1cs_constraints(true); // Fee as float fFee.generate_r1cs_constraints(); requireAccuracyFee.generate_r1cs_constraints(); // Fee payment from the user to the operator feePayment.generate_r1cs_constraints(); // Calculate how much can be withdrawn amountToWithdraw.generate_r1cs_constraints(); amountWithdrawn.generate_r1cs_constraints(); requireAccuracyAmountWithdrawn.generate_r1cs_constraints(); // Calculate the new balance balance_after.generate_r1cs_constraints(); // Increase the nonce of the user by 1 nonce_after.generate_r1cs_constraints(); // Update User updateBalanceF_A.generate_r1cs_constraints(); updateBalance_A.generate_r1cs_constraints(); updateAccount_A.generate_r1cs_constraints(); // Update Operator updateBalanceF_O.generate_r1cs_constraints(); // Check signature hash.generate_r1cs_constraints(); signatureVerifier.generate_r1cs_constraints(); } const std::vector<VariableArrayT> getApprovedWithdrawalData() const { return {VariableArrayT(6, constants.zero), tokenID.bits, accountID.bits, amountWithdrawn.bits()}; } const std::vector<VariableArrayT> getDataAvailabilityData() const { return {VariableArrayT(6, constants.zero), feeTokenID.bits, fFee.bits()}; } const VariableT& getNewAccountsRoot() const { return updateAccount_A.result(); } const VariableT& getNewOperatorBalancesRoot() const { return updateBalanceF_O.result(); } }; class OffchainWithdrawalCircuit : public Circuit { public: PublicDataGadget publicData; Constants constants; jubjub::Params params; // State AccountGadget accountBefore_O; // Inputs DualVariableGadget exchangeID; DualVariableGadget merkleRootBefore; DualVariableGadget merkleRootAfter; DualVariableGadget operatorAccountID; // Operator account check RequireNotZeroGadget publicKeyX_notZero; // Withdrawals bool onchainDataAvailability; unsigned int numWithdrawals; std::vector<OffchainWithdrawalGadget> withdrawals; // Update Operator std::unique_ptr<UpdateAccountGadget> updateAccount_O; OffchainWithdrawalCircuit(ProtoboardT& pb, const std::string& prefix) : Circuit(pb, prefix), publicData(pb, FMT(prefix, ".publicData")), constants(pb, FMT(prefix, ".constants")), // State accountBefore_O(pb, FMT(prefix, ".accountBefore_O")), // Inputs exchangeID(pb, NUM_BITS_EXCHANGE_ID, FMT(prefix, ".exchangeID")), merkleRootBefore(pb, 256, FMT(prefix, ".merkleRootBefore")), merkleRootAfter(pb, 256, FMT(prefix, ".merkleRootAfter")), operatorAccountID(pb, NUM_BITS_ACCOUNT, FMT(prefix, ".operatorAccountID")), // Operator account check publicKeyX_notZero(pb, accountBefore_O.publicKey.x, FMT(prefix, ".publicKeyX_notZero")) { } void generateConstraints(bool onchainDataAvailability, unsigned int blockSize) override { this->onchainDataAvailability = onchainDataAvailability; this->numWithdrawals = blockSize; constants.generate_r1cs_constraints(); // Inputs exchangeID.generate_r1cs_constraints(true); merkleRootBefore.generate_r1cs_constraints(true); merkleRootAfter.generate_r1cs_constraints(true); operatorAccountID.generate_r1cs_constraints(true); // Operator account check publicKeyX_notZero.generate_r1cs_constraints(); // Withdrawals withdrawals.reserve(numWithdrawals); for (size_t j = 0; j < numWithdrawals; j++) { VariableT withdrawalAccountsRoot = (j == 0) ? merkleRootBefore.packed : withdrawals.back().getNewAccountsRoot(); VariableT withdrawalOperatorBalancesRoot = (j == 0) ? accountBefore_O.balancesRoot : withdrawals.back().getNewOperatorBalancesRoot(); withdrawals.emplace_back( pb, params, constants, withdrawalAccountsRoot, withdrawalOperatorBalancesRoot, exchangeID.packed, std::string("withdrawals_") + std::to_string(j) ); // 每次更新withdraw的账户状态,只是保留修改operator操作费用的balanceRoot,最后对balanceRoot进行一次更新 withdrawals.back().generate_r1cs_constraints(); } // Update Operator // 最后更新一次balanceRoot updateAccount_O.reset(new UpdateAccountGadget(pb, withdrawals.back().getNewAccountsRoot(), operatorAccountID.bits, {accountBefore_O.publicKey.x, accountBefore_O.publicKey.y, accountBefore_O.nonce, accountBefore_O.balancesRoot}, {accountBefore_O.publicKey.x, accountBefore_O.publicKey.y, accountBefore_O.nonce, withdrawals.back().getNewOperatorBalancesRoot()}, FMT(annotation_prefix, ".updateAccount_O"))); updateAccount_O->generate_r1cs_constraints(); // Public data publicData.add(exchangeID.bits); publicData.add(merkleRootBefore.bits); publicData.add(merkleRootAfter.bits); // Store the approved data for all withdrawals for (auto& withdrawal : withdrawals) { publicData.add(withdrawal.getApprovedWithdrawalData()); } // Data availability if (onchainDataAvailability) { publicData.add(operatorAccountID.bits); for (auto& withdrawal : withdrawals) { publicData.add(withdrawal.getDataAvailabilityData()); } } publicData.generate_r1cs_constraints(); // Check the new merkle root // 检查merkletreeRoot的值 requireEqual(pb, updateAccount_O->result(), merkleRootAfter.packed, "newMerkleRoot"); } bool generateWitness(const OffchainWithdrawalBlock& block) { constants.generate_r1cs_witness(); // State accountBefore_O.generate_r1cs_witness(block.accountUpdate_O.before); // Inputs exchangeID.generate_r1cs_witness(pb, block.exchangeID); merkleRootBefore.generate_r1cs_witness(pb, block.merkleRootBefore); merkleRootAfter.generate_r1cs_witness(pb, block.merkleRootAfter); operatorAccountID.generate_r1cs_witness(pb, block.operatorAccountID); // Operator account check publicKeyX_notZero.generate_r1cs_witness(); // Withdrawals #ifdef MULTICORE #pragma omp parallel for #endif for(unsigned int i = 0; i < block.withdrawals.size(); i++) { withdrawals[i].generate_r1cs_witness(block.withdrawals[i]); } // Update Operator updateAccount_O->generate_r1cs_witness(block.accountUpdate_O.proof); // Public data publicData.generate_r1cs_witness(); return true; } bool generateWitness(const json& input) override { return generateWitness(input.get<Loopring::OffchainWithdrawalBlock>()); } BlockType getBlockType() override { return BlockType::OffchainWithdrawal; } unsigned int getBlockSize() override { return numWithdrawals; } void printInfo() override { std::cout << pb.num_constraints() << " constraints (" << (pb.num_constraints() / numWithdrawals) << "/offchain withdrawal)" << std::endl; } }; } #endif
matrix.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M M AAA TTTTT RRRR IIIII X X % % MM MM A A T R R I X X % % M M M AAAAA T RRRR I X % % M M A A T R R I X X % % M M A A T R R IIIII X X % % % % % % MagickCore Matrix Methods % % % % Software Design % % Cristy % % August 2007 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % 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 "MagickCore/studio.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image-private.h" #include "MagickCore/matrix.h" #include "MagickCore/memory_.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/resource_.h" #include "MagickCore/semaphore.h" #include "MagickCore/thread-private.h" #include "MagickCore/utility.h" /* Typedef declaration. */ struct _MatrixInfo { CacheType type; size_t columns, rows, stride; MagickSizeType length; MagickBooleanType mapped, synchronize; char path[MagickPathExtent]; int file; void *elements; SemaphoreInfo *semaphore; size_t signature; }; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e M a t r i x I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireMatrixInfo() allocates the ImageInfo structure. % % The format of the AcquireMatrixInfo method is: % % MatrixInfo *AcquireMatrixInfo(const size_t columns,const size_t rows, % const size_t stride,ExceptionInfo *exception) % % A description of each parameter follows: % % o columns: the matrix columns. % % o rows: the matrix rows. % % o stride: the matrix stride. % % o exception: return any errors or warnings in this structure. % */ #if defined(SIGBUS) static void MatrixSignalHandler(int status) { ThrowFatalException(CacheFatalError,"UnableToExtendMatrixCache"); } #endif static inline MagickOffsetType WriteMatrixElements( const MatrixInfo *magick_restrict matrix_info,const MagickOffsetType offset, const MagickSizeType length,const unsigned char *magick_restrict buffer) { register MagickOffsetType i; ssize_t count; #if !defined(MAGICKCORE_HAVE_PWRITE) LockSemaphoreInfo(matrix_info->semaphore); if (lseek(matrix_info->file,offset,SEEK_SET) < 0) { UnlockSemaphoreInfo(matrix_info->semaphore); return((MagickOffsetType) -1); } #endif count=0; for (i=0; i < (MagickOffsetType) length; i+=count) { #if !defined(MAGICKCORE_HAVE_PWRITE) count=write(matrix_info->file,buffer+i,(size_t) MagickMin(length-i, (MagickSizeType) SSIZE_MAX)); #else count=pwrite(matrix_info->file,buffer+i,(size_t) MagickMin(length-i, (MagickSizeType) SSIZE_MAX),(off_t) (offset+i)); #endif if (count <= 0) { count=0; if (errno != EINTR) break; } } #if !defined(MAGICKCORE_HAVE_PWRITE) UnlockSemaphoreInfo(matrix_info->semaphore); #endif return(i); } static MagickBooleanType SetMatrixExtent( MatrixInfo *magick_restrict matrix_info, MagickSizeType length) { MagickOffsetType count, extent, offset; if (length != (MagickSizeType) ((MagickOffsetType) length)) return(MagickFalse); offset=(MagickOffsetType) lseek(matrix_info->file,0,SEEK_END); if (offset < 0) return(MagickFalse); if ((MagickSizeType) offset >= length) return(MagickTrue); extent=(MagickOffsetType) length-1; count=WriteMatrixElements(matrix_info,extent,1,(const unsigned char *) ""); #if defined(MAGICKCORE_HAVE_POSIX_FALLOCATE) if (matrix_info->synchronize != MagickFalse) (void) posix_fallocate(matrix_info->file,offset+1,extent-offset); #endif #if defined(SIGBUS) (void) signal(SIGBUS,MatrixSignalHandler); #endif return(count != (MagickOffsetType) 1 ? MagickFalse : MagickTrue); } MagickExport MatrixInfo *AcquireMatrixInfo(const size_t columns, const size_t rows,const size_t stride,ExceptionInfo *exception) { char *synchronize; MagickBooleanType status; MatrixInfo *matrix_info; matrix_info=(MatrixInfo *) AcquireMagickMemory(sizeof(*matrix_info)); if (matrix_info == (MatrixInfo *) NULL) return((MatrixInfo *) NULL); (void) ResetMagickMemory(matrix_info,0,sizeof(*matrix_info)); matrix_info->signature=MagickCoreSignature; matrix_info->columns=columns; matrix_info->rows=rows; matrix_info->stride=stride; matrix_info->semaphore=AcquireSemaphoreInfo(); synchronize=GetEnvironmentValue("MAGICK_SYNCHRONIZE"); if (synchronize != (const char *) NULL) { matrix_info->synchronize=IsStringTrue(synchronize); synchronize=DestroyString(synchronize); } matrix_info->length=(MagickSizeType) columns*rows*stride; if (matrix_info->columns != (size_t) (matrix_info->length/rows/stride)) { (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "CacheResourcesExhausted","`%s'","matrix cache"); return(DestroyMatrixInfo(matrix_info)); } matrix_info->type=MemoryCache; status=AcquireMagickResource(AreaResource,matrix_info->length); if ((status != MagickFalse) && (matrix_info->length == (MagickSizeType) ((size_t) matrix_info->length))) { status=AcquireMagickResource(MemoryResource,matrix_info->length); if (status != MagickFalse) { matrix_info->mapped=MagickFalse; matrix_info->elements=AcquireMagickMemory((size_t) matrix_info->length); if (matrix_info->elements == NULL) { matrix_info->mapped=MagickTrue; matrix_info->elements=MapBlob(-1,IOMode,0,(size_t) matrix_info->length); } if (matrix_info->elements == (unsigned short *) NULL) RelinquishMagickResource(MemoryResource,matrix_info->length); } } matrix_info->file=(-1); if (matrix_info->elements == (unsigned short *) NULL) { status=AcquireMagickResource(DiskResource,matrix_info->length); if (status == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "CacheResourcesExhausted","`%s'","matrix cache"); return(DestroyMatrixInfo(matrix_info)); } matrix_info->type=DiskCache; (void) AcquireMagickResource(MemoryResource,matrix_info->length); matrix_info->file=AcquireUniqueFileResource(matrix_info->path); if (matrix_info->file == -1) return(DestroyMatrixInfo(matrix_info)); status=AcquireMagickResource(MapResource,matrix_info->length); if (status != MagickFalse) { status=SetMatrixExtent(matrix_info,matrix_info->length); if (status != MagickFalse) { matrix_info->elements=(void *) MapBlob(matrix_info->file,IOMode,0, (size_t) matrix_info->length); if (matrix_info->elements != NULL) matrix_info->type=MapCache; else RelinquishMagickResource(MapResource,matrix_info->length); } } } return(matrix_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e M a g i c k M a t r i x % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireMagickMatrix() allocates and returns a matrix in the form of an % array of pointers to an array of doubles, with all values pre-set to zero. % % This used to generate the two dimensional matrix, and vectors required % for the GaussJordanElimination() method below, solving some system of % simultanious equations. % % The format of the AcquireMagickMatrix method is: % % double **AcquireMagickMatrix(const size_t number_rows, % const size_t size) % % A description of each parameter follows: % % o number_rows: the number pointers for the array of pointers % (first dimension). % % o size: the size of the array of doubles each pointer points to % (second dimension). % */ MagickExport double **AcquireMagickMatrix(const size_t number_rows, const size_t size) { double **matrix; register ssize_t i, j; matrix=(double **) AcquireQuantumMemory(number_rows,sizeof(*matrix)); if (matrix == (double **) NULL) return((double **) NULL); for (i=0; i < (ssize_t) number_rows; i++) { matrix[i]=(double *) AcquireQuantumMemory(size,sizeof(*matrix[i])); if (matrix[i] == (double *) NULL) { for (j=0; j < i; j++) matrix[j]=(double *) RelinquishMagickMemory(matrix[j]); matrix=(double **) RelinquishMagickMemory(matrix); return((double **) NULL); } for (j=0; j < (ssize_t) size; j++) matrix[i][j]=0.0; } return(matrix); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y M a t r i x I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyMatrixInfo() dereferences a matrix, deallocating memory associated % with the matrix. % % The format of the DestroyImage method is: % % MatrixInfo *DestroyMatrixInfo(MatrixInfo *matrix_info) % % A description of each parameter follows: % % o matrix_info: the matrix. % */ MagickExport MatrixInfo *DestroyMatrixInfo(MatrixInfo *matrix_info) { assert(matrix_info != (MatrixInfo *) NULL); assert(matrix_info->signature == MagickCoreSignature); LockSemaphoreInfo(matrix_info->semaphore); switch (matrix_info->type) { case MemoryCache: { if (matrix_info->mapped == MagickFalse) matrix_info->elements=RelinquishMagickMemory(matrix_info->elements); else { (void) UnmapBlob(matrix_info->elements,(size_t) matrix_info->length); matrix_info->elements=(unsigned short *) NULL; } RelinquishMagickResource(MemoryResource,matrix_info->length); break; } case MapCache: { (void) UnmapBlob(matrix_info->elements,(size_t) matrix_info->length); matrix_info->elements=NULL; RelinquishMagickResource(MapResource,matrix_info->length); } case DiskCache: { if (matrix_info->file != -1) (void) close(matrix_info->file); (void) RelinquishUniqueFileResource(matrix_info->path); RelinquishMagickResource(DiskResource,matrix_info->length); break; } default: break; } UnlockSemaphoreInfo(matrix_info->semaphore); RelinquishSemaphoreInfo(&matrix_info->semaphore); return((MatrixInfo *) RelinquishMagickMemory(matrix_info)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G a u s s J o r d a n E l i m i n a t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GaussJordanElimination() returns a matrix in reduced row echelon form, % while simultaneously reducing and thus solving the augumented results % matrix. % % See also http://en.wikipedia.org/wiki/Gauss-Jordan_elimination % % The format of the GaussJordanElimination method is: % % MagickBooleanType GaussJordanElimination(double **matrix, % double **vectors,const size_t rank,const size_t number_vectors) % % A description of each parameter follows: % % o matrix: the matrix to be reduced, as an 'array of row pointers'. % % o vectors: the additional matrix argumenting the matrix for row reduction. % Producing an 'array of column vectors'. % % o rank: The size of the matrix (both rows and columns). % Also represents the number terms that need to be solved. % % o number_vectors: Number of vectors columns, argumenting the above matrix. % Usally 1, but can be more for more complex equation solving. % % Note that the 'matrix' is given as a 'array of row pointers' of rank size. % That is values can be assigned as matrix[row][column] where 'row' is % typically the equation, and 'column' is the term of the equation. % That is the matrix is in the form of a 'row first array'. % % However 'vectors' is a 'array of column pointers' which can have any number % of columns, with each column array the same 'rank' size as 'matrix'. % % This allows for simpler handling of the results, especially is only one % column 'vector' is all that is required to produce the desired solution. % % For example, the 'vectors' can consist of a pointer to a simple array of % doubles. when only one set of simultanious equations is to be solved from % the given set of coefficient weighted terms. % % double **matrix = AcquireMagickMatrix(8UL,8UL); % double coefficents[8]; % ... % GaussJordanElimination(matrix, &coefficents, 8UL, 1UL); % % However by specifing more 'columns' (as an 'array of vector columns', % you can use this function to solve a set of 'separable' equations. % % For example a distortion function where u = U(x,y) v = V(x,y) % And the functions U() and V() have separate coefficents, but are being % generated from a common x,y->u,v data set. % % Another example is generation of a color gradient from a set of colors at % specific coordients, such as a list x,y -> r,g,b,a. % % You can also use the 'vectors' to generate an inverse of the given 'matrix' % though as a 'column first array' rather than a 'row first array'. For % details see http://en.wikipedia.org/wiki/Gauss-Jordan_elimination % */ MagickPrivate MagickBooleanType GaussJordanElimination(double **matrix, double **vectors,const size_t rank,const size_t number_vectors) { #define GaussJordanSwap(x,y) \ { \ if ((x) != (y)) \ { \ (x)+=(y); \ (y)=(x)-(y); \ (x)=(x)-(y); \ } \ } double max, scale; register ssize_t i, j, k; ssize_t column, *columns, *pivots, row, *rows; columns=(ssize_t *) AcquireQuantumMemory(rank,sizeof(*columns)); rows=(ssize_t *) AcquireQuantumMemory(rank,sizeof(*rows)); pivots=(ssize_t *) AcquireQuantumMemory(rank,sizeof(*pivots)); if ((rows == (ssize_t *) NULL) || (columns == (ssize_t *) NULL) || (pivots == (ssize_t *) NULL)) { if (pivots != (ssize_t *) NULL) pivots=(ssize_t *) RelinquishMagickMemory(pivots); if (columns != (ssize_t *) NULL) columns=(ssize_t *) RelinquishMagickMemory(columns); if (rows != (ssize_t *) NULL) rows=(ssize_t *) RelinquishMagickMemory(rows); return(MagickFalse); } (void) ResetMagickMemory(columns,0,rank*sizeof(*columns)); (void) ResetMagickMemory(rows,0,rank*sizeof(*rows)); (void) ResetMagickMemory(pivots,0,rank*sizeof(*pivots)); column=0; row=0; for (i=0; i < (ssize_t) rank; i++) { max=0.0; for (j=0; j < (ssize_t) rank; j++) if (pivots[j] != 1) { for (k=0; k < (ssize_t) rank; k++) if (pivots[k] != 0) { if (pivots[k] > 1) return(MagickFalse); } else if (fabs(matrix[j][k]) >= max) { max=fabs(matrix[j][k]); row=j; column=k; } } pivots[column]++; if (row != column) { for (k=0; k < (ssize_t) rank; k++) GaussJordanSwap(matrix[row][k],matrix[column][k]); for (k=0; k < (ssize_t) number_vectors; k++) GaussJordanSwap(vectors[k][row],vectors[k][column]); } rows[i]=row; columns[i]=column; if (matrix[column][column] == 0.0) return(MagickFalse); /* sigularity */ scale=PerceptibleReciprocal(matrix[column][column]); matrix[column][column]=1.0; for (j=0; j < (ssize_t) rank; j++) matrix[column][j]*=scale; for (j=0; j < (ssize_t) number_vectors; j++) vectors[j][column]*=scale; for (j=0; j < (ssize_t) rank; j++) if (j != column) { scale=matrix[j][column]; matrix[j][column]=0.0; for (k=0; k < (ssize_t) rank; k++) matrix[j][k]-=scale*matrix[column][k]; for (k=0; k < (ssize_t) number_vectors; k++) vectors[k][j]-=scale*vectors[k][column]; } } for (j=(ssize_t) rank-1; j >= 0; j--) if (columns[j] != rows[j]) for (i=0; i < (ssize_t) rank; i++) GaussJordanSwap(matrix[i][rows[j]],matrix[i][columns[j]]); pivots=(ssize_t *) RelinquishMagickMemory(pivots); rows=(ssize_t *) RelinquishMagickMemory(rows); columns=(ssize_t *) RelinquishMagickMemory(columns); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t M a t r i x C o l u m n s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetMatrixColumns() returns the number of columns in the matrix. % % The format of the GetMatrixColumns method is: % % size_t GetMatrixColumns(const MatrixInfo *matrix_info) % % A description of each parameter follows: % % o matrix_info: the matrix. % */ MagickExport size_t GetMatrixColumns(const MatrixInfo *matrix_info) { assert(matrix_info != (MatrixInfo *) NULL); assert(matrix_info->signature == MagickCoreSignature); return(matrix_info->columns); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t M a t r i x E l e m e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetMatrixElement() returns the specifed element in the matrix. % % The format of the GetMatrixElement method is: % % MagickBooleanType GetMatrixElement(const MatrixInfo *matrix_info, % const ssize_t x,const ssize_t y,void *value) % % A description of each parameter follows: % % o matrix_info: the matrix columns. % % o x: the matrix x-offset. % % o y: the matrix y-offset. % % o value: return the matrix element in this buffer. % */ static inline ssize_t EdgeX(const ssize_t x,const size_t columns) { if (x < 0L) return(0L); if (x >= (ssize_t) columns) return((ssize_t) (columns-1)); return(x); } static inline ssize_t EdgeY(const ssize_t y,const size_t rows) { if (y < 0L) return(0L); if (y >= (ssize_t) rows) return((ssize_t) (rows-1)); return(y); } static inline MagickOffsetType ReadMatrixElements( const MatrixInfo *magick_restrict matrix_info,const MagickOffsetType offset, const MagickSizeType length,unsigned char *magick_restrict buffer) { register MagickOffsetType i; ssize_t count; #if !defined(MAGICKCORE_HAVE_PREAD) LockSemaphoreInfo(matrix_info->semaphore); if (lseek(matrix_info->file,offset,SEEK_SET) < 0) { UnlockSemaphoreInfo(matrix_info->semaphore); return((MagickOffsetType) -1); } #endif count=0; for (i=0; i < (MagickOffsetType) length; i+=count) { #if !defined(MAGICKCORE_HAVE_PREAD) count=read(matrix_info->file,buffer+i,(size_t) MagickMin(length-i, (MagickSizeType) SSIZE_MAX)); #else count=pread(matrix_info->file,buffer+i,(size_t) MagickMin(length-i, (MagickSizeType) SSIZE_MAX),(off_t) (offset+i)); #endif if (count <= 0) { count=0; if (errno != EINTR) break; } } #if !defined(MAGICKCORE_HAVE_PREAD) UnlockSemaphoreInfo(matrix_info->semaphore); #endif return(i); } MagickExport MagickBooleanType GetMatrixElement(const MatrixInfo *matrix_info, const ssize_t x,const ssize_t y,void *value) { MagickOffsetType count, i; assert(matrix_info != (const MatrixInfo *) NULL); assert(matrix_info->signature == MagickCoreSignature); i=(MagickOffsetType) EdgeY(y,matrix_info->rows)*matrix_info->columns+ EdgeX(x,matrix_info->columns); if (matrix_info->type != DiskCache) { (void) memcpy(value,(unsigned char *) matrix_info->elements+i* matrix_info->stride,matrix_info->stride); return(MagickTrue); } count=ReadMatrixElements(matrix_info,i*matrix_info->stride, matrix_info->stride,(unsigned char *) value); if (count != (MagickOffsetType) matrix_info->stride) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t M a t r i x R o w s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetMatrixRows() returns the number of rows in the matrix. % % The format of the GetMatrixRows method is: % % size_t GetMatrixRows(const MatrixInfo *matrix_info) % % A description of each parameter follows: % % o matrix_info: the matrix. % */ MagickExport size_t GetMatrixRows(const MatrixInfo *matrix_info) { assert(matrix_info != (const MatrixInfo *) NULL); assert(matrix_info->signature == MagickCoreSignature); return(matrix_info->rows); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + L e a s t S q u a r e s A d d T e r m s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LeastSquaresAddTerms() adds one set of terms and associate results to the % given matrix and vectors for solving using least-squares function fitting. % % The format of the AcquireMagickMatrix method is: % % void LeastSquaresAddTerms(double **matrix,double **vectors, % const double *terms,const double *results,const size_t rank, % const size_t number_vectors); % % A description of each parameter follows: % % o matrix: the square matrix to add given terms/results to. % % o vectors: the result vectors to add terms/results to. % % o terms: the pre-calculated terms (without the unknown coefficent % weights) that forms the equation being added. % % o results: the result(s) that should be generated from the given terms % weighted by the yet-to-be-solved coefficents. % % o rank: the rank or size of the dimensions of the square matrix. % Also the length of vectors, and number of terms being added. % % o number_vectors: Number of result vectors, and number or results being % added. Also represents the number of separable systems of equations % that is being solved. % % Example of use... % % 2 dimensional Affine Equations (which are separable) % c0*x + c2*y + c4*1 => u % c1*x + c3*y + c5*1 => v % % double **matrix = AcquireMagickMatrix(3UL,3UL); % double **vectors = AcquireMagickMatrix(2UL,3UL); % double terms[3], results[2]; % ... % for each given x,y -> u,v % terms[0] = x; % terms[1] = y; % terms[2] = 1; % results[0] = u; % results[1] = v; % LeastSquaresAddTerms(matrix,vectors,terms,results,3UL,2UL); % ... % if ( GaussJordanElimination(matrix,vectors,3UL,2UL) ) { % c0 = vectors[0][0]; % c2 = vectors[0][1]; % c4 = vectors[0][2]; % c1 = vectors[1][0]; % c3 = vectors[1][1]; % c5 = vectors[1][2]; % } % else % printf("Matrix unsolvable\n); % RelinquishMagickMatrix(matrix,3UL); % RelinquishMagickMatrix(vectors,2UL); % */ MagickPrivate void LeastSquaresAddTerms(double **matrix,double **vectors, const double *terms,const double *results,const size_t rank, const size_t number_vectors) { register ssize_t i, j; for (j=0; j < (ssize_t) rank; j++) { for (i=0; i < (ssize_t) rank; i++) matrix[i][j]+=terms[i]*terms[j]; for (i=0; i < (ssize_t) number_vectors; i++) vectors[i][j]+=results[i]*terms[j]; } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a t r i x T o I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MatrixToImage() returns a matrix as an image. The matrix elements must be % of type double otherwise nonsense is returned. % % The format of the MatrixToImage method is: % % Image *MatrixToImage(const MatrixInfo *matrix_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o matrix_info: the matrix. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MatrixToImage(const MatrixInfo *matrix_info, ExceptionInfo *exception) { CacheView *image_view; double max_value, min_value, scale_factor, value; Image *image; MagickBooleanType status; ssize_t y; assert(matrix_info != (const MatrixInfo *) NULL); assert(matrix_info->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (matrix_info->stride < sizeof(double)) return((Image *) NULL); /* Determine range of matrix. */ (void) GetMatrixElement(matrix_info,0,0,&value); min_value=value; max_value=value; for (y=0; y < (ssize_t) matrix_info->rows; y++) { register ssize_t x; for (x=0; x < (ssize_t) matrix_info->columns; x++) { if (GetMatrixElement(matrix_info,x,y,&value) == MagickFalse) continue; if (value < min_value) min_value=value; else if (value > max_value) max_value=value; } } if ((min_value == 0.0) && (max_value == 0.0)) scale_factor=0; else if (min_value == max_value) { scale_factor=(double) QuantumRange/min_value; min_value=0; } else scale_factor=(double) QuantumRange/(max_value-min_value); /* Convert matrix to image. */ image=AcquireImage((ImageInfo *) NULL,exception); image->columns=matrix_info->columns; image->rows=matrix_info->rows; image->colorspace=GRAYColorspace; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double value; register Quantum *q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if (GetMatrixElement(matrix_info,x,y,&value) == MagickFalse) continue; value=scale_factor*(value-min_value); *q=ClampToQuantum(value); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (status == MagickFalse) image=DestroyImage(image); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N u l l M a t r i x % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % NullMatrix() sets all elements of the matrix to zero. % % The format of the ResetMagickMemory method is: % % MagickBooleanType *NullMatrix(MatrixInfo *matrix_info) % % A description of each parameter follows: % % o matrix_info: the matrix. % */ MagickExport MagickBooleanType NullMatrix(MatrixInfo *matrix_info) { register ssize_t x; ssize_t count, y; unsigned char value; assert(matrix_info != (const MatrixInfo *) NULL); assert(matrix_info->signature == MagickCoreSignature); if (matrix_info->type != DiskCache) { (void) ResetMagickMemory(matrix_info->elements,0,(size_t) matrix_info->length); return(MagickTrue); } value=0; (void) lseek(matrix_info->file,0,SEEK_SET); for (y=0; y < (ssize_t) matrix_info->rows; y++) { for (x=0; x < (ssize_t) matrix_info->length; x++) { count=write(matrix_info->file,&value,sizeof(value)); if (count != (ssize_t) sizeof(value)) break; } if (x < (ssize_t) matrix_info->length) break; } return(y < (ssize_t) matrix_info->rows ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e l i n q u i s h M a g i c k M a t r i x % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RelinquishMagickMatrix() frees the previously acquired matrix (array of % pointers to arrays of doubles). % % The format of the RelinquishMagickMatrix method is: % % double **RelinquishMagickMatrix(double **matrix, % const size_t number_rows) % % A description of each parameter follows: % % o matrix: the matrix to relinquish % % o number_rows: the first dimension of the acquired matrix (number of % pointers) % */ MagickExport double **RelinquishMagickMatrix(double **matrix, const size_t number_rows) { register ssize_t i; if (matrix == (double **) NULL ) return(matrix); for (i=0; i < (ssize_t) number_rows; i++) matrix[i]=(double *) RelinquishMagickMemory(matrix[i]); matrix=(double **) RelinquishMagickMemory(matrix); return(matrix); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t M a t r i x E l e m e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetMatrixElement() sets the specifed element in the matrix. % % The format of the SetMatrixElement method is: % % MagickBooleanType SetMatrixElement(const MatrixInfo *matrix_info, % const ssize_t x,const ssize_t y,void *value) % % A description of each parameter follows: % % o matrix_info: the matrix columns. % % o x: the matrix x-offset. % % o y: the matrix y-offset. % % o value: set the matrix element to this value. % */ MagickExport MagickBooleanType SetMatrixElement(const MatrixInfo *matrix_info, const ssize_t x,const ssize_t y,const void *value) { MagickOffsetType count, i; assert(matrix_info != (const MatrixInfo *) NULL); assert(matrix_info->signature == MagickCoreSignature); i=(MagickOffsetType) y*matrix_info->columns+x; if ((i < 0) || ((MagickSizeType) (i*matrix_info->stride) >= matrix_info->length)) return(MagickFalse); if (matrix_info->type != DiskCache) { (void) memcpy((unsigned char *) matrix_info->elements+i* matrix_info->stride,value,matrix_info->stride); return(MagickTrue); } count=WriteMatrixElements(matrix_info,i*matrix_info->stride, matrix_info->stride,(unsigned char *) value); if (count != (MagickOffsetType) matrix_info->stride) return(MagickFalse); return(MagickTrue); }
Analyzer.h
#ifndef ANALYZER_H #define ANALYZER_H /************************************************************* * Copyright: (C) 2012 by Markus Schordan * * Author : Markus Schordan * * License : see file LICENSE in the CodeThorn distribution * *************************************************************/ #include <iostream> #include <fstream> #include <set> #include <string> #include <sstream> #include <omp.h> #include <boost/unordered_set.hpp> #include "AstTerm.h" #include "Labeler.h" #include "CFAnalysis.h" #include "RoseAst.h" #include "SgNodeHelper.h" #include "ExprAnalyzer.h" #include "StateRepresentations.h" #include "PropertyValueTable.h" // we use INT_MIN, INT_MAX #include "limits.h" namespace CodeThorn { #define DEBUGPRINT_STMT 0x1 #define DEBUGPRINT_STATE 0x2 #define DEBUGPRINT_STATEMOD 0x4 #define DEBUGPRINT_INFO 0x8 /*! * \author Markus Schordan * \date 2012. */ class AstNodeInfo : public AstAttribute { public: AstNodeInfo():label(0),initialLabel(0){} std::string toString() { std::stringstream ss; ss<<"\\n lab:"<<label<<" "; ss<<"init:"<<initialLabel<<" "; ss<<"final:"<<finalLabelsSet.toString(); return ss.str(); } void setLabel(Label l) { label=l; } void setInitialLabel(Label l) { initialLabel=l; } void setFinalLabels(LabelSet lset) { finalLabelsSet=lset; } private: Label label; Label initialLabel; LabelSet finalLabelsSet; }; typedef list<const EState*> EStateWorkList; typedef pair<int, const EState*> FailedAssertion; enum AnalyzerMode { AM_ALL_STATES, AM_LTL_STATES }; class Analyzer; class VariableValueMonitor { public: enum VariableMode { VARMODE_FORCED_TOP, VARMODE_ADAPTIVE_TOP, VARMODE_PRECISE, VARMODE_FORCED_PRECISE}; VariableValueMonitor(); void setThreshold(size_t threshold); size_t getThreshold(); bool isActive(); // the init function only uses the variableIds of a given estate (not its values) for initialization void init(const EState* estate); void init(const PState* pstate); VariableIdSet getHotVariables(Analyzer* analyzer, const EState* estate); VariableIdSet getHotVariables(Analyzer* analyzer, const PState* pstate); VariableIdSet getVariables(); void setVariableMode(VariableMode,VariableId); VariableMode getVariableMode(VariableId); void update(Analyzer* analyzer, EState* estate); bool isHotVariable(Analyzer* analyzer, VariableId varId); std::string toString(VariableIdMapping* variableIdMapping); #if 0 bool isVariableBeyondTreshold(Analyzer* analyzer, VariableId varId); #endif private: std::map<VariableId,std::set<int>* > _variablesMap; std::map<VariableId,VariableMode> _variablesModeMap; long int _threshold; }; /*! * \author Markus Schordan * \date 2012. */ class Analyzer { friend class Visualizer; friend class VariableValueMonitor; public: Analyzer(); ~Analyzer(); void initAstNodeInfo(SgNode* node); bool isActiveGlobalTopify(); static std::string nodeToString(SgNode* node); void initializeSolver1(std::string functionToStartAt,SgNode* root, bool oneFunctionOnly); void initializeTraceSolver(std::string functionToStartAt,SgNode* root); void continueAnalysisFrom(EState* newStartEState); PState analyzeAssignRhs(PState currentPState,VariableId lhsVar, SgNode* rhs,ConstraintSet& cset); EState analyzeVariableDeclaration(SgVariableDeclaration* nextNodeToAnalyze1,EState currentEState, Label targetLabel); list<EState> transferFunction(Edge edge, const EState* estate); void addToWorkList(const EState* estate); const EState* addToWorkListIfNew(EState estate); const EState* takeFromWorkList(); bool isInWorkList(const EState* estate); bool isEmptyWorkList(); const EState* topWorkList(); const EState* popWorkList(); void recordTransition(const EState* sourceEState, Edge e, const EState* targetEState); void printStatusMessage(bool); bool isLTLRelevantLabel(Label label); bool isStdIOLabel(Label label); bool isStartLabel(Label label); std::set<const EState*> nonLTLRelevantEStates(); bool isTerminationRelevantLabel(Label label); // 6 experimental functions // reduces all states different to stdin and stdout. void stdIOFoldingOfTransitionGraph(); void semanticFoldingOfTransitionGraph(); void semanticEliminationOfTransitions(); int semanticEliminationOfSelfInInTransitions(); // eliminates only input states int semanticEliminationOfDeadStates(); int semanticFusionOfInInTransitions(); // requires semantically reduced STG int semanticExplosionOfInputNodesFromOutputNodeConstraints(); bool checkEStateSet(); bool isConsistentEStatePtrSet(std::set<const EState*> estatePtrSet); bool checkTransitionGraph(); // this function requires that no LTL graph is computed void deleteNonRelevantEStates(); // bypasses and removes all states that are not standard I/O states void removeNonIOStates(); // bypasses and removes all states that are not stdIn/stdOut/stdErr/failedAssert states void reduceToObservableBehavior(); // erases transitions that lead directly from one output state to another output state void removeOutputOutputTransitions(); // erases transitions that lead directly from one input state to another input state void removeInputInputTransitions(); // cuts off all paths in the transition graph that lead to leaves // (recursively until only paths of infinite length remain) void pruneLeavesRec(); // connects start, input, output and worklist states according to possible paths in the transition graph. // removes all states and transitions that are not necessary for the graph that only consists of these new transitions. The two parameters allow to select input and/or output states to remain in the STG. void reduceGraphInOutWorklistOnly(bool includeIn=true, bool includeOut=true, bool includeErr=false); // extracts input sequences leading to each discovered failing assertion where discovered for the first time. // stores results in PropertyValueTable "reachabilityResults". // returns length of the longest of these sequences if it can be guaranteed that all processed traces are the // shortest ones leading to the individual failing assertion (returns -1 otherwise). int extractAssertionTraces(); private: /*! if state exists in stateSet, a pointer to the existing state is returned otherwise a new state is entered into stateSet and a pointer to it is returned. */ const PState* processNew(PState& s); const PState* processNewOrExisting(PState& s); const EState* processNew(EState& s); const EState* processNewOrExisting(EState& s); const EState* processCompleteNewOrExisting(const EState* es); void topifyVariable(PState& pstate, ConstraintSet& cset, VariableId varId); EStateSet::ProcessingResult process(EState& s); EStateSet::ProcessingResult process(Label label, PState pstate, ConstraintSet cset, InputOutput io); const ConstraintSet* processNewOrExisting(ConstraintSet& cset); EState createEState(Label label, PState pstate, ConstraintSet cset); EState createEState(Label label, PState pstate, ConstraintSet cset, InputOutput io); //returns a list of transitions representing existing paths from "startState" to all possible input/output/error states (no output -> output) // collection of transitions to worklist states currently disabled. the returned set has to be deleted by the calling function. boost::unordered_set<Transition*>* transitionsToInOutErrAndWorklist( const EState* startState, bool includeIn, bool includeOut, bool includeErr); boost::unordered_set<Transition*>* transitionsToInOutErrAndWorklist( const EState* currentState, const EState* startState, boost::unordered_set<Transition*>* results, boost::unordered_set<const EState*>* visited, bool includeIn, bool includeOut, bool includeErr); // adds a string representation of the shortest input path from start state to assertEState to reachabilityResults. returns the length of the // counterexample input sequence. int addCounterexample(int assertCode, const EState* assertEState); // returns a list of EStates from source to target. Target has to come before source in the STG (reversed trace). list<const EState*>reverseInOutSequenceBreadthFirst(const EState* source, const EState* target, bool counterexampleWithOutput = false); // returns a list of EStates from source to target (shortest input path). // please note: target has to be a predecessor of source (reversed trace) list<const EState*> reverseInOutSequenceDijkstra(const EState* source, const EState* target, bool counterexampleWithOutput = false); list<const EState*> filterStdInOutOnly(list<const EState*>& states, bool counterexampleWithOutput = false) const; std::string reversedInOutRunToString(list<const EState*>& run); //returns the shortest possible number of input states on the path leading to "target". int inputSequenceLength(const EState* target); public: SgNode* getCond(SgNode* node); void generateAstNodeInfo(SgNode* node); std::string generateSpotSTG(); private: void generateSpotTransition(std::stringstream& ss, const Transition& t); //less than comarisions on two states according to (#input transitions * #output transitions) bool indegreeTimesOutdegreeLessThan(const EState* a, const EState* b); public: //stores a backup of the created transitionGraph void storeStgBackup(); //load previous backup of the transitionGraph, storing the current version as a backup instead void swapStgWithBackup(); //solver 8 becomes the active solver used by the analyzer. Deletion of previous data iff "resetAnalyzerData" is set to true. void setAnalyzerToSolver8(EState* startEState, bool resetAnalyzerData); //! requires init void runSolver1(); void runSolver2(); void runSolver3(); void runSolver4(); void runSolver5(); void runSolver6(); void runSolver7(); void runSolver8(); void runSolver(); //! The analyzer requires a CFAnalysis to obtain the ICFG. void setCFAnalyzer(CFAnalysis* cf) { cfanalyzer=cf; } CFAnalysis* getCFAnalyzer() const { return cfanalyzer; } //void initializeVariableIdMapping(SgProject* project) { variableIdMapping.computeVariableSymbolMapping(project); } // access functions for computed information VariableIdMapping* getVariableIdMapping() { return &variableIdMapping; } SPRAY::IOLabeler* getLabeler() const { SPRAY::IOLabeler* ioLabeler=dynamic_cast<SPRAY::IOLabeler*>(cfanalyzer->getLabeler()); ROSE_ASSERT(ioLabeler); return ioLabeler; } Flow* getFlow() { return &flow; } PStateSet* getPStateSet() { return &pstateSet; } EStateSet* getEStateSet() { return &estateSet; } TransitionGraph* getTransitionGraph() { return &transitionGraph; } ConstraintSetMaintainer* getConstraintSetMaintainer() { return &constraintSetMaintainer; } //private: TODO Flow flow; SgNode* startFunRoot; CFAnalysis* cfanalyzer; VariableValueMonitor variableValueMonitor; void setVariableValueThreshold(int threshold) { variableValueMonitor.setThreshold(threshold); } public: //! compute the VariableIds of variable declarations VariableIdMapping::VariableIdSet determineVariableIdsOfVariableDeclarations(set<SgVariableDeclaration*> decls); //! compute the VariableIds of SgInitializedNamePtrList VariableIdMapping::VariableIdSet determineVariableIdsOfSgInitializedNames(SgInitializedNamePtrList& namePtrList); std::set<std::string> variableIdsToVariableNames(VariableIdMapping::VariableIdSet); typedef list<SgVariableDeclaration*> VariableDeclarationList; VariableDeclarationList computeUnusedGlobalVariableDeclarationList(SgProject* root); VariableDeclarationList computeUsedGlobalVariableDeclarationList(SgProject* root); //bool isAssertExpr(SgNode* node); bool isFailedAssertEState(const EState* estate); //! adds a specific code to the io-info of an estate which is checked by isFailedAsserEState and determines a failed-assert estate. Note that the actual assert (and its label) is associated with the previous estate (this information can therefore be obtained from a transition-edge in the transition graph). EState createFailedAssertEState(const EState estate, Label target); //! list of all asserts in a program list<SgNode*> listOfAssertNodes(SgProject *root); //! rers-specific error_x: assert(0) version list<pair<SgLabelStatement*,SgNode*> > listOfLabeledAssertNodes(SgProject *root); void initLabeledAssertNodes(SgProject* root) { _assertNodes=listOfLabeledAssertNodes(root); } size_t getNumberOfErrorLabels(); std::string labelNameOfAssertLabel(Label lab) { std::string labelName; for(list<pair<SgLabelStatement*,SgNode*> >::iterator i=_assertNodes.begin();i!=_assertNodes.end();++i) if(lab==getLabeler()->getLabel((*i).second)) labelName=SgNodeHelper::getLabelName((*i).first); //assert(labelName.size()>0); return labelName; } bool isCppLabeledAssertLabel(Label lab) { return labelNameOfAssertLabel(lab).size()>0; } InputOutput::OpType ioOp(const EState* estate) const; void setDisplayDiff(int diff) { _displayDiff=diff; } void setSolver(int solver) { _solver=solver; } int getSolver() { return _solver;} void setSemanticFoldThreshold(int t) { _semanticFoldThreshold=t; } void setLTLVerifier(int v) { _ltlVerifier=v; } int getLTLVerifier() { return _ltlVerifier; } void setNumberOfThreadsToUse(int n) { _numberOfThreadsToUse=n; } int getNumberOfThreadsToUse() { return _numberOfThreadsToUse; } void insertInputVarValue(int i) { _inputVarValues.insert(i); } void addInputSequenceValue(int i) { _inputSequence.push_back(i); } void resetToEmptyInputSequence() { _inputSequence.clear(); } void resetInputSequenceIterator() { _inputSequenceIterator=_inputSequence.begin(); } const EState* getEstateBeforeMissingInput() {return _estateBeforeMissingInput;} const EState* getLatestErrorEState() {return _latestErrorEState;} void setTreatStdErrLikeFailedAssert(bool x) { _treatStdErrLikeFailedAssert=x; } int numberOfInputVarValues() { return _inputVarValues.size(); } std::set<int> getInputVarValues() { return _inputVarValues; } list<pair<SgLabelStatement*,SgNode*> > _assertNodes; void setCsvAssertLiveFileName(std::string filename) { _csv_assert_live_file=filename; } VariableId globalVarIdByName(std::string varName) { return globalVarName2VarIdMapping[varName]; } void setStgTraceFileName(std::string filename) { _stg_trace_filename=filename; std::ofstream fout; fout.open(_stg_trace_filename.c_str()); // create new file/overwrite existing file fout<<"START"<<endl; fout.close(); // close. Will be used with append. } std::string _csv_assert_live_file; // to become private private: std::string _stg_trace_filename; public: // only used temporarily for binary-binding prototype std::map<std::string,VariableId> globalVarName2VarIdMapping; std::vector<bool> binaryBindingAssert; void setAnalyzerMode(AnalyzerMode am) { _analyzerMode=am; } void setMaxTransitions(size_t maxTransitions) { _maxTransitions=maxTransitions; } void setMaxTransitionsForcedTop(size_t maxTransitions) { _maxTransitionsForcedTop=maxTransitions; } void setMaxIterationsForcedTop(size_t maxIterations) { _maxIterationsForcedTop=maxIterations; } void eventGlobalTopifyTurnedOn(); void setMinimizeStates(bool minimizeStates) { _minimizeStates=minimizeStates; } bool isIncompleteSTGReady(); bool isPrecise(); PropertyValueTable reachabilityResults; int reachabilityAssertCode(const EState* currentEStatePtr); enum ExplorationMode { EXPL_DEPTH_FIRST, EXPL_BREADTH_FIRST, EXPL_LOOP_AWARE }; void setExplorationMode(ExplorationMode em) { _explorationMode=em; } ExplorationMode getExplorationMode() { return _explorationMode; } void setSkipSelectedFunctionCalls(bool defer) { _skipSelectedFunctionCalls=true; exprAnalyzer.setSkipSelectedFunctionCalls(true); } void setSkipArrayAccesses(bool skip) { exprAnalyzer.setSkipArrayAccesses(skip); } bool getSkipArrayAccesses() { return exprAnalyzer.getSkipArrayAccesses(); } ExprAnalyzer* getExprAnalyzer(); list<FailedAssertion> getFirstAssertionOccurences(){return _firstAssertionOccurences;} void incIterations() { if(isPrecise()) { #pragma omp atomic _iterations+=1; } else { #pragma omp atomic _approximated_iterations+=1; } } bool isLoopCondLabel(Label lab); int getApproximatedIterations() { return _approximated_iterations; } int getIterations() { return _iterations; } private: set<int> _inputVarValues; list<int> _inputSequence; list<int>::iterator _inputSequenceIterator; ExprAnalyzer exprAnalyzer; VariableIdMapping variableIdMapping; EStateWorkList estateWorkList; EStateSet estateSet; PStateSet pstateSet; ConstraintSetMaintainer constraintSetMaintainer; TransitionGraph transitionGraph; TransitionGraph backupTransitionGraph; set<const EState*> transitionSourceEStateSetOfLabel(Label lab); int _displayDiff; int _numberOfThreadsToUse; int _ltlVerifier; int _semanticFoldThreshold; VariableIdMapping::VariableIdSet _variablesToIgnore; int _solver; AnalyzerMode _analyzerMode; set<const EState*> _newNodesToFold; long int _maxTransitions; long int _maxTransitionsForcedTop; long int _maxIterationsForcedTop; bool _treatStdErrLikeFailedAssert; bool _skipSelectedFunctionCalls; ExplorationMode _explorationMode; list<FailedAssertion> _firstAssertionOccurences; const EState* _estateBeforeMissingInput; const EState* _latestOutputEState; const EState* _latestErrorEState; bool _minimizeStates; bool _topifyModeActive; int _iterations; int _approximated_iterations; int _curr_iteration_cnt; int _next_iteration_cnt; }; // end of class Analyzer } // end of namespace CodeThorn #define RERS_SPECIALIZATION #ifdef RERS_SPECIALIZATION // RERS-binary-binding-specific declarations #define STR_VALUE(arg) #arg #define COPY_PSTATEVAR_TO_GLOBALVAR(VARNAME) VARNAME[thread_id] = pstate[analyzer->globalVarIdByName(STR_VALUE(VARNAME))].getValue().getIntValue(); //cout<<"PSTATEVAR:"<<pstate[analyzer->globalVarIdByName(STR_VALUE(VARNAME))].toString()<<"="<<pstate[analyzer->globalVarIdByName(STR_VALUE(VARNAME))].getValue().toString()<<endl; #define COPY_GLOBALVAR_TO_PSTATEVAR(VARNAME) pstate[analyzer->globalVarIdByName(STR_VALUE(VARNAME))]=CodeThorn::AType::CppCapsuleConstIntLattice(VARNAME[thread_id]); // macro used to generate the initialization of global variables in the hybrid analyzer (linked binary with threads) #define INIT_GLOBALVAR(VARNAME) VARNAME = new int[numberOfThreads]; namespace RERS_Problem { void rersGlobalVarsCallInit(CodeThorn::Analyzer* analyzer, CodeThorn::PState& pstate, int thread_id); void rersGlobalVarsCallReturnInit(CodeThorn::Analyzer* analyzer, CodeThorn::PState& pstate, int thread_id); void rersGlobalVarsArrayInit(int numberOfThreads); #if 0 // input variable passed as a parameter (obsolete since transformation of "input" into a global varialbe) void calculate_output(int); #endif void calculate_output(int numberOfThreads); extern int* output; } // END OF RERS-binary-binding-specific declarations #endif #endif
GB_unaryop__ainv_fp64_int64.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_fp64_int64 // op(A') function: GB_tran__ainv_fp64_int64 // C type: double // A type: int64_t // cast: double cij = (double) aij // unaryop: cij = -aij #define GB_ATYPE \ int64_t #define GB_CTYPE \ double // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int64_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) \ double z = (double) 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_FP64 || GxB_NO_INT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__ainv_fp64_int64 ( double *restrict Cx, const int64_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_fp64_int64 ( 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
TuLi_Test.h
#pragma once namespace tinyDNN { void tuli_Conv_1() { LoadTuLi::load_Tuli(); LoadTuLi::load_Tuli_T(); std::shared_ptr<Inter_LayerQL<double>> in_01 = std::make_shared<Inter_LayerQL<double>>(128, 128); std::shared_ptr<LayerQL<double>> pool_01 = std::make_shared<PooLayerQL<double>>(Pool_Layer, 64, 64); //�ػ��� std::shared_ptr<Inter_LayerQL<double>> o_01 = in_01 + pool_01; // ���� �������� ���� ���� �����˿��� �����˼�Ƭ ������� std::shared_ptr<LayerQL<double>> conv_01 = std::make_shared<Conv_LayerQL<double>>(Conv_Layer, 32, 64, 64, 7, 1, 3); //������ std::shared_ptr<Inter_LayerQL<double>> o_02 = o_01 + conv_01; std::shared_ptr<LayerQL<double>> rule_01 = std::make_shared<Relu_LayerQL<double>>(Relu_Conv_Layer); //Relu�� std::shared_ptr<Inter_LayerQL<double>> o_03 = o_02 + rule_01; std::shared_ptr<LayerQL<double>> pool_02 = std::make_shared<PooLayerQL<double>>(Pool_Layer, 32, 32); //�ػ��� std::shared_ptr<Inter_LayerQL<double>> o_04 = o_03 + pool_02; // ���� �������� ���� ���� �����˿��� �����˼�Ƭ ������� std::shared_ptr<LayerQL<double>> conv_02 = std::make_shared<Conv_LayerQL<double>>(Conv_Layer, 32, 32, 32, 5, 32, 2); //������ std::shared_ptr<Inter_LayerQL<double>> o_05 = o_04 + conv_02; std::shared_ptr<LayerQL<double>> rule_02 = std::make_shared<Relu_LayerQL<double>>(Relu_Conv_Layer); //Relu�� std::shared_ptr<Inter_LayerQL<double>> o_06 = o_05 + rule_02; std::shared_ptr<LayerQL<double>> pool_03 = std::make_shared<PooLayerQL<double>>(Pool_Layer, 16, 16); //�ػ��� std::shared_ptr<Inter_LayerQL<double>> o_07 = o_06 + pool_03; // ���� �������� ���� ���� �����˿��� �����˼�Ƭ ������� std::shared_ptr<LayerQL<double>> conv_03 = std::make_shared<Conv_LayerQL<double>>(Conv_Layer, 16, 16, 16, 3, 32, 1); //������ std::shared_ptr<Inter_LayerQL<double>> o_08 = o_07 + conv_03; std::shared_ptr<LayerQL<double>> rule_03 = std::make_shared<Relu_LayerQL<double>>(Relu_Conv_Layer); //Relu�� std::shared_ptr<Inter_LayerQL<double>> o_09 = o_08 + rule_03; std::shared_ptr<LayerQL<double>> pool_04 = std::make_shared<PooLayerQL<double>>(Pool_Layer, 8, 8); //�ػ��� std::shared_ptr<Inter_LayerQL<double>> o_10 = o_09 + pool_04; std::shared_ptr<LayerQL<double>> dim_reduce_01 = std::make_shared<Dim_ReduceQL<double>>(Dim_Reduce_Layer, 16, 8, 8); //��ά�� std::shared_ptr<Inter_LayerQL<double>> o_11 = o_10 + dim_reduce_01; std::shared_ptr<LayerQL<double>> fullconnect_01 = std::make_shared<Fullconnect_LayerQL<double>>(Fullconnect_Layer, 16 * 8 * 8, 30); //ȫ���Ӳ� std::shared_ptr<Inter_LayerQL<double>> o_12 = o_11 + fullconnect_01; std::shared_ptr<LayerQL<double>> rule_04 = std::make_shared<Relu_LayerQL<double>>(Relu_Layer); //Relu�� std::shared_ptr<Inter_LayerQL<double>> o_13 = o_12 + rule_04; std::shared_ptr<LayerQL<double>> fullconnect_02 = std::make_shared<Fullconnect_LayerQL<double>>(Fullconnect_Layer, 30, 3); //ȫ���Ӳ� std::shared_ptr<Inter_LayerQL<double>> o_14 = o_13 + fullconnect_02; std::shared_ptr<LayerQL<double>> rule_05 = std::make_shared<Relu_LayerQL<double>>(Relu_Layer); //Relu�� std::shared_ptr<Inter_LayerQL<double>> o_15 = o_14 + rule_05; std::shared_ptr<LayerQL<double>> lossLayer_01 = std::make_shared<SoftMax_LayerQL<double>>(SoftMax_Layer); //Loss�� std::shared_ptr<Inter_LayerQL<double>> o_16 = o_15 + lossLayer_01; rule_01->pRelu_k = 0.12; rule_02->pRelu_k = 0.12; rule_03->pRelu_k = 0.12; rule_04->pRelu_k = 0.12; rule_05->pRelu_k = 0.12; conv_01->upConv = 0.005; conv_02->upConv = 0.005; conv_03->upConv = 0.005; fullconnect_01->upFull = 0.005; fullconnect_02->upFull = 0.005; for (int i = 0; i < 50; i++) { std::cout << i << std::endl; for (int j = 1; j < 24; j++) { in_01->forward_Matrix_Vector.clear(); in_01->forward_Matrix_Vector.push_back(LoadTuLi::tuli_Train[j - 1]); switch (j) { case 1: case 4: case 7: case 10: case 13: case 16: case 19: case 22: o_16->backward_Matrix->setMatrixQL().resize(1, 3); o_16->backward_Matrix->setMatrixQL().setZero(); o_16->backward_Matrix->setMatrixQL()(0, 0) = 1; break; case 2: case 5: case 8: case 11: case 14: case 17: case 20: case 23: o_16->backward_Matrix->setMatrixQL().resize(1, 3); o_16->backward_Matrix->setMatrixQL().setZero(); o_16->backward_Matrix->setMatrixQL()(0, 1) = 1; break; case 3: case 6: case 9: case 12: case 15: case 18: case 21: o_16->backward_Matrix->setMatrixQL().resize(1, 3); o_16->backward_Matrix->setMatrixQL().setZero(); o_16->backward_Matrix->setMatrixQL()(0, 2) = 1; break; default: break; } for (auto k = NetQL<double>::layerQLVector.begin(); k != NetQL<double>::layerQLVector.end(); k++) { (*k)->calForward(); } //��ͷ��ʼ���򴫲� + Ȩ�ظ��� //#pragma omp parallel for (auto k = NetQL<double>::layerQLVector.rbegin(); k != NetQL<double>::layerQLVector.rend(); k++) { (*k)->calBackward(); (*k)->upMatrix(); } if (i > 48) { std::cout << "i::" << o_16->forward_Matrix->getMatrixQL() << std::endl; } } } for (int j = 1; j < 10; j++) { in_01->forward_Matrix_Vector.clear(); in_01->forward_Matrix_Vector.push_back(LoadTuLi::tuli_Test[j - 1]); for (auto k = NetQL<double>::layerQLVector.begin(); k != NetQL<double>::layerQLVector.end(); k++) { (*k)->calForward(); } std::cout << "j::" << o_16->forward_Matrix->getMatrixQL() << std::endl; } } }
GB_unaryop__abs_uint8_int64.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__abs_uint8_int64 // op(A') function: GB_tran__abs_uint8_int64 // C type: uint8_t // A type: int64_t // cast: uint8_t cij = (uint8_t) aij // unaryop: cij = aij #define GB_ATYPE \ int64_t #define GB_CTYPE \ uint8_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int64_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) \ uint8_t z = (uint8_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ABS || GxB_NO_UINT8 || GxB_NO_INT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__abs_uint8_int64 ( uint8_t *restrict Cx, const int64_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__abs_uint8_int64 ( 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
nodal_residualbased_block_builder_and_solver.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Riccardo Rossi // // #if !defined(KRATOS_NODAL_RESIDUAL_BASED_BLOCK_BUILDER_AND_SOLVER ) #define KRATOS_NODAL_RESIDUAL_BASED_BLOCK_BUILDER_AND_SOLVER /* System includes */ #include <set> #ifdef _OPENMP #include <omp.h> #endif /* #include <unordered_set> */ /* #ifdef USE_GOOGLE_HASH */ /* #include "sparsehash/dense_hash_set" //included in external libraries */ /* #endif */ #ifdef USE_GOOGLE_HASH #include "sparsehash/dense_hash_set" //included in external libraries #else #include <unordered_set> #endif /* Project includes */ #include "utilities/timer.h" #include "includes/define.h" #include "includes/key_hash.h" #include "solving_strategies/builder_and_solvers/builder_and_solver.h" #include "includes/model_part.h" #include "utilities/openmp_utils.h" #include "includes/kratos_flags.h" namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /** * @class NodalResidualBasedBlockBuilderAndSolver * @ingroup KratosCore * @brief Current class provides an implementation for standard builder and solving operations. * @details The RHS is constituted by the unbalanced loads (residual) * Degrees of freedom are reordered putting the restrained degrees of freedom at * the end of the system ordered in reverse order with respect to the DofSet. * Imposition of the dirichlet conditions is naturally dealt with as the residual already contains * this information. * Calculation of the reactions involves a cost very similiar to the calculation of the total residual * @author Riccardo Rossi */ template<class TSparseSpace, class TDenseSpace, //= DenseSpace<double>, class TLinearSolver //= LinearSolver<TSparseSpace,TDenseSpace> > class NodalResidualBasedBlockBuilderAndSolver : public BuilderAndSolver< TSparseSpace, TDenseSpace, TLinearSolver > { public: ///@name Type Definitions ///@{ KRATOS_CLASS_POINTER_DEFINITION(NodalResidualBasedBlockBuilderAndSolver); typedef BuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver> BaseType; typedef typename BaseType::TSchemeType TSchemeType; typedef typename BaseType::TDataType TDataType; typedef typename BaseType::DofsArrayType DofsArrayType; typedef typename BaseType::TSystemMatrixType TSystemMatrixType; typedef typename BaseType::TSystemVectorType TSystemVectorType; typedef typename BaseType::LocalSystemVectorType LocalSystemVectorType; typedef typename BaseType::LocalSystemMatrixType LocalSystemMatrixType; typedef typename BaseType::TSystemMatrixPointerType TSystemMatrixPointerType; typedef typename BaseType::TSystemVectorPointerType TSystemVectorPointerType; typedef Node<3> NodeType; typedef typename BaseType::NodesArrayType NodesArrayType; typedef typename BaseType::ElementsArrayType ElementsArrayType; typedef typename BaseType::ConditionsArrayType ConditionsArrayType; typedef typename BaseType::ElementsContainerType ElementsContainerType; typedef Vector VectorType; ///@} ///@name Life Cycle ///@{ /** Constructor. */ NodalResidualBasedBlockBuilderAndSolver( typename TLinearSolver::Pointer pNewLinearSystemSolver) : BuilderAndSolver< TSparseSpace, TDenseSpace, TLinearSolver >(pNewLinearSystemSolver) { } /** Destructor. */ ~NodalResidualBasedBlockBuilderAndSolver() override { } ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ /** * @brief Function to perform the build of the RHS. The vector could be sized as the total number * of dofs or as the number of unrestrained ones * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param A The LHS matrix * @param b The RHS vector */ void Build( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& A, TSystemVectorType& b) override { KRATOS_TRY KRATOS_ERROR_IF(!pScheme) << "No scheme provided!" << std::endl; // Getting the elements from the model const int nelements = static_cast<int>(rModelPart.Elements().size()); // Getting the array of the conditions const int nconditions = static_cast<int>(rModelPart.Conditions().size()); ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo(); ModelPart::ElementsContainerType::iterator el_begin = rModelPart.ElementsBegin(); ModelPart::ConditionsContainerType::iterator cond_begin = rModelPart.ConditionsBegin(); //contributions to the system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0); LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); //vector containing the localization in the system of the different //terms Element::EquationIdVectorType EquationId; // assemble all elements double start_build = OpenMPUtils::GetCurrentTime(); #pragma omp parallel firstprivate(nelements,nconditions, LHS_Contribution, RHS_Contribution, EquationId ) { # pragma omp for schedule(guided, 512) nowait for (int k = 0; k < nelements; k++) { ModelPart::ElementsContainerType::iterator it = el_begin + k; //detect if the element is active or not. If the user did not make any choice the element //is active by default bool element_is_active = true; if ((it)->IsDefined(ACTIVE)) element_is_active = (it)->Is(ACTIVE); if (element_is_active) { //calculate elemental contribution pScheme->CalculateSystemContributions(*(it.base()), LHS_Contribution, RHS_Contribution, EquationId, CurrentProcessInfo); //assemble the elemental contribution #ifdef USE_LOCKS_IN_ASSEMBLY Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId, mlock_array); #else Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId); #endif // clean local elemental memory pScheme->CleanMemory(*(it.base())); } } //#pragma omp parallel for firstprivate(nconditions, LHS_Contribution, RHS_Contribution, EquationId ) schedule(dynamic, 1024) #pragma omp for schedule(guided, 512) for (int k = 0; k < nconditions; k++) { ModelPart::ConditionsContainerType::iterator it = cond_begin + k; //detect if the element is active or not. If the user did not make any choice the element //is active by default bool condition_is_active = true; if ((it)->IsDefined(ACTIVE)) condition_is_active = (it)->Is(ACTIVE); if (condition_is_active) { //calculate elemental contribution pScheme->Condition_CalculateSystemContributions(*(it.base()), LHS_Contribution, RHS_Contribution, EquationId, CurrentProcessInfo); //assemble the elemental contribution #ifdef USE_LOCKS_IN_ASSEMBLY Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId, mlock_array); #else Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId); #endif // clean local elemental memory pScheme->CleanMemory(*(it.base())); } } } const double stop_build = OpenMPUtils::GetCurrentTime(); KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", (this->GetEchoLevel() >= 1 && rModelPart.GetCommunicator().MyPID() == 0)) << "Build time: " << stop_build - start_build << std::endl; //for (int i = 0; i < A_size; i++) // omp_destroy_lock(&lock_array[i]); KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", (this->GetEchoLevel() > 2 && rModelPart.GetCommunicator().MyPID() == 0)) << "Finished parallel building" << std::endl; KRATOS_CATCH("") } void BuildNodally( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& A, TSystemVectorType& b) { KRATOS_TRY KRATOS_ERROR_IF(!pScheme) << "No scheme provided!" << std::endl; std::cout<<"Build Nodally Continuity Equation"<<std::endl; //contributions to the system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0); LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); //vector containing the localization in the system of the different terms Element::EquationIdVectorType EquationId; ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo(); /* const double start_build = OpenMPUtils::GetCurrentTime(); */ /* #pragma omp parallel */ { ModelPart::NodeIterator NodesBegin; ModelPart::NodeIterator NodesEnd; OpenMPUtils::PartitionedIterators(rModelPart.Nodes(),NodesBegin,NodesEnd); for (ModelPart::NodeIterator itNode = NodesBegin; itNode != NodesEnd; ++itNode) { VectorType nodalSFDneighboursId=itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS_ORDER); const unsigned int neighSize = nodalSFDneighboursId.size(); if(neighSize>1){ const unsigned int dimension = rModelPart.ElementsBegin()->GetGeometry().WorkingSpaceDimension(); const double nodalVolume=itNode->FastGetSolutionStepValue(NODAL_VOLUME); const double timeInterval = CurrentProcessInfo[DELTA_TIME]; LHS_Contribution= ZeroMatrix(neighSize,neighSize); RHS_Contribution= ZeroVector(neighSize); if (EquationId.size() != neighSize) EquationId.resize(neighSize, false); double deviatoricCoeff=itNode->FastGetSolutionStepValue(DEVIATORIC_COEFFICIENT); double volumetricCoeff=itNode->FastGetSolutionStepValue(VOLUMETRIC_COEFFICIENT)+2.0*deviatoricCoeff/3.0; const unsigned int xpos = itNode->GetDofPosition(VELOCITY_X); double deltaPressure=itNode->FastGetSolutionStepValue(PRESSURE,0)-itNode->FastGetSolutionStepValue(PRESSURE,1); double volumetricDefRate= itNode->GetSolutionStepValue(NODAL_VOLUMETRIC_DEF_RATE); LHS_Contribution(0,0)+= nodalVolume/volumetricCoeff; RHS_Contribution[0] += (-deltaPressure/volumetricCoeff + volumetricDefRate)*nodalVolume; bool stabilizationNeeded=false; if((itNode->Is(FLUID) || (itNode->Is(SOLID) && itNode->FastGetSolutionStepValue(POISSON_RATIO)>0.49))){ stabilizationNeeded=true; }else{ for (unsigned int i = 0; i< neighSize; i++) { unsigned int idNode=nodalSFDneighboursId[i]; EquationId[i]=rModelPart.Nodes()[idNode].GetDof(PRESSURE,xpos).EquationId(); } } if(stabilizationNeeded==true){ /* Vector& rNodalSFDneigh = itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS); */ unsigned int firstRow=0; unsigned int firstCol=0; double meanMeshSize=itNode->FastGetSolutionStepValue(NODAL_MEAN_MESH_SIZE); double characteristicLength=2.0*meanMeshSize; /* double nodalFreesurfaceArea=itNode->FastGetSolutionStepValue(NODAL_FREESURFACE_AREA); */ double density=itNode->FastGetSolutionStepValue(DENSITY); /* double tauStab=1.0/(8.0*deviatoricCoeff/(meanMeshSize*meanMeshSize)+2.0*density/timeInterval); */ double nodalVelocity=0; if(dimension==2){ nodalVelocity= sqrt(itNode->FastGetSolutionStepValue(VELOCITY_X)*itNode->FastGetSolutionStepValue(VELOCITY_X) + itNode->FastGetSolutionStepValue(VELOCITY_Y)*itNode->FastGetSolutionStepValue(VELOCITY_Y)); }else if(dimension==3){ nodalVelocity=sqrt(itNode->FastGetSolutionStepValue(VELOCITY_X)*itNode->FastGetSolutionStepValue(VELOCITY_X) + itNode->FastGetSolutionStepValue(VELOCITY_Y)*itNode->FastGetSolutionStepValue(VELOCITY_Y) + itNode->FastGetSolutionStepValue(VELOCITY_Z)*itNode->FastGetSolutionStepValue(VELOCITY_Z)); } double tauStab= 1.0 * (characteristicLength * characteristicLength * timeInterval) / ( density * nodalVelocity * timeInterval * characteristicLength + density * characteristicLength * characteristicLength + 8.0 * deviatoricCoeff * timeInterval ); /* tauStab*=10.0; */ /* tauStab=0.0000001; */ /* tauStab=100.0; */ LHS_Contribution(0,0)+= +nodalVolume*tauStab*density/(volumetricCoeff*timeInterval); RHS_Contribution[0] += -nodalVolume*tauStab*density/(volumetricCoeff*timeInterval)*(deltaPressure-itNode->FastGetSolutionStepValue(PRESSURE_VELOCITY,0)*timeInterval); if(itNode->Is(FREE_SURFACE)){ /* LHS_Contribution(0,0) += + 2.0 * tauStab * nodalFreesurfaceArea / meanMeshSize; */ /* RHS_Contribution[0] += - 2.0 * tauStab * nodalFreesurfaceArea / meanMeshSize * itNode->FastGetSolutionStepValue(PRESSURE,0); */ /* double boundLHScontribution=4.0 * tauStab * nodalVolume /(meanMeshSize*meanMeshSize); */ /* std::cout<<"boundLHScontribution "<<boundLHScontribution<<std::endl; */ /* if(itNode->IsNot(RIGID)){ */ LHS_Contribution(0,0) += + 4.0*2.0 * tauStab * nodalVolume /(meanMeshSize*meanMeshSize); RHS_Contribution[0] += - 4.0*2.0 * tauStab * nodalVolume /(meanMeshSize*meanMeshSize) * itNode->FastGetSolutionStepValue(PRESSURE,0); /* } */ /* else { */ /* LHS_Contribution(0,0) += + 4.0/3.0 * tauStab * nodalVolume /(meanMeshSize*meanMeshSize); */ /* RHS_Contribution[0] += - 4.0/3.0 * tauStab * nodalVolume /(meanMeshSize*meanMeshSize) * itNode->FastGetSolutionStepValue(PRESSURE,0); */ /* } */ const array_1d<double, 3> &Normal = itNode->FastGetSolutionStepValue(NORMAL); Vector& SpatialDefRate=itNode->FastGetSolutionStepValue(NODAL_SPATIAL_DEF_RATE); array_1d<double, 3> nodalAcceleration= 0.5*(itNode->FastGetSolutionStepValue(VELOCITY,0)-itNode->FastGetSolutionStepValue(VELOCITY,1))/timeInterval - itNode->FastGetSolutionStepValue(ACCELERATION,1); /* nodalAcceleration= (itNode->FastGetSolutionStepValue(VELOCITY,0)-itNode->FastGetSolutionStepValue(VELOCITY,1))/timeInterval; */ double nodalNormalAcceleration=0; double nodalNormalProjDefRate=0; if(dimension==2){ nodalNormalProjDefRate=Normal[0]*SpatialDefRate[0]*Normal[0] + Normal[1]*SpatialDefRate[1]*Normal[1] + 2*Normal[0]*SpatialDefRate[2]*Normal[1]; /* nodalNormalAcceleration=Normal[0]*itNode->FastGetSolutionStepValue(ACCELERATION_X,1) + Normal[1]*itNode->FastGetSolutionStepValue(ACCELERATION_Y,1); */ /* nodalNormalAcceleration=(itNode->FastGetSolutionStepValue(VELOCITY_X,0)-itNode->FastGetSolutionStepValue(VELOCITY_X,1))*Normal[0]/timeInterval + */ /* (itNode->FastGetSolutionStepValue(VELOCITY_Y,0)-itNode->FastGetSolutionStepValue(VELOCITY_Y,1))*Normal[1]/timeInterval; */ nodalNormalAcceleration=Normal[0]*nodalAcceleration[0] + Normal[1]*nodalAcceleration[1]; }else if(dimension==3){ nodalNormalProjDefRate=Normal[0]*SpatialDefRate[0]*Normal[0] + Normal[1]*SpatialDefRate[1]*Normal[1] + Normal[2]*SpatialDefRate[2]*Normal[2] + 2*Normal[0]*SpatialDefRate[3]*Normal[1] + 2*Normal[0]*SpatialDefRate[4]*Normal[2] + 2*Normal[1]*SpatialDefRate[5]*Normal[2]; /* nodalNormalAcceleration=Normal[0]*itNode->FastGetSolutionStepValue(ACCELERATION_X) + Normal[1]*itNode->FastGetSolutionStepValue(ACCELERATION_Y) + Normal[2]*itNode->FastGetSolutionStepValue(ACCELERATION_Z); */ /* nodalNormalAcceleration=Normal[0]*nodalAcceleration[0] + Normal[1]*nodalAcceleration[1] + Normal[2]*nodalAcceleration[2]; */ } /* RHS_Contribution[0] += tauStab * (density*nodalNormalAcceleration - 4.0*deviatoricCoeff*nodalNormalProjDefRate/meanMeshSize) * nodalFreesurfaceArea; */ double accelerationContribution=2.0*density*nodalNormalAcceleration/meanMeshSize; double deviatoricContribution=8.0*deviatoricCoeff*nodalNormalProjDefRate/(meanMeshSize*meanMeshSize); /* std::cout<<"nodalNormalAcceleration= "<<nodalNormalAcceleration<<std::endl; */ /* std::cout<<"nodalNormalProjDefRate= "<<nodalNormalProjDefRate<<std::endl; */ /* std::cout<<"meanMeshSize "<<meanMeshSize<<std::endl; */ /* accelerationContribution=0; */ /* deviatoricContribution=0; */ /* if(itNode->IsNot(RIGID)){ */ RHS_Contribution[0] += 2.0* tauStab * (accelerationContribution + deviatoricContribution) * nodalVolume; /* }else{ */ /* RHS_Contribution[0] += 1.0/3.0* tauStab * (accelerationContribution - deviatoricContribution) * nodalVolume; */ /* } */ } for (unsigned int i = 0; i< neighSize; i++) { unsigned int idNode=nodalSFDneighboursId[i]; EquationId[i]=rModelPart.Nodes()[idNode].GetDof(PRESSURE,xpos).EquationId(); double Density= rModelPart.Nodes()[idNode].FastGetSolutionStepValue(DENSITY); array_1d<double, 3 >& VolumeAcceleration = rModelPart.Nodes()[idNode].FastGetSolutionStepValue(VOLUME_ACCELERATION); double dNdXi=itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstCol]; double dNdYi=itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstCol+1]; double dNdZi=0; if(dimension==2){ RHS_Contribution[i] += - tauStab * Density * (dNdXi* VolumeAcceleration[0] + dNdYi* VolumeAcceleration[1]) * nodalVolume; } else if(dimension==3){ dNdZi=itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstCol+2]; RHS_Contribution[i] += - tauStab * Density * (dNdXi* VolumeAcceleration[0] + dNdYi* VolumeAcceleration[1] + dNdZi* VolumeAcceleration[2]) * nodalVolume; } firstRow=0; for (unsigned int j = 0; j< neighSize; j++) { unsigned int idNodeJ=nodalSFDneighboursId[j]; double dNdXj=itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstRow]; double dNdYj=itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstRow+1]; if(dimension==2){ ////////////////// Laplacian term for LHS LHS_Contribution(i,j)+= + tauStab * (dNdXi*dNdXj + dNdYi*dNdYj) * nodalVolume; ////////////////// Laplacian term L_ij*P_j for RHS RHS_Contribution[i] += - tauStab * (dNdXi*dNdXj + dNdYi*dNdYj) * nodalVolume * rModelPart.Nodes()[idNodeJ].FastGetSolutionStepValue(PRESSURE,0); } else if(dimension==3){ double dNdZj=itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS)[firstRow+2]; ////////////////// Laplacian term for LHS LHS_Contribution(i,j) += + tauStab * (dNdXi*dNdXj + dNdYi*dNdYj + dNdZi*dNdZj) * nodalVolume; ////////////////// Laplacian term L_ij*P_j for RHS RHS_Contribution[i] += - tauStab * (dNdXi*dNdXj + dNdYi*dNdYj + dNdZi*dNdZj) * nodalVolume * rModelPart.Nodes()[idNodeJ].FastGetSolutionStepValue(PRESSURE,0); } /* std::cout << "dNdXi= " <<dNdXi<< "dNdYi= " <<dNdYi<< "dNdYj= " <<dNdYj<< "dNdXj= " <<dNdXj<< std::endl; */ firstRow+=dimension; } firstCol+=dimension; } } //assemble the elemental contribution #ifdef USE_LOCKS_IN_ASSEMBLY Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId, mlock_array); #else Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId); #endif /* AssembleLHS(A, LHS_Contribution, EquationId); */ /* AssembleRHS(b, RHS_Contribution, EquationId); */ } } } /* /\* std::cout<<".... Build Nodally Continuity Equation DONE!"<<std::endl; *\/ */ /* const double stop_build = OpenMPUtils::GetCurrentTime(); */ /* KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", (this->GetEchoLevel() >= 1 && rModelPart.GetCommunicator().MyPID() == 0)) << "Build time: " << stop_build - start_build << std::endl; */ /* //for (int i = 0; i < A_size; i++) */ /* // omp_destroy_lock(&lock_array[i]); */ /* KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", (this->GetEchoLevel() > 2 && rModelPart.GetCommunicator().MyPID() == 0)) << "Finished parallel building" << std::endl; */ KRATOS_CATCH("") } /** * @brief Function to perform the building of the LHS * @details Depending on the implementation choosen the size of the matrix could * be equal to the total number of Dofs or to the number of unrestrained dofs * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param A The LHS matrix */ void BuildLHS( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& A) override { KRATOS_TRY TSystemVectorType tmp(A.size1(), 0.0); this->Build(pScheme, rModelPart, A, tmp); KRATOS_CATCH("") } /** * @brief Build a rectangular matrix of size n*N where "n" is the number of unrestrained degrees of freedom * and "N" is the total number of degrees of freedom involved. * @details This matrix is obtained by building the total matrix without the lines corresponding to the fixed * degrees of freedom (but keeping the columns!!) * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param A The LHS matrix */ void BuildLHS_CompleteOnFreeRows( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& A) override { KRATOS_TRY TSystemVectorType tmp(A.size1(), 0.0); this->Build(pScheme, rModelPart, A, tmp); KRATOS_CATCH("") } /** * @brief This is a call to the linear system solver * @param A The LHS matrix * @param Dx The Unknowns vector * @param b The RHS vector */ void SystemSolve( TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b ) override { KRATOS_TRY double norm_b; if (TSparseSpace::Size(b) != 0) norm_b = TSparseSpace::TwoNorm(b); else norm_b = 0.00; if (norm_b != 0.00) { //do solve BaseType::mpLinearSystemSolver->Solve(A, Dx, b); } else TSparseSpace::SetToZero(Dx); //prints informations about the current time KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", this->GetEchoLevel() > 1) << *(BaseType::mpLinearSystemSolver) << std::endl; KRATOS_CATCH("") } /** *@brief This is a call to the linear system solver (taking into account some physical particularities of the problem) * @param A The LHS matrix * @param Dx The Unknowns vector * @param b The RHS vector * @param rModelPart The model part of the problem to solve */ void SystemSolveWithPhysics( TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b, ModelPart& rModelPart ) { KRATOS_TRY double norm_b; if (TSparseSpace::Size(b) != 0) norm_b = TSparseSpace::TwoNorm(b); else norm_b = 0.00; if (norm_b != 0.00) { //provide physical data as needed if(BaseType::mpLinearSystemSolver->AdditionalPhysicalDataIsNeeded() ) BaseType::mpLinearSystemSolver->ProvideAdditionalData(A, Dx, b, BaseType::mDofSet, rModelPart); //do solve BaseType::mpLinearSystemSolver->Solve(A, Dx, b); } else { TSparseSpace::SetToZero(Dx); KRATOS_WARNING("NodalResidualBasedBlockBuilderAndSolver") << "ATTENTION! setting the RHS to zero!" << std::endl; } //prints informations about the current time KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", this->GetEchoLevel() > 1) << *(BaseType::mpLinearSystemSolver) << std::endl; KRATOS_CATCH("") } /** * @brief Function to perform the building and solving phase at the same time. * @details It is ideally the fastest and safer function to use when it is possible to solve * just after building * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param A The LHS matrix * @param Dx The Unknowns vector * @param b The RHS vector */ void BuildAndSolve( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b) override { KRATOS_TRY std::cout << "CONTINUITY EQ: buildAndSolve " << std::endl; Timer::Start("Build"); /* Build(pScheme, rModelPart, A, b); */ boost::timer build_time; BuildNodally(pScheme, rModelPart, A, b); std::cout << "CONTINUITY EQ: build_time : " << build_time.elapsed() << std::endl; Timer::Stop("Build"); ApplyDirichletConditions(pScheme, rModelPart, A, Dx, b); KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() == 3)) << "Before the solution of the system" << "\nSystem Matrix = " << A << "\nUnknowns vector = " << Dx << "\nRHS vector = " << b << std::endl; const double start_solve = OpenMPUtils::GetCurrentTime(); Timer::Start("Solve"); boost::timer solve_time; SystemSolveWithPhysics(A, Dx, b, rModelPart); std::cout << "CONTINUITY EQ: solve_time : " << solve_time.elapsed() << std::endl; Timer::Stop("Solve"); const double stop_solve = OpenMPUtils::GetCurrentTime(); KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", (this->GetEchoLevel() >=1 && rModelPart.GetCommunicator().MyPID() == 0)) << "System solve time: " << stop_solve - start_solve << std::endl; KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() == 3)) << "After the solution of the system" << "\nSystem Matrix = " << A << "\nUnknowns vector = " << Dx << "\nRHS vector = " << b << std::endl; KRATOS_CATCH("") } /** * @brief Corresponds to the previews, but the System's matrix is considered already built and only the RHS is built again * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param A The LHS matrix * @param Dx The Unknowns vector * @param b The RHS vector */ void BuildRHSAndSolve( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b) override { KRATOS_TRY BuildRHS(pScheme, rModelPart, b); SystemSolve(A, Dx, b); KRATOS_CATCH("") } /** * @brief Function to perform the build of the RHS. * @details The vector could be sized as the total number of dofs or as the number of unrestrained ones * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve */ void BuildRHS( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemVectorType& b) override { KRATOS_TRY BuildRHSNoDirichlet(pScheme,rModelPart,b); const int ndofs = static_cast<int>(BaseType::mDofSet.size()); //NOTE: dofs are assumed to be numbered consecutively in the BlockBuilderAndSolver #pragma omp parallel for firstprivate(ndofs) for (int k = 0; k<ndofs; k++) { typename DofsArrayType::iterator dof_iterator = BaseType::mDofSet.begin() + k; const std::size_t i = dof_iterator->EquationId(); if (dof_iterator->IsFixed()) b[i] = 0.0f; } KRATOS_CATCH("") } /** * @brief Builds the list of the DofSets involved in the problem by "asking" to each element * and condition its Dofs. * @details The list of dofs is stores insde the BuilderAndSolver as it is closely connected to the * way the matrix and RHS are built * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve */ void SetUpDofSet( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart ) override { KRATOS_TRY; KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() > 1 && rModelPart.GetCommunicator().MyPID() == 0)) << "Setting up the dofs" << std::endl; //Gets the array of elements from the modeler ElementsArrayType& pElements = rModelPart.Elements(); const int nelements = static_cast<int>(pElements.size()); Element::DofsVectorType ElementalDofList; ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo(); unsigned int nthreads = OpenMPUtils::GetNumThreads(); // typedef boost::fast_pool_allocator< NodeType::DofType::Pointer > allocator_type; // typedef std::unordered_set < NodeType::DofType::Pointer, // DofPointerHasher, // DofPointerComparor, // allocator_type > set_type; #ifdef USE_GOOGLE_HASH typedef google::dense_hash_set < NodeType::DofType::Pointer, DofPointerHasher> set_type; #else typedef std::unordered_set < NodeType::DofType::Pointer, DofPointerHasher> set_type; #endif // std::vector<set_type> dofs_aux_list(nthreads); // std::vector<allocator_type> allocators(nthreads); KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() > 2)) << "Number of threads" << nthreads << "\n" << std::endl; for (int i = 0; i < static_cast<int>(nthreads); i++) { #ifdef USE_GOOGLE_HASH dofs_aux_list[i].set_empty_key(NodeType::DofType::Pointer()); #else // dofs_aux_list[i] = set_type( allocators[i]); dofs_aux_list[i].reserve(nelements); #endif } KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() > 2)) << "Initializing element loop" << std::endl; #pragma omp parallel firstprivate(nelements, ElementalDofList) { #pragma omp for schedule(guided, 512) nowait for (int i = 0; i < nelements; i++) { typename ElementsArrayType::iterator it = pElements.begin() + i; const unsigned int this_thread_id = OpenMPUtils::ThisThread(); // gets list of Dof involved on every element pScheme->GetElementalDofList(*(it.base()), ElementalDofList, CurrentProcessInfo); dofs_aux_list[this_thread_id].insert(ElementalDofList.begin(), ElementalDofList.end()); } KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() > 2)) << "Initializing condition loop" << std::endl; ConditionsArrayType& pConditions = rModelPart.Conditions(); const int nconditions = static_cast<int>(pConditions.size()); #pragma omp for schedule(guided, 512) for (int i = 0; i < nconditions; i++) { typename ConditionsArrayType::iterator it = pConditions.begin() + i; const unsigned int this_thread_id = OpenMPUtils::ThisThread(); // gets list of Dof involved on every element pScheme->GetConditionDofList(*(it.base()), ElementalDofList, CurrentProcessInfo); dofs_aux_list[this_thread_id].insert(ElementalDofList.begin(), ElementalDofList.end()); } } KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() > 2)) << "Initializing tree reduction\n" << std::endl; // Here we do a reduction in a tree so to have everything on thread 0 unsigned int old_max = nthreads; unsigned int new_max = ceil(0.5*static_cast<double>(old_max)); while (new_max>=1 && new_max != old_max) { if( this->GetEchoLevel() > 2) { //just for debugging std::cout << "old_max" << old_max << " new_max:" << new_max << std::endl; for (int i = 0; i < static_cast<int>(new_max); i++) { if (i + new_max < old_max) { std::cout << i << " - " << i+new_max << std::endl; } } std::cout << "********************" << std::endl; } #pragma omp parallel for for (int i = 0; i < static_cast<int>(new_max); i++) { if (i + new_max < old_max) { dofs_aux_list[i].insert(dofs_aux_list[i+new_max].begin(), dofs_aux_list[i+new_max].end()); dofs_aux_list[i+new_max].clear(); } } old_max = new_max; new_max = ceil(0.5*static_cast<double>(old_max)); } KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() > 2)) << "Initializing ordered array filling\n" << std::endl; DofsArrayType Doftemp; BaseType::mDofSet = DofsArrayType(); Doftemp.reserve(dofs_aux_list[0].size()); for (auto it= dofs_aux_list[0].begin(); it!= dofs_aux_list[0].end(); it++) { Doftemp.push_back( it->get() ); } Doftemp.Sort(); BaseType::mDofSet = Doftemp; //Throws an exception if there are no Degrees Of Freedom involved in the analysis KRATOS_ERROR_IF(BaseType::mDofSet.size() == 0) << "No degrees of freedom!" << std::endl; KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() > 2)) << "Number of degrees of freedom:" << BaseType::mDofSet.size() << std::endl; BaseType::mDofSetIsInitialized = true; KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() > 2 && rModelPart.GetCommunicator().MyPID() == 0)) << "Finished setting up the dofs" << std::endl; KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() > 2)) << "Initializing lock array" << std::endl; #ifdef _OPENMP if (mlock_array.size() != 0) { for (int i = 0; i < static_cast<int>(mlock_array.size()); i++) { omp_destroy_lock(&mlock_array[i]); } } mlock_array.resize(BaseType::mDofSet.size()); for (int i = 0; i < static_cast<int>(mlock_array.size()); i++) { omp_init_lock(&mlock_array[i]); } #endif KRATOS_INFO_IF("NodalResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() > 2)) << "End of setup dof set\n" << std::endl; // If reactions are to be calculated, we check if all the dofs have reactions defined // This is tobe done only in debug mode #ifdef KRATOS_DEBUG if(BaseType::GetCalculateReactionsFlag()) { for(auto dof_iterator = BaseType::mDofSet.begin(); dof_iterator != BaseType::mDofSet.end(); ++dof_iterator) { KRATOS_ERROR_IF_NOT(dof_iterator->HasReaction()) << "Reaction variable not set for the following : " <<std::endl << "Node : "<<dof_iterator->Id()<< std::endl << "Dof : "<<(*dof_iterator)<<std::endl<<"Not possible to calculate reactions."<<std::endl; } } #endif KRATOS_CATCH(""); } /** * @brief Organises the dofset in order to speed up the building phase * @param rModelPart The model part of the problem to solve */ void SetUpSystem( ModelPart& rModelPart ) override { //int free_id = 0; BaseType::mEquationSystemSize = BaseType::mDofSet.size(); int ndofs = static_cast<int>(BaseType::mDofSet.size()); #pragma omp parallel for firstprivate(ndofs) for (int i = 0; i < static_cast<int>(ndofs); i++) { typename DofsArrayType::iterator dof_iterator = BaseType::mDofSet.begin() + i; dof_iterator->SetEquationId(i); } //for (typename DofsArrayType::iterator dof_iterator = BaseType::mDofSet.begin(); dof_iterator != BaseType::mDofSet.end(); ++dof_iterator) // dof_iterator->SetEquationId(free_id++); } //************************************************************************** //************************************************************************** void ResizeAndInitializeVectors( typename TSchemeType::Pointer pScheme, TSystemMatrixPointerType& pA, TSystemVectorPointerType& pDx, TSystemVectorPointerType& pb, ModelPart& rModelPart ) override { KRATOS_TRY boost::timer contruct_matrix; if (pA == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemMatrixPointerType pNewA = TSystemMatrixPointerType(new TSystemMatrixType(0, 0)); pA.swap(pNewA); } if (pDx == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemVectorPointerType pNewDx = TSystemVectorPointerType(new TSystemVectorType(0)); pDx.swap(pNewDx); } if (pb == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemVectorPointerType pNewb = TSystemVectorPointerType(new TSystemVectorType(0)); pb.swap(pNewb); } TSystemMatrixType& A = *pA; TSystemVectorType& Dx = *pDx; TSystemVectorType& b = *pb; //resizing the system vectors and matrix if (A.size1() == 0 || BaseType::GetReshapeMatrixFlag() == true) //if the matrix is not initialized { A.resize(BaseType::mEquationSystemSize, BaseType::mEquationSystemSize, false); ConstructMatrixStructure(pScheme, A, rModelPart); } else { if (A.size1() != BaseType::mEquationSystemSize || A.size2() != BaseType::mEquationSystemSize) { KRATOS_WATCH(" it should not come here!!!!!!!! ... this is SLOW"); KRATOS_ERROR <<"The equation system size has changed during the simulation. This is not permited."<<std::endl; A.resize(BaseType::mEquationSystemSize, BaseType::mEquationSystemSize, true); ConstructMatrixStructure(pScheme, A, rModelPart); } } if (Dx.size() != BaseType::mEquationSystemSize) Dx.resize(BaseType::mEquationSystemSize, false); if (b.size() != BaseType::mEquationSystemSize) b.resize(BaseType::mEquationSystemSize, false); std::cout << "CONTINUITY EQ: contruct_matrix : " << contruct_matrix.elapsed() << std::endl; KRATOS_CATCH("") } //************************************************************************** //************************************************************************** void InitializeSolutionStep( ModelPart& rModelPart, TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b) override { KRATOS_TRY std::cout << "Initialize Solution Step in nodal res based " << std::endl; KRATOS_CATCH("") } //************************************************************************** //************************************************************************** void FinalizeSolutionStep( ModelPart& rModelPart, TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b) override { } //************************************************************************** //************************************************************************** void CalculateReactions( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b) override { TSparseSpace::SetToZero(b); //refresh RHS to have the correct reactions BuildRHSNoDirichlet(pScheme, rModelPart, b); const int ndofs = static_cast<int>(BaseType::mDofSet.size()); //NOTE: dofs are assumed to be numbered consecutively in the BlockBuilderAndSolver #pragma omp parallel for firstprivate(ndofs) for (int k = 0; k<ndofs; k++) { typename DofsArrayType::iterator dof_iterator = BaseType::mDofSet.begin() + k; const int i = (dof_iterator)->EquationId(); (dof_iterator)->GetSolutionStepReactionValue() = -b[i]; } //KRATOS_WATCH(__LINE__) } /** * @brief Applies the dirichlet conditions. This operation may be very heavy or completely * unexpensive depending on the implementation choosen and on how the System Matrix is built. * @details For explanation of how it works for a particular implementation the user * should refer to the particular Builder And Solver choosen * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param A The LHS matrix * @param Dx The Unknowns vector * @param b The RHS vector */ void ApplyDirichletConditions( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b) override { std::size_t system_size = A.size1(); std::vector<double> scaling_factors (system_size, 0.0f); const int ndofs = static_cast<int>(BaseType::mDofSet.size()); //NOTE: dofs are assumed to be numbered consecutively in the BlockBuilderAndSolver #pragma omp parallel for firstprivate(ndofs) for(int k = 0; k<ndofs; k++) { typename DofsArrayType::iterator dof_iterator = BaseType::mDofSet.begin() + k; if(dof_iterator->IsFixed()) scaling_factors[k] = 0.0f; else scaling_factors[k] = 1.0f; } double* Avalues = A.value_data().begin(); std::size_t* Arow_indices = A.index1_data().begin(); std::size_t* Acol_indices = A.index2_data().begin(); //detect if there is a line of all zeros and set the diagonal to a 1 if this happens #pragma omp parallel for firstprivate(system_size) for(int k = 0; k < static_cast<int>(system_size); ++k) { std::size_t col_begin = Arow_indices[k]; std::size_t col_end = Arow_indices[k+1]; bool empty = true; for (std::size_t j = col_begin; j < col_end; ++j) { if(Avalues[j] != 0.0) { empty = false; break; } } if(empty == true) { A(k,k) = 1.0; b[k] = 0.0; } } #pragma omp parallel for for (int k = 0; k < static_cast<int>(system_size); ++k) { std::size_t col_begin = Arow_indices[k]; std::size_t col_end = Arow_indices[k+1]; double k_factor = scaling_factors[k]; if (k_factor == 0) { // zero out the whole row, except the diagonal for (std::size_t j = col_begin; j < col_end; ++j) if (static_cast<int>(Acol_indices[j]) != k ) Avalues[j] = 0.0; // zero out the RHS b[k] = 0.0; } else { // zero out the column which is associated with the zero'ed row for (std::size_t j = col_begin; j < col_end; ++j) if(scaling_factors[ Acol_indices[j] ] == 0 ) Avalues[j] = 0.0; } } } /** * @brief This function is intended to be called at the end of the solution step to clean up memory storage not needed */ void Clear() override { #ifdef _OPENMP for (int i = 0; i < static_cast<int>(mlock_array.size()); i++) omp_destroy_lock(&mlock_array[i]); mlock_array.resize(0); #endif BaseType::Clear(); } /** * @brief This function is designed to be called once to perform all the checks needed * on the input provided. Checks can be "expensive" as the function is designed * to catch user's errors. * @param rModelPart The model part of the problem to solve * @return 0 all ok */ int Check(ModelPart& rModelPart) override { KRATOS_TRY return 0; KRATOS_CATCH(""); } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ #ifdef _OPENMP std::vector< omp_lock_t > mlock_array; #endif ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ virtual void ConstructMatrixStructure( typename TSchemeType::Pointer pScheme, TSystemMatrixType& A, ModelPart& rModelPart) { std::cout<<" ConstructMatrixStructure for Continuity equation "<<std::endl; //filling with zero the matrix (creating the structure) Timer::Start("MatrixStructure"); ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo(); // Getting the array of the conditions const int nconditions = static_cast<int>(rModelPart.Conditions().size()); ModelPart::ConditionsContainerType::iterator cond_begin = rModelPart.ConditionsBegin(); const std::size_t equation_size = BaseType::mEquationSystemSize; #ifdef USE_GOOGLE_HASH std::vector<google::dense_hash_set<std::size_t> > indices(equation_size); const std::size_t empty_key = 2*equation_size + 10; #else std::vector<std::unordered_set<std::size_t> > indices(equation_size); #endif #pragma omp parallel for firstprivate(equation_size) for (int iii = 0; iii < static_cast<int>(equation_size); iii++) { #ifdef USE_GOOGLE_HASH indices[iii].set_empty_key(empty_key); #else indices[iii].reserve(40); #endif } Element::EquationIdVectorType EquationId; /* #pragma omp parallel */ /* { */ ModelPart::NodeIterator NodesBegin; ModelPart::NodeIterator NodesEnd; OpenMPUtils::PartitionedIterators(rModelPart.Nodes(),NodesBegin,NodesEnd); for (ModelPart::NodeIterator itNode = NodesBegin; itNode != NodesEnd; ++itNode) { /* VectorType nodalSFDneighboursId=itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS_ORDER); */ /* const unsigned int neighSize = nodalSFDneighboursId.size(); */ const unsigned int neighSize =itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS_ORDER).size(); if (EquationId.size() != neighSize) EquationId.resize(neighSize, false); /* const unsigned int xpos = itNode->GetDofPosition(VELOCITY_X); */ const unsigned int xpos = itNode->GetDofPosition(PRESSURE); for (unsigned int i = 0; i< neighSize; i++) { /* unsigned int idNode=nodalSFDneighboursId[i]; */ unsigned int idNode=itNode->FastGetSolutionStepValue(NODAL_SFD_NEIGHBOURS_ORDER)[i]; EquationId[i]=rModelPart.Nodes()[idNode].GetDof(PRESSURE,xpos).EquationId(); } for (std::size_t i = 0; i < EquationId.size(); i++) { if (EquationId[i] < BaseType::mEquationSystemSize) { #ifdef _OPENMP omp_set_lock(&mlock_array[EquationId[i]]); #endif auto& row_indices = indices[EquationId[i]]; for (auto it = EquationId.begin(); it != EquationId.end(); it++) { if (*it < BaseType::mEquationSystemSize) row_indices.insert(*it); } #ifdef _OPENMP omp_unset_lock(&mlock_array[EquationId[i]]); #endif } } /* for (std::size_t i = 0; i < EquationId.size(); i++) */ /* { */ /* #ifdef _OPENMP */ /* omp_set_lock(&mlock_array[EquationId[i]]); */ /* #endif */ /* auto& row_indices = indices[EquationId[i]]; */ /* row_indices.insert(EquationId.begin(), EquationId.end()); */ /* #ifdef _OPENMP */ /* omp_unset_lock(&mlock_array[EquationId[i]]); */ /* #endif */ /* } */ } /* } */ Element::EquationIdVectorType ids(3, 0); #pragma omp parallel for firstprivate(nconditions, ids) for (int iii = 0; iii<nconditions; iii++) { typename ConditionsArrayType::iterator i_condition = cond_begin + iii; pScheme->Condition_EquationId( *(i_condition.base()), ids, CurrentProcessInfo); for (std::size_t i = 0; i < ids.size(); i++) { #ifdef _OPENMP omp_set_lock(&mlock_array[ids[i]]); #endif auto& row_indices = indices[ids[i]]; row_indices.insert(ids.begin(), ids.end()); #ifdef _OPENMP omp_unset_lock(&mlock_array[ids[i]]); #endif } } //count the row sizes unsigned int nnz = 0; for (unsigned int i = 0; i < indices.size(); i++) nnz += indices[i].size(); A = boost::numeric::ublas::compressed_matrix<double>(indices.size(), indices.size(), nnz); double* Avalues = A.value_data().begin(); std::size_t* Arow_indices = A.index1_data().begin(); std::size_t* Acol_indices = A.index2_data().begin(); //filling the index1 vector - DO NOT MAKE PARALLEL THE FOLLOWING LOOP! Arow_indices[0] = 0; for (int i = 0; i < static_cast<int>(A.size1()); i++) Arow_indices[i+1] = Arow_indices[i] + indices[i].size(); #pragma omp parallel for for (int i = 0; i < static_cast<int>(A.size1()); i++) { const unsigned int row_begin = Arow_indices[i]; const unsigned int row_end = Arow_indices[i+1]; unsigned int k = row_begin; for (auto it = indices[i].begin(); it != indices[i].end(); it++) { Acol_indices[k] = *it; Avalues[k] = 0.0; k++; } indices[i].clear(); //deallocating the memory std::sort(&Acol_indices[row_begin], &Acol_indices[row_end]); } A.set_filled(indices.size()+1, nnz); Timer::Stop("MatrixStructure"); /* std::cout<<"..... ConstructMatrixStructure for Continuity equation DONE"<<std::endl; */ } /* virtual void ConstructMatrixStructure( */ /* typename TSchemeType::Pointer pScheme, */ /* TSystemMatrixType& A, */ /* ModelPart& rModelPart) */ /* { */ /* //filling with zero the matrix (creating the structure) */ /* Timer::Start("MatrixStructure"); */ /* // Getting the elements from the model */ /* const int nelements = static_cast<int>(rModelPart.Elements().size()); */ /* // Getting the array of the conditions */ /* const int nconditions = static_cast<int>(rModelPart.Conditions().size()); */ /* ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo(); */ /* ModelPart::ElementsContainerType::iterator el_begin = rModelPart.ElementsBegin(); */ /* ModelPart::ConditionsContainerType::iterator cond_begin = rModelPart.ConditionsBegin(); */ /* const std::size_t equation_size = BaseType::mEquationSystemSize; */ /* #ifdef USE_GOOGLE_HASH */ /* std::vector<google::dense_hash_set<std::size_t> > indices(equation_size); */ /* const std::size_t empty_key = 2*equation_size + 10; */ /* #else */ /* std::vector<std::unordered_set<std::size_t> > indices(equation_size); */ /* #endif */ /* #pragma omp parallel for firstprivate(equation_size) */ /* for (int iii = 0; iii < static_cast<int>(equation_size); iii++) */ /* { */ /* #ifdef USE_GOOGLE_HASH */ /* indices[iii].set_empty_key(empty_key); */ /* #else */ /* indices[iii].reserve(40); */ /* #endif */ /* } */ /* Element::EquationIdVectorType ids(3, 0); */ /* #pragma omp parallel for firstprivate(nelements, ids) */ /* for(int iii=0; iii<nelements; iii++) */ /* { */ /* typename ElementsContainerType::iterator i_element = el_begin + iii; */ /* pScheme->EquationId( *(i_element.base()) , ids, CurrentProcessInfo); */ /* for (std::size_t i = 0; i < ids.size(); i++) */ /* { */ /* #ifdef _OPENMP */ /* omp_set_lock(&mlock_array[ids[i]]); */ /* #endif */ /* auto& row_indices = indices[ids[i]]; */ /* row_indices.insert(ids.begin(), ids.end()); */ /* #ifdef _OPENMP */ /* omp_unset_lock(&mlock_array[ids[i]]); */ /* #endif */ /* } */ /* } */ /* #pragma omp parallel for firstprivate(nconditions, ids) */ /* for (int iii = 0; iii<nconditions; iii++) */ /* { */ /* typename ConditionsArrayType::iterator i_condition = cond_begin + iii; */ /* pScheme->Condition_EquationId( *(i_condition.base()), ids, CurrentProcessInfo); */ /* for (std::size_t i = 0; i < ids.size(); i++) */ /* { */ /* #ifdef _OPENMP */ /* omp_set_lock(&mlock_array[ids[i]]); */ /* #endif */ /* auto& row_indices = indices[ids[i]]; */ /* row_indices.insert(ids.begin(), ids.end()); */ /* #ifdef _OPENMP */ /* omp_unset_lock(&mlock_array[ids[i]]); */ /* #endif */ /* } */ /* } */ /* //count the row sizes */ /* unsigned int nnz = 0; */ /* for (unsigned int i = 0; i < indices.size(); i++) */ /* nnz += indices[i].size(); */ /* A = boost::numeric::ublas::compressed_matrix<double>(indices.size(), indices.size(), nnz); */ /* double* Avalues = A.value_data().begin(); */ /* std::size_t* Arow_indices = A.index1_data().begin(); */ /* std::size_t* Acol_indices = A.index2_data().begin(); */ /* //filling the index1 vector - DO NOT MAKE PARALLEL THE FOLLOWING LOOP! */ /* Arow_indices[0] = 0; */ /* for (int i = 0; i < static_cast<int>(A.size1()); i++) */ /* Arow_indices[i+1] = Arow_indices[i] + indices[i].size(); */ /* #pragma omp parallel for */ /* for (int i = 0; i < static_cast<int>(A.size1()); i++) */ /* { */ /* const unsigned int row_begin = Arow_indices[i]; */ /* const unsigned int row_end = Arow_indices[i+1]; */ /* unsigned int k = row_begin; */ /* for (auto it = indices[i].begin(); it != indices[i].end(); it++) */ /* { */ /* Acol_indices[k] = *it; */ /* Avalues[k] = 0.0; */ /* k++; */ /* } */ /* indices[i].clear(); //deallocating the memory */ /* std::sort(&Acol_indices[row_begin], &Acol_indices[row_end]); */ /* } */ /* A.set_filled(indices.size()+1, nnz); */ /* Timer::Stop("MatrixStructure"); */ /* } */ //************************************************************************** void AssembleLHS( TSystemMatrixType& A, LocalSystemMatrixType& LHS_Contribution, Element::EquationIdVectorType& EquationId ) { unsigned int local_size = LHS_Contribution.size1(); for (unsigned int i_local = 0; i_local < local_size; i_local++) { unsigned int i_global = EquationId[i_local]; for (unsigned int j_local = 0; j_local < local_size; j_local++) { unsigned int j_global = EquationId[j_local]; A(i_global, j_global) += LHS_Contribution(i_local, j_local); } } } void Assemble( TSystemMatrixType& A, TSystemVectorType& b, const LocalSystemMatrixType& LHS_Contribution, const LocalSystemVectorType& RHS_Contribution, Element::EquationIdVectorType& EquationId #ifdef USE_LOCKS_IN_ASSEMBLY ,std::vector< omp_lock_t >& lock_array #endif ) { unsigned int local_size = LHS_Contribution.size1(); for (unsigned int i_local = 0; i_local < local_size; i_local++) { unsigned int i_global = EquationId[i_local]; #ifdef USE_LOCKS_IN_ASSEMBLY omp_set_lock(&lock_array[i_global]); b[i_global] += RHS_Contribution(i_local); #else double& r_a = b[i_global]; const double& v_a = RHS_Contribution(i_local); #pragma omp atomic r_a += v_a; #endif AssembleRowContribution(A, LHS_Contribution, i_global, i_local, EquationId); #ifdef USE_LOCKS_IN_ASSEMBLY omp_unset_lock(&lock_array[i_global]); #endif //note that computation of reactions is not performed here! } } //************************************************************************** void AssembleRHS( TSystemVectorType& b, LocalSystemVectorType& RHS_Contribution, Element::EquationIdVectorType& EquationId ) { unsigned int local_size = RHS_Contribution.size(); for (unsigned int i_local = 0; i_local < local_size; i_local++) { unsigned int i_global = EquationId[i_local]; // ASSEMBLING THE SYSTEM VECTOR double& b_value = b[i_global]; const double& rhs_value = RHS_Contribution[i_local]; #pragma omp atomic b_value += rhs_value; } } ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ inline void AddUnique(std::vector<std::size_t>& v, const std::size_t& candidate) { std::vector<std::size_t>::iterator i = v.begin(); std::vector<std::size_t>::iterator endit = v.end(); while (i != endit && (*i) != candidate) { i++; } if (i == endit) { v.push_back(candidate); } } void BuildRHSNoDirichlet( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemVectorType& b) { KRATOS_TRY //Getting the Elements ElementsArrayType& pElements = rModelPart.Elements(); //getting the array of the conditions ConditionsArrayType& ConditionsArray = rModelPart.Conditions(); ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo(); //contributions to the system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0); LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); //vector containing the localization in the system of the different //terms Element::EquationIdVectorType EquationId; // assemble all elements //for (typename ElementsArrayType::ptr_iterator it = pElements.ptr_begin(); it != pElements.ptr_end(); ++it) const int nelements = static_cast<int>(pElements.size()); #pragma omp parallel firstprivate(nelements, RHS_Contribution, EquationId) { #pragma omp for schedule(guided, 512) nowait for(int i=0; i<nelements; i++) { typename ElementsArrayType::iterator it = pElements.begin() + i; //detect if the element is active or not. If the user did not make any choice the element //is active by default bool element_is_active = true; if( (it)->IsDefined(ACTIVE) ) element_is_active = (it)->Is(ACTIVE); if(element_is_active) { //calculate elemental Right Hand Side Contribution pScheme->Calculate_RHS_Contribution(*(it.base()), RHS_Contribution, EquationId, CurrentProcessInfo); //assemble the elemental contribution AssembleRHS(b, RHS_Contribution, EquationId); } } LHS_Contribution.resize(0, 0, false); RHS_Contribution.resize(0, false); // assemble all conditions //for (typename ConditionsArrayType::ptr_iterator it = ConditionsArray.ptr_begin(); it != ConditionsArray.ptr_end(); ++it) const int nconditions = static_cast<int>(ConditionsArray.size()); //#pragma omp parallel for firstprivate(nconditions, RHS_Contribution, EquationId) schedule(dynamic, 1024) #pragma omp for schedule(guided, 512) for (int i = 0; i<nconditions; i++) { auto it = ConditionsArray.begin() + i; //detect if the element is active or not. If the user did not make any choice the element //is active by default bool condition_is_active = true; if( (it)->IsDefined(ACTIVE) ) condition_is_active = (it)->Is(ACTIVE); if(condition_is_active) { //calculate elemental contribution pScheme->Condition_Calculate_RHS_Contribution(*(it.base()), RHS_Contribution, EquationId, CurrentProcessInfo); //assemble the elemental contribution AssembleRHS(b, RHS_Contribution, EquationId); } } } KRATOS_CATCH("") } //****************************************************************************************** //****************************************************************************************** inline void CreatePartition(unsigned int number_of_threads, const int number_of_rows, vector<unsigned int>& partitions) { partitions.resize(number_of_threads + 1); int partition_size = number_of_rows / number_of_threads; partitions[0] = 0; partitions[number_of_threads] = number_of_rows; for (unsigned int i = 1; i < number_of_threads; i++) partitions[i] = partitions[i - 1] + partition_size; } inline void AssembleRowContribution(TSystemMatrixType& A, const Matrix& Alocal, const unsigned int i, const unsigned int i_local, Element::EquationIdVectorType& EquationId) { double* values_vector = A.value_data().begin(); std::size_t* index1_vector = A.index1_data().begin(); std::size_t* index2_vector = A.index2_data().begin(); size_t left_limit = index1_vector[i]; // size_t right_limit = index1_vector[i+1]; //find the first entry size_t last_pos = ForwardFind(EquationId[0],left_limit,index2_vector); size_t last_found = EquationId[0]; #ifndef USE_LOCKS_IN_ASSEMBLY double& r_a = values_vector[last_pos]; const double& v_a = Alocal(i_local,0); #pragma omp atomic r_a += v_a; #else values_vector[last_pos] += Alocal(i_local,0); #endif //now find all of the other entries size_t pos = 0; for(unsigned int j=1; j<EquationId.size(); j++) { unsigned int id_to_find = EquationId[j]; if(id_to_find > last_found) pos = ForwardFind(id_to_find,last_pos+1,index2_vector); else pos = BackwardFind(id_to_find,last_pos-1,index2_vector); #ifndef USE_LOCKS_IN_ASSEMBLY double& r = values_vector[pos]; const double& v = Alocal(i_local,j); #pragma omp atomic r += v; #else values_vector[pos] += Alocal(i_local,j); #endif last_found = id_to_find; last_pos = pos; } } inline unsigned int ForwardFind(const unsigned int id_to_find, const unsigned int start, const size_t* index_vector) { unsigned int pos = start; while(id_to_find != index_vector[pos]) pos++; return pos; } inline unsigned int BackwardFind(const unsigned int id_to_find, const unsigned int start, const size_t* index_vector) { unsigned int pos = start; while(id_to_find != index_vector[pos]) pos--; return pos; } ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ ///@} ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ ///@} }; /* Class NodalResidualBasedBlockBuilderAndSolver */ ///@} ///@name Type Definitions ///@{ ///@} } /* namespace Kratos.*/ #endif /* KRATOS_NODAL_RESIDUAL_BASED_BLOCK_BUILDER_AND_SOLVER defined */
cancel-taskgroup-1.c
/* { dg-do run } */ /* { dg-set-target-env-var OMP_CANCELLATION "true" } */ #include <stdlib.h> #include <omp.h> struct T { struct T *children[2]; int val; }; struct T * search (struct T *tree, int val, int lvl) { if (tree == NULL || tree->val == val) return tree; struct T *ret = NULL; int i; for (i = 0; i < 2; i++) #pragma omp task shared(ret) if(lvl < 10) { struct T *r = search (tree->children[i], val, lvl + 1); if (r) { #pragma omp atomic write ret = r; #pragma omp cancel taskgroup } } #pragma omp taskwait return ret; } struct T * searchp (struct T *tree, int val) { struct T *ret; #pragma omp parallel shared(ret) firstprivate (tree, val) #pragma omp single #pragma omp taskgroup ret = search (tree, val, 0); return ret; } int main () { /* Must be power of two minus 1. */ int size = 0x7ffff; struct T *trees = (struct T *) malloc (size * sizeof (struct T)); if (trees == NULL) return 0; int i, l = 1, b = 0; for (i = 0; i < size; i++) { if (i == l) { b = l; l = l * 2 + 1; } trees[i].val = i; trees[i].children[0] = l == size ? NULL : &trees[l + (i - b) * 2]; trees[i].children[1] = l == size ? NULL : &trees[l + (i - b) * 2 + 1]; } for (i = 0; i < 50; i++) { int v = random () & size; if (searchp (&trees[0], v) != &trees[v]) abort (); } free (trees); return 0; }
GB_binop__rminus_uint32.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__rminus_uint32) // A.*B function (eWiseMult): GB (_AemultB_08__rminus_uint32) // A.*B function (eWiseMult): GB (_AemultB_02__rminus_uint32) // A.*B function (eWiseMult): GB (_AemultB_04__rminus_uint32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__rminus_uint32) // A*D function (colscale): GB (_AxD__rminus_uint32) // D*A function (rowscale): GB (_DxB__rminus_uint32) // C+=B function (dense accum): GB (_Cdense_accumB__rminus_uint32) // C+=b function (dense accum): GB (_Cdense_accumb__rminus_uint32) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__rminus_uint32) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__rminus_uint32) // C=scalar+B GB (_bind1st__rminus_uint32) // C=scalar+B' GB (_bind1st_tran__rminus_uint32) // C=A+scalar GB (_bind2nd__rminus_uint32) // C=A'+scalar GB (_bind2nd_tran__rminus_uint32) // C type: uint32_t // A type: uint32_t // A pattern? 0 // B type: uint32_t // B pattern? 0 // BinaryOp: cij = (bij - aij) #define GB_ATYPE \ uint32_t #define GB_BTYPE \ uint32_t #define GB_CTYPE \ uint32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint32_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint32_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (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_UINT32 || GxB_NO_RMINUS_UINT32) //------------------------------------------------------------------------------ // 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_uint32) ( 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__rminus_uint32) ( 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__rminus_uint32) ( 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_uint32) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint32_t uint32_t bwork = (*((uint32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__rminus_uint32) ( 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 uint32_t *restrict Cx = (uint32_t *) 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__rminus_uint32) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *restrict Cx = (uint32_t *) 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__rminus_uint32) ( 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) ; uint32_t alpha_scalar ; uint32_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint32_t *) alpha_scalar_in)) ; beta_scalar = (*((uint32_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__rminus_uint32) ( 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__rminus_uint32) ( 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__rminus_uint32) ( 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__rminus_uint32) ( 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_uint32) ( 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 uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t x = (*((uint32_t *) x_input)) ; uint32_t *Bx = (uint32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint32_t bij = GBX (Bx, p, false) ; 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_uint32) ( 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 ; uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t *Ax = (uint32_t *) Ax_input ; uint32_t y = (*((uint32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint32_t aij = GBX (Ax, p, false) ; 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) \ { \ uint32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij - x) ; \ } GrB_Info GB (_bind1st_tran__rminus_uint32) ( 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 \ uint32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t x = (*((const uint32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (y - aij) ; \ } GrB_Info GB (_bind2nd_tran__rminus_uint32) ( 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 uint32_t y = (*((const uint32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
f399_so12_adv.c
#define _POSIX_C_SOURCE 200809L #include "stdlib.h" #include "math.h" #include "sys/time.h" #include "xmmintrin.h" #include "pmmintrin.h" #include "omp.h" #include <stdio.h> #define min(a, b) (((a) < (b)) ? (a) : (b)) #define max(a, b) (((a) > (b)) ? (a) : (b)) struct dataobj { void *restrict data; int *size; int *npsize; int *dsize; int *hsize; int *hofs; int *oofs; }; struct profiler { double section0; double section1; double section2; }; void bf0(struct dataobj *restrict damp_vec, const float dt, struct dataobj *restrict epsilon_vec, float *restrict r73_vec, float *restrict r74_vec, float *restrict r75_vec, float *restrict r76_vec, float *restrict r77_vec, struct dataobj *restrict u_vec, struct dataobj *restrict v_vec, struct dataobj *restrict vp_vec, struct dataobj *restrict nnz_sp_source_mask_vec, struct dataobj *restrict sp_source_mask_vec, struct dataobj *restrict save_src_u_vec, struct dataobj *restrict save_src_v_vec, struct dataobj *restrict source_id_vec, struct dataobj *restrict source_mask_vec, const int x0_blk0_size, const int x_size, const int y0_blk0_size, const int y_size, const int z_size, const int t0, const int t1, const int t2, const int x_M, const int x_m, const int y_M, const int y_m, const int z_M, const int z_m, const int sp_zi_m, const int nthreads, const int xb, const int yb, const int xb_size, const int yb_size, float **restrict r131_vec, float **restrict r132_vec, const int time, const int tw); int ForwardTTI(struct dataobj *restrict block_sizes_vec, struct dataobj *restrict damp_vec, struct dataobj *restrict delta_vec, const float dt, struct dataobj *restrict epsilon_vec, struct dataobj *restrict nnz_sp_source_mask_vec, struct dataobj *restrict phi_vec, struct dataobj *restrict save_src_u_vec, struct dataobj *restrict save_src_v_vec, struct dataobj *restrict source_id_vec, struct dataobj *restrict source_mask_vec, struct dataobj *restrict sp_source_mask_vec, struct dataobj *restrict theta_vec, struct dataobj *restrict u_vec, struct dataobj *restrict v_vec, struct dataobj *restrict vp_vec, const int x_size, const int y_size, const int z_size, const int sp_zi_m, const int time_M, const int time_m, struct profiler *timers, const int x_M, const int x_m, const int y_M, const int y_m, const int z_M, const int z_m, const int nthreads, const int nthreads_nonaffine) { int(*restrict block_sizes) __attribute__((aligned(64))) = (int(*))block_sizes_vec->data; float(*restrict delta)[delta_vec->size[1]][delta_vec->size[2]] __attribute__((aligned(64))) = (float(*)[delta_vec->size[1]][delta_vec->size[2]])delta_vec->data; int(*restrict nnz_sp_source_mask)[nnz_sp_source_mask_vec->size[1]] __attribute__((aligned(64))) = (int(*)[nnz_sp_source_mask_vec->size[1]])nnz_sp_source_mask_vec->data; float(*restrict phi)[phi_vec->size[1]][phi_vec->size[2]] __attribute__((aligned(64))) = (float(*)[phi_vec->size[1]][phi_vec->size[2]])phi_vec->data; float(*restrict save_src_u)[save_src_u_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_u_vec->size[1]])save_src_u_vec->data; float(*restrict save_src_v)[save_src_v_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_v_vec->size[1]])save_src_v_vec->data; int(*restrict source_id)[source_id_vec->size[1]][source_id_vec->size[2]] __attribute__((aligned(64))) = (int(*)[source_id_vec->size[1]][source_id_vec->size[2]])source_id_vec->data; int(*restrict source_mask)[source_mask_vec->size[1]][source_mask_vec->size[2]] __attribute__((aligned(64))) = (int(*)[source_mask_vec->size[1]][source_mask_vec->size[2]])source_mask_vec->data; int(*restrict sp_source_mask)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]] __attribute__((aligned(64))) = (int(*)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]])sp_source_mask_vec->data; float(*restrict theta)[theta_vec->size[1]][theta_vec->size[2]] __attribute__((aligned(64))) = (float(*)[theta_vec->size[1]][theta_vec->size[2]])theta_vec->data; float(*restrict u)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]] __attribute__((aligned(64))) = (float(*)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]])u_vec->data; float(*restrict v)[v_vec->size[1]][v_vec->size[2]][v_vec->size[3]] __attribute__((aligned(64))) = (float(*)[v_vec->size[1]][v_vec->size[2]][v_vec->size[3]])v_vec->data; float(*r73)[y_size + 3 + 3][z_size + 3 + 3]; posix_memalign((void **)&r73, 64, sizeof(float[x_size + 3 + 3][y_size + 3 + 3][z_size + 3 + 3])); float(*r74)[y_size + 3 + 3][z_size + 3 + 3]; posix_memalign((void **)&r74, 64, sizeof(float[x_size + 3 + 3][y_size + 3 + 3][z_size + 3 + 3])); float(*r75)[y_size + 3 + 3][z_size + 3 + 3]; posix_memalign((void **)&r75, 64, sizeof(float[x_size + 3 + 3][y_size + 3 + 3][z_size + 3 + 3])); float(*r76)[y_size + 3 + 3][z_size + 3 + 3]; posix_memalign((void **)&r76, 64, sizeof(float[x_size + 3 + 3][y_size + 3 + 3][z_size + 3 + 3])); float(*r77)[y_size + 3 + 3][z_size + 3 + 3]; posix_memalign((void **)&r77, 64, sizeof(float[x_size + 3 + 3][y_size + 3 + 3][z_size + 3 + 3])); float **r131; posix_memalign((void **)&r131, 64, sizeof(float *) * nthreads); float **r132; posix_memalign((void **)&r132, 64, sizeof(float *) * nthreads); int y0_blk0_size = block_sizes[3]; int x0_blk0_size = block_sizes[2]; int yb_size = block_sizes[1]; int xb_size = block_sizes[0]; int sf = 6; int t_blk_size = 2 * sf * (time_M - time_m); printf(" Tiles: %d, %d ::: Blocks %d, %d \n", xb_size, yb_size, x0_blk0_size, y0_blk0_size); #pragma omp parallel num_threads(nthreads) { const int tid = omp_get_thread_num(); posix_memalign((void **)&r131[tid], 64, sizeof(float[x0_blk0_size + 3 + 3][y0_blk0_size + 3 + 3][z_size + 3 + 3])); posix_memalign((void **)&r132[tid], 64, sizeof(float[x0_blk0_size + 3 + 3][y0_blk0_size + 3 + 3][z_size + 3 + 3])); } /* Flush denormal numbers to zero in hardware */ _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); struct timeval start_section0, end_section0; gettimeofday(&start_section0, NULL); /* Begin section0 */ #pragma omp parallel num_threads(nthreads) { #pragma omp for collapse(2) schedule(static, 1) for (int x = x_m - 3; x <= x_M + 3; x += 1) { for (int y = y_m - 3; y <= y_M + 3; y += 1) { #pragma omp simd aligned(delta, phi, theta : 64) for (int z = z_m - 3; z <= z_M + 3; z += 1) { r73[x + 3][y + 3][z + 3] = sqrt(2 * delta[x + 12][y + 12][z + 12] + 1); r74[x + 3][y + 3][z + 3] = cos(theta[x + 12][y + 12][z + 12]); r75[x + 3][y + 3][z + 3] = sin(phi[x + 12][y + 12][z + 12]); r76[x + 3][y + 3][z + 3] = sin(theta[x + 12][y + 12][z + 12]); r77[x + 3][y + 3][z + 3] = cos(phi[x + 12][y + 12][z + 12]); } } } } /* End section0 */ gettimeofday(&end_section0, NULL); timers->section0 += (double)(end_section0.tv_sec - start_section0.tv_sec) + (double)(end_section0.tv_usec - start_section0.tv_usec) / 1000000; printf(" Tiles: %d, %d ::: Blocks %d, %d \n", xb_size, yb_size, x0_blk0_size, y0_blk0_size); for (int t_blk = time_m; t_blk <= 1 + sf * (time_M - time_m); t_blk += sf * t_blk_size) // for each t block { for (int xb = x_m - 1; xb <= (x_M + sf * (time_M - time_m)); xb += xb_size) { //printf(" Change of outer xblock %d \n", xb); for (int yb = y_m - 1; yb <= (y_M + sf * (time_M - time_m)); yb += yb_size) { for (int time = t_blk, t0 = (time) % (3), t1 = (time + 2) % (3), t2 = (time + 1) % (3); time <= 2 + min(t_blk + t_blk_size - 1, sf * (time_M - time_m)); time += sf, t0 = (((time / sf) % (time_M - time_m + 1))) % (3), t1 = (((time / sf) % (time_M - time_m + 1)) + 2) % (3), t2 = (((time / sf) % (time_M - time_m + 1)) + 1) % (3)) { int tw = ((time / sf) % (time_M - time_m + 1)); struct timeval start_section1, end_section1; gettimeofday(&start_section1, NULL); /* Begin section1 */ bf0(damp_vec, dt, epsilon_vec, (float *)r73, (float *)r74, (float *)r75, (float *)r76, (float *)r77, u_vec, v_vec, vp_vec, nnz_sp_source_mask_vec, sp_source_mask_vec, save_src_u_vec, save_src_v_vec, source_id_vec, source_mask_vec, x0_blk0_size, x_size, y0_blk0_size, y_size, z_size, t0, t1, t2, x_M, x_m, y_M, y_m, z_M, z_m, sp_zi_m, nthreads, xb, yb, xb_size, yb_size, (float **)r131, (float **)r132, time, tw); // x_M - (x_M - x_m + 1)%(x0_blk0_size), x_m, y_M - (y_M - y_m + 1)%(y0_blk0_size), y_m, /* End section1 */ gettimeofday(&end_section1, NULL); timers->section1 += (double)(end_section1.tv_sec - start_section1.tv_sec) + (double)(end_section1.tv_usec - start_section1.tv_usec) / 1000000; } } } } #pragma omp parallel num_threads(nthreads) { const int tid = omp_get_thread_num(); free(r131[tid]); free(r132[tid]); } free(r73); free(r74); free(r75); free(r76); free(r77); free(r131); free(r132); return 0; } void bf0(struct dataobj *restrict damp_vec, const float dt, struct dataobj *restrict epsilon_vec, float *restrict r73_vec, float *restrict r74_vec, float *restrict r75_vec, float *restrict r76_vec, float *restrict r77_vec, struct dataobj *restrict u_vec, struct dataobj *restrict v_vec, struct dataobj *restrict vp_vec, struct dataobj *restrict nnz_sp_source_mask_vec, struct dataobj *restrict sp_source_mask_vec, struct dataobj *restrict save_src_u_vec, struct dataobj *restrict save_src_v_vec, struct dataobj *restrict source_id_vec, struct dataobj *restrict source_mask_vec, const int x0_blk0_size, const int x_size, const int y0_blk0_size, const int y_size, const int z_size, const int t0, const int t1, const int t2, const int x_M, const int x_m, const int y_M, const int y_m, const int z_M, const int z_m, const int sp_zi_m, const int nthreads, const int xb, const int yb, const int xb_size, const int yb_size, float **restrict r131_vec, float **restrict r132_vec, const int time, const int tw) { float(*restrict damp)[damp_vec->size[1]][damp_vec->size[2]] __attribute__((aligned(64))) = (float(*)[damp_vec->size[1]][damp_vec->size[2]])damp_vec->data; float(*restrict epsilon)[epsilon_vec->size[1]][epsilon_vec->size[2]] __attribute__((aligned(64))) = (float(*)[epsilon_vec->size[1]][epsilon_vec->size[2]])epsilon_vec->data; float(*restrict r73)[y_size + 3 + 3][z_size + 3 + 3] __attribute__((aligned(64))) = (float(*)[y_size + 3 + 3][z_size + 3 + 3]) r73_vec; float(*restrict r74)[y_size + 3 + 3][z_size + 3 + 3] __attribute__((aligned(64))) = (float(*)[y_size + 3 + 3][z_size + 3 + 3]) r74_vec; float(*restrict r75)[y_size + 3 + 3][z_size + 3 + 3] __attribute__((aligned(64))) = (float(*)[y_size + 3 + 3][z_size + 3 + 3]) r75_vec; float(*restrict r76)[y_size + 3 + 3][z_size + 3 + 3] __attribute__((aligned(64))) = (float(*)[y_size + 3 + 3][z_size + 3 + 3]) r76_vec; float(*restrict r77)[y_size + 3 + 3][z_size + 3 + 3] __attribute__((aligned(64))) = (float(*)[y_size + 3 + 3][z_size + 3 + 3]) r77_vec; float(*restrict u)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]] __attribute__((aligned(64))) = (float(*)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]])u_vec->data; float(*restrict v)[v_vec->size[1]][v_vec->size[2]][v_vec->size[3]] __attribute__((aligned(64))) = (float(*)[v_vec->size[1]][v_vec->size[2]][v_vec->size[3]])v_vec->data; float(*restrict vp)[vp_vec->size[1]][vp_vec->size[2]] __attribute__((aligned(64))) = (float(*)[vp_vec->size[1]][vp_vec->size[2]])vp_vec->data; float **r131 = (float **)r131_vec; float **r132 = (float **)r132_vec; int(*restrict nnz_sp_source_mask)[nnz_sp_source_mask_vec->size[1]] __attribute__((aligned(64))) = (int(*)[nnz_sp_source_mask_vec->size[1]])nnz_sp_source_mask_vec->data; float(*restrict save_src_u)[save_src_u_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_u_vec->size[1]])save_src_u_vec->data; float(*restrict save_src_v)[save_src_v_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_v_vec->size[1]])save_src_v_vec->data; int(*restrict source_id)[source_id_vec->size[1]][source_id_vec->size[2]] __attribute__((aligned(64))) = (int(*)[source_id_vec->size[1]][source_id_vec->size[2]])source_id_vec->data; int(*restrict source_mask)[source_mask_vec->size[1]][source_mask_vec->size[2]] __attribute__((aligned(64))) = (int(*)[source_mask_vec->size[1]][source_mask_vec->size[2]])source_mask_vec->data; int(*restrict sp_source_mask)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]] __attribute__((aligned(64))) = (int(*)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]])sp_source_mask_vec->data; #pragma omp parallel num_threads(nthreads) { const int tid = omp_get_thread_num(); float(*restrict r118)[y0_blk0_size + 3 + 3][z_size + 3 + 3] __attribute__((aligned(64))) = (float(*)[y0_blk0_size + 3 + 3][z_size + 3 + 3]) r131[tid]; float(*restrict r119)[y0_blk0_size + 3 + 3][z_size + 3 + 3] __attribute__((aligned(64))) = (float(*)[y0_blk0_size + 3 + 3][z_size + 3 + 3]) r132[tid]; #pragma omp for collapse(2) schedule(dynamic, 1) for (int x0_blk0 = max((x_m + time), xb); x0_blk0 <= min((x_M + time), (xb + xb_size)); x0_blk0 += x0_blk0_size) { for (int y0_blk0 = max((y_m + time), yb); y0_blk0 <= min((y_M + time), (yb + yb_size)); y0_blk0 += y0_blk0_size) { for (int x = x0_blk0 - 3, xs = 0; x <= min(min((x_M + time), (xb + xb_size + 2)), (x0_blk0 + x0_blk0_size + 2)); x++, xs++) { for (int y = y0_blk0 - 3, ys = 0; y <= min(min((y_M + time), (yb + yb_size + 2)), (y0_blk0 + y0_blk0_size + 2)); y++, ys++) { #pragma omp simd aligned(u, v : 64) for (int z = z_m - 3; z <= z_M + 3; z += 1) { r118[xs][ys][z + 3] = -(1.66666669e-3F * (-u[t0][x - time + 9][y - time + 12][z + 12] + u[t0][x - time + 15][y - time + 12][z + 12]) + 1.50000002e-2F * (u[t0][x - time + 10][y - time + 12][z + 12] - u[t0][x - time + 14][y - time + 12][z + 12]) + 7.50000011e-2F * (-u[t0][x - time + 11][y - time + 12][z + 12] + u[t0][x - time + 13][y - time + 12][z + 12])) * r76[x - time + 3][y - time + 3][z + 3] * r77[x - time + 3][y - time + 3][z + 3] - (1.66666669e-3F * (-u[t0][x - time + 12][y - time + 9][z + 12] + u[t0][x - time + 12][y - time + 15][z + 12]) + 1.50000002e-2F * (u[t0][x - time + 12][y - time + 10][z + 12] - u[t0][x - time + 12][y - time + 14][z + 12]) + 7.50000011e-2F * (-u[t0][x - time + 12][y - time + 11][z + 12] + u[t0][x - time + 12][y - time + 13][z + 12])) * r75[x - time + 3][y - time + 3][z + 3] * r76[x - time + 3][y - time + 3][z + 3] - (1.66666669e-3F * (-u[t0][x - time + 12][y - time + 12][z + 9] + u[t0][x - time + 12][y - time + 12][z + 15]) + 1.50000002e-2F * (u[t0][x - time + 12][y - time + 12][z + 10] - u[t0][x - time + 12][y - time + 12][z + 14]) + 7.50000011e-2F * (-u[t0][x - time + 12][y - time + 12][z + 11] + u[t0][x - time + 12][y - time + 12][z + 13])) * r74[x - time + 3][y - time + 3][z + 3]; r119[xs][ys][z + 3] = -(1.66666669e-3F * (-v[t0][x - time + 9][y - time + 12][z + 12] + v[t0][x - time + 15][y - time + 12][z + 12]) + 1.50000002e-2F * (v[t0][x - time + 10][y - time + 12][z + 12] - v[t0][x - time + 14][y - time + 12][z + 12]) + 7.50000011e-2F * (-v[t0][x - time + 11][y - time + 12][z + 12] + v[t0][x - time + 13][y - time + 12][z + 12])) * r76[x - time + 3][y - time + 3][z + 3] * r77[x - time + 3][y - time + 3][z + 3] - (1.66666669e-3F * (-v[t0][x - time + 12][y - time + 9][z + 12] + v[t0][x - time + 12][y - time + 15][z + 12]) + 1.50000002e-2F * (v[t0][x - time + 12][y - time + 10][z + 12] - v[t0][x - time + 12][y - time + 14][z + 12]) + 7.50000011e-2F * (-v[t0][x - time + 12][y - time + 11][z + 12] + v[t0][x - time + 12][y - time + 13][z + 12])) * r75[x - time + 3][y - time + 3][z + 3] * r76[x - time + 3][y - time + 3][z + 3] - (1.66666669e-3F * (-v[t0][x - time + 12][y - time + 12][z + 9] + v[t0][x - time + 12][y - time + 12][z + 15]) + 1.50000002e-2F * (v[t0][x - time + 12][y - time + 12][z + 10] - v[t0][x - time + 12][y - time + 12][z + 14]) + 7.50000011e-2F * (-v[t0][x - time + 12][y - time + 12][z + 11] + v[t0][x - time + 12][y - time + 12][z + 13])) * r74[x - time + 3][y - time + 3][z + 3]; } } } for (int x = x0_blk0, xs = 0; x <= min(min((x_M + time), (xb + xb_size - 1)), (x0_blk0 + x0_blk0_size - 1)); x++, xs++) { for (int y = y0_blk0, ys = 0; y <= min(min((y_M + time), (yb + yb_size - 1)), (y0_blk0 + y0_blk0_size - 1)); y++, ys++) { #pragma omp simd aligned(damp, epsilon, u, v, vp : 64) for (int z = z_m; z <= z_M; z += 1) { float r130 = 1.0 / dt; float r129 = 1.0 / (dt * dt); float r128 = 1.50000002e-2F * (-r119[xs + 1][ys + 3][z + 3] * r76[x - time + 1][y - time + 3][z + 3] * r77[x - time + 1][y - time + 3][z + 3] - r119[xs + 3][ys + 1][z + 3] * r75[x - time + 3][y - time + 1][z + 3] * r76[x - time + 3][y - time + 1][z + 3] - r119[xs + 3][ys + 3][z + 1] * r74[x - time + 3][y - time + 3][z + 1] + r119[xs + 3][ys + 3][z + 5] * r74[x - time + 3][y - time + 3][z + 5] + r119[xs + 3][ys + 5][z + 3] * r75[x - time + 3][y - time + 5][z + 3] * r76[x - time + 3][y - time + 5][z + 3] + r119[xs + 5][ys + 3][z + 3] * r76[x - time + 5][y - time + 3][z + 3] * r77[x - time + 5][y - time + 3][z + 3]); float r127 = 1.66666669e-3F * (r119[xs][ys + 3][z + 3] * r76[x - time][y - time + 3][z + 3] * r77[x - time][y - time + 3][z + 3] + r119[xs + 3][ys][z + 3] * r75[x - time + 3][y - time][z + 3] * r76[x - time + 3][y - time][z + 3] + r119[xs + 3][ys + 3][z] * r74[x - time + 3][y - time + 3][z] - r119[xs + 3][ys + 3][z + 6] * r74[x - time + 3][y - time + 3][z + 6] - r119[xs + 3][ys + 6][z + 3] * r75[x - time + 3][y - time + 6][z + 3] * r76[x - time + 3][y - time + 6][z + 3] - r119[xs + 6][ys + 3][z + 3] * r76[x - time + 6][y - time + 3][z + 3] * r77[x - time + 6][y - time + 3][z + 3]); float r126 = 7.50000011e-2F * (r119[xs + 2][ys + 3][z + 3] * r76[x - time + 2][y - time + 3][z + 3] * r77[x - time + 2][y - time + 3][z + 3] + r119[xs + 3][ys + 2][z + 3] * r75[x - time + 3][y - time + 2][z + 3] * r76[x - time + 3][y - time + 2][z + 3] + r119[xs + 3][ys + 3][z + 2] * r74[x - time + 3][y - time + 3][z + 2] - r119[xs + 3][ys + 3][z + 4] * r74[x - time + 3][y - time + 3][z + 4] - r119[xs + 3][ys + 4][z + 3] * r75[x - time + 3][y - time + 4][z + 3] * r76[x - time + 3][y - time + 4][z + 3] - r119[xs + 4][ys + 3][z + 3] * r76[x - time + 4][y - time + 3][z + 3] * r77[x - time + 4][y - time + 3][z + 3]); float r125 = 1.0 / (vp[x - time + 12][y - time + 12][z + 12] * vp[x - time + 12][y - time + 12][z + 12]); float r124 = 1.0 / (r125 * r129 + r130 * damp[x - time + 1][y - time + 1][z + 1]); float r123 = 1.66666669e-3F * (-r118[xs][ys + 3][z + 3] * r76[x - time][y - time + 3][z + 3] * r77[x - time][y - time + 3][z + 3] - r118[xs + 3][ys][z + 3] * r75[x - time + 3][y - time][z + 3] * r76[x - time + 3][y - time][z + 3] - r118[xs + 3][ys + 3][z] * r74[x - time + 3][y - time + 3][z] + r118[xs + 3][ys + 3][z + 6] * r74[x - time + 3][y - time + 3][z + 6] + r118[xs + 3][ys + 6][z + 3] * r75[x - time + 3][y - time + 6][z + 3] * r76[x - time + 3][y - time + 6][z + 3] + r118[xs + 6][ys + 3][z + 3] * r76[x - time + 6][y - time + 3][z + 3] * r77[x - time + 6][y - time + 3][z + 3]) + 1.50000002e-2F * (r118[xs + 1][ys + 3][z + 3] * r76[x - time + 1][y - time + 3][z + 3] * r77[x - time + 1][y - time + 3][z + 3] + r118[xs + 3][ys + 1][z + 3] * r75[x - time + 3][y - time + 1][z + 3] * r76[x - time + 3][y - time + 1][z + 3] + r118[xs + 3][ys + 3][z + 1] * r74[x - time + 3][y - time + 3][z + 1] - r118[xs + 3][ys + 3][z + 5] * r74[x - time + 3][y - time + 3][z + 5] - r118[xs + 3][ys + 5][z + 3] * r75[x - time + 3][y - time + 5][z + 3] * r76[x - time + 3][y - time + 5][z + 3] - r118[xs + 5][ys + 3][z + 3] * r76[x - time + 5][y - time + 3][z + 3] * r77[x - time + 5][y - time + 3][z + 3]) + 7.50000011e-2F * (-r118[xs + 2][ys + 3][z + 3] * r76[x - time + 2][y - time + 3][z + 3] * r77[x - time + 2][y - time + 3][z + 3] - r118[xs + 3][ys + 2][z + 3] * r75[x - time + 3][y - time + 2][z + 3] * r76[x - time + 3][y - time + 2][z + 3] - r118[xs + 3][ys + 3][z + 2] * r74[x - time + 3][y - time + 3][z + 2] + r118[xs + 3][ys + 3][z + 4] * r74[x - time + 3][y - time + 3][z + 4] + r118[xs + 3][ys + 4][z + 3] * r75[x - time + 3][y - time + 4][z + 3] * r76[x - time + 3][y - time + 4][z + 3] + r118[xs + 4][ys + 3][z + 3] * r76[x - time + 4][y - time + 3][z + 3] * r77[x - time + 4][y - time + 3][z + 3]) - 6.01250588e-7F * (u[t0][x - time + 6][y - time + 12][z + 12] + u[t0][x - time + 12][y - time + 6][z + 12] + u[t0][x - time + 12][y - time + 12][z + 6] + u[t0][x - time + 12][y - time + 12][z + 18] + u[t0][x - time + 12][y - time + 18][z + 12] + u[t0][x - time + 18][y - time + 12][z + 12]) + 1.03896102e-5F * (u[t0][x - time + 7][y - time + 12][z + 12] + u[t0][x - time + 12][y - time + 7][z + 12] + u[t0][x - time + 12][y - time + 12][z + 7] + u[t0][x - time + 12][y - time + 12][z + 17] + u[t0][x - time + 12][y - time + 17][z + 12] + u[t0][x - time + 17][y - time + 12][z + 12]) - 8.92857123e-5F * (u[t0][x - time + 8][y - time + 12][z + 12] + u[t0][x - time + 12][y - time + 8][z + 12] + u[t0][x - time + 12][y - time + 12][z + 8] + u[t0][x - time + 12][y - time + 12][z + 16] + u[t0][x - time + 12][y - time + 16][z + 12] + u[t0][x - time + 16][y - time + 12][z + 12]) + 5.29100517e-4F * (u[t0][x - time + 9][y - time + 12][z + 12] + u[t0][x - time + 12][y - time + 9][z + 12] + u[t0][x - time + 12][y - time + 12][z + 9] + u[t0][x - time + 12][y - time + 12][z + 15] + u[t0][x - time + 12][y - time + 15][z + 12] + u[t0][x - time + 15][y - time + 12][z + 12]) - 2.67857137e-3F * (u[t0][x - time + 10][y - time + 12][z + 12] + u[t0][x - time + 12][y - time + 10][z + 12] + u[t0][x - time + 12][y - time + 12][z + 10] + u[t0][x - time + 12][y - time + 12][z + 14] + u[t0][x - time + 12][y - time + 14][z + 12] + u[t0][x - time + 14][y - time + 12][z + 12]) + 1.71428568e-2F * (u[t0][x - time + 11][y - time + 12][z + 12] + u[t0][x - time + 12][y - time + 11][z + 12] + u[t0][x - time + 12][y - time + 12][z + 11] + u[t0][x - time + 12][y - time + 12][z + 13] + u[t0][x - time + 12][y - time + 13][z + 12] + u[t0][x - time + 13][y - time + 12][z + 12]) - 8.94833313e-2F * u[t0][x - time + 12][y - time + 12][z + 12]; float r116 = r129 * (-2.0F * u[t0][x - time + 12][y - time + 12][z + 12] + u[t1][x - time + 12][y - time + 12][z + 12]); float r117 = r129 * (-2.0F * v[t0][x - time + 12][y - time + 12][z + 12] + v[t1][x - time + 12][y - time + 12][z + 12]); u[t2][x - time + 12][y - time + 12][z + 12] = r124 * ((-r116) * r125 + r123 * (2 * epsilon[x - time + 12][y - time + 12][z + 12] + 1) + r130 * (damp[x - time + 1][y - time + 1][z + 1] * u[t0][x - time + 12][y - time + 12][z + 12]) + (r126 + r127 + r128) * r73[x - time + 3][y - time + 3][z + 3]); v[t2][x - time + 12][y - time + 12][z + 12] = r124 * ((-r117) * r125 + r123 * r73[x - time + 3][y - time + 3][z + 3] + r126 + r127 + r128 + r130 * (damp[x - time + 1][y - time + 1][z + 1] * v[t0][x - time + 12][y - time + 12][z + 12])); } int sp_zi_M = nnz_sp_source_mask[x - time][y - time] - 1; for (int sp_zi = sp_zi_m; sp_zi <= sp_zi_M; sp_zi += 1) { int zind = sp_source_mask[x - time][y - time][sp_zi]; float r22 = save_src_u[tw][source_id[x - time][y - time][zind]] * source_mask[x - time][y - time][zind]; u[t2][x - time + 12][y - time + 12][zind + 12] += r22; float r23 = save_src_v[tw][source_id[x - time][y - time][zind]] * source_mask[x - time][y - time][zind]; v[t2][x - time + 12][y - time + 12][zind + 12] += r23; //printf("Source injection at time %d , at : x: %d, y: %d, %d, %f, %f \n", tw, x - time + 4, y - time + 4, zind + 4, r22, r23); } } } } } } }
omp_ex_07.c
#include <stdio.h> #include <omp.h> /* MIT License Copyright (c) 2019 NOUREDDINE DAGHBOUDJ 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. */ int main() { // After compiling this code, run it for a couple of times // What did you notice? #pragma omp parallel { #pragma omp sections { #pragma omp section { printf("Hello World! from Section A\n"); } #pragma omp section { printf("Hello World! from Section B\n"); } #pragma omp section { printf("Hello World! from Section C\n"); } #pragma omp section { printf("Hello World! from Section D\n"); } } } return 0; }
cache.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC AAA CCCC H H EEEEE % % C A A C H H E % % C AAAAA C HHHHH EEE % % C A A C H H E % % CCCC A A CCCC H H EEEEE % % % % % % MagickCore Pixel Cache Methods % % % % Software Design % % Cristy % % July 1999 % % % % % % 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 "MagickCore/studio.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite-private.h" #include "MagickCore/distribute-cache-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/geometry.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/nt-base-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/policy.h" #include "MagickCore/quantum.h" #include "MagickCore/random_.h" #include "MagickCore/registry.h" #include "MagickCore/resource_.h" #include "MagickCore/semaphore.h" #include "MagickCore/splay-tree.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #if defined(MAGICKCORE_ZLIB_DELEGATE) #include "zlib.h" #endif /* Define declarations. */ #define CacheTick(offset,extent) QuantumTick((MagickOffsetType) offset,extent) #define IsFileDescriptorLimitExceeded() (GetMagickResource(FileResource) > \ GetMagickResourceLimit(FileResource) ? MagickTrue : MagickFalse) /* Typedef declarations. */ typedef struct _MagickModulo { ssize_t quotient, remainder; } MagickModulo; /* Forward declarations. */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static Cache GetImagePixelCache(Image *,const MagickBooleanType,ExceptionInfo *) magick_hot_spot; static const Quantum *GetVirtualPixelCache(const Image *,const VirtualPixelMethod,const ssize_t, const ssize_t,const size_t,const size_t,ExceptionInfo *), *GetVirtualPixelsCache(const Image *); static const void *GetVirtualMetacontentFromCache(const Image *); static MagickBooleanType GetOneAuthenticPixelFromCache(Image *,const ssize_t,const ssize_t,Quantum *, ExceptionInfo *), GetOneVirtualPixelFromCache(const Image *,const VirtualPixelMethod, const ssize_t,const ssize_t,Quantum *,ExceptionInfo *), OpenPixelCache(Image *,const MapMode,ExceptionInfo *), OpenPixelCacheOnDisk(CacheInfo *,const MapMode), ReadPixelCachePixels(CacheInfo *magick_restrict,NexusInfo *magick_restrict, ExceptionInfo *), ReadPixelCacheMetacontent(CacheInfo *magick_restrict, NexusInfo *magick_restrict,ExceptionInfo *), SyncAuthenticPixelsCache(Image *,ExceptionInfo *), WritePixelCachePixels(CacheInfo *magick_restrict,NexusInfo *magick_restrict, ExceptionInfo *), WritePixelCacheMetacontent(CacheInfo *,NexusInfo *magick_restrict, ExceptionInfo *); static Quantum *GetAuthenticPixelsCache(Image *,const ssize_t,const ssize_t,const size_t, const size_t,ExceptionInfo *), *QueueAuthenticPixelsCache(Image *,const ssize_t,const ssize_t,const size_t, const size_t,ExceptionInfo *), *SetPixelCacheNexusPixels(const CacheInfo *,const MapMode, const RectangleInfo *,const MagickBooleanType,NexusInfo *, ExceptionInfo *) magick_hot_spot; #if defined(MAGICKCORE_OPENCL_SUPPORT) static void CopyOpenCLBuffer(CacheInfo *magick_restrict); #endif #if defined(__cplusplus) || defined(c_plusplus) } #endif /* Global declarations. */ static SemaphoreInfo *cache_semaphore = (SemaphoreInfo *) NULL; static ssize_t cache_anonymous_memory = (-1); static time_t cache_epoch = 0; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCache() acquires a pixel cache. % % The format of the AcquirePixelCache() method is: % % Cache AcquirePixelCache(const size_t number_threads) % % A description of each parameter follows: % % o number_threads: the number of nexus threads. % */ MagickPrivate Cache AcquirePixelCache(const size_t number_threads) { CacheInfo *magick_restrict cache_info; char *value; cache_info=(CacheInfo *) AcquireCriticalMemory(sizeof(*cache_info)); (void) memset(cache_info,0,sizeof(*cache_info)); cache_info->type=UndefinedCache; cache_info->mode=IOMode; cache_info->disk_mode=IOMode; cache_info->colorspace=sRGBColorspace; cache_info->file=(-1); cache_info->id=GetMagickThreadId(); cache_info->number_threads=number_threads; if (GetOpenMPMaximumThreads() > cache_info->number_threads) cache_info->number_threads=GetOpenMPMaximumThreads(); if (GetMagickResourceLimit(ThreadResource) > cache_info->number_threads) cache_info->number_threads=(size_t) GetMagickResourceLimit(ThreadResource); if (cache_info->number_threads == 0) cache_info->number_threads=1; cache_info->nexus_info=AcquirePixelCacheNexus(cache_info->number_threads); if (cache_info->nexus_info == (NexusInfo **) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); value=GetEnvironmentValue("MAGICK_SYNCHRONIZE"); if (value != (const char *) NULL) { cache_info->synchronize=IsStringTrue(value); value=DestroyString(value); } value=GetPolicyValue("cache:synchronize"); if (value != (const char *) NULL) { cache_info->synchronize=IsStringTrue(value); value=DestroyString(value); } cache_info->semaphore=AcquireSemaphoreInfo(); cache_info->reference_count=1; cache_info->file_semaphore=AcquireSemaphoreInfo(); cache_info->debug=IsEventLogging(); cache_info->signature=MagickCoreSignature; return((Cache ) cache_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCacheNexus() allocates the NexusInfo structure. % % The format of the AcquirePixelCacheNexus method is: % % NexusInfo **AcquirePixelCacheNexus(const size_t number_threads) % % A description of each parameter follows: % % o number_threads: the number of nexus threads. % */ MagickPrivate NexusInfo **AcquirePixelCacheNexus(const size_t number_threads) { NexusInfo **magick_restrict nexus_info; register ssize_t i; nexus_info=(NexusInfo **) MagickAssumeAligned(AcquireAlignedMemory( number_threads,sizeof(*nexus_info))); if (nexus_info == (NexusInfo **) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); nexus_info[0]=(NexusInfo *) AcquireQuantumMemory(number_threads, sizeof(**nexus_info)); if (nexus_info[0] == (NexusInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) memset(nexus_info[0],0,number_threads*sizeof(**nexus_info)); for (i=0; i < (ssize_t) number_threads; i++) { nexus_info[i]=(&nexus_info[0][i]); nexus_info[i]->signature=MagickCoreSignature; } return(nexus_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCachePixels() returns the pixels associated with the specified % image. % % The format of the AcquirePixelCachePixels() method is: % % void *AcquirePixelCachePixels(const Image *image,size_t *length, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o length: the pixel cache length. % % o exception: return any errors or warnings in this structure. % */ MagickExport void *AcquirePixelCachePixels(const Image *image,size_t *length, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); *length=0; if ((cache_info->type != MemoryCache) && (cache_info->type != MapCache)) return((void *) NULL); *length=(size_t) cache_info->length; return(cache_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C a c h e C o m p o n e n t G e n e s i s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CacheComponentGenesis() instantiates the cache component. % % The format of the CacheComponentGenesis method is: % % MagickBooleanType CacheComponentGenesis(void) % */ MagickPrivate MagickBooleanType CacheComponentGenesis(void) { if (cache_semaphore == (SemaphoreInfo *) NULL) cache_semaphore=AcquireSemaphoreInfo(); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C a c h e C o m p o n e n t T e r m i n u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CacheComponentTerminus() destroys the cache component. % % The format of the CacheComponentTerminus() method is: % % CacheComponentTerminus(void) % */ MagickPrivate void CacheComponentTerminus(void) { if (cache_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&cache_semaphore); /* no op-- nothing to destroy */ RelinquishSemaphoreInfo(&cache_semaphore); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l i p P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClipPixelCacheNexus() clips the cache nexus as defined by the image clip % mask. The method returns MagickTrue if the pixel region is clipped, % otherwise MagickFalse. % % The format of the ClipPixelCacheNexus() method is: % % MagickBooleanType ClipPixelCacheNexus(Image *image,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o nexus_info: the cache nexus to clip. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ClipPixelCacheNexus(Image *image, NexusInfo *nexus_info,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickSizeType number_pixels; NexusInfo **magick_restrict image_nexus; register Quantum *magick_restrict p, *magick_restrict q; register ssize_t n; /* Apply clip mask. */ if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->channels & WriteMaskChannel) == 0) return(MagickTrue); cache_info=(CacheInfo *) image->cache; if (cache_info == (Cache) NULL) return(MagickFalse); image_nexus=AcquirePixelCacheNexus(1); p=GetAuthenticPixelCacheNexus(image,nexus_info->region.x,nexus_info->region.y, nexus_info->region.width,nexus_info->region.height,image_nexus[0], exception); q=nexus_info->pixels; number_pixels=(MagickSizeType) nexus_info->region.width* nexus_info->region.height; for (n=0; n < (ssize_t) number_pixels; n++) { double mask_alpha; register ssize_t i; if (p == (Quantum *) NULL) break; mask_alpha=QuantumScale*GetPixelWriteMask(image,p); if (fabs(mask_alpha) >= MagickEpsilon) { for (i=0; i < (ssize_t) image->number_channels; i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ClampToQuantum(MagickOver_((double) p[i],mask_alpha* GetPixelAlpha(image,p),(double) q[i],(double) GetPixelAlpha(image,q))); } SetPixelAlpha(image,GetPixelAlpha(image,p),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(image); } image_nexus=DestroyPixelCacheNexus(image_nexus,1); if (n < (ssize_t) number_pixels) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelCache() clones a pixel cache. % % The format of the ClonePixelCache() method is: % % Cache ClonePixelCache(const Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ MagickPrivate Cache ClonePixelCache(const Cache cache) { CacheInfo *magick_restrict clone_info; const CacheInfo *magick_restrict cache_info; assert(cache != NULL); cache_info=(const CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); clone_info=(CacheInfo *) AcquirePixelCache(cache_info->number_threads); clone_info->virtual_pixel_method=cache_info->virtual_pixel_method; return((Cache ) clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelCacheMethods() clones the pixel cache methods from one cache to % another. % % The format of the ClonePixelCacheMethods() method is: % % void ClonePixelCacheMethods(Cache clone,const Cache cache) % % A description of each parameter follows: % % o clone: Specifies a pointer to a Cache structure. % % o cache: the pixel cache. % */ MagickPrivate void ClonePixelCacheMethods(Cache clone,const Cache cache) { CacheInfo *magick_restrict cache_info, *magick_restrict source_info; assert(clone != (Cache) NULL); source_info=(CacheInfo *) clone; assert(source_info->signature == MagickCoreSignature); if (source_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", source_info->filename); assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); source_info->methods=cache_info->methods; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e R e p o s i t o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelCacheRepository() clones the source pixel cache to the destination % cache. % % The format of the ClonePixelCacheRepository() method is: % % MagickBooleanType ClonePixelCacheRepository(CacheInfo *cache_info, % CacheInfo *source_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o source_info: the source pixel cache. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ClonePixelCacheOnDisk( CacheInfo *magick_restrict cache_info,CacheInfo *magick_restrict clone_info) { MagickSizeType extent; size_t quantum; ssize_t count; struct stat file_stats; unsigned char *buffer; /* Clone pixel cache on disk with identical morphology. */ if ((OpenPixelCacheOnDisk(cache_info,ReadMode) == MagickFalse) || (OpenPixelCacheOnDisk(clone_info,IOMode) == MagickFalse)) return(MagickFalse); quantum=(size_t) MagickMaxBufferExtent; if ((fstat(cache_info->file,&file_stats) == 0) && (file_stats.st_size > 0)) quantum=(size_t) MagickMin(file_stats.st_size,MagickMaxBufferExtent); buffer=(unsigned char *) AcquireQuantumMemory(quantum,sizeof(*buffer)); if (buffer == (unsigned char *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); extent=0; while ((count=read(cache_info->file,buffer,quantum)) > 0) { ssize_t number_bytes; number_bytes=write(clone_info->file,buffer,(size_t) count); if (number_bytes != count) break; extent+=number_bytes; } buffer=(unsigned char *) RelinquishMagickMemory(buffer); if (extent != cache_info->length) return(MagickFalse); return(MagickTrue); } static MagickBooleanType ClonePixelCacheRepository( CacheInfo *magick_restrict clone_info,CacheInfo *magick_restrict cache_info, ExceptionInfo *exception) { #define MaxCacheThreads ((size_t) GetMagickResourceLimit(ThreadResource)) #define cache_number_threads(source,destination,chunk,multithreaded) \ num_threads((multithreaded) == 0 ? 1 : \ (((source)->type != MemoryCache) && ((source)->type != MapCache)) || \ (((destination)->type != MemoryCache) && ((destination)->type != MapCache)) ? \ MagickMax(MagickMin(GetMagickResourceLimit(ThreadResource),2),1) : \ MagickMax(MagickMin((ssize_t) GetMagickResourceLimit(ThreadResource),(ssize_t) (chunk)/256),1)) MagickBooleanType optimize, status; NexusInfo **magick_restrict cache_nexus, **magick_restrict clone_nexus; size_t length; ssize_t y; assert(cache_info != (CacheInfo *) NULL); assert(clone_info != (CacheInfo *) NULL); assert(exception != (ExceptionInfo *) NULL); if (cache_info->type == PingCache) return(MagickTrue); length=cache_info->number_channels*sizeof(*cache_info->channel_map); if ((cache_info->columns == clone_info->columns) && (cache_info->rows == clone_info->rows) && (cache_info->number_channels == clone_info->number_channels) && (memcmp(cache_info->channel_map,clone_info->channel_map,length) == 0) && (cache_info->metacontent_extent == clone_info->metacontent_extent)) { /* Identical pixel cache morphology. */ if (((cache_info->type == MemoryCache) || (cache_info->type == MapCache)) && ((clone_info->type == MemoryCache) || (clone_info->type == MapCache))) { (void) memcpy(clone_info->pixels,cache_info->pixels, cache_info->number_channels*cache_info->columns*cache_info->rows* sizeof(*cache_info->pixels)); if ((cache_info->metacontent_extent != 0) && (clone_info->metacontent_extent != 0)) (void) memcpy(clone_info->metacontent,cache_info->metacontent, cache_info->columns*cache_info->rows* clone_info->metacontent_extent*sizeof(unsigned char)); return(MagickTrue); } if ((cache_info->type == DiskCache) && (clone_info->type == DiskCache)) return(ClonePixelCacheOnDisk(cache_info,clone_info)); } /* Mismatched pixel cache morphology. */ cache_nexus=AcquirePixelCacheNexus(MaxCacheThreads); clone_nexus=AcquirePixelCacheNexus(MaxCacheThreads); length=cache_info->number_channels*sizeof(*cache_info->channel_map); optimize=(cache_info->number_channels == clone_info->number_channels) && (memcmp(cache_info->channel_map,clone_info->channel_map,length) == 0) ? MagickTrue : MagickFalse; length=(size_t) MagickMin(cache_info->number_channels*cache_info->columns, clone_info->number_channels*clone_info->columns); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ cache_number_threads(cache_info,clone_info,cache_info->rows,1) #endif for (y=0; y < (ssize_t) cache_info->rows; y++) { const int id = GetOpenMPThreadId(); Quantum *pixels; RectangleInfo region; register ssize_t x; if (status == MagickFalse) continue; if (y >= (ssize_t) clone_info->rows) continue; region.width=cache_info->columns; region.height=1; region.x=0; region.y=y; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,&region,MagickFalse, cache_nexus[id],exception); if (pixels == (Quantum *) NULL) continue; status=ReadPixelCachePixels(cache_info,cache_nexus[id],exception); if (status == MagickFalse) continue; region.width=clone_info->columns; pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,&region,MagickFalse, clone_nexus[id],exception); if (pixels == (Quantum *) NULL) continue; (void) memset(clone_nexus[id]->pixels,0,(size_t) clone_nexus[id]->length); if (optimize != MagickFalse) (void) memcpy(clone_nexus[id]->pixels,cache_nexus[id]->pixels,length* sizeof(Quantum)); else { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; /* Mismatched pixel channel map. */ p=cache_nexus[id]->pixels; q=clone_nexus[id]->pixels; for (x=0; x < (ssize_t) cache_info->columns; x++) { register ssize_t i; if (x == (ssize_t) clone_info->columns) break; for (i=0; i < (ssize_t) clone_info->number_channels; i++) { PixelChannel channel; PixelTrait traits; channel=clone_info->channel_map[i].channel; traits=cache_info->channel_map[channel].traits; if (traits != UndefinedPixelTrait) *q=*(p+cache_info->channel_map[channel].offset); q++; } p+=cache_info->number_channels; } } status=WritePixelCachePixels(clone_info,clone_nexus[id],exception); } if ((cache_info->metacontent_extent != 0) && (clone_info->metacontent_extent != 0)) { /* Clone metacontent. */ length=(size_t) MagickMin(cache_info->metacontent_extent, clone_info->metacontent_extent); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ cache_number_threads(cache_info,clone_info,cache_info->rows,1) #endif for (y=0; y < (ssize_t) cache_info->rows; y++) { const int id = GetOpenMPThreadId(); Quantum *pixels; RectangleInfo region; if (status == MagickFalse) continue; if (y >= (ssize_t) clone_info->rows) continue; region.width=cache_info->columns; region.height=1; region.x=0; region.y=y; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,&region,MagickFalse, cache_nexus[id],exception); if (pixels == (Quantum *) NULL) continue; status=ReadPixelCacheMetacontent(cache_info,cache_nexus[id],exception); if (status == MagickFalse) continue; region.width=clone_info->columns; pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,&region, MagickFalse,clone_nexus[id],exception); if (pixels == (Quantum *) NULL) continue; if ((clone_nexus[id]->metacontent != (void *) NULL) && (cache_nexus[id]->metacontent != (void *) NULL)) (void) memcpy(clone_nexus[id]->metacontent, cache_nexus[id]->metacontent,length*sizeof(unsigned char)); status=WritePixelCacheMetacontent(clone_info,clone_nexus[id],exception); } } cache_nexus=DestroyPixelCacheNexus(cache_nexus,MaxCacheThreads); clone_nexus=DestroyPixelCacheNexus(clone_nexus,MaxCacheThreads); if (cache_info->debug != MagickFalse) { char message[MagickPathExtent]; (void) FormatLocaleString(message,MagickPathExtent,"%s => %s", CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type), CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) clone_info->type)); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImagePixelCache() deallocates memory associated with the pixel cache. % % The format of the DestroyImagePixelCache() method is: % % void DestroyImagePixelCache(Image *image) % % A description of each parameter follows: % % o image: the image. % */ static void DestroyImagePixelCache(Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->cache == (void *) NULL) return; image->cache=DestroyPixelCache(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImagePixels() deallocates memory associated with the pixel cache. % % The format of the DestroyImagePixels() method is: % % void DestroyImagePixels(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void DestroyImagePixels(Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.destroy_pixel_handler != (DestroyPixelHandler) NULL) { cache_info->methods.destroy_pixel_handler(image); return; } image->cache=DestroyPixelCache(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyPixelCache() deallocates memory associated with the pixel cache. % % The format of the DestroyPixelCache() method is: % % Cache DestroyPixelCache(Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ static MagickBooleanType ClosePixelCacheOnDisk(CacheInfo *cache_info) { int status; status=(-1); if (cache_info->file != -1) { status=close(cache_info->file); cache_info->file=(-1); RelinquishMagickResource(FileResource,1); } return(status == -1 ? MagickFalse : MagickTrue); } static inline void RelinquishPixelCachePixels(CacheInfo *cache_info) { switch (cache_info->type) { case MemoryCache: { #if defined(MAGICKCORE_OPENCL_SUPPORT) if (cache_info->opencl != (MagickCLCacheInfo) NULL) { cache_info->opencl=RelinquishMagickCLCacheInfo(cache_info->opencl, MagickTrue); cache_info->pixels=(Quantum *) NULL; break; } #endif if (cache_info->mapped == MagickFalse) cache_info->pixels=(Quantum *) RelinquishAlignedMemory( cache_info->pixels); else (void) UnmapBlob(cache_info->pixels,(size_t) cache_info->length); RelinquishMagickResource(MemoryResource,cache_info->length); break; } case MapCache: { (void) UnmapBlob(cache_info->pixels,(size_t) cache_info->length); cache_info->pixels=(Quantum *) NULL; if ((cache_info->mode != ReadMode) && (cache_info->mode != PersistMode)) (void) RelinquishUniqueFileResource(cache_info->cache_filename); *cache_info->cache_filename='\0'; RelinquishMagickResource(MapResource,cache_info->length); } case DiskCache: { if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); if ((cache_info->mode != ReadMode) && (cache_info->mode != PersistMode)) (void) RelinquishUniqueFileResource(cache_info->cache_filename); *cache_info->cache_filename='\0'; RelinquishMagickResource(DiskResource,cache_info->length); break; } case DistributedCache: { *cache_info->cache_filename='\0'; (void) RelinquishDistributePixelCache((DistributeCacheInfo *) cache_info->server_info); break; } default: break; } cache_info->type=UndefinedCache; cache_info->mapped=MagickFalse; cache_info->metacontent=(void *) NULL; } MagickPrivate Cache DestroyPixelCache(Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); LockSemaphoreInfo(cache_info->semaphore); cache_info->reference_count--; if (cache_info->reference_count != 0) { UnlockSemaphoreInfo(cache_info->semaphore); return((Cache) NULL); } UnlockSemaphoreInfo(cache_info->semaphore); if (cache_info->debug != MagickFalse) { char message[MagickPathExtent]; (void) FormatLocaleString(message,MagickPathExtent,"destroy %s", cache_info->filename); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } RelinquishPixelCachePixels(cache_info); if (cache_info->server_info != (DistributeCacheInfo *) NULL) cache_info->server_info=DestroyDistributeCacheInfo((DistributeCacheInfo *) cache_info->server_info); if (cache_info->nexus_info != (NexusInfo **) NULL) cache_info->nexus_info=DestroyPixelCacheNexus(cache_info->nexus_info, cache_info->number_threads); if (cache_info->random_info != (RandomInfo *) NULL) cache_info->random_info=DestroyRandomInfo(cache_info->random_info); if (cache_info->file_semaphore != (SemaphoreInfo *) NULL) RelinquishSemaphoreInfo(&cache_info->file_semaphore); if (cache_info->semaphore != (SemaphoreInfo *) NULL) RelinquishSemaphoreInfo(&cache_info->semaphore); cache_info->signature=(~MagickCoreSignature); cache_info=(CacheInfo *) RelinquishMagickMemory(cache_info); cache=(Cache) NULL; return(cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyPixelCacheNexus() destroys a pixel cache nexus. % % The format of the DestroyPixelCacheNexus() method is: % % NexusInfo **DestroyPixelCacheNexus(NexusInfo *nexus_info, % const size_t number_threads) % % A description of each parameter follows: % % o nexus_info: the nexus to destroy. % % o number_threads: the number of nexus threads. % */ static inline void RelinquishCacheNexusPixels(NexusInfo *nexus_info) { if (nexus_info->mapped == MagickFalse) (void) RelinquishAlignedMemory(nexus_info->cache); else (void) UnmapBlob(nexus_info->cache,(size_t) nexus_info->length); nexus_info->cache=(Quantum *) NULL; nexus_info->pixels=(Quantum *) NULL; nexus_info->metacontent=(void *) NULL; nexus_info->length=0; nexus_info->mapped=MagickFalse; } MagickPrivate NexusInfo **DestroyPixelCacheNexus(NexusInfo **nexus_info, const size_t number_threads) { register ssize_t i; assert(nexus_info != (NexusInfo **) NULL); for (i=0; i < (ssize_t) number_threads; i++) { if (nexus_info[i]->cache != (Quantum *) NULL) RelinquishCacheNexusPixels(nexus_info[i]); nexus_info[i]->signature=(~MagickCoreSignature); } nexus_info[0]=(NexusInfo *) RelinquishMagickMemory(nexus_info[0]); nexus_info=(NexusInfo **) RelinquishAlignedMemory(nexus_info); return(nexus_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticMetacontent() returns the authentic metacontent corresponding % with the last call to QueueAuthenticPixels() or GetVirtualPixels(). NULL is % returned if the associated pixels are not available. % % The format of the GetAuthenticMetacontent() method is: % % void *GetAuthenticMetacontent(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void *GetAuthenticMetacontent(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_authentic_metacontent_from_handler != (GetAuthenticMetacontentFromHandler) NULL) { void *metacontent; metacontent=cache_info->methods. get_authentic_metacontent_from_handler(image); return(metacontent); } assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->metacontent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c M e t a c o n t e n t F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticMetacontentFromCache() returns the meta-content corresponding % with the last call to QueueAuthenticPixelsCache() or % GetAuthenticPixelsCache(). % % The format of the GetAuthenticMetacontentFromCache() method is: % % void *GetAuthenticMetacontentFromCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static void *GetAuthenticMetacontentFromCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->metacontent); } #if defined(MAGICKCORE_OPENCL_SUPPORT) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c O p e n C L B u f f e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticOpenCLBuffer() returns an OpenCL buffer used to execute OpenCL % operations. % % The format of the GetAuthenticOpenCLBuffer() method is: % % cl_mem GetAuthenticOpenCLBuffer(const Image *image, % MagickCLDevice device,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o device: the device to use. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate cl_mem GetAuthenticOpenCLBuffer(const Image *image, MagickCLDevice device,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(device != (const MagickCLDevice) NULL); cache_info=(CacheInfo *) image->cache; if ((cache_info->type == UndefinedCache) || (cache_info->reference_count > 1)) { SyncImagePixelCache((Image *) image,exception); cache_info=(CacheInfo *) image->cache; } if ((cache_info->type != MemoryCache) || (cache_info->mapped != MagickFalse)) return((cl_mem) NULL); LockSemaphoreInfo(cache_info->semaphore); if ((cache_info->opencl != (MagickCLCacheInfo) NULL) && (cache_info->opencl->device->context != device->context)) cache_info->opencl=CopyMagickCLCacheInfo(cache_info->opencl); if (cache_info->opencl == (MagickCLCacheInfo) NULL) { assert(cache_info->pixels != (Quantum *) NULL); cache_info->opencl=AcquireMagickCLCacheInfo(device,cache_info->pixels, cache_info->length); } if (cache_info->opencl != (MagickCLCacheInfo) NULL) RetainOpenCLMemObject(cache_info->opencl->buffer); UnlockSemaphoreInfo(cache_info->semaphore); if (cache_info->opencl == (MagickCLCacheInfo) NULL) return((cl_mem) NULL); assert(cache_info->opencl->pixels == cache_info->pixels); return(cache_info->opencl->buffer); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelCacheNexus() gets authentic pixels from the in-memory or % disk pixel cache as defined by the geometry parameters. A pointer to the % pixels is returned if the pixels are transferred, otherwise a NULL is % returned. % % The format of the GetAuthenticPixelCacheNexus() method is: % % Quantum *GetAuthenticPixelCacheNexus(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to return. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate Quantum *GetAuthenticPixelCacheNexus(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows,NexusInfo *nexus_info, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; Quantum *magick_restrict pixels; /* Transfer pixels from the cache. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); pixels=QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickTrue, nexus_info,exception); if (pixels == (Quantum *) NULL) return((Quantum *) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (nexus_info->authentic_pixel_cache != MagickFalse) return(pixels); if (ReadPixelCachePixels(cache_info,nexus_info,exception) == MagickFalse) return((Quantum *) NULL); if (cache_info->metacontent_extent != 0) if (ReadPixelCacheMetacontent(cache_info,nexus_info,exception) == MagickFalse) return((Quantum *) NULL); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l s F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelsFromCache() returns the pixels associated with the last % call to the QueueAuthenticPixelsCache() or GetAuthenticPixelsCache() methods. % % The format of the GetAuthenticPixelsFromCache() method is: % % Quantum *GetAuthenticPixelsFromCache(const Image image) % % A description of each parameter follows: % % o image: the image. % */ static Quantum *GetAuthenticPixelsFromCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c P i x e l Q u e u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelQueue() returns the authentic pixels associated % corresponding with the last call to QueueAuthenticPixels() or % GetAuthenticPixels(). % % The format of the GetAuthenticPixelQueue() method is: % % Quantum *GetAuthenticPixelQueue(const Image image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport Quantum *GetAuthenticPixelQueue(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_authentic_pixels_from_handler != (GetAuthenticPixelsFromHandler) NULL) return(cache_info->methods.get_authentic_pixels_from_handler(image)); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixels() obtains a pixel region for read/write access. If the % region is successfully accessed, a pointer to a Quantum array % representing the region is returned, otherwise NULL is returned. % % The returned pointer may point to a temporary working copy of the pixels % or it may point to the original pixels in memory. Performance is maximized % if the selected region is part of one row, or one or more full rows, since % then there is opportunity to access the pixels in-place (without a copy) % if the image is in memory, or in a memory-mapped file. The returned pointer % must *never* be deallocated by the user. % % Pixels accessed via the returned pointer represent a simple array of type % Quantum. If the image has corresponding metacontent,call % GetAuthenticMetacontent() after invoking GetAuthenticPixels() to obtain the % meta-content corresponding to the region. Once the Quantum array has % been updated, the changes must be saved back to the underlying image using % SyncAuthenticPixels() or they may be lost. % % The format of the GetAuthenticPixels() method is: % % Quantum *GetAuthenticPixels(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Quantum *GetAuthenticPixels(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); Quantum *pixels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_authentic_pixels_handler != (GetAuthenticPixelsHandler) NULL) { pixels=cache_info->methods.get_authentic_pixels_handler(image,x,y,columns, rows,exception); return(pixels); } assert(id < (int) cache_info->number_threads); pixels=GetAuthenticPixelCacheNexus(image,x,y,columns,rows, cache_info->nexus_info[id],exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l s C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelsCache() gets pixels from the in-memory or disk pixel cache % as defined by the geometry parameters. A pointer to the pixels is returned % if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetAuthenticPixelsCache() method is: % % Quantum *GetAuthenticPixelsCache(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static Quantum *GetAuthenticPixelsCache(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); Quantum *magick_restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; if (cache_info == (Cache) NULL) return((Quantum *) NULL); assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); pixels=GetAuthenticPixelCacheNexus(image,x,y,columns,rows, cache_info->nexus_info[id],exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageExtent() returns the extent of the pixels associated corresponding % with the last call to QueueAuthenticPixels() or GetAuthenticPixels(). % % The format of the GetImageExtent() method is: % % MagickSizeType GetImageExtent(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport MagickSizeType GetImageExtent(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(GetPixelCacheNexusExtent(cache_info,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImagePixelCache() ensures that there is only a single reference to the % pixel cache to be modified, updating the provided cache pointer to point to % a clone of the original pixel cache if necessary. % % The format of the GetImagePixelCache method is: % % Cache GetImagePixelCache(Image *image,const MagickBooleanType clone, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o clone: any value other than MagickFalse clones the cache pixels. % % o exception: return any errors or warnings in this structure. % */ static inline MagickBooleanType ValidatePixelCacheMorphology( const Image *magick_restrict image) { const CacheInfo *magick_restrict cache_info; const PixelChannelMap *magick_restrict p, *magick_restrict q; /* Does the image match the pixel cache morphology? */ cache_info=(CacheInfo *) image->cache; p=image->channel_map; q=cache_info->channel_map; if ((image->storage_class != cache_info->storage_class) || (image->colorspace != cache_info->colorspace) || (image->alpha_trait != cache_info->alpha_trait) || (image->channels != cache_info->channels) || (image->columns != cache_info->columns) || (image->rows != cache_info->rows) || (image->number_channels != cache_info->number_channels) || (memcmp(p,q,image->number_channels*sizeof(*p)) != 0) || (image->metacontent_extent != cache_info->metacontent_extent) || (cache_info->nexus_info == (NexusInfo **) NULL)) return(MagickFalse); return(MagickTrue); } static Cache GetImagePixelCache(Image *image,const MagickBooleanType clone, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickBooleanType destroy, status; static MagickSizeType cache_timelimit = MagickResourceInfinity, cpu_throttle = MagickResourceInfinity, cycles = 0; status=MagickTrue; if (cpu_throttle == MagickResourceInfinity) cpu_throttle=GetMagickResourceLimit(ThrottleResource); if ((cpu_throttle != 0) && ((cycles++ % 32) == 0)) MagickDelay(cpu_throttle); if (cache_epoch == 0) { /* Set the expire time in seconds. */ cache_timelimit=GetMagickResourceLimit(TimeResource); cache_epoch=time((time_t *) NULL); } if ((cache_timelimit != MagickResourceInfinity) && ((MagickSizeType) (time((time_t *) NULL)-cache_epoch) >= cache_timelimit)) { #if defined(ECANCELED) errno=ECANCELED; #endif cache_info=(CacheInfo *) image->cache; if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); ThrowFatalException(ResourceLimitFatalError,"TimeLimitExceeded"); } LockSemaphoreInfo(image->semaphore); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; #if defined(MAGICKCORE_OPENCL_SUPPORT) CopyOpenCLBuffer(cache_info); #endif destroy=MagickFalse; if ((cache_info->reference_count > 1) || (cache_info->mode == ReadMode)) { LockSemaphoreInfo(cache_info->semaphore); if ((cache_info->reference_count > 1) || (cache_info->mode == ReadMode)) { CacheInfo *clone_info; Image clone_image; /* Clone pixel cache. */ clone_image=(*image); clone_image.semaphore=AcquireSemaphoreInfo(); clone_image.reference_count=1; clone_image.cache=ClonePixelCache(cache_info); clone_info=(CacheInfo *) clone_image.cache; status=OpenPixelCache(&clone_image,IOMode,exception); if (status == MagickFalse) clone_info=(CacheInfo *) DestroyPixelCache(clone_info); else { if (clone != MagickFalse) status=ClonePixelCacheRepository(clone_info,cache_info, exception); if (status == MagickFalse) clone_info=(CacheInfo *) DestroyPixelCache(clone_info); else { destroy=MagickTrue; image->cache=clone_info; } } RelinquishSemaphoreInfo(&clone_image.semaphore); } UnlockSemaphoreInfo(cache_info->semaphore); } if (destroy != MagickFalse) cache_info=(CacheInfo *) DestroyPixelCache(cache_info); if (status != MagickFalse) { /* Ensure the image matches the pixel cache morphology. */ image->type=UndefinedType; if (ValidatePixelCacheMorphology(image) == MagickFalse) { status=OpenPixelCache(image,IOMode,exception); cache_info=(CacheInfo *) image->cache; if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); } } UnlockSemaphoreInfo(image->semaphore); if (status == MagickFalse) return((Cache) NULL); return(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e P i x e l C a c h e T y p e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImagePixelCacheType() returns the pixel cache type: UndefinedCache, % DiskCache, MemoryCache, MapCache, or PingCache. % % The format of the GetImagePixelCacheType() method is: % % CacheType GetImagePixelCacheType(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport CacheType GetImagePixelCacheType(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); return(cache_info->type); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e A u t h e n t i c P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneAuthenticPixel() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. % % The format of the GetOneAuthenticPixel() method is: % % MagickBooleanType GetOneAuthenticPixel(const Image image,const ssize_t x, % const ssize_t y,Quantum *pixel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ static inline MagickBooleanType CopyPixel(const Image *image, const Quantum *source,Quantum *destination) { register ssize_t i; if (source == (const Quantum *) NULL) { destination[RedPixelChannel]=ClampToQuantum(image->background_color.red); destination[GreenPixelChannel]=ClampToQuantum( image->background_color.green); destination[BluePixelChannel]=ClampToQuantum( image->background_color.blue); destination[BlackPixelChannel]=ClampToQuantum( image->background_color.black); destination[AlphaPixelChannel]=ClampToQuantum( image->background_color.alpha); return(MagickFalse); } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); destination[channel]=source[i]; } return(MagickTrue); } MagickExport MagickBooleanType GetOneAuthenticPixel(Image *image, const ssize_t x,const ssize_t y,Quantum *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; register Quantum *magick_restrict q; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel)); if (cache_info->methods.get_one_authentic_pixel_from_handler != (GetOneAuthenticPixelFromHandler) NULL) return(cache_info->methods.get_one_authentic_pixel_from_handler(image,x,y,pixel,exception)); q=GetAuthenticPixelsCache(image,x,y,1UL,1UL,exception); return(CopyPixel(image,q,pixel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t O n e A u t h e n t i c P i x e l F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneAuthenticPixelFromCache() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. % % The format of the GetOneAuthenticPixelFromCache() method is: % % MagickBooleanType GetOneAuthenticPixelFromCache(const Image image, % const ssize_t x,const ssize_t y,Quantum *pixel, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType GetOneAuthenticPixelFromCache(Image *image, const ssize_t x,const ssize_t y,Quantum *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); register Quantum *magick_restrict q; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel)); q=GetAuthenticPixelCacheNexus(image,x,y,1UL,1UL,cache_info->nexus_info[id], exception); return(CopyPixel(image,q,pixel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e V i r t u a l P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualPixel() returns a single virtual pixel at the specified % (x,y) location. The image background color is returned if an error occurs. % If you plan to modify the pixel, use GetOneAuthenticPixel() instead. % % The format of the GetOneVirtualPixel() method is: % % MagickBooleanType GetOneVirtualPixel(const Image image,const ssize_t x, % const ssize_t y,Quantum *pixel,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetOneVirtualPixel(const Image *image, const ssize_t x,const ssize_t y,Quantum *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const Quantum *p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel)); if (cache_info->methods.get_one_virtual_pixel_from_handler != (GetOneVirtualPixelFromHandler) NULL) return(cache_info->methods.get_one_virtual_pixel_from_handler(image, GetPixelCacheVirtualMethod(image),x,y,pixel,exception)); assert(id < (int) cache_info->number_threads); p=GetVirtualPixelsFromNexus(image,GetPixelCacheVirtualMethod(image),x,y, 1UL,1UL,cache_info->nexus_info[id],exception); return(CopyPixel(image,p,pixel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t O n e V i r t u a l P i x e l F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualPixelFromCache() returns a single virtual pixel at the % specified (x,y) location. The image background color is returned if an % error occurs. % % The format of the GetOneVirtualPixelFromCache() method is: % % MagickBooleanType GetOneVirtualPixelFromCache(const Image image, % const VirtualPixelMethod method,const ssize_t x,const ssize_t y, % Quantum *pixel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType GetOneVirtualPixelFromCache(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, Quantum *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const Quantum *p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel)); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method,x,y,1UL,1UL, cache_info->nexus_info[id],exception); return(CopyPixel(image,p,pixel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e V i r t u a l P i x e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualPixelInfo() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. If % you plan to modify the pixel, use GetOneAuthenticPixel() instead. % % The format of the GetOneVirtualPixelInfo() method is: % % MagickBooleanType GetOneVirtualPixelInfo(const Image image, % const VirtualPixelMethod virtual_pixel_method,const ssize_t x, % const ssize_t y,PixelInfo *pixel,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y: these values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetOneVirtualPixelInfo(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, PixelInfo *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); register const Quantum *magick_restrict p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); GetPixelInfo(image,pixel); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method,x,y,1UL,1UL, cache_info->nexus_info[id],exception); if (p == (const Quantum *) NULL) return(MagickFalse); GetPixelInfoPixel(image,p,pixel); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e C o l o r s p a c e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheColorspace() returns the class type of the pixel cache. % % The format of the GetPixelCacheColorspace() method is: % % Colorspace GetPixelCacheColorspace(Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ MagickPrivate ColorspaceType GetPixelCacheColorspace(const Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); return(cache_info->colorspace); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e F i l e n a m e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheFilename() returns the filename associated with the pixel % cache. % % The format of the GetPixelCacheFilename() method is: % % const char *GetPixelCacheFilename(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const char *GetPixelCacheFilename(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); return(cache_info->cache_filename); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheMethods() initializes the CacheMethods structure. % % The format of the GetPixelCacheMethods() method is: % % void GetPixelCacheMethods(CacheMethods *cache_methods) % % A description of each parameter follows: % % o cache_methods: Specifies a pointer to a CacheMethods structure. % */ MagickPrivate void GetPixelCacheMethods(CacheMethods *cache_methods) { assert(cache_methods != (CacheMethods *) NULL); (void) memset(cache_methods,0,sizeof(*cache_methods)); cache_methods->get_virtual_pixel_handler=GetVirtualPixelCache; cache_methods->get_virtual_pixels_handler=GetVirtualPixelsCache; cache_methods->get_virtual_metacontent_from_handler= GetVirtualMetacontentFromCache; cache_methods->get_one_virtual_pixel_from_handler=GetOneVirtualPixelFromCache; cache_methods->get_authentic_pixels_handler=GetAuthenticPixelsCache; cache_methods->get_authentic_metacontent_from_handler= GetAuthenticMetacontentFromCache; cache_methods->get_authentic_pixels_from_handler=GetAuthenticPixelsFromCache; cache_methods->get_one_authentic_pixel_from_handler= GetOneAuthenticPixelFromCache; cache_methods->queue_authentic_pixels_handler=QueueAuthenticPixelsCache; cache_methods->sync_authentic_pixels_handler=SyncAuthenticPixelsCache; cache_methods->destroy_pixel_handler=DestroyImagePixelCache; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e N e x u s E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheNexusExtent() returns the extent of the pixels associated % corresponding with the last call to SetPixelCacheNexusPixels() or % GetPixelCacheNexusPixels(). % % The format of the GetPixelCacheNexusExtent() method is: % % MagickSizeType GetPixelCacheNexusExtent(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o nexus_info: the nexus info. % */ MagickPrivate MagickSizeType GetPixelCacheNexusExtent(const Cache cache, NexusInfo *magick_restrict nexus_info) { CacheInfo *magick_restrict cache_info; MagickSizeType extent; assert(cache != NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); extent=(MagickSizeType) nexus_info->region.width*nexus_info->region.height; if (extent == 0) return((MagickSizeType) cache_info->columns*cache_info->rows); return(extent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCachePixels() returns the pixels associated with the specified image. % % The format of the GetPixelCachePixels() method is: % % void *GetPixelCachePixels(Image *image,MagickSizeType *length, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o length: the pixel cache length. % % o exception: return any errors or warnings in this structure. % */ MagickExport void *GetPixelCachePixels(Image *image,MagickSizeType *length, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); assert(length != (MagickSizeType *) NULL); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); *length=cache_info->length; if ((cache_info->type != MemoryCache) && (cache_info->type != MapCache)) return((void *) NULL); return((void *) cache_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e S t o r a g e C l a s s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheStorageClass() returns the class type of the pixel cache. % % The format of the GetPixelCacheStorageClass() method is: % % ClassType GetPixelCacheStorageClass(Cache cache) % % A description of each parameter follows: % % o type: GetPixelCacheStorageClass returns DirectClass or PseudoClass. % % o cache: the pixel cache. % */ MagickPrivate ClassType GetPixelCacheStorageClass(const Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); return(cache_info->storage_class); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e T i l e S i z e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheTileSize() returns the pixel cache tile size. % % The format of the GetPixelCacheTileSize() method is: % % void GetPixelCacheTileSize(const Image *image,size_t *width, % size_t *height) % % A description of each parameter follows: % % o image: the image. % % o width: the optimized cache tile width in pixels. % % o height: the optimized cache tile height in pixels. % */ MagickPrivate void GetPixelCacheTileSize(const Image *image,size_t *width, size_t *height) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); *width=2048UL/(cache_info->number_channels*sizeof(Quantum)); if (GetImagePixelCacheType(image) == DiskCache) *width=8192UL/(cache_info->number_channels*sizeof(Quantum)); *height=(*width); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e V i r t u a l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheVirtualMethod() gets the "virtual pixels" method for the % pixel cache. A virtual pixel is any pixel access that is outside the % boundaries of the image cache. % % The format of the GetPixelCacheVirtualMethod() method is: % % VirtualPixelMethod GetPixelCacheVirtualMethod(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickPrivate VirtualPixelMethod GetPixelCacheVirtualMethod(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); return(cache_info->virtual_pixel_method); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l M e t a c o n t e n t F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualMetacontentFromCache() returns the meta-content corresponding with % the last call to QueueAuthenticPixelsCache() or GetVirtualPixelCache(). % % The format of the GetVirtualMetacontentFromCache() method is: % % void *GetVirtualMetacontentFromCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static const void *GetVirtualMetacontentFromCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const void *magick_restrict metacontent; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); metacontent=GetVirtualMetacontentFromNexus(cache_info, cache_info->nexus_info[id]); return(metacontent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l M e t a c o n t e n t F r o m N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualMetacontentFromNexus() returns the meta-content for the specified % cache nexus. % % The format of the GetVirtualMetacontentFromNexus() method is: % % const void *GetVirtualMetacontentFromNexus(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o cache: the pixel cache. % % o nexus_info: the cache nexus to return the meta-content. % */ MagickPrivate const void *GetVirtualMetacontentFromNexus(const Cache cache, NexusInfo *magick_restrict nexus_info) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->storage_class == UndefinedClass) return((void *) NULL); return(nexus_info->metacontent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualMetacontent() returns the virtual metacontent corresponding with % the last call to QueueAuthenticPixels() or GetVirtualPixels(). NULL is % returned if the meta-content are not available. % % The format of the GetVirtualMetacontent() method is: % % const void *GetVirtualMetacontent(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const void *GetVirtualMetacontent(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const void *magick_restrict metacontent; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); metacontent=cache_info->methods.get_virtual_metacontent_from_handler(image); if (metacontent != (void *) NULL) return(metacontent); assert(id < (int) cache_info->number_threads); metacontent=GetVirtualMetacontentFromNexus(cache_info, cache_info->nexus_info[id]); return(metacontent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l s F r o m N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelsFromNexus() gets virtual pixels from the in-memory or disk % pixel cache as defined by the geometry parameters. A pointer to the pixels % is returned if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetVirtualPixelsFromNexus() method is: % % Quantum *GetVirtualPixelsFromNexus(const Image *image, % const VirtualPixelMethod method,const ssize_t x,const ssize_t y, % const size_t columns,const size_t rows,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to acquire. % % o exception: return any errors or warnings in this structure. % */ static ssize_t DitherMatrix[64] = { 0, 48, 12, 60, 3, 51, 15, 63, 32, 16, 44, 28, 35, 19, 47, 31, 8, 56, 4, 52, 11, 59, 7, 55, 40, 24, 36, 20, 43, 27, 39, 23, 2, 50, 14, 62, 1, 49, 13, 61, 34, 18, 46, 30, 33, 17, 45, 29, 10, 58, 6, 54, 9, 57, 5, 53, 42, 26, 38, 22, 41, 25, 37, 21 }; static inline ssize_t DitherX(const ssize_t x,const size_t columns) { ssize_t index; index=x+DitherMatrix[x & 0x07]-32L; if (index < 0L) return(0L); if (index >= (ssize_t) columns) return((ssize_t) columns-1L); return(index); } static inline ssize_t DitherY(const ssize_t y,const size_t rows) { ssize_t index; index=y+DitherMatrix[y & 0x07]-32L; if (index < 0L) return(0L); if (index >= (ssize_t) rows) return((ssize_t) rows-1L); return(index); } static inline ssize_t EdgeX(const ssize_t x,const size_t columns) { if (x < 0L) return(0L); if (x >= (ssize_t) columns) return((ssize_t) (columns-1)); return(x); } static inline ssize_t EdgeY(const ssize_t y,const size_t rows) { if (y < 0L) return(0L); if (y >= (ssize_t) rows) return((ssize_t) (rows-1)); return(y); } static inline ssize_t RandomX(RandomInfo *random_info,const size_t columns) { return((ssize_t) (columns*GetPseudoRandomValue(random_info))); } static inline ssize_t RandomY(RandomInfo *random_info,const size_t rows) { return((ssize_t) (rows*GetPseudoRandomValue(random_info))); } static inline MagickModulo VirtualPixelModulo(const ssize_t offset, const size_t extent) { MagickModulo modulo; /* Compute the remainder of dividing offset by extent. It returns not only the quotient (tile the offset falls in) but also the positive remainer within that tile such that 0 <= remainder < extent. This method is essentially a ldiv() using a floored modulo division rather than the normal default truncated modulo division. */ modulo.quotient=offset/(ssize_t) extent; if (offset < 0L) modulo.quotient--; modulo.remainder=(ssize_t) (offset-(MagickOffsetType) modulo.quotient* (ssize_t) extent); return(modulo); } MagickPrivate const Quantum *GetVirtualPixelsFromNexus(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, const size_t columns,const size_t rows,NexusInfo *nexus_info, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickOffsetType offset; MagickSizeType length, number_pixels; NexusInfo **magick_restrict virtual_nexus; Quantum *magick_restrict pixels, virtual_pixel[MaxPixelChannels]; RectangleInfo region; register const Quantum *magick_restrict p; register const void *magick_restrict r; register Quantum *magick_restrict q; register ssize_t i, u; register unsigned char *magick_restrict s; ssize_t v; void *magick_restrict virtual_metacontent; /* Acquire pixels. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->type == UndefinedCache) return((const Quantum *) NULL); #if defined(MAGICKCORE_OPENCL_SUPPORT) CopyOpenCLBuffer(cache_info); #endif region.x=x; region.y=y; region.width=columns; region.height=rows; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,&region, ((image->channels & WriteMaskChannel) != 0) || ((image->channels & CompositeMaskChannel) != 0) ? MagickTrue : MagickFalse, nexus_info,exception); if (pixels == (Quantum *) NULL) return((const Quantum *) NULL); q=pixels; offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) (nexus_info->region.height-1L)*cache_info->columns+ nexus_info->region.width-1L; number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; if ((offset >= 0) && (((MagickSizeType) offset+length) < number_pixels)) if ((x >= 0) && ((ssize_t) (x+columns) <= (ssize_t) cache_info->columns) && (y >= 0) && ((ssize_t) (y+rows) <= (ssize_t) cache_info->rows)) { MagickBooleanType status; /* Pixel request is inside cache extents. */ if (nexus_info->authentic_pixel_cache != MagickFalse) return(q); status=ReadPixelCachePixels(cache_info,nexus_info,exception); if (status == MagickFalse) return((const Quantum *) NULL); if (cache_info->metacontent_extent != 0) { status=ReadPixelCacheMetacontent(cache_info,nexus_info,exception); if (status == MagickFalse) return((const Quantum *) NULL); } return(q); } /* Pixel request is outside cache extents. */ s=(unsigned char *) nexus_info->metacontent; virtual_nexus=AcquirePixelCacheNexus(1); (void) memset(virtual_pixel,0,cache_info->number_channels* sizeof(*virtual_pixel)); virtual_metacontent=(void *) NULL; switch (virtual_pixel_method) { case BackgroundVirtualPixelMethod: case BlackVirtualPixelMethod: case GrayVirtualPixelMethod: case TransparentVirtualPixelMethod: case MaskVirtualPixelMethod: case WhiteVirtualPixelMethod: case EdgeVirtualPixelMethod: case CheckerTileVirtualPixelMethod: case HorizontalTileVirtualPixelMethod: case VerticalTileVirtualPixelMethod: { if (cache_info->metacontent_extent != 0) { /* Acquire a metacontent buffer. */ virtual_metacontent=(void *) AcquireQuantumMemory(1, cache_info->metacontent_extent); if (virtual_metacontent == (void *) NULL) { virtual_nexus=DestroyPixelCacheNexus(virtual_nexus,1); (void) ThrowMagickException(exception,GetMagickModule(), CacheError,"UnableToGetCacheNexus","`%s'",image->filename); return((const Quantum *) NULL); } (void) memset(virtual_metacontent,0,cache_info->metacontent_extent); } switch (virtual_pixel_method) { case BlackVirtualPixelMethod: { for (i=0; i < (ssize_t) cache_info->number_channels; i++) SetPixelChannel(image,(PixelChannel) i,(Quantum) 0,virtual_pixel); SetPixelAlpha(image,OpaqueAlpha,virtual_pixel); break; } case GrayVirtualPixelMethod: { for (i=0; i < (ssize_t) cache_info->number_channels; i++) SetPixelChannel(image,(PixelChannel) i,QuantumRange/2, virtual_pixel); SetPixelAlpha(image,OpaqueAlpha,virtual_pixel); break; } case TransparentVirtualPixelMethod: { for (i=0; i < (ssize_t) cache_info->number_channels; i++) SetPixelChannel(image,(PixelChannel) i,(Quantum) 0,virtual_pixel); SetPixelAlpha(image,TransparentAlpha,virtual_pixel); break; } case MaskVirtualPixelMethod: case WhiteVirtualPixelMethod: { for (i=0; i < (ssize_t) cache_info->number_channels; i++) SetPixelChannel(image,(PixelChannel) i,QuantumRange,virtual_pixel); SetPixelAlpha(image,OpaqueAlpha,virtual_pixel); break; } default: { SetPixelRed(image,ClampToQuantum(image->background_color.red), virtual_pixel); SetPixelGreen(image,ClampToQuantum(image->background_color.green), virtual_pixel); SetPixelBlue(image,ClampToQuantum(image->background_color.blue), virtual_pixel); SetPixelBlack(image,ClampToQuantum(image->background_color.black), virtual_pixel); SetPixelAlpha(image,ClampToQuantum(image->background_color.alpha), virtual_pixel); break; } } break; } default: break; } for (v=0; v < (ssize_t) rows; v++) { ssize_t y_offset; y_offset=y+v; if ((virtual_pixel_method == EdgeVirtualPixelMethod) || (virtual_pixel_method == UndefinedVirtualPixelMethod)) y_offset=EdgeY(y_offset,cache_info->rows); for (u=0; u < (ssize_t) columns; u+=length) { ssize_t x_offset; x_offset=x+u; length=(MagickSizeType) MagickMin(cache_info->columns-x_offset,columns-u); if (((x_offset < 0) || (x_offset >= (ssize_t) cache_info->columns)) || ((y_offset < 0) || (y_offset >= (ssize_t) cache_info->rows)) || (length == 0)) { MagickModulo x_modulo, y_modulo; /* Transfer a single pixel. */ length=(MagickSizeType) 1; switch (virtual_pixel_method) { case EdgeVirtualPixelMethod: default: { p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, EdgeX(x_offset,cache_info->columns), EdgeY(y_offset,cache_info->rows),1UL,1UL,*virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case RandomVirtualPixelMethod: { if (cache_info->random_info == (RandomInfo *) NULL) cache_info->random_info=AcquireRandomInfo(); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, RandomX(cache_info->random_info,cache_info->columns), RandomY(cache_info->random_info,cache_info->rows),1UL,1UL, *virtual_nexus,exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case DitherVirtualPixelMethod: { p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, DitherX(x_offset,cache_info->columns), DitherY(y_offset,cache_info->rows),1UL,1UL,*virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case TileVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case MirrorVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); if ((x_modulo.quotient & 0x01) == 1L) x_modulo.remainder=(ssize_t) cache_info->columns- x_modulo.remainder-1L; y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); if ((y_modulo.quotient & 0x01) == 1L) y_modulo.remainder=(ssize_t) cache_info->rows- y_modulo.remainder-1L; p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case HorizontalTileEdgeVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,EdgeY(y_offset,cache_info->rows),1UL,1UL, *virtual_nexus,exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case VerticalTileEdgeVirtualPixelMethod: { y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, EdgeX(x_offset,cache_info->columns),y_modulo.remainder,1UL,1UL, *virtual_nexus,exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case BackgroundVirtualPixelMethod: case BlackVirtualPixelMethod: case GrayVirtualPixelMethod: case TransparentVirtualPixelMethod: case MaskVirtualPixelMethod: case WhiteVirtualPixelMethod: { p=virtual_pixel; r=virtual_metacontent; break; } case CheckerTileVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); if (((x_modulo.quotient ^ y_modulo.quotient) & 0x01) != 0L) { p=virtual_pixel; r=virtual_metacontent; break; } p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case HorizontalTileVirtualPixelMethod: { if ((y_offset < 0) || (y_offset >= (ssize_t) cache_info->rows)) { p=virtual_pixel; r=virtual_metacontent; break; } x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case VerticalTileVirtualPixelMethod: { if ((x_offset < 0) || (x_offset >= (ssize_t) cache_info->columns)) { p=virtual_pixel; r=virtual_metacontent; break; } x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } } if (p == (const Quantum *) NULL) break; (void) memcpy(q,p,(size_t) length*cache_info->number_channels* sizeof(*p)); q+=cache_info->number_channels; if ((s != (void *) NULL) && (r != (const void *) NULL)) { (void) memcpy(s,r,(size_t) cache_info->metacontent_extent); s+=cache_info->metacontent_extent; } continue; } /* Transfer a run of pixels. */ p=GetVirtualPixelsFromNexus(image,virtual_pixel_method,x_offset,y_offset, (size_t) length,1UL,*virtual_nexus,exception); if (p == (const Quantum *) NULL) break; r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); (void) memcpy(q,p,(size_t) length*cache_info->number_channels*sizeof(*p)); q+=length*cache_info->number_channels; if ((r != (void *) NULL) && (s != (const void *) NULL)) { (void) memcpy(s,r,(size_t) length); s+=length*cache_info->metacontent_extent; } } if (u < (ssize_t) columns) break; } /* Free resources. */ if (virtual_metacontent != (void *) NULL) virtual_metacontent=(void *) RelinquishMagickMemory(virtual_metacontent); virtual_nexus=DestroyPixelCacheNexus(virtual_nexus,1); if (v < (ssize_t) rows) return((const Quantum *) NULL); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelCache() get virtual pixels from the in-memory or disk pixel % cache as defined by the geometry parameters. A pointer to the pixels % is returned if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetVirtualPixelCache() method is: % % const Quantum *GetVirtualPixelCache(const Image *image, % const VirtualPixelMethod virtual_pixel_method,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static const Quantum *GetVirtualPixelCache(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, const size_t columns,const size_t rows,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const Quantum *magick_restrict p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method,x,y,columns,rows, cache_info->nexus_info[id],exception); return(p); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l P i x e l Q u e u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelQueue() returns the virtual pixels associated corresponding % with the last call to QueueAuthenticPixels() or GetVirtualPixels(). % % The format of the GetVirtualPixelQueue() method is: % % const Quantum *GetVirtualPixelQueue(const Image image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const Quantum *GetVirtualPixelQueue(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_virtual_pixels_handler != (GetVirtualPixelsHandler) NULL) return(cache_info->methods.get_virtual_pixels_handler(image)); assert(id < (int) cache_info->number_threads); return(GetVirtualPixelsNexus(cache_info,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixels() returns an immutable pixel region. If the % region is successfully accessed, a pointer to it is returned, otherwise % NULL is returned. The returned pointer may point to a temporary working % copy of the pixels or it may point to the original pixels in memory. % Performance is maximized if the selected region is part of one row, or one % or more full rows, since there is opportunity to access the pixels in-place % (without a copy) if the image is in memory, or in a memory-mapped file. The % returned pointer must *never* be deallocated by the user. % % Pixels accessed via the returned pointer represent a simple array of type % Quantum. If the image type is CMYK or the storage class is PseudoClass, % call GetAuthenticMetacontent() after invoking GetAuthenticPixels() to % access the meta-content (of type void) corresponding to the the % region. % % If you plan to modify the pixels, use GetAuthenticPixels() instead. % % Note, the GetVirtualPixels() and GetAuthenticPixels() methods are not thread- % safe. In a threaded environment, use GetCacheViewVirtualPixels() or % GetCacheViewAuthenticPixels() instead. % % The format of the GetVirtualPixels() method is: % % const Quantum *GetVirtualPixels(const Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport const Quantum *GetVirtualPixels(const Image *image, const ssize_t x,const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const Quantum *magick_restrict p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_virtual_pixel_handler != (GetVirtualPixelHandler) NULL) return(cache_info->methods.get_virtual_pixel_handler(image, GetPixelCacheVirtualMethod(image),x,y,columns,rows,exception)); assert(id < (int) cache_info->number_threads); p=GetVirtualPixelsFromNexus(image,GetPixelCacheVirtualMethod(image),x,y, columns,rows,cache_info->nexus_info[id],exception); return(p); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l s F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelsCache() returns the pixels associated corresponding with the % last call to QueueAuthenticPixelsCache() or GetVirtualPixelCache(). % % The format of the GetVirtualPixelsCache() method is: % % Quantum *GetVirtualPixelsCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static const Quantum *GetVirtualPixelsCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(GetVirtualPixelsNexus(image->cache,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l s N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelsNexus() returns the pixels associated with the specified % cache nexus. % % The format of the GetVirtualPixelsNexus() method is: % % const Quantum *GetVirtualPixelsNexus(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o cache: the pixel cache. % % o nexus_info: the cache nexus to return the colormap pixels. % */ MagickPrivate const Quantum *GetVirtualPixelsNexus(const Cache cache, NexusInfo *magick_restrict nexus_info) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->storage_class == UndefinedClass) return((Quantum *) NULL); return((const Quantum *) nexus_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + M a s k P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MaskPixelCacheNexus() masks the cache nexus as defined by the image mask. % The method returns MagickTrue if the pixel region is masked, otherwise % MagickFalse. % % The format of the MaskPixelCacheNexus() method is: % % MagickBooleanType MaskPixelCacheNexus(Image *image, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o nexus_info: the cache nexus to clip. % % o exception: return any errors or warnings in this structure. % */ static inline Quantum ApplyPixelCompositeMask(const Quantum p, const MagickRealType alpha,const Quantum q,const MagickRealType beta) { double mask_alpha; if (fabs(alpha-OpaqueAlpha) < MagickEpsilon) return(p); mask_alpha=1.0-QuantumScale*QuantumScale*alpha*beta; mask_alpha=PerceptibleReciprocal(mask_alpha); return(ClampToQuantum(mask_alpha*MagickOver_((double) p,alpha,(double) q,beta))); } static MagickBooleanType MaskPixelCacheNexus(Image *image,NexusInfo *nexus_info, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickSizeType number_pixels; NexusInfo **magick_restrict image_nexus; register Quantum *magick_restrict p, *magick_restrict q; register ssize_t n; /* Apply clip mask. */ if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->channels & CompositeMaskChannel) == 0) return(MagickTrue); cache_info=(CacheInfo *) image->cache; if (cache_info == (Cache) NULL) return(MagickFalse); image_nexus=AcquirePixelCacheNexus(1); p=GetAuthenticPixelCacheNexus(image,nexus_info->region.x,nexus_info->region.y, nexus_info->region.width,nexus_info->region.height,image_nexus[0], exception); q=nexus_info->pixels; number_pixels=(MagickSizeType) nexus_info->region.width* nexus_info->region.height; for (n=0; n < (ssize_t) number_pixels; n++) { double mask_alpha; register ssize_t i; if (p == (Quantum *) NULL) break; mask_alpha=(double) GetPixelCompositeMask(image,p); for (i=0; i < (ssize_t) image->number_channels; i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ApplyPixelCompositeMask(p[i],mask_alpha,q[i], (MagickRealType) GetPixelAlpha(image,q)); } p+=GetPixelChannels(image); q+=GetPixelChannels(image); } image_nexus=DestroyPixelCacheNexus(image_nexus,1); if (n < (ssize_t) number_pixels) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + O p e n P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OpenPixelCache() allocates the pixel cache. This includes defining the cache % dimensions, allocating space for the image pixels and optionally the % metacontent, and memory mapping the cache if it is disk based. The cache % nexus array is initialized as well. % % The format of the OpenPixelCache() method is: % % MagickBooleanType OpenPixelCache(Image *image,const MapMode mode, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o mode: ReadMode, WriteMode, or IOMode. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType OpenPixelCacheOnDisk(CacheInfo *cache_info, const MapMode mode) { int file; /* Open pixel cache on disk. */ if ((cache_info->file != -1) && (cache_info->disk_mode == mode)) return(MagickTrue); /* cache already open and in the proper mode */ if (*cache_info->cache_filename == '\0') file=AcquireUniqueFileResource(cache_info->cache_filename); else switch (mode) { case ReadMode: { file=open_utf8(cache_info->cache_filename,O_RDONLY | O_BINARY,0); break; } case WriteMode: { file=open_utf8(cache_info->cache_filename,O_WRONLY | O_CREAT | O_BINARY | O_EXCL,S_MODE); if (file == -1) file=open_utf8(cache_info->cache_filename,O_WRONLY | O_BINARY,S_MODE); break; } case IOMode: default: { file=open_utf8(cache_info->cache_filename,O_RDWR | O_CREAT | O_BINARY | O_EXCL,S_MODE); if (file == -1) file=open_utf8(cache_info->cache_filename,O_RDWR | O_BINARY,S_MODE); break; } } if (file == -1) return(MagickFalse); (void) AcquireMagickResource(FileResource,1); if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); cache_info->file=file; cache_info->disk_mode=mode; return(MagickTrue); } static inline MagickOffsetType WritePixelCacheRegion( const CacheInfo *magick_restrict cache_info,const MagickOffsetType offset, const MagickSizeType length,const unsigned char *magick_restrict buffer) { register MagickOffsetType i; ssize_t count; #if !defined(MAGICKCORE_HAVE_PWRITE) if (lseek(cache_info->file,offset,SEEK_SET) < 0) return((MagickOffsetType) -1); #endif count=0; for (i=0; i < (MagickOffsetType) length; i+=count) { #if !defined(MAGICKCORE_HAVE_PWRITE) count=write(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX)); #else count=pwrite(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX),(off_t) (offset+i)); #endif if (count <= 0) { count=0; if (errno != EINTR) break; } } return(i); } static MagickBooleanType SetPixelCacheExtent(Image *image,MagickSizeType length) { CacheInfo *magick_restrict cache_info; MagickOffsetType count, extent, offset; cache_info=(CacheInfo *) image->cache; if (image->debug != MagickFalse) { char format[MagickPathExtent], message[MagickPathExtent]; (void) FormatMagickSize(length,MagickFalse,"B",MagickPathExtent,format); (void) FormatLocaleString(message,MagickPathExtent, "extend %s (%s[%d], disk, %s)",cache_info->filename, cache_info->cache_filename,cache_info->file,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } if (length != (MagickSizeType) ((MagickOffsetType) length)) return(MagickFalse); offset=(MagickOffsetType) lseek(cache_info->file,0,SEEK_END); if (offset < 0) return(MagickFalse); if ((MagickSizeType) offset >= length) count=(MagickOffsetType) 1; else { extent=(MagickOffsetType) length-1; count=WritePixelCacheRegion(cache_info,extent,1,(const unsigned char *) ""); if (count != 1) return(MagickFalse); #if defined(MAGICKCORE_HAVE_POSIX_FALLOCATE) if (cache_info->synchronize != MagickFalse) (void) posix_fallocate(cache_info->file,offset+1,extent-offset); #endif } offset=(MagickOffsetType) lseek(cache_info->file,0,SEEK_SET); if (offset < 0) return(MagickFalse); return(MagickTrue); } static MagickBooleanType OpenPixelCache(Image *image,const MapMode mode, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info, source_info; char format[MagickPathExtent], message[MagickPathExtent]; const char *hosts, *type; MagickBooleanType status; MagickSizeType length, number_pixels; size_t columns, packet_size; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (cache_anonymous_memory < 0) { char *value; /* Does the security policy require anonymous mapping for pixel cache? */ cache_anonymous_memory=0; value=GetPolicyValue("pixel-cache-memory"); if (value == (char *) NULL) value=GetPolicyValue("cache:memory-map"); if (LocaleCompare(value,"anonymous") == 0) { #if defined(MAGICKCORE_HAVE_MMAP) && defined(MAP_ANONYMOUS) cache_anonymous_memory=1; #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn", "'%s' (policy requires anonymous memory mapping)",image->filename); #endif } value=DestroyString(value); } if ((image->columns == 0) || (image->rows == 0)) ThrowBinaryException(CacheError,"NoPixelsDefinedInCache",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if ((AcquireMagickResource(WidthResource,image->columns) == MagickFalse) || (AcquireMagickResource(HeightResource,image->rows) == MagickFalse)) ThrowBinaryException(ImageError,"WidthOrHeightExceedsLimit", image->filename); length=GetImageListLength(image); if (AcquireMagickResource(ListLengthResource,length) == MagickFalse) ThrowBinaryException(ResourceLimitError,"ListLengthExceedsLimit", image->filename); source_info=(*cache_info); source_info.file=(-1); (void) FormatLocaleString(cache_info->filename,MagickPathExtent,"%s[%.20g]", image->filename,(double) image->scene); cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->alpha_trait=image->alpha_trait; cache_info->channels=image->channels; cache_info->rows=image->rows; cache_info->columns=image->columns; InitializePixelChannelMap(image); cache_info->number_channels=GetPixelChannels(image); (void) memcpy(cache_info->channel_map,image->channel_map,MaxPixelChannels* sizeof(*image->channel_map)); cache_info->metacontent_extent=image->metacontent_extent; cache_info->mode=mode; number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; packet_size=cache_info->number_channels*sizeof(Quantum); if (image->metacontent_extent != 0) packet_size+=cache_info->metacontent_extent; length=number_pixels*packet_size; columns=(size_t) (length/cache_info->rows/packet_size); if ((cache_info->columns != columns) || ((ssize_t) cache_info->columns < 0) || ((ssize_t) cache_info->rows < 0)) ThrowBinaryException(ResourceLimitError,"PixelCacheAllocationFailed", image->filename); cache_info->length=length; if (image->ping != MagickFalse) { cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->type=PingCache; return(MagickTrue); } status=AcquireMagickResource(AreaResource,(MagickSizeType) cache_info->columns*cache_info->rows); if (cache_info->mode == PersistMode) status=MagickFalse; length=number_pixels*(cache_info->number_channels*sizeof(Quantum)+ cache_info->metacontent_extent); if ((status != MagickFalse) && (length == (MagickSizeType) ((size_t) length)) && ((cache_info->type == UndefinedCache) || (cache_info->type == MemoryCache))) { status=AcquireMagickResource(MemoryResource,cache_info->length); if (status != MagickFalse) { status=MagickTrue; if (cache_anonymous_memory <= 0) { cache_info->mapped=MagickFalse; cache_info->pixels=(Quantum *) MagickAssumeAligned( AcquireAlignedMemory(1,(size_t) cache_info->length)); } else { cache_info->mapped=MagickTrue; cache_info->pixels=(Quantum *) MapBlob(-1,IOMode,0,(size_t) cache_info->length); } if (cache_info->pixels == (Quantum *) NULL) cache_info->pixels=source_info.pixels; else { /* Create memory pixel cache. */ cache_info->type=MemoryCache; cache_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) cache_info->metacontent=(void *) (cache_info->pixels+ number_pixels*cache_info->number_channels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s %s, %.20gx%.20gx%.20g %s)", cache_info->filename,cache_info->mapped != MagickFalse ? "Anonymous" : "Heap",type,(double) cache_info->columns, (double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } return(status == 0 ? MagickFalse : MagickTrue); } } } status=AcquireMagickResource(DiskResource,cache_info->length); hosts=(const char *) GetImageRegistry(StringRegistryType,"cache:hosts", exception); if ((status == MagickFalse) && (hosts != (const char *) NULL)) { DistributeCacheInfo *server_info; /* Distribute the pixel cache to a remote server. */ server_info=AcquireDistributeCacheInfo(exception); if (server_info != (DistributeCacheInfo *) NULL) { status=OpenDistributePixelCache(server_info,image); if (status == MagickFalse) { ThrowFileException(exception,CacheError,"UnableToOpenPixelCache", GetDistributeCacheHostname(server_info)); server_info=DestroyDistributeCacheInfo(server_info); } else { /* Create a distributed pixel cache. */ status=MagickTrue; cache_info->type=DistributedCache; cache_info->server_info=server_info; (void) FormatLocaleString(cache_info->cache_filename, MagickPathExtent,"%s:%d",GetDistributeCacheHostname( (DistributeCacheInfo *) cache_info->server_info), GetDistributeCachePort((DistributeCacheInfo *) cache_info->server_info)); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)", cache_info->filename,cache_info->cache_filename, GetDistributeCacheFile((DistributeCacheInfo *) cache_info->server_info),type,(double) cache_info->columns, (double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } return(status == 0 ? MagickFalse : MagickTrue); } } cache_info->type=UndefinedCache; (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "CacheResourcesExhausted","`%s'",image->filename); return(MagickFalse); } /* Create pixel cache on disk. */ if (status == MagickFalse) { cache_info->type=UndefinedCache; (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "CacheResourcesExhausted","`%s'",image->filename); return(MagickFalse); } if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode) && (cache_info->mode != PersistMode)) { (void) ClosePixelCacheOnDisk(cache_info); *cache_info->cache_filename='\0'; } if (OpenPixelCacheOnDisk(cache_info,mode) == MagickFalse) { ThrowFileException(exception,CacheError,"UnableToOpenPixelCache", image->filename); return(MagickFalse); } status=SetPixelCacheExtent(image,(MagickSizeType) cache_info->offset+ cache_info->length); if (status == MagickFalse) { ThrowFileException(exception,CacheError,"UnableToExtendCache", image->filename); return(MagickFalse); } length=number_pixels*(cache_info->number_channels*sizeof(Quantum)+ cache_info->metacontent_extent); if (length != (MagickSizeType) ((size_t) length)) cache_info->type=DiskCache; else { status=AcquireMagickResource(MapResource,cache_info->length); if (status == MagickFalse) cache_info->type=DiskCache; else if ((cache_info->type != MapCache) && (cache_info->type != MemoryCache)) { cache_info->type=DiskCache; RelinquishMagickResource(MapResource,cache_info->length); } else { cache_info->pixels=(Quantum *) MapBlob(cache_info->file,mode, cache_info->offset,(size_t) cache_info->length); if (cache_info->pixels == (Quantum *) NULL) { cache_info->type=DiskCache; cache_info->pixels=source_info.pixels; RelinquishMagickResource(MapResource,cache_info->length); } else { /* Create file-backed memory-mapped pixel cache. */ (void) ClosePixelCacheOnDisk(cache_info); cache_info->type=MapCache; cache_info->mapped=MagickTrue; cache_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) cache_info->metacontent=(void *) (cache_info->pixels+ number_pixels*cache_info->number_channels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)", cache_info->filename,cache_info->cache_filename, cache_info->file,type,(double) cache_info->columns, (double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } return(status == 0 ? MagickFalse : MagickTrue); } } } status=MagickTrue; if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info,exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)",cache_info->filename, cache_info->cache_filename,cache_info->file,type,(double) cache_info->columns,(double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } return(status == 0 ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P e r s i s t P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PersistPixelCache() attaches to or initializes a persistent pixel cache. A % persistent pixel cache is one that resides on disk and is not destroyed % when the program exits. % % The format of the PersistPixelCache() method is: % % MagickBooleanType PersistPixelCache(Image *image,const char *filename, % const MagickBooleanType attach,MagickOffsetType *offset, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o filename: the persistent pixel cache filename. % % o attach: A value other than zero initializes the persistent pixel cache. % % o initialize: A value other than zero initializes the persistent pixel % cache. % % o offset: the offset in the persistent cache to store pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType PersistPixelCache(Image *image, const char *filename,const MagickBooleanType attach,MagickOffsetType *offset, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info, *magick_restrict clone_info; MagickBooleanType status; ssize_t page_size; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (void *) NULL); assert(filename != (const char *) NULL); assert(offset != (MagickOffsetType *) NULL); page_size=GetMagickPageSize(); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) CopyOpenCLBuffer(cache_info); #endif if (attach != MagickFalse) { /* Attach existing persistent pixel cache. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "attach persistent cache"); (void) CopyMagickString(cache_info->cache_filename,filename, MagickPathExtent); cache_info->type=DiskCache; cache_info->offset=(*offset); if (OpenPixelCache(image,ReadMode,exception) == MagickFalse) return(MagickFalse); *offset+=cache_info->length+page_size-(cache_info->length % page_size); return(SyncImagePixelCache(image,exception)); } /* Clone persistent pixel cache. */ status=AcquireMagickResource(DiskResource,cache_info->length); if (status == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "CacheResourcesExhausted","`%s'",image->filename); return(MagickFalse); } clone_info=(CacheInfo *) ClonePixelCache(cache_info); clone_info->type=DiskCache; (void) CopyMagickString(clone_info->cache_filename,filename,MagickPathExtent); clone_info->file=(-1); clone_info->storage_class=cache_info->storage_class; clone_info->colorspace=cache_info->colorspace; clone_info->alpha_trait=cache_info->alpha_trait; clone_info->channels=cache_info->channels; clone_info->columns=cache_info->columns; clone_info->rows=cache_info->rows; clone_info->number_channels=cache_info->number_channels; clone_info->metacontent_extent=cache_info->metacontent_extent; clone_info->mode=PersistMode; clone_info->length=cache_info->length; (void) memcpy(clone_info->channel_map,cache_info->channel_map, MaxPixelChannels*sizeof(*cache_info->channel_map)); clone_info->offset=(*offset); status=ClonePixelCacheRepository(clone_info,cache_info,exception); *offset+=cache_info->length+page_size-(cache_info->length % page_size); clone_info=(CacheInfo *) DestroyPixelCache(clone_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Q u e u e A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixelCacheNexus() allocates an region to store image pixels as % defined by the region rectangle and returns a pointer to the region. This % region is subsequently transferred from the pixel cache with % SyncAuthenticPixelsCache(). A pointer to the pixels is returned if the % pixels are transferred, otherwise a NULL is returned. % % The format of the QueueAuthenticPixelCacheNexus() method is: % % Quantum *QueueAuthenticPixelCacheNexus(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % const MagickBooleanType clone,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to set. % % o clone: clone the pixel cache. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate Quantum *QueueAuthenticPixelCacheNexus(Image *image, const ssize_t x,const ssize_t y,const size_t columns,const size_t rows, const MagickBooleanType clone,NexusInfo *nexus_info,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickOffsetType offset; MagickSizeType number_pixels; Quantum *magick_restrict pixels; RectangleInfo region; /* Validate pixel cache geometry. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) GetImagePixelCache(image,clone,exception); if (cache_info == (Cache) NULL) return((Quantum *) NULL); assert(cache_info->signature == MagickCoreSignature); if ((cache_info->columns == 0) || (cache_info->rows == 0) || (x < 0) || (y < 0) || (x >= (ssize_t) cache_info->columns) || (y >= (ssize_t) cache_info->rows)) { (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "PixelsAreNotAuthentic","`%s'",image->filename); return((Quantum *) NULL); } offset=(MagickOffsetType) y*cache_info->columns+x; if (offset < 0) return((Quantum *) NULL); number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; offset+=(MagickOffsetType) (rows-1)*cache_info->columns+columns-1; if ((MagickSizeType) offset >= number_pixels) return((Quantum *) NULL); /* Return pixel cache. */ region.x=x; region.y=y; region.width=columns; region.height=rows; pixels=SetPixelCacheNexusPixels(cache_info,WriteMode,&region, ((image->channels & WriteMaskChannel) != 0) || ((image->channels & CompositeMaskChannel) != 0) ? MagickTrue : MagickFalse, nexus_info,exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Q u e u e A u t h e n t i c P i x e l s C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixelsCache() allocates an region to store image pixels as % defined by the region rectangle and returns a pointer to the region. This % region is subsequently transferred from the pixel cache with % SyncAuthenticPixelsCache(). A pointer to the pixels is returned if the % pixels are transferred, otherwise a NULL is returned. % % The format of the QueueAuthenticPixelsCache() method is: % % Quantum *QueueAuthenticPixelsCache(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static Quantum *QueueAuthenticPixelsCache(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); Quantum *magick_restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); pixels=QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickFalse, cache_info->nexus_info[id],exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Q u e u e A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixels() queues a mutable pixel region. If the region is % successfully initialized a pointer to a Quantum array representing the % region is returned, otherwise NULL is returned. The returned pointer may % point to a temporary working buffer for the pixels or it may point to the % final location of the pixels in memory. % % Write-only access means that any existing pixel values corresponding to % the region are ignored. This is useful if the initial image is being % created from scratch, or if the existing pixel values are to be % completely replaced without need to refer to their pre-existing values. % The application is free to read and write the pixel buffer returned by % QueueAuthenticPixels() any way it pleases. QueueAuthenticPixels() does not % initialize the pixel array values. Initializing pixel array values is the % application's responsibility. % % Performance is maximized if the selected region is part of one row, or % one or more full rows, since then there is opportunity to access the % pixels in-place (without a copy) if the image is in memory, or in a % memory-mapped file. The returned pointer must *never* be deallocated % by the user. % % Pixels accessed via the returned pointer represent a simple array of type % Quantum. If the image type is CMYK or the storage class is PseudoClass, % call GetAuthenticMetacontent() after invoking GetAuthenticPixels() to % obtain the meta-content (of type void) corresponding to the region. % Once the Quantum (and/or Quantum) array has been updated, the % changes must be saved back to the underlying image using % SyncAuthenticPixels() or they may be lost. % % The format of the QueueAuthenticPixels() method is: % % Quantum *QueueAuthenticPixels(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Quantum *QueueAuthenticPixels(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); Quantum *magick_restrict pixels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.queue_authentic_pixels_handler != (QueueAuthenticPixelsHandler) NULL) { pixels=cache_info->methods.queue_authentic_pixels_handler(image,x,y, columns,rows,exception); return(pixels); } assert(id < (int) cache_info->number_threads); pixels=QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickFalse, cache_info->nexus_info[id],exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e a d P i x e l C a c h e M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPixelCacheMetacontent() reads metacontent from the specified region of % the pixel cache. % % The format of the ReadPixelCacheMetacontent() method is: % % MagickBooleanType ReadPixelCacheMetacontent(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to read the metacontent. % % o exception: return any errors or warnings in this structure. % */ static inline MagickOffsetType ReadPixelCacheRegion( const CacheInfo *magick_restrict cache_info,const MagickOffsetType offset, const MagickSizeType length,unsigned char *magick_restrict buffer) { register MagickOffsetType i; ssize_t count; #if !defined(MAGICKCORE_HAVE_PREAD) if (lseek(cache_info->file,offset,SEEK_SET) < 0) return((MagickOffsetType) -1); #endif count=0; for (i=0; i < (MagickOffsetType) length; i+=count) { #if !defined(MAGICKCORE_HAVE_PREAD) count=read(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX)); #else count=pread(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX),(off_t) (offset+i)); #endif if (count <= 0) { count=0; if (errno != EINTR) break; } } return(i); } static MagickBooleanType ReadPixelCacheMetacontent( CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info, ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register ssize_t y; register unsigned char *magick_restrict q; size_t rows; if (cache_info->metacontent_extent == 0) return(MagickFalse); if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) nexus_info->region.width* cache_info->metacontent_extent; extent=length*nexus_info->region.height; rows=nexus_info->region.height; y=0; q=(unsigned char *) nexus_info->metacontent; switch (cache_info->type) { case MemoryCache: case MapCache: { register unsigned char *magick_restrict p; /* Read meta-content from memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } p=(unsigned char *) cache_info->metacontent+offset* cache_info->metacontent_extent; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=cache_info->metacontent_extent*cache_info->columns; q+=cache_info->metacontent_extent*nexus_info->region.width; } break; } case DiskCache: { /* Read meta content from disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } extent=(MagickSizeType) cache_info->columns*cache_info->rows; for (y=0; y < (ssize_t) rows; y++) { count=ReadPixelCacheRegion(cache_info,cache_info->offset+extent* cache_info->number_channels*sizeof(Quantum)+offset* cache_info->metacontent_extent,length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; offset+=cache_info->columns; q+=cache_info->metacontent_extent*nexus_info->region.width; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Read metacontent from distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadDistributePixelCacheMetacontent((DistributeCacheInfo *) cache_info->server_info,&region,length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; q+=cache_info->metacontent_extent*nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToReadPixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e a d P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPixelCachePixels() reads pixels from the specified region of the pixel % cache. % % The format of the ReadPixelCachePixels() method is: % % MagickBooleanType ReadPixelCachePixels(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to read the pixels. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ReadPixelCachePixels( CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info, ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register Quantum *magick_restrict q; register ssize_t y; size_t number_channels, rows; if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns; if ((ssize_t) (offset/cache_info->columns) != nexus_info->region.y) return(MagickFalse); offset+=nexus_info->region.x; number_channels=cache_info->number_channels; length=(MagickSizeType) number_channels*nexus_info->region.width* sizeof(Quantum); if ((length/number_channels/sizeof(Quantum)) != nexus_info->region.width) return(MagickFalse); rows=nexus_info->region.height; extent=length*rows; if ((extent == 0) || ((extent/length) != rows)) return(MagickFalse); y=0; q=nexus_info->pixels; switch (cache_info->type) { case MemoryCache: case MapCache: { register Quantum *magick_restrict p; /* Read pixels from memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } p=cache_info->pixels+offset*cache_info->number_channels; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=cache_info->number_channels*cache_info->columns; q+=cache_info->number_channels*nexus_info->region.width; } break; } case DiskCache: { /* Read pixels from disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadPixelCacheRegion(cache_info,cache_info->offset+offset* cache_info->number_channels*sizeof(*q),length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; offset+=cache_info->columns; q+=cache_info->number_channels*nexus_info->region.width; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Read pixels from distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadDistributePixelCachePixels((DistributeCacheInfo *) cache_info->server_info,&region,length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; q+=cache_info->number_channels*nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToReadPixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e f e r e n c e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReferencePixelCache() increments the reference count associated with the % pixel cache returning a pointer to the cache. % % The format of the ReferencePixelCache method is: % % Cache ReferencePixelCache(Cache cache_info) % % A description of each parameter follows: % % o cache_info: the pixel cache. % */ MagickPrivate Cache ReferencePixelCache(Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache *) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); LockSemaphoreInfo(cache_info->semaphore); cache_info->reference_count++; UnlockSemaphoreInfo(cache_info->semaphore); return(cache_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e s e t P i x e l C a c h e C h a n n e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetPixelCacheChannels() resets the pixel cache channels. % % The format of the ResetPixelCacheChannels method is: % % void ResetPixelCacheChannels(Image *) % % A description of each parameter follows: % % o image: the image. % */ MagickPrivate void ResetPixelCacheChannels(Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); cache_info->number_channels=GetPixelChannels(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e s e t C a c h e A n o n y m o u s M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetCacheAnonymousMemory() resets the anonymous_memory value. % % The format of the ResetCacheAnonymousMemory method is: % % void ResetCacheAnonymousMemory(void) % */ MagickPrivate void ResetCacheAnonymousMemory(void) { cache_anonymous_memory=0; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e s e t P i x e l C a c h e E p o c h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetPixelCacheEpoch() resets the pixel cache epoch. % % The format of the ResetPixelCacheEpoch method is: % % void ResetPixelCacheEpoch(void) % */ MagickPrivate void ResetPixelCacheEpoch(void) { cache_epoch=0; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S e t P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheMethods() sets the image pixel methods to the specified ones. % % The format of the SetPixelCacheMethods() method is: % % SetPixelCacheMethods(Cache *,CacheMethods *cache_methods) % % A description of each parameter follows: % % o cache: the pixel cache. % % o cache_methods: Specifies a pointer to a CacheMethods structure. % */ MagickPrivate void SetPixelCacheMethods(Cache cache,CacheMethods *cache_methods) { CacheInfo *magick_restrict cache_info; GetOneAuthenticPixelFromHandler get_one_authentic_pixel_from_handler; GetOneVirtualPixelFromHandler get_one_virtual_pixel_from_handler; /* Set cache pixel methods. */ assert(cache != (Cache) NULL); assert(cache_methods != (CacheMethods *) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); if (cache_methods->get_virtual_pixel_handler != (GetVirtualPixelHandler) NULL) cache_info->methods.get_virtual_pixel_handler= cache_methods->get_virtual_pixel_handler; if (cache_methods->destroy_pixel_handler != (DestroyPixelHandler) NULL) cache_info->methods.destroy_pixel_handler= cache_methods->destroy_pixel_handler; if (cache_methods->get_virtual_metacontent_from_handler != (GetVirtualMetacontentFromHandler) NULL) cache_info->methods.get_virtual_metacontent_from_handler= cache_methods->get_virtual_metacontent_from_handler; if (cache_methods->get_authentic_pixels_handler != (GetAuthenticPixelsHandler) NULL) cache_info->methods.get_authentic_pixels_handler= cache_methods->get_authentic_pixels_handler; if (cache_methods->queue_authentic_pixels_handler != (QueueAuthenticPixelsHandler) NULL) cache_info->methods.queue_authentic_pixels_handler= cache_methods->queue_authentic_pixels_handler; if (cache_methods->sync_authentic_pixels_handler != (SyncAuthenticPixelsHandler) NULL) cache_info->methods.sync_authentic_pixels_handler= cache_methods->sync_authentic_pixels_handler; if (cache_methods->get_authentic_pixels_from_handler != (GetAuthenticPixelsFromHandler) NULL) cache_info->methods.get_authentic_pixels_from_handler= cache_methods->get_authentic_pixels_from_handler; if (cache_methods->get_authentic_metacontent_from_handler != (GetAuthenticMetacontentFromHandler) NULL) cache_info->methods.get_authentic_metacontent_from_handler= cache_methods->get_authentic_metacontent_from_handler; get_one_virtual_pixel_from_handler= cache_info->methods.get_one_virtual_pixel_from_handler; if (get_one_virtual_pixel_from_handler != (GetOneVirtualPixelFromHandler) NULL) cache_info->methods.get_one_virtual_pixel_from_handler= cache_methods->get_one_virtual_pixel_from_handler; get_one_authentic_pixel_from_handler= cache_methods->get_one_authentic_pixel_from_handler; if (get_one_authentic_pixel_from_handler != (GetOneAuthenticPixelFromHandler) NULL) cache_info->methods.get_one_authentic_pixel_from_handler= cache_methods->get_one_authentic_pixel_from_handler; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S e t P i x e l C a c h e N e x u s P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheNexusPixels() defines the region of the cache for the % specified cache nexus. % % The format of the SetPixelCacheNexusPixels() method is: % % Quantum SetPixelCacheNexusPixels(const CacheInfo *cache_info, % const MapMode mode,const RectangleInfo *region, % const MagickBooleanType buffered,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o mode: ReadMode, WriteMode, or IOMode. % % o region: A pointer to the RectangleInfo structure that defines the % region of this particular cache nexus. % % o buffered: if true, nexus pixels are buffered. % % o nexus_info: the cache nexus to set. % % o exception: return any errors or warnings in this structure. % */ static inline MagickBooleanType AcquireCacheNexusPixels( const CacheInfo *magick_restrict cache_info,NexusInfo *nexus_info, ExceptionInfo *exception) { if (nexus_info->length != (MagickSizeType) ((size_t) nexus_info->length)) return(MagickFalse); if (cache_anonymous_memory <= 0) { nexus_info->mapped=MagickFalse; nexus_info->cache=(Quantum *) MagickAssumeAligned(AcquireAlignedMemory(1, (size_t) nexus_info->length)); if (nexus_info->cache != (Quantum *) NULL) (void) memset(nexus_info->cache,0,(size_t) nexus_info->length); } else { nexus_info->mapped=MagickTrue; nexus_info->cache=(Quantum *) MapBlob(-1,IOMode,0,(size_t) nexus_info->length); } if (nexus_info->cache == (Quantum *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", cache_info->filename); return(MagickFalse); } return(MagickTrue); } static inline MagickBooleanType IsPixelCacheAuthentic( const CacheInfo *magick_restrict cache_info, const NexusInfo *magick_restrict nexus_info) { MagickBooleanType status; MagickOffsetType offset; /* Does nexus pixels point directly to in-core cache pixels or is it buffered? */ if (cache_info->type == PingCache) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; status=nexus_info->pixels == (cache_info->pixels+offset* cache_info->number_channels) ? MagickTrue : MagickFalse; return(status); } static inline void PrefetchPixelCacheNexusPixels(const NexusInfo *nexus_info, const MapMode mode) { if (mode == ReadMode) { MagickCachePrefetch((unsigned char *) nexus_info->pixels,0,1); return; } MagickCachePrefetch((unsigned char *) nexus_info->pixels,1,1); } static Quantum *SetPixelCacheNexusPixels(const CacheInfo *cache_info, const MapMode mode,const RectangleInfo *region, const MagickBooleanType buffered,NexusInfo *nexus_info, ExceptionInfo *exception) { MagickBooleanType status; MagickSizeType length, number_pixels; assert(cache_info != (const CacheInfo *) NULL); assert(cache_info->signature == MagickCoreSignature); if (cache_info->type == UndefinedCache) return((Quantum *) NULL); if ((region->width == 0) || (region->height == 0)) return((Quantum *) NULL); nexus_info->region=(*region); number_pixels=(MagickSizeType) nexus_info->region.width* nexus_info->region.height; if (number_pixels == 0) return((Quantum *) NULL); if (((cache_info->type == MemoryCache) || (cache_info->type == MapCache)) && (buffered == MagickFalse)) { ssize_t x, y; x=nexus_info->region.x+(ssize_t) nexus_info->region.width-1; y=nexus_info->region.y+(ssize_t) nexus_info->region.height-1; if (((nexus_info->region.x >= 0) && (x < (ssize_t) cache_info->columns) && (nexus_info->region.y >= 0) && (y < (ssize_t) cache_info->rows)) && ((nexus_info->region.height == 1UL) || ((nexus_info->region.x == 0) && ((nexus_info->region.width == cache_info->columns) || ((nexus_info->region.width % cache_info->columns) == 0))))) { MagickOffsetType offset; /* Pixels are accessed directly from memory. */ offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; nexus_info->pixels=cache_info->pixels+cache_info->number_channels* offset; nexus_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) nexus_info->metacontent=(unsigned char *) cache_info->metacontent+ offset*cache_info->metacontent_extent; PrefetchPixelCacheNexusPixels(nexus_info,mode); nexus_info->authentic_pixel_cache=IsPixelCacheAuthentic(cache_info, nexus_info); return(nexus_info->pixels); } } /* Pixels are stored in a staging region until they are synced to the cache. */ length=number_pixels*cache_info->number_channels*sizeof(Quantum); if (cache_info->metacontent_extent != 0) length+=number_pixels*cache_info->metacontent_extent; if (nexus_info->cache == (Quantum *) NULL) { nexus_info->length=length; status=AcquireCacheNexusPixels(cache_info,nexus_info,exception); if (status == MagickFalse) { nexus_info->length=0; return((Quantum *) NULL); } } else if (nexus_info->length < length) { RelinquishCacheNexusPixels(nexus_info); nexus_info->length=length; status=AcquireCacheNexusPixels(cache_info,nexus_info,exception); if (status == MagickFalse) { nexus_info->length=0; return((Quantum *) NULL); } } nexus_info->pixels=nexus_info->cache; nexus_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) nexus_info->metacontent=(void *) (nexus_info->pixels+number_pixels* cache_info->number_channels); PrefetchPixelCacheNexusPixels(nexus_info,mode); nexus_info->authentic_pixel_cache=IsPixelCacheAuthentic(cache_info, nexus_info); return(nexus_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t P i x e l C a c h e V i r t u a l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheVirtualMethod() sets the "virtual pixels" method for the % pixel cache and returns the previous setting. A virtual pixel is any pixel % access that is outside the boundaries of the image cache. % % The format of the SetPixelCacheVirtualMethod() method is: % % VirtualPixelMethod SetPixelCacheVirtualMethod(Image *image, % const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: choose the type of virtual pixel. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType SetCacheAlphaChannel(Image *image,const Quantum alpha, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; CacheView *magick_restrict image_view; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); image->alpha_trait=BlendPixelTrait; status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); /* must be virtual */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=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++) { SetPixelAlpha(image,alpha,q); q+=GetPixelChannels(image); } status=SyncCacheViewAuthenticPixels(image_view,exception); } image_view=DestroyCacheView(image_view); return(status); } MagickPrivate VirtualPixelMethod SetPixelCacheVirtualMethod(Image *image, const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; VirtualPixelMethod method; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); method=cache_info->virtual_pixel_method; cache_info->virtual_pixel_method=virtual_pixel_method; if ((image->columns != 0) && (image->rows != 0)) switch (virtual_pixel_method) { case BackgroundVirtualPixelMethod: { if ((image->background_color.alpha_trait != UndefinedPixelTrait) && (image->alpha_trait == UndefinedPixelTrait)) (void) SetCacheAlphaChannel(image,OpaqueAlpha,exception); if ((IsPixelInfoGray(&image->background_color) == MagickFalse) && (IsGrayColorspace(image->colorspace) != MagickFalse)) (void) SetImageColorspace(image,sRGBColorspace,exception); break; } case TransparentVirtualPixelMethod: { if (image->alpha_trait == UndefinedPixelTrait) (void) SetCacheAlphaChannel(image,OpaqueAlpha,exception); break; } default: break; } return(method); } #if defined(MAGICKCORE_OPENCL_SUPPORT) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c A u t h e n t i c O p e n C L B u f f e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticOpenCLBuffer() makes sure that all the OpenCL operations have % been completed and updates the host memory. % % The format of the SyncAuthenticOpenCLBuffer() method is: % % void SyncAuthenticOpenCLBuffer(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static void CopyOpenCLBuffer(CacheInfo *magick_restrict cache_info) { assert(cache_info != (CacheInfo *) NULL); assert(cache_info->signature == MagickCoreSignature); if ((cache_info->type != MemoryCache) || (cache_info->opencl == (MagickCLCacheInfo) NULL)) return; /* Ensure single threaded access to OpenCL environment. */ LockSemaphoreInfo(cache_info->semaphore); cache_info->opencl=CopyMagickCLCacheInfo(cache_info->opencl); UnlockSemaphoreInfo(cache_info->semaphore); } MagickPrivate void SyncAuthenticOpenCLBuffer(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); cache_info=(CacheInfo *) image->cache; CopyOpenCLBuffer(cache_info); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixelCacheNexus() saves the authentic image pixels to the % in-memory or disk cache. The method returns MagickTrue if the pixel region % is synced, otherwise MagickFalse. % % The format of the SyncAuthenticPixelCacheNexus() method is: % % MagickBooleanType SyncAuthenticPixelCacheNexus(Image *image, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o nexus_info: the cache nexus to sync. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate MagickBooleanType SyncAuthenticPixelCacheNexus(Image *image, NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickBooleanType status; /* Transfer pixels to the cache. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->cache == (Cache) NULL) ThrowBinaryException(CacheError,"PixelCacheIsNotOpen",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->type == UndefinedCache) return(MagickFalse); if (image->mask_trait != UpdatePixelTrait) { if (((image->channels & WriteMaskChannel) != 0) && (ClipPixelCacheNexus(image,nexus_info,exception) == MagickFalse)) return(MagickFalse); if (((image->channels & CompositeMaskChannel) != 0) && (MaskPixelCacheNexus(image,nexus_info,exception) == MagickFalse)) return(MagickFalse); } if (nexus_info->authentic_pixel_cache != MagickFalse) { image->taint=MagickTrue; return(MagickTrue); } assert(cache_info->signature == MagickCoreSignature); status=WritePixelCachePixels(cache_info,nexus_info,exception); if ((cache_info->metacontent_extent != 0) && (WritePixelCacheMetacontent(cache_info,nexus_info,exception) == MagickFalse)) return(MagickFalse); if (status != MagickFalse) image->taint=MagickTrue; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c A u t h e n t i c P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixelsCache() saves the authentic image pixels to the in-memory % or disk cache. The method returns MagickTrue if the pixel region is synced, % otherwise MagickFalse. % % The format of the SyncAuthenticPixelsCache() method is: % % MagickBooleanType SyncAuthenticPixelsCache(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 MagickBooleanType SyncAuthenticPixelsCache(Image *image, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); status=SyncAuthenticPixelCacheNexus(image,cache_info->nexus_info[id], exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S y n c A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixels() saves the image pixels to the in-memory or disk cache. % The method returns MagickTrue if the pixel region is flushed, otherwise % MagickFalse. % % The format of the SyncAuthenticPixels() method is: % % MagickBooleanType SyncAuthenticPixels(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 SyncAuthenticPixels(Image *image, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.sync_authentic_pixels_handler != (SyncAuthenticPixelsHandler) NULL) { status=cache_info->methods.sync_authentic_pixels_handler(image, exception); return(status); } assert(id < (int) cache_info->number_threads); status=SyncAuthenticPixelCacheNexus(image,cache_info->nexus_info[id], exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImagePixelCache() saves the image pixels to the in-memory or disk cache. % The method returns MagickTrue if the pixel region is flushed, otherwise % MagickFalse. % % The format of the SyncImagePixelCache() method is: % % MagickBooleanType SyncImagePixelCache(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate MagickBooleanType SyncImagePixelCache(Image *image, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(exception != (ExceptionInfo *) NULL); cache_info=(CacheInfo *) GetImagePixelCache(image,MagickTrue,exception); return(cache_info == (CacheInfo *) NULL ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + W r i t e P i x e l C a c h e M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePixelCacheMetacontent() writes the meta-content to the specified region % of the pixel cache. % % The format of the WritePixelCacheMetacontent() method is: % % MagickBooleanType WritePixelCacheMetacontent(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to write the meta-content. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePixelCacheMetacontent(CacheInfo *cache_info, NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register const unsigned char *magick_restrict p; register ssize_t y; size_t rows; if (cache_info->metacontent_extent == 0) return(MagickFalse); if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) nexus_info->region.width* cache_info->metacontent_extent; extent=(MagickSizeType) length*nexus_info->region.height; rows=nexus_info->region.height; y=0; p=(unsigned char *) nexus_info->metacontent; switch (cache_info->type) { case MemoryCache: case MapCache: { register unsigned char *magick_restrict q; /* Write associated pixels to memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } q=(unsigned char *) cache_info->metacontent+offset* cache_info->metacontent_extent; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=nexus_info->region.width*cache_info->metacontent_extent; q+=cache_info->columns*cache_info->metacontent_extent; } break; } case DiskCache: { /* Write associated pixels to disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } extent=(MagickSizeType) cache_info->columns*cache_info->rows; for (y=0; y < (ssize_t) rows; y++) { count=WritePixelCacheRegion(cache_info,cache_info->offset+extent* cache_info->number_channels*sizeof(Quantum)+offset* cache_info->metacontent_extent,length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=cache_info->metacontent_extent*nexus_info->region.width; offset+=cache_info->columns; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Write metacontent to distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WriteDistributePixelCacheMetacontent((DistributeCacheInfo *) cache_info->server_info,&region,length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=cache_info->metacontent_extent*nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToWritePixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + W r i t e C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePixelCachePixels() writes image pixels to the specified region of the % pixel cache. % % The format of the WritePixelCachePixels() method is: % % MagickBooleanType WritePixelCachePixels(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to write the pixels. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePixelCachePixels( CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info, ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register const Quantum *magick_restrict p; register ssize_t y; size_t rows; if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) cache_info->number_channels*nexus_info->region.width* sizeof(Quantum); extent=length*nexus_info->region.height; rows=nexus_info->region.height; y=0; p=nexus_info->pixels; switch (cache_info->type) { case MemoryCache: case MapCache: { register Quantum *magick_restrict q; /* Write pixels to memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } q=cache_info->pixels+offset*cache_info->number_channels; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=cache_info->number_channels*nexus_info->region.width; q+=cache_info->number_channels*cache_info->columns; } break; } case DiskCache: { /* Write pixels to disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WritePixelCacheRegion(cache_info,cache_info->offset+offset* cache_info->number_channels*sizeof(*p),length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=cache_info->number_channels*nexus_info->region.width; offset+=cache_info->columns; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Write pixels to distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WriteDistributePixelCachePixels((DistributeCacheInfo *) cache_info->server_info,&region,length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=cache_info->number_channels*nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToWritePixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); }
oskar_dftw_o2c_2d_omp.c
/* * Copyright (c) 2013, The University of Oxford * 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 University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "math/oskar_dftw_o2c_2d_omp.h" #include <math.h> #ifdef __cplusplus extern "C" { #endif #if 0 /* Single precision. */ void oskar_dftw_o2c_2d_omp_f(const int n_in, const float wavenumber, const float* x_in, const float* y_in, const float2* weights_in, const int n_out, const float* x_out, const float* y_out, float2* output) { int i_out = 0; /* Loop over output points. */ #pragma omp parallel for private(i_out) for (i_out = 0; i_out < n_out; ++i_out) { int i; float xp_out, yp_out; float2 out, out_c, out_cnt, out_new; /* Clear output value. */ out.x = 0.0f; out.y = 0.0f; out_c.x = 0.0f; out_c.y = 0.0f; /* Get the output position. */ xp_out = wavenumber * x_out[i_out]; yp_out = wavenumber * y_out[i_out]; /* Loop over input points. */ for (i = 0; i < n_in; ++i) { float signal_x, signal_y; /* Calculate the phase for the output position. */ { float a; a = xp_out * x_in[i] + yp_out * y_in[i]; signal_x = cos(a); signal_y = sin(a); } /* Perform complex multiply-accumulate using Kahan summation. */ { float2 w, r; w = weights_in[i]; r.x = signal_x * w.x - signal_y * w.y; r.y = signal_x * w.y + signal_y * w.x; out_cnt.x = r.x - out_c.x; out_new.x = out.x + out_cnt.x; out_c.x = (out_new.x - out.x) - out_cnt.x; out.x = out_new.x; out_cnt.y = r.y - out_c.y; out_new.y = out.y + out_cnt.y; out_c.y = (out_new.y - out.y) - out_cnt.y; out.y = out_new.y; } } /* Store the output point. */ output[i_out] = out; } } #endif /* Single precision. */ void oskar_dftw_o2c_2d_omp_f(const int n_in, const float wavenumber, const float* x_in, const float* y_in, const float2* weights_in, const int n_out, const float* x_out, const float* y_out, float2* output) { int i_out = 0; /* Loop over output points. */ #pragma omp parallel for private(i_out) for (i_out = 0; i_out < n_out; ++i_out) { int i; float xp_out, yp_out; float2 out; /* Clear output value. */ out.x = 0.0f; out.y = 0.0f; /* Get the output position. */ xp_out = wavenumber * x_out[i_out]; yp_out = wavenumber * y_out[i_out]; /* Loop over input points. */ for (i = 0; i < n_in; ++i) { float signal_x, signal_y; /* Calculate the phase for the output position. */ { float a; a = xp_out * x_in[i] + yp_out * y_in[i]; signal_x = cosf(a); signal_y = sinf(a); } /* Perform complex multiply-accumulate. */ { float2 w; w = weights_in[i]; out.x += signal_x * w.x; out.x -= signal_y * w.y; out.y += signal_y * w.x; out.y += signal_x * w.y; } } /* Store the output point. */ output[i_out] = out; } } /* Double precision. */ void oskar_dftw_o2c_2d_omp_d(const int n_in, const double wavenumber, const double* x_in, const double* y_in, const double2* weights_in, const int n_out, const double* x_out, const double* y_out, double2* output) { int i_out = 0; /* Loop over output points. */ #pragma omp parallel for private(i_out) for (i_out = 0; i_out < n_out; ++i_out) { int i; double xp_out, yp_out; double2 out; /* Clear output value. */ out.x = 0.0; out.y = 0.0; /* Get the output position. */ xp_out = wavenumber * x_out[i_out]; yp_out = wavenumber * y_out[i_out]; /* Loop over input points. */ for (i = 0; i < n_in; ++i) { double signal_x, signal_y; /* Calculate the phase for the output position. */ { double a; a = xp_out * x_in[i] + yp_out * y_in[i]; signal_x = cos(a); signal_y = sin(a); } /* Perform complex multiply-accumulate. */ { double2 w; w = weights_in[i]; out.x += signal_x * w.x; out.x -= signal_y * w.y; out.y += signal_y * w.x; out.y += signal_x * w.y; } } /* Store the output point. */ output[i_out] = out; } } #ifdef __cplusplus } #endif
a.31.2.c
/* { dg-do compile } */ void a31_2 (float *x, int *y, int n) { int i, b, b_p; float a, a_p; a = 0.0; b = 0; #pragma omp parallel shared(a, b, x, y, n) \ private(a_p, b_p) { a_p = 0.0; b_p = 0; #pragma omp for private(i) for (i = 0; i < n; i++) { a_p += x[i]; b_p ^= y[i]; } #pragma omp critical { a += a_p; b ^= b_p; } } }
wendy.c
/* wendy.c: One time-step of a one-dimensional N-body code */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <wendy.h> #include <bst.h> double _solve_coll_quad(double c0, double c1, double c2){ // Solves for collisions under quadratic motion: a t^2/2 + vt + x double mba; mba= -c1/c2; return 0.5 * ( mba + sqrt ( mba * mba - 4. * c0/c2) ); } double _solve_coll_harm(double c0, double c1, double c2, double omega){ // Solves for collisions under harmonic motion: A cos(omegaxt+phi)+a/omega^2 double A, B, out; A= c0-c2; B= c1/omega; out= -asin(c2/sqrt(B*B+A*A))-atan2(A,B); if ( out < 0 ) { out= M_PI+asin(c2/sqrt(B*B+A*A))-atan2(A,B); } //printf("Solves equation22? %g,%g,%g,%g\n",A*cos(out),B*sin(out),C, // A * cos(out) + B * sin(out) - C); //fflush(stdout); return out/omega; } void _wendy_nbody_onestep(int N, double * x, double * v, double * a, double * m, int * sindx, int * cindx, double * next_tcoll, double * tcoll, double dt, int maxcoll, int * err, int * ncoll, double * time_elapsed){ int cnt_coll,ii, tmpi; int c_in_x_indx, c_in_x_next_indx; double dv,tdt, dm, tmpd; struct node* minNode; double * t= (double *) malloc ( N * sizeof(double) ); #pragma omp parallel for schedule(static,chunk) private(ii) for (ii=0; ii < N; ii++) *(t+ii)= 0.; cnt_coll= 0; // Build binary search tree for keeping track of collision times int * idx= (int *) malloc ( (N-1) * sizeof(int) ); #pragma omp parallel for schedule(static,chunk) private(ii) for (ii=0; ii < N-1; ii++) *(idx+ii)= ii; struct node* bst_tcoll= bst_build(N-1,idx,tcoll); free(idx); //bst_inorder(bst_tcoll); // Time how long the loop takes clock_t time_begin= clock(); while ( *next_tcoll < dt && cnt_coll < maxcoll ){ //printf("Colliding in %f\n",*next_tcoll); //fflush(stdout); cnt_coll+= 1; // collide, update collided particles c_in_x_indx= *(sindx+ *cindx); c_in_x_next_indx= *(sindx+ *cindx+1); tdt= ( *next_tcoll - *(t + c_in_x_indx) ); dv= *(a + c_in_x_indx) * tdt; *(x + c_in_x_indx)+= dv * tdt / 2. + *(v + c_in_x_indx) * tdt; *(v + c_in_x_indx)+= dv; *(t + c_in_x_indx)= *next_tcoll; tdt= ( *next_tcoll - *(t + c_in_x_next_indx) ); dv= *(a + c_in_x_next_indx) * tdt; *(x + c_in_x_next_indx)+= dv * tdt / 2. + *(v + c_in_x_next_indx) * tdt; *(v + c_in_x_next_indx)+= dv; *(t + c_in_x_next_indx)= *next_tcoll; // swap tmpi= *(sindx+ *cindx); *(sindx+ *cindx)= *(sindx+ *cindx+1); *(sindx+ *cindx+1)= tmpi; // track mass and update accelerations dm= *(m + c_in_x_next_indx) - *(m + c_in_x_indx); *(a + c_in_x_indx)-= dm; *(a + c_in_x_next_indx)-= dm; tmpd= *(a + c_in_x_indx); *(a + c_in_x_indx)= *(a + c_in_x_next_indx); *(a + c_in_x_next_indx)= tmpd; // Update collision times, solution for delta x = 0 //printf("Collide in %f\n",2.* (*(v + c_in_x_indx) - *(v + c_in_x_next_indx)) / // (*(a + c_in_x_next_indx) - *(a + c_in_x_indx))); //fflush(stdout); tmpd= 2.* (*(v + c_in_x_indx) - *(v + c_in_x_next_indx)) / (*(a + c_in_x_next_indx) - *(a + c_in_x_indx)); bst_tcoll= bst_deleteNode(bst_tcoll,tcoll+*cindx); *(tcoll + *cindx)= *next_tcoll+tmpd; bst_tcoll= bst_forceInsert(bst_tcoll,*cindx,tcoll+*cindx); // Abuse the c_in_x_indx and c_in_x_next_indx arrays if ( *cindx > 0 ){ c_in_x_indx= *(sindx+ *cindx-1); c_in_x_next_indx= *(sindx+ *cindx); tdt= *(t + c_in_x_indx) - *next_tcoll; bst_tcoll= bst_deleteNode(bst_tcoll,tcoll+*cindx-1); *(tcoll + *cindx -1)= *next_tcoll + _solve_coll_quad(*(x + c_in_x_indx) + *(a+c_in_x_indx) * tdt*tdt / 2. - *(v+c_in_x_indx) * tdt - *(x + c_in_x_next_indx), *(v + c_in_x_indx) - *(a + c_in_x_indx) * tdt - *(v + c_in_x_next_indx), 0.5*(*(a + c_in_x_indx) - *(a + c_in_x_next_indx))); bst_tcoll= bst_forceInsert(bst_tcoll,*cindx-1,tcoll+*cindx-1); } if ( *cindx < N-2 ){ c_in_x_indx= *(sindx+ *cindx+2); c_in_x_next_indx= *(sindx+ *cindx+1); tdt= *(t + c_in_x_indx) - *next_tcoll; bst_tcoll= bst_deleteNode(bst_tcoll,tcoll+*cindx+1); *(tcoll + *cindx+1)= *next_tcoll + _solve_coll_quad(*(x + c_in_x_indx) + *(a+c_in_x_indx) * tdt*tdt / 2. - *(v+c_in_x_indx) * tdt - *(x + c_in_x_next_indx), *(v + c_in_x_indx) - *(a + c_in_x_indx) * tdt - *(v + c_in_x_next_indx), 0.5*(*(a + c_in_x_indx) - *(a + c_in_x_next_indx))); bst_tcoll= bst_forceInsert(bst_tcoll,*cindx+1,tcoll+*cindx+1); } // Find minimum minNode= bst_minValueNode(bst_tcoll); *cindx= minNode->idx; *next_tcoll= *minNode->val; //printf("Next one %f\n",*next_tcoll); //fflush(stdout); } clock_t time_end= clock(); *time_elapsed= (double) (time_end-time_begin) / CLOCKS_PER_SEC; //printf("Next %f\n",*next_tcoll-dt); //fflush(stdout); // Update all to next snapshot #pragma omp parallel for schedule(static,chunk) private(ii,tdt,dv) for (ii=0; ii < N; ii++) { tdt= dt - *(t+ii); dv= *(a+ii) * tdt; *(x+ii)+= dv * tdt / 2. + *(v+ii) * tdt; *(v+ii)+= dv; } #pragma omp parallel for schedule(static,chunk) private(ii) for (ii=0; ii < N-1; ii++) { *(tcoll+ii)-= dt; } *next_tcoll-= dt; free(t); bst_destroy(bst_tcoll); *ncoll= cnt_coll; if ( cnt_coll == maxcoll ) *err= -2; } void _wendy_nbody_harm_onestep(int N, double * x, double * v, double * a, double * m, int * sindx, int * cindx, double * next_tcoll, double * tcoll,double dt, int maxcoll, int * err, int * ncoll,double * time_elapsed, double omega){ int cnt_coll,ii, tmpi; int c_in_x_indx, c_in_x_next_indx; double tdt, dm, tmpd, cosot, sinot; struct node* minNode; double * t= (double *) malloc ( N * sizeof(double) ); #pragma omp parallel for schedule(static,chunk) private(ii) for (ii=0; ii < N; ii++) *(t+ii)= 0.; cnt_coll= 0; // Build binary search tree for keeping track of collision times int * idx= (int *) malloc ( (N-1) * sizeof(int) ); #pragma omp parallel for schedule(static,chunk) private(ii) for (ii=0; ii < N-1; ii++) *(idx+ii)= ii; struct node* bst_tcoll= bst_build(N-1,idx,tcoll); free(idx); //bst_inorder(bst_tcoll); // Time how long the loop takes clock_t time_begin= clock(); while ( *next_tcoll < dt && cnt_coll < maxcoll ){ //printf("Colliding in %f\n",*next_tcoll); //fflush(stdout); cnt_coll+= 1; // collide, update collided particles c_in_x_indx= *(sindx+ *cindx); c_in_x_next_indx= *(sindx+ *cindx+1); tdt= ( *next_tcoll - *(t + c_in_x_indx) ); sinot = sin( omega * tdt ); cosot= sqrt(1.-sinot*sinot); tmpd= *(x + c_in_x_indx) - *(a + c_in_x_indx); *(x + c_in_x_indx)= tmpd * cosot \ + *(v + c_in_x_indx) / omega * sinot \ + *(a + c_in_x_indx); *(v + c_in_x_indx)= -tmpd * omega * sinot \ + *(v + c_in_x_indx) * cosot; *(t + c_in_x_indx)= *next_tcoll; tdt= ( *next_tcoll - *(t + c_in_x_next_indx) ); sinot = sin( omega * tdt ); cosot= sqrt(1.-sinot*sinot); tmpd= *(x + c_in_x_next_indx) - *(a + c_in_x_next_indx); *(x + c_in_x_next_indx)= tmpd * cosot \ + *(v + c_in_x_next_indx) / omega * sinot \ + *(a + c_in_x_next_indx) ; *(v + c_in_x_next_indx)= -tmpd * omega * sinot \ + *(v + c_in_x_next_indx) * cosot; *(t + c_in_x_next_indx)= *next_tcoll; //printf("Collide? %g, %g, %g\n",*(x + c_in_x_indx),*(x + c_in_x_next_indx), // *(x + c_in_x_indx)-*(x + c_in_x_next_indx)); //fflush(stdout); // swap tmpi= *(sindx+ *cindx); *(sindx+ *cindx)= *(sindx+ *cindx+1); *(sindx+ *cindx+1)= tmpi; // track mass and update accelerations dm= *(m + c_in_x_next_indx) - *(m + c_in_x_indx); *(a + c_in_x_indx)-= dm; *(a + c_in_x_next_indx)-= dm; tmpd= *(a + c_in_x_indx); *(a + c_in_x_indx)= *(a + c_in_x_next_indx); *(a + c_in_x_next_indx)= tmpd; // Update collision times, solution for delta x = 0 tmpd= (*(v + c_in_x_indx) - *(v + c_in_x_next_indx)) / \ (*(a + c_in_x_next_indx) - *(a + c_in_x_indx)) / omega; tmpd*= tmpd; tmpd= (1.-tmpd)/(1.+tmpd); tmpd= acos(tmpd)/omega; bst_tcoll= bst_deleteNode(bst_tcoll,tcoll+*cindx); *(tcoll + *cindx)= *next_tcoll+tmpd; bst_tcoll= bst_forceInsert(bst_tcoll,*cindx,tcoll+*cindx); //printf("Collide in %f\n",*(tcoll + *cindx)-*next_tcoll); //fflush(stdout); // Abuse the c_in_x_indx and c_in_x_next_indx arrays if ( *cindx > 0 ){ c_in_x_indx= *(sindx+ *cindx-1); c_in_x_next_indx= *(sindx+ *cindx); // Also forward the previous sheet to the collision time for convenience tdt= *next_tcoll - *(t + c_in_x_indx); sinot = sin( omega * tdt ); cosot= sqrt(1.-sinot*sinot); tmpd= *(x + c_in_x_indx) - *(a + c_in_x_indx); *(x + c_in_x_indx)= tmpd * cosot \ + *(v + c_in_x_indx) / omega * sinot \ + *(a + c_in_x_indx); *(v + c_in_x_indx)= -tmpd * omega * sinot \ + *(v + c_in_x_indx) * cosot; *(t + c_in_x_indx)= *next_tcoll; bst_tcoll= bst_deleteNode(bst_tcoll,tcoll+*cindx-1); *(tcoll + *cindx -1)= *next_tcoll + _solve_coll_harm(*(x + c_in_x_indx) - *(x + c_in_x_next_indx), *(v + c_in_x_indx) - *(v + c_in_x_next_indx), *(a + c_in_x_indx) - *(a + c_in_x_next_indx), omega); bst_tcoll= bst_forceInsert(bst_tcoll,*cindx-1,tcoll+*cindx-1); } if ( *cindx < N-2 ){ c_in_x_indx= *(sindx+ *cindx+2); c_in_x_next_indx= *(sindx+ *cindx+1); // Also forward the next sheet to the collision time for convenience tdt= *next_tcoll - *(t + c_in_x_indx); sinot = sin( omega * tdt ); cosot= sqrt(1.-sinot*sinot); tmpd= *(x + c_in_x_indx) - *(a + c_in_x_indx); *(x + c_in_x_indx)= tmpd * cosot \ + *(v + c_in_x_indx) / omega * sinot \ + *(a + c_in_x_indx); *(v + c_in_x_indx)= -tmpd * omega * sinot \ + *(v + c_in_x_indx) * cosot; *(t + c_in_x_indx)= *next_tcoll; bst_tcoll= bst_deleteNode(bst_tcoll,tcoll+*cindx+1); *(tcoll + *cindx+1)= *next_tcoll + _solve_coll_harm(*(x + c_in_x_indx) - *(x + c_in_x_next_indx), *(v + c_in_x_indx) - *(v + c_in_x_next_indx), *(a + c_in_x_indx) - *(a + c_in_x_next_indx), omega); bst_tcoll= bst_forceInsert(bst_tcoll,*cindx+1,tcoll+*cindx+1); } // Find minimum minNode= bst_minValueNode(bst_tcoll); *cindx= minNode->idx; *next_tcoll= *minNode->val; //printf("Next one %f\n",*next_tcoll); //fflush(stdout); } clock_t time_end= clock(); *time_elapsed= (double) (time_end-time_begin) / CLOCKS_PER_SEC; //printf("Next %f\n",*next_tcoll-dt); //fflush(stdout); // Update all to next snapshot #pragma omp parallel for schedule(static,chunk) private(ii,tdt,dv,cosot,sinot,tmpd) for (ii=0; ii < N; ii++) { tdt= dt - *(t+ii); sinot = sin( omega * tdt ); cosot= sqrt(1.-sinot*sinot); tmpd= *(x+ii) - *(a+ii); *(x+ii)= tmpd * cosot + *(v+ii) / omega * sinot + *(a+ii); *(v+ii)= -tmpd * omega * sinot + *(v+ii) * cosot; } #pragma omp parallel for schedule(static,chunk) private(ii) for (ii=0; ii < N-1; ii++) { *(tcoll+ii)-= dt; } *next_tcoll-= dt; free(t); bst_destroy(bst_tcoll); *ncoll= cnt_coll; if ( cnt_coll == maxcoll ) *err= -2; } // Approximate solution using leapfrog integration w/ exact forces void leapfrog_leapq(int N, struct array_w_index *xi,double *v,double dt){ int ii; for (ii=0; ii < N; ii++) (xi+ii)->val+= dt * *(v + (xi+ii)->idx); } void leapfrog_leappq(int N, struct array_w_index * xi, double *v,double dt_kick,double dt_drift, double *a){ int ii; for (ii=0; ii< N; ii++) { *(v + (xi+ii)->idx)+= dt_kick * *(a + (xi+ii)->idx); (xi+ii)->val+= dt_drift * *(v + (xi+ii)->idx); } } int argsort_compare_function(const void *a,const void *b) { struct array_w_index *x = (struct array_w_index *) a; struct array_w_index *y = (struct array_w_index *) b; if (x->val < y->val) return -1; else if (x->val > y->val) return 1; else return 0; } void _nbody_force(int N, struct array_w_index * xi, double * m, double * a, double omega2, double * cumulmass,double * revcumulmass){ int ii; // argsort qsort(xi,N,sizeof(struct array_w_index),argsort_compare_function); // Compute cumulative mass for (ii=0; ii< N-1; ii++) *(cumulmass+ii+1)= *(cumulmass+ii) + *(m+(xi+ii)->idx); // Now compute acceleration from reverse-cumulative mass for (ii=0; ii< N-1; ii++) *(revcumulmass+N-ii-2)= *(revcumulmass+N-ii-1) + *(m+(xi+N-ii-1)->idx); if ( omega2 < 0 ) for (ii=0; ii< N; ii++) *(a + (xi+ii)->idx)= *(revcumulmass+ii) - *(cumulmass+ii); else for (ii=0; ii< N; ii++) *(a + (xi+ii)->idx)= *(revcumulmass+ii) - *(cumulmass+ii) \ - omega2 * (xi+ii)->val; } void _wendy_nbody_approx_onestep(int N, struct array_w_index * xi, double * x, double * v, double * m, double * a, double dt, int nleap, double omega2, int * err,double * time_elapsed, double * cumulmass, double * revcumulmass){ int ii; clock_t time_begin= clock(); //drift half leapfrog_leapq(N,xi,v,dt/2.); //now drift full for a while for (ii=0; ii < (nleap-1); ii++){ //kick+drift _nbody_force(N,xi,m,a,omega2,cumulmass,revcumulmass); leapfrog_leappq(N,xi,v,dt,dt,a); } //end with one last kick and drift _nbody_force(N,xi,m,a,omega2,cumulmass,revcumulmass); leapfrog_leappq(N,xi,v,dt,dt/2.,a); //de-sort for (ii=0; ii< N; ii++) *(x+(xi+ii)->idx)= (xi+ii)->val; clock_t time_end= clock(); *time_elapsed= (double) (time_end-time_begin) / CLOCKS_PER_SEC; }
compare.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC OOO M M PPPP AAA RRRR EEEEE % % C O O MM MM P P A A R R E % % C O O M M M PPPP AAAAA RRRR EEE % % C O O M M P A A R R E % % CCCC OOO M M P A A R R EEEEE % % % % % % MagickCore Image Comparison Methods % % % % Software Design % % Cristy % % December 2003 % % % % % % Copyright 1999-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 "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/client.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/compare.h" #include "MagickCore/composite-private.h" #include "MagickCore/constitute.h" #include "MagickCore/exception-private.h" #include "MagickCore/geometry.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/resource_.h" #include "MagickCore/string_.h" #include "MagickCore/statistic.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/transform.h" #include "MagickCore/utility.h" #include "MagickCore/version.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p a r e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompareImages() compares one or more pixel channels of an image to a % reconstructed image and returns the difference image. % % The format of the CompareImages method is: % % Image *CompareImages(const Image *image,const Image *reconstruct_image, % const MetricType metric,double *distortion,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o reconstruct_image: the reconstruct image. % % o metric: the metric. % % o distortion: the computed distortion between the images. % % o exception: return any errors or warnings in this structure. % */ static size_t GetImageChannels(const Image *image) { register ssize_t i; size_t channels; channels=0; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) != 0) channels++; } return(channels == 0 ? (size_t) 1 : channels); } MagickExport Image *CompareImages(Image *image,const Image *reconstruct_image, const MetricType metric,double *distortion,ExceptionInfo *exception) { CacheView *highlight_view, *image_view, *reconstruct_view; const char *artifact; double fuzz; Image *clone_image, *difference_image, *highlight_image; MagickBooleanType status; PixelInfo highlight, lowlight, masklight; RectangleInfo geometry; size_t columns, rows; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(reconstruct_image != (const Image *) NULL); assert(reconstruct_image->signature == MagickCoreSignature); assert(distortion != (double *) NULL); *distortion=0.0; if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=GetImageDistortion(image,reconstruct_image,metric,distortion, exception); if (status == MagickFalse) return((Image *) NULL); columns=MagickMax(image->columns,reconstruct_image->columns); rows=MagickMax(image->rows,reconstruct_image->rows); SetGeometry(image,&geometry); geometry.width=columns; geometry.height=rows; clone_image=CloneImage(image,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) return((Image *) NULL); (void) SetImageMask(clone_image,ReadPixelMask,(Image *) NULL,exception); difference_image=ExtentImage(clone_image,&geometry,exception); clone_image=DestroyImage(clone_image); if (difference_image == (Image *) NULL) return((Image *) NULL); (void) SetImageAlphaChannel(difference_image,OpaqueAlphaChannel,exception); highlight_image=CloneImage(image,columns,rows,MagickTrue,exception); if (highlight_image == (Image *) NULL) { difference_image=DestroyImage(difference_image); return((Image *) NULL); } status=SetImageStorageClass(highlight_image,DirectClass,exception); if (status == MagickFalse) { difference_image=DestroyImage(difference_image); highlight_image=DestroyImage(highlight_image); return((Image *) NULL); } (void) SetImageMask(highlight_image,ReadPixelMask,(Image *) NULL,exception); (void) SetImageAlphaChannel(highlight_image,OpaqueAlphaChannel,exception); (void) QueryColorCompliance("#f1001ecc",AllCompliance,&highlight,exception); artifact=GetImageArtifact(image,"compare:highlight-color"); if (artifact != (const char *) NULL) (void) QueryColorCompliance(artifact,AllCompliance,&highlight,exception); (void) QueryColorCompliance("#ffffffcc",AllCompliance,&lowlight,exception); artifact=GetImageArtifact(image,"compare:lowlight-color"); if (artifact != (const char *) NULL) (void) QueryColorCompliance(artifact,AllCompliance,&lowlight,exception); (void) QueryColorCompliance("#888888cc",AllCompliance,&masklight,exception); artifact=GetImageArtifact(image,"compare:masklight-color"); if (artifact != (const char *) NULL) (void) QueryColorCompliance(artifact,AllCompliance,&masklight,exception); /* Generate difference image. */ status=MagickTrue; fuzz=GetFuzzyColorDistance(image,reconstruct_image); image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); highlight_view=AcquireAuthenticCacheView(highlight_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_number_threads(image,highlight_image,rows,1) #endif for (y=0; y < (ssize_t) rows; y++) { MagickBooleanType sync; register const Quantum *magick_restrict p, *magick_restrict q; register Quantum *magick_restrict r; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception); r=QueueCacheViewAuthenticPixels(highlight_view,0,y,columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL) || (r == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) columns; x++) { double Da, Sa; MagickStatusType difference; register ssize_t i; if ((GetPixelReadMask(image,p) <= (QuantumRange/2)) || (GetPixelReadMask(reconstruct_image,q) <= (QuantumRange/2))) { SetPixelViaPixelInfo(highlight_image,&masklight,r); p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); r+=GetPixelChannels(highlight_image); continue; } difference=MagickFalse; Sa=QuantumScale*GetPixelAlpha(image,p); Da=QuantumScale*GetPixelAlpha(reconstruct_image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double distance; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image, channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; if (channel == AlphaPixelChannel) distance=(double) p[i]-GetPixelChannel(reconstruct_image,channel,q); else distance=Sa*p[i]-Da*GetPixelChannel(reconstruct_image,channel,q); if ((distance*distance) > fuzz) { difference=MagickTrue; break; } } if (difference == MagickFalse) SetPixelViaPixelInfo(highlight_image,&lowlight,r); else SetPixelViaPixelInfo(highlight_image,&highlight,r); p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); r+=GetPixelChannels(highlight_image); } sync=SyncCacheViewAuthenticPixels(highlight_view,exception); if (sync == MagickFalse) status=MagickFalse; } highlight_view=DestroyCacheView(highlight_view); reconstruct_view=DestroyCacheView(reconstruct_view); image_view=DestroyCacheView(image_view); (void) CompositeImage(difference_image,highlight_image,image->compose, MagickTrue,0,0,exception); highlight_image=DestroyImage(highlight_image); if (status == MagickFalse) difference_image=DestroyImage(difference_image); return(difference_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e D i s t o r t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageDistortion() compares one or more pixel channels of an image to a % reconstructed image and returns the specified distortion metric. % % The format of the GetImageDistortion method is: % % MagickBooleanType GetImageDistortion(const Image *image, % const Image *reconstruct_image,const MetricType metric, % double *distortion,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o reconstruct_image: the reconstruct image. % % o metric: the metric. % % o distortion: the computed distortion between the images. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType GetAbsoluteDistortion(const Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { CacheView *image_view, *reconstruct_view; double fuzz; MagickBooleanType status; size_t columns, rows; ssize_t y; /* Compute the absolute difference in pixels between two images. */ status=MagickTrue; fuzz=MagickMin(GetPixelChannels(image),GetPixelChannels(reconstruct_image))* GetFuzzyColorDistance(image,reconstruct_image); rows=MagickMax(image->rows,reconstruct_image->rows); columns=MagickMax(image->columns,reconstruct_image->columns); image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_number_threads(image,image,rows,1) #endif for (y=0; y < (ssize_t) rows; y++) { double channel_distortion[MaxPixelChannels+1]; register const Quantum *magick_restrict p, *magick_restrict q; register ssize_t j, x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL)) { status=MagickFalse; continue; } (void) ResetMagickMemory(channel_distortion,0,sizeof(channel_distortion)); for (x=0; x < (ssize_t) columns; x++) { double Da, distance, Sa; MagickBooleanType difference; register ssize_t i; if (GetPixelWriteMask(image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); continue; } difference=MagickFalse; distance=0.0; Sa=QuantumScale*GetPixelAlpha(image,p); Da=QuantumScale*GetPixelAlpha(reconstruct_image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double pixel; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image, channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; if (channel == AlphaPixelChannel) pixel=(double) p[i]-GetPixelChannel(reconstruct_image,channel,q); else pixel=Sa*p[i]-Da*GetPixelChannel(reconstruct_image,channel,q); distance+=pixel*pixel; if (distance > fuzz) { channel_distortion[i]++; difference=MagickTrue; } } if (difference != MagickFalse) channel_distortion[CompositePixelChannel]++; p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GetAbsoluteDistortion) #endif for (j=0; j <= MaxPixelChannels; j++) distortion[j]+=channel_distortion[j]; } reconstruct_view=DestroyCacheView(reconstruct_view); image_view=DestroyCacheView(image_view); return(status); } static MagickBooleanType GetFuzzDistortion(const Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { CacheView *image_view, *reconstruct_view; double area; MagickBooleanType status; register ssize_t j; size_t columns, rows; ssize_t y; status=MagickTrue; rows=MagickMax(image->rows,reconstruct_image->rows); columns=MagickMax(image->columns,reconstruct_image->columns); area=0.0; image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_number_threads(image,image,rows,1) reduction(+:area) #endif for (y=0; y < (ssize_t) rows; y++) { double channel_distortion[MaxPixelChannels+1]; register const Quantum *magick_restrict p, *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } (void) ResetMagickMemory(channel_distortion,0,sizeof(channel_distortion)); for (x=0; x < (ssize_t) columns; x++) { double Da, Sa; register ssize_t i; if ((GetPixelReadMask(image,p) <= (QuantumRange/2)) || (GetPixelReadMask(reconstruct_image,q) <= (QuantumRange/2))) { p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); continue; } Sa=QuantumScale*GetPixelAlpha(image,p); Da=QuantumScale*GetPixelAlpha(reconstruct_image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double distance; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image, channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; if (channel == AlphaPixelChannel) distance=QuantumScale*(p[i]-GetPixelChannel(reconstruct_image, channel,q)); else distance=QuantumScale*(Sa*p[i]-Da*GetPixelChannel(reconstruct_image, channel,q)); channel_distortion[i]+=distance*distance; channel_distortion[CompositePixelChannel]+=distance*distance; } area++; p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GetFuzzDistortion) #endif for (j=0; j <= MaxPixelChannels; j++) distortion[j]+=channel_distortion[j]; } reconstruct_view=DestroyCacheView(reconstruct_view); image_view=DestroyCacheView(image_view); area=PerceptibleReciprocal(area); for (j=0; j <= MaxPixelChannels; j++) distortion[j]*=area; distortion[CompositePixelChannel]/=(double) GetImageChannels(image); distortion[CompositePixelChannel]=sqrt(distortion[CompositePixelChannel]); return(status); } static MagickBooleanType GetMeanAbsoluteDistortion(const Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { CacheView *image_view, *reconstruct_view; double area; MagickBooleanType status; register ssize_t j; size_t columns, rows; ssize_t y; status=MagickTrue; rows=MagickMax(image->rows,reconstruct_image->rows); columns=MagickMax(image->columns,reconstruct_image->columns); area=0.0; image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_number_threads(image,image,rows,1) reduction(+:area) #endif for (y=0; y < (ssize_t) rows; y++) { double channel_distortion[MaxPixelChannels+1]; register const Quantum *magick_restrict p, *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL)) { status=MagickFalse; continue; } (void) ResetMagickMemory(channel_distortion,0,sizeof(channel_distortion)); for (x=0; x < (ssize_t) columns; x++) { double Da, Sa; register ssize_t i; if ((GetPixelReadMask(image,p) <= (QuantumRange/2)) || (GetPixelReadMask(reconstruct_image,q) <= (QuantumRange/2))) { p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); continue; } Sa=QuantumScale*GetPixelAlpha(image,p); Da=QuantumScale*GetPixelAlpha(reconstruct_image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double distance; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image, channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; if (channel == AlphaPixelChannel) distance=QuantumScale*fabs((double) p[i]- GetPixelChannel(reconstruct_image,channel,q)); else distance=QuantumScale*fabs(Sa*p[i]-Da* GetPixelChannel(reconstruct_image,channel,q)); channel_distortion[i]+=distance; channel_distortion[CompositePixelChannel]+=distance; } area++; p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GetMeanAbsoluteError) #endif for (j=0; j <= MaxPixelChannels; j++) distortion[j]+=channel_distortion[j]; } reconstruct_view=DestroyCacheView(reconstruct_view); image_view=DestroyCacheView(image_view); area=PerceptibleReciprocal(area); for (j=0; j <= MaxPixelChannels; j++) distortion[j]*=area; distortion[CompositePixelChannel]/=(double) GetImageChannels(image); return(status); } static MagickBooleanType GetMeanErrorPerPixel(Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { CacheView *image_view, *reconstruct_view; MagickBooleanType status; double area, maximum_error, mean_error; size_t columns, rows; ssize_t y; status=MagickTrue; area=0.0; maximum_error=0.0; mean_error=0.0; rows=MagickMax(image->rows,reconstruct_image->rows); columns=MagickMax(image->columns,reconstruct_image->columns); image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); for (y=0; y < (ssize_t) rows; y++) { register const Quantum *magick_restrict p, *magick_restrict q; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL)) { status=MagickFalse; break; } for (x=0; x < (ssize_t) columns; x++) { double Da, Sa; register ssize_t i; if ((GetPixelReadMask(image,p) <= (QuantumRange/2)) || (GetPixelReadMask(reconstruct_image,q) <= (QuantumRange/2))) { p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); continue; } Sa=QuantumScale*GetPixelAlpha(image,p); Da=QuantumScale*GetPixelAlpha(reconstruct_image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double distance; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image, channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; if (channel == AlphaPixelChannel) distance=fabs((double) p[i]- GetPixelChannel(reconstruct_image,channel,q)); else distance=fabs(Sa*p[i]-Da* GetPixelChannel(reconstruct_image,channel,q)); distortion[i]+=distance; distortion[CompositePixelChannel]+=distance; mean_error+=distance*distance; if (distance > maximum_error) maximum_error=distance; area++; } p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); } } reconstruct_view=DestroyCacheView(reconstruct_view); image_view=DestroyCacheView(image_view); image->error.mean_error_per_pixel=distortion[CompositePixelChannel]/area; image->error.normalized_mean_error=QuantumScale*QuantumScale*mean_error/area; image->error.normalized_maximum_error=QuantumScale*maximum_error; return(status); } static MagickBooleanType GetMeanSquaredDistortion(const Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { CacheView *image_view, *reconstruct_view; double area; MagickBooleanType status; register ssize_t j; size_t columns, rows; ssize_t y; status=MagickTrue; rows=MagickMax(image->rows,reconstruct_image->rows); columns=MagickMax(image->columns,reconstruct_image->columns); area=0.0; image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_number_threads(image,image,rows,1) reduction(+:area) #endif for (y=0; y < (ssize_t) rows; y++) { double channel_distortion[MaxPixelChannels+1]; register const Quantum *magick_restrict p, *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL)) { status=MagickFalse; continue; } (void) ResetMagickMemory(channel_distortion,0,sizeof(channel_distortion)); for (x=0; x < (ssize_t) columns; x++) { double Da, Sa; register ssize_t i; if ((GetPixelReadMask(image,p) <= (QuantumRange/2)) || (GetPixelReadMask(reconstruct_image,q) <= (QuantumRange/2))) { p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); continue; } Sa=QuantumScale*GetPixelAlpha(image,p); Da=QuantumScale*GetPixelAlpha(reconstruct_image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double distance; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image, channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; if (channel == AlphaPixelChannel) distance=QuantumScale*(p[i]-GetPixelChannel(reconstruct_image, channel,q)); else distance=QuantumScale*(Sa*p[i]-Da*GetPixelChannel(reconstruct_image, channel,q)); channel_distortion[i]+=distance*distance; channel_distortion[CompositePixelChannel]+=distance*distance; } area++; p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GetMeanSquaredError) #endif for (j=0; j <= MaxPixelChannels; j++) distortion[j]+=channel_distortion[j]; } reconstruct_view=DestroyCacheView(reconstruct_view); image_view=DestroyCacheView(image_view); area=PerceptibleReciprocal(area); for (j=0; j <= MaxPixelChannels; j++) distortion[j]*=area; distortion[CompositePixelChannel]/=GetImageChannels(image); return(status); } static MagickBooleanType GetNormalizedCrossCorrelationDistortion( const Image *image,const Image *reconstruct_image,double *distortion, ExceptionInfo *exception) { #define SimilarityImageTag "Similarity/Image" CacheView *image_view, *reconstruct_view; ChannelStatistics *image_statistics, *reconstruct_statistics; double area; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; size_t columns, rows; ssize_t y; /* Normalize to account for variation due to lighting and exposure condition. */ image_statistics=GetImageStatistics(image,exception); reconstruct_statistics=GetImageStatistics(reconstruct_image,exception); if ((image_statistics == (ChannelStatistics *) NULL) || (reconstruct_statistics == (ChannelStatistics *) NULL)) { if (image_statistics != (ChannelStatistics *) NULL) image_statistics=(ChannelStatistics *) RelinquishMagickMemory( image_statistics); if (reconstruct_statistics != (ChannelStatistics *) NULL) reconstruct_statistics=(ChannelStatistics *) RelinquishMagickMemory( reconstruct_statistics); return(MagickFalse); } status=MagickTrue; progress=0; for (i=0; i <= MaxPixelChannels; i++) distortion[i]=0.0; rows=MagickMax(image->rows,reconstruct_image->rows); columns=MagickMax(image->columns,reconstruct_image->columns); area=0.0; image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); for (y=0; y < (ssize_t) rows; y++) { register const Quantum *magick_restrict p, *magick_restrict q; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL)) { status=MagickFalse; break; } for (x=0; x < (ssize_t) columns; x++) { if ((GetPixelReadMask(image,p) <= (QuantumRange/2)) || (GetPixelReadMask(reconstruct_image,q) <= (QuantumRange/2))) { p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); continue; } area++; p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); } } area=PerceptibleReciprocal(area); for (y=0; y < (ssize_t) rows; y++) { register const Quantum *magick_restrict p, *magick_restrict q; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL)) { status=MagickFalse; break; } for (x=0; x < (ssize_t) columns; x++) { double Da, Sa; if ((GetPixelReadMask(image,p) <= (QuantumRange/2)) || (GetPixelReadMask(reconstruct_image,q) <= (QuantumRange/2))) { p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); continue; } Sa=QuantumScale*GetPixelAlpha(image,p); Da=QuantumScale*GetPixelAlpha(reconstruct_image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image, channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; if (channel == AlphaPixelChannel) { distortion[i]+=area*QuantumScale*(p[i]- image_statistics[channel].mean)*(GetPixelChannel( reconstruct_image,channel,q)- reconstruct_statistics[channel].mean); } else { distortion[i]+=area*QuantumScale*(Sa*p[i]- image_statistics[channel].mean)*(Da*GetPixelChannel( reconstruct_image,channel,q)- reconstruct_statistics[channel].mean); } } p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,SimilarityImageTag,progress++,rows); if (proceed == MagickFalse) { status=MagickFalse; break; } } } reconstruct_view=DestroyCacheView(reconstruct_view); image_view=DestroyCacheView(image_view); /* Divide by the standard deviation. */ distortion[CompositePixelChannel]=0.0; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double gamma; PixelChannel channel = GetPixelChannelChannel(image,i); gamma=image_statistics[channel].standard_deviation* reconstruct_statistics[channel].standard_deviation; gamma=PerceptibleReciprocal(gamma); distortion[i]=QuantumRange*gamma*distortion[i]; distortion[CompositePixelChannel]+=distortion[i]*distortion[i]; } distortion[CompositePixelChannel]=sqrt(distortion[CompositePixelChannel]/ GetImageChannels(image)); /* Free resources. */ reconstruct_statistics=(ChannelStatistics *) RelinquishMagickMemory( reconstruct_statistics); image_statistics=(ChannelStatistics *) RelinquishMagickMemory( image_statistics); return(status); } static MagickBooleanType GetPeakAbsoluteDistortion(const Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { CacheView *image_view, *reconstruct_view; MagickBooleanType status; size_t columns, rows; ssize_t y; status=MagickTrue; rows=MagickMax(image->rows,reconstruct_image->rows); columns=MagickMax(image->columns,reconstruct_image->columns); image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_number_threads(image,image,rows,1) #endif for (y=0; y < (ssize_t) rows; y++) { double channel_distortion[MaxPixelChannels+1]; register const Quantum *magick_restrict p, *magick_restrict q; register ssize_t j, x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL)) { status=MagickFalse; continue; } (void) ResetMagickMemory(channel_distortion,0,sizeof(channel_distortion)); for (x=0; x < (ssize_t) columns; x++) { double Da, Sa; register ssize_t i; if ((GetPixelReadMask(image,p) <= (QuantumRange/2)) || (GetPixelReadMask(reconstruct_image,q) <= (QuantumRange/2))) { p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); continue; } Sa=QuantumScale*GetPixelAlpha(image,p); Da=QuantumScale*GetPixelAlpha(reconstruct_image,q); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double distance; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image, channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; if (channel == AlphaPixelChannel) distance=QuantumScale*fabs((double) p[i]- GetPixelChannel(reconstruct_image,channel,q)); else distance=QuantumScale*fabs(Sa*p[i]-Da* GetPixelChannel(reconstruct_image,channel,q)); if (distance > channel_distortion[i]) channel_distortion[i]=distance; if (distance > channel_distortion[CompositePixelChannel]) channel_distortion[CompositePixelChannel]=distance; } p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GetPeakAbsoluteError) #endif for (j=0; j <= MaxPixelChannels; j++) if (channel_distortion[j] > distortion[j]) distortion[j]=channel_distortion[j]; } reconstruct_view=DestroyCacheView(reconstruct_view); image_view=DestroyCacheView(image_view); return(status); } static inline double MagickLog10(const double x) { #define Log10Epsilon (1.0e-11) if (fabs(x) < Log10Epsilon) return(log10(Log10Epsilon)); return(log10(fabs(x))); } static MagickBooleanType GetPeakSignalToNoiseRatio(const Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { MagickBooleanType status; register ssize_t i; status=GetMeanSquaredDistortion(image,reconstruct_image,distortion,exception); for (i=0; i <= MaxPixelChannels; i++) if (fabs(distortion[i]) < MagickEpsilon) distortion[i]=INFINITY; else distortion[i]=20.0*MagickLog10(1.0/sqrt(distortion[i])); return(status); } static MagickBooleanType GetPerceptualHashDistortion(const Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { ChannelPerceptualHash *channel_phash, *reconstruct_phash; const char *artifact; MagickBooleanType normalize; ssize_t channel; /* Compute perceptual hash in the sRGB colorspace. */ channel_phash=GetImagePerceptualHash(image,exception); if (channel_phash == (ChannelPerceptualHash *) NULL) return(MagickFalse); reconstruct_phash=GetImagePerceptualHash(reconstruct_image,exception); if (reconstruct_phash == (ChannelPerceptualHash *) NULL) { channel_phash=(ChannelPerceptualHash *) RelinquishMagickMemory( channel_phash); return(MagickFalse); } artifact=GetImageArtifact(image,"phash:normalize"); normalize=(artifact == (const char *) NULL) || (IsStringTrue(artifact) == MagickFalse) ? MagickFalse : MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) #endif for (channel=0; channel < MaxPixelChannels; channel++) { double difference; register ssize_t i; difference=0.0; for (i=0; i < MaximumNumberOfImageMoments; i++) { double alpha, beta; register ssize_t j; for (j=0; j < (ssize_t) channel_phash[0].number_colorspaces; j++) { alpha=channel_phash[channel].phash[j][i]; beta=reconstruct_phash[channel].phash[j][i]; if (normalize == MagickFalse) difference+=(beta-alpha)*(beta-alpha); else difference=sqrt((beta-alpha)*(beta-alpha)/ channel_phash[0].number_channels); } } distortion[channel]+=difference; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GetPerceptualHashDistortion) #endif distortion[CompositePixelChannel]+=difference; } /* Free resources. */ reconstruct_phash=(ChannelPerceptualHash *) RelinquishMagickMemory( reconstruct_phash); channel_phash=(ChannelPerceptualHash *) RelinquishMagickMemory(channel_phash); return(MagickTrue); } static MagickBooleanType GetRootMeanSquaredDistortion(const Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { MagickBooleanType status; register ssize_t i; status=GetMeanSquaredDistortion(image,reconstruct_image,distortion,exception); for (i=0; i <= MaxPixelChannels; i++) distortion[i]=sqrt(distortion[i]); return(status); } static MagickBooleanType GetStructuralSimilarityDistortion(const Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { #define SSIMRadius 5.0 #define SSIMSigma 1.5 #define SSIMBlocksize 8 #define SSIMK1 0.01 #define SSIMK2 0.03 #define SSIML 1.0 CacheView *image_view, *reconstruct_view; char geometry[MagickPathExtent]; const char *artifact; double c1, c2, radius, sigma; KernelInfo *kernel_info; MagickBooleanType status; register ssize_t i; size_t columns, rows; ssize_t y; /* Compute structural similarity index @ https://en.wikipedia.org/wiki/Structural_similarity. */ radius=SSIMRadius; artifact=GetImageArtifact(image,"compare:ssim-radius"); if (artifact != (const char *) NULL) radius=StringToDouble(artifact,(char **) NULL); sigma=SSIMSigma; artifact=GetImageArtifact(image,"compare:ssim-sigma"); if (artifact != (const char *) NULL) sigma=StringToDouble(artifact,(char **) NULL); (void) FormatLocaleString(geometry,MagickPathExtent,"gaussian:%.20gx%.20g", radius,sigma); kernel_info=AcquireKernelInfo(geometry,exception); if (kernel_info == (KernelInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); c1=pow(SSIMK1*SSIML,2.0); artifact=GetImageArtifact(image,"compare:ssim-k1"); if (artifact != (const char *) NULL) c1=pow(StringToDouble(artifact,(char **) NULL)*SSIML,2.0); c2=pow(SSIMK2*SSIML,2.0); artifact=GetImageArtifact(image,"compare:ssim-k2"); if (artifact != (const char *) NULL) c2=pow(StringToDouble(artifact,(char **) NULL)*SSIML,2.0); status=MagickTrue; rows=MagickMax(image->rows,reconstruct_image->rows); columns=MagickMax(image->columns,reconstruct_image->columns); image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_number_threads(image,reconstruct_image,rows,1) #endif for (y=0; y < (ssize_t) rows; y++) { double channel_distortion[MaxPixelChannels+1]; register const Quantum *magick_restrict p, *magick_restrict q; register ssize_t i, x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) kernel_info->width/2L),y- ((ssize_t) kernel_info->height/2L),columns+kernel_info->width, kernel_info->height,exception); q=GetCacheViewVirtualPixels(reconstruct_view,-((ssize_t) kernel_info->width/ 2L),y-((ssize_t) kernel_info->height/2L),columns+kernel_info->width, kernel_info->height,exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL)) { status=MagickFalse; continue; } (void) ResetMagickMemory(channel_distortion,0,sizeof(channel_distortion)); for (x=0; x < (ssize_t) columns; x++) { double x_pixel_mu[MaxPixelChannels+1], x_pixel_sigma_squared[MaxPixelChannels+1], xy_sigma[MaxPixelChannels+1], y_pixel_mu[MaxPixelChannels+1], y_pixel_sigma_squared[MaxPixelChannels+1]; register const Quantum *magick_restrict reference, *magick_restrict target; register double *k; ssize_t v; (void) ResetMagickMemory(x_pixel_mu,0,sizeof(x_pixel_mu)); (void) ResetMagickMemory(x_pixel_sigma_squared,0, sizeof(x_pixel_sigma_squared)); (void) ResetMagickMemory(xy_sigma,0,sizeof(xy_sigma)); (void) ResetMagickMemory(x_pixel_sigma_squared,0, sizeof(y_pixel_sigma_squared)); (void) ResetMagickMemory(y_pixel_mu,0,sizeof(y_pixel_mu)); (void) ResetMagickMemory(y_pixel_sigma_squared,0, sizeof(y_pixel_sigma_squared)); k=kernel_info->values; reference=p; target=q; for (v=0; v < (ssize_t) kernel_info->height; v++) { register ssize_t u; for (u=0; u < (ssize_t) kernel_info->width; u++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double x_pixel, y_pixel; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits = GetPixelChannelTraits( reconstruct_image,channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; x_pixel=QuantumScale*reference[i]; x_pixel_mu[i]+=(*k)*x_pixel; x_pixel_sigma_squared[i]+=(*k)*x_pixel*x_pixel; y_pixel=QuantumScale* GetPixelChannel(reconstruct_image,channel,target); y_pixel_mu[i]+=(*k)*y_pixel; y_pixel_sigma_squared[i]+=(*k)*y_pixel*y_pixel; xy_sigma[i]+=(*k)*x_pixel*y_pixel; } k++; reference+=GetPixelChannels(image); target+=GetPixelChannels(reconstruct_image); } reference+=GetPixelChannels(image)*columns; target+=GetPixelChannels(reconstruct_image)*columns; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double ssim, x_pixel_mu_squared, x_pixel_sigmas_squared, xy_mu, xy_sigmas, y_pixel_mu_squared, y_pixel_sigmas_squared; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits = GetPixelChannelTraits( reconstruct_image,channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; x_pixel_mu_squared=x_pixel_mu[i]*x_pixel_mu[i]; y_pixel_mu_squared=y_pixel_mu[i]*y_pixel_mu[i]; xy_mu=x_pixel_mu[i]*y_pixel_mu[i]; xy_sigmas=xy_sigma[i]-xy_mu; x_pixel_sigmas_squared=x_pixel_sigma_squared[i]-x_pixel_mu_squared; y_pixel_sigmas_squared=y_pixel_sigma_squared[i]-y_pixel_mu_squared; ssim=((2.0*xy_mu+c1)*(2.0*xy_sigmas+c2))/ ((x_pixel_mu_squared+y_pixel_mu_squared+c1)* (x_pixel_sigmas_squared+y_pixel_sigmas_squared+c2)); channel_distortion[i]+=ssim; channel_distortion[CompositePixelChannel]+=ssim; } p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GetStructuralSimilarityDistortion) #endif for (i=0; i <= MaxPixelChannels; i++) distortion[i]+=channel_distortion[i]; } image_view=DestroyCacheView(image_view); reconstruct_view=DestroyCacheView(reconstruct_view); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits == UndefinedPixelTrait) || ((traits & UpdatePixelTrait) == 0)) continue; distortion[i]/=((double) columns*rows); } distortion[CompositePixelChannel]/=((double) columns*rows); distortion[CompositePixelChannel]/=(double) GetImageChannels(image); kernel_info=DestroyKernelInfo(kernel_info); return(status); } static MagickBooleanType GetStructuralDisimilarityDistortion(const Image *image, const Image *reconstruct_image,double *distortion,ExceptionInfo *exception) { MagickBooleanType status; register ssize_t i; status=GetStructuralSimilarityDistortion(image,reconstruct_image, distortion,exception); for (i=0; i <= MaxPixelChannels; i++) distortion[i]=(1.0-(distortion[i]))/2.0; return(status); } MagickExport MagickBooleanType GetImageDistortion(Image *image, const Image *reconstruct_image,const MetricType metric,double *distortion, ExceptionInfo *exception) { double *channel_distortion; MagickBooleanType status; size_t length; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(reconstruct_image != (const Image *) NULL); assert(reconstruct_image->signature == MagickCoreSignature); assert(distortion != (double *) NULL); *distortion=0.0; if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); /* Get image distortion. */ length=MaxPixelChannels+1; channel_distortion=(double *) AcquireQuantumMemory(length, sizeof(*channel_distortion)); if (channel_distortion == (double *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) ResetMagickMemory(channel_distortion,0,length* sizeof(*channel_distortion)); switch (metric) { case AbsoluteErrorMetric: { status=GetAbsoluteDistortion(image,reconstruct_image,channel_distortion, exception); break; } case FuzzErrorMetric: { status=GetFuzzDistortion(image,reconstruct_image,channel_distortion, exception); break; } case MeanAbsoluteErrorMetric: { status=GetMeanAbsoluteDistortion(image,reconstruct_image, channel_distortion,exception); break; } case MeanErrorPerPixelErrorMetric: { status=GetMeanErrorPerPixel(image,reconstruct_image,channel_distortion, exception); break; } case MeanSquaredErrorMetric: { status=GetMeanSquaredDistortion(image,reconstruct_image, channel_distortion,exception); break; } case NormalizedCrossCorrelationErrorMetric: default: { status=GetNormalizedCrossCorrelationDistortion(image,reconstruct_image, channel_distortion,exception); break; } case PeakAbsoluteErrorMetric: { status=GetPeakAbsoluteDistortion(image,reconstruct_image, channel_distortion,exception); break; } case PeakSignalToNoiseRatioErrorMetric: { status=GetPeakSignalToNoiseRatio(image,reconstruct_image, channel_distortion,exception); break; } case PerceptualHashErrorMetric: { status=GetPerceptualHashDistortion(image,reconstruct_image, channel_distortion,exception); break; } case RootMeanSquaredErrorMetric: { status=GetRootMeanSquaredDistortion(image,reconstruct_image, channel_distortion,exception); break; } case StructuralSimilarityErrorMetric: { status=GetStructuralSimilarityDistortion(image,reconstruct_image, channel_distortion,exception); break; } case StructuralDissimilarityErrorMetric: { status=GetStructuralDisimilarityDistortion(image,reconstruct_image, channel_distortion,exception); break; } } *distortion=channel_distortion[CompositePixelChannel]; channel_distortion=(double *) RelinquishMagickMemory(channel_distortion); (void) FormatImageProperty(image,"distortion","%.*g",GetMagickPrecision(), *distortion); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e D i s t o r t i o n s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageDistortions() compares the pixel channels of an image to a % reconstructed image and returns the specified distortion metric for each % channel. % % The format of the GetImageDistortions method is: % % double *GetImageDistortions(const Image *image, % const Image *reconstruct_image,const MetricType metric, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o reconstruct_image: the reconstruct image. % % o metric: the metric. % % o exception: return any errors or warnings in this structure. % */ MagickExport double *GetImageDistortions(Image *image, const Image *reconstruct_image,const MetricType metric, ExceptionInfo *exception) { double *channel_distortion; MagickBooleanType status; size_t length; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(reconstruct_image != (const Image *) NULL); assert(reconstruct_image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); /* Get image distortion. */ length=MaxPixelChannels+1UL; channel_distortion=(double *) AcquireQuantumMemory(length, sizeof(*channel_distortion)); if (channel_distortion == (double *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) ResetMagickMemory(channel_distortion,0,length* sizeof(*channel_distortion)); status=MagickTrue; switch (metric) { case AbsoluteErrorMetric: { status=GetAbsoluteDistortion(image,reconstruct_image,channel_distortion, exception); break; } case FuzzErrorMetric: { status=GetFuzzDistortion(image,reconstruct_image,channel_distortion, exception); break; } case MeanAbsoluteErrorMetric: { status=GetMeanAbsoluteDistortion(image,reconstruct_image, channel_distortion,exception); break; } case MeanErrorPerPixelErrorMetric: { status=GetMeanErrorPerPixel(image,reconstruct_image,channel_distortion, exception); break; } case MeanSquaredErrorMetric: { status=GetMeanSquaredDistortion(image,reconstruct_image, channel_distortion,exception); break; } case NormalizedCrossCorrelationErrorMetric: default: { status=GetNormalizedCrossCorrelationDistortion(image,reconstruct_image, channel_distortion,exception); break; } case PeakAbsoluteErrorMetric: { status=GetPeakAbsoluteDistortion(image,reconstruct_image, channel_distortion,exception); break; } case PeakSignalToNoiseRatioErrorMetric: { status=GetPeakSignalToNoiseRatio(image,reconstruct_image, channel_distortion,exception); break; } case PerceptualHashErrorMetric: { status=GetRootMeanSquaredDistortion(image,reconstruct_image, channel_distortion,exception); break; } case RootMeanSquaredErrorMetric: { status=GetRootMeanSquaredDistortion(image,reconstruct_image, channel_distortion,exception); break; } case StructuralSimilarityErrorMetric: { status=GetStructuralSimilarityDistortion(image,reconstruct_image, channel_distortion,exception); break; } case StructuralDissimilarityErrorMetric: { status=GetStructuralDisimilarityDistortion(image,reconstruct_image, channel_distortion,exception); break; } } if (status == MagickFalse) { channel_distortion=(double *) RelinquishMagickMemory(channel_distortion); return((double *) NULL); } return(channel_distortion); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s I m a g e s E q u a l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsImagesEqual() compare the pixels of two images and returns immediately % if any pixel is not identical. % % The format of the IsImagesEqual method is: % % MagickBooleanType IsImagesEqual(const Image *image, % const Image *reconstruct_image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o reconstruct_image: the reconstruct image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType IsImagesEqual(const Image *image, const Image *reconstruct_image,ExceptionInfo *exception) { CacheView *image_view, *reconstruct_view; size_t columns, rows; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(reconstruct_image != (const Image *) NULL); assert(reconstruct_image->signature == MagickCoreSignature); rows=MagickMax(image->rows,reconstruct_image->rows); columns=MagickMax(image->columns,reconstruct_image->columns); image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); for (y=0; y < (ssize_t) rows; y++) { register const Quantum *magick_restrict p, *magick_restrict q; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) columns; x++) { register ssize_t i; if (GetPixelWriteMask(image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double distance; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image, channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; distance=fabs(p[i]-(double) GetPixelChannel(reconstruct_image, channel,q)); if (distance >= MagickEpsilon) break; } if (i < (ssize_t) GetPixelChannels(image)) break; p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); } if (x < (ssize_t) columns) break; } reconstruct_view=DestroyCacheView(reconstruct_view); image_view=DestroyCacheView(image_view); return(y < (ssize_t) rows ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e C o l o r M e t r i c % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageColorMetric() measures the difference between colors at each pixel % location of two images. A value other than 0 means the colors match % exactly. Otherwise an error measure is computed by summing over all % pixels in an image the distance squared in RGB space between each image % pixel and its corresponding pixel in the reconstruct image. The error % measure is assigned to these image members: % % o mean_error_per_pixel: The mean error for any single pixel in % the image. % % o normalized_mean_error: The normalized mean quantization error for % any single pixel in the image. This distance measure is normalized to % a range between 0 and 1. It is independent of the range of red, green, % and blue values in the image. % % o normalized_maximum_error: The normalized maximum quantization % error for any single pixel in the image. This distance measure is % normalized to a range between 0 and 1. It is independent of the range % of red, green, and blue values in your image. % % A small normalized mean square error, accessed as % image->normalized_mean_error, suggests the images are very similar in % spatial layout and color. % % The format of the SetImageColorMetric method is: % % MagickBooleanType SetImageColorMetric(Image *image, % const Image *reconstruct_image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o reconstruct_image: the reconstruct image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageColorMetric(Image *image, const Image *reconstruct_image,ExceptionInfo *exception) { CacheView *image_view, *reconstruct_view; double area, maximum_error, mean_error, mean_error_per_pixel; MagickBooleanType status; size_t columns, rows; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(reconstruct_image != (const Image *) NULL); assert(reconstruct_image->signature == MagickCoreSignature); area=0.0; maximum_error=0.0; mean_error_per_pixel=0.0; mean_error=0.0; rows=MagickMax(image->rows,reconstruct_image->rows); columns=MagickMax(image->columns,reconstruct_image->columns); image_view=AcquireVirtualCacheView(image,exception); reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception); for (y=0; y < (ssize_t) rows; y++) { register const Quantum *magick_restrict p, *magick_restrict q; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception); q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) columns; x++) { register ssize_t i; if (GetPixelWriteMask(image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double distance; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image, channel); if ((traits == UndefinedPixelTrait) || (reconstruct_traits == UndefinedPixelTrait) || ((reconstruct_traits & UpdatePixelTrait) == 0)) continue; distance=fabs(p[i]-(double) GetPixelChannel(reconstruct_image, channel,q)); if (distance >= MagickEpsilon) { mean_error_per_pixel+=distance; mean_error+=distance*distance; if (distance > maximum_error) maximum_error=distance; } area++; } p+=GetPixelChannels(image); q+=GetPixelChannels(reconstruct_image); } } reconstruct_view=DestroyCacheView(reconstruct_view); image_view=DestroyCacheView(image_view); image->error.mean_error_per_pixel=(double) (mean_error_per_pixel/area); image->error.normalized_mean_error=(double) (QuantumScale*QuantumScale* mean_error/area); image->error.normalized_maximum_error=(double) (QuantumScale*maximum_error); status=image->error.mean_error_per_pixel == 0.0 ? MagickTrue : MagickFalse; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S i m i l a r i t y I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SimilarityImage() compares the reference image of the image and returns the % best match offset. In addition, it returns a similarity image such that an % exact match location is completely white and if none of the pixels match, % black, otherwise some gray level in-between. % % The format of the SimilarityImageImage method is: % % Image *SimilarityImage(const Image *image,const Image *reference, % const MetricType metric,const double similarity_threshold, % RectangleInfo *offset,double *similarity,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o reference: find an area of the image that closely resembles this image. % % o metric: the metric. % % o similarity_threshold: minimum distortion for (sub)image match. % % o offset: the best match offset of the reference image within the image. % % o similarity: the computed similarity between the images. % % o exception: return any errors or warnings in this structure. % */ static double GetSimilarityMetric(const Image *image,const Image *reference, const MetricType metric,const ssize_t x_offset,const ssize_t y_offset, ExceptionInfo *exception) { double distortion; Image *similarity_image; MagickBooleanType status; RectangleInfo geometry; SetGeometry(reference,&geometry); geometry.x=x_offset; geometry.y=y_offset; similarity_image=CropImage(image,&geometry,exception); if (similarity_image == (Image *) NULL) return(0.0); distortion=0.0; status=GetImageDistortion(similarity_image,reference,metric,&distortion, exception); similarity_image=DestroyImage(similarity_image); if (status == MagickFalse) return(0.0); return(distortion); } MagickExport Image *SimilarityImage(const Image *image,const Image *reference, const MetricType metric,const double similarity_threshold, RectangleInfo *offset,double *similarity_metric,ExceptionInfo *exception) { #define SimilarityImageTag "Similarity/Image" CacheView *similarity_view; Image *similarity_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); assert(offset != (RectangleInfo *) NULL); SetGeometry(reference,offset); *similarity_metric=MagickMaximumValue; similarity_image=CloneImage(image,image->columns-reference->columns+1, image->rows-reference->rows+1,MagickTrue,exception); if (similarity_image == (Image *) NULL) return((Image *) NULL); status=SetImageStorageClass(similarity_image,DirectClass,exception); if (status == MagickFalse) { similarity_image=DestroyImage(similarity_image); return((Image *) NULL); } (void) SetImageAlphaChannel(similarity_image,DeactivateAlphaChannel, exception); /* Measure similarity of reference image against image. */ status=MagickTrue; progress=0; similarity_view=AcquireAuthenticCacheView(similarity_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) \ shared(progress,status,similarity_metric) \ magick_number_threads(image,image,image->rows-reference->rows+1,1) #endif for (y=0; y < (ssize_t) (image->rows-reference->rows+1); y++) { double similarity; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp flush(similarity_metric) #endif if (*similarity_metric <= similarity_threshold) continue; q=GetCacheViewAuthenticPixels(similarity_view,0,y,similarity_image->columns, 1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) (image->columns-reference->columns+1); x++) { register ssize_t i; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp flush(similarity_metric) #endif if (*similarity_metric <= similarity_threshold) break; similarity=GetSimilarityMetric(image,reference,metric,x,y,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_SimilarityImage) #endif if ((metric == NormalizedCrossCorrelationErrorMetric) || (metric == UndefinedErrorMetric)) similarity=1.0-similarity; if (similarity < *similarity_metric) { offset->x=x; offset->y=y; *similarity_metric=similarity; } if (metric == PerceptualHashErrorMetric) similarity=MagickMin(0.01*similarity,1.0); if (GetPixelWriteMask(similarity_image,q) <= (QuantumRange/2)) { SetPixelBackgoundColor(similarity_image,q); q+=GetPixelChannels(similarity_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait similarity_traits=GetPixelChannelTraits(similarity_image, channel); if ((traits == UndefinedPixelTrait) || (similarity_traits == UndefinedPixelTrait) || ((similarity_traits & UpdatePixelTrait) == 0)) continue; SetPixelChannel(similarity_image,channel,ClampToQuantum(QuantumRange- QuantumRange*similarity),q); } q+=GetPixelChannels(similarity_image); } if (SyncCacheViewAuthenticPixels(similarity_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_SimilarityImage) #endif proceed=SetImageProgress(image,SimilarityImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } similarity_view=DestroyCacheView(similarity_view); if (status == MagickFalse) similarity_image=DestroyImage(similarity_image); return(similarity_image); }
Example_private.3.c
/* * @@name: private.3c * @@type: C * @@compilable: yes * @@linkable: no * @@expect: success */ #include <assert.h> void priv_example3() { int i, a; #pragma omp parallel private(a) { a = 1; #pragma omp parallel for private(a) for (i=0; i<10; i++) { a = 2; } assert(a == 1); } }
pmtv-OpenMP.c
/* * pmtv-OpenMP.c * * Created on: 04/05/2014 * Author: Carlos de la Torre */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #ifdef _OPENMP #include <omp.h> // biblioteca para programas paralelos #else #define omp_get_thread_num() 0 #endif #define PRINT_ALL_MIN 15 // Ponemos que los elementos mínimos para que se // impriman todos los valores de la matriz sea 15 #define NELEMENTOS(x) (sizeof(x) / sizeof(x[0])) // Con esto lo que hacemos es saber cual es el numero // de elementos de cualquier vector de C solo tenemos // que poner donde pone x el nombre del vector #define DEBUGMODE 1 // con esta definición nos aseguramos que solo // salgan las cifras de tiempo en cada ejecución // así de esa manera es mas fácil realizar el // estudio empírico del programa void error(char* param[]){ printf("\n [USAGE]-%s [num iteraciones] [planificación] [num chunk] [num hebras]\n" " para mas información %s --help\n\n", param[0],param[0]); if (param[1]==NULL){ fprintf(stderr, " [ERROR]-Falta iteraciones\n"); exit(-1); }else if (param[2]==NULL){ fprintf(stderr, " [ERROR]-Falta modo de planificación: static, dynamic, guided\n"); exit(-1); }else if (param[3]==NULL){ fprintf(stderr, " [ERROR]-Falta chunk\n"); exit(-1); } // }else if (argv[4]==NULL){ // fprintf(stderr, " [ERROR]-Falta numero de hebras\n"); // exit(-1); // } exit(-1); } int main(int argc, char* argv[]) { int f,c,N; char planificacion[10], chunk[2]="", hebras[2], tmp[6], help[6]="--help"; char statics[9]="static", dynamic[10]="dynamic", guided[9]="guided"; double tr, t1, t2; if (argc!=2 && argc!=3 && argc!=4 && argc!=5){ error(argv); }else if (argc==2){ if (getenv("OMP_SCHEDULE")!=NULL){ N = atoi(argv[1]); // Este sera el tamaño del vector y de las filas/columnas de la matriz snprintf(hebras, sizeof(int), "%d", omp_get_num_procs()); if (!strncmp(dynamic,getenv("OMP_SCHEDULE"),7)) setenv("OMP_DYNAMIC","TRUE",1); strcpy(planificacion,getenv("OMP_SCHEDULE")); }else{ strcpy(tmp,argv[1]); if (!strncmp(tmp,help,6)){ printf("\n [USAGE]-%s [num iteraciones] [planificación] [num chunk] [num hebras]\n\n" " Tambien se puede utilizar la variable de entorno\n" " OMP_SCHEDULE para modificar la planificación\n\n" " Ejemplos:\n" " export OMP_SCHEDULE=\"static,4\"\n" " %s 10 la cantidad de hebras se asignará según el número de cores\n\n O\n" " %s 10 dynamic 4 4\n\n",argv[0],argv[0],argv[0]); exit(-1); }else error(argv); } }else if (argc==3){ N = atoi(argv[1]); // Este sera el tamaño del vector y de las filas/columnas de la matriz strcpy(planificacion,argv[2]); // Esto es para poder capturar el texto desde consola sprintf(hebras,"%d",12); }else if (argc==4){ N = atoi(argv[1]); // Este sera el tamaño del vector y de las filas/columnas de la matriz strcpy(planificacion,argv[2]); // Esto es para poder capturar el texto desde consola strcpy(chunk,argv[3]); // Cual es el chunk del programa sprintf(hebras,"%d",omp_get_num_procs()); }else if (argc==5){ N = atoi(argv[1]); // Este sera el tamaño del vector y de las filas/columnas de la matriz strcpy(planificacion,argv[2]); // Esto es para poder capturar el texto desde consola strcpy(chunk,argv[3]); // Cual es el chunk del programa strcpy(hebras,argv[4]); } /* He elegido esta manera de asignar los valores al programa por que en OMP * en la escala de prioridad esta es la segunda opción osea que la unica * manera de poder cambiar la planificación del programa sería editando * el codigo y utilizando un if. */ if (!strcmp(statics,planificacion)){ // ponemos ! por que si las cadenas son iguales el valor es 0 if (strcmp(chunk,"")){ strcat(statics,","); strcat(statics,chunk); } setenv("OMP_SCHEDULE",statics,1); // Elegimos como queremos la planificación de bucles }else if (!strcmp(dynamic,planificacion)){ if (strcmp(chunk,"")){ strcat(dynamic,","); strcat(dynamic,chunk); } setenv("OMP_SCHEDULE",dynamic,1); // Elegimos como queremos la planificación de bucles setenv("OMP_DYNAMIC","TRUE",1); // Seteamos a true el ajuste dinámico del nº de threads }else if (!strcmp(guided,planificacion)){ if (strcmp(chunk,"")){ strcat(guided,","); strcat(guided,chunk); } setenv("OMP_SCHEDULE",guided,1); // Elegimos como queremos la planificación de bucles } setenv("OMP_NUM_THREADS",hebras,1); // Seteamos el nº de threads en la siguiente ejecución paralela int *vector, *Vresultado; int **MatrizTri; MatrizTri = (int**) malloc(N * sizeof(int*)); for (f = 0; f < N; f++) MatrizTri[f] = (int*) malloc(N * sizeof(int)); vector = (int*) malloc(N * sizeof(int)); //si no hay espacio suficiente malloc devuelve NULL Vresultado = (int*) malloc(N * sizeof(int)); if ((MatrizTri == NULL) || (vector == NULL) || (Vresultado == NULL)) { printf("Error en la reserva de espacio para los Vectores o MatrizTri\n"); exit(-2); } srand(time(NULL)); // esta es la semilla que se usa para los random #pragma omp parallel for schedule(runtime) private(f,c) shared(MatrizTri,vector)// Inicializamos la Matriz y el vector for(f = 0; f < N; f++){ for(c = 0; c < N; c++){ if(f > c) // <---- Cambiando el sentido del simbolo la matriz es superior o inferior MatrizTri[f][c]=rand()%10; else MatrizTri[f][c]=0; } vector[f] = rand()%10; } // imprimimos la matriz y el vector si el tamaño de N < PRINT_ALL_MIN if (N <= PRINT_ALL_MIN && DEBUGMODE!=1){ printf ("\nEsta es la matriz: \n"); for (f = 0; f < N; f++){ for (c = 0; c < N; c++){ printf ("%d ",MatrizTri[f][c]); } printf ("\n"); } printf ("\nEste es el vector: \n"); for (f = 0; f < N; f++) printf ("%d ",vector[f]); printf("\n\n"); } t1 = omp_get_wtime(); // Calcular la multiplicación de una matriz por un vector #pragma omp parallel shared(MatrizTri,vector,Vresultado) { #pragma omp for schedule(runtime) private(f,c) for (f = 0; f < N; f++){ for (c = 0; c < N; c++) Vresultado[f] += MatrizTri[f][c]*vector[c]; } #pragma omp master if (omp_in_parallel()) printf("Valores de las variables de control dentro del parallel:\n" " dyn-var: %s\n" " nthreads-var: %s\n" " thread-limit-var: %s\n" " nest-var: %s\n" " run-sched-var: %s\n",getenv("OMP_DYNAMIC"),getenv("OMP_NUM_THREADS"), getenv("OMP_THREAD_LIMIT"),getenv("OMP_NESTED"),getenv("OMP_SCHEDULE")); } t2 = omp_get_wtime(); tr = t2 - t1; // Calculo el tiempo que he tardado en multiplicarlo // Ahora imprimimos por pantalla los resultados obtenidos segun las restricciones del problema if (N <= PRINT_ALL_MIN){ // si queremos imprimir datos completos y N < PRINT_ALL_MIN printf("Tiempo(seg.):%11.9f\nTamaño Matriz y Vector:%u\n",tr,N); printf ("Este es el vector resultante: \n"); printf("{"); for (f = 0; f < N; f++){ if (f==N-1) printf ("VR[%d]=%d",f,Vresultado[f]); else printf ("VR[%d]=%d, ",f,Vresultado[f]); } printf("}\n"); }else if (DEBUGMODE==1) // si queremos imprimir unicamente el tiempo de cálculo printf("%11.9f\n",tr);// else{ // y si queremos imprimir el tiempo la primera y la ultima multiplicacón printf("Tiempo(seg.):%11.9f\n",tr); printf("Tamaño Matriz y Vector:%u\n",N); printf("(Matriz[0][0]=%d)*(Vector[0]=%d)=%d\n",MatrizTri[0][0],vector[0],MatrizTri[0][0]*vector[0]); printf("(Matriz[%d][%d]=%d)*(Vector[%d]=%d)=%d\n",N-1,N-1,MatrizTri[N-1][N-1],N-1,vector[N-1],MatrizTri[N-1][N-1]*vector[N-1]); } free(vector); free(Vresultado); for(f=0; f<N; f++) free(MatrizTri[f]); free(MatrizTri); return 0; }
resize.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % RRRR EEEEE SSSSS IIIII ZZZZZ EEEEE % % R R E SS I ZZ E % % RRRR EEE SSS I ZZZ EEE % % R R E SS I ZZ E % % R R EEEEE SSSSS IIIII ZZZZZ EEEEE % % % % % % MagickCore Image Resize Methods % % % % Software Design % % John Cristy % % July 1992 % % % % % % Copyright 1999-2011 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/blob.h" #include "magick/cache.h" #include "magick/cache-view.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/draw.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/gem.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/memory_.h" #include "magick/magick.h" #include "magick/pixel-private.h" #include "magick/property.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel.h" #include "magick/option.h" #include "magick/resample.h" #include "magick/resample-private.h" #include "magick/resize.h" #include "magick/resize-private.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #include "magick/utility.h" #include "magick/version.h" #if defined(MAGICKCORE_LQR_DELEGATE) #include <lqr.h> #endif /* Typedef declarations. */ struct _ResizeFilter { MagickRealType (*filter)(const MagickRealType,const ResizeFilter *), (*window)(const MagickRealType,const ResizeFilter *), support, /* filter region of support - the filter support limit */ window_support, /* window support, usally equal to support (expert only) */ scale, /* dimension scaling to fit window support (usally 1.0) */ blur, /* x-scale (blur-sharpen) */ coefficient[7]; /* cubic coefficents for BC-cubic spline filters */ size_t signature; }; /* Forward declaractions. */ static MagickRealType I0(MagickRealType x), BesselOrderOne(MagickRealType), Sinc(const MagickRealType, const ResizeFilter *), SincFast(const MagickRealType, const ResizeFilter *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + F i l t e r F u n c t i o n s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % These are the various filter and windowing functions that are provided. % % They are internal to this module only. See AcquireResizeFilterInfo() for % details of the access to these functions, via the GetResizeFilterSupport() % and GetResizeFilterWeight() API interface. % % The individual filter functions have this format... % % static MagickRealtype *FilterName(const MagickRealType x, % const MagickRealType support) % % A description of each parameter follows: % % o x: the distance from the sampling point generally in the range of 0 to % support. The GetResizeFilterWeight() ensures this a positive value. % % o resize_filter: current filter information. This allows function to % access support, and possibly other pre-calculated information defining % the functions. % */ #define MagickPIL ((MagickRealType) 3.14159265358979323846264338327950288420L) static MagickRealType Jinc(const MagickRealType x, const ResizeFilter *magick_unused(resize_filter)) { /* See Pratt "Digital Image Processing" p.97 for Jinc/Bessel functions. http://mathworld.wolfram.com/JincFunction.html and page 11 of http://www.ph.ed.ac.uk/%7ewjh/teaching/mo/slides/lens/lens.pdf The original "zoom" program by Paul Heckbert called this "Bessel". But really it is more accurately named "Jinc". */ if (x == 0.0) return(0.5*MagickPIL); return(BesselOrderOne(MagickPIL*x)/x); } static MagickRealType Blackman(const MagickRealType x, const ResizeFilter *magick_unused(resize_filter)) { /* Blackman: 2nd order cosine windowing function: 0.42 + 0.5 cos(pi x) + 0.08 cos(2pi x) Refactored by Chantal Racette and Nicolas Robidoux to one trig call and five flops. */ const MagickRealType cospix = cos((double) (MagickPIL*x)); return(0.34+cospix*(0.5+cospix*0.16)); } static MagickRealType Bohman(const MagickRealType x, const ResizeFilter *magick_unused(resize_filter)) { /* Bohman: 2rd Order cosine windowing function: (1-x) cos(pi x) + sin(pi x) / pi. Refactored by Nicolas Robidoux to one trig call, one sqrt call, and 7 flops, taking advantage of the fact that the support of Bohman is 1 (so that we know that sin(pi x) >= 0). */ const double cospix = cos((double) (MagickPIL*x)); const double sinpix = sqrt(1.0-cospix*cospix); return((1.0-x)*cospix+(1.0/MagickPIL)*sinpix); } static MagickRealType Box(const MagickRealType magick_unused(x), const ResizeFilter *magick_unused(resize_filter)) { /* A Box filter is a equal weighting function (all weights equal). DO NOT LIMIT results by support or resize point sampling will work as it requests points beyond its normal 0.0 support size. */ return(1.0); } static MagickRealType CubicBC(const MagickRealType x, const ResizeFilter *resize_filter) { /* Cubic Filters using B,C determined values: Mitchell-Netravali B= 1/3 C= 1/3 "Balanced" cubic spline filter Catmull-Rom B= 0 C= 1/2 Interpolatory and exact on linears Cubic B-Spline B= 1 C= 0 Spline approximation of Gaussian Hermite B= 0 C= 0 Spline with small support (= 1) See paper by Mitchell and Netravali, Reconstruction Filters in Computer Graphics Computer Graphics, Volume 22, Number 4, August 1988 http://www.cs.utexas.edu/users/fussell/courses/cs384g/lectures/mitchell/ Mitchell.pdf. Coefficents are determined from B,C values: P0 = ( 6 - 2*B )/6 = coeff[0] P1 = 0 P2 = (-18 +12*B + 6*C )/6 = coeff[1] P3 = ( 12 - 9*B - 6*C )/6 = coeff[2] Q0 = ( 8*B +24*C )/6 = coeff[3] Q1 = ( -12*B -48*C )/6 = coeff[4] Q2 = ( 6*B +30*C )/6 = coeff[5] Q3 = ( - 1*B - 6*C )/6 = coeff[6] which are used to define the filter: P0 + P1*x + P2*x^2 + P3*x^3 0 <= x < 1 Q0 + Q1*x + Q2*x^2 + Q3*x^3 1 <= x < 2 which ensures function is continuous in value and derivative (slope). */ if (x < 1.0) return(resize_filter->coefficient[0]+x*(x* (resize_filter->coefficient[1]+x*resize_filter->coefficient[2]))); if (x < 2.0) return(resize_filter->coefficient[3]+x*(resize_filter->coefficient[4]+x* (resize_filter->coefficient[5]+x*resize_filter->coefficient[6]))); return(0.0); } static MagickRealType Gaussian(const MagickRealType x, const ResizeFilter *resize_filter) { /* Gaussian with a fixed sigma = 1/2 Gaussian Formula (1D) ... exp( -(x^2)/((2.0*sigma^2) ) / sqrt(2*PI)sigma^2)) The constants are pre-calculated... exp( -coeff[0]*(x^2)) ) * coeff[1] However the multiplier coefficent (1) is not needed and not used. Gaussian Formula (2D) ... exp( -(x^2)/((2.0*sigma^2) ) / (PI*sigma^2) ) Note that it is only a change in the normalization multiplier which is not needed or used when gausian is used as a filter. This separates the gaussian 'sigma' value from the 'blur/support' settings allowing for its use in special 'small sigma' gaussians, without the filter 'missing' pixels because the support becomes too small. */ return(exp((double)(-resize_filter->coefficient[0]*x*x))); } static MagickRealType Hanning(const MagickRealType x, const ResizeFilter *magick_unused(resize_filter)) { /* Cosine window function: .5+.5cos(pi x). */ const MagickRealType cospix = cos((double) (MagickPIL*x)); return(0.5+0.5*cospix); } static MagickRealType Hamming(const MagickRealType x, const ResizeFilter *magick_unused(resize_filter)) { /* Offset cosine window function: .54 + .46 cos(pi x). */ const MagickRealType cospix = cos((double) (MagickPIL*x)); return(0.54+0.46*cospix); } static MagickRealType Kaiser(const MagickRealType x, const ResizeFilter *magick_unused(resize_filter)) { #define Alpha 6.5 #define I0A (1.0/I0(Alpha)) /* Kaiser Windowing Function (bessel windowing): Alpha is a free value from 5 to 8 (currently hardcoded to 6.5). Future: make alpha the IOA pre-calculation, an 'expert' setting. */ return(I0A*I0(Alpha*sqrt((double) (1.0-x*x)))); } static MagickRealType Lagrange(const MagickRealType x, const ResizeFilter *resize_filter) { MagickRealType value; register ssize_t i; ssize_t n, order; /* Lagrange piecewise polynomial fit of sinc: N is the 'order' of the lagrange function and depends on the overall support window size of the filter. That is: for a support of 2, it gives a lagrange-4 (piecewise cubic function). "n" identifies the piece of the piecewise polynomial. See Survey: Interpolation Methods, IEEE Transactions on Medical Imaging, Vol 18, No 11, November 1999, p1049-1075, -- Equation 27 on p1064. */ if (x > resize_filter->support) return(0.0); order=(ssize_t) (2.0*resize_filter->window_support); /* number of pieces */ /*n=(ssize_t)((1.0*order)/2.0+x); -- which piece does x belong to */ n = (ssize_t)(resize_filter->window_support + x); value=1.0f; for (i=0; i < order; i++) if (i != n) value*=(n-i-x)/(n-i); return(value); } static MagickRealType Quadratic(const MagickRealType x, const ResizeFilter *magick_unused(resize_filter)) { /* 2rd order (quadratic) B-Spline approximation of Gaussian. */ if (x < 0.5) return(0.75-x*x); if (x < 1.5) return(0.5*(x-1.5)*(x-1.5)); return(0.0); } static MagickRealType Sinc(const MagickRealType x, const ResizeFilter *magick_unused(resize_filter)) { /* Scaled sinc(x) function using a trig call: sinc(x) == sin(pi x)/(pi x). */ if (x != 0.0) { const MagickRealType pix = (MagickRealType) (MagickPIL*x); return(sin((double) pix)/pix); } return((MagickRealType) 1.0); } static MagickRealType SincFast(const MagickRealType x, const ResizeFilter *magick_unused(resize_filter)) { /* Approximations of the sinc function sin(pi x)/(pi x) over the interval [-4,4] constructed by Nicolas Robidoux and Chantal Racette with funding from the Natural Sciences and Engineering Research Council of Canada. Although the approximations are polynomials (for low order of approximation) and quotients of polynomials (for higher order of approximation) and consequently are similar in form to Taylor polynomials/Pade approximants, the approximations are computed with a completely different technique. Summary: These approximations are "the best" in terms of bang (accuracy) for the buck (flops). More specifically: Among the polynomial quotients that can be computed using a fixed number of flops (with a given "+ - * / budget"), the chosen polynomial quotient is the one closest to the approximated function with respect to maximum absolute relative error over the given interval. The Remez algorithm, as implemented in the boost library's minimax package, is the key to the construction: http://www.boost.org/doc/libs/1_36_0/libs/math/doc/... ...sf_and_dist/html/math_toolkit/backgrounders/remez.html */ /* If outside of the interval of approximation, use the standard trig formula. */ if (x > 4.0) { const MagickRealType pix = (MagickRealType) (MagickPIL*x); return(sin((double) pix)/pix); } { /* The approximations only depend on x^2 (sinc is an even function). */ const MagickRealType xx = x*x; #if MAGICKCORE_QUANTUM_DEPTH <= 8 /* Maximum absolute relative error 6.3e-6 < 1/2^17. */ const MagickRealType c0 = 0.173610016489197553621906385078711564924e-2L; const MagickRealType c1 = -0.384186115075660162081071290162149315834e-3L; const MagickRealType c2 = 0.393684603287860108352720146121813443561e-4L; const MagickRealType c3 = -0.248947210682259168029030370205389323899e-5L; const MagickRealType c4 = 0.107791837839662283066379987646635416692e-6L; const MagickRealType c5 = -0.324874073895735800961260474028013982211e-8L; const MagickRealType c6 = 0.628155216606695311524920882748052490116e-10L; const MagickRealType c7 = -0.586110644039348333520104379959307242711e-12L; const MagickRealType p = c0+xx*(c1+xx*(c2+xx*(c3+xx*(c4+xx*(c5+xx*(c6+xx*c7)))))); return((xx-1.0)*(xx-4.0)*(xx-9.0)*(xx-16.0)*p); #elif MAGICKCORE_QUANTUM_DEPTH <= 16 /* Max. abs. rel. error 2.2e-8 < 1/2^25. */ const MagickRealType c0 = 0.173611107357320220183368594093166520811e-2L; const MagickRealType c1 = -0.384240921114946632192116762889211361285e-3L; const MagickRealType c2 = 0.394201182359318128221229891724947048771e-4L; const MagickRealType c3 = -0.250963301609117217660068889165550534856e-5L; const MagickRealType c4 = 0.111902032818095784414237782071368805120e-6L; const MagickRealType c5 = -0.372895101408779549368465614321137048875e-8L; const MagickRealType c6 = 0.957694196677572570319816780188718518330e-10L; const MagickRealType c7 = -0.187208577776590710853865174371617338991e-11L; const MagickRealType c8 = 0.253524321426864752676094495396308636823e-13L; const MagickRealType c9 = -0.177084805010701112639035485248501049364e-15L; const MagickRealType p = c0+xx*(c1+xx*(c2+xx*(c3+xx*(c4+xx*(c5+xx*(c6+xx*(c7+xx*(c8+xx*c9)))))))); return((xx-1.0)*(xx-4.0)*(xx-9.0)*(xx-16.0)*p); #else /* Max. abs. rel. error 1.2e-12 < 1/2^39. */ const MagickRealType c0 = 0.173611111110910715186413700076827593074e-2L; const MagickRealType c1 = -0.289105544717893415815859968653611245425e-3L; const MagickRealType c2 = 0.206952161241815727624413291940849294025e-4L; const MagickRealType c3 = -0.834446180169727178193268528095341741698e-6L; const MagickRealType c4 = 0.207010104171026718629622453275917944941e-7L; const MagickRealType c5 = -0.319724784938507108101517564300855542655e-9L; const MagickRealType c6 = 0.288101675249103266147006509214934493930e-11L; const MagickRealType c7 = -0.118218971804934245819960233886876537953e-13L; const MagickRealType p = c0+xx*(c1+xx*(c2+xx*(c3+xx*(c4+xx*(c5+xx*(c6+xx*c7)))))); const MagickRealType d0 = 1.0L; const MagickRealType d1 = 0.547981619622284827495856984100563583948e-1L; const MagickRealType d2 = 0.134226268835357312626304688047086921806e-2L; const MagickRealType d3 = 0.178994697503371051002463656833597608689e-4L; const MagickRealType d4 = 0.114633394140438168641246022557689759090e-6L; const MagickRealType q = d0+xx*(d1+xx*(d2+xx*(d3+xx*d4))); return((xx-1.0)*(xx-4.0)*(xx-9.0)*(xx-16.0)/q*p); #endif } } static MagickRealType Triangle(const MagickRealType x, const ResizeFilter *magick_unused(resize_filter)) { /* 1st order (linear) B-Spline, bilinear interpolation, Tent 1D filter, or a Bartlett 2D Cone filter. Also used as a Bartlett Windowing function for Sinc(). */ if (x < 1.0) return(1.0-x); return(0.0); } static MagickRealType Welsh(const MagickRealType x, const ResizeFilter *magick_unused(resize_filter)) { /* Welsh parabolic windowing filter. */ if (x < 1.0) return(1.0-x*x); return(0.0); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e R e s i z e F i l t e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireResizeFilter() allocates the ResizeFilter structure. Choose from % these filters: % % FIR (Finite impulse Response) Filters % Box Triangle Quadratic % Cubic Hermite Catrom % Mitchell % % IIR (Infinite impulse Response) Filters % Gaussian Sinc Jinc (Bessel) % % Windowed Sinc/Jinc Filters % Blackman Hanning Hamming % Kaiser Lanczos % % Special purpose Filters % SincFast LanczosSharp Lanczos2D Lanczos2DSharp Robidoux % % The users "-filter" selection is used to lookup the default 'expert' % settings for that filter from a internal table. However any provided % 'expert' settings (see below) may override this selection. % % FIR filters are used as is, and are limited to that filters support window % (unless over-ridden). 'Gaussian' while classed as an IIR filter, is also % simply clipped by its support size (currently 1.5 or approximatally 3*sigma % as recommended by many references) % % The special a 'cylindrical' filter flag will promote the default 4-lobed % Windowed Sinc filter to a 3-lobed Windowed Jinc equivalent, which is better % suited to this style of image resampling. This typically happens when using % such a filter for images distortions. % % Directly requesting 'Sinc', 'Jinc' function as a filter will force the use % of function without any windowing, or promotion for cylindrical usage. This % is not recommended, except by image processing experts, especially as part % of expert option filter function selection. % % Two forms of the 'Sinc' function are available: Sinc and SincFast. Sinc is % computed using the traditional sin(pi*x)/(pi*x); it is selected if the user % specifically specifies the use of a Sinc filter. SincFast uses highly % accurate (and fast) polynomial (low Q) and rational (high Q) approximations, % and will be used by default in most cases. % % The Lanczos filter is a special 3-lobed Sinc-windowed Sinc filter (promoted % to Jinc-windowed Jinc for cylindrical (Elliptical Weighted Average) use). % The Sinc version is the most popular windowed filter. % % LanczosSharp is a slightly sharpened (blur=0.9812505644269356 < 1) form of % the Lanczos filter, specifically designed for EWA distortion (as a % Jinc-Jinc); it can also be used as a slightly sharper orthogonal Lanczos % (Sinc-Sinc) filter. The chosen blur value comes as close as possible to % satisfying the following condition without changing the character of the % corresponding EWA filter: % % 'No-Op' Vertical and Horizontal Line Preservation Condition: Images with % only vertical or horizontal features are preserved when performing 'no-op" % with EWA distortion. % % The Lanczos2 and Lanczos2Sharp filters are 2-lobe versions of the Lanczos % filters. The 'sharp' version uses a blur factor of 0.9549963639785485, % again chosen because the resulting EWA filter comes as close as possible to % satisfying the above condition. % % Robidoux is another filter tuned for EWA. It is the Keys cubic filter % defined by B=(228 - 108 sqrt(2))/199. Robidoux satisfies the "'No-Op' % Vertical and Horizontal Line Preservation Condition" exactly, and it % moderately blurs high frequency 'pixel-hash' patterns under no-op. It turns % out to be close to both Mitchell and Lanczos2Sharp. For example, its first % crossing is at (36 sqrt(2) + 123)/(72 sqrt(2) + 47), almost the same as the % first crossing of Mitchell and Lanczos2Sharp. % % 'EXPERT' OPTIONS: % % These artifact "defines" are not recommended for production use without % expert knowledge of resampling, filtering, and the effects they have on the % resulting resampled (resize ro distorted) image. % % They can be used to override any and all filter default, and it is % recommended you make good use of "filter:verbose" to make sure that the % overall effect of your selection (before and after) is as expected. % % "filter:verbose" controls whether to output the exact results of the % filter selections made, as well as plotting data for graphing the % resulting filter over the filters support range. % % "filter:filter" select the main function associated with this filter % name, as the weighting function of the filter. This can be used to % set a windowing function as a weighting function, for special % purposes, such as graphing. % % If a "filter:window" operation has not been provided, a 'Box' % windowing function will be set to denote that no windowing function is % being used. % % "filter:window" Select this windowing function for the filter. While any % filter could be used as a windowing function, using the 'first lobe' of % that filter over the whole support window, using a non-windowing % function is not advisible. If no weighting filter function is specifed % a 'SincFast' filter is used. % % "filter:lobes" Number of lobes to use for the Sinc/Jinc filter. This a % simpler method of setting filter support size that will correctly % handle the Sinc/Jinc switch for an operators filtering requirements. % Only integers should be given. % % "filter:support" Set the support size for filtering to the size given. % This not recommended for Sinc/Jinc windowed filters (lobes should be % used instead). This will override any 'filter:lobes' option. % % "filter:win-support" Scale windowing function to this size instead. This % causes the windowing (or self-windowing Lagrange filter) to act is if % the support window it much much larger than what is actually supplied % to the calling operator. The filter however is still clipped to the % real support size given, by the support range suppiled to the caller. % If unset this will equal the normal filter support size. % % "filter:blur" Scale the filter and support window by this amount. A value % > 1 will generally result in a more burred image with more ringing % effects, while a value <1 will sharpen the resulting image with more % aliasing effects. % % "filter:sigma" The sigma value to use for the Gaussian filter only. % Defaults to '1/2'. Using a different sigma effectively provides a % method of using the filter as a 'blur' convolution. Particularly when % using it for Distort. % % "filter:b" % "filter:c" Override the preset B,C values for a Cubic type of filter. % If only one of these are given it is assumes to be a 'Keys' type of % filter such that B+2C=1, where Keys 'alpha' value = C. % % Examples: % % Set a true un-windowed Sinc filter with 10 lobes (very slow): % -define filter:filter=Sinc % -define filter:lobes=8 % % Set an 8 lobe Lanczos (Sinc or Jinc) filter: % -filter Lanczos % -define filter:lobes=8 % % The format of the AcquireResizeFilter method is: % % ResizeFilter *AcquireResizeFilter(const Image *image, % const FilterTypes filter_type, const MagickBooleanType radial, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o filter: the filter type, defining a preset filter, window and support. % The artifact settings listed above will override those selections. % % o blur: blur the filter by this amount, use 1.0 if unknown. Image % artifact "filter:blur" will override this API call usage, including any % internal change (such as for cylindrical usage). % % o radial: use a 1D orthogonal filter (Sinc) or 2D cylindrical (radial) % filter (Jinc). % % o exception: return any errors or warnings in this structure. % */ MagickExport ResizeFilter *AcquireResizeFilter(const Image *image, const FilterTypes filter,const MagickRealType blur, const MagickBooleanType cylindrical,ExceptionInfo *exception) { const char *artifact; FilterTypes filter_type, window_type; MagickRealType B, C, sigma; register ResizeFilter *resize_filter; /* Table Mapping given Filter, into Weighting and Windowing functions. A 'Box' windowing function means its a simble non-windowed filter. An 'SincFast' filter function could be upgraded to a 'Jinc' filter if a "cylindrical", unless a 'Sinc' or 'SincFast' filter was specifically requested. WARNING: The order of this tabel must match the order of the FilterTypes enumeration specified in "resample.h", or the filter names will not match the filter being setup. You can check filter setups with the "filter:verbose" setting. */ static struct { FilterTypes filter, window; } const mapping[SentinelFilter] = { { UndefinedFilter, BoxFilter }, /* Undefined (default to Box) */ { PointFilter, BoxFilter }, /* SPECIAL: Nearest neighbour */ { BoxFilter, BoxFilter }, /* Box averaging filter */ { TriangleFilter, BoxFilter }, /* Linear interpolation filter */ { HermiteFilter, BoxFilter }, /* Hermite interpolation filter */ { SincFastFilter, HanningFilter }, /* Hanning -- cosine-sinc */ { SincFastFilter, HammingFilter }, /* Hamming -- '' variation */ { SincFastFilter, BlackmanFilter }, /* Blackman -- 2*cosine-sinc */ { GaussianFilter, BoxFilter }, /* Gaussian blur filter */ { QuadraticFilter, BoxFilter }, /* Quadratic Gaussian approx */ { CubicFilter, BoxFilter }, /* Cubic B-Spline */ { CatromFilter, BoxFilter }, /* Cubic-Keys interpolator */ { MitchellFilter, BoxFilter }, /* 'Ideal' Cubic-Keys filter */ { JincFilter, BoxFilter }, /* Raw 3-lobed Jinc function */ { SincFilter, BoxFilter }, /* Raw 4-lobed Sinc function */ { SincFastFilter, BoxFilter }, /* Raw fast sinc ("Pade"-type) */ { SincFastFilter, KaiserFilter }, /* Kaiser -- square root-sinc */ { SincFastFilter, WelshFilter }, /* Welsh -- parabolic-sinc */ { SincFastFilter, CubicFilter }, /* Parzen -- cubic-sinc */ { SincFastFilter, BohmanFilter }, /* Bohman -- 2*cosine-sinc */ { SincFastFilter, TriangleFilter }, /* Bartlett -- triangle-sinc */ { LagrangeFilter, BoxFilter }, /* Lagrange self-windowing */ { LanczosFilter, LanczosFilter }, /* Lanczos Sinc-Sinc filters */ { LanczosSharpFilter, LanczosSharpFilter }, /* | these require */ { Lanczos2Filter, Lanczos2Filter }, /* | special handling */ { Lanczos2SharpFilter,Lanczos2SharpFilter }, { RobidouxFilter, BoxFilter }, /* Cubic Keys tuned for EWA */ }; /* Table mapping the filter/window from the above table to an actual function. The default support size for that filter as a weighting function, the range to scale with to use that function as a sinc windowing function, (typ 1.0). Note that the filter_type -> function is 1 to 1 except for Sinc(), SincFast(), and CubicBC() functions, which may have multiple filter to function associations. See "filter:verbose" handling below for the function -> filter mapping. */ static struct { MagickRealType (*function)(const MagickRealType, const ResizeFilter*), lobes, /* Default lobes/support size of the weighting filter. */ scale, /* Support when function used as a windowing function Typically equal to the location of the first zero crossing. */ B,C; /* BC-spline coefficients, ignored if not a CubicBC filter. */ } const filters[SentinelFilter] = { { Box, 0.5, 0.5, 0.0, 0.0 }, /* Undefined (default to Box) */ { Box, 0.0, 0.5, 0.0, 0.0 }, /* Point (special handling) */ { Box, 0.5, 0.5, 0.0, 0.0 }, /* Box */ { Triangle, 1.0, 1.0, 0.0, 0.0 }, /* Triangle */ { CubicBC, 1.0, 1.0, 0.0, 0.0 }, /* Hermite (cubic B=C=0) */ { Hanning, 1.0, 1.0, 0.0, 0.0 }, /* Hanning, cosine window */ { Hamming, 1.0, 1.0, 0.0, 0.0 }, /* Hamming, '' variation */ { Blackman, 1.0, 1.0, 0.0, 0.0 }, /* Blackman, 2*cosine window */ { Gaussian, 2.0, 1.5, 0.0, 0.0 }, /* Gaussian */ { Quadratic, 1.5, 1.5, 0.0, 0.0 }, /* Quadratic gaussian */ { CubicBC, 2.0, 2.0, 1.0, 0.0 }, /* Cubic B-Spline (B=1,C=0) */ { CubicBC, 2.0, 1.0, 0.0, 0.5 }, /* Catmull-Rom (B=0,C=1/2) */ { CubicBC, 2.0, 8.0/7.0, 1./3., 1./3. }, /* Mitchell (B=C=1/3) */ { Jinc, 3.0, 1.2196698912665045, 0.0, 0.0 }, /* Raw 3-lobed Jinc */ { Sinc, 4.0, 1.0, 0.0, 0.0 }, /* Raw 4-lobed Sinc */ { SincFast, 4.0, 1.0, 0.0, 0.0 }, /* Raw fast sinc ("Pade"-type) */ { Kaiser, 1.0, 1.0, 0.0, 0.0 }, /* Kaiser (square root window) */ { Welsh, 1.0, 1.0, 0.0, 0.0 }, /* Welsh (parabolic window) */ { CubicBC, 2.0, 2.0, 1.0, 0.0 }, /* Parzen (B-Spline window) */ { Bohman, 1.0, 1.0, 0.0, 0.0 }, /* Bohman, 2*Cosine window */ { Triangle, 1.0, 1.0, 0.0, 0.0 }, /* Bartlett (triangle window) */ { Lagrange, 2.0, 1.0, 0.0, 0.0 }, /* Lagrange sinc approximation */ { SincFast, 3.0, 1.0, 0.0, 0.0 }, /* Lanczos, 3-lobed Sinc-Sinc */ { SincFast, 3.0, 1.0, 0.0, 0.0 }, /* lanczos, Sharpened */ { SincFast, 2.0, 1.0, 0.0, 0.0 }, /* Lanczos, 2-lobed */ { SincFast, 2.0, 1.0, 0.0, 0.0 }, /* Lanczos2, sharpened */ { CubicBC, 2.0, 1.1685777620836932, 0.37821575509399867, 0.31089212245300067 } /* Robidoux: Keys cubic close to Lanczos2D sharpened */ }; /* The known zero crossings of the Jinc() or more accurately the Jinc(x*PI) function being used as a filter. It is used by the "filter:lobes" expert setting and for 'lobes' for Jinc functions in the previous table. This way users do not have to deal with the highly irrational lobe sizes of the Jinc filter. Values taken from http://cose.math.bas.bg/webMathematica/webComputing/BesselZeros.jsp using Jv-function with v=1, then dividing by PI. */ static MagickRealType jinc_zeros[16] = { 1.2196698912665045, 2.2331305943815286, 3.2383154841662362, 4.2410628637960699, 5.2427643768701817, 6.2439216898644877, 7.244759868719957, 8.2453949139520427, 9.2458926849494673, 10.246293348754916, 11.246622794877883, 12.246898461138105, 13.247132522181061, 14.247333735806849, 15.2475085630373, 16.247661874700962 }; /* Allocate resize filter. */ assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(UndefinedFilter < filter && filter < SentinelFilter); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); resize_filter=(ResizeFilter *) AcquireMagickMemory(sizeof(*resize_filter)); if (resize_filter == (ResizeFilter *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); /* Defaults for the requested filter. */ filter_type=mapping[filter].filter; window_type=mapping[filter].window; resize_filter->blur = blur; /* function argument blur factor */ sigma = 0.5; /* guassian sigma of half a pixel by default */ /* Promote 1D Windowed Sinc Filters to a 2D Windowed Jinc filters */ if (cylindrical != MagickFalse && filter_type == SincFastFilter && filter != SincFastFilter ) filter_type=JincFilter; /* Expert filter setting override */ artifact=GetImageArtifact(image,"filter:filter"); if (artifact != (const char *) NULL) { ssize_t option; option=ParseCommandOption(MagickFilterOptions,MagickFalse,artifact); if ((UndefinedFilter < option) && (option < SentinelFilter)) { /* Raw filter request - no window function. */ filter_type=(FilterTypes) option; window_type=BoxFilter; } /* Filter override with a specific window function. */ artifact=GetImageArtifact(image,"filter:window"); if (artifact != (const char *) NULL) { option=ParseCommandOption(MagickFilterOptions,MagickFalse,artifact); if ((UndefinedFilter < option) && (option < SentinelFilter)) window_type=(FilterTypes) option; } } else { /* Window specified, but no filter function? Assume Sinc/Jinc. */ artifact=GetImageArtifact(image,"filter:window"); if (artifact != (const char *) NULL) { ssize_t option; option=ParseCommandOption(MagickFilterOptions,MagickFalse, artifact); if ((UndefinedFilter < option) && (option < SentinelFilter)) { filter_type=cylindrical != MagickFalse ? JincFilter : SincFastFilter; window_type=(FilterTypes) option; } } } /* Assign the real functions to use for the filters selected. */ resize_filter->filter=filters[filter_type].function; resize_filter->support=filters[filter_type].lobes; resize_filter->window=filters[window_type].function; resize_filter->scale=filters[window_type].scale; resize_filter->signature=MagickSignature; /* Filter Modifications for orthogonal/cylindrical usage */ if (cylindrical != MagickFalse) switch (filter_type) { case BoxFilter: /* Support for Cylindrical Box should be sqrt(2)/2 */ resize_filter->support=(MagickRealType) MagickSQ1_2; break; case LanczosFilter: case LanczosSharpFilter: case Lanczos2Filter: case Lanczos2SharpFilter: resize_filter->filter=filters[JincFilter].function; resize_filter->window=filters[JincFilter].function; resize_filter->scale=filters[JincFilter].scale; /* number of lobes (support window size) remain unchanged */ break; default: break; } /* Global Sharpening (regardless of orthoginal/cylindrical) */ switch (filter_type) { case LanczosSharpFilter: resize_filter->blur *= 0.9812505644269356; break; case Lanczos2SharpFilter: resize_filter->blur *= 0.9549963639785485; break; default: break; } /* ** Other Expert Option Modifications */ /* User Sigma Override - no support change */ artifact=GetImageArtifact(image,"filter:sigma"); if (artifact != (const char *) NULL) sigma=InterpretLocaleValue(artifact,(char **) NULL); /* Define coefficents for Gaussian */ if ( GaussianFilter ) { resize_filter->coefficient[0]=1.0/(2.0*sigma*sigma); resize_filter->coefficient[1]=(MagickRealType) (1.0/(Magick2PI*sigma* sigma)); /* Normalization Multiplier - unneeded for filters */ } /* Blur Override */ artifact=GetImageArtifact(image,"filter:blur"); if (artifact != (const char *) NULL) resize_filter->blur *= InterpretLocaleValue(artifact,(char **) NULL); if (resize_filter->blur < MagickEpsilon) resize_filter->blur=(MagickRealType) MagickEpsilon; /* Support Overrides */ artifact=GetImageArtifact(image,"filter:lobes"); if (artifact != (const char *) NULL) { ssize_t lobes; lobes=(ssize_t) StringToLong(artifact); if (lobes < 1) lobes=1; resize_filter->support=(MagickRealType) lobes; } /* Convert a Jinc function lobes value to a real support value */ if (resize_filter->filter == Jinc) { if (resize_filter->support > 16) resize_filter->support=jinc_zeros[15]; /* largest entry in table */ else resize_filter->support = jinc_zeros[((long)resize_filter->support)-1]; } /* expert override of the support setting */ artifact=GetImageArtifact(image,"filter:support"); if (artifact != (const char *) NULL) resize_filter->support=fabs(InterpretLocaleValue(artifact,(char **) NULL)); /* Scale windowing function separatally to the support 'clipping' window that calling operator is planning to actually use. (Expert override) */ resize_filter->window_support=resize_filter->support; /* default */ artifact=GetImageArtifact(image,"filter:win-support"); if (artifact != (const char *) NULL) resize_filter->window_support=fabs(InterpretLocaleValue(artifact,(char **) NULL)); /* Adjust window function scaling to match windowing support for weighting function. This avoids a division on every filter call. */ resize_filter->scale /= resize_filter->window_support; /* * Set Cubic Spline B,C values, calculate Cubic coefficients. */ B=0.0; C=0.0; if ((filters[filter_type].function == CubicBC) || (filters[window_type].function == CubicBC)) { B=filters[filter_type].B; C=filters[filter_type].C; if (filters[window_type].function == CubicBC) { B=filters[window_type].B; C=filters[window_type].C; } artifact=GetImageArtifact(image,"filter:b"); if (artifact != (const char *) NULL) { B=InterpretLocaleValue(artifact,(char **) NULL); C=(1.0-B)/2.0; /* Calculate C to get a Keys cubic filter. */ artifact=GetImageArtifact(image,"filter:c"); /* user C override */ if (artifact != (const char *) NULL) C=InterpretLocaleValue(artifact,(char **) NULL); } else { artifact=GetImageArtifact(image,"filter:c"); if (artifact != (const char *) NULL) { C=InterpretLocaleValue(artifact,(char **) NULL); B=1.0-2.0*C; /* Calculate B to get a Keys cubic filter. */ } } /* Convert B,C values into Cubic Coefficents. See CubicBC(). */ { const double twoB = B+B; resize_filter->coefficient[0]=1.0-(1.0/3.0)*B; resize_filter->coefficient[1]=-3.0+twoB+C; resize_filter->coefficient[2]=2.0-1.5*B-C; resize_filter->coefficient[3]=(4.0/3.0)*B+4.0*C; resize_filter->coefficient[4]=-8.0*C-twoB; resize_filter->coefficient[5]=B+5.0*C; resize_filter->coefficient[6]=(-1.0/6.0)*B-C; } } /* Expert Option Request for verbose details of the resulting filter. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp master { #endif artifact=GetImageArtifact(image,"filter:verbose"); if (IsMagickTrue(artifact)) { double support, x; /* Set the weighting function properly when the weighting function may not exactly match the filter of the same name. EG: a Point filter is really uses a Box weighting function with a different support than is typically used. */ if (resize_filter->filter == Box) filter_type=BoxFilter; if (resize_filter->filter == Sinc) filter_type=SincFilter; if (resize_filter->filter == SincFast) filter_type=SincFastFilter; if (resize_filter->filter == Jinc) filter_type=JincFilter; if (resize_filter->filter == CubicBC) filter_type=CubicFilter; if (resize_filter->window == Box) window_type=BoxFilter; if (resize_filter->window == Sinc) window_type=SincFilter; if (resize_filter->window == SincFast) window_type=SincFastFilter; if (resize_filter->window == Jinc) window_type=JincFilter; if (resize_filter->window == CubicBC) window_type=CubicFilter; /* Report Filter Details. */ support=GetResizeFilterSupport(resize_filter); /* practical_support */ (void) FormatLocaleFile(stdout,"# Resize Filter (for graphing)\n#\n"); (void) FormatLocaleFile(stdout,"# filter = %s\n", CommandOptionToMnemonic(MagickFilterOptions,filter_type)); (void) FormatLocaleFile(stdout,"# window = %s\n", CommandOptionToMnemonic(MagickFilterOptions, window_type)); (void) FormatLocaleFile(stdout,"# support = %.*g\n", GetMagickPrecision(),(double) resize_filter->support); (void) FormatLocaleFile(stdout,"# win-support = %.*g\n", GetMagickPrecision(),(double) resize_filter->window_support); (void) FormatLocaleFile(stdout,"# scale_blur = %.*g\n", GetMagickPrecision(), (double)resize_filter->blur); if ( filter_type == GaussianFilter ) (void) FormatLocaleFile(stdout,"# gaussian_sigma = %.*g\n", GetMagickPrecision(), (double)sigma); (void) FormatLocaleFile(stdout,"# practical_support = %.*g\n", GetMagickPrecision(), (double)support); if ( filter_type == CubicFilter || window_type == CubicFilter ) (void) FormatLocaleFile(stdout,"# B,C = %.*g,%.*g\n", GetMagickPrecision(),(double)B, GetMagickPrecision(),(double)C); (void) FormatLocaleFile(stdout,"\n"); /* Output values of resulting filter graph -- for graphing filter result. */ for (x=0.0; x <= support; x+=0.01f) (void) FormatLocaleFile(stdout,"%5.2lf\t%.*g\n",x,GetMagickPrecision(), (double) GetResizeFilterWeight(resize_filter,x)); /* A final value so gnuplot can graph the 'stop' properly. */ (void) FormatLocaleFile(stdout,"%5.2lf\t%.*g\n",support, GetMagickPrecision(),0.0); } /* Output the above once only for each image - remove setting */ (void) DeleteImageArtifact((Image *) image,"filter:verbose"); #if defined(MAGICKCORE_OPENMP_SUPPORT) } #endif return(resize_filter); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d a p t i v e R e s i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AdaptiveResizeImage() adaptively resize image with pixel resampling. % % The format of the AdaptiveResizeImage method is: % % Image *AdaptiveResizeImage(const Image *image,const size_t columns, % const size_t rows,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the resized image. % % o rows: the number of rows in the resized image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AdaptiveResizeImage(const Image *image, const size_t columns,const size_t rows,ExceptionInfo *exception) { #define AdaptiveResizeImageTag "Resize/Image" CacheView *image_view, *resize_view; Image *resize_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Adaptively resize image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); if ((columns == 0) || (rows == 0)) return((Image *) NULL); if ((columns == image->columns) && (rows == image->rows)) return(CloneImage(image,0,0,MagickTrue,exception)); resize_image=CloneImage(image,columns,rows,MagickTrue,exception); if (resize_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(resize_image,DirectClass) == MagickFalse) { InheritException(exception,&resize_image->exception); resize_image=DestroyImage(resize_image); return((Image *) NULL); } status=MagickTrue; progress=0; image_view=AcquireCacheView(image); resize_view=AcquireCacheView(resize_image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(progress,status) omp_throttle(1) #endif for (y=0; y < (ssize_t) resize_image->rows; y++) { MagickPixelPacket pixel; PointInfo offset; register IndexPacket *restrict resize_indexes; register PixelPacket *restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(resize_view,0,y,resize_image->columns,1, exception); if (q == (PixelPacket *) NULL) continue; resize_indexes=GetCacheViewAuthenticIndexQueue(resize_view); offset.y=((MagickRealType) (y+0.5)*image->rows/resize_image->rows); GetMagickPixelPacket(image,&pixel); for (x=0; x < (ssize_t) resize_image->columns; x++) { offset.x=((MagickRealType) (x+0.5)*image->columns/resize_image->columns); (void) InterpolateMagickPixelPacket(image,image_view, MeshInterpolatePixel,offset.x-0.5,offset.y-0.5,&pixel,exception); SetPixelPacket(resize_image,&pixel,q,resize_indexes+x); q++; } if (SyncCacheViewAuthenticPixels(resize_view,exception) == MagickFalse) continue; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_AdaptiveResizeImage) #endif proceed=SetImageProgress(image,AdaptiveResizeImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } resize_view=DestroyCacheView(resize_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) resize_image=DestroyImage(resize_image); return(resize_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + B e s s e l O r d e r O n e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BesselOrderOne() computes the Bessel function of x of the first kind of % order 0. This is used to create the Jinc() filter function below. % % Reduce x to |x| since j1(x)= -j1(-x), and for x in (0,8] % % j1(x) = x*j1(x); % % For x in (8,inf) % % j1(x) = sqrt(2/(pi*x))*(p1(x)*cos(x1)-q1(x)*sin(x1)) % % where x1 = x-3*pi/4. Compute sin(x1) and cos(x1) as follow: % % cos(x1) = cos(x)cos(3pi/4)+sin(x)sin(3pi/4) % = 1/sqrt(2) * (sin(x) - cos(x)) % sin(x1) = sin(x)cos(3pi/4)-cos(x)sin(3pi/4) % = -1/sqrt(2) * (sin(x) + cos(x)) % % The format of the BesselOrderOne method is: % % MagickRealType BesselOrderOne(MagickRealType x) % % A description of each parameter follows: % % o x: MagickRealType value. % */ #undef I0 static MagickRealType I0(MagickRealType x) { MagickRealType sum, t, y; register ssize_t i; /* Zeroth order Bessel function of the first kind. */ sum=1.0; y=x*x/4.0; t=y; for (i=2; t > MagickEpsilon; i++) { sum+=t; t*=y/((MagickRealType) i*i); } return(sum); } #undef J1 static MagickRealType J1(MagickRealType x) { MagickRealType p, q; register ssize_t i; static const double Pone[] = { 0.581199354001606143928050809e+21, -0.6672106568924916298020941484e+20, 0.2316433580634002297931815435e+19, -0.3588817569910106050743641413e+17, 0.2908795263834775409737601689e+15, -0.1322983480332126453125473247e+13, 0.3413234182301700539091292655e+10, -0.4695753530642995859767162166e+7, 0.270112271089232341485679099e+4 }, Qone[] = { 0.11623987080032122878585294e+22, 0.1185770712190320999837113348e+20, 0.6092061398917521746105196863e+17, 0.2081661221307607351240184229e+15, 0.5243710262167649715406728642e+12, 0.1013863514358673989967045588e+10, 0.1501793594998585505921097578e+7, 0.1606931573481487801970916749e+4, 0.1e+1 }; p=Pone[8]; q=Qone[8]; for (i=7; i >= 0; i--) { p=p*x*x+Pone[i]; q=q*x*x+Qone[i]; } return(p/q); } #undef P1 static MagickRealType P1(MagickRealType x) { MagickRealType p, q; register ssize_t i; static const double Pone[] = { 0.352246649133679798341724373e+5, 0.62758845247161281269005675e+5, 0.313539631109159574238669888e+5, 0.49854832060594338434500455e+4, 0.2111529182853962382105718e+3, 0.12571716929145341558495e+1 }, Qone[] = { 0.352246649133679798068390431e+5, 0.626943469593560511888833731e+5, 0.312404063819041039923015703e+5, 0.4930396490181088979386097e+4, 0.2030775189134759322293574e+3, 0.1e+1 }; p=Pone[5]; q=Qone[5]; for (i=4; i >= 0; i--) { p=p*(8.0/x)*(8.0/x)+Pone[i]; q=q*(8.0/x)*(8.0/x)+Qone[i]; } return(p/q); } #undef Q1 static MagickRealType Q1(MagickRealType x) { MagickRealType p, q; register ssize_t i; static const double Pone[] = { 0.3511751914303552822533318e+3, 0.7210391804904475039280863e+3, 0.4259873011654442389886993e+3, 0.831898957673850827325226e+2, 0.45681716295512267064405e+1, 0.3532840052740123642735e-1 }, Qone[] = { 0.74917374171809127714519505e+4, 0.154141773392650970499848051e+5, 0.91522317015169922705904727e+4, 0.18111867005523513506724158e+4, 0.1038187585462133728776636e+3, 0.1e+1 }; p=Pone[5]; q=Qone[5]; for (i=4; i >= 0; i--) { p=p*(8.0/x)*(8.0/x)+Pone[i]; q=q*(8.0/x)*(8.0/x)+Qone[i]; } return(p/q); } static MagickRealType BesselOrderOne(MagickRealType x) { MagickRealType p, q; if (x == 0.0) return(0.0); p=x; if (x < 0.0) x=(-x); if (x < 8.0) return(p*J1(x)); q=sqrt((double) (2.0/(MagickPI*x)))*(P1(x)*(1.0/sqrt(2.0)*(sin((double) x)- cos((double) x)))-8.0/x*Q1(x)*(-1.0/sqrt(2.0)*(sin((double) x)+ cos((double) x)))); if (p < 0.0) q=(-q); return(q); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y R e s i z e F i l t e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyResizeFilter() destroy the resize filter. % % The format of the DestroyResizeFilter method is: % % ResizeFilter *DestroyResizeFilter(ResizeFilter *resize_filter) % % A description of each parameter follows: % % o resize_filter: the resize filter. % */ MagickExport ResizeFilter *DestroyResizeFilter(ResizeFilter *resize_filter) { assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickSignature); resize_filter->signature=(~MagickSignature); resize_filter=(ResizeFilter *) RelinquishMagickMemory(resize_filter); return(resize_filter); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t R e s i z e F i l t e r S u p p o r t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetResizeFilterSupport() return the current support window size for this % filter. Note that this may have been enlarged by filter:blur factor. % % The format of the GetResizeFilterSupport method is: % % MagickRealType GetResizeFilterSupport(const ResizeFilter *resize_filter) % % A description of each parameter follows: % % o filter: Image filter to use. % */ MagickExport MagickRealType GetResizeFilterSupport( const ResizeFilter *resize_filter) { assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickSignature); return(resize_filter->support*resize_filter->blur); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t R e s i z e F i l t e r W e i g h t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetResizeFilterWeight evaluates the specified resize filter at the point x % which usally lies between zero and the filters current 'support' and % returns the weight of the filter function at that point. % % The format of the GetResizeFilterWeight method is: % % MagickRealType GetResizeFilterWeight(const ResizeFilter *resize_filter, % const MagickRealType x) % % A description of each parameter follows: % % o filter: the filter type. % % o x: the point. % */ MagickExport MagickRealType GetResizeFilterWeight( const ResizeFilter *resize_filter,const MagickRealType x) { MagickRealType scale, weight, x_blur; /* Windowing function - scale the weighting filter by this amount. */ assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickSignature); x_blur=fabs((double) x)/resize_filter->blur; /* X offset with blur scaling */ if ((resize_filter->window_support < MagickEpsilon) || (resize_filter->window == Box)) scale=1.0; /* Point or Box Filter -- avoid division by zero */ else { scale=resize_filter->scale; scale=resize_filter->window(x_blur*scale,resize_filter); } weight=scale*resize_filter->filter(x_blur,resize_filter); return(weight); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g n i f y I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagnifyImage() is a convenience method that scales an image proportionally % to twice its size. % % The format of the MagnifyImage method is: % % Image *MagnifyImage(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 *MagnifyImage(const Image *image,ExceptionInfo *exception) { Image *magnify_image; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); magnify_image=ResizeImage(image,2*image->columns,2*image->rows,CubicFilter, 1.0,exception); return(magnify_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M i n i f y I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MinifyImage() is a convenience method that scales an image proportionally % to half its size. % % The format of the MinifyImage method is: % % Image *MinifyImage(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 *MinifyImage(const Image *image,ExceptionInfo *exception) { Image *minify_image; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); minify_image=ResizeImage(image,image->columns/2,image->rows/2,CubicFilter,1.0, exception); return(minify_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s a m p l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResampleImage() resize image in terms of its pixel size, so that when % displayed at the given resolution it will be the same size in terms of % real world units as the original image at the original resolution. % % The format of the ResampleImage method is: % % Image *ResampleImage(Image *image,const double x_resolution, % const double y_resolution,const FilterTypes filter,const double blur, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image to be resized to fit the given resolution. % % o x_resolution: the new image x resolution. % % o y_resolution: the new image y resolution. % % o filter: Image filter to use. % % o blur: the blur factor where > 1 is blurry, < 1 is sharp. % */ MagickExport Image *ResampleImage(const Image *image,const double x_resolution, const double y_resolution,const FilterTypes filter,const double blur, ExceptionInfo *exception) { #define ResampleImageTag "Resample/Image" Image *resample_image; size_t height, width; /* Initialize sampled image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); width=(size_t) (x_resolution*image->columns/(image->x_resolution == 0.0 ? 72.0 : image->x_resolution)+0.5); height=(size_t) (y_resolution*image->rows/(image->y_resolution == 0.0 ? 72.0 : image->y_resolution)+0.5); resample_image=ResizeImage(image,width,height,filter,blur,exception); if (resample_image != (Image *) NULL) { resample_image->x_resolution=x_resolution; resample_image->y_resolution=y_resolution; } return(resample_image); } #if defined(MAGICKCORE_LQR_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i q u i d R e s c a l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LiquidRescaleImage() rescales image with seam carving. % % The format of the LiquidRescaleImage method is: % % Image *LiquidRescaleImage(const Image *image, % const size_t columns,const size_t rows, % const double delta_x,const double rigidity,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the rescaled image. % % o rows: the number of rows in the rescaled image. % % o delta_x: maximum seam transversal step (0 means straight seams). % % o rigidity: introduce a bias for non-straight seams (typically 0). % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *LiquidRescaleImage(const Image *image,const size_t columns, const size_t rows,const double delta_x,const double rigidity, ExceptionInfo *exception) { #define LiquidRescaleImageTag "Rescale/Image" CacheView *rescale_view; const char *map; guchar *packet; Image *rescale_image; int x, y; LqrCarver *carver; LqrRetVal lqr_status; MagickBooleanType status; MagickPixelPacket pixel; unsigned char *pixels; /* Liquid rescale image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); if ((columns == 0) || (rows == 0)) return((Image *) NULL); if ((columns == image->columns) && (rows == image->rows)) return(CloneImage(image,0,0,MagickTrue,exception)); if ((columns <= 2) || (rows <= 2)) return(ResizeImage(image,columns,rows,image->filter,image->blur,exception)); if ((columns >= (2*image->columns)) || (rows >= (2*image->rows))) { Image *resize_image; size_t height, width; /* Honor liquid resize size limitations. */ for (width=image->columns; columns >= (2*width-1); width*=2); for (height=image->rows; rows >= (2*height-1); height*=2); resize_image=ResizeImage(image,width,height,image->filter,image->blur, exception); if (resize_image == (Image *) NULL) return((Image *) NULL); rescale_image=LiquidRescaleImage(resize_image,columns,rows,delta_x, rigidity,exception); resize_image=DestroyImage(resize_image); return(rescale_image); } map="RGB"; if (image->matte == MagickFalse) map="RGBA"; if (image->colorspace == CMYKColorspace) { map="CMYK"; if (image->matte == MagickFalse) map="CMYKA"; } pixels=(unsigned char *) AcquireQuantumMemory(image->columns,image->rows* strlen(map)*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) return((Image *) NULL); status=ExportImagePixels(image,0,0,image->columns,image->rows,map,CharPixel, pixels,exception); if (status == MagickFalse) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } carver=lqr_carver_new(pixels,image->columns,image->rows,strlen(map)); if (carver == (LqrCarver *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } lqr_status=lqr_carver_init(carver,(int) delta_x,rigidity); lqr_status=lqr_carver_resize(carver,columns,rows); (void) lqr_status; rescale_image=CloneImage(image,lqr_carver_get_width(carver), lqr_carver_get_height(carver),MagickTrue,exception); if (rescale_image == (Image *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); return((Image *) NULL); } if (SetImageStorageClass(rescale_image,DirectClass) == MagickFalse) { InheritException(exception,&rescale_image->exception); rescale_image=DestroyImage(rescale_image); return((Image *) NULL); } GetMagickPixelPacket(rescale_image,&pixel); (void) lqr_carver_scan_reset(carver); rescale_view=AcquireCacheView(rescale_image); while (lqr_carver_scan(carver,&x,&y,&packet) != 0) { register IndexPacket *restrict rescale_indexes; register PixelPacket *restrict q; q=QueueCacheViewAuthenticPixels(rescale_view,x,y,1,1,exception); if (q == (PixelPacket *) NULL) break; rescale_indexes=GetCacheViewAuthenticIndexQueue(rescale_view); pixel.red=QuantumRange*(packet[0]/255.0); pixel.green=QuantumRange*(packet[1]/255.0); pixel.blue=QuantumRange*(packet[2]/255.0); if (image->colorspace != CMYKColorspace) { if (image->matte == MagickFalse) pixel.opacity=QuantumRange*(packet[3]/255.0); } else { pixel.index=QuantumRange*(packet[3]/255.0); if (image->matte == MagickFalse) pixel.opacity=QuantumRange*(packet[4]/255.0); } SetPixelPacket(rescale_image,&pixel,q,rescale_indexes); if (SyncCacheViewAuthenticPixels(rescale_view,exception) == MagickFalse) break; } rescale_view=DestroyCacheView(rescale_view); /* Relinquish resources. */ lqr_carver_destroy(carver); return(rescale_image); } #else MagickExport Image *LiquidRescaleImage(const Image *image, const size_t magick_unused(columns),const size_t magick_unused(rows), const double magick_unused(delta_x),const double magick_unused(rigidity), ExceptionInfo *exception) { assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); (void) ThrowMagickException(exception,GetMagickModule(),MissingDelegateError, "DelegateLibrarySupportNotBuiltIn","`%s' (LQR)",image->filename); return((Image *) NULL); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResizeImage() scales an image to the desired dimensions, using the given % filter (see AcquireFilterInfo()). % % If an undefined filter is given the filter defaults to Mitchell for a % colormapped image, a image with a matte channel, or if the image is % enlarged. Otherwise the filter defaults to a Lanczos. % % ResizeImage() was inspired by Paul Heckbert's "zoom" program. % % The format of the ResizeImage method is: % % Image *ResizeImage(Image *image,const size_t columns, % const size_t rows,const FilterTypes filter,const double blur, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the scaled image. % % o rows: the number of rows in the scaled image. % % o filter: Image filter to use. % % o blur: the blur factor where > 1 is blurry, < 1 is sharp. Typically set % this to 1.0. % % o exception: return any errors or warnings in this structure. % */ typedef struct _ContributionInfo { MagickRealType weight; ssize_t pixel; } ContributionInfo; static ContributionInfo **DestroyContributionThreadSet( ContributionInfo **contribution) { register ssize_t i; assert(contribution != (ContributionInfo **) NULL); for (i=0; i < (ssize_t) GetOpenMPMaximumThreads(); i++) if (contribution[i] != (ContributionInfo *) NULL) contribution[i]=(ContributionInfo *) RelinquishMagickMemory( contribution[i]); contribution=(ContributionInfo **) RelinquishMagickMemory(contribution); return(contribution); } static ContributionInfo **AcquireContributionThreadSet(const size_t count) { register ssize_t i; ContributionInfo **contribution; size_t number_threads; number_threads=GetOpenMPMaximumThreads(); contribution=(ContributionInfo **) AcquireQuantumMemory(number_threads, sizeof(*contribution)); if (contribution == (ContributionInfo **) NULL) return((ContributionInfo **) NULL); (void) ResetMagickMemory(contribution,0,number_threads*sizeof(*contribution)); for (i=0; i < (ssize_t) number_threads; i++) { contribution[i]=(ContributionInfo *) AcquireQuantumMemory(count, sizeof(**contribution)); if (contribution[i] == (ContributionInfo *) NULL) return(DestroyContributionThreadSet(contribution)); } return(contribution); } 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); } static MagickBooleanType HorizontalFilter(const ResizeFilter *resize_filter, const Image *image,Image *resize_image,const MagickRealType x_factor, const MagickSizeType span,MagickOffsetType *offset,ExceptionInfo *exception) { #define ResizeImageTag "Resize/Image" CacheView *image_view, *resize_view; ClassType storage_class; ContributionInfo **restrict contributions; MagickBooleanType status; MagickPixelPacket zero; MagickRealType scale, support; ssize_t x; /* Apply filter to resize horizontally from image to resize image. */ scale=MagickMax(1.0/x_factor+MagickEpsilon,1.0); support=scale*GetResizeFilterSupport(resize_filter); storage_class=support > 0.5 ? DirectClass : image->storage_class; if (SetImageStorageClass(resize_image,storage_class) == MagickFalse) { InheritException(exception,&resize_image->exception); return(MagickFalse); } if (support < 0.5) { /* Support too small even for nearest neighbour: Reduce to point sampling. */ support=(MagickRealType) 0.5; scale=1.0; } contributions=AcquireContributionThreadSet((size_t) (2.0*support+3.0)); if (contributions == (ContributionInfo **) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } status=MagickTrue; scale=1.0/scale; (void) ResetMagickMemory(&zero,0,sizeof(zero)); image_view=AcquireCacheView(image); resize_view=AcquireCacheView(resize_image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for shared(status) #endif for (x=0; x < (ssize_t) resize_image->columns; x++) { MagickRealType center, density; register const IndexPacket *restrict indexes; register const PixelPacket *restrict p; register ContributionInfo *restrict contribution; register IndexPacket *restrict resize_indexes; register PixelPacket *restrict q; register ssize_t y; ssize_t n, start, stop; if (status == MagickFalse) continue; center=(MagickRealType) (x+0.5)/x_factor; start=(ssize_t) MagickMax(center-support+0.5,0.0); stop=(ssize_t) MagickMin(center+support+0.5,(double) image->columns); density=0.0; contribution=contributions[GetOpenMPThreadId()]; for (n=0; n < (stop-start); n++) { contribution[n].pixel=start+n; contribution[n].weight=GetResizeFilterWeight(resize_filter,scale* ((MagickRealType) (start+n)-center+0.5)); density+=contribution[n].weight; } if ((density != 0.0) && (density != 1.0)) { register ssize_t i; /* Normalize. */ density=1.0/density; for (i=0; i < n; i++) contribution[i].weight*=density; } p=GetCacheViewVirtualPixels(image_view,contribution[0].pixel,0,(size_t) (contribution[n-1].pixel-contribution[0].pixel+1),image->rows,exception); q=QueueCacheViewAuthenticPixels(resize_view,x,0,1,resize_image->rows, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); resize_indexes=GetCacheViewAuthenticIndexQueue(resize_view); for (y=0; y < (ssize_t) resize_image->rows; y++) { MagickPixelPacket pixel; MagickRealType alpha; register ssize_t i; ssize_t j; pixel=zero; if (image->matte == MagickFalse) { for (i=0; i < n; i++) { j=y*(contribution[n-1].pixel-contribution[0].pixel+1)+ (contribution[i].pixel-contribution[0].pixel); alpha=contribution[i].weight; pixel.red+=alpha*GetRedPixelComponent(p+j); pixel.green+=alpha*GetGreenPixelComponent(p+j); pixel.blue+=alpha*GetBluePixelComponent(p+j); pixel.opacity+=alpha*GetOpacityPixelComponent(p+j); } SetRedPixelComponent(q,ClampToQuantum(pixel.red)); SetGreenPixelComponent(q,ClampToQuantum(pixel.green)); SetBluePixelComponent(q,ClampToQuantum(pixel.blue)); SetOpacityPixelComponent(q,ClampToQuantum(pixel.opacity)); if ((image->colorspace == CMYKColorspace) && (resize_image->colorspace == CMYKColorspace)) { for (i=0; i < n; i++) { j=y*(contribution[n-1].pixel-contribution[0].pixel+1)+ (contribution[i].pixel-contribution[0].pixel); alpha=contribution[i].weight; pixel.index+=alpha*GetIndexPixelComponent(indexes+j); } SetIndexPixelComponent(resize_indexes+y,ClampToQuantum( pixel.index)); } } else { MagickRealType gamma; gamma=0.0; for (i=0; i < n; i++) { j=y*(contribution[n-1].pixel-contribution[0].pixel+1)+ (contribution[i].pixel-contribution[0].pixel); alpha=contribution[i].weight*QuantumScale* GetAlphaPixelComponent(p+j); pixel.red+=alpha*GetRedPixelComponent(p+j); pixel.green+=alpha*GetGreenPixelComponent(p+j); pixel.blue+=alpha*GetBluePixelComponent(p+j); pixel.opacity+=contribution[i].weight*GetOpacityPixelComponent(p+j); gamma+=alpha; } gamma=1.0/(fabs((double) gamma) <= MagickEpsilon ? 1.0 : gamma); SetRedPixelComponent(q,ClampToQuantum(gamma*pixel.red)); SetGreenPixelComponent(q,ClampToQuantum(gamma*pixel.green)); SetBluePixelComponent(q,ClampToQuantum(gamma*pixel.blue)); SetOpacityPixelComponent(q,ClampToQuantum(pixel.opacity)); if ((image->colorspace == CMYKColorspace) && (resize_image->colorspace == CMYKColorspace)) { for (i=0; i < n; i++) { j=y*(contribution[n-1].pixel-contribution[0].pixel+1)+ (contribution[i].pixel-contribution[0].pixel); alpha=contribution[i].weight*QuantumScale* GetAlphaPixelComponent(p+j); pixel.index+=alpha*GetIndexPixelComponent(indexes+j); } SetIndexPixelComponent(resize_indexes+y,ClampToQuantum(gamma* pixel.index)); } } if ((resize_image->storage_class == PseudoClass) && (image->storage_class == PseudoClass)) { i=(ssize_t) (MagickMin(MagickMax(center,(double) start),(double) stop- 1.0)+0.5); j=y*(contribution[n-1].pixel-contribution[0].pixel+1)+ (contribution[i-start].pixel-contribution[0].pixel); SetIndexPixelComponent(resize_indexes+y,GetIndexPixelComponent( indexes+j)); } q++; } if (SyncCacheViewAuthenticPixels(resize_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_HorizontalFilter) #endif proceed=SetImageProgress(image,ResizeImageTag,(*offset)++,span); if (proceed == MagickFalse) status=MagickFalse; } } resize_view=DestroyCacheView(resize_view); image_view=DestroyCacheView(image_view); contributions=DestroyContributionThreadSet(contributions); return(status); } static MagickBooleanType VerticalFilter(const ResizeFilter *resize_filter, const Image *image,Image *resize_image,const MagickRealType y_factor, const MagickSizeType span,MagickOffsetType *offset,ExceptionInfo *exception) { CacheView *image_view, *resize_view; ClassType storage_class; ContributionInfo **restrict contributions; MagickBooleanType status; MagickPixelPacket zero; MagickRealType scale, support; ssize_t y; /* Apply filter to resize vertically from image to resize image. */ scale=MagickMax(1.0/y_factor+MagickEpsilon,1.0); support=scale*GetResizeFilterSupport(resize_filter); storage_class=support > 0.5 ? DirectClass : image->storage_class; if (SetImageStorageClass(resize_image,storage_class) == MagickFalse) { InheritException(exception,&resize_image->exception); return(MagickFalse); } if (support < 0.5) { /* Support too small even for nearest neighbour: Reduce to point sampling. */ support=(MagickRealType) 0.5; scale=1.0; } contributions=AcquireContributionThreadSet((size_t) (2.0*support+3.0)); if (contributions == (ContributionInfo **) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } status=MagickTrue; scale=1.0/scale; (void) ResetMagickMemory(&zero,0,sizeof(zero)); image_view=AcquireCacheView(image); resize_view=AcquireCacheView(resize_image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for shared(status) #endif for (y=0; y < (ssize_t) resize_image->rows; y++) { MagickRealType center, density; register const IndexPacket *restrict indexes; register const PixelPacket *restrict p; register ContributionInfo *restrict contribution; register IndexPacket *restrict resize_indexes; register PixelPacket *restrict q; register ssize_t x; ssize_t n, start, stop; if (status == MagickFalse) continue; center=(MagickRealType) (y+0.5)/y_factor; start=(ssize_t) MagickMax(center-support+0.5,0.0); stop=(ssize_t) MagickMin(center+support+0.5,(double) image->rows); density=0.0; contribution=contributions[GetOpenMPThreadId()]; for (n=0; n < (stop-start); n++) { contribution[n].pixel=start+n; contribution[n].weight=GetResizeFilterWeight(resize_filter,scale* ((MagickRealType) (start+n)-center+0.5)); density+=contribution[n].weight; } if ((density != 0.0) && (density != 1.0)) { register ssize_t i; /* Normalize. */ density=1.0/density; for (i=0; i < n; i++) contribution[i].weight*=density; } p=GetCacheViewVirtualPixels(image_view,0,contribution[0].pixel, image->columns,(size_t) (contribution[n-1].pixel-contribution[0].pixel+1), exception); q=QueueCacheViewAuthenticPixels(resize_view,0,y,resize_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); resize_indexes=GetCacheViewAuthenticIndexQueue(resize_view); for (x=0; x < (ssize_t) resize_image->columns; x++) { MagickPixelPacket pixel; MagickRealType alpha; register ssize_t i; ssize_t j; pixel=zero; if (image->matte == MagickFalse) { for (i=0; i < n; i++) { j=(ssize_t) ((contribution[i].pixel-contribution[0].pixel)* image->columns+x); alpha=contribution[i].weight; pixel.red+=alpha*GetRedPixelComponent(p+j); pixel.green+=alpha*GetGreenPixelComponent(p+j); pixel.blue+=alpha*GetBluePixelComponent(p+j); pixel.opacity+=alpha*GetOpacityPixelComponent(p+j); } SetRedPixelComponent(q,ClampToQuantum(pixel.red)); SetGreenPixelComponent(q,ClampToQuantum(pixel.green)); SetBluePixelComponent(q,ClampToQuantum(pixel.blue)); SetOpacityPixelComponent(q,ClampToQuantum(pixel.opacity)); if ((image->colorspace == CMYKColorspace) && (resize_image->colorspace == CMYKColorspace)) { for (i=0; i < n; i++) { j=(ssize_t) ((contribution[i].pixel-contribution[0].pixel)* image->columns+x); alpha=contribution[i].weight; pixel.index+=alpha*GetIndexPixelComponent(indexes+j); } SetIndexPixelComponent(resize_indexes+x,ClampToQuantum( pixel.index)); } } else { MagickRealType gamma; gamma=0.0; for (i=0; i < n; i++) { j=(ssize_t) ((contribution[i].pixel-contribution[0].pixel)* image->columns+x); alpha=contribution[i].weight*QuantumScale* GetAlphaPixelComponent(p+j); pixel.red+=alpha*GetRedPixelComponent(p+j); pixel.green+=alpha*GetGreenPixelComponent(p+j); pixel.blue+=alpha*GetBluePixelComponent(p+j); pixel.opacity+=contribution[i].weight*GetOpacityPixelComponent(p+j); gamma+=alpha; } gamma=1.0/(fabs((double) gamma) <= MagickEpsilon ? 1.0 : gamma); SetRedPixelComponent(q,ClampToQuantum(gamma*pixel.red)); SetGreenPixelComponent(q,ClampToQuantum(gamma*pixel.green)); SetBluePixelComponent(q,ClampToQuantum(gamma*pixel.blue)); SetOpacityPixelComponent(q,ClampToQuantum(pixel.opacity)); if ((image->colorspace == CMYKColorspace) && (resize_image->colorspace == CMYKColorspace)) { for (i=0; i < n; i++) { j=(ssize_t) ((contribution[i].pixel-contribution[0].pixel)* image->columns+x); alpha=contribution[i].weight*QuantumScale* GetAlphaPixelComponent(p+j); pixel.index+=alpha*GetIndexPixelComponent(indexes+j); } SetIndexPixelComponent(resize_indexes+x,ClampToQuantum(gamma* pixel.index)); } } if ((resize_image->storage_class == PseudoClass) && (image->storage_class == PseudoClass)) { i=(ssize_t) (MagickMin(MagickMax(center,(double) start),(double) stop- 1.0)+0.5); j=(ssize_t) ((contribution[i-start].pixel-contribution[0].pixel)* image->columns+x); SetIndexPixelComponent(resize_indexes+x, GetIndexPixelComponent(indexes+j)); } q++; } if (SyncCacheViewAuthenticPixels(resize_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_VerticalFilter) #endif proceed=SetImageProgress(image,ResizeImageTag,(*offset)++,span); if (proceed == MagickFalse) status=MagickFalse; } } resize_view=DestroyCacheView(resize_view); image_view=DestroyCacheView(image_view); contributions=DestroyContributionThreadSet(contributions); return(status); } MagickExport Image *ResizeImage(const Image *image,const size_t columns, const size_t rows,const FilterTypes filter,const double blur, ExceptionInfo *exception) { #define WorkLoadFactor 0.265 FilterTypes filter_type; Image *filter_image, *resize_image; MagickOffsetType offset; MagickRealType x_factor, y_factor; MagickSizeType span; MagickStatusType status; ResizeFilter *resize_filter; /* Acquire resize image. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); if ((columns == 0) || (rows == 0)) ThrowImageException(ImageError,"NegativeOrZeroImageSize"); if ((columns == image->columns) && (rows == image->rows) && (filter == UndefinedFilter) && (blur == 1.0)) return(CloneImage(image,0,0,MagickTrue,exception)); resize_image=CloneImage(image,columns,rows,MagickTrue,exception); if (resize_image == (Image *) NULL) return(resize_image); /* Acquire resize filter. */ x_factor=(MagickRealType) columns/(MagickRealType) image->columns; y_factor=(MagickRealType) rows/(MagickRealType) image->rows; if ((x_factor*y_factor) > WorkLoadFactor) filter_image=CloneImage(image,columns,image->rows,MagickTrue,exception); else filter_image=CloneImage(image,image->columns,rows,MagickTrue,exception); if (filter_image == (Image *) NULL) return(DestroyImage(resize_image)); filter_type=LanczosFilter; if (filter != UndefinedFilter) filter_type=filter; else if ((x_factor == 1.0) && (y_factor == 1.0)) filter_type=PointFilter; else if ((image->storage_class == PseudoClass) || (image->matte != MagickFalse) || ((x_factor*y_factor) > 1.0)) filter_type=MitchellFilter; resize_filter=AcquireResizeFilter(image,filter_type,blur,MagickFalse, exception); /* Resize image. */ offset=0; if ((x_factor*y_factor) > WorkLoadFactor) { span=(MagickSizeType) (filter_image->columns+rows); status=HorizontalFilter(resize_filter,image,filter_image,x_factor,span, &offset,exception); status&=VerticalFilter(resize_filter,filter_image,resize_image,y_factor, span,&offset,exception); } else { span=(MagickSizeType) (filter_image->rows+columns); status=VerticalFilter(resize_filter,image,filter_image,y_factor,span, &offset,exception); status&=HorizontalFilter(resize_filter,filter_image,resize_image,x_factor, span,&offset,exception); } /* Free resources. */ filter_image=DestroyImage(filter_image); resize_filter=DestroyResizeFilter(resize_filter); if ((status == MagickFalse) || (resize_image == (Image *) NULL)) return((Image *) NULL); resize_image->type=image->type; return(resize_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S a m p l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SampleImage() scales an image to the desired dimensions with pixel % sampling. Unlike other scaling methods, this method does not introduce % any additional color into the scaled image. % % The format of the SampleImage method is: % % Image *SampleImage(const Image *image,const size_t columns, % const size_t rows,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the sampled image. % % o rows: the number of rows in the sampled image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SampleImage(const Image *image,const size_t columns, const size_t rows,ExceptionInfo *exception) { #define SampleImageTag "Sample/Image" CacheView *image_view, *sample_view; Image *sample_image; MagickBooleanType status; MagickOffsetType progress; register ssize_t x; ssize_t *x_offset, y; /* Initialize sampled image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); if ((columns == 0) || (rows == 0)) ThrowImageException(ImageError,"NegativeOrZeroImageSize"); if ((columns == image->columns) && (rows == image->rows)) return(CloneImage(image,0,0,MagickTrue,exception)); sample_image=CloneImage(image,columns,rows,MagickTrue,exception); if (sample_image == (Image *) NULL) return((Image *) NULL); /* Allocate scan line buffer and column offset buffers. */ x_offset=(ssize_t *) AcquireQuantumMemory((size_t) sample_image->columns, sizeof(*x_offset)); if (x_offset == (ssize_t *) NULL) { sample_image=DestroyImage(sample_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } for (x=0; x < (ssize_t) sample_image->columns; x++) x_offset[x]=(ssize_t) (((MagickRealType) x+0.5)*image->columns/ sample_image->columns); /* Sample each row. */ status=MagickTrue; progress=0; image_view=AcquireCacheView(image); sample_view=AcquireCacheView(sample_image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(progress,status) #endif for (y=0; y < (ssize_t) sample_image->rows; y++) { register const IndexPacket *restrict indexes; register const PixelPacket *restrict p; register IndexPacket *restrict sample_indexes; register PixelPacket *restrict q; register ssize_t x; ssize_t y_offset; if (status == MagickFalse) continue; y_offset=(ssize_t) (((MagickRealType) y+0.5)*image->rows/ sample_image->rows); p=GetCacheViewVirtualPixels(image_view,0,y_offset,image->columns,1, exception); q=QueueCacheViewAuthenticPixels(sample_view,0,y,sample_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); sample_indexes=GetCacheViewAuthenticIndexQueue(sample_view); /* Sample each column. */ for (x=0; x < (ssize_t) sample_image->columns; x++) *q++=p[x_offset[x]]; if ((image->storage_class == PseudoClass) || (image->colorspace == CMYKColorspace)) for (x=0; x < (ssize_t) sample_image->columns; x++) SetIndexPixelComponent(sample_indexes+x, GetIndexPixelComponent(indexes+x_offset[x])); if (SyncCacheViewAuthenticPixels(sample_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_SampleImage) #endif proceed=SetImageProgress(image,SampleImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); sample_view=DestroyCacheView(sample_view); x_offset=(ssize_t *) RelinquishMagickMemory(x_offset); sample_image->type=image->type; return(sample_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S c a l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ScaleImage() changes the size of an image to the given dimensions. % % The format of the ScaleImage method is: % % Image *ScaleImage(const Image *image,const size_t columns, % const size_t rows,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the scaled image. % % o rows: the number of rows in the scaled image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ScaleImage(const Image *image,const size_t columns, const size_t rows,ExceptionInfo *exception) { #define ScaleImageTag "Scale/Image" CacheView *image_view, *scale_view; Image *scale_image; MagickBooleanType next_column, next_row, proceed; MagickPixelPacket pixel, *scale_scanline, *scanline, *x_vector, *y_vector, zero; MagickRealType alpha; PointInfo scale, span; register ssize_t i; ssize_t number_rows, y; /* Initialize scaled image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); if ((columns == 0) || (rows == 0)) return((Image *) NULL); if ((columns == image->columns) && (rows == image->rows)) return(CloneImage(image,0,0,MagickTrue,exception)); scale_image=CloneImage(image,columns,rows,MagickTrue,exception); if (scale_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(scale_image,DirectClass) == MagickFalse) { InheritException(exception,&scale_image->exception); scale_image=DestroyImage(scale_image); return((Image *) NULL); } /* Allocate memory. */ x_vector=(MagickPixelPacket *) AcquireQuantumMemory((size_t) image->columns, sizeof(*x_vector)); scanline=x_vector; if (image->rows != scale_image->rows) scanline=(MagickPixelPacket *) AcquireQuantumMemory((size_t) image->columns, sizeof(*scanline)); scale_scanline=(MagickPixelPacket *) AcquireQuantumMemory((size_t) scale_image->columns,sizeof(*scale_scanline)); y_vector=(MagickPixelPacket *) AcquireQuantumMemory((size_t) image->columns, sizeof(*y_vector)); if ((scanline == (MagickPixelPacket *) NULL) || (scale_scanline == (MagickPixelPacket *) NULL) || (x_vector == (MagickPixelPacket *) NULL) || (y_vector == (MagickPixelPacket *) NULL)) { scale_image=DestroyImage(scale_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Scale image. */ number_rows=0; next_row=MagickTrue; span.y=1.0; scale.y=(double) scale_image->rows/(double) image->rows; (void) ResetMagickMemory(y_vector,0,(size_t) image->columns* sizeof(*y_vector)); GetMagickPixelPacket(image,&pixel); (void) ResetMagickMemory(&zero,0,sizeof(zero)); i=0; image_view=AcquireCacheView(image); scale_view=AcquireCacheView(scale_image); for (y=0; y < (ssize_t) scale_image->rows; y++) { register const IndexPacket *restrict indexes; register const PixelPacket *restrict p; register IndexPacket *restrict scale_indexes; register MagickPixelPacket *restrict s, *restrict t; register PixelPacket *restrict q; register ssize_t x; q=QueueCacheViewAuthenticPixels(scale_view,0,y,scale_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; alpha=1.0; scale_indexes=GetCacheViewAuthenticIndexQueue(scale_view); if (scale_image->rows == image->rows) { /* Read a new scanline. */ p=GetCacheViewVirtualPixels(image_view,0,i++,image->columns,1, exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if (image->matte != MagickFalse) alpha=QuantumScale*GetAlphaPixelComponent(p); x_vector[x].red=(MagickRealType) (alpha*GetRedPixelComponent(p)); x_vector[x].green=(MagickRealType) (alpha*GetGreenPixelComponent(p)); x_vector[x].blue=(MagickRealType) (alpha*GetBluePixelComponent(p)); if (image->matte != MagickFalse) x_vector[x].opacity=(MagickRealType) GetOpacityPixelComponent(p); if (indexes != (IndexPacket *) NULL) x_vector[x].index=(MagickRealType) (alpha* GetIndexPixelComponent(indexes+x)); p++; } } else { /* Scale Y direction. */ while (scale.y < span.y) { if ((next_row != MagickFalse) && (number_rows < (ssize_t) image->rows)) { /* Read a new scanline. */ p=GetCacheViewVirtualPixels(image_view,0,i++,image->columns,1, exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if (image->matte != MagickFalse) alpha=QuantumScale*GetAlphaPixelComponent(p); x_vector[x].red=(MagickRealType) (alpha* GetRedPixelComponent(p)); x_vector[x].green=(MagickRealType) (alpha* GetGreenPixelComponent(p)); x_vector[x].blue=(MagickRealType) (alpha* GetBluePixelComponent(p)); if (image->matte != MagickFalse) x_vector[x].opacity=(MagickRealType) GetOpacityPixelComponent(p); if (indexes != (IndexPacket *) NULL) x_vector[x].index=(MagickRealType) (alpha* GetIndexPixelComponent(indexes+x)); p++; } number_rows++; } for (x=0; x < (ssize_t) image->columns; x++) { y_vector[x].red+=scale.y*x_vector[x].red; y_vector[x].green+=scale.y*x_vector[x].green; y_vector[x].blue+=scale.y*x_vector[x].blue; if (scale_image->matte != MagickFalse) y_vector[x].opacity+=scale.y*x_vector[x].opacity; if (scale_indexes != (IndexPacket *) NULL) y_vector[x].index+=scale.y*x_vector[x].index; } span.y-=scale.y; scale.y=(double) scale_image->rows/(double) image->rows; next_row=MagickTrue; } if ((next_row != MagickFalse) && (number_rows < (ssize_t) image->rows)) { /* Read a new scanline. */ p=GetCacheViewVirtualPixels(image_view,0,i++,image->columns,1, exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if (image->matte != MagickFalse) alpha=QuantumScale*GetAlphaPixelComponent(p); x_vector[x].red=(MagickRealType) (alpha* GetRedPixelComponent(p)); x_vector[x].green=(MagickRealType) (alpha* GetGreenPixelComponent(p)); x_vector[x].blue=(MagickRealType) (alpha* GetBluePixelComponent(p)); if (image->matte != MagickFalse) x_vector[x].opacity=(MagickRealType) GetOpacityPixelComponent(p); if (indexes != (IndexPacket *) NULL) x_vector[x].index=(MagickRealType) (alpha* GetIndexPixelComponent(indexes+x)); p++; } number_rows++; next_row=MagickFalse; } s=scanline; for (x=0; x < (ssize_t) image->columns; x++) { pixel.red=y_vector[x].red+span.y*x_vector[x].red; pixel.green=y_vector[x].green+span.y*x_vector[x].green; pixel.blue=y_vector[x].blue+span.y*x_vector[x].blue; if (image->matte != MagickFalse) pixel.opacity=y_vector[x].opacity+span.y*x_vector[x].opacity; if (scale_indexes != (IndexPacket *) NULL) pixel.index=y_vector[x].index+span.y*x_vector[x].index; s->red=pixel.red; s->green=pixel.green; s->blue=pixel.blue; if (scale_image->matte != MagickFalse) s->opacity=pixel.opacity; if (scale_indexes != (IndexPacket *) NULL) s->index=pixel.index; s++; y_vector[x]=zero; } scale.y-=span.y; if (scale.y <= 0) { scale.y=(double) scale_image->rows/(double) image->rows; next_row=MagickTrue; } span.y=1.0; } if (scale_image->columns == image->columns) { /* Transfer scanline to scaled image. */ s=scanline; for (x=0; x < (ssize_t) scale_image->columns; x++) { if (scale_image->matte != MagickFalse) alpha=QuantumScale*(QuantumRange-s->opacity); alpha=1.0/(fabs(alpha) <= MagickEpsilon ? 1.0 : alpha); SetRedPixelComponent(q,ClampToQuantum(alpha*s->red)); SetGreenPixelComponent(q,ClampToQuantum(alpha*s->green)); SetBluePixelComponent(q,ClampToQuantum(alpha*s->blue)); if (scale_image->matte != MagickFalse) SetOpacityPixelComponent(q,ClampToQuantum(s->opacity)); if (scale_indexes != (IndexPacket *) NULL) SetIndexPixelComponent(scale_indexes+x,ClampToQuantum(alpha* s->index)); q++; s++; } } else { /* Scale X direction. */ pixel=zero; next_column=MagickFalse; span.x=1.0; s=scanline; t=scale_scanline; for (x=0; x < (ssize_t) image->columns; x++) { scale.x=(double) scale_image->columns/(double) image->columns; while (scale.x >= span.x) { if (next_column != MagickFalse) { pixel=zero; t++; } pixel.red+=span.x*s->red; pixel.green+=span.x*s->green; pixel.blue+=span.x*s->blue; if (image->matte != MagickFalse) pixel.opacity+=span.x*s->opacity; if (scale_indexes != (IndexPacket *) NULL) pixel.index+=span.x*s->index; t->red=pixel.red; t->green=pixel.green; t->blue=pixel.blue; if (scale_image->matte != MagickFalse) t->opacity=pixel.opacity; if (scale_indexes != (IndexPacket *) NULL) t->index=pixel.index; scale.x-=span.x; span.x=1.0; next_column=MagickTrue; } if (scale.x > 0) { if (next_column != MagickFalse) { pixel=zero; next_column=MagickFalse; t++; } pixel.red+=scale.x*s->red; pixel.green+=scale.x*s->green; pixel.blue+=scale.x*s->blue; if (scale_image->matte != MagickFalse) pixel.opacity+=scale.x*s->opacity; if (scale_indexes != (IndexPacket *) NULL) pixel.index+=scale.x*s->index; span.x-=scale.x; } s++; } if (span.x > 0) { s--; pixel.red+=span.x*s->red; pixel.green+=span.x*s->green; pixel.blue+=span.x*s->blue; if (scale_image->matte != MagickFalse) pixel.opacity+=span.x*s->opacity; if (scale_indexes != (IndexPacket *) NULL) pixel.index+=span.x*s->index; } if ((next_column == MagickFalse) && ((ssize_t) (t-scale_scanline) < (ssize_t) scale_image->columns)) { t->red=pixel.red; t->green=pixel.green; t->blue=pixel.blue; if (scale_image->matte != MagickFalse) t->opacity=pixel.opacity; if (scale_indexes != (IndexPacket *) NULL) t->index=pixel.index; } /* Transfer scanline to scaled image. */ t=scale_scanline; for (x=0; x < (ssize_t) scale_image->columns; x++) { if (scale_image->matte != MagickFalse) alpha=QuantumScale*(QuantumRange-s->opacity); alpha=1.0/(fabs(alpha) <= MagickEpsilon ? 1.0 : alpha); SetRedPixelComponent(q,ClampToQuantum(alpha*t->red)); SetGreenPixelComponent(q,ClampToQuantum(alpha*t->green)); SetBluePixelComponent(q,ClampToQuantum(alpha*t->blue)); if (scale_image->matte != MagickFalse) SetOpacityPixelComponent(q,ClampToQuantum(t->opacity)); if (scale_indexes != (IndexPacket *) NULL) SetIndexPixelComponent(scale_indexes+x,ClampToQuantum(alpha* t->index)); t++; q++; } } if (SyncCacheViewAuthenticPixels(scale_view,exception) == MagickFalse) break; proceed=SetImageProgress(image,ScaleImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) break; } scale_view=DestroyCacheView(scale_view); image_view=DestroyCacheView(image_view); /* Free allocated memory. */ y_vector=(MagickPixelPacket *) RelinquishMagickMemory(y_vector); scale_scanline=(MagickPixelPacket *) RelinquishMagickMemory(scale_scanline); if (scale_image->rows != image->rows) scanline=(MagickPixelPacket *) RelinquishMagickMemory(scanline); x_vector=(MagickPixelPacket *) RelinquishMagickMemory(x_vector); scale_image->type=image->type; return(scale_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T h u m b n a i l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ThumbnailImage() changes the size of an image to the given dimensions and % removes any associated profiles. The goal is to produce small low cost % thumbnail images suited for display on the Web. % % The format of the ThumbnailImage method is: % % Image *ThumbnailImage(const Image *image,const size_t columns, % const size_t rows,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the scaled image. % % o rows: the number of rows in the scaled image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ThumbnailImage(const Image *image,const size_t columns, const size_t rows,ExceptionInfo *exception) { #define SampleFactor 5 char value[MaxTextExtent]; const char *name; Image *thumbnail_image; MagickRealType x_factor, y_factor; size_t version; struct stat attributes; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); x_factor=(MagickRealType) columns/(MagickRealType) image->columns; y_factor=(MagickRealType) rows/(MagickRealType) image->rows; if ((x_factor*y_factor) > 0.1) thumbnail_image=ResizeImage(image,columns,rows,image->filter,image->blur, exception); else if (((SampleFactor*columns) < 128) || ((SampleFactor*rows) < 128)) thumbnail_image=ResizeImage(image,columns,rows,image->filter, image->blur,exception); else { Image *sample_image; sample_image=SampleImage(image,SampleFactor*columns,SampleFactor*rows, exception); if (sample_image == (Image *) NULL) return((Image *) NULL); thumbnail_image=ResizeImage(sample_image,columns,rows,image->filter, image->blur,exception); sample_image=DestroyImage(sample_image); } if (thumbnail_image == (Image *) NULL) return(thumbnail_image); (void) ParseAbsoluteGeometry("0x0+0+0",&thumbnail_image->page); if (thumbnail_image->matte == MagickFalse) (void) SetImageAlphaChannel(thumbnail_image,OpaqueAlphaChannel); thumbnail_image->depth=8; thumbnail_image->interlace=NoInterlace; /* Strip all profiles except color profiles. */ ResetImageProfileIterator(thumbnail_image); for (name=GetNextImageProfile(thumbnail_image); name != (const char *) NULL; ) { if ((LocaleCompare(name,"icc") != 0) && (LocaleCompare(name,"icm") != 0)) { (void) DeleteImageProfile(thumbnail_image,name); ResetImageProfileIterator(thumbnail_image); } name=GetNextImageProfile(thumbnail_image); } (void) DeleteImageProperty(thumbnail_image,"comment"); (void) CopyMagickString(value,image->magick_filename,MaxTextExtent); if (strstr(image->magick_filename,"//") == (char *) NULL) (void) FormatLocaleString(value,MaxTextExtent,"file://%s", image->magick_filename); (void) SetImageProperty(thumbnail_image,"Thumb::URI",value); (void) CopyMagickString(value,image->magick_filename,MaxTextExtent); if (GetPathAttributes(image->filename,&attributes) != MagickFalse) { (void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double) attributes.st_mtime); (void) SetImageProperty(thumbnail_image,"Thumb::MTime",value); } (void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double) attributes.st_mtime); (void) FormatMagickSize(GetBlobSize(image),MagickFalse,value); (void) ConcatenateMagickString(value,"B",MaxTextExtent); (void) SetImageProperty(thumbnail_image,"Thumb::Size",value); (void) FormatLocaleString(value,MaxTextExtent,"image/%s",image->magick); LocaleLower(value); (void) SetImageProperty(thumbnail_image,"Thumb::Mimetype",value); (void) SetImageProperty(thumbnail_image,"software", GetMagickVersion(&version)); (void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double) image->magick_columns); (void) SetImageProperty(thumbnail_image,"Thumb::Image::Width",value); (void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double) image->magick_rows); (void) SetImageProperty(thumbnail_image,"Thumb::Image::height",value); (void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double) GetImageListLength(image)); (void) SetImageProperty(thumbnail_image,"Thumb::Document::Pages",value); return(thumbnail_image); }
target_update.c
// -------------------------------------------------- // Check 'to' // -------------------------------------------------- // RUN: %libomptarget-compile-aarch64-unknown-linux-gnu \ // RUN: -fopenmp-version=51 -DCLAUSE=to // RUN: %libomptarget-run-fail-aarch64-unknown-linux-gnu 2>&1 \ // RUN: | %fcheck-aarch64-unknown-linux-gnu // RUN: %libomptarget-compile-powerpc64-ibm-linux-gnu \ // RUN: -fopenmp-version=51 -DCLAUSE=to // RUN: %libomptarget-run-fail-powerpc64-ibm-linux-gnu 2>&1 \ // RUN: | %fcheck-powerpc64-ibm-linux-gnu // RUN: %libomptarget-compile-powerpc64le-ibm-linux-gnu \ // RUN: -fopenmp-version=51 -DCLAUSE=to // RUN: %libomptarget-run-fail-powerpc64le-ibm-linux-gnu 2>&1 \ // RUN: | %fcheck-powerpc64le-ibm-linux-gnu // RUN: %libomptarget-compile-x86_64-pc-linux-gnu \ // RUN: -fopenmp-version=51 -DCLAUSE=to // RUN: %libomptarget-run-fail-x86_64-pc-linux-gnu 2>&1 \ // RUN: | %fcheck-x86_64-pc-linux-gnu // -------------------------------------------------- // Check 'from' // -------------------------------------------------- // RUN: %libomptarget-compile-aarch64-unknown-linux-gnu \ // RUN: -fopenmp-version=51 -DCLAUSE=from // RUN: %libomptarget-run-fail-aarch64-unknown-linux-gnu 2>&1 \ // RUN: | %fcheck-aarch64-unknown-linux-gnu // RUN: %libomptarget-compile-powerpc64-ibm-linux-gnu \ // RUN: -fopenmp-version=51 -DCLAUSE=from // RUN: %libomptarget-run-fail-powerpc64-ibm-linux-gnu 2>&1 \ // RUN: | %fcheck-powerpc64-ibm-linux-gnu // RUN: %libomptarget-compile-powerpc64le-ibm-linux-gnu \ // RUN: -fopenmp-version=51 -DCLAUSE=from // RUN: %libomptarget-run-fail-powerpc64le-ibm-linux-gnu 2>&1 \ // RUN: | %fcheck-powerpc64le-ibm-linux-gnu // RUN: %libomptarget-compile-x86_64-pc-linux-gnu \ // RUN: -fopenmp-version=51 -DCLAUSE=from // RUN: %libomptarget-run-fail-x86_64-pc-linux-gnu 2>&1 \ // RUN: | %fcheck-x86_64-pc-linux-gnu #include <stdio.h> int main() { int i; // CHECK: addr=0x[[#%x,HOST_ADDR:]], size=[[#%u,SIZE:]] fprintf(stderr, "addr=%p, size=%ld\n", &i, sizeof i); // CHECK-NOT: Libomptarget #pragma omp target enter data map(alloc: i) #pragma omp target update CLAUSE(present: i) #pragma omp target exit data map(delete: i) // CHECK: i is present fprintf(stderr, "i is present\n"); // CHECK: Libomptarget message: device mapping required by 'present' motion modifier does not exist for host address 0x{{0*}}[[#HOST_ADDR]] ([[#SIZE]] bytes) // CHECK: Libomptarget fatal error 1: failure of target construct while offloading is mandatory #pragma omp target update CLAUSE(present: i) // CHECK-NOT: i is present fprintf(stderr, "i is present\n"); return 0; }
ellipticBuildContinuous.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. */ #include "elliptic.h" // compare on global indices int parallelCompareRowColumn(const void *a, const void *b){ nonZero_t *fa = (nonZero_t*) a; nonZero_t *fb = (nonZero_t*) b; if(fa->row < fb->row) return -1; if(fa->row > fb->row) return +1; if(fa->col < fb->col) return -1; if(fa->col > fb->col) return +1; return 0; } void ellipticBuildContinuousTri2D (elliptic_t *elliptic, dfloat lambda, nonZero_t **A, dlong *nnz, ogs_t **ogs, hlong *globalStarts); void ellipticBuildContinuousQuad2D(elliptic_t *elliptic, dfloat lambda, nonZero_t **A, dlong *nnz, ogs_t **ogs, hlong *globalStarts); void ellipticBuildContinuousQuad3D(elliptic_t *elliptic, dfloat lambda, nonZero_t **A, dlong *nnz, ogs_t **ogs, hlong *globalStarts); void ellipticBuildContinuousTet3D (elliptic_t *elliptic, dfloat lambda, nonZero_t **A, dlong *nnz, ogs_t **ogs, hlong *globalStarts); void ellipticBuildContinuousHex3D (elliptic_t *elliptic, dfloat lambda, nonZero_t **A, dlong *nnz, ogs_t **ogs, hlong *globalStarts); void ellipticBuildContinuous(elliptic_t *elliptic, dfloat lambda, nonZero_t **A, dlong *nnz, ogs_t **ogs, hlong *globalStarts) { switch(elliptic->elementType){ case TRIANGLES: ellipticBuildContinuousTri2D(elliptic, lambda, A, nnz, ogs, globalStarts); break; case QUADRILATERALS:{ if(elliptic->dim==2) ellipticBuildContinuousQuad2D(elliptic, lambda, A, nnz, ogs, globalStarts); else ellipticBuildContinuousQuad3D(elliptic, lambda, A, nnz, ogs, globalStarts); break; } case TETRAHEDRA: ellipticBuildContinuousTet3D(elliptic, lambda, A, nnz, ogs, globalStarts); break; case HEXAHEDRA: ellipticBuildContinuousHex3D(elliptic, lambda, A, nnz, ogs, globalStarts); break; } } void ellipticBuildContinuousTri2D(elliptic_t *elliptic, dfloat lambda, nonZero_t **A, dlong *nnz, ogs_t **ogs, hlong *globalStarts) { mesh2D *mesh = elliptic->mesh; setupAide options = elliptic->options; int rank = mesh->rank; //use the masked gs handle to define a global ordering // number of degrees of freedom on this rank (after gathering) hlong Ngather = elliptic->ogs->Ngather; dlong Ntotal = mesh->Np*mesh->Nelements; // create a global numbering system hlong *globalIds = (hlong *) calloc(Ngather,sizeof(hlong)); int *owner = (int *) calloc(Ngather,sizeof(int)); // every gathered degree of freedom has its own global id MPI_Allgather(&Ngather, 1, MPI_HLONG, globalStarts+1, 1, MPI_HLONG, mesh->comm); for(int r=0;r<mesh->size;++r) globalStarts[r+1] = globalStarts[r]+globalStarts[r+1]; //use the offsets to set a consecutive global numbering for (dlong n =0;n<elliptic->ogs->Ngather;n++) { globalIds[n] = n + globalStarts[rank]; owner[n] = rank; } //scatter this numbering to the original nodes hlong *globalNumbering = (hlong *) calloc(Ntotal,sizeof(hlong)); int *globalOwners = (int *) calloc(Ntotal,sizeof(int)); for (dlong n=0;n<Ntotal;n++) globalNumbering[n] = -1; ogsScatter(globalNumbering, globalIds, ogsHlong, ogsAdd, elliptic->ogs); ogsScatter(globalOwners, owner, ogsInt, ogsAdd, elliptic->ogs); free(globalIds); free(owner); // Build non-zeros of stiffness matrix (unassembled) dlong nnzLocal = mesh->Np*mesh->Np*mesh->Nelements; nonZero_t *sendNonZeros = (nonZero_t*) calloc(nnzLocal, sizeof(nonZero_t)); int *AsendCounts = (int*) calloc(mesh->size, sizeof(int)); int *ArecvCounts = (int*) calloc(mesh->size, sizeof(int)); int *AsendOffsets = (int*) calloc(mesh->size+1, sizeof(int)); int *ArecvOffsets = (int*) calloc(mesh->size+1, sizeof(int)); dfloat *Srr = (dfloat *) calloc(mesh->Np*mesh->Np,sizeof(dfloat)); dfloat *Srs = (dfloat *) calloc(mesh->Np*mesh->Np,sizeof(dfloat)); dfloat *Sss = (dfloat *) calloc(mesh->Np*mesh->Np,sizeof(dfloat)); dfloat *MM = (dfloat *) calloc(mesh->Np*mesh->Np,sizeof(dfloat)); for (int n=0;n<mesh->Np;n++) { for (int m=0;m<mesh->Np;m++) { Srr[m+n*mesh->Np] = mesh->Srr[m+n*mesh->Np]; Srs[m+n*mesh->Np] = mesh->Srs[m+n*mesh->Np] + mesh->Ssr[m+n*mesh->Np]; Sss[m+n*mesh->Np] = mesh->Sss[m+n*mesh->Np]; MM[m+n*mesh->Np] = mesh->MM[m+n*mesh->Np]; } } if(mesh->rank==0) printf("Building full FEM matrix...");fflush(stdout); //Build unassembed non-zeros dlong cnt =0; for (dlong e=0;e<mesh->Nelements;e++) { dfloat Grr = mesh->ggeo[e*mesh->Nggeo + G00ID]; dfloat Grs = mesh->ggeo[e*mesh->Nggeo + G01ID]; dfloat Gss = mesh->ggeo[e*mesh->Nggeo + G11ID]; dfloat J = mesh->ggeo[e*mesh->Nggeo + GWJID]; for (int n=0;n<mesh->Np;n++) { if (globalNumbering[e*mesh->Np + n]<0) continue; //skip masked nodes for (int m=0;m<mesh->Np;m++) { if (globalNumbering[e*mesh->Np + m]<0) continue; //skip masked nodes dfloat val = 0.; val += Grr*Srr[m+n*mesh->Np]; val += Grs*Srs[m+n*mesh->Np]; val += Gss*Sss[m+n*mesh->Np]; val += J*lambda*MM[m+n*mesh->Np]; dfloat nonZeroThreshold = 1e-7; if (fabs(val)>nonZeroThreshold) { // pack non-zero sendNonZeros[cnt].val = val; sendNonZeros[cnt].row = globalNumbering[e*mesh->Np + n]; sendNonZeros[cnt].col = globalNumbering[e*mesh->Np + m]; sendNonZeros[cnt].ownerRank = globalOwners[e*mesh->Np + n]; cnt++; } } } } // Make the MPI_NONZERO_T data type MPI_Datatype MPI_NONZERO_T; MPI_Datatype dtype[4] = {MPI_HLONG, MPI_HLONG, MPI_INT, MPI_DFLOAT}; int blength[4] = {1, 1, 1, 1}; MPI_Aint addr[4], displ[4]; MPI_Get_address ( &(sendNonZeros[0] ), addr+0); MPI_Get_address ( &(sendNonZeros[0].col ), addr+1); MPI_Get_address ( &(sendNonZeros[0].ownerRank), addr+2); MPI_Get_address ( &(sendNonZeros[0].val ), addr+3); displ[0] = 0; displ[1] = addr[1] - addr[0]; displ[2] = addr[2] - addr[0]; displ[3] = addr[3] - addr[0]; MPI_Type_create_struct (4, blength, displ, dtype, &MPI_NONZERO_T); MPI_Type_commit (&MPI_NONZERO_T); // count how many non-zeros to send to each process for(dlong n=0;n<cnt;++n) AsendCounts[sendNonZeros[n].ownerRank]++; // sort by row ordering qsort(sendNonZeros, cnt, sizeof(nonZero_t), parallelCompareRowColumn); // find how many nodes to expect (should use sparse version) MPI_Alltoall(AsendCounts, 1, MPI_INT, ArecvCounts, 1, MPI_INT, mesh->comm); // find send and recv offsets for gather *nnz = 0; for(int r=0;r<mesh->size;++r){ AsendOffsets[r+1] = AsendOffsets[r] + AsendCounts[r]; ArecvOffsets[r+1] = ArecvOffsets[r] + ArecvCounts[r]; *nnz += ArecvCounts[r]; } *A = (nonZero_t*) calloc(*nnz, sizeof(nonZero_t)); // determine number to receive MPI_Alltoallv(sendNonZeros, AsendCounts, AsendOffsets, MPI_NONZERO_T, (*A), ArecvCounts, ArecvOffsets, MPI_NONZERO_T, mesh->comm); // sort received non-zero entries by row block (may need to switch compareRowColumn tests) qsort((*A), *nnz, sizeof(nonZero_t), parallelCompareRowColumn); // compress duplicates cnt = 0; for(dlong n=1;n<*nnz;++n){ if((*A)[n].row == (*A)[cnt].row && (*A)[n].col == (*A)[cnt].col){ (*A)[cnt].val += (*A)[n].val; } else{ ++cnt; (*A)[cnt] = (*A)[n]; } } if (*nnz) cnt++; *nnz = cnt; if(mesh->rank==0) printf("done.\n"); MPI_Barrier(mesh->comm); MPI_Type_free(&MPI_NONZERO_T); free(sendNonZeros); free(globalNumbering); free(globalOwners); free(AsendCounts); free(ArecvCounts); free(AsendOffsets); free(ArecvOffsets); free(Srr); free(Srs); free(Sss); free(MM ); } void ellipticBuildContinuousQuad3D(elliptic_t *elliptic, dfloat lambda, nonZero_t **A, dlong *nnz, ogs_t **ogs, hlong *globalStarts) { mesh2D *mesh = elliptic->mesh; setupAide options = elliptic->options; int rank = mesh->rank; //use the masked gs handle to define a global ordering // number of degrees of freedom on this rank (after gathering) hlong Ngather = elliptic->ogs->Ngather; dlong Ntotal = mesh->Np*mesh->Nelements; // create a global numbering system hlong *globalIds = (hlong *) calloc(Ngather,sizeof(hlong)); int *owner = (int *) calloc(Ngather,sizeof(int)); // every gathered degree of freedom has its own global id MPI_Allgather(&Ngather, 1, MPI_HLONG, globalStarts+1, 1, MPI_HLONG, mesh->comm); for(int r=0;r<mesh->size;++r) globalStarts[r+1] = globalStarts[r]+globalStarts[r+1]; //use the offsets to set a consecutive global numbering for (dlong n =0;n<elliptic->ogs->Ngather;n++) { globalIds[n] = n + globalStarts[rank]; owner[n] = rank; } //scatter this numbering to the original nodes hlong *globalNumbering = (hlong *) calloc(Ntotal,sizeof(hlong)); int *globalOwners = (int *) calloc(Ntotal,sizeof(int)); for (dlong n=0;n<Ntotal;n++) globalNumbering[n] = -1; ogsScatter(globalNumbering, globalIds, ogsHlong, ogsAdd, elliptic->ogs); ogsScatter(globalOwners, owner, ogsInt, ogsAdd, elliptic->ogs); free(globalIds); free(owner); // 2. Build non-zeros of stiffness matrix (unassembled) dlong nnzLocal = mesh->Np*mesh->Np*mesh->Nelements; nonZero_t *sendNonZeros = (nonZero_t*) calloc(nnzLocal, sizeof(nonZero_t)); int *AsendCounts = (int*) calloc(mesh->size, sizeof(int)); int *ArecvCounts = (int*) calloc(mesh->size, sizeof(int)); int *AsendOffsets = (int*) calloc(mesh->size+1, sizeof(int)); int *ArecvOffsets = (int*) calloc(mesh->size+1, sizeof(int)); int *mask = (int *) calloc(mesh->Np*mesh->Nelements,sizeof(int)); for (dlong n=0;n<elliptic->Nmasked;n++) mask[elliptic->maskIds[n]] = 1; if(mesh->rank==0) printf("Building full FEM matrix...");fflush(stdout); #if 0 hlong NTf = mesh->Nelements*mesh->Np * mesh->Nelements*mesh->Np ; dfloat *Af = (dfloat *)calloc(NTf, sizeof(dfloat)); #endif //Build unassembed non-zeros dlong cnt =0; for (dlong e=0;e<mesh->Nelements;e++) { for (int ny=0;ny<mesh->Nq;ny++) { for (int nx=0;nx<mesh->Nq;nx++) { if (mask[e*mesh->Np + nx+ny*mesh->Nq]) continue; //skip masked nodes for (int my=0;my<mesh->Nq;my++) { for (int mx=0;mx<mesh->Nq;mx++) { if (mask[e*mesh->Np + mx+my*mesh->Nq]) continue; //skip masked nodes int id; dfloat val = 0.; if (ny==my) { for (int k=0;k<mesh->Nq;k++) { id = k+ny*mesh->Nq; dfloat Grr = mesh->ggeo[e*mesh->Np*mesh->Nggeo + id + G00ID*mesh->Np]; val += Grr*mesh->D[nx+k*mesh->Nq]*mesh->D[mx+k*mesh->Nq]; } } id = mx+ny*mesh->Nq; dfloat Grs = mesh->ggeo[e*mesh->Np*mesh->Nggeo + id + G01ID*mesh->Np]; val += Grs*mesh->D[nx+mx*mesh->Nq]*mesh->D[my+ny*mesh->Nq]; id = nx+my*mesh->Nq; dfloat Gsr = mesh->ggeo[e*mesh->Np*mesh->Nggeo + id + G01ID*mesh->Np]; val += Gsr*mesh->D[mx+nx*mesh->Nq]*mesh->D[ny+my*mesh->Nq]; // id = mx+ny*mesh->Nq; // dfloat Grt = mesh->ggeo[e*mesh->Np*mesh->Nggeo + id + G02ID*mesh->Np]; // val += Grt*mesh->D[nx+mx*mesh->Nq]; // id = nx+my*mesh->Nq; // dfloat Gtr = mesh->ggeo[e*mesh->Np*mesh->Nggeo + id + G02ID*mesh->Np]; // val += Gtr*mesh->D[mx+nx*mesh->Nq]; if (nx==mx) { for (int k=0;k<mesh->Nq;k++) { id = nx+k*mesh->Nq; dfloat Gss = mesh->ggeo[e*mesh->Np*mesh->Nggeo + id + G11ID*mesh->Np]; val += Gss*mesh->D[ny+k*mesh->Nq]*mesh->D[my+k*mesh->Nq]; } } // double check following two: AK // id = nx+my*mesh->Nq; // dfloat Gst = mesh->ggeo[e*mesh->Np*mesh->Nggeo + id + G12ID*mesh->Np]; // val += Gst*mesh->D[ny+my*mesh->Nq]; // id = mx+ny*mesh->Nq; // dfloat Gts = mesh->ggeo[e*mesh->Np*mesh->Nggeo + id + G12ID*mesh->Np]; // val += Gts*mesh->D[my+ny*mesh->Nq]; if ((nx==mx)&&(ny==my)) { id = nx + ny*mesh->Nq; // dfloat Gtt = mesh->ggeo[e*mesh->Np*mesh->Nggeo + id + G22ID*mesh->Np]; // val += Gtt; dfloat JW = mesh->ggeo[e*mesh->Np*mesh->Nggeo + id + GWJID*mesh->Np]; val += JW*lambda; } #if 0 const hlong rowid = e*mesh->Np + nx + ny*mesh->Nq; const hlong colid = e*mesh->Np + mx + my*mesh->Nq; Af[rowid*mesh->Nelements*mesh->Np + colid] = val; #endif dfloat nonZeroThreshold = 1e-7; if (fabs(val)>nonZeroThreshold) { // pack non-zero sendNonZeros[cnt].val = val; sendNonZeros[cnt].row = globalNumbering[e*mesh->Np + nx+ny*mesh->Nq]; sendNonZeros[cnt].col = globalNumbering[e*mesh->Np + mx+my*mesh->Nq]; sendNonZeros[cnt].ownerRank = globalOwners[e*mesh->Np + nx+ny*mesh->Nq]; cnt++; } } } } } } #if 0 // Write matlab dat for postprocess char fname[BUFSIZ]; sprintf(fname, "Ax.dat"); FILE *fp; fp = fopen(fname, "w"); for(hlong row = 0; row<(mesh->Nelements*mesh->Np); row++){ for(hlong col = 0; col<(mesh->Nelements*mesh->Np); col++){ dfloat val = Af[row*mesh->Nelements*mesh->Np + col]; fprintf(fp,"%.8e ", val); } fprintf(fp,"\n"); } fclose(fp); #endif // Make the MPI_NONZERO_T data type MPI_Datatype MPI_NONZERO_T; MPI_Datatype dtype[4] = {MPI_HLONG, MPI_HLONG, MPI_INT, MPI_DFLOAT}; int blength[4] = {1, 1, 1, 1}; MPI_Aint addr[4], displ[4]; MPI_Get_address ( &(sendNonZeros[0] ), addr+0); MPI_Get_address ( &(sendNonZeros[0].col ), addr+1); MPI_Get_address ( &(sendNonZeros[0].ownerRank), addr+2); MPI_Get_address ( &(sendNonZeros[0].val ), addr+3); displ[0] = 0; displ[1] = addr[1] - addr[0]; displ[2] = addr[2] - addr[0]; displ[3] = addr[3] - addr[0]; MPI_Type_create_struct (4, blength, displ, dtype, &MPI_NONZERO_T); MPI_Type_commit (&MPI_NONZERO_T); // count how many non-zeros to send to each process for(dlong n=0;n<cnt;++n) AsendCounts[sendNonZeros[n].ownerRank]++; // sort by row ordering qsort(sendNonZeros, cnt, sizeof(nonZero_t), parallelCompareRowColumn); // find how many nodes to expect (should use sparse version) MPI_Alltoall(AsendCounts, 1, MPI_INT, ArecvCounts, 1, MPI_INT, mesh->comm); // find send and recv offsets for gather *nnz = 0; for(int r=0;r<mesh->size;++r){ AsendOffsets[r+1] = AsendOffsets[r] + AsendCounts[r]; ArecvOffsets[r+1] = ArecvOffsets[r] + ArecvCounts[r]; *nnz += ArecvCounts[r]; } *A = (nonZero_t*) calloc(*nnz, sizeof(nonZero_t)); // determine number to receive MPI_Alltoallv(sendNonZeros, AsendCounts, AsendOffsets, MPI_NONZERO_T, (*A), ArecvCounts, ArecvOffsets, MPI_NONZERO_T, mesh->comm); // sort received non-zero entries by row block (may need to switch compareRowColumn tests) qsort((*A), *nnz, sizeof(nonZero_t), parallelCompareRowColumn); // compress duplicates cnt = 0; for(dlong n=1;n<*nnz;++n){ if((*A)[n].row == (*A)[cnt].row && (*A)[n].col == (*A)[cnt].col){ (*A)[cnt].val += (*A)[n].val; } else{ ++cnt; (*A)[cnt] = (*A)[n]; } } if (*nnz) cnt++; *nnz = cnt; #if 0 // Write matlab dat for postprocess char fname[BUFSIZ]; sprintf(fname, "Ax.dat"); FILE *fp; fp = fopen(fname, "w"); for(dlong n=1;n<*nnz;++n){ fprintf(fp,"%d %d %.8e\n", (*A)[n].row+1, (*A)[n].col+1, (*A)[n].val); } fclose(fp); #endif if(mesh->rank==0) printf("done.\n"); MPI_Barrier(mesh->comm); MPI_Type_free(&MPI_NONZERO_T); free(sendNonZeros); free(globalNumbering); free(globalOwners); free(AsendCounts); free(ArecvCounts); free(AsendOffsets); free(ArecvOffsets); } void ellipticBuildContinuousQuad2D(elliptic_t *elliptic, dfloat lambda, nonZero_t **A, dlong *nnz, ogs_t **ogs, hlong *globalStarts) { mesh_t *mesh = elliptic->mesh; setupAide options = elliptic->options; int rank = mesh->rank; //use the masked gs handle to define a global ordering // number of degrees of freedom on this rank (after gathering) hlong Ngather = elliptic->ogs->Ngather; dlong Ntotal = mesh->Np*mesh->Nelements; // create a global numbering system hlong *globalIds = (hlong *) calloc(Ngather,sizeof(hlong)); int *owner = (int *) calloc(Ngather,sizeof(int)); // every gathered degree of freedom has its own global id MPI_Allgather(&Ngather, 1, MPI_HLONG, globalStarts+1, 1, MPI_HLONG, mesh->comm); for(int r=0;r<mesh->size;++r) globalStarts[r+1] = globalStarts[r]+globalStarts[r+1]; //use the offsets to set a consecutive global numbering for (dlong n =0;n<elliptic->ogs->Ngather;n++) { globalIds[n] = n + globalStarts[rank]; owner[n] = rank; } //scatter this numbering to the original nodes hlong *globalNumbering = (hlong *) calloc(Ntotal,sizeof(hlong)); int *globalOwners = (int *) calloc(Ntotal,sizeof(int)); for (dlong n=0;n<Ntotal;n++) globalNumbering[n] = -1; ogsScatter(globalNumbering, globalIds, ogsHlong, ogsAdd, elliptic->ogs); ogsScatter(globalOwners, owner, ogsInt, ogsAdd, elliptic->ogs); free(globalIds); free(owner); // 2. Build non-zeros of stiffness matrix (unassembled) dlong nnzLocal = mesh->Np*mesh->Np*mesh->Nelements; nonZero_t *sendNonZeros = (nonZero_t*) calloc(nnzLocal, sizeof(nonZero_t)); int *AsendCounts = (int*) calloc(mesh->size, sizeof(int)); int *ArecvCounts = (int*) calloc(mesh->size, sizeof(int)); int *AsendOffsets = (int*) calloc(mesh->size+1, sizeof(int)); int *ArecvOffsets = (int*) calloc(mesh->size+1, sizeof(int)); int *mask = (int *) calloc(mesh->Np*mesh->Nelements,sizeof(int)); for (dlong n=0;n<elliptic->Nmasked;n++) mask[elliptic->maskIds[n]] = 1; if(mesh->rank==0) printf("Building full FEM matrix...");fflush(stdout); //Build unassembed non-zeros dlong cnt =0; for (dlong e=0;e<mesh->Nelements;e++) { for (int ny=0;ny<mesh->Nq;ny++) { for (int nx=0;nx<mesh->Nq;nx++) { if (mask[e*mesh->Np + nx+ny*mesh->Nq]) continue; //skip masked nodes for (int my=0;my<mesh->Nq;my++) { for (int mx=0;mx<mesh->Nq;mx++) { if (mask[e*mesh->Np + mx+my*mesh->Nq]) continue; //skip masked nodes int id; dfloat val = 0.; if (ny==my) { for (int k=0;k<mesh->Nq;k++) { id = k+ny*mesh->Nq; dfloat Grr = mesh->ggeo[e*mesh->Np*mesh->Nggeo + id + G00ID*mesh->Np]; val += Grr*mesh->D[nx+k*mesh->Nq]*mesh->D[mx+k*mesh->Nq]; } } id = mx+ny*mesh->Nq; dfloat Grs = mesh->ggeo[e*mesh->Np*mesh->Nggeo + id + G01ID*mesh->Np]; val += Grs*mesh->D[nx+mx*mesh->Nq]*mesh->D[my+ny*mesh->Nq]; id = nx+my*mesh->Nq; dfloat Gsr = mesh->ggeo[e*mesh->Np*mesh->Nggeo + id + G01ID*mesh->Np]; val += Gsr*mesh->D[mx+nx*mesh->Nq]*mesh->D[ny+my*mesh->Nq]; if (nx==mx) { for (int k=0;k<mesh->Nq;k++) { id = nx+k*mesh->Nq; dfloat Gss = mesh->ggeo[e*mesh->Np*mesh->Nggeo + id + G11ID*mesh->Np]; val += Gss*mesh->D[ny+k*mesh->Nq]*mesh->D[my+k*mesh->Nq]; } } if ((nx==mx)&&(ny==my)) { id = nx + ny*mesh->Nq; dfloat JW = mesh->ggeo[e*mesh->Np*mesh->Nggeo + id + GWJID*mesh->Np]; val += JW*lambda; } dfloat nonZeroThreshold = 1e-7; if (fabs(val)>nonZeroThreshold) { // pack non-zero sendNonZeros[cnt].val = val; sendNonZeros[cnt].row = globalNumbering[e*mesh->Np + nx+ny*mesh->Nq]; sendNonZeros[cnt].col = globalNumbering[e*mesh->Np + mx+my*mesh->Nq]; sendNonZeros[cnt].ownerRank = globalOwners[e*mesh->Np + nx+ny*mesh->Nq]; cnt++; } } } } } } // Make the MPI_NONZERO_T data type MPI_Datatype MPI_NONZERO_T; MPI_Datatype dtype[4] = {MPI_HLONG, MPI_HLONG, MPI_INT, MPI_DFLOAT}; int blength[4] = {1, 1, 1, 1}; MPI_Aint addr[4], displ[4]; MPI_Get_address ( &(sendNonZeros[0] ), addr+0); MPI_Get_address ( &(sendNonZeros[0].col ), addr+1); MPI_Get_address ( &(sendNonZeros[0].ownerRank), addr+2); MPI_Get_address ( &(sendNonZeros[0].val ), addr+3); displ[0] = 0; displ[1] = addr[1] - addr[0]; displ[2] = addr[2] - addr[0]; displ[3] = addr[3] - addr[0]; MPI_Type_create_struct (4, blength, displ, dtype, &MPI_NONZERO_T); MPI_Type_commit (&MPI_NONZERO_T); // count how many non-zeros to send to each process for(dlong n=0;n<cnt;++n) AsendCounts[sendNonZeros[n].ownerRank]++; // sort by row ordering qsort(sendNonZeros, cnt, sizeof(nonZero_t), parallelCompareRowColumn); // find how many nodes to expect (should use sparse version) MPI_Alltoall(AsendCounts, 1, MPI_INT, ArecvCounts, 1, MPI_INT, mesh->comm); // find send and recv offsets for gather *nnz = 0; for(int r=0;r<mesh->size;++r){ AsendOffsets[r+1] = AsendOffsets[r] + AsendCounts[r]; ArecvOffsets[r+1] = ArecvOffsets[r] + ArecvCounts[r]; *nnz += ArecvCounts[r]; } *A = (nonZero_t*) calloc(*nnz, sizeof(nonZero_t)); // determine number to receive MPI_Alltoallv(sendNonZeros, AsendCounts, AsendOffsets, MPI_NONZERO_T, (*A), ArecvCounts, ArecvOffsets, MPI_NONZERO_T, mesh->comm); // sort received non-zero entries by row block (may need to switch compareRowColumn tests) qsort((*A), *nnz, sizeof(nonZero_t), parallelCompareRowColumn); // compress duplicates cnt = 0; for(dlong n=1;n<*nnz;++n){ if((*A)[n].row == (*A)[cnt].row && (*A)[n].col == (*A)[cnt].col){ (*A)[cnt].val += (*A)[n].val; } else{ ++cnt; (*A)[cnt] = (*A)[n]; } } if (*nnz) cnt++; *nnz = cnt; #if 1 // Write matlab dat for postprocess char fname[BUFSIZ]; sprintf(fname, "Ax.dat"); FILE *fp; fp = fopen(fname, "w"); for(dlong n=1;n<*nnz;++n){ fprintf(fp, hlongFormat " " hlongFormat " %.8e\n", (*A)[n].row+1, (*A)[n].col+1, (*A)[n].val); } fclose(fp); #endif if(mesh->rank==0) printf("done.\n"); MPI_Barrier(mesh->comm); MPI_Type_free(&MPI_NONZERO_T); free(sendNonZeros); free(globalNumbering); free(globalOwners); free(AsendCounts); free(ArecvCounts); free(AsendOffsets); free(ArecvOffsets); } void ellipticBuildContinuousTet3D(elliptic_t *elliptic, dfloat lambda, nonZero_t **A, dlong *nnz, ogs_t **ogs, hlong *globalStarts) { mesh2D *mesh = elliptic->mesh; setupAide options = elliptic->options; int rank = mesh->rank; //use the masked gs handle to define a global ordering // number of degrees of freedom on this rank (after gathering) hlong Ngather = elliptic->ogs->Ngather; dlong Ntotal = mesh->Np*mesh->Nelements; // create a global numbering system hlong *globalIds = (hlong *) calloc(Ngather,sizeof(hlong)); int *owner = (int *) calloc(Ngather,sizeof(int)); // every gathered degree of freedom has its own global id MPI_Allgather(&Ngather, 1, MPI_HLONG, globalStarts+1, 1, MPI_HLONG, mesh->comm); for(int r=0;r<mesh->size;++r) globalStarts[r+1] = globalStarts[r]+globalStarts[r+1]; //use the offsets to set a consecutive global numbering for (dlong n =0;n<elliptic->ogs->Ngather;n++) { globalIds[n] = n + globalStarts[rank]; owner[n] = rank; } //scatter this numbering to the original nodes hlong *globalNumbering = (hlong *) calloc(Ntotal,sizeof(hlong)); int *globalOwners = (int *) calloc(Ntotal,sizeof(int)); for (dlong n=0;n<Ntotal;n++) globalNumbering[n] = -1; ogsScatter(globalNumbering, globalIds, ogsHlong, ogsAdd, elliptic->ogs); ogsScatter(globalOwners, owner, ogsInt, ogsAdd, elliptic->ogs); free(globalIds); free(owner); // Build non-zeros of stiffness matrix (unassembled) dlong nnzLocal = mesh->Np*mesh->Np*mesh->Nelements; nonZero_t *sendNonZeros = (nonZero_t*) calloc(nnzLocal, sizeof(nonZero_t)); int *AsendCounts = (int*) calloc(mesh->size, sizeof(int)); int *ArecvCounts = (int*) calloc(mesh->size, sizeof(int)); int *AsendOffsets = (int*) calloc(mesh->size+1, sizeof(int)); int *ArecvOffsets = (int*) calloc(mesh->size+1, sizeof(int)); int *mask = (int *) calloc(mesh->Np*mesh->Nelements,sizeof(int)); for (dlong n=0;n<elliptic->Nmasked;n++) mask[elliptic->maskIds[n]] = 1; //Build unassembed non-zeros if(mesh->rank==0) printf("Building full FEM matrix...");fflush(stdout); dlong cnt =0; #pragma omp parallel for for (dlong e=0;e<mesh->Nelements;e++) { dfloat Grr = mesh->ggeo[e*mesh->Nggeo + G00ID]; dfloat Grs = mesh->ggeo[e*mesh->Nggeo + G01ID]; dfloat Grt = mesh->ggeo[e*mesh->Nggeo + G02ID]; dfloat Gss = mesh->ggeo[e*mesh->Nggeo + G11ID]; dfloat Gst = mesh->ggeo[e*mesh->Nggeo + G12ID]; dfloat Gtt = mesh->ggeo[e*mesh->Nggeo + G22ID]; dfloat J = mesh->ggeo[e*mesh->Nggeo + GWJID]; for (int n=0;n<mesh->Np;n++) { if (mask[e*mesh->Np + n]) continue; //skip masked nodes for (int m=0;m<mesh->Np;m++) { if (mask[e*mesh->Np + m]) continue; //skip masked nodes dfloat val = 0.; val += Grr*mesh->Srr[m+n*mesh->Np]; val += Grs*mesh->Srs[m+n*mesh->Np]; val += Grt*mesh->Srt[m+n*mesh->Np]; val += Grs*mesh->Ssr[m+n*mesh->Np]; val += Gss*mesh->Sss[m+n*mesh->Np]; val += Gst*mesh->Sst[m+n*mesh->Np]; val += Grt*mesh->Str[m+n*mesh->Np]; val += Gst*mesh->Sts[m+n*mesh->Np]; val += Gtt*mesh->Stt[m+n*mesh->Np]; val += J*lambda*mesh->MM[m+n*mesh->Np]; dfloat nonZeroThreshold = 1e-7; if (fabs(val)>nonZeroThreshold) { #pragma omp critical { // pack non-zero sendNonZeros[cnt].val = val; sendNonZeros[cnt].row = globalNumbering[e*mesh->Np + n]; sendNonZeros[cnt].col = globalNumbering[e*mesh->Np + m]; sendNonZeros[cnt].ownerRank = globalOwners[e*mesh->Np + n]; cnt++; } } } } } // Make the MPI_NONZERO_T data type MPI_Datatype MPI_NONZERO_T; MPI_Datatype dtype[4] = {MPI_HLONG, MPI_HLONG, MPI_INT, MPI_DFLOAT}; int blength[4] = {1, 1, 1, 1}; MPI_Aint addr[4], displ[4]; MPI_Get_address ( &(sendNonZeros[0] ), addr+0); MPI_Get_address ( &(sendNonZeros[0].col ), addr+1); MPI_Get_address ( &(sendNonZeros[0].ownerRank), addr+2); MPI_Get_address ( &(sendNonZeros[0].val ), addr+3); displ[0] = 0; displ[1] = addr[1] - addr[0]; displ[2] = addr[2] - addr[0]; displ[3] = addr[3] - addr[0]; MPI_Type_create_struct (4, blength, displ, dtype, &MPI_NONZERO_T); MPI_Type_commit (&MPI_NONZERO_T); // count how many non-zeros to send to each process for(dlong n=0;n<cnt;++n) AsendCounts[sendNonZeros[n].ownerRank] += 1; // sort by row ordering qsort(sendNonZeros, cnt, sizeof(nonZero_t), parallelCompareRowColumn); // find how many nodes to expect (should use sparse version) MPI_Alltoall(AsendCounts, 1, MPI_INT, ArecvCounts, 1, MPI_INT, mesh->comm); // find send and recv offsets for gather *nnz = 0; for(int r=0;r<mesh->size;++r){ AsendOffsets[r+1] = AsendOffsets[r] + AsendCounts[r]; ArecvOffsets[r+1] = ArecvOffsets[r] + ArecvCounts[r]; *nnz += ArecvCounts[r]; } *A = (nonZero_t*) calloc(*nnz, sizeof(nonZero_t)); // determine number to receive MPI_Alltoallv(sendNonZeros, AsendCounts, AsendOffsets, MPI_NONZERO_T, (*A), ArecvCounts, ArecvOffsets, MPI_NONZERO_T, mesh->comm); // sort received non-zero entries by row block (may need to switch compareRowColumn tests) qsort((*A), *nnz, sizeof(nonZero_t), parallelCompareRowColumn); // compress duplicates cnt = 0; for(dlong n=1;n<*nnz;++n){ if((*A)[n].row == (*A)[cnt].row && (*A)[n].col == (*A)[cnt].col){ (*A)[cnt].val += (*A)[n].val; } else{ ++cnt; (*A)[cnt] = (*A)[n]; } } if (*nnz) cnt++; *nnz = cnt; if(mesh->rank==0) printf("done.\n"); MPI_Barrier(mesh->comm); MPI_Type_free(&MPI_NONZERO_T); free(sendNonZeros); free(globalNumbering); free(globalOwners); free(AsendCounts); free(ArecvCounts); free(AsendOffsets); free(ArecvOffsets); free(mask); } void ellipticBuildContinuousHex3D(elliptic_t *elliptic, dfloat lambda, nonZero_t **A, dlong *nnz, ogs_t **ogs, hlong *globalStarts) { mesh2D *mesh = elliptic->mesh; setupAide options = elliptic->options; int rank = mesh->rank; //use the masked gs handle to define a global ordering // number of degrees of freedom on this rank (after gathering) hlong Ngather = elliptic->ogs->Ngather; dlong Ntotal = mesh->Np*mesh->Nelements; // create a global numbering system hlong *globalIds = (hlong *) calloc(Ngather,sizeof(hlong)); int *owner = (int *) calloc(Ngather,sizeof(int)); // every gathered degree of freedom has its own global id MPI_Allgather(&Ngather, 1, MPI_HLONG, globalStarts+1, 1, MPI_HLONG, mesh->comm); for(int r=0;r<mesh->size;++r) globalStarts[r+1] = globalStarts[r]+globalStarts[r+1]; //use the offsets to set a consecutive global numbering for (dlong n =0;n<elliptic->ogs->Ngather;n++) { globalIds[n] = n + globalStarts[rank]; owner[n] = rank; } //scatter this numbering to the original nodes hlong *globalNumbering = (hlong *) calloc(Ntotal,sizeof(hlong)); int *globalOwners = (int *) calloc(Ntotal,sizeof(int)); for (dlong n=0;n<Ntotal;n++) globalNumbering[n] = -1; ogsScatter(globalNumbering, globalIds, ogsHlong, ogsAdd, elliptic->ogs); ogsScatter(globalOwners, owner, ogsInt, ogsAdd, elliptic->ogs); free(globalIds); free(owner); // 2. Build non-zeros of stiffness matrix (unassembled) dlong nnzLocal = mesh->Np*mesh->Np*mesh->Nelements; nonZero_t *sendNonZeros = (nonZero_t*) calloc(nnzLocal, sizeof(nonZero_t)); int *AsendCounts = (int*) calloc(mesh->size, sizeof(int)); int *ArecvCounts = (int*) calloc(mesh->size, sizeof(int)); int *AsendOffsets = (int*) calloc(mesh->size+1, sizeof(int)); int *ArecvOffsets = (int*) calloc(mesh->size+1, sizeof(int)); int *mask = (int *) calloc(mesh->Np*mesh->Nelements,sizeof(int)); for (dlong n=0;n<elliptic->Nmasked;n++) mask[elliptic->maskIds[n]] = 1; if(mesh->rank==0) printf("Building full FEM matrix...");fflush(stdout); dlong cnt =0; for (dlong e=0;e<mesh->Nelements;e++) { for (int nz=0;nz<mesh->Nq;nz++) { for (int ny=0;ny<mesh->Nq;ny++) { for (int nx=0;nx<mesh->Nq;nx++) { int idn = nx+ny*mesh->Nq+nz*mesh->Nq*mesh->Nq; if (mask[e*mesh->Np + idn]) continue; //skip masked nodes for (int mz=0;mz<mesh->Nq;mz++) { for (int my=0;my<mesh->Nq;my++) { for (int mx=0;mx<mesh->Nq;mx++) { int idm = mx+my*mesh->Nq+mz*mesh->Nq*mesh->Nq; if (mask[e*mesh->Np + idm]) continue; //skip masked nodes int id; dfloat val = 0.; if ((ny==my)&&(nz==mz)) { for (int k=0;k<mesh->Nq;k++) { id = k+ny*mesh->Nq+nz*mesh->Nq*mesh->Nq; dfloat Grr = mesh->ggeo[e*mesh->Np*mesh->Nggeo + id + G00ID*mesh->Np]; val += Grr*mesh->D[nx+k*mesh->Nq]*mesh->D[mx+k*mesh->Nq]; } } if (nz==mz) { id = mx+ny*mesh->Nq+nz*mesh->Nq*mesh->Nq; dfloat Grs = mesh->ggeo[e*mesh->Np*mesh->Nggeo + id + G01ID*mesh->Np]; val += Grs*mesh->D[nx+mx*mesh->Nq]*mesh->D[my+ny*mesh->Nq]; id = nx+my*mesh->Nq+nz*mesh->Nq*mesh->Nq; dfloat Gsr = mesh->ggeo[e*mesh->Np*mesh->Nggeo + id + G01ID*mesh->Np]; val += Gsr*mesh->D[mx+nx*mesh->Nq]*mesh->D[ny+my*mesh->Nq]; } if (ny==my) { id = mx+ny*mesh->Nq+nz*mesh->Nq*mesh->Nq; dfloat Grt = mesh->ggeo[e*mesh->Np*mesh->Nggeo + id + G02ID*mesh->Np]; val += Grt*mesh->D[nx+mx*mesh->Nq]*mesh->D[mz+nz*mesh->Nq]; id = nx+ny*mesh->Nq+mz*mesh->Nq*mesh->Nq; dfloat Gst = mesh->ggeo[e*mesh->Np*mesh->Nggeo + id + G02ID*mesh->Np]; val += Gst*mesh->D[mx+nx*mesh->Nq]*mesh->D[nz+mz*mesh->Nq]; } if ((nx==mx)&&(nz==mz)) { for (int k=0;k<mesh->Nq;k++) { id = nx+k*mesh->Nq+nz*mesh->Nq*mesh->Nq; dfloat Gss = mesh->ggeo[e*mesh->Np*mesh->Nggeo + id + G11ID*mesh->Np]; val += Gss*mesh->D[ny+k*mesh->Nq]*mesh->D[my+k*mesh->Nq]; } } if (nx==mx) { id = nx+my*mesh->Nq+nz*mesh->Nq*mesh->Nq; dfloat Gst = mesh->ggeo[e*mesh->Np*mesh->Nggeo + id + G12ID*mesh->Np]; val += Gst*mesh->D[ny+my*mesh->Nq]*mesh->D[mz+nz*mesh->Nq]; id = nx+ny*mesh->Nq+mz*mesh->Nq*mesh->Nq; dfloat Gts = mesh->ggeo[e*mesh->Np*mesh->Nggeo + id + G12ID*mesh->Np]; val += Gts*mesh->D[my+ny*mesh->Nq]*mesh->D[nz+mz*mesh->Nq]; } if ((nx==mx)&&(ny==my)) { for (int k=0;k<mesh->Nq;k++) { id = nx+ny*mesh->Nq+k*mesh->Nq*mesh->Nq; dfloat Gtt = mesh->ggeo[e*mesh->Np*mesh->Nggeo + id + G22ID*mesh->Np]; val += Gtt*mesh->D[nz+k*mesh->Nq]*mesh->D[mz+k*mesh->Nq]; } } if ((nx==mx)&&(ny==my)&&(nz==mz)) { id = nx + ny*mesh->Nq+nz*mesh->Nq*mesh->Nq; dfloat JW = mesh->ggeo[e*mesh->Np*mesh->Nggeo + id + GWJID*mesh->Np]; val += JW*lambda; } // pack non-zero dfloat nonZeroThreshold = 1e-7; if (fabs(val) >= nonZeroThreshold) { sendNonZeros[cnt].val = val; sendNonZeros[cnt].row = globalNumbering[e*mesh->Np + idn]; sendNonZeros[cnt].col = globalNumbering[e*mesh->Np + idm]; sendNonZeros[cnt].ownerRank = globalOwners[e*mesh->Np + idn]; cnt++; } } } } } } } } // Make the MPI_NONZERO_T data type MPI_Datatype MPI_NONZERO_T; MPI_Datatype dtype[4] = {MPI_HLONG, MPI_HLONG, MPI_INT, MPI_DFLOAT}; int blength[4] = {1, 1, 1, 1}; MPI_Aint addr[4], displ[4]; MPI_Get_address ( &(sendNonZeros[0] ), addr+0); MPI_Get_address ( &(sendNonZeros[0].col ), addr+1); MPI_Get_address ( &(sendNonZeros[0].ownerRank), addr+2); MPI_Get_address ( &(sendNonZeros[0].val ), addr+3); displ[0] = 0; displ[1] = addr[1] - addr[0]; displ[2] = addr[2] - addr[0]; displ[3] = addr[3] - addr[0]; MPI_Type_create_struct (4, blength, displ, dtype, &MPI_NONZERO_T); MPI_Type_commit (&MPI_NONZERO_T); // count how many non-zeros to send to each process for(dlong n=0;n<cnt;++n) AsendCounts[sendNonZeros[n].ownerRank]++; // sort by row ordering qsort(sendNonZeros, cnt, sizeof(nonZero_t), parallelCompareRowColumn); // find how many nodes to expect (should use sparse version) MPI_Alltoall(AsendCounts, 1, MPI_INT, ArecvCounts, 1, MPI_INT, mesh->comm); // find send and recv offsets for gather *nnz = 0; for(int r=0;r<mesh->size;++r){ AsendOffsets[r+1] = AsendOffsets[r] + AsendCounts[r]; ArecvOffsets[r+1] = ArecvOffsets[r] + ArecvCounts[r]; *nnz += ArecvCounts[r]; } *A = (nonZero_t*) calloc(*nnz, sizeof(nonZero_t)); // determine number to receive MPI_Alltoallv(sendNonZeros, AsendCounts, AsendOffsets, MPI_NONZERO_T, (*A), ArecvCounts, ArecvOffsets, MPI_NONZERO_T, mesh->comm); // sort received non-zero entries by row block (may need to switch compareRowColumn tests) qsort((*A), *nnz, sizeof(nonZero_t), parallelCompareRowColumn); // compress duplicates cnt = 0; for(dlong n=1;n<*nnz;++n){ if((*A)[n].row == (*A)[cnt].row && (*A)[n].col == (*A)[cnt].col){ (*A)[cnt].val += (*A)[n].val; } else{ ++cnt; (*A)[cnt] = (*A)[n]; } } if (*nnz) cnt++; *nnz = cnt; if(mesh->rank==0) printf("done.\n"); MPI_Barrier(mesh->comm); MPI_Type_free(&MPI_NONZERO_T); free(sendNonZeros); free(globalNumbering); free(globalOwners); free(AsendCounts); free(ArecvCounts); free(AsendOffsets); free(ArecvOffsets); }
omp_single_exemple.c
// omp_single_exemple.c // compile with: /openmp /* ############################################################################# ## DESCRIPTION: Simple exemple using single in OpenMP. ## NAME: omp_single_exemple.c ## AUTHOR: Lucca Pessoa da Silva Matos ## DATE: 10.04.2020 ## VERSION: 1.0 ## EXEMPLE: ## PS C:\> gcc -fopenmp -o omp_single_exemple omp_single_exemple.c ##############################################################################*/ // ============================================================================= // LIBRARYS // ============================================================================= #include <omp.h> #include <stdio.h> #include <stdlib.h> #include <locale.h> // ============================================================================= // MACROS // ============================================================================= #define NUM_THREADS 12 // ============================================================================= // CALL FUNCTIONS // ============================================================================= void cabecalho(); void set_portuguese(); // ============================================================================= // MAIN // ============================================================================= int main(int argc, char const *argv[]){ set_portuguese(); cabecalho(); int thread_id; printf("\n1 - Estamos fora do contexto paralelo. Entrando...\n\n"); #pragma omp parallel num_threads(2) { #pragma omp single // Only a single thread can read the input. printf("Read input\n"); // Multiple threads in the team compute the results. printf("Compute results\n"); #pragma omp single // Only a single thread can write the output. printf("Write output\n"); } printf("\n2 - Estamos fora do contexto paralelo. Saindo...\n"); return 0; } // ============================================================================= // FUNCTIONS // ============================================================================= void set_portuguese(){ setlocale(LC_ALL, "Portuguese"); } void cabecalho(){ printf("\n**************************************************"); printf("\n* *"); printf("\n* *"); printf("\n* PROGRAMACAO PARALELA COM OPENMP - LUCCA PESSOA *"); printf("\n* *"); printf("\n* *"); printf("\n**************************************************\n"); }
ch-placement-benchmark.c
/* * Copyright (C) 2013 University of Chicago. * See COPYRIGHT notice in top-level directory. * */ #include <string.h> #include <assert.h> #include <stdio.h> #include <stdint.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <limits.h> #include <sys/time.h> #include <math.h> #include <time.h> #include <omp.h> #include "ch-placement-oid-gen.h" #include "ch-placement.h" #ifdef CH_ENABLE_CRUSH #include "ch-placement-crush.h" #endif #include "comb.h" struct options { unsigned int num_servers; unsigned int num_devices; unsigned int num_objs; unsigned int replication; char *placement; unsigned int virt_factor; unsigned block_size; unsigned int sector_size; unsigned int threads; unsigned int algm; }; struct comb_stats { unsigned long count; unsigned long bytes; }; struct device_type{ int idex; int count; double cap; double remain; double bandwidth; double workload; double latency; long int endura; }; struct node_type{ int idex; int count; int device1_count; int device2_count; int device3_count; int num_device; double cap; double remain; double perform; double workload; struct device_type *media; }; const struct device_type DEVICE[3] = { {0,0, 1000000000000, //Byte 1000000000000, 96000000, //Bytes/s 0, 4200, //μs 1<<50 }, {0,0, 200000000000, 200000000000, 228000000, 0, 60, 1<<20 }, {0,0, 32000000000, 32000000000, 2100000000, 0, 12, 1<<40 } }; // static int comb_cmp(const void *a, const void *b); static int usage(char *exename); static struct options *parse_args(int argc, char *argv[]); #ifdef CH_ENABLE_CRUSH #include <hash.h> static int setup_crush(struct options *ig_opts, struct crush_map **map, __u32 **weight, int *n_weight) { struct crush_bucket *bucket; int i; int *items; int *weights; int ret; int id; struct crush_rule *rule; *n_weight = ig_opts->num_servers; *weight = malloc(sizeof(**weight) * ig_opts->num_servers); weights = malloc(sizeof(*weights) * ig_opts->num_servers); items = malloc(sizeof(*items) * ig_opts->num_servers); if (!(*weight) || !weights || !items || !map) { return (-1); } for (i = 0; i < ig_opts->num_servers; i++) { items[i] = i; weights[i] = 0x10000; (*weight)[i] = 0x10000; } *map = crush_create(); assert(*map); if (strcmp(ig_opts->placement, "crush-vring") == 0) #ifdef CH_ENABLE_CRUSH_VRING bucket = crush_make_bucket(*map, CRUSH_BUCKET_VRING, CRUSH_HASH_DEFAULT, 1, ig_opts->num_servers, items, weights); #else assert(0); #endif else bucket = crush_make_bucket(*map, CRUSH_BUCKET_STRAW, CRUSH_HASH_DEFAULT, 1, ig_opts->num_servers, items, weights); assert(bucket); ret = crush_add_bucket(*map, -2, bucket, &id); assert(ret == 0); crush_finalize(*map); rule = crush_make_rule(3, 0, 1, 1, 10); assert(rule); crush_rule_set_step(rule, 0, CRUSH_RULE_TAKE, id, 0); crush_rule_set_step(rule, 1, CRUSH_RULE_CHOOSELEAF_FIRSTN, 8, 0); crush_rule_set_step(rule, 2, CRUSH_RULE_EMIT, 0, 0); ret = crush_add_rule(*map, rule, 0); assert(ret == 0); return (0); } #endif ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* gen */ void server_gen(int num_servers ,int num_devices, struct node_type** server){ unsigned int i; int r = 0; *server = malloc(num_servers*sizeof(**server)); assert(*server); for(i=0; i<num_servers;i++){ r = rand() % 13; (*server)[i].idex = i; (*server)[i].count = 0; (*server)[i].num_device = num_devices; (*server)[i].cap = 0; (*server)[i].remain = 0; (*server)[i].perform = 0; (*server)[i].workload = 0; (*server)[i].device1_count = 0; (*server)[i].device2_count = 0; (*server)[i].device3_count = 0; } return; } void device_gen(struct node_type server_i , struct device_type** device){ unsigned int i; int r = 0; *device = malloc(server_i.num_device*sizeof(**device)); assert(*device); for(i=0;i<server_i.num_device;i++){ r = rand() % 3; (*device)[i].idex = i; (*device)[i].count = 0; (*device)[i].cap = DEVICE[r].cap; (*device)[i].remain = DEVICE[r].remain; (*device)[i].bandwidth = DEVICE[r].bandwidth; (*device)[i].workload = DEVICE[r].workload; (*device)[i].latency = DEVICE[r].latency; (*device)[i].endura = DEVICE[r].endura; } return; } //TACH int server_choose1(int i, int window, int num_server,struct node_type *server,double bsize){ int j =0; int k =0; double blocksize = bsize*1000,max = 0; double a[window],b[window],c[window],d[window]; for(k = 0;k<window;k++){ a[k] = server[(i+k)%num_server].cap * server[(i+k)%num_server].perform; b[k] = server[(i+k)%num_server].remain; c[k] = server[(i+k)%num_server].perform - server[(i+k)%num_server].workload; } for(k = 0;k<window;k++){ d[k] = ((b[k]-blocksize)*(c[k]-blocksize/10000)*a[k]+b[(k+1)%window]*c[(k+1)%window]*a[(k+1)%window]+b[(k+2)%window]*c[(k+2)%window]*a[(k+2)%window] ) / sqrt(((b[k]-blocksize)*(c[k]-blocksize/10000)*(b[k]-blocksize)*(c[k]-blocksize/10000) +b[(k+1)%window]*c[(k+1)%window]*b[(k+1)%window]*c[(k+1)%window] +b[(k+2)%window]*c[(k+2)%window]*b[(k+2)%window]*c[(k+2)%window])*(a[0]*a[0]+a[1]*a[1]+a[2]*a[2])); if(d[k]>max){ max = d[k]; j = k; } } return i+j; } int device_choose1(int i, int window,int num_device, struct device_type *device,double bsize){ int j = 0; int k = 0; double blocksize = bsize*1000,max = 0; double a[window]; double b[window]; double c[window]; double d[window]; for(k = 0;k<window;k++){ a[k] = device[(i+k)%num_device].cap * device[(i+k)%num_device].bandwidth / device[(i+k)%num_device].latency; b[k] = device[(i+k)%num_device].remain; c[k] = (device[(i+k)%num_device].bandwidth - device[(i+k)%num_device].workload) / device[(i+k)%num_device].latency; } for(k = 0;k<window;k++){ d[k] = ((b[k]-blocksize)*(c[k]-blocksize/10000)*a[k]+b[(k+1)%window]*c[(k+1)%window]*a[(k+1)%window]+b[(k+2)%window]*c[(k+2)%window]*a[(k+2)%window] ) / sqrt(((b[k]-blocksize)*(c[k]-blocksize/10000)*(b[k]-blocksize)*(c[k]-blocksize/10000) +b[(k+1)%window]*c[(k+1)%window]*b[(k+1)%window]*c[(k+1)%window] +b[(k+2)%window]*c[(k+2)%window]*b[(k+2)%window]*c[(k+2)%window])*(a[0]*a[0]+a[1]*a[1]+a[2]*a[2])); if(d[k]>max){ max = d[k]; j = k; } } return j+i; } //Capacity-based CH int server_choose2(int i, int window, int num_server,struct node_type *server,double bsize){ int j =0; int k =0; double blocksize = bsize*1000,max = 0; double a[window],b[window],c[window],d[window]; for(k = 0;k<window;k++){ a[k] = server[(i+k)%num_server].cap ; b[k] = server[(i+k)%num_server].remain; c[k] = 1; } for(k = 0;k<window;k++){ d[k] = ((b[k]-blocksize)*c[k]*a[k]+b[(k+1)%window]*c[(k+1)%window]*a[(k+1)%window]+b[(k+2)%window]*c[(k+2)%window]*a[(k+2)%window] ) / sqrt(((b[k]-blocksize)*c[k]*(b[k]-blocksize)*c[k] +b[(k+1)%window]*c[(k+1)%window]*b[(k+1)%window]*c[(k+1)%window] +b[(k+2)%window]*c[(k+2)%window]*b[(k+2)%window]*c[(k+2)%window])*(a[0]*a[0]+a[1]*a[1]+a[2]*a[2])); if(d[k]>max){ max = d[k]; j = k; } } return i+j; } int device_choose2(int i, int window,int num_device, struct device_type *device,double bsize){ int j = 0; int k = 0; double blocksize = bsize*1000,max = 0; double a[window]; double b[window]; double c[window]; double d[window]; for(k = 0;k<window;k++){ a[k] = device[(i+k)%num_device].cap ; b[k] = device[(i+k)%num_device].remain; c[k] = 1; } for(k = 0;k<window;k++){ d[k] = ((b[k]-blocksize)*c[k]*a[k]+b[(k+1)%window]*c[(k+1)%window]*a[(k+1)%window]+b[(k+2)%window]*c[(k+2)%window]*a[(k+2)%window] ) / sqrt(((b[k]-blocksize)*c[k]*(b[k]-blocksize)*c[k] +b[(k+1)%window]*c[(k+1)%window]*b[(k+1)%window]*c[(k+1)%window] +b[(k+2)%window]*c[(k+2)%window]*b[(k+2)%window]*c[(k+2)%window])*(a[0]*a[0]+a[1]*a[1]+a[2]*a[2])); if(d[k]>max){ max = d[k]; j = k; } } return j+i; } //Performance-based CH int server_choose3(int i, int window, int num_server,struct node_type *server,double bsize){ int j =0; int k =0; double blocksize = bsize*1000,max = 0; double a[window],b[window],c[window],d[window]; for(k = 0;k<window;k++){ a[k] = server[(i+k)%num_server].perform; b[k] = server[(i+k)%num_server].remain; c[k] = server[(i+k)%num_server].perform - server[(i+k)%num_server].workload; } for(k = 0;k<window;k++){ d[k] = ((c[k]-blocksize)*a[k]+c[(k+1)%window]*a[(k+1)%window]+c[(k+2)%window]*a[(k+2)%window] ) / sqrt(((c[k]-blocksize)*(c[k]-blocksize) +c[(k+1)%window]*c[(k+1)%window] +c[(k+2)%window]*c[(k+2)%window])*(a[0]*a[0]+a[1]*a[1]+a[2]*a[2])); if(d[k]>max){ max = d[k]; j = k; } } return i+j; } int device_choose3(int i, int window,int num_device, struct device_type *device,double bsize){ int j = 0; int k = 0; double blocksize = bsize*1000,max = 0; double a[window]; double b[window]; double c[window]; double d[window]; for(k = 0;k<window;k++){ a[k] = device[(i+k)%num_device].bandwidth; b[k] = device[(i+k)%num_device].remain; c[k] = (device[(i+k)%num_device].bandwidth - device[(i+k)%num_device].workload) ; } for(k = 0;k<window;k++){ d[k] = ((c[k]-blocksize)*a[k]+c[(k+1)%window]*a[(k+1)%window]+c[(k+2)%window]*a[(k+2)%window] ) / sqrt(((c[k]-blocksize)*(c[k]-blocksize) +c[(k+1)%window]*c[(k+1)%window] +c[(k+2)%window]*c[(k+2)%window])*(a[0]*a[0]+a[1]*a[1]+a[2]*a[2])); if(d[k]>max){ max = d[k]; j = k; } } return j+i; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int main( int argc, char **argv) { struct options *ig_opts = NULL; unsigned long total_byte_count = 0; unsigned long total_obj_count = 0; struct obj *total_objs = NULL; struct node_type *server = NULL; struct device_type *device = NULL; unsigned int i,j,k; struct ch_placement_instance *instance; struct ch_placement_instance *instance2; int fd; struct comb_stats *cs; uint64_t num_combs; unsigned long comb_tmp[CH_MAX_REPLICATION]; unsigned long server_index[CH_MAX_REPLICATION]; unsigned long device_index_temp[1]; unsigned long device_index; int ret; // srand((unsigned)time(NULL)); //random seed srand(123); //solid seed struct timeval start1,end1; gettimeofday(&start1, NULL ); #ifdef CH_ENABLE_CRUSH struct crush_map *map; __u32 *weight; int n_weight; #endif ig_opts = parse_args(argc, argv); // input ig_opts->placement = "ring"; //we use ring hashing if (!ig_opts) { usage(argv[0]); return (-1); } if (strcmp(ig_opts->placement, "crush") == 0 || strcmp(ig_opts->placement, "crush-vring") == 0) { #ifdef CH_ENABLE_CRUSH ret = setup_crush(ig_opts, &map, &weight, &n_weight); if (ret < 0) { fprintf(stderr, "Error: failed to set up CRUSH.\n"); return (-1); } instance = ch_placement_initialize_crush(map, weight, n_weight); #else fprintf(stderr, "Error: not compiled with CRUSH support.\n"); #endif } else { instance = ch_placement_initialize(ig_opts->placement, ig_opts->num_servers, ig_opts->virt_factor, 0); } /* generate random set of objects for testing */ printf("# Generating random object IDs...\n"); oid_gen("random", instance, ig_opts->num_objs, ULONG_MAX, 8675309, ig_opts->replication, ig_opts->num_servers, NULL, &total_byte_count, &total_obj_count, &total_objs); /* generate server and device */ server_gen(ig_opts->num_servers, ig_opts->num_devices,&server); for(i = 0; i < ig_opts->num_servers; i++){ double sum1 = 0, sum2 = 0; device_gen(server[i] ,&device); server[i].media = device; for(j = 0;j<server[i].num_device;j++){ sum1 += device[j].bandwidth; sum2 += device[j].cap; } server[i].perform = (sum1 / (server[i].num_device)); server[i].cap = sum2; server[i].remain = sum2; } printf("# Done.\n"); printf("# Object population consuming approximately %lu MiB of memory.\n", (ig_opts->num_objs * sizeof(*total_objs)) / (1024 * 1024)); assert(total_obj_count == ig_opts->num_objs); sleep(1); printf("# Calculating placement for each object ID...\n"); int o = 0; double timecost = 0; double Time = 0; double Time_last = 0; struct node_type *server_last = NULL; server_last = malloc(ig_opts->num_servers*sizeof(*server_last)); unsigned int block = (ig_opts->block_size)*1000; unsigned int THD = ig_opts->threads; double incre[THD]; int tid = 0; #pragma omp parallel num_threads(THD) { for (i = 0; i < ig_opts->num_objs; i++) { ch_placement_find_closest(instance, total_objs[i].oid, ig_opts->replication, total_objs[i].server_idxs); //hashing memcpy(comb_tmp, total_objs[i].server_idxs, //hashing result, saved in comb_tmp ig_opts->replication * sizeof(*comb_tmp)); /* hashing */ for(j = 0;j<ig_opts->replication;j++){ switch(ig_opts->algm) { case 1: server_index[j] = server_choose1(comb_tmp[j],ig_opts->sector_size,ig_opts->num_servers,server,ig_opts->block_size) % ig_opts->num_servers; break; case 2: server_index[j] = server_choose2(comb_tmp[j],ig_opts->sector_size,ig_opts->num_servers,server,ig_opts->block_size) % ig_opts->num_servers; break; case 3: server_index[j] = server_choose3(comb_tmp[j],ig_opts->sector_size,ig_opts->num_servers,server,ig_opts->block_size) % ig_opts->num_servers; break; case 4: server_index[j] = comb_tmp[j] % ig_opts->num_servers; break; } //server_index[j] = server_choose(comb_tmp[j],ig_opts->sector_size,ig_opts->num_servers,server,ig_opts->block_size) % ig_opts->num_servers; server[server_index[j]].count++; server[server_index[j]].remain = server[server_index[j]].remain - block; server[server_index[j]].workload = server[server_index[j]].workload + block/10000; instance2 = ch_placement_initialize(ig_opts->placement, server[server_index[j]].num_device, ig_opts->virt_factor, 0); ch_placement_find_closest(instance2, total_objs[i].oid, 1, device_index_temp);//hashing switch(ig_opts->algm) { case 1: device_index = device_choose1(device_index_temp[0],ig_opts->sector_size,server[server_index[j]].num_device, server[server_index[j]].media,ig_opts->block_size) % server[server_index[j]].num_device; break; case 2: device_index = device_choose2(device_index_temp[0],ig_opts->sector_size,server[server_index[j]].num_device, server[server_index[j]].media,ig_opts->block_size) % server[server_index[j]].num_device; break; case 3: device_index = device_choose3(device_index_temp[0],ig_opts->sector_size,server[server_index[j]].num_device, server[server_index[j]].media,ig_opts->block_size) % server[server_index[j]].num_device; break; case 4: device_index = device_index_temp[0] % server[server_index[j]].num_device; break; } //device_index = device_choose(device_index_temp[0],ig_opts->sector_size,server[server_index[j]].num_device, server[server_index[j]].media,ig_opts->block_size) % server[server_index[j]].num_device; tid = omp_get_thread_num(); incre[tid] = block /(server[server_index[j]].media[device_index].bandwidth); double yu = 0; yu = (i*3+j)%THD; if(yu==THD-1){ double max = 0; double sm = 0; for(k = 0;k<THD;k++){ sm += incre[k]; } max = sm/THD; Time = Time + max; } server[server_index[j]].media[device_index].count++; if(server[server_index[j]].media[device_index].latency == 4200){ server[server_index[j]].device1_count++; } if(server[server_index[j]].media[device_index].latency == 60){ server[server_index[j]].device2_count++; } if(server[server_index[j]].media[device_index].latency == 12){ server[server_index[j]].device3_count++; } server[server_index[j]].media[device_index].remain = server[server_index[j]].media[device_index].remain - block; server[server_index[j]].media[device_index].workload = server[server_index[j]].media[device_index].workload + block/10000; } } } gettimeofday(&end1, NULL ); long timeuse =1000000 * ( end1.tv_sec - start1.tv_sec ) + end1.tv_usec - start1.tv_usec; double sumsum = 0; for(i = 0;i<ig_opts->num_servers;i++){ sumsum += server[i].cap/1000000000 * server[i].perform/1000000 ; } /* result */ for(i = 0;i<ig_opts->num_servers;i++){ printf("server_index:%d\n ", i); printf("capcity:%.1f GB\n remain:%.1f GB\n perform:%.0lf MBps\n num_device:%.0d\n", server[i].cap/1000000000,server[i].remain/1000000000, server[i].perform/1000000, server[i].num_device); printf("workload:%.1lf MBps\n",server[i].workload/1000000); printf("datacount:%d\n",server[i].count); printf("device1_count:%d\n",server[i].device1_count); printf("device2_count:%d\n",server[i].device2_count); printf("device3_count:%d\n",server[i].device3_count); double use = 0; use = (server[i].cap - server[i].remain) / server[i].cap * 100; printf("used_rate(%):%.2f\n",use); //ideal distribution // double ca = server[i].cap/1000000000; // double pe = server[i].perform/1000000; // double x = ca*pe/sumsum; //rate_x // double y = ig_opts->num_objs * ig_opts->replication * x; // printf("ideal_count:%.0f\n",y); //device info if need /* for(int j = 0;j<server[i].num_device;j++){ printf("device index:%d\t device_cap:%.1f GB\t",j,server[i].media[j].cap / 1000000000); printf("device remain:%.1f GB\t",server[i].media[j].remain / 1000000000); printf("device_bandwidth:%.0lf MBps\t",server[i].media[j].bandwidth / 1000000); printf("device_workload:%.1lf\t",server[i].media[j].workload); printf("device_latency:%.0f μs\n",server[i].media[j].latency); printf("data_count:%d \n",server[i].media[j].count); } */ printf("\n"); } printf("total_byte_count:%ld\n total_obj_count:%ld\n",total_byte_count,total_obj_count); printf("time_algorithm=%f\n",timeuse /1000000.0); printf("time_distribution=%f\n",Time); printf("# Done.\n"); /* we don't need the global list any more */ free(total_objs); total_obj_count = 0; total_byte_count = 0; return (0); } static int usage(char *exename) { fprintf(stderr, "Usage: %s [options]\n", exename); fprintf(stderr, " -s <number of servers>\n"); fprintf(stderr, " -d <number of devices>\n"); fprintf(stderr, " -o <number of objects>\n"); fprintf(stderr, " -r <replication factor>\n"); fprintf(stderr, " -v <virtual nodes per physical node>\n"); fprintf(stderr, " -b <size of block (KB)>\n"); fprintf(stderr, " -e <size of sector>\n"); fprintf(stderr, " -t <number of threads>\n"); fprintf(stderr, " -a <placement algorithm(1=TACH 2=Capacity-based 3=Performance-based 4=CH)>\n"); exit(1); } static struct options *parse_args(int argc, char *argv[]) { struct options *opts = NULL; int ret = -1; int one_opt = 0; opts = (struct options *)malloc(sizeof(*opts)); if (!opts) return (NULL); memset(opts, 0, sizeof(*opts)); while ((one_opt = getopt(argc, argv, "s:d:o:r:hv:b:e:t:a:")) != EOF) { switch (one_opt) { case 's': ret = sscanf(optarg, "%u", &opts->num_servers); if (ret != 1) return (NULL); break; case 'd': ret = sscanf(optarg, "%u", &opts->num_devices); if (ret != 1) return (NULL); break; case 'o': ret = sscanf(optarg, "%u", &opts->num_objs); if (ret != 1) return (NULL); break; case 'v': ret = sscanf(optarg, "%u", &opts->virt_factor); if (ret != 1) return (NULL); break; case 'r': ret = sscanf(optarg, "%u", &opts->replication); if (ret != 1) return (NULL); break; case 'b': ret = sscanf(optarg, "%u", &opts->block_size); if (ret != 1) return (NULL); break; case 'e': ret = sscanf(optarg, "%u", &opts->sector_size); if (ret != 1) return (NULL); break; case 't': ret = sscanf(optarg, "%u", &opts->threads); if (ret != 1) return (NULL); break; case 'a': ret = sscanf(optarg, "%u", &opts->algm); if (ret != 1) return (NULL); break; /* case 'p': opts->placement = strdup(optarg); if (!opts->placement) return (NULL); break; */ case '?': usage(argv[0]); exit(1); case 'h': usage(argv[0]); exit(1); } } if (opts->replication < 2) return (NULL); if (opts->num_servers < (opts->replication + 1)) return (NULL); if (opts->num_devices < 1) return (NULL); if (opts->num_objs < 1) return (NULL); if (opts->virt_factor < 1) return (NULL); /* if (!opts->placement) return (NULL); */ if (opts->num_devices<1) return (NULL); if (opts->sector_size<3) return (NULL); if (opts->threads<1) return (NULL); if (opts->algm!=1 && opts->algm!=2 && opts->algm!=3 && opts->algm!=4) return (NULL); assert(opts->replication <= CH_MAX_REPLICATION); return (opts); } static int comb_cmp(const void *a, const void *b) { unsigned long au = ((struct comb_stats *)a)->count; unsigned long bu = ((struct comb_stats *)b)->count; int rtn; if (au < bu) rtn = -1; else if (au == bu) rtn = 0; else rtn = 1; return rtn; } /* * Local variables: * c-indent-level: 4 * c-basic-offset: 4 * End: * * vim: ft=c ts=8 sts=4 sw=4 expandtab */
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] = 16; tile_size[1] = 16; tile_size[2] = 16; 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; // 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<=floord(Nt-1,2);t1++) { lbp=max(ceild(t1,2),ceild(4*t1-Nt+2,4)); ubp=min(floord(4*Nt+Nz-9,16),floord(8*t1+Nz+2,16)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(0,ceild(t1-1,2)),ceild(16*t2-Nz-3,16));t3<=min(min(min(floord(4*Nt+Ny-9,16),floord(8*t1+Ny+7,16)),floord(16*t2+Ny+3,16)),floord(16*t1-16*t2+Nz+Ny+5,16));t3++) { for (t4=max(max(max(0,ceild(t1-31,32)),ceild(16*t2-Nz-243,256)),ceild(16*t3-Ny-243,256));t4<=min(min(min(min(floord(4*Nt+Nx-9,256),floord(8*t1+Nx+7,256)),floord(16*t2+Nx+3,256)),floord(16*t3+Nx+3,256)),floord(16*t1-16*t2+Nz+Nx+5,256));t4++) { for (t5=max(max(max(max(max(0,ceild(16*t2-Nz+5,4)),ceild(16*t3-Ny+5,4)),ceild(256*t4-Nx+5,4)),2*t1),4*t1-4*t2+1);t5<=min(min(min(min(min(floord(16*t1-16*t2+Nz+10,4),Nt-1),2*t1+3),4*t2+2),4*t3+2),64*t4+62);t5++) { for (t6=max(max(16*t2,4*t5+4),-16*t1+16*t2+8*t5-15);t6<=min(min(16*t2+15,-16*t1+16*t2+8*t5),4*t5+Nz-5);t6++) { for (t7=max(16*t3,4*t5+4);t7<=min(16*t3+15,4*t5+Ny-5);t7++) { lbv=max(256*t4,4*t5+4); ubv=min(256*t4+255,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; }
SimulationTools.h
////////////////////////////////////////////////////////////////////////////////// // COMPANY: Ruhr University Bochum, Embedded Security // AUTHOR: Amir Moradi (for the paper: https://eprint.iacr.org/2019/1312 ) ////////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2019, Amir Moradi // All rights reserved. // // BSD-3-Clause License // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the copyright holder, their organization nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTERS 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. //*************************************************************************************** int RunSimulation(SignalStruct** Signals, int ClockSignal, int Max_No_ClockCycles, int InitialSim_NumberOfClockCycles, int InitialSim_NumberOfInputs, int** InitialSim_Inputs, char** InitialSim_Values, CellStruct** Cells, int* Regs, int NumberOfRegs, short MaxDepth, int** CellsInDepth, int* NumberOfCellsInDepth, CellTypeStruct** CellTypes, int* EndSimCondition_Signals, char* EndSimCondition_Values, int EndSimCondition_NumberOfSignals, int EndSim_NumberOfWaitCycles, int* SignalValues, int* RegValues, char*** Faults) { int i; int InputIndex; int OutputIndex; int SignalIndex; int RegIndex; int DepthIndex; int CellIndex; int ClockCycle; int v; int Value; int NumberOfWaitedClockCycles = -1; for (ClockCycle = 0;ClockCycle < Max_No_ClockCycles;ClockCycle++) { SignalValues[ClockSignal] = 1; // ----------- evaluate the registers for (RegIndex = 0;RegIndex < NumberOfRegs;RegIndex++) { v = 0; for (InputIndex = 0;InputIndex < Cells[Regs[RegIndex]]->NumberOfInputs;InputIndex++) v |= SignalValues[Cells[Regs[RegIndex]]->Inputs[InputIndex]] << InputIndex; for (OutputIndex = 0;OutputIndex < Cells[Regs[RegIndex]]->NumberOfOutputs;OutputIndex++) v |= RegValues[Cells[Regs[RegIndex]]->RegValueIndexes[OutputIndex]] << (Cells[Regs[RegIndex]]->NumberOfInputs + OutputIndex); for (OutputIndex = 0;OutputIndex < Cells[Regs[RegIndex]]->NumberOfOutputs;OutputIndex++) { Value = CellTypes[Cells[Regs[RegIndex]]->Type]->Tables[OutputIndex][v]; Value ^= Faults[FaultInjection_toggle][ClockCycle][Regs[RegIndex]]; Value |= Faults[FaultInjection_stuck_at_1][ClockCycle][Regs[RegIndex]]; Value &= !Faults[FaultInjection_stuck_at_0][ClockCycle][Regs[RegIndex]]; RegValues[Cells[Regs[RegIndex]]->RegValueIndexes[OutputIndex]] = Value; } } // ----------- applying the initial inputs if (ClockCycle < InitialSim_NumberOfClockCycles) for (InputIndex = 0;InputIndex < InitialSim_NumberOfInputs;InputIndex++) SignalValues[InitialSim_Inputs[ClockCycle][InputIndex]] = InitialSim_Values[ClockCycle][InputIndex]; // ----------- applying the register outputs to the output signals for (RegIndex = 0;RegIndex < NumberOfRegs;RegIndex++) for (OutputIndex = 0;OutputIndex < Cells[Regs[RegIndex]]->NumberOfOutputs;OutputIndex++) if (Cells[Regs[RegIndex]]->Outputs[OutputIndex] != -1) SignalValues[Cells[Regs[RegIndex]]->Outputs[OutputIndex]] = RegValues[Cells[Regs[RegIndex]]->RegValueIndexes[OutputIndex]]; // ----------- evaluate the circuits :D for (DepthIndex = 1;DepthIndex <= MaxDepth;DepthIndex++) { for (i = 0;i < NumberOfCellsInDepth[DepthIndex];i++) { CellIndex = CellsInDepth[DepthIndex][i]; v = 0; for (InputIndex = 0;InputIndex < Cells[CellIndex]->NumberOfInputs;InputIndex++) v |= SignalValues[Cells[CellIndex]->Inputs[InputIndex]] << InputIndex; for (OutputIndex = 0;OutputIndex < Cells[CellIndex]->NumberOfOutputs;OutputIndex++) if (Cells[CellIndex]->Outputs[OutputIndex] != -1) { Value = CellTypes[Cells[CellIndex]->Type]->Tables[OutputIndex][v]; Value ^= Faults[FaultInjection_toggle][ClockCycle][CellIndex]; Value |= Faults[FaultInjection_stuck_at_1][ClockCycle][CellIndex]; Value &= !Faults[FaultInjection_stuck_at_0][ClockCycle][CellIndex]; SignalValues[Cells[CellIndex]->Outputs[OutputIndex]] = Value; } } } SignalValues[ClockSignal] = 0; // re-evaluate (we don't need it in this design since it works only at possitive edge of the clock and does not have a latch // // // // ----------- check the conditions to terminate the simulation if (ClockCycle > InitialSim_NumberOfClockCycles) { if (NumberOfWaitedClockCycles == -1) { for (SignalIndex = 0;SignalIndex < EndSimCondition_NumberOfSignals;SignalIndex++) if (SignalValues[EndSimCondition_Signals[SignalIndex]] != EndSimCondition_Values[SignalIndex]) break; if (SignalIndex >= EndSimCondition_NumberOfSignals) NumberOfWaitedClockCycles = 0; } else NumberOfWaitedClockCycles++; if (NumberOfWaitedClockCycles >= EndSim_NumberOfWaitCycles) break; } } return (ClockCycle); } //*************************************************************************************** int RunFaultInjection(int Max_no_of_Threads, SignalStruct** Signals, int NumberOfSignals, int ClockSignal, int NumberOfRegValues, int Max_No_ClockCycles, CellStruct** Cells, int NumberOfCells, char FaultInjectionType, char FaultInjectionMethod, int NumberOfSimulationsInFile, int NumberOfTargetClockCycles, int* TargetClockCycles, int MaxNumberOfFaultsPerRun, int MinNumberOfFaultsPerRun, int MaxNumberOfFaultsPerCycle, int MinNumberOfFaultsPerCycle, char* EvaluationResultFileName, int InitialSim_NumberOfClockCycles, int InitialSim_NumberOfInputs, int** InitialSim_Inputs, char** InitialSim_Values, int* Regs, int NumberOfRegs, short MaxDepth, int** CellsInDepth, int* NumberOfCellsInDepth, CellTypeStruct** CellTypes, int* EndSimCondition_Signals, char* EndSimCondition_Values, int EndSimCondition_NumberOfSignals, int EndSim_NumberOfWaitCycles, char** EndSim_OutputNames,int* EndSim_Outputs_IndexL, int* EndSim_Outputs_IndexH, char* EndSim_Outputs_Base, int EndSim_NumberOfOutputBlocks, int* FaultFreeSignalValues, int NumberOfFaultFreeOutputs, int* FaultFreeOutputs, char Print_Nondetected, char Print_Detected, char Print_Ineffective, char Print_RunTimeOver, SimulationResultStruct* &SimulationResults, int &NumberOfSimulations) { int CellIndex; int *FaultAllowedCells; int NumberOfFaultAllowedCells; int ClockCycle; int **SignalValues = NULL; int **RegValues = NULL; char ****Faults = NULL; int ThreadIndex; int SimulationIndex; int SimulationCounter; int RangeNumberOfFaultsPerCycle; int RangeNumberOfFaultsPerRun; int *DetectedCounter; int *NondetectedCounter; int *IneffectiveCounter; int *RunTimeOverCounter; FILE *EvaluationResultFile; int TotalDetected; int TotalNondetected; int TotalIneffective; int TotalRunTimeOver; int LocalIndex; int i, j, k; char ValidSimulation; int NumberOfInjectedFaults; int NumberOfFaultsInCycle; int SelectedNumberOfInjectedFaults; char *Seeded; char abort; int MaxTargetClockCycle; int MinTargetClockCycle; char *TargetClockCycleValid; int ClockCycleIndex; clock_t begin; NumberOfFaultAllowedCells = 0; for (CellIndex = 0;CellIndex < NumberOfCells;CellIndex++) if (Cells[CellIndex]->FaultAllowed) NumberOfFaultAllowedCells++; FaultAllowedCells = (int*)malloc(NumberOfFaultAllowedCells * sizeof(int)); NumberOfFaultAllowedCells = 0; for (CellIndex = 0;CellIndex < NumberOfCells;CellIndex++) if (Cells[CellIndex]->FaultAllowed) FaultAllowedCells[NumberOfFaultAllowedCells++] = CellIndex; SignalValues = (int **)malloc(Max_no_of_Threads * sizeof(int *)); RegValues = (int **)malloc(Max_no_of_Threads * sizeof(int *)); Faults = (char ****)malloc(Max_no_of_Threads * sizeof(char ***)); DetectedCounter = (int *)calloc(Max_no_of_Threads, sizeof(int)); NondetectedCounter = (int *)calloc(Max_no_of_Threads, sizeof(int)); IneffectiveCounter = (int *)calloc(Max_no_of_Threads, sizeof(int)); RunTimeOverCounter = (int *)calloc(Max_no_of_Threads, sizeof(int)); Seeded = (char *)calloc(Max_no_of_Threads, sizeof(char)); for (ThreadIndex = 0;ThreadIndex < Max_no_of_Threads;ThreadIndex++) { SignalValues[ThreadIndex] = (int *)calloc(NumberOfSignals, sizeof(int)); RegValues[ThreadIndex] = (int *)calloc(NumberOfRegValues, sizeof(int)); Faults[ThreadIndex] = (char ***)malloc(NumberOfFaultInjectionTypes * sizeof(char **)); SignalValues[ThreadIndex][1] = 1; // constant 1'b1 for (i = 0;i < NumberOfFaultInjectionTypes;i++) { Faults[ThreadIndex][i] = (char **)malloc(Max_No_ClockCycles * sizeof(char *)); for (ClockCycle = 0;ClockCycle < Max_No_ClockCycles;ClockCycle++) Faults[ThreadIndex][i][ClockCycle] = (char *)calloc(NumberOfCells, sizeof(char)); } } TargetClockCycleValid = (char*)calloc(Max_No_ClockCycles, sizeof(char)); MaxTargetClockCycle = TargetClockCycles[0]; MinTargetClockCycle = TargetClockCycles[0]; for (ClockCycleIndex = 0;ClockCycleIndex < NumberOfTargetClockCycles;ClockCycleIndex++) { TargetClockCycleValid[TargetClockCycles[ClockCycleIndex]] = 1; if (MaxTargetClockCycle < TargetClockCycles[ClockCycleIndex]) MaxTargetClockCycle = TargetClockCycles[ClockCycleIndex]; if (MinTargetClockCycle > TargetClockCycles[ClockCycleIndex]) MinTargetClockCycle = TargetClockCycles[ClockCycleIndex]; } if (FaultInjectionMethod == FaultInjection_Exhaustive) NumberOfSimulations = pow(NumberOfFaultAllowedCells, MinNumberOfFaultsPerCycle * NumberOfTargetClockCycles); else // FaultInjection_Random NumberOfSimulations = NumberOfSimulationsInFile; if (NumberOfSimulations > 600000000L) { printf("Number of simulations %d is over the threshold", NumberOfSimulations); _getch(); return 1; } else { if (FaultInjectionMethod == FaultInjection_Exhaustive) printf("Number of cells to be faulty: %d\n", NumberOfFaultAllowedCells); printf("Number of simulations: %d\n", NumberOfSimulations); } SimulationResults = (SimulationResultStruct *)malloc(NumberOfSimulations * sizeof(SimulationResultStruct)); omp_set_num_threads(Max_no_of_Threads); RangeNumberOfFaultsPerCycle = MaxNumberOfFaultsPerCycle - MinNumberOfFaultsPerCycle + 1; RangeNumberOfFaultsPerRun = MaxNumberOfFaultsPerRun - MinNumberOfFaultsPerRun + 1; SimulationCounter = 0; EvaluationResultFile = fopen(EvaluationResultFileName, "wt"); abort = 0; begin = clock(); for (i = 0;i < NumberOfSignals;i++) if (!strcmp(Signals[i]->Name, "Error_0_")) i = i; #pragma omp parallel for schedule(guided) private(ThreadIndex, ClockCycleIndex, ClockCycle, i, j, k, LocalIndex, SelectedNumberOfInjectedFaults, NumberOfInjectedFaults, NumberOfFaultsInCycle, ValidSimulation, TotalDetected, TotalNondetected, TotalIneffective, TotalRunTimeOver) for (SimulationIndex = 0;SimulationIndex < NumberOfSimulations; SimulationIndex++) { if (!abort) { if (_kbhit()) { #pragma omp critical { if ((!abort) & _kbhit()) { char ch = _getch(); if (ch == 'q') { printf("abort\n"); abort++; } } } } ThreadIndex = omp_get_thread_num(); if (!Seeded[ThreadIndex]) { srand(int(time(NULL)) ^ ThreadIndex); Seeded[ThreadIndex] = 1; } SimulationResults[SimulationIndex].TaregtCells = (int *)malloc(MaxNumberOfFaultsPerRun * sizeof(int)); SimulationResults[SimulationIndex].TaregtClockCycles = (int *)malloc(MaxNumberOfFaultsPerRun * sizeof(int)); if (FaultInjectionMethod == FaultInjection_Exhaustive) { NumberOfInjectedFaults = NumberOfTargetClockCycles * MinNumberOfFaultsPerCycle; ValidSimulation = 1; LocalIndex = SimulationIndex; for (ClockCycleIndex = 0;(ClockCycleIndex < NumberOfTargetClockCycles) & ValidSimulation;ClockCycleIndex++) { k = ClockCycleIndex * MinNumberOfFaultsPerCycle; for (i = 0;(i < MinNumberOfFaultsPerCycle) & ValidSimulation;i++) { SimulationResults[SimulationIndex].TaregtCells[k + i] = FaultAllowedCells[LocalIndex % NumberOfFaultAllowedCells]; LocalIndex = (LocalIndex - (LocalIndex % NumberOfFaultAllowedCells)) / NumberOfFaultAllowedCells; SimulationResults[SimulationIndex].TaregtClockCycles[k + i] = TargetClockCycles[ClockCycleIndex]; for (j = 0;(j < i) & ValidSimulation;j++) if (SimulationResults[SimulationIndex].TaregtCells[k + i] >= SimulationResults[SimulationIndex].TaregtCells[k + j]) ValidSimulation = 0; } } } else //FaultInjection_Random { NumberOfInjectedFaults = 0; ValidSimulation = 1; SelectedNumberOfInjectedFaults = MinNumberOfFaultsPerRun + (rand() % RangeNumberOfFaultsPerRun); while (NumberOfInjectedFaults < SelectedNumberOfInjectedFaults) { do { ClockCycleIndex = rand() % NumberOfTargetClockCycles; ClockCycle = TargetClockCycles[ClockCycleIndex]; for (j = 0;j < NumberOfInjectedFaults;j++) if (SimulationResults[SimulationIndex].TaregtClockCycles[j] == ClockCycle) break; } while (j < NumberOfInjectedFaults); NumberOfFaultsInCycle = MinNumberOfFaultsPerCycle + (rand() % RangeNumberOfFaultsPerCycle); for (i = 0;(i < NumberOfFaultsInCycle) & (NumberOfInjectedFaults < MaxNumberOfFaultsPerRun);i++) { SimulationResults[SimulationIndex].TaregtCells[NumberOfInjectedFaults] = rand() % NumberOfCells; if (Cells[SimulationResults[SimulationIndex].TaregtCells[NumberOfInjectedFaults]]->FaultAllowed) { SimulationResults[SimulationIndex].TaregtClockCycles[NumberOfInjectedFaults] = ClockCycle; for (j = 0;j < i;j++) if (SimulationResults[SimulationIndex].TaregtCells[NumberOfInjectedFaults] == SimulationResults[SimulationIndex].TaregtCells[NumberOfInjectedFaults - j - 1]) break; if (j < i) i--; else NumberOfInjectedFaults++; } else i--; } } } SimulationResults[SimulationIndex].Valid = ValidSimulation; if (ValidSimulation) { SimulationResults[SimulationIndex].NumberOfInjectedFaults = NumberOfInjectedFaults; for (i = 0;i < NumberOfInjectedFaults;i++) Faults[ThreadIndex][FaultInjectionType][SimulationResults[SimulationIndex].TaregtClockCycles[i]][SimulationResults[SimulationIndex].TaregtCells[i]] = 1; ClockCycle = RunSimulation(Signals, ClockSignal, Max_No_ClockCycles, InitialSim_NumberOfClockCycles, InitialSim_NumberOfInputs, InitialSim_Inputs, InitialSim_Values, Cells, Regs, NumberOfRegs, MaxDepth, CellsInDepth, NumberOfCellsInDepth, CellTypes, EndSimCondition_Signals, EndSimCondition_Values, EndSimCondition_NumberOfSignals, EndSim_NumberOfWaitCycles, SignalValues[ThreadIndex], RegValues[ThreadIndex], Faults[ThreadIndex]); CheckResults(ClockCycle, Max_No_ClockCycles, EndSim_OutputNames, EndSim_Outputs_IndexL, EndSim_Outputs_IndexH, EndSim_Outputs_Base, EndSim_NumberOfOutputBlocks, Signals, NumberOfSignals, FaultFreeSignalValues, NumberOfFaultFreeOutputs, FaultFreeOutputs, SignalValues[ThreadIndex], SimulationResults[SimulationIndex], Print_Nondetected, Print_Detected, Print_Ineffective, IneffectiveCounter[ThreadIndex], NondetectedCounter[ThreadIndex], DetectedCounter[ThreadIndex], RunTimeOverCounter[ThreadIndex]); for (i = 0;i < NumberOfInjectedFaults;i++) Faults[ThreadIndex][FaultInjectionType][SimulationResults[SimulationIndex].TaregtClockCycles[i]][SimulationResults[SimulationIndex].TaregtCells[i]] = 0; #pragma omp atomic SimulationCounter++; if ((SimulationCounter & 0x7ff) == 0x7ff) { TotalDetected = 0; TotalNondetected = 0; TotalIneffective = 0; TotalRunTimeOver = 0; for (i = 0; i < Max_no_of_Threads; i++) { TotalDetected += DetectedCounter[i]; TotalNondetected += NondetectedCounter[i]; TotalIneffective += IneffectiveCounter[i]; TotalRunTimeOver += RunTimeOverCounter[i]; } int elapsed_secs = int(double(clock() - begin) / CLOCKS_PER_SEC); char Str1[200]; sprintf(Str1, "%04d:%02d Total: %d Ineffective: %d Detected: %d Non-detected: %d RunTimeOver: %d\n", elapsed_secs / 60, elapsed_secs % 60, SimulationCounter, TotalIneffective, TotalDetected, TotalNondetected, TotalRunTimeOver); printf(Str1); fprintf(EvaluationResultFile, Str1); } } else { free(SimulationResults[SimulationIndex].TaregtCells); free(SimulationResults[SimulationIndex].TaregtClockCycles); } } else SimulationResults[SimulationIndex].Valid = 0; } TotalDetected = 0; TotalNondetected = 0; TotalIneffective = 0; TotalRunTimeOver = 0; for (i = 0; i < Max_no_of_Threads; i++) { TotalDetected += DetectedCounter[i]; TotalNondetected += NondetectedCounter[i]; TotalIneffective += IneffectiveCounter[i]; TotalRunTimeOver += RunTimeOverCounter[i]; } int elapsed_secs = int(double(clock() - begin) / CLOCKS_PER_SEC); char Str1[200]; sprintf(Str1, "%04d:%02d Total: %d Ineffective: %d Detected: %d Non-detected: %d RunTimeOver: %d\n", elapsed_secs / 60, elapsed_secs % 60, SimulationCounter, TotalIneffective, TotalDetected, TotalNondetected, TotalRunTimeOver); printf(Str1); fprintf(EvaluationResultFile, Str1); fclose(EvaluationResultFile); return 0; } //***************************************************************************************
TestCompilerOpenMP.c
#include <omp.h> #include <stdlib.h> int main() { int *id = (int*)malloc(omp_get_max_threads() * sizeof(int)); #pragma omp parallel { id[omp_get_thread_num()] = omp_get_thread_num(); } free(id); return 0; }
trmm_x_dia_u_hi_row.c
#include "alphasparse/kernel.h" #include "alphasparse/util.h" #include "alphasparse/opt.h" #ifdef _OPENMP #include <omp.h> #endif alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_DIA *mat, const ALPHA_Number *x, const ALPHA_INT columns, const ALPHA_INT ldx, const ALPHA_Number beta, ALPHA_Number *y, const ALPHA_INT ldy) { ALPHA_INT num_threads = alpha_get_thread_num(); #ifdef _OPENMP #pragma omp parallel for num_threads(num_threads) #endif for (ALPHA_INT r = 0; r < mat->rows; r++) for(ALPHA_INT c = 0; c < columns; c++){ alpha_mul(y[index2(r,c,ldy)],y[index2(r,c,ldy)],beta); alpha_madde(y[index2(r,c,ldy)],x[index2(r,c,ldx)],alpha); } #ifdef _OPENMP #pragma omp parallel num_threads(num_threads) #endif { ALPHA_INT tid = alpha_get_thread_id(); ALPHA_INT bcl = cross_block_low(tid,num_threads,columns); ALPHA_INT bch = cross_block_high(tid,num_threads,columns); for(ALPHA_INT di = 0; di < mat->ndiag;++di){ ALPHA_INT d = mat->distance[di]; if(d > 0){ ALPHA_INT ars = alpha_max(0,-d); ALPHA_INT acs = alpha_max(0,d); ALPHA_INT an = alpha_min(mat->rows - ars,mat->cols - acs); for(ALPHA_INT i = 0; i < an; ++i){ ALPHA_INT ar = ars + i; ALPHA_INT ac = acs + i; ALPHA_Number val; alpha_mul(val,mat->values[index2(di,ar,mat->lval)],alpha); for(ALPHA_INT bc = bcl;bc < bch;++bc){ alpha_madde(y[index2(ar,bc,ldy)],val,x[index2(ac,bc,ldx)]); } } } } } return ALPHA_SPARSE_STATUS_SUCCESS; }
transform.h
/*! * Copyright 2018 XGBoost contributors */ #ifndef XGBOOST_COMMON_TRANSFORM_H_ #define XGBOOST_COMMON_TRANSFORM_H_ #include <dmlc/omp.h> #include <dmlc/common.h> #include <xgboost/data.h> #include <utility> #include <vector> #include <type_traits> // enable_if #include "xgboost/host_device_vector.h" #include "xgboost/span.h" #include "common.h" #if defined (__CUDACC__) #include "device_helpers.cuh" #endif // defined (__CUDACC__) namespace xgboost { namespace common { constexpr size_t kBlockThreads = 256; namespace detail { #if defined(__CUDACC__) template <typename Functor, typename... SpanType> __global__ void LaunchCUDAKernel(Functor _func, Range _range, SpanType... _spans) { for (auto i : dh::GridStrideRange(*_range.begin(), *_range.end())) { _func(i, _spans...); } } #endif // defined(__CUDACC__) } // namespace detail /*! \brief Do Transformation on HostDeviceVectors. * * \tparam CompiledWithCuda A bool parameter used to distinguish compilation * trajectories, users do not need to use it. * * Note: Using Transform is a VERY tricky thing to do. Transform uses template * argument to duplicate itself into two different types, one for CPU, * another for CUDA. The trick is not without its flaw: * * If you use it in a function that can be compiled by both nvcc and host * compiler, the behaviour is un-defined! Because your function is NOT * duplicated by `CompiledWithCuda`. At link time, cuda compiler resolution * will merge functions with same signature. */ template <bool CompiledWithCuda = WITH_CUDA()> class Transform { private: template <typename Functor> struct Evaluator { public: Evaluator(Functor func, Range range, int device, bool shard) : func_(func), range_{std::move(range)}, shard_{shard}, device_{device} {} /*! * \brief Evaluate the functor with input pointers to HostDeviceVector. * * \tparam HDV... HostDeviceVectors type. * \param vectors Pointers to HostDeviceVector. */ template <typename... HDV> void Eval(HDV... vectors) const { bool on_device = device_ >= 0; if (on_device) { LaunchCUDA(func_, vectors...); } else { LaunchCPU(func_, vectors...); } } private: // CUDA UnpackHDV template <typename T> Span<T> UnpackHDVOnDevice(HostDeviceVector<T>* _vec) const { auto span = _vec->DeviceSpan(); return span; } template <typename T> Span<T const> UnpackHDVOnDevice(const HostDeviceVector<T>* _vec) const { auto span = _vec->ConstDeviceSpan(); return span; } // CPU UnpackHDV template <typename T> Span<T> UnpackHDV(HostDeviceVector<T>* _vec) const { return Span<T> {_vec->HostPointer(), static_cast<typename Span<T>::index_type>(_vec->Size())}; } template <typename T> Span<T const> UnpackHDV(const HostDeviceVector<T>* _vec) const { return Span<T const> {_vec->ConstHostPointer(), static_cast<typename Span<T>::index_type>(_vec->Size())}; } // Recursive unpack for Shard. template <typename T> void UnpackShard(int device, const HostDeviceVector<T> *vector) const { vector->SetDevice(device); } template <typename Head, typename... Rest> void UnpackShard(int device, const HostDeviceVector<Head> *_vector, const HostDeviceVector<Rest> *... _vectors) const { _vector->SetDevice(device); UnpackShard(device, _vectors...); } #if defined(__CUDACC__) template <typename std::enable_if<CompiledWithCuda>::type* = nullptr, typename... HDV> void LaunchCUDA(Functor _func, HDV*... _vectors) const { if (shard_) UnpackShard(device_, _vectors...); size_t range_size = *range_.end() - *range_.begin(); // Extract index to deal with possible old OpenMP. // This deals with situation like multi-class setting where // granularity is used in data vector. size_t shard_size = range_size; Range shard_range {0, static_cast<Range::DifferenceType>(shard_size)}; dh::safe_cuda(cudaSetDevice(device_)); const int kGrids = static_cast<int>(DivRoundUp(*(range_.end()), kBlockThreads)); if (kGrids == 0) { return; } detail::LaunchCUDAKernel<<<kGrids, kBlockThreads>>>( // NOLINT _func, shard_range, UnpackHDVOnDevice(_vectors)...); } #else /*! \brief Dummy funtion defined when compiling for CPU. */ template <typename std::enable_if<!CompiledWithCuda>::type* = nullptr, typename... HDV> void LaunchCUDA(Functor _func, HDV*... _vectors) const { LOG(FATAL) << "Not part of device code. WITH_CUDA: " << WITH_CUDA(); } #endif // defined(__CUDACC__) template <typename... HDV> void LaunchCPU(Functor func, HDV*... vectors) const { omp_ulong end = static_cast<omp_ulong>(*(range_.end())); dmlc::OMPException omp_exc; #pragma omp parallel for schedule(static) for (omp_ulong idx = 0; idx < end; ++idx) { omp_exc.Run(func, idx, UnpackHDV(vectors)...); } omp_exc.Rethrow(); } private: /*! \brief Callable object. */ Functor func_; /*! \brief Range object specifying parallel threads index range. */ Range range_; /*! \brief Whether sharding for vectors is required. */ bool shard_; int device_; }; public: /*! * \brief Initialize a Transform object. * * \tparam Functor A callable object type. * \return A Evaluator having one method Eval. * * \param func A callable object, accepting a size_t thread index, * followed by a set of Span classes. * \param range Range object specifying parallel threads index range. * \param devices GPUSet specifying GPUs to use, when compiling for CPU, * this should be GPUSet::Empty(). * \param shard Whether Shard for HostDeviceVector is needed. */ template <typename Functor> static Evaluator<Functor> Init(Functor func, Range const range, int device, bool const shard = true) { return Evaluator<Functor> {func, std::move(range), device, shard}; } }; } // namespace common } // namespace xgboost #endif // XGBOOST_COMMON_TRANSFORM_H_
3d25pt_var.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-1, 3D 25 point stencil with axis-symmetric ariable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*13); for(m=0; m<13;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 24; tile_size[1] = 24; tile_size[2] = 16; tile_size[3] = 1024; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<13; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) { for (t1=-1;t1<=floord(Nt-1,3);t1++) { lbp=max(ceild(t1,2),ceild(6*t1-Nt+2,6)); ubp=min(floord(4*Nt+Nz-9,24),floord(12*t1+Nz+6,24)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(max(0,ceild(3*t1-3*t2,2)),ceild(3*t1-2,4)),ceild(24*t2-Nz-3,16));t3<=min(min(min(floord(4*Nt+Ny-9,16),floord(12*t1+Ny+15,16)),floord(24*t2+Ny+11,16)),floord(24*t1-24*t2+Nz+Ny+13,16));t3++) { for (t4=max(max(max(max(0,ceild(3*t1-3*t2-126,128)),ceild(3*t1-254,256)),ceild(24*t2-Nz-1011,1024)),ceild(16*t3-Ny-1011,1024));t4<=min(min(min(min(floord(4*Nt+Nx-9,1024),floord(12*t1+Nx+15,1024)),floord(24*t2+Nx+11,1024)),floord(16*t3+Nx+3,1024)),floord(24*t1-24*t2+Nz+Nx+13,1024));t4++) { for (t5=max(max(max(max(max(0,ceild(24*t2-Nz+5,4)),ceild(16*t3-Ny+5,4)),ceild(1024*t4-Nx+5,4)),3*t1),6*t1-6*t2+1);t5<=min(min(min(min(min(floord(24*t1-24*t2+Nz+18,4),Nt-1),3*t1+5),6*t2+4),4*t3+2),256*t4+254);t5++) { for (t6=max(max(24*t2,4*t5+4),-24*t1+24*t2+8*t5-23);t6<=min(min(24*t2+23,-24*t1+24*t2+8*t5),4*t5+Nz-5);t6++) { for (t7=max(16*t3,4*t5+4);t7<=min(16*t3+15,4*t5+Ny-5);t7++) { lbv=max(1024*t4,4*t5+4); ubv=min(1024*t4+1023,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)] = (((((((((((((coef[0][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef[1][ (-4*t5+t6)][ (-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) + 1][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[2][ (-4*t5+t6)][ (-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)]))) + (coef[3][ (-4*t5+t6)][ (-4*t5+t7)][ (-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]))) + (coef[4][ (-4*t5+t6)][ (-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) + 2][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[5][ (-4*t5+t6)][ (-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)]))) + (coef[6][ (-4*t5+t6)][ (-4*t5+t7)][ (-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]))) + (coef[7][ (-4*t5+t6)][ (-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) + 3][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[8][ (-4*t5+t6)][ (-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)]))) + (coef[9][ (-4*t5+t6)][ (-4*t5+t7)][ (-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]))) + (coef[10][ (-4*t5+t6)][ (-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][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[11][ (-4*t5+t6)][ (-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)]))) + (coef[12][ (-4*t5+t6)][ (-4*t5+t7)][ (-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, "variable axis-symmetric") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<13;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
GB_unop__identity_int64_fc64.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__identity_int64_fc64 // op(A') function: GB_unop_tran__identity_int64_fc64 // C type: int64_t // A type: GxB_FC64_t // cast: int64_t cij = GB_cast_to_int64_t (creal (aij)) // unaryop: cij = aij #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ int64_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 = x ; // casting #define GB_CAST(z, aij) \ int64_t z = GB_cast_to_int64_t (creal (aij)) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int64_t z = GB_cast_to_int64_t (creal (aij)) ; \ Cx [pC] = z ; \ } // 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_IDENTITY || GxB_NO_INT64 || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__identity_int64_fc64 ( int64_t *Cx, // Cx and Ax may be aliased const GxB_FC64_t *Ax, const int8_t *GB_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) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (GxB_FC64_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; int64_t z = GB_cast_to_int64_t (creal (aij)) ; Cx [p] = z ; } #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 ; GxB_FC64_t aij = Ax [p] ; int64_t z = GB_cast_to_int64_t (creal (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_fc64 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_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
3d7pt.c
/* * 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] = 16; tile_size[1] = 16; tile_size[2] = 32; 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 #pragma scop for (t = 0; t < Nt-1; t++) { for (i = 1; i < Nz-1; i++) { for (j = 1; j < Ny-1; j++) { for (k = 1; k < Nx-1; k++) { A[(t+1)%2][i][j][k] = alpha * (A[t%2][i][j][k]) + beta * (A[t%2][i - 1][j][k] + A[t%2][i][j - 1][k] + A[t%2][i][j][k - 1] + A[t%2][i + 1][j][k] + A[t%2][i][j + 1][k] + A[t%2][i][j][k + 1]); } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "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; }
ssempush2.c
/* SSE2 C Library for Skeleton 2D Electrostatic OpenMP/Vector PIC Code */ /* written by Viktor K. Decyk, UCLA and Ricardo Fonseca, ISCTE */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <complex.h> #include <math.h> #include <xmmintrin.h> #include "ssempush2.h" void cfft2r2x(float complex f[], int isign, int mixup[], float complex sct[], int indx, int indy, int nyi, int nyp, int nxhd, int nyd, int nxhyd, int nxyhd); void cfft2r2y(float complex f[], int isign, int mixup[], float complex sct[], int indx, int indy, int nxi, int nxp, int nxhd, int nyd, int nxhyd, int nxyhd); /*--------------------------------------------------------------------*/ void csse2gppush2lt(float ppart[], float fxy[], int kpic[], float qbm, float dt, float *ek, int idimp, int nppmx, int nx, int ny, int mx, int my, int nxv, int nyv, int mx1, int mxy1, int ipbc) { /* for 2d code, this subroutine updates particle co-ordinates and velocities using leap-frog scheme in time and first-order linear interpolation in space, with various boundary conditions. OpenMP/vector version using guard cells data read in tiles particles stored segmented array 44 flops/particle, 12 loads, 4 stores input: all, output: ppart, ek equations used are: vx(t+dt/2) = vx(t-dt/2) + (q/m)*fx(x(t),y(t))*dt, vy(t+dt/2) = vy(t-dt/2) + (q/m)*fy(x(t),y(t))*dt, where q/m is charge/mass, and x(t+dt) = x(t) + vx(t+dt/2)*dt, y(t+dt) = y(t) + vy(t+dt/2)*dt fx(x(t),y(t)) and fy(x(t),y(t)) are approximated by interpolation from the nearest grid points: fx(x,y) = (1-dy)*((1-dx)*fx(n,m)+dx*fx(n+1,m)) + dy*((1-dx)*fx(n,m+1) + dx*fx(n+1,m+1)) fy(x,y) = (1-dy)*((1-dx)*fy(n,m)+dx*fy(n+1,m)) + dy*((1-dx)*fy(n,m+1) + dx*fy(n+1,m+1)) where n,m = leftmost grid points and dx = x-n, dy = y-m ppart[m][0][n] = position x of particle n in tile m ppart[m][1][n] = position y of particle n in tile m ppart[m][2][n] = velocity vx of particle n in tile m ppart[m][3][n] = velocity vy of particle n in tile m fxy[k][j][0] = x component of force/charge at grid (j,k) fxy[k][j][1] = y component of force/charge at grid (j,k) that is, convolution of electric field over particle shape kpic = number of particles per tile qbm = particle charge/mass dt = time interval between successive calculations kinetic energy/mass at time t is also calculated, using ek = .125*sum((vx(t+dt/2)+vx(t-dt/2))**2+(vy(t+dt/2)+vy(t-dt/2))**2) idimp = size of phase space = 4 nppmx = maximum number of particles in tile nx/ny = system length in x/y direction mx/my = number of grids in sorting cell in x/y nxv = second dimension of field arrays, must be >= nx+1 nyv = third dimension of field arrays, must be >= ny+1 mx1 = (system length in x direction - 1)/mx + 1 mxy1 = mx1*my1, where my1 = (system length in y direction - 1)/my + 1 ipbc = particle boundary condition = (0,1,2,3) = (none,2d periodic,2d reflecting,mixed reflecting/periodic) requires SSE2, ppart needs to be 16 byte aligned nppmx needs to be a multiple of 4 local data */ #define MXV 33 #define MYV 33 int noff, moff, npoff, npp, nps; int i, j, k, nn, mm, mxv; float qtm, edgelx, edgely, edgerx, edgery, dxp, dyp, amx, amy; float x, y, dx, dy, vx, vy; double sum1, sum2; __m128i v_noff, v_moff, v_mxv; __m128i v_nn, v_mm, v_it; __m128 v_qtm, v_dt, v_one; __m128 v_dxp, v_dyp, v_amx, v_amy, v_at; __m128 v_x, v_y, v_dx, v_dy, v_vx, v_vy; __m128 v_edgelx, v_edgely, v_edgerx, v_edgery; __m128 a, b, c, d; __m128d v_sum1, v_d; __attribute__((aligned(16))) unsigned int ll[4]; __attribute__((aligned(16))) double dd[2]; __attribute__((aligned(16))) float sfxy[2*MXV*MYV]; /* __attribute__((aligned(16))) float sfxy[2*(mx+1)*(my+1)]; */ mxv = mx + 1; qtm = qbm*dt; sum2 = 0.0; /* set boundary values */ edgelx = 0.0f; edgely = 0.0f; edgerx = (float) nx; edgery = (float) ny; if (ipbc==2) { edgelx = 1.0f; edgely = 1.0f; edgerx = (float) (nx-1); edgery = (float) (ny-1); } else if (ipbc==3) { edgelx = 1.0f; edgerx = (float) (nx-1); } v_mxv = _mm_set1_epi32(mxv); v_qtm = _mm_set1_ps(qtm); v_one = _mm_set1_ps(1.0f); v_dt = _mm_set1_ps(dt); v_edgelx = _mm_set1_ps(edgelx); v_edgely = _mm_set1_ps(edgely); v_edgerx = _mm_set1_ps(edgerx); v_edgery = _mm_set1_ps(edgery); /* error if local array is too small */ /* if ((mx >= MXV) || (my >= MYV)) */ /* return; */ /* loop over tiles */ #pragma omp parallel for \ private(i,j,k,noff,moff,npp,nps,npoff,nn,mm,x,y,dxp,dyp,amx,amy,dx,dy, \ vx,vy,sum1,v_noff,v_moff,v_nn,v_mm,v_it,v_x,v_y,v_dxp,v_dyp,v_amx,v_amy, \ v_dx,v_dy,v_vx,v_vy,v_at,v_d,v_sum1,a,b,c,d,ll,dd,sfxy) \ reduction(+:sum2) for (k = 0; k < mxy1; k++) { noff = k/mx1; moff = my*noff; noff = mx*(k - mx1*noff); v_noff = _mm_set1_epi32(noff); v_moff = _mm_set1_epi32(moff); npp = kpic[k]; npoff = idimp*nppmx*k; /* load local fields from global array */ nn = (mx < nx-noff ? mx : nx-noff) + 1; mm = (my < ny-moff ? my : ny-moff) + 1; nps = 4*((2*nn)/4); for (j = 0; j < mm; j++) { /* vector loop over elements in blocks of 4 */ /* for (i = 0; i < nn; i++) { */ /* sfxy[2*(i+mxv*j)] = fxy[2*(i+noff+nxv*(j+moff))]; */ /* sfxy[1+2*(i+mxv*j)] = fxy[1+2*(i+noff+nxv*(j+moff))]; */ /* } */ for (i = 0; i < nps; i+=4) { v_at = _mm_loadu_ps(&fxy[i+2*(noff+nxv*(j+moff))]); _mm_storeu_ps(&sfxy[i+2*(mxv*j)],v_at); } /* loop over remaining elements */ for (i = nps; i < 2*nn; i++) { sfxy[i+2*(mxv*j)] = fxy[i+2*(noff+nxv*(j+moff))]; } } nps = 4*(npp/4); sum1 = 0.0; v_sum1 = _mm_set1_pd(0.0); /* loop over particles in tile in groups of 4 */ for (j = 0; j < nps; j+=4) { /* find interpolation weights */ /* x = ppart[j+npoff]; */ /* y = ppart[j+nppmx+npoff]; */ v_x = _mm_load_ps(&ppart[j+npoff]); v_y = _mm_load_ps(&ppart[j+nppmx+npoff]); /* nn = x; */ /* mm = y; */ v_nn = _mm_cvttps_epi32(v_x); v_mm = _mm_cvttps_epi32(v_y); /* dxp = x - (float) nn; */ v_dxp = _mm_sub_ps(v_x,_mm_cvtepi32_ps(v_nn)); /* dyp = y - (float) mm; */ v_dyp = _mm_sub_ps(v_y,_mm_cvtepi32_ps(v_mm)); /* nn = 2*(nn - noff + mxv*(mm - moff)); */ v_nn = _mm_sub_epi32(v_nn,v_noff); v_mm = _mm_sub_epi32(v_mm,v_moff); v_it = _mm_mul_epu32(v_mxv,_mm_srli_si128(v_mm,4)); v_mm = _mm_mul_epu32(v_mm,v_mxv); v_mm = _mm_add_epi32(v_mm,_mm_slli_si128(v_it,4)); v_nn = _mm_slli_epi32(_mm_add_epi32(v_nn,v_mm),1); /* amx = 1.0f - dxp; */ /* amy = 1.0f - dyp; */ v_amx = _mm_sub_ps(v_one,v_dxp); v_amy = _mm_sub_ps(v_one,v_dyp); /* find acceleration */ /* load fields, for lower left/right */ _mm_store_si128((__m128i *)ll,v_nn); a = _mm_loadu_ps(&sfxy[ll[0]]); b = _mm_loadu_ps(&sfxy[ll[1]]); c = _mm_loadu_ps(&sfxy[ll[2]]); d = _mm_loadu_ps(&sfxy[ll[3]]); /* transpose so a,b,c,d contain first 4 fields for each of 4 particles */ _MM_TRANSPOSE4_PS(a,b,c,d); /* dx = amx*sfxy[nn]; */ /* dy = amx*sfxy[nn+1]; */ v_dx = _mm_mul_ps(v_amx,a); v_dy = _mm_mul_ps(v_amx,b); /* dx = amy*(dxp*sfxy[nn+2] + dx); */ /* dy = amy*(dxp*sfxy[nn+3] + dy); */ v_dx = _mm_mul_ps(v_amy,_mm_add_ps(_mm_mul_ps(v_dxp,c),v_dx)); v_dy = _mm_mul_ps(v_amy,_mm_add_ps(_mm_mul_ps(v_dxp,d),v_dy)); /* nn += 2*mxv; */ /* load fields, for upper left/right */ a = _mm_loadu_ps(&sfxy[ll[0]+2*mxv]); b = _mm_loadu_ps(&sfxy[ll[1]+2*mxv]); c = _mm_loadu_ps(&sfxy[ll[2]+2*mxv]); d = _mm_loadu_ps(&sfxy[ll[3]+2*mxv]); /* transpose so a,b,c,d contain next 4 fields for each of 4 particles */ _MM_TRANSPOSE4_PS(a,b,c,d); /* vx = amx*sfxy[nn]; */ /* vy = amx*sfxy[nn+1]; */ a = _mm_mul_ps(v_amx,a); b = _mm_mul_ps(v_amx,b); /* dx += dyp*(dxp*sfxy[nn+2] + vx); */ /* dy += dyp*(dxp*sfxy[nn+3] + vy); */ a = _mm_mul_ps(v_dyp,_mm_add_ps(_mm_mul_ps(v_dxp,c),a)); b = _mm_mul_ps(v_dyp,_mm_add_ps(_mm_mul_ps(v_dxp,d),b)); v_dx = _mm_add_ps(v_dx,a); v_dy = _mm_add_ps(v_dy,b); /* new velocity */ /* dxp = ppart[j+2*nppmx+npoff]; */ /* dyp = ppart[j+3*nppmx+npoff]; */ v_dxp = _mm_load_ps(&ppart[j+2*nppmx+npoff]); v_dyp = _mm_load_ps(&ppart[j+3*nppmx+npoff]); /* vx = dxp + qtm*dx; */ /* vy = dyp + qtm*dy; */ v_vx = _mm_add_ps(v_dxp,_mm_mul_ps(v_qtm,v_dx)); v_vy = _mm_add_ps(v_dyp,_mm_mul_ps(v_qtm,v_dy)); /* average kinetic energy */ /* dxp += vx; */ /* dyp += vy; */ v_dxp = _mm_add_ps(v_dxp,v_vx); v_dyp = _mm_add_ps(v_dyp,v_vy); /* sum1 += dxp*dxp + dyp*dyp; */ v_at = _mm_mul_ps(v_dxp,v_dxp); v_at = _mm_add_ps(v_at,_mm_mul_ps(v_dyp,v_dyp)); /* convert to double precision before accumulating */ v_d = _mm_cvtps_pd(v_at); v_sum1 = _mm_add_pd(v_sum1,v_d); v_it = _mm_srli_si128((__m128i)v_at,8); v_d = _mm_cvtps_pd((__m128)v_it); v_sum1 = _mm_add_pd(v_sum1,v_d); /* new position */ /* dx = x + vx*dt; */ /* dy = y + vy*dt; */ v_dx = _mm_add_ps(v_x,_mm_mul_ps(v_vx,v_dt)); v_dy = _mm_add_ps(v_y,_mm_mul_ps(v_vy,v_dt)); /* reflecting boundary conditions */ if (ipbc==2) { /* if ((dx < edgelx) || (dx >= edgerx)) { */ /* dx = x; */ /* vx = -vx; */ /* } */ v_at = _mm_cmplt_ps(v_dx,v_edgelx); v_at = _mm_or_ps(v_at,_mm_cmpge_ps(v_dx,v_edgerx)); v_x = _mm_and_ps(v_at,v_x); v_dx = _mm_add_ps(_mm_andnot_ps(v_at,v_dx),v_x); v_dxp = _mm_and_ps(v_at,v_vx); v_vx = _mm_sub_ps(_mm_andnot_ps(v_at,v_vx),v_dxp); /* if ((dy < edgely) || (dy >= edgery)) { */ /* dy = y; */ /* vy = -vy; */ /* } */ v_at = _mm_cmplt_ps(v_dy,v_edgely); v_at = _mm_or_ps(v_at,_mm_cmpge_ps(v_dy,v_edgery)); v_y = _mm_and_ps(v_at,v_y); v_dy = _mm_add_ps(_mm_andnot_ps(v_at,v_dy),v_y); v_dyp = _mm_and_ps(v_at,v_vy); v_vy = _mm_sub_ps(_mm_andnot_ps(v_at,v_vy),v_dyp); } /* mixed reflecting/periodic boundary conditions */ else if (ipbc==3) { /* if ((dx < edgelx) || (dx >= edgerx)) { */ /* dx = x; */ /* vx = -vx; */ /* } */ v_at = _mm_cmplt_ps(v_dx,v_edgelx); v_at = _mm_or_ps(v_at,_mm_cmpge_ps(v_dx,v_edgerx)); v_x = _mm_and_ps(v_at,v_x); v_dx = _mm_add_ps(_mm_andnot_ps(v_at,v_dx),v_x); v_dxp = _mm_and_ps(v_at,v_vx); v_vx = _mm_sub_ps(_mm_andnot_ps(v_at,v_vx),v_dxp); } /* set new position */ /* ppart[j+npoff] = dx; */ /* ppart[j+nppmx+npoff] = dy; */ _mm_store_ps(&ppart[j+npoff],v_dx); _mm_store_ps(&ppart[j+nppmx+npoff],v_dy); /* set new velocity */ /* ppart[j+2*nppmx+npoff] = vx; */ /* ppart[j+3*nppmx+npoff] = vy; */ _mm_store_ps(&ppart[j+2*nppmx+npoff],v_vx); _mm_store_ps(&ppart[j+3*nppmx+npoff],v_vy); } /* loop over remaining particles in tile */ for (j = nps; j < npp; j++) { /* find interpolation weights */ x = ppart[j+npoff]; y = ppart[j+nppmx+npoff]; nn = x; mm = y; dxp = x - (float) nn; dyp = y - (float) mm; nn = 2*(nn - noff + mxv*(mm - moff)); amx = 1.0f - dxp; amy = 1.0f - dyp; /* find acceleration */ dx = amx*sfxy[nn]; dy = amx*sfxy[nn+1]; dx = amy*(dxp*sfxy[nn+2] + dx); dy = amy*(dxp*sfxy[nn+3] + dy); nn += 2*mxv; vx = amx*sfxy[nn]; vy = amx*sfxy[nn+1]; dx += dyp*(dxp*sfxy[nn+2] + vx); dy += dyp*(dxp*sfxy[nn+3] + vy); /* new velocity */ dxp = ppart[j+2*nppmx+npoff]; dyp = ppart[j+3*nppmx+npoff]; vx = dxp + qtm*dx; vy = dyp + qtm*dy; /* average kinetic energy */ dxp += vx; dyp += vy; sum1 += dxp*dxp + dyp*dyp; /* new position */ dx = x + vx*dt; dy = y + vy*dt; /* reflecting boundary conditions */ if (ipbc==2) { if ((dx < edgelx) || (dx >= edgerx)) { dx = x; vx = -vx; } if ((dy < edgely) || (dy >= edgery)) { dy = y; vy = -vy; } } /* mixed reflecting/periodic boundary conditions */ else if (ipbc==3) { if ((dx < edgelx) || (dx >= edgerx)) { dx = x; vx = -vx; } } /* set new position */ ppart[j+npoff] = dx; ppart[j+nppmx+npoff] = dy; /* set new velocity */ ppart[j+2*nppmx+npoff] = vx; ppart[j+3*nppmx+npoff] = vy; } /* sum2 += sum1; */ _mm_store_pd(&dd[0],v_sum1); for (j = 1; j < 2; j++) { dd[0] += dd[j]; } sum2 += (sum1 + dd[0]); } /* normalize kinetic energy */ *ek += 0.125f*sum2; return; #undef MXV #undef MYV } /*--------------------------------------------------------------------*/ void csse2gppushf2lt(float ppart[], float fxy[], int kpic[], int ncl[], int ihole[], float qbm, float dt, float *ek, int idimp, int nppmx, int nx, int ny, int mx, int my, int nxv, int nyv, int mx1, int mxy1, int ntmax, int *irc) { /* for 2d code, this subroutine updates particle co-ordinates and velocities using leap-frog scheme in time and first-order linear interpolation in space, with periodic boundary conditions. also determines list of particles which are leaving this tile OpenMP/vector version using guard cells data read in tiles particles stored segmented array 44 flops/particle, 12 loads, 4 stores input: all except ncl, ihole, irc, output: ppart, ncl, ihole, ek, irc equations used are: vx(t+dt/2) = vx(t-dt/2) + (q/m)*fx(x(t),y(t))*dt, vy(t+dt/2) = vy(t-dt/2) + (q/m)*fy(x(t),y(t))*dt, where q/m is charge/mass, and x(t+dt) = x(t) + vx(t+dt/2)*dt, y(t+dt) = y(t) + vy(t+dt/2)*dt fx(x(t),y(t)) and fy(x(t),y(t)) are approximated by interpolation from the nearest grid points: fx(x,y) = (1-dy)*((1-dx)*fx(n,m)+dx*fx(n+1,m)) + dy*((1-dx)*fx(n,m+1) + dx*fx(n+1,m+1)) fy(x,y) = (1-dy)*((1-dx)*fy(n,m)+dx*fy(n+1,m)) + dy*((1-dx)*fy(n,m+1) + dx*fy(n+1,m+1)) where n,m = leftmost grid points and dx = x-n, dy = y-m ppart[m][0][n] = position x of particle n in tile m ppart[m][1][n] = position y of particle n in tile m ppart[m][2][n] = velocity vx of particle n in tile m ppart[m][3][n] = velocity vy of particle n in tile m fxy[k][j][0] = x component of force/charge at grid (j,k) fxy[k][j][1] = y component of force/charge at grid (j,k) that is, convolution of electric field over particle shape kpic[k] = number of particles in tile k ncl[k][i] = number of particles going to destination i, tile k ihole[k][:][0] = location of hole in array left by departing particle ihole[k][:][1] = destination of particle leaving hole ihole[k][0][0] = ih, number of holes left (error, if negative) qbm = particle charge/mass dt = time interval between successive calculations kinetic energy/mass at time t is also calculated, using ek = .125*sum((vx(t+dt/2)+vx(t-dt/2))**2+(vy(t+dt/2)+vy(t-dt/2))**2) idimp = size of phase space = 4 nppmx = maximum number of particles in tile nx/ny = system length in x/y direction mx/my = number of grids in sorting cell in x/y nxv = second dimension of field arrays, must be >= nx+1 nyv = third dimension of field arrays, must be >= ny+1 mx1 = (system length in x direction - 1)/mx + 1 mxy1 = mx1*my1, where my1 = (system length in y direction - 1)/my + 1 ntmax = size of hole array for particles leaving tiles irc = maximum overflow, returned only if error occurs, when irc > 0 requires SSE2, ppart needs to be 16 byte aligned nppmx needs to be a multiple of 4 optimized version local data */ #define MXV 33 #define MYV 33 int noff, moff, npoff, npp, nps; int i, j, k, ih, nh, nn, mm, kk, mxv; float qtm, dxp, dyp, amx, amy; float x, y, dx, dy, vx, vy; float anx, any, edgelx, edgely, edgerx, edgery; double sum1, sum2; __m128i v_noff, v_moff, v_mxv; __m128i v_nn, v_mm, v_it; __m128 v_qtm, v_dt, v_one; __m128 v_dxp, v_dyp, v_amx, v_amy, v_st, v_at; __m128 v_x, v_y, v_dx, v_dy, v_vx, v_vy; __m128 v_anx, v_any, v_edgelx, v_edgely, v_edgerx, v_edgery; __m128 v_zero, v_two, v_three, v_six; __m128 a, b, c, d; __m128d v_sum1, v_d; __attribute__((aligned(16))) unsigned int ll[4], lm[8]; __attribute__((aligned(16))) unsigned long jj[1]; __attribute__((aligned(16))) double dd[2]; __attribute__((aligned(16))) float sfxy[2*MXV*MYV]; /* __attribute__((aligned(16))) float sfxy[2*(mx+1)*(my+1)]; */ mxv = mx + 1; qtm = qbm*dt; anx = (float) nx; any = (float) ny; sum2 = 0.0; v_mxv = _mm_set1_epi32(mxv); v_qtm = _mm_set1_ps(qtm); v_one = _mm_set1_ps(1.0f); v_dt = _mm_set1_ps(dt); v_anx = _mm_set1_ps(anx); v_any = _mm_set1_ps(any); v_zero = _mm_setzero_ps(); v_two = _mm_set1_ps(2.0f); v_three = _mm_set1_ps(3.0f); v_six = _mm_set1_ps(6.0f); /* error if local array is too small */ /* if ((mx >= MXV) || (my >= MYV)) */ /* return; */ /* loop over tiles */ #pragma omp parallel for \ private(i,j,k,noff,moff,npp,nps,npoff,nn,mm,kk,ih,nh,x,y,dxp,dyp,amx, \ amy,dx,dy,vx,vy,edgelx,edgely,edgerx,edgery,sum1,v_noff,v_moff,v_nn, \ v_mm,v_it,v_x,v_y,v_dxp,v_dyp,v_amx,v_amy,v_dx,v_dy,v_vx,v_vy,v_st, \ v_at,v_edgelx,v_edgely,v_edgerx,v_edgery,v_d,v_sum1,a,b,c,d,jj,ll,lm, \ dd,sfxy) \ reduction(+:sum2) for (k = 0; k < mxy1; k++) { noff = k/mx1; moff = my*noff; noff = mx*(k - mx1*noff); v_noff = _mm_set1_epi32(noff); v_moff = _mm_set1_epi32(moff); npp = kpic[k]; npoff = idimp*nppmx*k; nn = nx - noff; nn = mx < nn ? mx : nn; mm = ny - moff; mm = my < mm ? my : mm; edgelx = noff; edgerx = noff + nn; edgely = moff; edgery = moff + mm; v_edgelx = _mm_set1_ps(edgelx); v_edgely = _mm_set1_ps(edgely); v_edgerx = _mm_set1_ps(edgerx); v_edgery = _mm_set1_ps(edgery); ih = 0; nh = 0; nn += 1; mm += 1; /* load local fields from global array */ nn = (mx < nx-noff ? mx : nx-noff) + 1; mm = (my < ny-moff ? my : ny-moff) + 1; nps = 4*((2*nn)/4); for (j = 0; j < mm; j++) { /* vector loop over elements in blocks of 4 */ /* for (i = 0; i < nn; i++) { */ /* sfxy[2*(i+mxv*j)] = fxy[2*(i+noff+nxv*(j+moff))]; */ /* sfxy[1+2*(i+mxv*j)] = fxy[1+2*(i+noff+nxv*(j+moff))]; */ /* } */ for (i = 0; i < nps; i+=4) { v_at = _mm_loadu_ps(&fxy[i+2*(noff+nxv*(j+moff))]); _mm_storeu_ps(&sfxy[i+2*(mxv*j)],v_at); } /* loop over remaining elements */ for (i = nps; i < 2*nn; i++) { sfxy[i+2*(mxv*j)] = fxy[i+2*(noff+nxv*(j+moff))]; } } /* clear counters */ /* for (j = 0; j < 8; j++) { */ /* ncl[j+8*k] = 0; */ /* } */ memset((void*)&ncl[8*k],0,8*sizeof(int)); nps = 4*(npp/4); sum1 = 0.0; v_sum1 = _mm_set1_pd(0.0); /* loop over particles in tile in groups of 4 */ for (j = 0; j < nps; j+=4) { /* find interpolation weights */ /* x = ppart[j+npoff]; */ /* y = ppart[j+nppmx+npoff]; */ v_x = _mm_load_ps(&ppart[j+npoff]); v_y = _mm_load_ps(&ppart[j+nppmx+npoff]); /* nn = x; */ /* mm = y; */ v_nn = _mm_cvttps_epi32(v_x); v_mm = _mm_cvttps_epi32(v_y); /* dxp = x - (float) nn; */ v_dxp = _mm_sub_ps(v_x,_mm_cvtepi32_ps(v_nn)); /* dyp = y - (float) mm; */ v_dyp = _mm_sub_ps(v_y,_mm_cvtepi32_ps(v_mm)); /* nn = 2*(nn - noff + mxv*(mm - moff)); */ v_nn = _mm_sub_epi32(v_nn,v_noff); v_mm = _mm_sub_epi32(v_mm,v_moff); v_it = _mm_mul_epu32(v_mxv,_mm_srli_si128(v_mm,4)); v_mm = _mm_mul_epu32(v_mm,v_mxv); v_mm = _mm_add_epi32(v_mm,_mm_slli_si128(v_it,4)); v_nn = _mm_slli_epi32(_mm_add_epi32(v_nn,v_mm),1); /* amx = 1.0f - dxp; */ /* amy = 1.0f - dyp; */ v_amx = _mm_sub_ps(v_one,v_dxp); v_amy = _mm_sub_ps(v_one,v_dyp); /* find acceleration */ /* load fields, for lower left/right */ _mm_store_si128((__m128i *)ll,v_nn); a = _mm_loadu_ps(&sfxy[ll[0]]); b = _mm_loadu_ps(&sfxy[ll[1]]); c = _mm_loadu_ps(&sfxy[ll[2]]); d = _mm_loadu_ps(&sfxy[ll[3]]); /* transpose so a,b,c,d contain first 4 fields for each of 4 particles */ _MM_TRANSPOSE4_PS(a,b,c,d); /* dx = amx*sfxy[nn]; */ /* dy = amx*sfxy[nn+1]; */ v_dx = _mm_mul_ps(v_amx,a); v_dy = _mm_mul_ps(v_amx,b); /* dx = amy*(dxp*sfxy[nn+2] + dx); */ /* dy = amy*(dxp*sfxy[nn+3] + dy); */ v_dx = _mm_mul_ps(v_amy,_mm_add_ps(_mm_mul_ps(v_dxp,c),v_dx)); v_dy = _mm_mul_ps(v_amy,_mm_add_ps(_mm_mul_ps(v_dxp,d),v_dy)); /* nn += 2*mxv; */ /* load fields, for upper left/right */ a = _mm_loadu_ps(&sfxy[ll[0]+2*mxv]); b = _mm_loadu_ps(&sfxy[ll[1]+2*mxv]); c = _mm_loadu_ps(&sfxy[ll[2]+2*mxv]); d = _mm_loadu_ps(&sfxy[ll[3]+2*mxv]); /* transpose so a,b,c,d contain next 4 fields for each of 4 particles */ _MM_TRANSPOSE4_PS(a,b,c,d); /* vx = amx*sfxy[nn]; */ /* vy = amx*sfxy[nn+1]; */ a = _mm_mul_ps(v_amx,a); b = _mm_mul_ps(v_amx,b); /* dx += dyp*(dxp*sfxy[nn+2] + vx); */ /* dy += dyp*(dxp*sfxy[nn+3] + vy); */ a = _mm_mul_ps(v_dyp,_mm_add_ps(_mm_mul_ps(v_dxp,c),a)); b = _mm_mul_ps(v_dyp,_mm_add_ps(_mm_mul_ps(v_dxp,d),b)); v_dx = _mm_add_ps(v_dx,a); v_dy = _mm_add_ps(v_dy,b); /* new velocity */ /* dxp = ppart[j+2*nppmx+npoff]; */ /* dyp = ppart[j+3*nppmx+npoff]; */ v_dxp = _mm_load_ps(&ppart[j+2*nppmx+npoff]); v_dyp = _mm_load_ps(&ppart[j+3*nppmx+npoff]); /* vx = dxp + qtm*dx; */ /* vy = dyp + qtm*dy; */ v_vx = _mm_add_ps(v_dxp,_mm_mul_ps(v_qtm,v_dx)); v_vy = _mm_add_ps(v_dyp,_mm_mul_ps(v_qtm,v_dy)); /* average kinetic energy */ /* dxp += vx; */ /* dyp += vy; */ v_dxp = _mm_add_ps(v_dxp,v_vx); v_dyp = _mm_add_ps(v_dyp,v_vy); /* sum1 += dxp*dxp + dyp*dyp; */ v_at = _mm_mul_ps(v_dxp,v_dxp); v_at = _mm_add_ps(v_at,_mm_mul_ps(v_dyp,v_dyp)); /* convert to double precision before accumulating */ v_d = _mm_cvtps_pd(v_at); v_sum1 = _mm_add_pd(v_sum1,v_d); v_it = _mm_srli_si128((__m128i)v_at,8); v_d = _mm_cvtps_pd((__m128)v_it); v_sum1 = _mm_add_pd(v_sum1,v_d); /* new position */ /* dx = x + vx*dt; */ /* dy = y + vy*dt; */ v_dx = _mm_add_ps(v_x,_mm_mul_ps(v_vx,v_dt)); v_dy = _mm_add_ps(v_y,_mm_mul_ps(v_vy,v_dt)); /* find particles going out of bounds */ /* mm = 0; */ v_st = v_zero; /* count how many particles are going in each direction in ncl */ /* save their address and destination in ihole */ /* use periodic boundary conditions and check for roundoff error */ /* mm = direction particle is going */ /* if (dx >= edgerx) { */ /* if (dx >= anx) */ /* dx -= anx; */ /* mm = 2; */ /* } */ v_x = _mm_cmpge_ps(v_dx,v_edgerx); v_y = _mm_cmplt_ps(v_dx,v_edgelx); v_at = _mm_or_ps(v_x,v_y); v_it = _mm_srli_si128((__m128i)v_at,8); v_it = _mm_add_epi64((__m128i)v_at,v_it); _mm_storel_epi64((__m128i *)&jj[0],v_it); /* execute if either test result is true for any particle */ if (jj[0] != 0) { v_st = _mm_and_ps(v_two,v_x); v_x = _mm_and_ps(v_x,_mm_cmpge_ps(v_dx,v_anx)); v_dx = _mm_sub_ps(v_dx,_mm_and_ps(v_anx,v_x)); /* if (dx < edgelx) { */ /* if (dx < 0.0f) { */ /* dx += anx; */ /* if (dx < anx) */ /* mm = 1; */ /* else */ /* dx = 0.0; */ /* } */ /* else { */ /* mm = 1; */ /* } */ /* } */ v_at = _mm_and_ps(v_one,v_y); v_x = _mm_and_ps(v_y,_mm_cmplt_ps(v_dx,v_zero)); v_dx = _mm_add_ps(v_dx,_mm_and_ps(v_anx,v_x)); v_y = _mm_cmplt_ps(v_dx,v_anx); v_dx = _mm_and_ps(v_dx,v_y); v_st = _mm_add_ps(v_st,_mm_and_ps(v_at,v_y)); } /* if (dy >= edgery) { */ /* if (dy >= any) */ /* dy -= any; */ /* mm += 6; */ /* } */ v_y = _mm_cmpge_ps(v_dy,v_edgery); v_x = _mm_cmplt_ps(v_dy,v_edgely); v_at = _mm_or_ps(v_x,v_y); v_it = _mm_srli_si128((__m128i)v_at,8); v_it = _mm_add_epi64((__m128i)v_at,v_it); _mm_storel_epi64((__m128i *)&jj[0],v_it); /* execute if either test result is true for any particle */ if (jj[0] != 0) { v_st = _mm_add_ps(v_st,_mm_and_ps(v_six,v_y)); v_y = _mm_and_ps(v_y,_mm_cmpge_ps(v_dy,v_any)); v_dy = _mm_sub_ps(v_dy,_mm_and_ps(v_any,v_y)); /* if (dy < edgely) { */ /* if (dy < 0.0) { */ /* dy += any; */ /* if (dy < any) */ /* mm += 3; */ /* else */ /* dy = 0.0; */ /* } */ /* else { */ /* mm += 3; */ /* } */ /* } */ v_at = _mm_and_ps(v_three,v_x); v_y = _mm_and_ps(v_x,_mm_cmplt_ps(v_dy,v_zero)); v_dy = _mm_add_ps(v_dy,_mm_and_ps(v_any,v_y)); v_x = _mm_cmplt_ps(v_dy,v_any); v_dy = _mm_and_ps(v_dy,v_x); v_st = _mm_add_ps(v_st,_mm_and_ps(v_at,v_x)); } /* set new position */ /* ppart[j+npoff] = dx; */ /* ppart[j+nppmx+npoff] = dy; */ _mm_store_ps(&ppart[j+npoff],v_dx); _mm_store_ps(&ppart[j+nppmx+npoff],v_dy); /* set new velocity */ /* ppart[j+2*nppmx+npoff] = vx; */ /* ppart[j+3*nppmx+npoff] = vy; */ _mm_store_ps(&ppart[j+2*nppmx+npoff],v_vx); _mm_store_ps(&ppart[j+3*nppmx+npoff],v_vy); /* increment counters */ /* if (mm > 0) { */ /* ncl[mm+8*k-1] += 1; */ /* ih += 1; */ /* if (ih <= ntmax) { */ /* ihole[2*(ih+(ntmax+1)*k)] = j + 1; */ /* ihole[1+2*(ih+(ntmax+1)*k)] = mm; */ /* } */ /* else { */ /* nh = 1; */ /* } */ /* } */ _mm_store_si128((__m128i *)ll,_mm_cvttps_epi32(v_st)); /* remove zero ist values and left shift data */ kk = 0; memset((void*)lm,0,8*sizeof(int)); for (i = 0; i < 4; i++) { mm = ll[i]; if (mm > 0) { lm[2*kk] = j + i + 1; lm[1+2*kk] = mm; ncl[mm+8*k-1] += 1; kk += 1; } } if (kk > 0) { if ((ih+kk) > ntmax) { nh = 1; } else { v_it = _mm_load_si128((__m128i *)lm); _mm_storeu_si128((__m128i *)&ihole[2*(ih+1+(ntmax+1)*k)],v_it); if (kk > 2) { v_it = _mm_load_si128((__m128i *)&lm[4]); _mm_storeu_si128((__m128i *)&ihole[2*(ih+3+(ntmax+1)*k)],v_it); } } ih += kk; } } /* loop over remaining particles in tile */ for (j = nps; j < npp; j++) { /* find interpolation weights */ x = ppart[j+npoff]; y = ppart[j+nppmx+npoff]; nn = x; mm = y; dxp = x - (float) nn; dyp = y - (float) mm; nn = 2*(nn - noff + mxv*(mm - moff)); amx = 1.0f - dxp; amy = 1.0f - dyp; /* find acceleration */ dx = amx*sfxy[nn]; dy = amx*sfxy[nn+1]; dx = amy*(dxp*sfxy[nn+2] + dx); dy = amy*(dxp*sfxy[nn+3] + dy); nn += 2*mxv; vx = amx*sfxy[nn]; vy = amx*sfxy[nn+1]; dx += dyp*(dxp*sfxy[nn+2] + vx); dy += dyp*(dxp*sfxy[nn+3] + vy); /* new velocity */ dxp = ppart[j+2*nppmx+npoff]; dyp = ppart[j+3*nppmx+npoff]; vx = dxp + qtm*dx; vy = dyp + qtm*dy; /* average kinetic energy */ dxp += vx; dyp += vy; sum1 += dxp*dxp + dyp*dyp; /* new position */ dx = x + vx*dt; dy = y + vy*dt; /* find particles going out of bounds */ mm = 0; /* count how many particles are going in each direction in ncl */ /* save their address and destination in ihole */ /* use periodic boundary conditions and check for roundoff error */ /* mm = direction particle is going */ if (dx >= edgerx) { if (dx >= anx) dx -= anx; mm = 2; } else if (dx < edgelx) { if (dx < 0.0f) { dx += anx; if (dx < anx) mm = 1; else dx = 0.0; } else { mm = 1; } } if (dy >= edgery) { if (dy >= any) dy -= any; mm += 6; } else if (dy < edgely) { if (dy < 0.0) { dy += any; if (dy < any) mm += 3; else dy = 0.0; } else { mm += 3; } } /* set new position */ ppart[j+npoff] = dx; ppart[j+nppmx+npoff] = dy; /* set new velocity */ ppart[j+2*nppmx+npoff] = vx; ppart[j+3*nppmx+npoff] = vy; /* increment counters */ if (mm > 0) { ncl[mm+8*k-1] += 1; ih += 1; if (ih <= ntmax) { ihole[2*(ih+(ntmax+1)*k)] = j + 1; ihole[1+2*(ih+(ntmax+1)*k)] = mm; } else { nh = 1; } } } /* sum2 += sum1; */ _mm_store_pd(&dd[0],v_sum1); for (j = 1; j < 2; j++) { dd[0] += dd[j]; } sum2 += (sum1 + dd[0]); /* set error and end of file flag */ /* ihole overflow */ if (nh > 0) { *irc = ih; ih = -ih; } ihole[2*(ntmax+1)*k] = ih; } /* normalize kinetic energy */ *ek += 0.125f*sum2; return; #undef MXV #undef MYV } /*--------------------------------------------------------------------*/ void csse2gppost2lt(float ppart[], float q[], int kpic[], float qm, int nppmx, int idimp, int mx, int my, int nxv, int nyv, int mx1, int mxy1) { /* for 2d code, this subroutine calculates particle charge density using first-order linear interpolation, periodic boundaries OpenMP/vector version using guard cells data deposited in tiles particles stored segmented array 17 flops/particle, 6 loads, 4 stores input: all, output: q charge density is approximated by values at the nearest grid points q(n,m)=qm*(1.-dx)*(1.-dy) q(n+1,m)=qm*dx*(1.-dy) q(n,m+1)=qm*(1.-dx)*dy q(n+1,m+1)=qm*dx*dy where n,m = leftmost grid points and dx = x-n, dy = y-m ppart[m][0][n] = position x of particle n in tile m ppart[m][1][n] = position y of particle n in tile m q[k][j] = charge density at grid point j,k kpic = number of particles per tile qm = charge on particle, in units of e nppmx = maximum number of particles in tile idimp = size of phase space = 4 mx/my = number of grids in sorting cell in x/y nxv = first dimension of charge array, must be >= nx+1 nyv = second dimension of charge array, must be >= ny+1 mx1 = (system length in x direction - 1)/mx + 1 mxy1 = mx1*my1, where my1 = (system length in y direction - 1)/my + 1 requires SSE2, ppart needs to be 16 byte aligned nppmx needs to be a multiple of 4 local data */ #define MXV 33 #define MYV 33 int noff, moff, npoff, npp, nps, mxv; int i, j, k, nn, mm, it; float x, y, dxp, dyp, amx, amy; __m128i v_noff, v_moff, v_mxv; __m128i v_nn, v_mm, v_it; __m128 v_qm, v_one, v_m; __m128 v_x, v_y, v_dxp, v_dyp, v_amx, v_amy; __m128 a, b, c, d; __attribute__((aligned(16))) unsigned int ll[4]; __attribute__((aligned(16))) float sq[MXV*MYV]; /* __attribute__((aligned(16))) float sq[(mx+1)*(my+1)]; */ mxv = mx + 1; v_mxv = _mm_set1_epi32(mxv); v_qm = _mm_set1_ps(qm); v_one = _mm_set1_ps(1.0f); v_m = _mm_castsi128_ps(_mm_set_epi32(-1,-1,-1,0)); /* error if local array is too small */ /* if ((mx >= MXV) || (my >= MYV)) */ /* return; */ /* loop over tiles */ #pragma omp parallel for \ private(i,j,k,noff,moff,npp,nps,npoff,nn,mm,it,x,y,dxp,dyp,amx,amy, \ v_noff,v_moff,v_nn,v_mm,v_it,v_x,v_y,v_dxp,v_dyp,v_amx,v_amy,a,b,c,d, \ ll,sq) for (k = 0; k < mxy1; k++) { noff = k/mx1; moff = my*noff; noff = mx*(k - mx1*noff); v_noff = _mm_set1_epi32(noff); v_moff = _mm_set1_epi32(moff); npp = kpic[k]; nps = 4*(npp/4); npoff = idimp*nppmx*k; /* zero out local accumulator */ /* for (j = 0; j < mxv*(my+1); j++) { */ /* sq[j] = 0.0f; */ /* } */ memset((void*)sq,0,mxv*(my+1)*sizeof(float)); /* loop over particles in tile in groups of 4 */ for (j = 0; j < nps; j+=4) { /* find interpolation weights */ /* x = ppart[j+npoff]; */ /* y = ppart[j+nppmx+npoff]; */ v_x = _mm_load_ps(&ppart[j+npoff]); v_y = _mm_load_ps(&ppart[j+nppmx+npoff]); /* nn = x; */ /* mm = y; */ v_nn = _mm_cvttps_epi32(v_x); v_mm = _mm_cvttps_epi32(v_y); /* dxp = qm*(x - (float) nn); */ v_dxp = _mm_sub_ps(v_x,_mm_cvtepi32_ps(v_nn)); v_dxp = _mm_mul_ps(v_dxp,v_qm); /* dyp = y - (float) mm; */ v_dyp = _mm_sub_ps(v_y,_mm_cvtepi32_ps(v_mm)); /* nn = nn - noff + mxv*(mm - moff); */ v_nn = _mm_sub_epi32(v_nn,v_noff); v_mm = _mm_sub_epi32(v_mm,v_moff); v_it = _mm_mul_epu32(v_mxv,_mm_srli_si128(v_mm,4)); v_mm = _mm_mul_epu32(v_mm,v_mxv); v_mm = _mm_add_epi32(v_mm,_mm_slli_si128(v_it,4)); v_nn = _mm_add_epi32(v_nn,v_mm); /* amx = qm - dxp; */ /* amy = 1.0f - dyp; */ v_amx = _mm_sub_ps(v_qm,v_dxp); v_amy = _mm_sub_ps(v_one,v_dyp); /* calculate weights, for lower left/right, upper left/right */ a = _mm_mul_ps(v_amx,v_amy); b = _mm_mul_ps(v_dxp,v_amy); c = _mm_mul_ps(v_amx,v_dyp); d = _mm_mul_ps(v_dxp,v_dyp); _mm_store_si128((__m128i *)ll,v_nn); /* transpose so a,b,c,d contain the 4 weights for each of 4 particles */ _MM_TRANSPOSE4_PS(a,b,c,d); /* deposit charge within tile to local accumulator */ /* x = q[nn] + amx*amy; */ /* y = q[nn+1] + dxp*amy; */ /* q[nn] = x; */ /* q[nn+1] = y; */ /* nn += nxv; */ /* x = q[nn] + amx*dyp; */ /* y = q[nn+1] + dxp*dyp; */ /* q[nn] = x; */ /* q[nn+1] = y; */ /* deposit for first particle */ mm = ll[0]; v_x = _mm_loadl_pi(v_x,(__m64 *)&sq[mm]); v_x = _mm_loadh_pi(v_x,(__m64 *)&sq[mm+mxv]); v_x = _mm_add_ps(v_x,a); _mm_storel_pi((__m64 *)&sq[mm],v_x); _mm_storeh_pi((__m64 *)&sq[mm+mxv],v_x); /* deposit for second particle */ mm = ll[1]; v_y = _mm_loadl_pi(v_y,(__m64 *)&sq[mm]); v_y = _mm_loadh_pi(v_y,(__m64 *)&sq[mm+mxv]); v_y = _mm_add_ps(v_y,b); _mm_storel_pi((__m64 *)&sq[mm],v_y); _mm_storeh_pi((__m64 *)&sq[mm+mxv],v_y); /* deposit for third particle */ mm = ll[2]; v_x = _mm_loadl_pi(v_x,(__m64 *)&sq[mm]); v_x = _mm_loadh_pi(v_x,(__m64 *)&sq[mm+mxv]); v_x = _mm_add_ps(v_x,c); _mm_storel_pi((__m64 *)&sq[mm],v_x); _mm_storeh_pi((__m64 *)&sq[mm+mxv],v_x); /* deposit for fourth particle */ mm = ll[3]; v_y = _mm_loadl_pi(v_y,(__m64 *)&sq[mm]); v_y = _mm_loadh_pi(v_y,(__m64 *)&sq[mm+mxv]); v_y = _mm_add_ps(v_y,d); _mm_storel_pi((__m64 *)&sq[mm],v_y); _mm_storeh_pi((__m64 *)&sq[mm+mxv],v_y); } /* loop over remaining particles in tile */ for (j = nps; j < npp; j++) { /* find interpolation weights */ x = ppart[j+npoff]; y = ppart[j+nppmx+npoff]; nn = x; mm = y; dxp = qm*(x - (float) nn); dyp = y - (float) mm; nn = nn - noff + mxv*(mm - moff); amx = qm - dxp; amy = 1.0f - dyp; /* deposit charge within tile to local accumulator */ x = sq[nn] + amx*amy; y = sq[nn+1] + dxp*amy; sq[nn] = x; sq[nn+1] = y; nn += mxv; x = sq[nn] + amx*dyp; y = sq[nn+1] + dxp*dyp; sq[nn] = x; sq[nn+1] = y; } /* deposit charge to interior points in global array */ nn = nxv - noff; mm = nyv - moff; nn = mx < nn ? mx : nn; mm = my < mm ? my : mm; nps = 4*(nn/4); for (j = 1; j < mm; j++) { /* vector loop over elements in blocks of 4 */ /* for (i = 1; i < nn; i++) { */ /* q[i+noff+nxv*(j+moff)] += sq[i+mxv*j]; */ /* } */ for (i = 0; i < nps; i+=4) { v_x = _mm_loadu_ps(&q[i+noff+nxv*(j+moff)]); v_y = _mm_loadu_ps(&sq[i+mxv*j]); /* zero out first element for i = 0 */ if (i==0) v_y = _mm_and_ps(v_y,v_m); v_x = _mm_add_ps(v_x,v_y); _mm_storeu_ps(&q[i+noff+nxv*(j+moff)],v_x); } /* loop over remaining elements */ it = 1 > nps ? 1 : nps; for (i = it; i < nn; i++) { q[i+noff+nxv*(j+moff)] += sq[i+mxv*j]; } } /* deposit charge to edge points in global array */ mm = nyv - moff; mm = my+1 < mm ? my+1 : mm; for (i = 1; i < nn; i++) { #pragma omp atomic q[i+noff+nxv*moff] += sq[i]; if (mm > my) { #pragma omp atomic q[i+noff+nxv*(mm+moff-1)] += sq[i+mxv*(mm-1)]; } } nn = nxv - noff; nn = mx+1 < nn ? mx+1 : nn; for (j = 0; j < mm; j++) { #pragma omp atomic q[noff+nxv*(j+moff)] += sq[mxv*j]; if (nn > mx) { #pragma omp atomic q[nn+noff-1+nxv*(j+moff)] += sq[nn-1+mxv*j]; } } } return; #undef MXV #undef MYV } /*--------------------------------------------------------------------*/ void csse2pporder2lt(float ppart[], float ppbuff[], int kpic[], int ncl[], int ihole[], int idimp, int nppmx, int nx, int ny, int mx, int my, int mx1, int my1, int npbmx, int ntmax, int *irc) { /* this subroutine sorts particles by x,y grid in tiles of mx, my linear interpolation, with periodic boundary conditions tiles are assumed to be arranged in 2D linear memory algorithm has 3 steps. first, one finds particles leaving tile and stores their number in each directon, location, and destination in ncl and ihole. second, a prefix scan of ncl is performed and departing particles are buffered in ppbuff in direction order. finally, we copy the incoming particles from other tiles into ppart. input: all except ppbuff, ncl, ihole, irc output: ppart, ppbuff, kpic, ncl, ihole, irc ppart[k][0][n] = position x of particle n in tile k ppart[k][1][n] = position y of particle n in tile k ppbuff[k][i][n] = i co-ordinate of particle n in tile k kpic[k] = number of particles in tile k ncl[k][i] = number of particles going to destination i, tile k ihole[k][:][0] = location of hole in array left by departing particle ihole[k][:][1] = direction destination of particle leaving hole all for tile k ihole[k][0][0] = ih, number of holes left (error, if negative) idimp = size of phase space = 4 nppmx = maximum number of particles in tile nx/ny = system length in x/y direction mx/my = number of grids in sorting cell in x/y mx1 = (system length in x direction - 1)/mx + 1 my1 = (system length in y direction - 1)/my + 1 npbmx = size of buffer array ppbuff ntmax = size of hole array for particles leaving tiles irc = maximum overflow, returned only if error occurs, when irc > 0 requires SSE2, ppart, ppbuff need to be 16 byte aligned nppmx, npbmx need to be a multiple of 4 local data */ int mxy1, noff, moff, npoff, npp, nps, nboff, ncoff; int i, j, k, ii, kx, ky, ih, nh, ist, nn, mm, isum; int ip, in, j1, j2, kxl, kxr, kk, kl, kr; float anx, any, edgelx, edgely, edgerx, edgery, dx, dy; __m128i v_it, v_is, v_in, v_m1, v_m2; __m128 v_dx, v_dy, v_st, v_at, v_x, v_y; __m128 v_anx, v_any, v_edgelx, v_edgely, v_edgerx, v_edgery; __m128 v_zero, v_one, v_two, v_three, v_six; __attribute__((aligned(16))) unsigned int ll[8], lm[8]; __attribute__((aligned(16))) unsigned long jj[1]; int ks[8]; mxy1 = mx1*my1; anx = (float) nx; any = (float) ny; /* find and count particles leaving tiles and determine destination */ /* update ppart, ihole, ncl */ v_anx = _mm_set1_ps(anx); v_any = _mm_set1_ps(any); v_zero = _mm_setzero_ps(); v_one = _mm_set1_ps(1.0f); v_two = _mm_set1_ps(2.0f); v_three = _mm_set1_ps(3.0f); v_six = _mm_set1_ps(6.0f); /* loop over tiles */ #pragma omp parallel for \ private(i,j,k,noff,moff,npp,nps,npoff,nn,mm,ih,nh,ist,kk,dx,dy, \ edgelx,edgely,edgerx,edgery,v_it,v_edgelx,v_edgely,v_edgerx,v_edgery,\ v_dx,v_dy,v_st,v_at,v_x,v_y,jj,ll,lm) for (k = 0; k < mxy1; k++) { noff = k/mx1; moff = my*noff; noff = mx*(k - mx1*noff); npp = kpic[k]; /* nps = 4*(npp/4); */ nps = (npp >> 2) << 2; npoff = idimp*nppmx*k; nn = nx - noff; nn = mx < nn ? mx : nn; mm = ny - moff; mm = my < mm ? my : mm; ih = 0; nh = 0; edgelx = noff; edgerx = noff + nn; edgely = moff; edgery = moff + mm; noff = (ntmax+1)*k; v_edgelx = _mm_set1_ps(edgelx); v_edgely = _mm_set1_ps(edgely); v_edgerx = _mm_set1_ps(edgerx); v_edgery = _mm_set1_ps(edgery); /* clear counters */ /* for (j = 0; j < 8; j++) { */ /* ncl[j+8*k] = 0; */ /* } */ memset((void*)&ncl[8*k],0,8*sizeof(int)); /* loop over particles in tile in groups of 4 */ for (j = 0; j < nps; j+=4) { /* dx = ppart[j+npoff]; */ /* dy = ppart[j+nppmx+npoff]; */ v_dx = _mm_load_ps(&ppart[j+npoff]); v_dy = _mm_load_ps(&ppart[j+nppmx+npoff]); /* find particles going out of bounds */ /* ist = 0; */ v_st = v_zero; /* count how many particles are going in each direction in ncl */ /* save their address and destination in ihole */ /* use periodic boundary conditions and check for roundoff error */ /* ist = direction particle is going */ /* if (dx >= edgerx) { */ /* if (dx >= anx) */ /* ppart[j+npoff] = dx - anx; */ /* ist = 2; */ /* } */ v_x = _mm_cmpge_ps(v_dx,v_edgerx); v_y = _mm_cmplt_ps(v_dx,v_edgelx); v_at = _mm_or_ps(v_x,v_y); v_it = _mm_srli_si128((__m128i)v_at,8); v_it = _mm_add_epi64((__m128i)v_at,v_it); _mm_storel_epi64((__m128i *)&jj[0],v_it); /* execute if either test result is true for any particle */ if (jj[0] != 0) { v_st = _mm_and_ps(v_two,v_x); v_x = _mm_and_ps(v_x,_mm_cmpge_ps(v_dx,v_anx)); /* write output if test result is true for any particle */ v_it = _mm_srli_si128((__m128i)v_x,8); v_it = _mm_add_epi64((__m128i)v_x,v_it); _mm_storel_epi64((__m128i *)&jj[0],v_it); if (jj[0] != 0) { v_x = _mm_sub_ps(v_dx,_mm_and_ps(v_anx,v_x)); _mm_store_ps(&ppart[j+npoff],v_x); } /* if (dx < edgelx) { */ /* if (dx < 0.0) { */ /* dx += anx; */ /* if (dx < anx) */ /* ist += 1; */ /* else */ /* dx = 0.0; */ /* ppart[j+npoff] = dx; */ /* } */ /* else { */ /* ist += 1; */ /* } */ /* } */ v_at = _mm_and_ps(v_one,v_y); v_x = _mm_and_ps(v_y,_mm_cmplt_ps(v_dx,v_zero)); /* write output if test result is true for any particle */ v_it = _mm_srli_si128((__m128i)v_x,8); v_it = _mm_add_epi64((__m128i)v_x,v_it); _mm_storel_epi64((__m128i *)&jj[0],v_it); if (jj[0] != 0) { v_x = _mm_add_ps(v_dx,_mm_and_ps(v_anx,v_x)); v_y = _mm_cmplt_ps(v_x,v_anx); v_at = _mm_and_ps(v_at,v_y); v_x = _mm_and_ps(v_x,v_y); _mm_store_ps(&ppart[j+npoff],v_x); } v_st = _mm_add_ps(v_st,v_at); } /* if (dy >= edgery) { */ /* if (dy >= any) */ /* ppart[j+nppmx+npoff] = dy - any; */ /* ist += 6; */ /* } */ v_y = _mm_cmpge_ps(v_dy,v_edgery); v_x = _mm_cmplt_ps(v_dy,v_edgely); v_at = _mm_or_ps(v_x,v_y); v_it = _mm_srli_si128((__m128i)v_at,8); v_it = _mm_add_epi64((__m128i)v_at,v_it); _mm_storel_epi64((__m128i *)&jj[0],v_it); /* execute if either test result is true for any particle */ if (jj[0] != 0) { v_st = _mm_add_ps(v_st,_mm_and_ps(v_six,v_y)); v_y = _mm_and_ps(v_y,_mm_cmpge_ps(v_dy,v_any)); /* write output if test result is true for any particle */ v_it = _mm_srli_si128((__m128i)v_y,8); v_it = _mm_add_epi64((__m128i)v_y,v_it); _mm_storel_epi64((__m128i *)&jj[0],v_it); if (jj[0] != 0) { v_y = _mm_sub_ps(v_dy,_mm_and_ps(v_any,v_y)); _mm_store_ps(&ppart[j+nppmx+npoff],v_y); } /* if (dy < edgely) { */ /* if (dy < 0.0) { */ /* dy += any; */ /* if (dy < any) */ /* ist += 3; */ /* else */ /* dy = 0.0; */ /* ppart[j+nppmx+npoff] = dy; */ /* } */ /* else { */ /* ist += 3; */ /* } */ /* } */ v_at = _mm_and_ps(v_three,v_x); v_y = _mm_and_ps(v_x,_mm_cmplt_ps(v_dy,v_zero)); /* write output if test result is true for any particle */ v_it = _mm_srli_si128((__m128i)v_y,8); v_it = _mm_add_epi64((__m128i)v_y,v_it); _mm_storel_epi64((__m128i *)&jj[0],v_it); if (jj[0] != 0) { v_y = _mm_add_ps(v_dy,_mm_and_ps(v_any,v_y)); v_x = _mm_cmplt_ps(v_y,v_any); v_at = _mm_and_ps(v_at,v_x); v_y = _mm_and_ps(v_y,v_x); _mm_store_ps(&ppart[j+nppmx+npoff],v_y); } v_st = _mm_add_ps(v_st,v_at); } /* increment counters */ /* if (ist > 0) { */ /* ncl[ist+8*k-1] += 1; */ /* ih += 1; */ /* if (ih <= ntmax) { */ /* ihole[2*(ih+(ntmax+1)*k)] = j + 1; */ /* ihole[1+2*(ih+(ntmax+1)*k)] = ist; */ /* } */ /* else { */ /* nh = 1; */ /* } */ /* } */ _mm_store_si128((__m128i *)ll,_mm_cvttps_epi32(v_st)); /* remove zero ist values and left shift data */ kk = 0; memset((void*)lm,0,8*sizeof(int)); for (i = 0; i < 4; i++) { ist = ll[i]; if (ist > 0) { lm[2*kk] = j + i + 1; lm[1+2*kk] = ist; ncl[ist+8*k-1] += 1; kk += 1; } } if (kk > 0) { if ((ih+kk) > ntmax) { nh = 1; } else { v_it = _mm_load_si128((__m128i *)lm); _mm_storeu_si128((__m128i *)&ihole[2*(ih+1+noff)],v_it); if (kk > 2) { v_it = _mm_load_si128((__m128i *)&lm[4]); _mm_storeu_si128((__m128i *)&ihole[2*(ih+3+noff)],v_it); } } ih += kk; } } /* loop over remaining particles in tile */ for (j = nps; j < npp; j++) { dx = ppart[j+npoff]; dy = ppart[j+nppmx+npoff]; /* find particles going out of bounds */ ist = 0; /* count how many particles are going in each direction in ncl */ /* save their address and destination in ihole */ /* use periodic boundary conditions and check for roundoff error */ /* ist = direction particle is going */ if (dx >= edgerx) { if (dx >= anx) ppart[j+npoff] = dx - anx; ist = 2; } else if (dx < edgelx) { if (dx < 0.0) { dx += anx; if (dx < anx) ist = 1; else dx = 0.0; ppart[j+npoff] = dx; } else { ist = 1; } } if (dy >= edgery) { if (dy >= any) ppart[j+nppmx+npoff] = dy - any; ist += 6; } else if (dy < edgely) { if (dy < 0.0) { dy += any; if (dy < any) ist += 3; else dy = 0.0; ppart[j+nppmx+npoff] = dy; } else { ist += 3; } } if (ist > 0) { ncl[ist+8*k-1] += 1; ih += 1; if (ih <= ntmax) { ihole[2*(ih+noff)] = j + 1; ihole[1+2*(ih+noff)] = ist; } else { nh = 1; } } } /* set error and end of file flag */ if (nh > 0) { *irc = ih; ih = -ih; } ihole[2*noff] = ih; } /* ihole overflow */ if (*irc > 0) return; /* buffer particles that are leaving tile: update ppbuff, ncl */ /* loop over tiles */ v_m1 = _mm_set_epi32(0,-1,0,-1); v_m2 = _mm_set_epi32(0,-1,-1,0); #pragma omp parallel for \ private(i,j,k,noff,npoff,nboff,isum,ist,nh,nps,ip,j1,ii,kk, \ v_it,v_is,v_in,lm) for (k = 0; k < mxy1; k++) { npoff = idimp*nppmx*k; nboff = idimp*npbmx*k; noff = (ntmax+1)*k; /* find address offset for ordered ppbuff array */ isum = 0; /* for (j = 0; j < 8; j++) { */ /* ist = ncl[j+8*k]; */ /* ncl[j+8*k] = isum; */ /* isum += ist; */ /* } */ /* perform exclusive prefix scan */ v_is = _mm_setzero_si128(); for (i = 0; i < 8; i+=4) { v_it = _mm_load_si128((__m128i *)&ncl[i+8*k]); /* save last entry */ v_in = _mm_srli_si128(v_it,12); /* shift and add last entry from previous read */ v_it = _mm_add_epi32(v_is,_mm_slli_si128(v_it,4)); /* first pass */ v_is = _mm_slli_si128(_mm_and_si128(v_it,v_m1),4); v_it = _mm_add_epi32(v_is,v_it); /* second pass */ v_is = _mm_shuffle_epi32(v_it,212); v_is = _mm_slli_si128(_mm_and_si128(v_is,v_m2),4); v_it = _mm_add_epi32(v_is,v_it); /* add last sum to next entry */ v_is = _mm_add_epi32(v_in,_mm_srli_si128(v_it,12)); _mm_store_si128((__m128i *)&ncl[i+8*k],v_it); } nh = ihole[2*noff]; /* nps = 4*(nh/4); */ nps = (nh >> 2) << 2; ip = 0; /* loop over particles leaving tile in groups of 4 */ for (j = 0; j < nps; j+=4) { /* buffer particles that are leaving tile, in direction order */ /* j1 = ihole[2*(j+1+noff)] - 1; */ /* ist = ihole[1+2*(j+1+noff)]; */ v_it = _mm_loadu_si128((__m128i *)&ihole[2*(j+1+noff)]); _mm_store_si128((__m128i *)lm,v_it); v_it = _mm_loadu_si128((__m128i *)&ihole[2*(j+3+noff)]); _mm_store_si128((__m128i *)&lm[4],v_it); for (kk = 0; kk < 4; kk++) { j1 = lm[2*kk] - 1; ist = lm[1+2*kk]; ii = ncl[ist+8*k-1]; if (ii < npbmx) { for (i = 0; i < idimp; i++) { ppbuff[ii+npbmx*i+nboff] = ppart[j1+nppmx*i+npoff]; } } else { ip = 1; } ncl[ist+8*k-1] = ii + 1; } } /* loop over remaining particles leaving tile */ for (j = nps; j < nh; j++) { /* buffer particles that are leaving tile, in direction order */ j1 = ihole[2*(j+1+noff)] - 1; ist = ihole[1+2*(j+1+noff)]; ii = ncl[ist+8*k-1]; if (ii < npbmx) { for (i = 0; i < idimp; i++) { ppbuff[ii+npbmx*i+nboff] = ppart[j1+nppmx*i+npoff]; } } else { ip = 1; } ncl[ist+8*k-1] = ii + 1; } /* set error */ if (ip > 0) *irc = ncl[7+8*k]; } /* ppbuff overflow */ if (*irc > 0) return; /* copy incoming particles from buffer into ppart: update ppart, kpic */ /* loop over tiles */ #pragma omp parallel for \ private(i,j,k,ii,kk,npp,nps,noff,npoff,nboff,kx,ky,kl,kr,kxl,kxr,ih,nh, \ nn,mm,ncoff,ist,j1,j2,ip,in,v_it,v_is,v_in,v_x,ks,ll,lm) for (k = 0; k < mxy1; k++) { npp = kpic[k]; npoff = idimp*nppmx*k; noff = (ntmax+1)*k; ky = k/mx1; /* loop over tiles in y, assume periodic boundary conditions */ kk = ky*mx1; /* find tile above */ kl = ky - 1; if (kl < 0) kl += my1; kl = kl*mx1; /* find tile below */ kr = ky + 1; if (kr >= my1) kr -= my1; kr = kr*mx1; /* loop over tiles in x, assume periodic boundary conditions */ kx = k - ky*mx1; kxl = kx - 1; if (kxl < 0) kxl += mx1; kxr = kx + 1; if (kxr >= mx1) kxr -= mx1; /* find tile number for different directions */ ks[0] = kxr + kk; ks[1] = kxl + kk; ks[2] = kx + kr; ks[3] = kxr + kr; ks[4] = kxl + kr; ks[5] = kx + kl; ks[6] = kxr + kl; ks[7] = kxl + kl; /* loop over directions */ nh = ihole[2*noff]; ncoff = 0; ih = 0; ist = 0; j1 = 0; v_in = _mm_set1_epi32(1); for (ii = 0; ii < 8; ii++) { nboff = idimp*npbmx*ks[ii]; if (ii > 0) ncoff = ncl[ii-1+8*ks[ii]]; /* ip = number of particles coming from direction ii */ ip = ncl[ii+8*ks[ii]] - ncoff; /* nps = 4*(ip/4); */ nps = (ip >> 2) << 2; /* loop over particles in this direction in groups of 4 */ for (j = 0; j < nps; j+=4) { /* insert incoming particles into holes */ /* ih += 1; */ /* if (ih <= nh) { */ /* j1 = ihole[2*(ih+noff)] - 1; */ /* } */ if (ih < nh) { v_it = _mm_loadu_si128((__m128i *)&ihole[2*(ih+1+noff)]); _mm_store_si128((__m128i *)lm,_mm_sub_epi32(v_it,v_in)); } if ((ih+2) < nh) { v_is = _mm_loadu_si128((__m128i *)&ihole[2*(ih+3+noff)]); _mm_store_si128((__m128i *)&lm[4],_mm_sub_epi32(v_is,v_in)); } /* place overflow at end of array */ /* else { */ /* j1 = npp; */ /* npp += 1; */ /* } */ ih += 4; nn = ih - nh; if (nn >= 4) { for (kk = 0; kk < 4; kk++) { lm[2*kk] = npp + kk; } npp += 4; } else if (nn > 0) { nn = nn < 4 ? nn : 4; for (kk = 4-nn; kk < 4; kk++) { lm[2*kk] = npp; npp += 1; } } for (i = 0; i < idimp; i++) { /* if (j1 < nppmx) */ /* ppart[j1+nppmx*i+npoff] */ /* = ppbuff[j+ncoff+npbmx*i+nboff]; */ v_x = _mm_loadu_ps(&ppbuff[j+ncoff+npbmx*i+nboff]); for (kk = 0; kk < 4; kk++) { j1 = lm[2*kk]; if (j1 < nppmx) { _mm_store_ss(&ppart[j1+nppmx*i+npoff],v_x); v_x = (__m128)_mm_srli_si128((__m128i)v_x,4); } else { ist = 1; } } } } /* loop over remaining particles in this direction */ for (j = nps; j < ip; j++) { ih += 1; /* insert incoming particles into holes */ if (ih <= nh) { j1 = ihole[2*(ih+noff)] - 1; } /* place overflow at end of array */ else { j1 = npp; npp += 1; } if (j1 < nppmx) { for (i = 0; i < idimp; i++) { ppart[j1+nppmx*i+npoff] = ppbuff[j+ncoff+npbmx*i+nboff]; } } else { ist = 1; } } } /* set error */ if (ist > 0) *irc = j1+1; /* fill up remaining holes in particle array with particles from bottom */ if (ih < nh) { ip = nh - ih; ii = nh; ih += 1; /* move particles from end into remaining holes */ /* holes are processed in increasing order */ /* nps = 4*(ip/4); */ nps = (ip >> 2) << 2; /* loop over particles in groups of 4 */ for (j = 0; j < nps; j+=4) { /* nn = ihole[2*(ii+noff)] - 1; */ v_it = _mm_loadu_si128((__m128i *)&ihole[2*(ii-3+noff)]); _mm_store_si128((__m128i *)ll,_mm_sub_epi32(v_it,v_in)); v_is = _mm_loadu_si128((__m128i *)&ihole[2*(ii-1+noff)]); _mm_store_si128((__m128i *)&ll[4],_mm_sub_epi32(v_is,v_in)); /* j2 = ihole[2*(ih+(ntmax+1)*k)] - 1; */ v_it = _mm_loadu_si128((__m128i *)&ihole[2*(ih+noff)]); _mm_store_si128((__m128i *)lm,_mm_sub_epi32(v_it,v_in)); v_is = _mm_loadu_si128((__m128i *)&ihole[2*(ih+2+noff)]); _mm_store_si128((__m128i *)&lm[4],_mm_sub_epi32(v_is,v_in)); /* holes with locations great than npp-ip do not need to be filled */ in = 0; mm = 0; nn = ll[6]; j2 = lm[0]; for (kk = 0; kk < 4; kk++) { j1 = npp - (j + kk) - 1; ll[2*kk+1] = nn; lm[2*kk+1] = j2; if (j1==nn) { in += 1; if (in < 4) nn = ll[6-2*in]; } else { mm += 1; if (mm < 4) j2 = lm[2*mm]; } } ii -= in; ih += mm; /* fill holes */ for (i = 0; i < idimp; i++) { ist = npp - j - 1; v_x = _mm_loadu_ps(&ppart[ist-3+nppmx*i+npoff]); v_x = _mm_shuffle_ps(v_x,v_x,27); /* j1 = npp - j - 1; */ /* if (j1==nn) { */ /* ii -= 1; */ /* nn = ihole[2*(ii+noff)] - 1; */ /* } */ for (kk = 0; kk < 4; kk++) { j1 = ist - kk; nn = ll[2*kk+1]; if (j1 != nn) { /* ppart[j2+nppmx*i+npoff] */ /* = ppart[j1+nppmx*i+npoff]; */ _mm_store_ss(&ppart[lm[2*kk+1]+nppmx*i+npoff],v_x); } v_x = (__m128)_mm_srli_si128((__m128i)v_x,4); } } } /* loop over remaining particles */ if (nps < ip) { nn = ihole[2*(ii+noff)] - 1; j2 = ihole[2*(ih+noff)] - 1; } for (j = nps; j < ip; j++) { j1 = npp - j - 1; if (j1==nn) { ii -= 1; nn = ihole[2*(ii+noff)] - 1; } else { for (i = 0; i < idimp; i++) { ppart[j2+nppmx*i+npoff] = ppart[j1+nppmx*i+npoff]; } ih += 1; j2 = ihole[2*(ih+(ntmax+1)*k)] - 1; } } npp -= ip; } kpic[k] = npp; } return; } /*--------------------------------------------------------------------*/ void csse2pporderf2lt(float ppart[], float ppbuff[], int kpic[], int ncl[], int ihole[], int idimp, int nppmx, int mx1, int my1, int npbmx, int ntmax, int *irc) { /* this subroutine sorts particles by x,y grid in tiles of mx, my linear interpolation, with periodic boundary conditions tiles are assumed to be arranged in 2D linear memory the algorithm has 2 steps. first, a prefix scan of ncl is performed and departing particles are buffered in ppbuff in direction order. then we copy the incoming particles from other tiles into ppart. it assumes that the number, location, and destination of particles leaving a tile have been previously stored in ncl and ihole by the cgppushf2lt procedure. input: all except ppbuff, irc output: ppart, ppbuff, kpic, ncl, irc ppart[k][0][n] = position x of particle n in tile k ppart[k][1][n] = position y of particle n in tile k ppbuff[k][i][n] = i co-ordinate of particle n in tile k kpic[k] = number of particles in tile k ncl[k][i] = number of particles going to destination i, tile k ihole[k][:][0] = location of hole in array left by departing particle ihole[k][:][1] = direction destination of particle leaving hole all for tile k ihole[k][0][0] = ih, number of holes left (error, if negative) idimp = size of phase space = 4 nppmx = maximum number of particles in tile mx1 = (system length in x direction - 1)/mx + 1 my1 = (system length in y direction - 1)/my + 1 npbmx = size of buffer array ppbuff ntmax = size of hole array for particles leaving tiles irc = maximum overflow, returned only if error occurs, when irc > 0 local data */ int mxy1, noff, npoff, npp, nps, nboff, ncoff; int i, j, k, ii, kx, ky, ih, nh, ist, nn, mm, isum; int ip, in, j1, j2, kxl, kxr, kk, kl, kr; __m128i v_it, v_is, v_in, v_m1, v_m2; __m128 v_x; __attribute__((aligned(16))) unsigned int ll[8], lm[8]; int ks[8]; mxy1 = mx1*my1; /* buffer particles that are leaving tile: update ppbuff, ncl */ /* loop over tiles */ v_m1 = _mm_set_epi32(0,-1,0,-1); v_m2 = _mm_set_epi32(0,-1,-1,0); #pragma omp parallel for \ private(i,j,k,noff,npoff,nboff,isum,ist,nh,nps,ip,j1,ii,kk, \ v_it,v_is,v_in,lm) for (k = 0; k < mxy1; k++) { npoff = idimp*nppmx*k; nboff = idimp*npbmx*k; noff = (ntmax+1)*k; /* find address offset for ordered ppbuff array */ isum = 0; /* for (j = 0; j < 8; j++) { */ /* ist = ncl[j+8*k]; */ /* ncl[j+8*k] = isum; */ /* isum += ist; */ /* } */ /* perform exclusive prefix scan */ v_is = _mm_setzero_si128(); for (i = 0; i < 8; i+=4) { v_it = _mm_load_si128((__m128i *)&ncl[i+8*k]); /* save last entry */ v_in = _mm_srli_si128(v_it,12); /* shift and add last entry from previous read */ v_it = _mm_add_epi32(v_is,_mm_slli_si128(v_it,4)); /* first pass */ v_is = _mm_slli_si128(_mm_and_si128(v_it,v_m1),4); v_it = _mm_add_epi32(v_is,v_it); /* second pass */ v_is = _mm_shuffle_epi32(v_it,212); v_is = _mm_slli_si128(_mm_and_si128(v_is,v_m2),4); v_it = _mm_add_epi32(v_is,v_it); /* add last sum to next entry */ v_is = _mm_add_epi32(v_in,_mm_srli_si128(v_it,12)); _mm_store_si128((__m128i *)&ncl[i+8*k],v_it); } nh = ihole[2*noff]; /* nps = 4*(nh/4); */ nps = (nh >> 2) << 2; ip = 0; /* loop over particles leaving tile in groups of 4 */ for (j = 0; j < nps; j+=4) { /* buffer particles that are leaving tile, in direction order */ /* j1 = ihole[2*(j+1+noff)] - 1; */ /* ist = ihole[1+2*(j+1+noff)]; */ v_it = _mm_loadu_si128((__m128i *)&ihole[2*(j+1+noff)]); _mm_store_si128((__m128i *)lm,v_it); v_it = _mm_loadu_si128((__m128i *)&ihole[2*(j+3+noff)]); _mm_store_si128((__m128i *)&lm[4],v_it); for (kk = 0; kk < 4; kk++) { j1 = lm[2*kk] - 1; ist = lm[1+2*kk]; ii = ncl[ist+8*k-1]; if (ii < npbmx) { for (i = 0; i < idimp; i++) { ppbuff[ii+npbmx*i+nboff] = ppart[j1+nppmx*i+npoff]; } } else { ip = 1; } ncl[ist+8*k-1] = ii + 1; } } /* loop over remaining particles leaving tile */ for (j = nps; j < nh; j++) { /* buffer particles that are leaving tile, in direction order */ j1 = ihole[2*(j+1+noff)] - 1; ist = ihole[1+2*(j+1+noff)]; ii = ncl[ist+8*k-1]; if (ii < npbmx) { for (i = 0; i < idimp; i++) { ppbuff[ii+npbmx*i+nboff] = ppart[j1+nppmx*i+npoff]; } } else { ip = 1; } ncl[ist+8*k-1] = ii + 1; } /* set error */ if (ip > 0) *irc = ncl[7+8*k]; } /* ppbuff overflow */ if (*irc > 0) return; /* copy incoming particles from buffer into ppart: update ppart, kpic */ /* loop over tiles */ #pragma omp parallel for \ private(i,j,k,ii,kk,npp,nps,noff,npoff,nboff,kx,ky,kl,kr,kxl,kxr,ih,nh, \ nn,mm,ncoff,ist,j1,j2,ip,in,v_it,v_is,v_in,v_x,ks,ll,lm) for (k = 0; k < mxy1; k++) { npp = kpic[k]; npoff = idimp*nppmx*k; noff = (ntmax+1)*k; ky = k/mx1; /* loop over tiles in y, assume periodic boundary conditions */ kk = ky*mx1; /* find tile above */ kl = ky - 1; if (kl < 0) kl += my1; kl = kl*mx1; /* find tile below */ kr = ky + 1; if (kr >= my1) kr -= my1; kr = kr*mx1; /* loop over tiles in x, assume periodic boundary conditions */ kx = k - ky*mx1; kxl = kx - 1; if (kxl < 0) kxl += mx1; kxr = kx + 1; if (kxr >= mx1) kxr -= mx1; /* find tile number for different directions */ ks[0] = kxr + kk; ks[1] = kxl + kk; ks[2] = kx + kr; ks[3] = kxr + kr; ks[4] = kxl + kr; ks[5] = kx + kl; ks[6] = kxr + kl; ks[7] = kxl + kl; /* loop over directions */ nh = ihole[2*noff]; ncoff = 0; ih = 0; ist = 0; j1 = 0; v_in = _mm_set1_epi32(1); for (ii = 0; ii < 8; ii++) { nboff = idimp*npbmx*ks[ii]; if (ii > 0) ncoff = ncl[ii-1+8*ks[ii]]; /* ip = number of particles coming from direction ii */ ip = ncl[ii+8*ks[ii]] - ncoff; /* nps = 4*(ip/4); */ nps = (ip >> 2) << 2; /* loop over particles in this direction in groups of 4 */ for (j = 0; j < nps; j+=4) { /* insert incoming particles into holes */ /* ih += 1; */ /* if (ih <= nh) { */ /* j1 = ihole[2*(ih+noff)] - 1; */ /* } */ if (ih < nh) { v_it = _mm_loadu_si128((__m128i *)&ihole[2*(ih+1+noff)]); _mm_store_si128((__m128i *)lm,_mm_sub_epi32(v_it,v_in)); } if ((ih+2) < nh) { v_is = _mm_loadu_si128((__m128i *)&ihole[2*(ih+3+noff)]); _mm_store_si128((__m128i *)&lm[4],_mm_sub_epi32(v_is,v_in)); } /* place overflow at end of array */ /* else { */ /* j1 = npp; */ /* npp += 1; */ /* } */ ih += 4; nn = ih - nh; if (nn >= 4) { for (kk = 0; kk < 4; kk++) { lm[2*kk] = npp + kk; } npp += 4; } else if (nn > 0) { nn = nn < 4 ? nn : 4; for (kk = 4-nn; kk < 4; kk++) { lm[2*kk] = npp; npp += 1; } } for (i = 0; i < idimp; i++) { /* if (j1 < nppmx) */ /* ppart[j1+nppmx*i+npoff] */ /* = ppbuff[j+ncoff+npbmx*i+nboff]; */ v_x = _mm_loadu_ps(&ppbuff[j+ncoff+npbmx*i+nboff]); for (kk = 0; kk < 4; kk++) { j1 = lm[2*kk]; if (j1 < nppmx) { _mm_store_ss(&ppart[j1+nppmx*i+npoff],v_x); v_x = (__m128)_mm_srli_si128((__m128i)v_x,4); } else { ist = 1; } } } } /* loop over remaining particles in this direction */ for (j = nps; j < ip; j++) { ih += 1; /* insert incoming particles into holes */ if (ih <= nh) { j1 = ihole[2*(ih+noff)] - 1; } /* place overflow at end of array */ else { j1 = npp; npp += 1; } if (j1 < nppmx) { for (i = 0; i < idimp; i++) { ppart[j1+nppmx*i+npoff] = ppbuff[j+ncoff+npbmx*i+nboff]; } } else { ist = 1; } } } /* set error */ if (ist > 0) *irc = j1+1; /* fill up remaining holes in particle array with particles from bottom */ if (ih < nh) { ip = nh - ih; ii = nh; ih += 1; /* move particles from end into remaining holes */ /* holes are processed in increasing order */ /* nps = 4*(ip/4); */ nps = (ip >> 2) << 2; /* loop over particles in groups of 4 */ for (j = 0; j < nps; j+=4) { /* nn = ihole[2*(ii+noff)] - 1; */ v_it = _mm_loadu_si128((__m128i *)&ihole[2*(ii-3+noff)]); _mm_store_si128((__m128i *)ll,_mm_sub_epi32(v_it,v_in)); v_is = _mm_loadu_si128((__m128i *)&ihole[2*(ii-1+noff)]); _mm_store_si128((__m128i *)&ll[4],_mm_sub_epi32(v_is,v_in)); /* j2 = ihole[2*(ih+(ntmax+1)*k)] - 1; */ v_it = _mm_loadu_si128((__m128i *)&ihole[2*(ih+noff)]); _mm_store_si128((__m128i *)lm,_mm_sub_epi32(v_it,v_in)); v_is = _mm_loadu_si128((__m128i *)&ihole[2*(ih+2+noff)]); _mm_store_si128((__m128i *)&lm[4],_mm_sub_epi32(v_is,v_in)); /* holes with locations great than npp-ip do not need to be filled */ in = 0; mm = 0; nn = ll[6]; j2 = lm[0]; for (kk = 0; kk < 4; kk++) { j1 = npp - (j + kk) - 1; ll[2*kk+1] = nn; lm[2*kk+1] = j2; if (j1==nn) { in += 1; if (in < 4) nn = ll[6-2*in]; } else { mm += 1; if (mm < 4) j2 = lm[2*mm]; } } ii -= in; ih += mm; /* fill holes */ for (i = 0; i < idimp; i++) { ist = npp - j - 1; v_x = _mm_loadu_ps(&ppart[ist-3+nppmx*i+npoff]); v_x = _mm_shuffle_ps(v_x,v_x,27); /* j1 = npp - j - 1; */ /* if (j1==nn) { */ /* ii -= 1; */ /* nn = ihole[2*(ii+noff)] - 1; */ /* } */ for (kk = 0; kk < 4; kk++) { j1 = ist - kk; nn = ll[2*kk+1]; if (j1 != nn) { /* ppart[j2+nppmx*i+npoff] */ /* = ppart[j1+nppmx*i+npoff]; */ _mm_store_ss(&ppart[lm[2*kk+1]+nppmx*i+npoff],v_x); } v_x = (__m128)_mm_srli_si128((__m128i)v_x,4); } } } /* loop over remaining particles */ if (nps < ip) { nn = ihole[2*(ii+noff)] - 1; j2 = ihole[2*(ih+noff)] - 1; } for (j = nps; j < ip; j++) { j1 = npp - j - 1; if (j1==nn) { ii -= 1; nn = ihole[2*(ii+noff)] - 1; } else { for (i = 0; i < idimp; i++) { ppart[j2+nppmx*i+npoff] = ppart[j1+nppmx*i+npoff]; } ih += 1; j2 = ihole[2*(ih+(ntmax+1)*k)] - 1; } } npp -= ip; } kpic[k] = npp; } return; } /*--------------------------------------------------------------------*/ void csse2cguard2l(float fxy[], int nx, int ny, int nxe, int nye) { /* replicate extended periodic vector field fxy linear interpolation nx/ny = system length in x/y direction nxe = first dimension of field arrays, must be >= nx+1 nye = second dimension of field arrays, must be >= ny+1 requires SSE2, fxy needs to be 16 byte aligned nxe*ny needs to be a multiple of 2 local data */ int j, k, nxs; nxs = 2*(nx/2); /* copy edges of extended field */ for (k = 0; k < ny; k++) { fxy[2*nx+2*nxe*k] = fxy[2*nxe*k]; fxy[1+2*nx+2*nxe*k] = fxy[1+2*nxe*k]; } /* vector loop over elements in blocks of 2 */ for (j = 0; j < nxs; j+=2) { _mm_store_ps(&fxy[2*j+2*nxe*ny],_mm_load_ps(&fxy[2*j])); } /* loop over remaining elements */ for (j = nxs; j < nx; j++) { fxy[2*j+2*nxe*ny] = fxy[2*j]; fxy[1+2*j+2*nxe*ny] = fxy[1+2*j]; } fxy[2*nx+2*nxe*ny] = fxy[0]; fxy[1+2*nx+2*nxe*ny] = fxy[1]; return; } /*--------------------------------------------------------------------*/ void csse2aguard2l(float q[], int nx, int ny, int nxe, int nye) { /* accumulate extended periodic scalar field q linear interpolation nx/ny = system length in x/y direction nxe = first dimension of field arrays, must be >= nx+1 nye = second dimension of field arrays, must be >= ny+1 requires SSE2, q needs to be 16 byte aligned nxe*ny needs to be a multiple of 4 local data */ int j, k, nxs; __m128 v_q; nxs = 4*(nx/4); /* accumulate edges of extended field */ for (k = 0; k < ny; k++) { q[nxe*k] += q[nx+nxe*k]; q[nx+nxe*k] = 0.0; } /* vector loop over elements in blocks of 4 */ for (j = 0; j < nxs; j+=4) { v_q = _mm_add_ps(_mm_load_ps(&q[j]),_mm_load_ps(&q[j+nxe*ny])); _mm_store_ps(&q[j],v_q); _mm_store_ps(&q[j+nxe*ny],_mm_setzero_ps()); } /* loop over remaining elements */ for (j = nxs; j < nx; j++) { q[j] += q[j+nxe*ny]; q[j+nxe*ny] = 0.0; } q[0] += q[nx+nxe*ny]; q[nx+nxe*ny] = 0.0; return; } /*--------------------------------------------------------------------*/ void csse2mpois22(float complex q[], float complex fxy[], int isign, float complex ffc[], float ax, float ay, float affp, float *we, int nx, int ny, int nxvh, int nyv, int nxhd, int nyhd) { /* this subroutine solves 2d poisson's equation in fourier space for force/charge (or convolution of electric field over particle shape) with periodic boundary conditions. for isign = 0, input: isign,ax,ay,affp,nx,ny,nxvh,nyhd, output: ffc for isign /= 0, input: q,ffc,isign,nx,ny,nxvh,nyhd, output: fxy,we approximate flop count is: 26*nxc*nyc + 12*(nxc + nyc) where nxc = nx/2 - 1, nyc = ny/2 - 1 equation used is: fx[ky][kx] = -sqrt(-1)*kx*g[ky][kx]*s[ky][kx]*q[ky][kx], fy[ky][kx] = -sqrt(-1)*ky*g[ky][kx]*s[ky][kx]*q[ky][kx], where kx = 2pi*j/nx, ky = 2pi*k/ny, and j,k = fourier mode numbers, g[ky][kx] = (affp/(kx**2+ky**2))*s(kx,ky), s[ky][kx] = exp(-((kx*ax)**2+(ky*ay)**2)/2), except for fx(kx=pi) = fy(kx=pi) = fx(ky=pi) = fy(ky=pi) = 0, and fx(kx=0,ky=0) = fy(kx=0,ky=0) = 0. q[k][j] = complex charge density for fourier mode (j,k) fxy[k][j][0] = x component of complex force/charge, fxy[k][j][1] = y component of complex force/charge, all for fourier mode (j,k) if isign = 0, form factor array is prepared if isign is not equal to 0, force/charge is calculated cimag(ffc[k][j]) = finite-size particle shape factor s for fourier mode (j,k) creal(ffc[k][j]) = potential green's function g for fourier mode (j,k) ax/ay = half-width of particle in x/y direction affp = normalization constant = nx*ny/np, where np=number of particles electric field energy is also calculated, using we = nx*ny*sum((affp/(kx**2+ky**2))*|q[ky][kx]*s[ky][kx]|**2) nx/ny = system length in x/y direction nxvh = first dimension of field arrays, must be >= nxh nyv = second dimension of field arrays, must be >= ny nxhd = first dimension of form factor array, must be >= nxh nyhd = second dimension of form factor array, must be >= nyh requires SSE2, q, fxy, ffc need to be 16 byte aligned nxhd, nxvh need to be a multiple of 2 local data */ int nxh, nyh, nxhs, j, k, k1, kk, kj, it; float dnx, dny, dkx, dky, at1, at2, at3, at4; float complex zero, zt1, zt2; double wp, sum1; __m128i v_j, v_it; __m128 v_dnx, v_dny, v_dky, v_at1, v_at2, v_at3, v_at4; __m128 v_zero, v_m, v_zt1, v_zt2, v_zt3, v_zt4; __m128d v_wp, v_d; __attribute__((aligned(16))) double dd[2]; nxh = nx/2; nyh = 1 > ny/2 ? 1 : ny/2; nxhs = 2*(nxh/2); dnx = 6.28318530717959/(float) nx; dny = 6.28318530717959/(float) ny; zero = 0.0 + 0.0*_Complex_I; v_j = _mm_set_epi32(1,1,0,0); v_dnx = _mm_set1_ps(dnx); v_dny = _mm_set1_ps(dny); v_zero = _mm_set1_ps(0.0f); v_m = _mm_set_ps(1.0f,-1.0f,1.0f,-1.0f); if (isign != 0) goto L30; /* prepare form factor array */ for (k = 0; k < nyh; k++) { dky = dny*(float) k; kk = nxhd*k; at1 = dky*dky; at2 = pow((dky*ay),2); for (j = 0; j < nxh; j++) { dkx = dnx*(float) j; at3 = dkx*dkx + at1; at4 = exp(-0.5*(pow((dkx*ax),2) + at2)); if (at3==0.0) { ffc[j+kk] = affp + 1.0*_Complex_I; } else { ffc[j+kk] = (affp*at4/at3) + at4*_Complex_I; } } } return; /* calculate force/charge and sum field energy */ L30: sum1 = 0.0; #pragma omp parallel for \ private(j,k,k1,kk,kj,dky,at1,at2,at3,zt1,zt2,wp,v_it,v_dky,v_at1, \ v_at2,v_at3,v_at4,v_zt1,v_zt2,v_zt3,v_zt4,v_wp,v_d,dd) \ reduction(+:sum1) /* mode numbers 0 < kx < nx/2 and 0 < ky < ny/2 */ for (k = 1; k < nyh; k++) { k1 = ny - k; dky = dny*(float) k; v_dky = _mm_mul_ps(v_dny,_mm_cvtepi32_ps(_mm_set1_epi32(k))); kk = nxhd*k; kj = nxvh*k; k1 = nxvh*ny - kj; wp = 0.0; v_wp = _mm_set1_pd(0.0); /* vector loop over elements in blocks of 2 */ for (j = 0; j < nxhs; j+=2) { /* at1 = crealf(ffc[j+kk])*cimagf(ffc[j+kk]); */ v_at1 = _mm_load_ps((float *)&ffc[j+kk]); v_at1 = _mm_mul_ps(v_at1,_mm_shuffle_ps(v_at1,v_at1,177)); /* at2 = at1*dnx*(float) j; */ v_it = _mm_add_epi32(_mm_set1_epi32(j),v_j); v_at2 = _mm_mul_ps(v_dnx,_mm_cvtepi32_ps(v_it)); v_at2 = _mm_mul_ps(v_at1,v_at2); /* at3 = dky*at1; */ v_at3 = _mm_mul_ps(v_dky,v_at1); /* zt1 = cimagf(q[j+kj]) - crealf(q[j+kj])*_Complex_I; */ v_zt1 = _mm_load_ps((float *)&q[j+kj]); v_zt1 = _mm_mul_ps(v_zt1,v_m); v_zt1 = _mm_shuffle_ps(v_zt1,v_zt1,177); /* zt2 = cimagf(q[j+k1]) - crealf(q[j+k1])*_Complex_I; */ v_zt2 = _mm_load_ps((float *)&q[j+k1]); v_zt2 = _mm_mul_ps(v_zt2,v_m); v_zt2 = _mm_shuffle_ps(v_zt2,v_zt2,177); /* zero out kx = 0 mode */ if (j==0) { v_at4 = _mm_castsi128_ps(_mm_set_epi32(-1,-1,0,0)); v_zt1 = _mm_and_ps(v_zt1,v_at4); v_zt2 = _mm_and_ps(v_zt2,v_at4); } /* fxy[2*j+2*kj] = at2*zt1; */ /* fxy[1+2*j+2*kj] = at3*zt1; */ v_at4 = _mm_mul_ps(v_at2,v_zt1); v_zt4 = _mm_mul_ps(v_at3,v_zt1); v_at4 = _mm_mul_ps(v_at2,v_zt1); v_zt4 = _mm_mul_ps(v_at3,v_zt1); /* reorder write */ v_zt3 = _mm_shuffle_ps(v_at4,v_zt4,68); v_zt4 = _mm_shuffle_ps(v_at4,v_zt4,238); _mm_store_ps((float *)&fxy[2*(j+kj)],v_zt3); _mm_store_ps((float *)&fxy[2*(j+1+kj)],v_zt4); /* fxy[2*j+2*k1] = at2*zt2; */ /* fxy[1+2*j+2*k1] = -at3*zt2; */ v_at4 = _mm_mul_ps(v_at2,v_zt2); v_zt4 = _mm_sub_ps(v_zero,_mm_mul_ps(v_at3,v_zt2)); /* reorder write */ v_zt3 = _mm_shuffle_ps(v_at4,v_zt4,68); v_zt4 = _mm_shuffle_ps(v_at4,v_zt4,238); _mm_store_ps((float *)&fxy[2*(j+k1)],v_zt3); _mm_store_ps((float *)&fxy[2*(j+1+k1)],v_zt4); /* wp += at1*(q[j+kj]*conjf(q[j+kj]) + q[j+k1]*conjf(q[j+k1])); */ v_at4 = _mm_mul_ps(v_zt1,v_zt1); v_at4 = _mm_add_ps(v_at4,_mm_mul_ps(v_zt2,v_zt2)); v_at4 = _mm_mul_ps(v_at1,v_at4); /* convert to double precision before accumulating */ v_d = _mm_cvtps_pd(v_at4); v_wp = _mm_add_pd(v_wp,v_d); v_it = _mm_srli_si128((__m128i)v_at4,8); v_d = _mm_cvtps_pd((__m128)v_it); v_wp = _mm_add_pd(v_wp,v_d); } /* loop over remaining elements */ it = 1 > nxhs ? 1 : nxhs; for (j = it; j < nxh; j++) { at1 = crealf(ffc[j+kk])*cimagf(ffc[j+kk]); at2 = at1*dnx*(float) j; at3 = dky*at1; zt1 = cimagf(q[j+kj]) - crealf(q[j+kj])*_Complex_I; zt2 = cimagf(q[j+k1]) - crealf(q[j+k1])*_Complex_I; fxy[2*j+2*kj] = at2*zt1; fxy[1+2*j+2*kj] = at3*zt1; fxy[2*j+2*k1] = at2*zt2; fxy[1+2*j+2*k1] = -at3*zt2; wp += at1*(q[j+kj]*conjf(q[j+kj]) + q[j+k1]*conjf(q[j+k1])); } /* sum1 += wp; */ _mm_store_pd(&dd[0],v_wp); for (j = 1; j < 2; j++) { dd[0] += dd[j]; } sum1 += (wp + dd[0]); } wp = 0.0; v_wp = _mm_set1_pd(0.0); /* mode numbers kx = 0, nx/2 */ for (k = 1; k < nyh; k++) { kk = nxhd*k; kj = nxvh*k; k1 = nxvh*ny - kj; at1 = crealf(ffc[kk])*cimagf(ffc[kk]); at3 = at1*dny*(float) k; zt1 = cimagf(q[kj]) - crealf(q[kj])*_Complex_I; fxy[2*kj] = zero; fxy[1+2*kj] = at3*zt1; fxy[2*k1] = zero; fxy[1+2*k1] = zero; wp += at1*(q[kj]*conjf(q[kj])); } /* mode numbers ky = 0, ny/2 */ k1 = 2*nxvh*nyh; /* vector loop over elements in blocks of 2 */ for (j = 0; j < nxhs; j+=2) { /* at1 = crealf(ffc[j])*cimagf(ffc[j]); */ v_at1 = _mm_load_ps((float *)&ffc[j]); v_at1 = _mm_mul_ps(v_at1,_mm_shuffle_ps(v_at1,v_at1,177)); /* at2 = at1*dnx*(float) j; */ v_it = _mm_add_epi32(_mm_set1_epi32(j),v_j); v_at2 = _mm_mul_ps(v_dnx,_mm_cvtepi32_ps(v_it)); v_at2 = _mm_mul_ps(v_at1,v_at2); /* zt1 = cimagf(q[j]) - crealf(q[j])*_Complex_I; */ v_zt1 = _mm_load_ps((float *)&q[j]); v_zt1 = _mm_mul_ps(v_zt1,v_m); v_zt1 = _mm_shuffle_ps(v_zt1,v_zt1,177); /* zero out kx = 0 mode */ if (j==0) { v_at4 = _mm_castsi128_ps(_mm_set_epi32(-1,-1,0,0)); v_zt1 = _mm_and_ps(v_zt1,v_at4); } /* fxy[2*j] = at2*zt1; */ /* fxy[1+2*j] = zero; */ v_at4 = _mm_mul_ps(v_at2,v_zt1); /* reorder write */ v_zt3 = _mm_shuffle_ps(v_at4,v_zero,68); v_zt4 = _mm_shuffle_ps(v_at4,v_zero,238); _mm_store_ps((float *)&fxy[2*j],v_zt3); _mm_store_ps((float *)&fxy[2*j+2],v_zt4); /* fxy[2*j+k1] = zero; */ /* fxy[1+2*j+k1] = zero; */ _mm_store_ps((float *)&fxy[2*j+k1],v_zero); _mm_store_ps((float *)&fxy[2*j+2+k1],v_zero); /* wp += at1*(q[j]*conjf(q[j])); */ v_at4 = _mm_mul_ps(v_at1,_mm_mul_ps(v_zt1,v_zt1)); /* convert to double precision before accumulating */ v_d = _mm_cvtps_pd(v_at4); v_wp = _mm_add_pd(v_wp,v_d); v_it = _mm_srli_si128((__m128i)v_at4,8); v_d = _mm_cvtps_pd((__m128)v_it); v_wp = _mm_add_pd(v_wp,v_d); } /* loop over remaining elements */ it = 1 > nxhs ? 1 : nxhs; for (j = it; j < nxh; j++) { at1 = crealf(ffc[j])*cimagf(ffc[j]); at2 = at1*dnx*(float) j; zt1 = cimagf(q[j]) - crealf(q[j])*_Complex_I; fxy[2*j] = at2*zt1; fxy[1+2*j] = zero; fxy[2*j+k1] = zero; fxy[1+2*j+k1] = zero; wp += at1*(q[j]*conjf(q[j])); } fxy[0] = zero; fxy[1] = zero; fxy[k1] = zero; fxy[1+k1] = zero; sum1 += wp; /* *we = sum1*(float) (nx*ny); */ _mm_store_pd(&dd[0],v_wp); for (j = 1; j < 2; j++) { dd[0] += dd[j]; } *we = (sum1 + dd[0])*(float) (nx*ny); return; } /*--------------------------------------------------------------------*/ void csse2fft2rmxx(float complex f[], int isign, int mixup[], float complex sct[], int indx, int indy, int nyi, int nyp, int nxhd, int nyd, int nxhyd, int nxyhd) { /* this subroutine performs the x part of a two dimensional real to complex fast fourier transform and its inverse, for a subset of y, using complex arithmetic, with OpenMP for isign = (-1,1), input: all, output: f for isign = -1, approximate flop count: N*(5*log2(N) + 19/2) for isign = 1, approximate flop count: N*(5*log2(N) + 15/2) where N = (nx/2)*ny indx/indy = exponent which determines length in x/y direction, where nx=2**indx, ny=2**indy if isign = -1, an inverse fourier transform in x is performed f[m][n] = (1/nx*ny)*sum(f[k][j]*exp(-sqrt(-1)*2pi*n*j/nx)) if isign = 1, a forward fourier transform in x is performed f[k][j] = sum(f[m][n]*exp(sqrt(-1)*2pi*n*j/nx)) mixup = array of bit reversed addresses sct = sine/cosine table nyi = initial y index used nyp = number of y indices used nxhd = first dimension of f >= nx/2 nyd = second dimension of f >= ny nxhyd = maximum of (nx/2,ny) nxyhd = maximum of (nx,ny)/2 fourier coefficients are stored as follows: f[k][j] = real, imaginary part of mode j,k, where 0 <= j < nx/2 and 0 <= k < ny, except for f[k][1] = real, imaginary part of mode nx/2,k, where ny/2+1 <= k < ny, and imag(f[0][0]) = real part of mode nx/2,0 and imag(f[0][ny/2]) = real part of mode nx/2,ny/2 written by viktor k. decyk, ucla requires SSE2, f needs to be 16 byte aligned nxhd need to be a multiple of 2 local data */ int indx1, indx1y, nx, nxh, nxhh, ny, nxy, nxhy, nyt; int nrx, i, j, k, l, j1, k1, k2, ns, ns2, km, kmr, nrxb, joff; int nss, nxhhs, it; float ani; float complex t1, t2, t3; __m128 v_m, v_n, v_t1, v_t2, v_t3, v_t4, v_ani; if (isign==0) return; indx1 = indx - 1; indx1y = indx1 > indy ? indx1 : indy; nx = 1L<<indx; nxh = nx/2; nxhh = nx/4; ny = 1L<<indy; nxy = nx > ny ? nx : ny; nxhy = 1L<<indx1y; nyt = nyi + nyp - 1; nxhhs = 2*(nxhh/2); v_m = _mm_set_ps(1.0f,-1.0f,1.0f,-1.0f); v_n = _mm_set_ps(-1.0f,1.0f,-1.0f,1.0f); v_t1 = _mm_setzero_ps(); v_t2 = _mm_setzero_ps(); v_t3 = _mm_setzero_ps(); if (isign > 0) goto L70; /* inverse fourier transform */ nrxb = nxhy/nxh; nrx = nxy/nxh; #pragma omp parallel for \ private(i,j,k,l,ns,ns2,nss,km,kmr,k1,k2,j1,joff,it,ani,t1,t2,t3,v_t1, \ v_t2,v_t3,v_t4) for (i = nyi-1; i < nyt; i++) { joff = nxhd*i; /* bit-reverse array elements in x */ for (j = 0; j < nxh; j++) { j1 = (mixup[j] - 1)/nrxb; if (j < j1) { /* t1 = f[j1+joff]; */ v_t1 = _mm_loadl_pi(v_t1,(__m64 *)&f[j1+joff]); /* f[j1+joff] = f[j+joff]; */ v_t2 = _mm_loadl_pi(v_t2,(__m64 *)&f[j+joff]); _mm_storel_pi((__m64 *)&f[j1+joff],v_t2); /* f[j+joff] = t1; */ _mm_storel_pi((__m64 *)&f[j+joff],v_t1); } } /* then transform in x */ ns = 1; for (l = 0; l < indx1; l++) { ns2 = ns + ns; km = nxhh/ns; kmr = km*nrx; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; nss = 2*(ns/2); /* vector loop over elements in blocks of 2 */ for (j = 0; j < nss; j+=2) { /* t1 = sct[kmr*j]; */ v_t1 = _mm_loadl_pi(v_t1,(__m64 *)&sct[kmr*j]); v_t1 = _mm_loadh_pi(v_t1,(__m64 *)&sct[kmr*j+kmr]); /* t2 = t1*f[j+k2+joff]; */ v_t2 = _mm_load_ps((float *)&f[j+k2+joff]); v_t3 = _mm_mul_ps(v_t2,_mm_shuffle_ps(v_t1,v_t1,160)); v_t2 = _mm_shuffle_ps(v_t2,v_t2,177); v_t2 = _mm_mul_ps(v_t2,_mm_shuffle_ps(v_t1,v_t1,245)); v_t2 = _mm_add_ps(v_t3,_mm_mul_ps(v_t2,v_m)); /* f[j+k2+joff] = f[j+k1+joff] - t2; */ v_t3 = _mm_load_ps((float *)&f[j+k1+joff]); _mm_store_ps((float *)&f[j+k2+joff],_mm_sub_ps(v_t3,v_t2)); /* f[j+k1+joff] += t2; */ _mm_store_ps((float *)&f[j+k1+joff],_mm_add_ps(v_t3,v_t2)); } /* loop over remaining elements */ for (j = nss; j < ns; j++) { t1 = sct[kmr*j]; t2 = t1*f[j+k2+joff]; f[j+k2+joff] = f[j+k1+joff] - t2; f[j+k1+joff] += t2; } } ns = ns2; } /* unscramble coefficients and normalize */ kmr = nxy/nx; ani = 0.5/(((float) nx)*((float) ny)); v_ani = _mm_set1_ps(ani); /* vector loop over elements in blocks of 2 */ for (j = 0; j < nxhhs; j+=2) { /* t3 = cimagf(sct[kmr*j]) - crealf(sct[kmr*j])*_Complex_I; */ v_t3 = _mm_loadl_pi(v_t3,(__m64 *)&sct[kmr*j]); v_t3 = _mm_loadh_pi(v_t3,(__m64 *)&sct[kmr*j+kmr]); v_t3 = _mm_mul_ps(v_t3,v_m); v_t3 = _mm_shuffle_ps(v_t3,v_t3,177); /* t2 = conjf(f[nxh-j+joff]); */ if (j==0) { v_t2 = _mm_setzero_ps(); } else { v_t2 = _mm_loadl_pi(v_t2,(__m64 *)&f[nxh-j+joff]); } v_t2 = _mm_loadh_pi(v_t2,(__m64 *)&f[nxh-j-1+joff]); v_t2 = _mm_mul_ps(v_t2,v_n); /* t1 = f[j+joff] + t2; */ v_t4 = _mm_load_ps((float *)&f[j+joff]); v_t1 = _mm_add_ps(v_t4,v_t2); /* t2 = (f[j+joff] - t2)*t3; */ v_t2 = _mm_sub_ps(v_t4,v_t2); v_t4 = _mm_mul_ps(v_t2,_mm_shuffle_ps(v_t3,v_t3,160)); v_t2 = _mm_shuffle_ps(v_t2,v_t2,177); v_t2 = _mm_mul_ps(v_t2,_mm_shuffle_ps(v_t3,v_t3,245)); v_t2 = _mm_add_ps(v_t4,_mm_mul_ps(v_t2,v_m)); /* f[j+joff] = ani*(t1 + t2); */ /* f[nxh-j+joff] = ani*conjf(t1 - t2); */ v_t3 = _mm_mul_ps(v_ani,_mm_add_ps(v_t1,v_t2)); v_t4 = _mm_mul_ps(v_ani,_mm_mul_ps(_mm_sub_ps(v_t1,v_t2),v_n)); if (j==0) { _mm_storeh_pi((__m64 *)&f[joff+1],v_t3); _mm_storeh_pi((__m64 *)&f[nxh-1+joff],v_t4); } else { _mm_store_ps((float *)&f[j+joff],v_t3); _mm_storel_pi((__m64 *)&f[nxh-j+joff],v_t4); _mm_storeh_pi((__m64 *)&f[nxh-j-1+joff],v_t4); } } /* loop over remaining elements */ it = 1 > nxhhs ? 1 : nxhhs; for (j = it; j < nxhh; j++) { t3 = cimagf(sct[kmr*j]) - crealf(sct[kmr*j])*_Complex_I; t2 = conjf(f[nxh-j+joff]); t1 = f[j+joff] + t2; t2 = (f[j+joff] - t2)*t3; f[j+joff] = ani*(t1 + t2); f[nxh-j+joff] = ani*conjf(t1 - t2); } ani = 2.0*ani; f[nxhh+joff] = ani*conjf(f[nxhh+joff]); f[joff] = ani*((crealf(f[joff]) + cimagf(f[joff])) + (crealf(f[joff]) - cimagf(f[joff]))*_Complex_I); } return; /* forward fourier transform */ L70: nrxb = nxhy/nxh; nrx = nxy/nxh; #pragma omp parallel for \ private(i,j,k,l,ns,ns2,nss,km,kmr,k1,k2,j1,joff,it,t1,t2,t3,v_t1,v_t2, \ v_t3,v_t4) for (i = nyi-1; i < nyt; i++) { joff = nxhd*i; /* scramble coefficients */ kmr = nxy/nx; /* vector loop over elements in blocks of 2 */ for (j = 0; j < nxhhs; j+=2) { /* t3 = cimagf(sct[kmr*j]) + crealf(sct[kmr*j])*_Complex_I; */ v_t3 = _mm_loadl_pi(v_t3,(__m64 *)&sct[kmr*j]); v_t3 = _mm_loadh_pi(v_t3,(__m64 *)&sct[kmr*j+kmr]); v_t3 = _mm_shuffle_ps(v_t3,v_t3,177); /* t2 = conjf(f[nxh-j+joff]); */ if (j==0) { v_t2 = _mm_setzero_ps(); } else { v_t2 = _mm_loadl_pi(v_t2,(__m64 *)&f[nxh-j+joff]); } v_t2 = _mm_loadh_pi(v_t2,(__m64 *)&f[nxh-j-1+joff]); v_t2 = _mm_mul_ps(v_t2,v_n); /* t1 = f[j+joff] + t2; */ v_t4 = _mm_load_ps((float *)&f[j+joff]); v_t1 = _mm_add_ps(v_t4,v_t2); /* t2 = (f[j+joff] - t2)*t3; */ v_t2 = _mm_sub_ps(v_t4,v_t2); v_t4 = _mm_mul_ps(v_t2,_mm_shuffle_ps(v_t3,v_t3,160)); v_t2 = _mm_shuffle_ps(v_t2,v_t2,177); v_t2 = _mm_mul_ps(v_t2,_mm_shuffle_ps(v_t3,v_t3,245)); v_t2 = _mm_add_ps(v_t4,_mm_mul_ps(v_t2,v_m)); /* f[j+joff] = t1 + t2; */ /* f[nxh-j+joff] = conjf(t1 - t2); */ v_t3 = _mm_add_ps(v_t1,v_t2); v_t4 = _mm_mul_ps(_mm_sub_ps(v_t1,v_t2),v_n); if (j==0) { _mm_storeh_pi((__m64 *)&f[joff+1],v_t3); _mm_storeh_pi((__m64 *)&f[nxh-1+joff],v_t4); } else { _mm_store_ps((float *)&f[j+joff],v_t3); _mm_storel_pi((__m64 *)&f[nxh-j+joff],v_t4); _mm_storeh_pi((__m64 *)&f[nxh-j-1+joff],v_t4); } } /* loop over remaining elements */ it = 1 > nxhhs ? 1 : nxhhs; for (j = it; j < nxhh; j++) { t3 = cimagf(sct[kmr*j]) + crealf(sct[kmr*j])*_Complex_I; t2 = conjf(f[nxh-j+joff]); t1 = f[j+joff] + t2; t2 = (f[j+joff] - t2)*t3; f[j+joff] = t1 + t2; f[nxh-j+joff] = conjf(t1 - t2); } f[nxhh+joff] = 2.0*conjf(f[nxhh+joff]); f[joff] = (crealf(f[joff]) + cimagf(f[joff])) + (crealf(f[joff]) - cimagf(f[joff]))*_Complex_I; /* bit-reverse array elements in x */ for (j = 0; j < nxh; j++) { j1 = (mixup[j] - 1)/nrxb; if (j < j1) { /* t1 = f[j1+joff]; */ v_t1 = _mm_loadl_pi(v_t1,(__m64 *)&f[j1+joff]); /* f[j1+joff] = f[j+joff]; */ v_t2 = _mm_loadl_pi(v_t2,(__m64 *)&f[j+joff]); _mm_storel_pi((__m64 *)&f[j1+joff],v_t2); /* f[j+joff] = t1; */ _mm_storel_pi((__m64 *)&f[j+joff],v_t1); } } /* then transform in x */ ns = 1; for (l = 0; l < indx1; l++) { ns2 = ns + ns; km = nxhh/ns; kmr = km*nrx; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; nss = 2*(ns/2); /* vector loop over elements in blocks of 2 */ for (j = 0; j < nss; j+=2) { /* t1 = conjf(sct[kmr*j]); */ v_t1 = _mm_loadl_pi(v_t1,(__m64 *)&sct[kmr*j]); v_t1 = _mm_loadh_pi(v_t1,(__m64 *)&sct[kmr*j+kmr]); v_t1 = _mm_mul_ps(v_t1,v_n); /* t2 = t1*f[j+k2+joff]; */ v_t2 = _mm_load_ps((float *)&f[j+k2+joff]); v_t3 = _mm_mul_ps(v_t2,_mm_shuffle_ps(v_t1,v_t1,160)); v_t2 = _mm_shuffle_ps(v_t2,v_t2,177); v_t2 = _mm_mul_ps(v_t2,_mm_shuffle_ps(v_t1,v_t1,245)); v_t2 = _mm_add_ps(v_t3,_mm_mul_ps(v_t2,v_m)); /* f[j+k2+joff] = f[j+k1+joff] - t2; */ v_t3 = _mm_load_ps((float *)&f[j+k1+joff]); _mm_store_ps((float *)&f[j+k2+joff],_mm_sub_ps(v_t3,v_t2)); /* f[j+k1+joff] += t2; */ _mm_store_ps((float *)&f[j+k1+joff],_mm_add_ps(v_t3,v_t2)); } /* loop over remaining elements */ for (j = nss; j < ns; j++) { t1 = conjf(sct[kmr*j]); t2 = t1*f[j+k2+joff]; f[j+k2+joff] = f[j+k1+joff] - t2; f[j+k1+joff] += t2; } } ns = ns2; } } return; } /*--------------------------------------------------------------------*/ void csse2fft2rmxy(float complex f[], int isign, int mixup[], float complex sct[], int indx, int indy, int nxi, int nxp, int nxhd, int nyd, int nxhyd, int nxyhd) { /* this subroutine performs the y part of a two dimensional real to complex fast fourier transform and its inverse, for a subset of x, using complex arithmetic, with OpenMP for isign = (-1,1), input: all, output: f for isign = -1, approximate flop count: N*(5*log2(N) + 19/2) for isign = 1, approximate flop count: N*(5*log2(N) + 15/2) where N = (nx/2)*ny indx/indy = exponent which determines length in x/y direction, where nx=2**indx, ny=2**indy if isign = -1, an inverse fourier transform in y is performed f[m][n] = sum(f[k][j]*exp(-sqrt(-1)*2pi*m*k/ny)) if isign = 1, a forward fourier transform in y is performed f[k][j] = sum(f[m][n]*exp(sqrt(-1)*2pi*m*k/ny)) mixup = array of bit reversed addresses sct = sine/cosine table nxi = initial x index used nxp = number of x indices used nxhd = first dimension of f >= nx/2 nyd = second dimension of f >= ny nxhyd = maximum of (nx/2,ny) nxyhd = maximum of (nx,ny)/2 fourier coefficients are stored as follows: f[k][j] = real, imaginary part of mode j,k, where 0 <= j < nx/2 and 0 <= k < ny, except for f[k][1] = real, imaginary part of mode nx/2,k, where ny/2+1 <= k < ny, and imag(f[0][0]) = real part of mode nx/2,0 and imag(f[0][ny/2]) = real part of mode nx/2,ny/2 written by viktor k. decyk, ucla requires SSE2, f needs to be 16 byte aligned nxhd needs to be a multiple of 2, and nxi needs to be odd local data */ int indx1, indx1y, nx, ny, nyh, nxy, nxhy, nxt; int nry, i, j, k, l, j1, j2, k1, k2, ns, ns2, km, kmr, nryb, koff; int nss; float complex t1, t2; __m128 v_m, v_n, v_t1, v_t2, v_t3; if (isign==0) return; indx1 = indx - 1; indx1y = indx1 > indy ? indx1 : indy; nx = 1L<<indx; ny = 1L<<indy; nyh = ny/2; nxy = nx > ny ? nx : ny; nxhy = 1L<<indx1y; nxt = nxi + nxp - 1; v_m = _mm_set_ps(1.0f,-1.0f,1.0f,-1.0f); v_n = _mm_set_ps(-1.0f,1.0f,-1.0f,1.0f); if (isign > 0) goto L70; /* inverse fourier transform */ nryb = nxhy/ny; nry = nxy/ny; #pragma omp parallel for \ private(i,j,k,l,ns,ns2,nss,km,kmr,k1,k2,j1,j2,koff,t1,t2,v_t1,v_t2,v_t3) for (i = nxi-1; i < nxt; i++) { /* bit-reverse array elements in y */ for (k = 0; k < ny; k++) { koff = nxhd*k; k1 = (mixup[k] - 1)/nryb; if (k < k1) { k1 = nxhd*k1; /* t1 = f[i+k1]; */ v_t1 = _mm_loadl_pi(v_t1,(__m64 *)&f[i+k1]); /* f[i+k1] = f[i+koff]; */ v_t2 = _mm_loadl_pi(v_t2,(__m64 *)&f[i+koff]); _mm_storel_pi((__m64 *)&f[i+k1],v_t2); /* f[i+koff] = t1; */ _mm_storel_pi((__m64 *)&f[i+koff],v_t1); } } /* then transform in y */ ns = 1; for (l = 0; l < indy; l++) { ns2 = ns + ns; km = nyh/ns; kmr = km*nry; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; nss = 2*(ns/2); /* vector loop over elements in blocks of 2 */ for (j = 0; j < nss; j+=2) { j1 = nxhd*(j + k1); j2 = nxhd*(j + k2); /* t1 = sct[kmr*j]; */ v_t1 = _mm_loadl_pi(v_t1,(__m64 *)&sct[kmr*j]); v_t1 = _mm_loadh_pi(v_t1,(__m64 *)&sct[kmr*j+kmr]); /* t2 = t1*f[i+j2]; */ v_t2 = _mm_loadl_pi(v_t2,(__m64 *)&f[i+j2]); v_t2 = _mm_loadh_pi(v_t2,(__m64 *)&f[i+j2+nxhd]); v_t3 = _mm_mul_ps(v_t2,_mm_shuffle_ps(v_t1,v_t1,160)); v_t2 = _mm_shuffle_ps(v_t2,v_t2,177); v_t2 = _mm_mul_ps(v_t2,_mm_shuffle_ps(v_t1,v_t1,245)); v_t2 = _mm_add_ps(v_t3,_mm_mul_ps(v_t2,v_m)); /* f[i+j2] = f[i+j1] - t2; */ v_t3 = _mm_loadl_pi(v_t3,(__m64 *)&f[i+j1]); v_t3 = _mm_loadh_pi(v_t3,(__m64 *)&f[i+j1+nxhd]); v_t1 = _mm_sub_ps(v_t3,v_t2); _mm_storel_pi((__m64 *)&f[i+j2],v_t1); _mm_storeh_pi((__m64 *)&f[i+j2+nxhd],v_t1); /* f[i+j1] += t2; */ v_t1 = _mm_add_ps(v_t3,v_t2); _mm_storel_pi((__m64 *)&f[i+j1],v_t1); _mm_storeh_pi((__m64 *)&f[i+j1+nxhd],v_t1); } /* loop over remaining elements */ for (j = nss; j < ns; j++) { j1 = nxhd*(j + k1); j2 = nxhd*(j + k2); t1 = sct[kmr*j]; t2 = t1*f[i+j2]; f[i+j2] = f[i+j1] - t2; f[i+j1] += t2; } } ns = ns2; } } /* unscramble modes kx = 0, nx/2 */ if (nxi==1) { for (k = 1; k < nyh; k++) { koff = nxhd*k; k1 = nxhd*ny - koff; t1 = f[k1]; f[k1] = 0.5*(cimagf(f[koff] + t1) + crealf(f[koff] - t1)*_Complex_I); f[koff] = 0.5*(crealf(f[koff] + t1) + cimagf(f[koff] - t1)*_Complex_I); } } return; /* forward fourier transform */ L70: nryb = nxhy/ny; nry = nxy/ny; /* scramble modes kx = 0, nx/2 */ if (nxi==1) { for (k = 1; k < nyh; k++) { koff = nxhd*k; k1 = nxhd*ny - koff; t1 = cimagf(f[k1]) + crealf(f[k1])*_Complex_I; f[k1] = conjf(f[koff] - t1); f[koff] += t1; } } #pragma omp parallel for \ private(i,j,k,l,ns,ns2,nss,km,kmr,k1,k2,j1,j2,koff,t1,t2,v_t1,v_t2,v_t3) for (i = nxi-1; i < nxt; i++) { /* bit-reverse array elements in y */ for (k = 0; k < ny; k++) { koff = nxhd*k; k1 = (mixup[k] - 1)/nryb; if (k < k1) { k1 = nxhd*k1; /* t1 = f[i+k1]; */ v_t1 = _mm_loadl_pi(v_t1,(__m64 *)&f[i+k1]); /* f[i+k1] = f[i+koff]; */ v_t2 = _mm_loadl_pi(v_t2,(__m64 *)&f[i+koff]); _mm_storel_pi((__m64 *)&f[i+k1],v_t2); /* f[i+koff] = t1; */ _mm_storel_pi((__m64 *)&f[i+koff],v_t1); } } /* then transform in y */ ns = 1; for (l = 0; l < indy; l++) { ns2 = ns + ns; km = nyh/ns; kmr = km*nry; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; nss = 2*(ns/2); /* vector loop over elements in blocks of 2 */ for (j = 0; j < nss; j+=2) { j1 = nxhd*(j + k1); j2 = nxhd*(j + k2); /* t1 = conjf(sct[kmr*j]); */ v_t1 = _mm_loadl_pi(v_t1,(__m64 *)&sct[kmr*j]); v_t1 = _mm_loadh_pi(v_t1,(__m64 *)&sct[kmr*j+kmr]); v_t1 = _mm_mul_ps(v_t1,v_n); /* t2 = t1*f[i+j2]; */ v_t2 = _mm_loadl_pi(v_t2,(__m64 *)&f[i+j2]); v_t2 = _mm_loadh_pi(v_t2,(__m64 *)&f[i+j2+nxhd]); v_t3 = _mm_mul_ps(v_t2,_mm_shuffle_ps(v_t1,v_t1,160)); v_t2 = _mm_shuffle_ps(v_t2,v_t2,177); v_t2 = _mm_mul_ps(v_t2,_mm_shuffle_ps(v_t1,v_t1,245)); v_t2 = _mm_add_ps(v_t3,_mm_mul_ps(v_t2,v_m)); /* f[i+j2] = f[i+j1] - t2; */ v_t3 = _mm_loadl_pi(v_t3,(__m64 *)&f[i+j1]); v_t3 = _mm_loadh_pi(v_t3,(__m64 *)&f[i+j1+nxhd]); v_t1 = _mm_sub_ps(v_t3,v_t2); _mm_storel_pi((__m64 *)&f[i+j2],v_t1); _mm_storeh_pi((__m64 *)&f[i+j2+nxhd],v_t1); /* f[i+j1] += t2; */ v_t1 = _mm_add_ps(v_t3,v_t2); _mm_storel_pi((__m64 *)&f[i+j1],v_t1); _mm_storeh_pi((__m64 *)&f[i+j1+nxhd],v_t1); } /* loop over remaining elements */ for (j = nss; j < ns; j++) { j1 = nxhd*(j + k1); j2 = nxhd*(j + k2); t1 = conjf(sct[kmr*j]); t2 = t1*f[i+j2]; f[i+j2] = f[i+j1] - t2; f[i+j1] += t2; } } ns = ns2; } } return; } /*--------------------------------------------------------------------*/ void csse2fft2rm2x(float complex f[], int isign, int mixup[], float complex sct[], int indx, int indy, int nyi, int nyp, int nxhd, int nyd, int nxhyd, int nxyhd) { /* this subroutine performs the x part of 2 two dimensional real to complex fast fourier transforms, and their inverses, for a subset of y, using complex arithmetic, with OpenMP for isign = (-1,1), input: all, output: f for isign = -1, approximate flop count: N*(5*log2(N) + 19/2) for isign = 1, approximate flop count: N*(5*log2(N) + 15/2) where N = (nx/2)*ny indx/indy = exponent which determines length in x/y direction, where nx=2**indx, ny=2**indy if isign = -1, two inverse fourier transforms in x are performed f[m][n][0:1] = (1/nx*ny)*sum(f[k][j][0:1]*exp(-sqrt(-1)*2pi*n*j/nx)) if isign = 1, two forward fourier transforms in x are performed f[k][j][0:1] = sum(f[m][n][0:1]*exp(sqrt(-1)*2pi*n*j/nx)) mixup = array of bit reversed addresses sct = sine/cosine table nyi = initial y index used nyp = number of y indices used nxhd = second dimension of f >= nx/2 nyd = third dimension of f >= ny nxhyd = maximum of (nx/2,ny) nxyhd = maximum of (nx,ny)/2 fourier coefficients are stored as follows: f[k][j][0:1] = real, imaginary part of mode j,k, where 0 <= j < nx/2 and 0 <= k < ny, except for f[k][1][0:1] = real, imaginary part of mode nx/2,k, where ny/2+1 <= k < ny, and imag(f[0][0][0:1]) = real part of mode nx/2,0 and imag(f[0][ny/2][0:1]) = real part of mode nx/2,ny/2 written by viktor k. decyk, ucla requires SSE2, f needs to be 16 byte aligned local data */ int indx1, indx1y, nx, nxh, nxhh, ny, nxy, nxhy, nyt; int nrx, i, j, k, l, jj, j1, k1, k2, ns, ns2, km, kmr, joff; int nrxb; float ani; /* float complex t1, t2, t3; */ __m128 v_m, v_n, v_t1, v_t2, v_t3, v_t4, v_ani; if (isign==0) return; indx1 = indx - 1; indx1y = indx1 > indy ? indx1 : indy; nx = 1L<<indx; nxh = nx/2; nxhh = nx/4; ny = 1L<<indy; nxy = nx > ny ? nx : ny; nxhy = 1L<<indx1y; nyt = nyi + nyp - 1; v_m = _mm_set_ps(1.0f,-1.0f,1.0f,-1.0f); v_n = _mm_set_ps(-1.0f,1.0f,-1.0f,1.0f); v_t1 = _mm_setzero_ps(); v_t3 = _mm_setzero_ps(); if (isign > 0) goto L100; /* inverse fourier transform */ nrxb = nxhy/nxh; nrx = nxy/nxh; #pragma omp parallel for \ private(i,j,k,l,ns,ns2,km,kmr,k1,k2,jj,j1,joff,ani,v_t1,v_t2,v_t3,v_t4, \ v_ani) for (i = nyi-1; i < nyt; i++) { joff = 2*nxhd*i; /* swap complex components */ for (j = 0; j < nxh; j++) { v_t1 = _mm_load_ps((float *)&f[2*j+joff]); v_t1 = _mm_shuffle_ps(v_t1,v_t1,216); _mm_store_ps((float *)&f[2*j+joff],v_t1); } /* bit-reverse array elements in x */ for (j = 0; j < nxh; j++) { j1 = (mixup[j] - 1)/nrxb; if (j < j1) { /* t1 = f[2*j1+joff]; */ /* t2 = f[1+2*j1+joff]; */ v_t1 = _mm_load_ps((float *)&f[2*j1+joff]); /* f[2*j1+joff] = f[2*j+joff]; */ /* f[1+2*j1+joff] = f[1+2*j+joff]; */ v_t2 = _mm_load_ps((float *)&f[2*j+joff]); _mm_store_ps((float *)&f[2*j1+joff],v_t2); /* f[2*j+joff] = t1; */ /* f[1+2*j+joff] = t2; */ _mm_store_ps((float *)&f[2*j+joff],v_t1); } } /* then transform in x */ ns = 1; for (l = 0; l < indx1; l++) { ns2 = ns + ns; km = nxhh/ns; kmr = km*nrx; for (k = 0; k < km; k++) { k1 = 2*ns2*k; k2 = k1 + 2*ns; for (j = 0; j < ns; j++) { /* t1 = sct[kmr*j]; */ v_t1 = _mm_loadl_pi(v_t1,(__m64 *)&sct[kmr*j]); v_t1 = _mm_movelh_ps(v_t1,v_t1); /* t2 = t1*f[2*j+k2+joff]; */ /* t3 = t1*f[1+2*j+k2+joff]; */ v_t2 = _mm_load_ps((float *)&f[2*j+k2+joff]); v_t3 = _mm_mul_ps(v_t2,_mm_shuffle_ps(v_t1,v_t1,160)); v_t2 = _mm_shuffle_ps(v_t2,v_t2,177); v_t2 = _mm_mul_ps(v_t2,_mm_shuffle_ps(v_t1,v_t1,245)); v_t2 = _mm_add_ps(v_t3,_mm_mul_ps(v_t2,v_m)); /* f[2*j+k2+joff] = f[2*j+k1+joff] - t2; */ /* f[1+2*j+k2+joff] = f[1+2*j+k1+joff] - t3; */ v_t3 = _mm_load_ps((float *)&f[2*j+k1+joff]); v_t4 = _mm_sub_ps(v_t3,v_t2); _mm_store_ps((float *)&f[2*j+k2+joff],v_t4); /* f[2*j+k1+joff] += t2; */ /* f[1+2*j+k1+joff] += t3; */ v_t2 = _mm_add_ps(v_t3,v_t2); _mm_store_ps((float *)&f[2*j+k1+joff],v_t2); } } ns = ns2; } /* unscramble coefficients and normalize */ kmr = nxy/nx; ani = 0.5/(((float) nx)*((float) ny)); v_ani = _mm_set1_ps(ani); for (j = 1; j < nxhh; j++) { /* t3 = cimagf(sct[kmr*j]) - crealf(sct[kmr*j])*_Complex_I; */ v_t3 = _mm_loadl_pi(v_t3,(__m64 *)&sct[kmr*j]); v_t3 = _mm_movelh_ps(v_t3,v_t3); v_t3 = _mm_mul_ps(v_t3,v_m); v_t3 = _mm_shuffle_ps(v_t3,v_t3,177); /* t2 = conjf(f[jj+2*(nxh-j)+joff]); */ v_t2 = _mm_load_ps((float *)&f[2*(nxh-j)+joff]); v_t2 = _mm_mul_ps(v_t2,v_n); /* t1 = f[jj+2*j+joff] + t2; */ v_t4 = _mm_load_ps((float *)&f[2*j+joff]); v_t1 = _mm_add_ps(v_t4,v_t2); /* t2 = (f[jj+2*j+joff] - t2)*t3; */ v_t2 = _mm_sub_ps(v_t4,v_t2); v_t4 = _mm_mul_ps(v_t2,_mm_shuffle_ps(v_t3,v_t3,160)); v_t2 = _mm_shuffle_ps(v_t2,v_t2,177); v_t2 = _mm_mul_ps(v_t2,_mm_shuffle_ps(v_t3,v_t3,245)); v_t2 = _mm_add_ps(v_t4,_mm_mul_ps(v_t2,v_m)); /* f[jj+2*j+joff] = ani*(t1 + t2); */ v_t3 = _mm_mul_ps(v_ani,_mm_add_ps(v_t1,v_t2)); _mm_store_ps((float *)&f[2*j+joff],v_t3); /* f[jj+2*(nxh-j)+joff] = ani*conjf(t1 - t2); */ v_t4 = _mm_mul_ps(v_ani,_mm_mul_ps(_mm_sub_ps(v_t1,v_t2),v_n)); _mm_store_ps((float *)&f[2*(nxh-j)+joff],v_t4); } ani = 2.0*ani; for (jj = 0; jj < 2; jj++) { f[jj+2*nxhh+joff] = ani*conjf(f[jj+2*nxhh+joff]); f[jj+joff] = ani*((crealf(f[jj+joff]) + cimagf(f[jj+joff])) + (crealf(f[jj+joff]) - cimagf(f[jj+joff]))*_Complex_I); } } return; /* forward fourier transform */ L100: nrxb = nxhy/nxh; nrx = nxy/nxh; #pragma omp parallel for \ private(i,j,k,l,ns,ns2,km,kmr,k1,k2,jj,j1,joff,v_t1,v_t2,v_t3,v_t4) for (i = nyi-1; i < nyt; i++) { joff = 2*nxhd*i; /* scramble coefficients */ kmr = nxy/nx; for (j = 1; j < nxhh; j++) { /* t3 = cimagf(sct[kmr*j]) + crealf(sct[kmr*j])*_Complex_I; */ v_t3 = _mm_loadl_pi(v_t3,(__m64 *)&sct[kmr*j]); v_t3 = _mm_movelh_ps(v_t3,v_t3); v_t3 = _mm_shuffle_ps(v_t3,v_t3,177); /* t2 = conjf(f[jj+2*(nxh-j)+joff]); */ v_t2 = _mm_load_ps((float *)&f[2*(nxh-j)+joff]); v_t2 = _mm_mul_ps(v_t2,v_n); /* t1 = f[jj+2*j+joff] + t2; */ v_t4 = _mm_load_ps((float *)&f[2*j+joff]); v_t1 = _mm_add_ps(v_t4,v_t2); /* t2 = (f[jj+2*j+joff] - t2)*t3; */ v_t2 = _mm_sub_ps(v_t4,v_t2); v_t4 = _mm_mul_ps(v_t2,_mm_shuffle_ps(v_t3,v_t3,160)); v_t2 = _mm_shuffle_ps(v_t2,v_t2,177); v_t2 = _mm_mul_ps(v_t2,_mm_shuffle_ps(v_t3,v_t3,245)); v_t2 = _mm_add_ps(v_t4,_mm_mul_ps(v_t2,v_m)); /* f[jj+2*j+joff] = t1 + t2; */ v_t3 = _mm_add_ps(v_t1,v_t2); _mm_store_ps((float *)&f[2*j+joff],v_t3); /* f[jj+2*(nxh-j)+joff] = conjf(t1 - t2); */ v_t4 = _mm_mul_ps(_mm_sub_ps(v_t1,v_t2),v_n); _mm_store_ps((float *)&f[2*(nxh-j)+joff],v_t4); } for (jj = 0; jj < 2; jj++) { f[jj+2*nxhh+joff] = 2.0*conjf(f[jj+2*nxhh+joff]); f[jj+joff] = (crealf(f[jj+joff]) + cimagf(f[jj+joff])) + (crealf(f[jj+joff]) - cimagf(f[jj+joff]))*_Complex_I; } /* bit-reverse array elements in x */ for (j = 0; j < nxh; j++) { j1 = (mixup[j] - 1)/nrxb; if (j < j1) { /* t1 = f[2*j1+joff]; */ /* t2 = f[1+2*j1+joff]; */ v_t1 = _mm_load_ps((float *)&f[2*j1+joff]); /* f[2*j1+joff] = f[2*j+joff]; */ /* f[1+2*j1+joff] = f[1+2*j+joff]; */ v_t2 = _mm_load_ps((float *)&f[2*j+joff]); _mm_store_ps((float *)&f[2*j1+joff],v_t2); /* f[2*j+joff] = t1; */ /* f[1+2*j+joff] = t2; */ _mm_store_ps((float *)&f[2*j+joff],v_t1); } } /* then transform in x */ ns = 1; for (l = 0; l < indx1; l++) { ns2 = ns + ns; km = nxhh/ns; kmr = km*nrx; for (k = 0; k < km; k++) { k1 = 2*ns2*k; k2 = k1 + 2*ns; for (j = 0; j < ns; j++) { /* t1 = conjf(sct[kmr*j]); */ v_t1 = _mm_loadl_pi(v_t1,(__m64 *)&sct[kmr*j]); v_t1 = _mm_movelh_ps(v_t1,v_t1); v_t1 = _mm_mul_ps(v_t1,v_n); /* t2 = t1*f[2*j+k2+joff]; */ /* t3 = t1*f[1+2*j+k2+joff]; */ v_t2 = _mm_load_ps((float *)&f[2*j+k2+joff]); v_t3 = _mm_mul_ps(v_t2,_mm_shuffle_ps(v_t1,v_t1,160)); v_t2 = _mm_shuffle_ps(v_t2,v_t2,177); v_t2 = _mm_mul_ps(v_t2,_mm_shuffle_ps(v_t1,v_t1,245)); v_t2 = _mm_add_ps(v_t3,_mm_mul_ps(v_t2,v_m)); /* f[2*j+k2+joff] = f[2*j+k1+joff] - t2; */ /* f[1+2*j+k2+joff] = f[1+2*j+k1+joff] - t3; */ v_t3 = _mm_load_ps((float *)&f[2*j+k1+joff]); v_t4 = _mm_sub_ps(v_t3,v_t2); _mm_store_ps((float *)&f[2*j+k2+joff],v_t4); /* f[2*j+k1+joff] += t2; */ /* f[1+2*j+k1+joff] += t3; */ v_t2 = _mm_add_ps(v_t3,v_t2); _mm_store_ps((float *)&f[2*j+k1+joff],v_t2); } } ns = ns2; } /* swap complex components */ for (j = 0; j < nxh; j++) { v_t1 = _mm_load_ps((float *)&f[2*j+joff]); v_t1 = _mm_shuffle_ps(v_t1,v_t1,216); _mm_store_ps((float *)&f[2*j+joff],v_t1); } } return; } /*--------------------------------------------------------------------*/ void csse2fft2rm2y(float complex f[], int isign, int mixup[], float complex sct[], int indx, int indy, int nxi, int nxp, int nxhd, int nyd, int nxhyd, int nxyhd) { /* this subroutine performs the y part of 2 two dimensional real to complex fast fourier transforms, and their inverses, for a subset of x, using complex arithmetic, with OpenMP for isign = (-1,1), input: all, output: f for isign = -1, approximate flop count: N*(5*log2(N) + 19/2) for isign = 1, approximate flop count: N*(5*log2(N) + 15/2) where N = (nx/2)*ny indx/indy = exponent which determines length in x/y direction, where nx=2**indx, ny=2**indy if isign = -1, two inverse fourier transforms in y are performed f[m][n][0:1] = *sum(f[k][j][0:1]*exp(-sqrt(-1)*2pi*m*k/ny)) if isign = 1, two forward fourier transforms in y are performed f[k][j][0:1] = sum(f[m][n][0:1]*exp(sqrt(-1)*2pi*n*j/nx)) mixup = array of bit reversed addresses sct = sine/cosine table nxi = initial x index used nxp = number of x indices used nxhd = second dimension of f >= nx/2 nyd = third dimension of f >= ny nxhyd = maximum of (nx/2,ny) nxyhd = maximum of (nx,ny)/2 fourier coefficients are stored as follows: f[k][j][0:1] = real, imaginary part of mode j,k, where 0 <= j < nx/2 and 0 <= k < ny, except for f[k][1][0:1] = real, imaginary part of mode nx/2,k, where ny/2+1 <= k < ny, and imag(f[0][0][0:1]) = real part of mode nx/2,0 and imag(f[0][ny/2][0:1]) = real part of mode nx/2,ny/2 written by viktor k. decyk, ucla requires SSE2, f needs to be 16 byte aligned local data */ int indx1, indx1y, nx, ny, nyh, nxy, nxhy, nxt; int nry, i, j, k, l, jj, j1, j2, k1, k2, ns, ns2, km, kmr, koff; int nryb; float complex t1; __m128 v_m, v_n, v_t1, v_t2, v_t3, v_t4; if (isign==0) return; indx1 = indx - 1; indx1y = indx1 > indy ? indx1 : indy; nx = 1L<<indx; ny = 1L<<indy; nyh = ny/2; nxy = nx > ny ? nx : ny; nxhy = 1L<<indx1y; nxt = nxi + nxp - 1; v_m = _mm_set_ps(1.0f,-1.0f,1.0f,-1.0f); v_n = _mm_set_ps(-1.0f,1.0f,-1.0f,1.0f); v_t1 = _mm_setzero_ps(); if (isign > 0) goto L80; /* inverse fourier transform */ nryb = nxhy/ny; nry = nxy/ny; #pragma omp parallel for \ private(i,j,k,l,ns,ns2,km,kmr,k1,k2,jj,j1,j2,koff,v_t1,v_t2,v_t3,v_t4) for (i = nxi-1; i < nxt; i++) { /* bit-reverse array elements in y */ for (k = 0; k < ny; k++) { koff = 2*nxhd*k; k1 = (mixup[k] - 1)/nryb; if (k < k1) { k1 = 2*nxhd*k1; /* t1 = f[2*i+k1]; */ /* t2 = f[1+2*i+k1]; */ v_t1 = _mm_load_ps((float *)&f[2*i+k1]); /* f[2*i+k1] = f[2*i+koff]; */ /* f[1+2*i+k1] = f[1+2*i+koff]; */ v_t2 = _mm_load_ps((float *)&f[2*i+koff]); _mm_store_ps((float *)&f[2*i+k1],v_t2); /* f[2*i+koff] = t1; */ /* f[1+2*i+koff] = t2; */ _mm_store_ps((float *)&f[2*i+koff],v_t1); } } /* then transform in y */ ns = 1; for (l = 0; l < indy; l++) { ns2 = ns + ns; km = nyh/ns; kmr = km*nry; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; for (j = 0; j < ns; j++) { j1 = 2*nxhd*(j + k1); j2 = 2*nxhd*(j + k2); /* t1 = sct[kmr*j]; */ v_t1 = _mm_loadl_pi(v_t1,(__m64 *)&sct[kmr*j]); v_t1 = _mm_movelh_ps(v_t1,v_t1); /* t2 = t1*f[2*i+j2]; */ /* t3 = t1*f[1+2*i+j2]; */ v_t2 = _mm_load_ps((float *)&f[2*i+j2]); v_t3 = _mm_mul_ps(v_t2,_mm_shuffle_ps(v_t1,v_t1,160)); v_t2 = _mm_shuffle_ps(v_t2,v_t2,177); v_t2 = _mm_mul_ps(v_t2,_mm_shuffle_ps(v_t1,v_t1,245)); v_t2 = _mm_add_ps(v_t3,_mm_mul_ps(v_t2,v_m)); /* f[2*i+j2] = f[2*i+j1] - t2; */ /* f[1+2*i+j2] = f[1+2*i+j1] - t3; */ v_t3 = _mm_load_ps((float *)&f[2*i+j1]); v_t4 = _mm_sub_ps(v_t3,v_t2); _mm_store_ps((float *)&f[2*i+j2],v_t4); /* f[2*i+j1] += t2; */ /* f[1+2*i+j1] += t3; */ v_t2 = _mm_add_ps(v_t3,v_t2); _mm_store_ps((float *)&f[2*i+j1],v_t2); } } ns = ns2; } } /* unscramble modes kx = 0, nx/2 */ if (nxi==1) { for (k = 1; k < nyh; k++) { koff = 2*nxhd*k; k1 = 2*nxhd*ny - koff; for (jj = 0; jj < 2; jj++) { t1 = f[jj+k1]; f[jj+k1] = 0.5*(cimagf(f[jj+koff] + t1) + crealf(f[jj+koff] - t1)*_Complex_I); f[jj+koff] = 0.5*(crealf(f[jj+koff] + t1) + cimagf(f[jj+koff] - t1)*_Complex_I); } } } return; /* forward fourier transform */ L80: nryb = nxhy/ny; nry = nxy/ny; /* scramble modes kx = 0, nx/2 */ if (nxi==1) { for (k = 1; k < nyh; k++) { koff = 2*nxhd*k; k1 = 2*nxhd*ny - koff; for (jj = 0; jj < 2; jj++) { t1 = cimagf(f[jj+k1]) + crealf(f[jj+k1])*_Complex_I; f[jj+k1] = conjf(f[jj+koff] - t1); f[jj+koff] += t1; } } } #pragma omp parallel for \ private(i,j,k,l,ns,ns2,km,kmr,k1,k2,jj,j1,j2,koff,v_t1,v_t2,v_t3,v_t4) for (i = nxi-1; i < nxt; i++) { /* bit-reverse array elements in y */ for (k = 0; k < ny; k++) { koff = 2*nxhd*k; k1 = (mixup[k] - 1)/nryb; if (k < k1) { k1 = 2*nxhd*k1; /* t1 = f[2*i+k1]; */ /* t2 = f[1+2*i+k1]; */ v_t1 = _mm_load_ps((float *)&f[2*i+k1]); /* f[2*i+k1] = f[2*i+koff]; */ /* f[1+2*i+k1] = f[1+2*i+koff]; */ v_t2 = _mm_load_ps((float *)&f[2*i+koff]); _mm_store_ps((float *)&f[2*i+k1],v_t2); /* f[2*i+koff] = t1; */ /* f[1+2*i+koff] = t2; */ _mm_store_ps((float *)&f[2*i+koff],v_t1); } } /* then transform in y */ ns = 1; for (l = 0; l < indy; l++) { ns2 = ns + ns; km = nyh/ns; kmr = km*nry; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; for (j = 0; j < ns; j++) { j1 = 2*nxhd*(j + k1); j2 = 2*nxhd*(j + k2); /* t1 = conjf(sct[kmr*j]); */ v_t1 = _mm_loadl_pi(v_t1,(__m64 *)&sct[kmr*j]); v_t1 = _mm_movelh_ps(v_t1,v_t1); v_t1 = _mm_mul_ps(v_t1,v_n); /* t2 = t1*f[2*i+j2]; */ /* t3 = t1*f[1+2*i+j2]; */ v_t2 = _mm_load_ps((float *)&f[2*i+j2]); v_t3 = _mm_mul_ps(v_t2,_mm_shuffle_ps(v_t1,v_t1,160)); v_t2 = _mm_shuffle_ps(v_t2,v_t2,177); v_t2 = _mm_mul_ps(v_t2,_mm_shuffle_ps(v_t1,v_t1,245)); v_t2 = _mm_add_ps(v_t3,_mm_mul_ps(v_t2,v_m)); /* f[2*i+j2] = f[2*i+j1] - t2; */ /* f[1+2*i+j2] = f[1+2*i+j1] - t3; */ v_t3 = _mm_load_ps((float *)&f[2*i+j1]); v_t4 = _mm_sub_ps(v_t3,v_t2); _mm_store_ps((float *)&f[2*i+j2],v_t4); /* f[2*i+j1] += t2; */ /* f[1+2*i+j1] += t3; */ v_t2 = _mm_add_ps(v_t3,v_t2); _mm_store_ps((float *)&f[2*i+j1],v_t2); } } ns = ns2; } } return; } /*--------------------------------------------------------------------*/ void csse2wfft2rmx(float complex f[], int isign, int mixup[], float complex sct[], int indx, int indy, int nxhd, int nyd, int nxhyd, int nxyhd) { /* wrapper function for real to complex fft, with packed data */ /* parallelized with OpenMP */ /* local data */ int nxh, ny; static int nxi = 1, nyi = 1; /* calculate range of indices */ nxh = 1L<<(indx - 1); ny = 1L<<indy; /* inverse fourier transform */ if (isign < 0) { /* perform x fft */ csse2fft2rmxx(f,isign,mixup,sct,indx,indy,nyi,ny,nxhd,nyd,nxhyd, nxyhd); /* perform y fft */ csse2fft2rmxy(f,isign,mixup,sct,indx,indy,nxi,nxh,nxhd,nyd,nxhyd, nxyhd); } /* forward fourier transform */ else if (isign > 0) { /* perform y fft */ csse2fft2rmxy(f,isign,mixup,sct,indx,indy,nxi,nxh,nxhd,nyd,nxhyd, nxyhd); /* perform x fft */ csse2fft2rmxx(f,isign,mixup,sct,indx,indy,nyi,ny,nxhd,nyd,nxhyd, nxyhd); } return; } /*--------------------------------------------------------------------*/ void csse2wfft2rm2(float complex f[], int isign, int mixup[], float complex sct[], int indx, int indy, int nxhd, int nyd, int nxhyd, int nxyhd) { /* wrapper function for 2 2d real to complex ffts, with packed data */ /* parallelized with OpenMP */ /* local data */ int nxh, ny; static int nxi = 1, nyi = 1; /* calculate range of indices */ nxh = 1L<<(indx - 1); ny = 1L<<indy; /* inverse fourier transform */ if (isign < 0) { /* perform x fft */ csse2fft2rm2x(f,isign,mixup,sct,indx,indy,nyi,ny,nxhd,nyd,nxhyd, nxyhd); /* perform y fft */ csse2fft2rm2y(f,isign,mixup,sct,indx,indy,nxi,nxh,nxhd,nyd,nxhyd, nxyhd); } /* forward fourier transform */ else if (isign > 0) { /* perform y fft */ csse2fft2rm2y(f,isign,mixup,sct,indx,indy,nxi,nxh,nxhd,nyd,nxhyd, nxyhd); /* perform x fft */ csse2fft2rm2x(f,isign,mixup,sct,indx,indy,nyi,ny,nxhd,nyd,nxhyd, nxyhd); } return; } /* Interfaces to Fortran */ /*--------------------------------------------------------------------*/ void csse2gppush2lt_(float *ppart, float *fxy, int *kpic, float *qbm, float *dt, float *ek, int *idimp, int *nppmx, int *nx, int *ny, int *mx, int *my, int *nxv, int *nyv, int *mx1, int *mxy1, int *ipbc) { csse2gppush2lt(ppart,fxy,kpic,*qbm,*dt,ek,*idimp,*nppmx,*nx,*ny,*mx, *my,*nxv,*nyv,*mx1,*mxy1,*ipbc); return; } /*--------------------------------------------------------------------*/ void csse2gppushf2lt_(float *ppart, float *fxy, int *kpic, int *ncl, int *ihole, float *qbm, float *dt, float *ek, int *idimp, int *nppmx, int *nx, int *ny, int *mx, int *my, int *nxv, int *nyv, int *mx1, int *mxy1, int *ntmax, int *irc) { csse2gppushf2lt(ppart,fxy,kpic,ncl,ihole,*qbm,*dt,ek,*idimp,*nppmx, *nx,*ny,*mx,*my,*nxv,*nyv,*mx1,*mxy1,*ntmax,irc); return; } /*--------------------------------------------------------------------*/ void csse2gppost2lt_(float *ppart, float *q, int *kpic, float *qm, int *nppmx, int *idimp, int *mx, int *my, int *nxv, int *nyv, int *mx1, int *mxy1) { csse2gppost2lt(ppart,q,kpic,*qm,*nppmx,*idimp,*mx,*my,*nxv,*nyv,*mx1, *mxy1); return; } /*--------------------------------------------------------------------*/ void csse2pporder2lt_(float *ppart, float *ppbuff, int *kpic, int *ncl, int *ihole, int *idimp, int *nppmx, int *nx, int *ny, int *mx, int *my, int *mx1, int *my1, int *npbmx, int *ntmax, int *irc) { csse2pporder2lt(ppart,ppbuff,kpic,ncl,ihole,*idimp,*nppmx,*nx,*ny, *mx,*my,*mx1,*my1,*npbmx,*ntmax,irc); return; } /*--------------------------------------------------------------------*/ void csse2pporderf2lt_(float *ppart, float *ppbuff, int *kpic, int *ncl, int *ihole, int *idimp, int *nppmx, int *mx1, int *my1, int *npbmx, int *ntmax, int *irc) { csse2pporderf2lt(ppart,ppbuff,kpic,ncl,ihole,*idimp,*nppmx,*mx1,*my1, *npbmx,*ntmax,irc); return; } /*--------------------------------------------------------------------*/ void csse2cguard2l_(float *fxy, int *nx, int *ny, int *nxe, int *nye) { csse2cguard2l(fxy,*nx,*ny,*nxe,*nye); return; } /*--------------------------------------------------------------------*/ void csse2aguard2l_(float *q, int *nx, int *ny, int *nxe, int *nye) { csse2aguard2l(q,*nx,*ny,*nxe,*nye); return; } /*--------------------------------------------------------------------*/ void csse2mpois22_(float complex *q, float complex *fxy, int *isign, float complex *ffc, float *ax, float *ay, float *affp, float *we, int *nx, int *ny, int *nxvh, int *nyv, int *nxhd, int *nyhd) { csse2mpois22(q,fxy,*isign,ffc,*ax,*ay,*affp,we,*nx,*ny,*nxvh,*nyv, *nxhd,*nyhd); return; } /*--------------------------------------------------------------------*/ void csse2wfft2rmx_(float complex *f, int *isign, int *mixup, float complex *sct, int *indx, int *indy, int *nxhd, int *nyd, int *nxhyd, int *nxyhd) { csse2wfft2rmx(f,*isign,mixup,sct,*indx,*indy,*nxhd,*nyd,*nxhyd, *nxyhd); return; } /*--------------------------------------------------------------------*/ void csse2wfft2rm2_(float complex *f, int *isign, int *mixup, float complex *sct, int *indx, int *indy, int *nxhd, int *nyd, int *nxhyd, int *nxyhd) { csse2wfft2rm2(f,*isign,mixup,sct,*indx,*indy,*nxhd,*nyd,*nxhyd, *nxyhd); return; }
render.c
#include "simpleRayTracer.h" void renderKernel(const int NI, const int NJ, scene_t scene, const sensor_t sensor, const dfloat costheta, const dfloat sintheta, const dfloat *randomNumbers, unsigned char *img){ const colour_t bg = sensor.bg; // unpack contents of scene grid_t *grid = scene.grid; material_t *materials = scene.materials; shape_t *shapes = scene.shapes; light_t *lights = scene.lights; const int Nlights = scene.Nlights; const int Nmaterials = scene.Nmaterials; const int Nshapes = scene.Nshapes; // (I,J) loop over pixels in image #pragma omp parallel for for(int J=0;J<NJ;++J){ for(int I=0;I<NI;++I){ ray_t r; dfloat coef = 1.0; int level = 0; // 2.5 location of sensor pixel colour_t c; dfloat x0 = sensor.eyeX.x; dfloat y0 = sensor.eyeX.y; dfloat z0 = sensor.eyeX.z; // multiple rays emanating from sensor, passing through lens and focusing at the focal plane // 1. compute intersection of ray passing through lens center to focal plane // (sensorX + alpha*(lensC -sensorX)).sensorN = focalPlaneOffset // alpha = (focalOffset-s.sensorN)/( (lensC-s).sensorN) [ . dot product ] dfloat cx = BOXSIZE/2., cy = HEIGHT, cz = BOXSIZE/2; vector_t sensorN = vectorCrossProduct(sensor.Idir, sensor.Jdir); vector_t sensorX = sensorLocation(NI, NJ, I, J, sensor); dfloat focalPlaneOffset = sensor.focalPlaneOffset; vector_t centralRayDir = vectorSub(sensor.lensC, sensorX); dfloat alpha = (focalPlaneOffset - vectorDot(sensorX, sensorN))/vectorDot(centralRayDir, sensorN); // 2. target vector_t targetX = vectorAdd(sensorX, vectorScale(alpha, centralRayDir)); x0 = sensorX.x; y0 = sensorX.y; z0 = sensorX.z; // 3. loop over vertical offsets on lens (thin lens) c.red = 0; c.green = 0; c.blue = 0; for(int samp=0;samp<p_Nsamples;++samp){ // aperture width int sampId = (I+J*NI + samp*25*25)%NRANDOM; dfloat offI = p_apertureRadius; dfloat offJ = p_apertureRadius; // choose random starting point on lens (assumes lens and sensor arre parallel) if(samp>0) { // primary ray x0 = sensor.lensC.x + offI*sensor.Idir.x + offJ*sensor.Jdir.x; y0 = sensor.lensC.y + offI*sensor.Idir.y + offJ*sensor.Jdir.y; z0 = sensor.lensC.z + offI*sensor.Idir.z + offJ*sensor.Jdir.z; } dfloat dx0 = targetX.x - x0; dfloat dy0 = targetX.y - y0; dfloat dz0 = targetX.z - z0; dfloat L0 = sqrt(dx0*dx0+dy0*dy0+dz0*dz0); dx0 = dx0/L0; dy0 = dy0/L0; dz0 = dz0/L0; r.start.x = costheta*(x0-cx) - sintheta*(z0-cz) + cx; r.start.y = y0; r.start.z = sintheta*(x0-cx) + costheta*(z0-cz) + cz; r.dir.x = costheta*dx0 - sintheta*dz0; r.dir.y = dy0; r.dir.z = sintheta*dx0 + costheta*dz0; // trace ray through scene (possibly with multipathing, reflection, refraction) colour_t newc = gridTrace(grid[0], Nshapes, shapes, Nlights, lights, Nmaterials, materials, r, level, coef, bg); // add colors to final intensity for IJ pixel dfloat sc = (samp==0) ? p_primaryWeight: 1.f; c.red += sc*newc.red; c.green += sc*newc.green; c.blue += sc*newc.blue; } // primary weighted average c.red /= (p_primaryWeight+p_Nsamples-1); c.green /= (p_primaryWeight+p_Nsamples-1); c.blue /= (p_primaryWeight+p_Nsamples-1); // store pixel rgb intensities (reverse vertical because of lensing) img[(I + (NJ-1-J)*NI)*3 + 0] = (unsigned char)min( c.red*255.0f, 255.0f); img[(I + (NJ-1-J)*NI)*3 + 1] = (unsigned char)min(c.green*255.0f, 255.0f); img[(I + (NJ-1-J)*NI)*3 + 2] = (unsigned char)min( c.blue*255.0f, 255.0f); } } }
hello.c
#include <stdio.h> #include <stdlib.h> #include <omp.h> void hello (void); int main (int argx, char* argv[]){ int thread_conut = strtol(argv[1], NULL, 10); #pragma omp parallel num_threads(thread_count) Hello(); omp_get_thread_num return =0; }
dynamic_smagorinsky_utilities.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Jordi Cotela // // System includes #include <vector> #include <map> // External includes // Project includes #include "includes/define.h" #include "includes/model_part.h" #include "includes/node.h" #include "includes/element.h" #include "utilities/openmp_utils.h" #include "utilities/geometry_utilities.h" #include "includes/cfd_variables.h" #include "fluid_dynamics_application_variables.h" #include "includes/global_pointer_variables.h" #ifndef KRATOS_DYNAMIC_SMAGORINSKY_UTILITIES_H_INCLUDED #define KRATOS_DYNAMIC_SMAGORINSKY_UTILITIES_H_INCLUDED namespace Kratos { ///@addtogroup FluidDynamicsApplication ///@{ ///@name Kratos Classes ///@{ /// Helper class to dynamically determine a value for the Smagorinsly parameter. /** This class uses the Variational Germano Identity to determine a value for the Smagorinsky parameter. This value is stored in the elemental variable C_SMAGORINSKY, the element implementation is responsible for using it. The ability to assign different values to different patches of elements (identified by the PATCH_INDEX variable) is supported, although it tends to produce unreliable results due to a 0/0 indetermination in patches with smooth velocity fields. This class is based in Oberai, A.A. and Wanderer, J., Variational formulation of the Germano identity for the Navier Stokes equations, Journal of Turbulence, 2005, vol 6. Note that the formulation described there requires a nested mesh. It takes the model part containing a coarse mesh as input and assumes that all elements will be subdivided before CalculateC() is called. Remember to call StoreCoarseMesh before refining the element, otherwise the coarse mesh will be lost. @see VMS for an element implementation that uses the Smagorinsky model. @see Local_Refine_Triangle_Mesh,Local_Refine_Tetrahedra_Mesh for the element refinement process. */ class DynamicSmagorinskyUtils { public: ///@name Life Cycle ///@{ /// Constructor /** @param rModelPart Reference to the model part containing the coarse mesh @param DomainSize Spatial dimension (2 or 3) */ DynamicSmagorinskyUtils(ModelPart& rModelPart, unsigned int DomainSize): mrModelPart(rModelPart), mDomainSize(DomainSize), mCoarseMesh(), mPatchIndices() {} /// Destructor ~DynamicSmagorinskyUtils() {} ///@} ///@name Operations ///@{ /// Store current mesh as coarse mesh. Call before refining. /** If you are refining more than once, this only has to be called before last refinement. */ void StoreCoarseMesh() { // Clear existing mesh (if any) mCoarseMesh.clear(); // Store current mesh for( ModelPart::ElementsContainerType::ptr_iterator itpElem = mrModelPart.Elements().ptr_begin(); itpElem != mrModelPart.Elements().ptr_end(); ++itpElem) { // (*itpElem)->GetValue(C_SMAGORINSKY) = 0.0; // Set the Smagorinsky parameter to zero for the coarse mesh (do this once to reset any input values) mCoarseMesh.push_back(*itpElem); } // Count the number of patches in the model (in parallel) const int NumThreads = OpenMPUtils::GetNumThreads(); OpenMPUtils::PartitionVector ElementPartition; OpenMPUtils::DivideInPartitions(mCoarseMesh.size(),NumThreads,ElementPartition); std::vector< std::vector<int> > LocalIndices(NumThreads); #pragma omp parallel { int k = OpenMPUtils::ThisThread(); ModelPart::ElementsContainerType::iterator ElemBegin = mCoarseMesh.begin() + ElementPartition[k]; ModelPart::ElementsContainerType::iterator ElemEnd = mCoarseMesh.begin() + ElementPartition[k+1]; for( ModelPart::ElementIterator itElem = ElemBegin; itElem != ElemEnd; ++itElem) { this->AddNewIndex(LocalIndices[k],itElem->GetValue(PATCH_INDEX)); } } // Combine the partial lists and create a map for PATCH_INDEX -> Vector position unsigned int Counter = 0; std::pair<int, unsigned int> NewVal; std::pair< std::map<int, unsigned int>::iterator, bool > Result; for( std::vector< std::vector<int> >::iterator itList = LocalIndices.begin(); itList != LocalIndices.end(); ++itList ) { for( std::vector<int>::iterator itIndex = itList->begin(); itIndex != itList->end(); ++itIndex) { // Note that instering in map already sorts and checks for uniqueness NewVal.first = *itIndex; NewVal.second = Counter; Result = mPatchIndices.insert(NewVal); if (Result.second) ++Counter; } } } /// Provide a value for the Smagorinsky coefficient using the Variational Germano Identity void CalculateC() { // Update the velocity values for the terms that belong to the coarse mesh this->SetCoarseVel(); // Partitioning const int NumThreads = OpenMPUtils::GetNumThreads(); OpenMPUtils::PartitionVector CoarseElementPartition,FineElementPartition; OpenMPUtils::DivideInPartitions(mCoarseMesh.size(),NumThreads,CoarseElementPartition); OpenMPUtils::DivideInPartitions(mrModelPart.Elements().size(),NumThreads,FineElementPartition); // Initialize temporary containers unsigned int PatchNumber = mPatchIndices.size(); std::vector< std::vector<double> > GlobalPatchNum(NumThreads); // Numerator on each patch std::vector< std::vector<double> > GlobalPatchDen(NumThreads); // Denominator on each patch const double EnergyTol = 0.005; double TotalDissipation = 0; #pragma omp parallel reduction(+:TotalDissipation) { int k = OpenMPUtils::ThisThread(); // Initialize the iterator boundaries for this thread ModelPart::ElementsContainerType::iterator CoarseElemBegin = mCoarseMesh.begin() + CoarseElementPartition[k]; ModelPart::ElementsContainerType::iterator CoarseElemEnd = mCoarseMesh.begin() + CoarseElementPartition[k+1]; ModelPart::ElementsContainerType::iterator FineElemBegin = mrModelPart.ElementsBegin() + FineElementPartition[k]; ModelPart::ElementsContainerType::iterator FineElemEnd = mrModelPart.ElementsBegin() + FineElementPartition[k+1]; // Initialize some thread-local variables Vector LocalValues, LocalCoarseVel; Matrix LocalMassMatrix; ProcessInfo& rProcessInfo = mrModelPart.GetProcessInfo(); double Residual,Model; unsigned int PatchPosition; // Thread-local containers for the values in each patch std::vector<double>& rPatchNum = GlobalPatchNum[k]; std::vector<double>& rPatchDen = GlobalPatchDen[k]; rPatchNum.resize(PatchNumber,0.0);// Fill with zeros rPatchDen.resize(PatchNumber,0.0); if (mDomainSize == 2) { LocalValues.resize(9); LocalCoarseVel.resize(9); LocalMassMatrix.resize(9,9,false); array_1d<double,3> N; BoundedMatrix<double,3,2> DN_DX; BoundedMatrix<double,2,2> dv_dx; // Evaluate the N-S and model terms in each coarse element for( ModelPart::ElementsContainerType::iterator itElem = CoarseElemBegin; itElem != CoarseElemEnd; ++itElem) { PatchPosition = mPatchIndices[ itElem->GetValue(PATCH_INDEX) ]; this->GermanoTerms2D(*itElem,N,DN_DX,dv_dx,LocalValues,LocalCoarseVel,LocalMassMatrix,rProcessInfo,Residual,Model); rPatchNum[PatchPosition] += Residual; rPatchDen[PatchPosition] += Model; TotalDissipation += Residual; } // Now evaluate the corresponding terms in the fine mesh for( ModelPart::ElementsContainerType::iterator itElem = FineElemBegin; itElem != FineElemEnd; ++itElem) { // Deactivate Smagorinsky to compute the residual of galerkin+stabilization terms only itElem->GetValue(C_SMAGORINSKY) = 0.0; PatchPosition = mPatchIndices[ itElem->GetValue(PATCH_INDEX) ]; this->GermanoTerms2D(*itElem,N,DN_DX,dv_dx,LocalValues,LocalCoarseVel,LocalMassMatrix,rProcessInfo,Residual,Model); rPatchNum[PatchPosition] -= Residual; rPatchDen[PatchPosition] -= Model; } } else // mDomainSize == 3 { LocalValues.resize(16); LocalCoarseVel.resize(16); LocalMassMatrix.resize(16,16,false); array_1d<double,4> N; BoundedMatrix<double,4,3> DN_DX; BoundedMatrix<double,3,3> dv_dx; // Evaluate the N-S and model terms in each coarse element for( ModelPart::ElementsContainerType::iterator itElem = CoarseElemBegin; itElem != CoarseElemEnd; ++itElem) { PatchPosition = mPatchIndices[ itElem->GetValue(PATCH_INDEX) ]; this->GermanoTerms3D(*itElem,N,DN_DX,dv_dx,LocalValues,LocalCoarseVel,LocalMassMatrix,rProcessInfo,Residual,Model); rPatchNum[PatchPosition] += Residual; rPatchDen[PatchPosition] += Model; TotalDissipation += Residual; } // Now evaluate the corresponding terms in the fine mesh for( ModelPart::ElementsContainerType::iterator itElem = FineElemBegin; itElem != FineElemEnd; ++itElem) { // Deactivate Smagorinsky to compute the residual of galerkin+stabilization terms only itElem->GetValue(C_SMAGORINSKY) = 0.0; PatchPosition = mPatchIndices[ itElem->GetValue(PATCH_INDEX) ]; this->GermanoTerms3D(*itElem,N,DN_DX,dv_dx,LocalValues,LocalCoarseVel,LocalMassMatrix,rProcessInfo,Residual,Model); rPatchNum[PatchPosition] -= Residual; rPatchDen[PatchPosition] -= Model; } } } // Combine the results of each thread in position 0 for( std::vector< std::vector<double> >::iterator itNum = GlobalPatchNum.begin()+1, itDen = GlobalPatchDen.begin()+1; itNum != GlobalPatchNum.end(); ++itNum, ++itDen) { for( std::vector<double>::iterator TotalNum = GlobalPatchNum[0].begin(), LocalNum = itNum->begin(), TotalDen = GlobalPatchDen[0].begin(), LocalDen = itDen->begin(); TotalNum != GlobalPatchNum[0].end(); ++TotalNum,++LocalNum,++TotalDen,++LocalDen) { *TotalNum += *LocalNum; *TotalDen += *LocalDen; } } // Compute the smagorinsky coefficient for each patch by combining the values from each thread std::vector<double> PatchC(PatchNumber); double NumTol = EnergyTol * fabs(TotalDissipation); for( std::vector<double>::iterator itNum = GlobalPatchNum[0].begin(), itDen = GlobalPatchDen[0].begin(), itC = PatchC.begin(); itC != PatchC.end(); ++itNum, ++itDen, ++itC) { // If the dissipation we are "missing" by not considering Smagorinsky is small, do not use Smagorinsky (this avoids a division by ~0, as the denominator should go to zero too) if ( (fabs(*itNum) < NumTol) )//|| (fabs(*itDen) < 1.0e-12) ) *itC = 0.0; else *itC = sqrt( 0.5 * fabs( *itNum / *itDen ) ); } // Finally, assign each element its new smagorinsky value #pragma omp parallel { int k = OpenMPUtils::ThisThread(); ModelPart::ElementsContainerType::iterator ElemBegin = mrModelPart.ElementsBegin() + FineElementPartition[k]; ModelPart::ElementsContainerType::iterator ElemEnd = mrModelPart.ElementsBegin() + FineElementPartition[k+1]; unsigned int PatchPosition; for( ModelPart::ElementIterator itElem = ElemBegin; itElem != ElemEnd; ++itElem) { PatchPosition = mPatchIndices[ itElem->GetValue(PATCH_INDEX) ]; itElem->GetValue(C_SMAGORINSKY) = PatchC[PatchPosition]; } } } /// For the bridge analysis problem, correct the boundary flag after the refinement. /** Remember to run this AFTER EACH REFINEMENT STEP Possible values for the variable: 1.0 inlet, 2.0 bridge surface, 3.0 outlet, 0.0 otherwise @param rThisVariable The Kratos variable used to identify the boundary */ void CorrectFlagValues(Variable<double>& rThisVariable = FLAG_VARIABLE) { // Loop over coarse mesh to evaluate all terms that do not involve the fine mesh const int NumThreads = OpenMPUtils::GetNumThreads(); OpenMPUtils::PartitionVector NodePartition; OpenMPUtils::DivideInPartitions(mrModelPart.NumberOfNodes(),NumThreads,NodePartition); #pragma omp parallel { int k = OpenMPUtils::ThisThread(); ModelPart::NodeIterator NodesBegin = mrModelPart.NodesBegin() + NodePartition[k]; ModelPart::NodeIterator NodesEnd = mrModelPart.NodesBegin() + NodePartition[k+1]; double Value0, Value1; for( ModelPart::NodeIterator itNode = NodesBegin; itNode != NodesEnd; ++itNode) { if( itNode->GetValue(FATHER_NODES).size() == 2 ) // If the node is refined { Value0 = itNode->GetValue(FATHER_NODES)[0].FastGetSolutionStepValue(rThisVariable); Value1 = itNode->GetValue(FATHER_NODES)[1].FastGetSolutionStepValue(rThisVariable); if( Value0 != Value1 ) // If this node is problematic { if ( Value0 == 0.0 || Value1 == 0.0 ) { // if either of the parents is not on the boundary, this node is not on the boundary itNode->FastGetSolutionStepValue(rThisVariable) = 0.0; } /* All remaining cases are unlikely in well-posed problems, I'm arbitrarily giving priority to the outlet, so that the node is only inlet or bridge surface if both parents are */ else if( Value0 == 3.0 ) { itNode->FastGetSolutionStepValue(rThisVariable) = Value0; } else if( Value1 == 3.0 ) { // The node is only bridge surface if both parents are itNode->FastGetSolutionStepValue(rThisVariable) = Value1; } else // Default behaviour: Parent 0 takes precedence { itNode->FastGetSolutionStepValue(rThisVariable) = Value0; } } } } } } ///@} private: ///@name Member Variables ///@{ /// ModelPart of the fluid problem ModelPart& mrModelPart; /// Spatial dimenstion unsigned int mDomainSize; /// Container for the coarse mesh (the fine mesh is stored by the model part) ModelPart::ElementsContainerType mCoarseMesh; /// A map relating patch indices to positions in the internal storage arrays std::map<int, unsigned int> mPatchIndices; ///@name Private Operations ///@{ /// Calculate the "Coarse Mesh" velocity /** The operations on the coarse mesh are evaluated on the fine mesh, but using an averaged velocity on the nodes that only exist on the fine mesh. Velocity gradients calculated on the fine mesh using this average velocity will be equal to those that would be obtained using the coarse mesh. This function assigns the "coarse" velocity value to all nodes */ void SetCoarseVel() { /* Note: This loop can't be parallelized, as we are relying on the fact that refined nodes are at the end of the list and their parents will be updated before the refined nodes are reached. There is an alternative solution (always calculate the coarse mesh velocity from the historic database) which can be parallelized but won't work for multiple levels of refinement */ for( ModelPart::NodeIterator itNode = mrModelPart.NodesBegin(); itNode != mrModelPart.NodesEnd(); ++itNode) { if( itNode->GetValue(FATHER_NODES).size() == 2 ) { Node<3>& rParent1 = itNode->GetValue(FATHER_NODES)[0]; Node<3>& rParent2 = itNode->GetValue(FATHER_NODES)[1]; itNode->GetValue(COARSE_VELOCITY) = 0.5 * ( rParent1.FastGetSolutionStepValue(VELOCITY) + rParent2.FastGetSolutionStepValue(VELOCITY) ); } else { itNode->GetValue(COARSE_VELOCITY) = itNode->FastGetSolutionStepValue(VELOCITY); } } } /// Return the Galerkin (+stabilization) and Model terms for this element (2D version) void GermanoTerms2D(Element& rElem, array_1d<double,3>& rShapeFunc, BoundedMatrix<double,3,2>& rShapeDeriv, BoundedMatrix<double,2,2>& rGradient, Vector& rNodalResidualContainer, Vector& rNodalVelocityContainer, Matrix& rMassMatrix, ProcessInfo& rProcessInfo, double& rResidual, double& rModel) { const double Dim = 2; const double NumNodes = 3; // Initialize double Area; double Density = 0.0; rGradient = ZeroMatrix(Dim,Dim); rResidual = 0.0; rModel = 0.0; // Calculate the residual this->CalculateResidual(rElem,rMassMatrix,rNodalVelocityContainer,rNodalResidualContainer,rProcessInfo); // We use rNodalVelocityContainer as an auxiliaty variable this->GetCoarseVelocity2D(rElem,rNodalVelocityContainer); for( Vector::iterator itRHS = rNodalResidualContainer.begin(), itVel = rNodalVelocityContainer.begin(); itRHS != rNodalResidualContainer.end(); ++itRHS, ++itVel) rResidual += (*itVel) * (*itRHS); // Calculate the model term GeometryUtils::CalculateGeometryData( rElem.GetGeometry(), rShapeDeriv, rShapeFunc, Area); // Compute Grad(u), Density and < Grad(w), Grad(u) > for (unsigned int j = 0; j < NumNodes; ++j) // Columns of <Grad(Ni),Grad(Nj)> { Density += rShapeFunc[j] * rElem.GetGeometry()[j].FastGetSolutionStepValue(DENSITY); const array_1d< double,3 >& rNodeVel = rElem.GetGeometry()[j].FastGetSolutionStepValue(VELOCITY); // Nodal velocity for (unsigned int i = 0; i < NumNodes; ++i) // Rows of <Grad(Ni),Grad(Nj)> { const array_1d< double,3 >& rNodeTest = rElem.GetGeometry()[i].GetValue(COARSE_VELOCITY); // Test function (particularized to coarse velocity) for (unsigned int k = 0; k < Dim; ++k) // Space Dimensions rModel += rNodeTest[k] * rShapeDeriv(i,k) * rShapeDeriv(j,k) * rNodeVel[k]; } for (unsigned int m = 0; m < Dim; ++m) // Calculate symmetric gradient { for (unsigned int n = 0; n < m; ++n) // Off-diagonal rGradient(m,n) += 0.5 * (rShapeDeriv(j,n) * rNodeVel[m] + rShapeDeriv(j,m) * rNodeVel[n]); // Symmetric gradient, only lower half is written rGradient(m,m) += rShapeDeriv(j,m) * rNodeVel[m]; // Diagonal } } rModel *= Area; // To this point, rModel contains the integral over the element of Grad(U_coarse):Grad(U) // Norm[ Grad(u) ] double SqNorm = 0.0; for (unsigned int i = 0; i < Dim; ++i) { for (unsigned int j = 0; j < i; ++j) SqNorm += 2.0 * rGradient(i,j) * rGradient(i,j); // Adding off-diagonal terms (twice, as matrix is symmetric) SqNorm += rGradient(i,i) * rGradient(i,i); // Diagonal terms } // "Fixed" part of Smagorinsky viscosity: Density * FilterWidth^2 * Norm(SymmetricGrad(U)). 2*C^2 is accounted for in the caller function const double sqH = 2*Area; rModel *= Density * sqH * sqrt(SqNorm); } /// Return the Galerkin (+stabilization) and Model terms for this element (3D version) void GermanoTerms3D(Element& rElem, array_1d<double,4>& rShapeFunc, BoundedMatrix<double,4,3>& rShapeDeriv, BoundedMatrix<double,3,3>& rGradient, Vector& rNodalResidualContainer, Vector& rNodalVelocityContainer, Matrix& rMassMatrix, ProcessInfo& rProcessInfo, double& rResidual, double& rModel) { const double Dim = 3; const double NumNodes = 4; // Initialize double Volume; double Density = 0.0; rGradient = ZeroMatrix(Dim,Dim); rResidual = 0.0; rModel = 0.0; // Calculate the residual this->CalculateResidual(rElem,rMassMatrix,rNodalVelocityContainer,rNodalResidualContainer,rProcessInfo); // We use rNodalVelocityContainer as an auxiliaty variable this->GetCoarseVelocity3D(rElem,rNodalVelocityContainer); for( Vector::iterator itRHS = rNodalResidualContainer.begin(), itVel = rNodalVelocityContainer.begin(); itRHS != rNodalResidualContainer.end(); ++itRHS, ++itVel) rResidual += (*itVel) * (*itRHS); // Calculate the model term GeometryUtils::CalculateGeometryData( rElem.GetGeometry(), rShapeDeriv, rShapeFunc, Volume); // Compute Grad(u), Density and < Grad(w), Grad(u) > for (unsigned int j = 0; j < NumNodes; ++j) // Columns of <Grad(Ni),Grad(Nj)> { Density += rShapeFunc[j] * rElem.GetGeometry()[j].FastGetSolutionStepValue(DENSITY); const array_1d< double,3 >& rNodeVel = rElem.GetGeometry()[j].FastGetSolutionStepValue(VELOCITY); // Nodal velocity for (unsigned int i = 0; i < NumNodes; ++i) // Rows of <Grad(Ni),Grad(Nj)> { const array_1d< double,3 >& rNodeTest = rElem.GetGeometry()[i].GetValue(COARSE_VELOCITY); // Test function (particularized to coarse velocity) for (unsigned int k = 0; k < Dim; ++k) // Space Dimensions rModel += rNodeTest[k] * rShapeDeriv(i,k) * rShapeDeriv(j,k) * rNodeVel[k]; } for (unsigned int m = 0; m < Dim; ++m) // Calculate symmetric gradient { for (unsigned int n = 0; n < m; ++n) // Off-diagonal rGradient(m,n) += 0.5 * (rShapeDeriv(j,n) * rNodeVel[m] + rShapeDeriv(j,m) * rNodeVel[n]); // Symmetric gradient, only lower half is written rGradient(m,m) += rShapeDeriv(j,m) * rNodeVel[m]; // Diagonal } } rModel *= Volume; // To this point, rModel contains the integral over the element of Grad(U_coarse):Grad(U) // Norm[ Symmetric Grad(u) ] = ( 2 * Sij * Sij )^(1/2), we compute the Sij * Sij part in the following loop: double SqNorm = 0.0; for (unsigned int i = 0; i < Dim; ++i) { for (unsigned int j = 0; j < i; ++j) SqNorm += 2.0 * rGradient(i,j) * rGradient(i,j); // Adding off-diagonal terms (twice, as matrix is symmetric) SqNorm += rGradient(i,i) * rGradient(i,i); // Diagonal terms } const double cubeH = 6*Volume; rModel *= Density * pow(cubeH, 2.0/3.0) * sqrt(2.0 * SqNorm); } /// Equivalent to VMS2DSmagorinsky::GetFirstDerivativesVector(), using the velocity evaluated on the coarse mesh void GetCoarseVelocity2D(Element& rElement, Vector& rVar) { unsigned int LocalIndex = 0; const Element::GeometryType& rGeom = rElement.GetGeometry(); for (unsigned int itNode = 0; itNode < 3; ++itNode) { const array_1d< double,3>& rCoarseVel = rGeom[itNode].GetValue(COARSE_VELOCITY); rVar[LocalIndex++] = rCoarseVel[0]; rVar[LocalIndex++] = rCoarseVel[1]; rVar[LocalIndex++] = 0.0; // Pressure Dof } } /// Equivalent to VMS3DSmagorinsky::GetFirstDerivativesVector(), using the velocity evaluated on the coarse mesh void GetCoarseVelocity3D(Element& rElement, Vector& rVar) { unsigned int LocalIndex = 0; const Element::GeometryType& rGeom = rElement.GetGeometry(); for (unsigned int itNode = 0; itNode < 4; ++itNode) { const array_1d< double,3>& rCoarseVel = rGeom[itNode].GetValue(COARSE_VELOCITY); rVar[LocalIndex++] = rCoarseVel[0]; rVar[LocalIndex++] = rCoarseVel[1]; rVar[LocalIndex++] = rCoarseVel[2]; rVar[LocalIndex++] = 0.0; // Pressure Dof } } /// Call the element's member functions to obtain its residual void CalculateResidual(Element& rElement, Matrix& rMassMatrix, ///@todo This matrix and the next vector should be transformed to static members once we find a threadsafe way to do so Vector& rAuxVector, Vector& rResidual, const ProcessInfo& rCurrentProcessInfo) { const auto& r_const_elem_ref = rElement; rElement.InitializeNonLinearIteration(rCurrentProcessInfo); // Dynamic stabilization terms rElement.CalculateRightHandSide(rResidual,rCurrentProcessInfo); // Dynamic Terms rElement.CalculateMassMatrix(rMassMatrix,rCurrentProcessInfo); r_const_elem_ref.GetSecondDerivativesVector(rAuxVector,0); noalias(rResidual) -= prod(rMassMatrix,rAuxVector); // Velocity Terms rElement.CalculateLocalVelocityContribution(rMassMatrix,rResidual,rCurrentProcessInfo); // Note that once we are here, we no longer need the mass matrix } /// Check if a patch index is known void AddNewIndex( std::vector<int>& rIndices, int ThisIndex ) { bool IsNew = true; for( std::vector<int>::iterator itIndex = rIndices.begin(); itIndex != rIndices.end(); ++itIndex) { if( ThisIndex == *itIndex) { IsNew = false; break; } } if (IsNew) rIndices.push_back(ThisIndex); } ///@} // Private operations }; ///@} Kratos classes ///@} Application group } // namespace Kratos #endif /* KRATOS_DYNAMIC_SMAGORINSKY_UTILITIES_H_INCLUDED */
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_unaryop__minv_bool_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__minv_bool_fp32 // op(A') function: GB_tran__minv_bool_fp32 // C type: bool // A type: float // cast: ; // unaryop: cij = true #define GB_ATYPE \ float #define GB_CTYPE \ bool // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ ; #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = true ; // 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_MINV || GxB_NO_BOOL || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_bool_fp32 ( bool *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__minv_bool_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
NavierStokesSolver_impl.h
// Copyright (c) 2004-2022 Tomáš Oberhuber et al. // // This file is part of TNL - Template Numerical Library (https://tnl-project.org/) // // SPDX-License-Identifier: MIT #pragma once #include <TNL/Solvers/cfd/navier-stokes/NavierStokesSolver.h> namespace TNL { template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::NavierStokesSolver() : advection( 0 ), u1Viscosity( 0 ), u2Viscosity( 0 ), energyViscosity( 0 ), mu( 0.0 ), gravity( 0.0 ), R( 0.0 ), T( 0.0 ) {} template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > void NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::setAdvectionScheme( AdvectionSchemeType& advection ) { this->advection = &advection; } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > void NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::setDiffusionScheme( DiffusionSchemeType& u1Viscosity, DiffusionSchemeType& u2Viscosity, DiffusionSchemeType& energyViscosity ) { this->u1Viscosity = &u1Viscosity; this->u2Viscosity = &u2Viscosity; this->energyViscosity = &energyViscosity; } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > void NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::setBoundaryConditions( BoundaryConditionsType& boundaryConditions ) { this->boundaryConditions = &boundaryConditions; } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > void NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::setMesh( MeshType& mesh ) { this->mesh = &mesh; this->rho.setSize( this->mesh->getDofs() ); this->u1.setSize( this->mesh->getDofs() ); this->u2.setSize( this->mesh->getDofs() ); this->u.setSize( this->mesh->getDofs() ); this->p.setSize( this->mesh->getDofs() ); this->energy.setSize( this->mesh->getDofs() ); this->rhsDofVector.setSize( this->getDofs() ); } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > void NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::setMu( const RealType& mu ) { this->mu = mu; } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > const typename NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::RealType& NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::getMu() const { return this->mu; } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > void NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::setR( const RealType& R ) { this->R = R; } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > const typename NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::RealType& NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::getR() const { return this->R; } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > void NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::setT( const RealType& T ) { this->T = T; } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > const typename NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::RealType& NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::getT() const { return this->T; } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > void NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::setHeatCapacityRatio( const RealType& gamma ) { this->gamma = gamma; } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > const typename NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::RealType& NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::getHeatCapacityRatio() const { return this->gamma; } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > void NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::setGravity( const RealType& gravity ) { this->gravity = gravity; } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > const typename NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::RealType& NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::getGravity() const { return this->gravity; } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > typename NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::VectorType& NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::getRho() { return this->rho; } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > const typename NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::VectorType& NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::getRho() const { return this->rho; } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > typename NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::VectorType& NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::getU1() { return this->u1; } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > const typename NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::VectorType& NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::getU1() const { return this->u1; } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > typename NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::VectorType& NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::getU2() { return this->u2; } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > const typename NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::VectorType& NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::getU2() const { return this->u2; } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > typename NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::VectorType& NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::getU() { return this->u; } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > const typename NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::VectorType& NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::getU() const { return this->u; } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > typename NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::VectorType& NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::getPressure() { return this->p; } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > const typename NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::VectorType& NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::getPressure() const { return this->p; } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > typename NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::VectorType& NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::getEnergy() { return this->energy; } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > const typename NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::VectorType& NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::getEnergy() const { return this->energy; } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > typename NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::IndexType NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::getDofs() const { return 4 * this->mesh->getDofs(); } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > void NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::bindDofVector( RealType* data ) { this->dofVector.bind( data, this->getDofs() ); } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > typename NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::DofVectorType& NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::getDofVector() { return this->dofVector; } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > template< typename Vector > void NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::updatePhysicalQuantities( const Vector& dofs_rho, const Vector& dofs_rho_u1, const Vector& dofs_rho_u2, const Vector& dofs_e ) { if( DeviceType ::getDevice() == Devices::HostDevice ) { const IndexType size = dofs_rho.getSize(); #ifdef HAVE_OPENMP #pragma omp parallel for, if( Devices::Host::isOMPEnabled() ) #endif for( IndexType c = 0; c < size; c++ ) { this->rho[ c ] = dofs_rho[ c ]; const RealType u1 = this->u1[ c ] = dofs_rho_u1[ c ] / dofs_rho[ c ]; const RealType u2 = this->u2[ c ] = dofs_rho_u2[ c ] / dofs_rho[ c ]; this->u[ c ] = ::sqrt( u1 * u1 + u2 * u2 ); // this->p[ c ] = dofs_rho[ c ] * this->R * this->T; this->p[ c ] = ( this->gamma - 1.0 ) * ( dofs_e[ c ] - 0.5 * this->rho[ c ] * ( this->u1[ c ] * this->u1[ c ] + this->u2[ c ] * this->u2[ c ] ) ); this->energy[ c ] = dofs_e[ c ]; // this->temperature[ c ] = this->p[ c ] / ( this->rho[ c ] * this->R ); } } } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > template< typename SolverVectorType > void NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::getExplicitUpdate( const RealType& time, const RealType& tau, SolverVectorType& u, SolverVectorType& fu ) { TNL_ASSERT_TRUE( this->advection, "advection scheme was not set" ); TNL_ASSERT_TRUE( this->u1Viscosity, "diffusion scheme was not set" ); TNL_ASSERT_TRUE( this->u2Viscosity, "diffusion scheme was not set" ); TNL_ASSERT_TRUE( this->boundaryConditions, "boundary conditions were not set" ); SharedVector< RealType, DeviceType, IndexType > dofs_rho, dofs_rho_u1, dofs_rho_u2, dofs_e, rho_t, rho_u1_t, rho_u2_t, e_t; const IndexType& dofs = this->mesh->getDofs(); dofs_rho.bind( &u.getData()[ 0 ], dofs ); dofs_rho_u1.bind( &u.getData()[ dofs ], dofs ); dofs_rho_u2.bind( &u.getData()[ 2 * dofs ], dofs ); dofs_e.bind( &u.getData()[ 3 * dofs ], dofs ); this->advection->setRho( dofs_rho ); this->advection->setRhoU1( dofs_rho_u1 ); this->advection->setRhoU2( dofs_rho_u2 ); this->advection->setE( dofs_e ); this->advection->setP( this->p ); this->energyViscosity->setFunction( this->energy ); rho_t.bind( &fu.getData()[ 0 ], dofs ); rho_u1_t.bind( &fu.getData()[ dofs ], dofs ); rho_u2_t.bind( &fu.getData()[ 2 * dofs ], dofs ); e_t.bind( &fu.getData()[ 3 * dofs ], dofs ); updatePhysicalQuantities( dofs_rho, dofs_rho_u1, dofs_rho_u2, dofs_e ); this->boundaryConditions->apply( time, tau, this->rho, this->u1, this->u2, this->energy ); const IndexType& xSize = this->mesh->getDimensions().x(); const IndexType& ySize = this->mesh->getDimensions().y(); if( DeviceType::getDevice() == Devices::HostDevice ) { for( IndexType i = 0; i < xSize; i++ ) { const IndexType c1 = mesh->getElementIndex( i, 0 ); const IndexType c2 = mesh->getElementIndex( i, 1 ); const IndexType c3 = mesh->getElementIndex( i, ySize - 1 ); const IndexType c4 = mesh->getElementIndex( i, ySize - 2 ); dofs_rho[ c1 ] = this->rho[ c1 ]; dofs_rho_u1[ c1 ] = this->rho[ c1 ] * this->u1[ c1 ]; dofs_rho_u2[ c1 ] = this->rho[ c1 ] * this->u2[ c1 ]; dofs_e[ c1 ] = this->energy[ c1 ]; /*dofs_e[ c1 ] = this->computeEnergy( this->rho[ c1 ], this->temperature[ c1 ], this->gamma, this->u1[ c1 ], this->u2[ c1 ] );*/ dofs_rho[ c3 ] = this->rho[ c3 ]; dofs_rho_u1[ c3 ] = this->rho[ c3 ] * this->u1[ c3 ]; dofs_rho_u2[ c3 ] = this->rho[ c3 ] * this->u2[ c3 ]; dofs_e[ c3 ] = this->energy[ c3 ]; /*dofs_e[ c3 ] = this->computeEnergy( this->rho[ c3 ], this->temperature[ c3 ], this->gamma, this->u1[ c3 ], this->u2[ c3 ] );*/ } for( IndexType j = 0; j < ySize; j++ ) { const IndexType c1 = mesh->getElementIndex( 0, j ); const IndexType c2 = mesh->getElementIndex( 1, j ); const IndexType c3 = mesh->getElementIndex( xSize - 1, j ); const IndexType c4 = mesh->getElementIndex( xSize - 2, j ); dofs_rho[ c1 ] = this->rho[ c1 ]; dofs_rho_u1[ c1 ] = this->rho[ c1 ] * this->u1[ c1 ]; dofs_rho_u2[ c1 ] = this->rho[ c1 ] * this->u2[ c1 ]; dofs_e[ c1 ] = this->energy[ c1 ]; /*dofs_e[ c1 ] = this->computeEnergy( this->rho[ c1 ], this->temperature[ c1 ], this->gamma, this->u1[ c1 ], this->u2[ c1 ] );*/ dofs_rho[ c3 ] = this->rho[ c3 ]; dofs_rho_u1[ c3 ] = this->rho[ c3 ] * this->u1[ c3 ]; dofs_rho_u2[ c3 ] = this->rho[ c3 ] * this->u2[ c3 ]; dofs_e[ c3 ] = this->energy[ c3 ]; /*dofs_e[ c3 ] = this->computeEnergy( this->rho[ c3 ], this->temperature[ c3 ], this->gamma, this->u1[ c3 ], this->u2[ c3 ] );*/ } } writePhysicalVariables( time, -4 ); #ifdef HAVE_OPENMP #pragma omp parallel for, if( Devices::Host::isOMPEnabled() ) #endif for( IndexType j = 0; j < ySize; j++ ) for( IndexType i = 0; i < xSize; i++ ) { IndexType c = this->mesh->getElementIndex( i, j ); if( i == 0 || j == 0 || i == xSize - 1 || j == ySize - 1 ) { rho_t[ c ] = rho_u1_t[ c ] = rho_u2_t[ c ] = e_t[ c ] = 0.0; continue; } this->advection->getExplicitUpdate( c, rho_t[ c ], rho_u1_t[ c ], rho_u2_t[ c ], e_t[ c ], tau ); // rho_u1_t[ c ] += ; // rho_u2_t[ c ] -= startUpCoefficient * this->gravity * this->rho[ c ]; /*** * Add the viscosity term */ /*rho_u1_t[ c ] += this->mu*( u1Viscosity->getDiffusion( c, 4.0/3.0, 1.0, 0.0 ) + u2Viscosity->getDiffusion( c, 0.0, 0.0, 1.0/3.0 ) ); rho_u2_t[ c ] += this->mu*( u2Viscosity->getDiffusion( c, 1.0, 4.0/3.0, 0.0 ) + u1Viscosity->getDiffusion( c, 0.0, 0.0, 1.0/3.0 ) ); RealType k = 2.495*pow( 400.0, 1.5 ) / ( 400.0 + 194.0 ); e_t[ c ] += this->mu*( u1Viscosity->getDiffusion( c, this->u1, this->u1, this->u2, 4.0/3.0, 1.0, -2.0/3.0 ) + u1Viscosity->getDiffusion( c, this->u1, this->u1, this->u2, 0.0, 0.0, 1.0 ) + u2Viscosity->getDiffusion( c, this->u2, this->u2, this->u1, 1.0, 4.0/3.0, -2.0/3.0 ) + u2Viscosity->getDiffusion( c, this->u2, this->u2, this->u1, 0.0, 0.0, 1.0 ) + k * energyViscosity->getDiffusion( c, 1.0, 1.0, 0.0 ) ); */ rho_u1_t[ c ] += this->mu * ( u1Viscosity->getDiffusion( c, 1.0, 1.0, 0.0 ) ); rho_u2_t[ c ] += this->mu * ( u2Viscosity->getDiffusion( c, 1.0, 1.0, 0.0 ) ); RealType k = 2.495 * pow( 400.0, 1.5 ) / ( 400.0 + 194.0 ); // cout << k << std::endl; /*e_t[ c ] += this->mu*( u1Viscosity->getDiffusion( c, this->u1, this->u1, this->u2, 1.0, 1.0, 0.0 ) + u2Viscosity->getDiffusion( c, this->u2, this->u2, this->u1, 1.0, 1.0, -0.0 ) );*/ // energyViscosity->getDiffusion( c, 1.0, 1.0, 0.0 ) ); // e_t[ c ] = 0.0; } } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > bool NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::writePhysicalVariables( const RealType& t, const IndexType step ) { SharedVector< RealType, DeviceType, IndexType > dofs_rho, dofs_rho_u1, dofs_rho_u2, dofs_e; const IndexType& dofs = mesh->getDofs(); dofs_rho.bind( &dofVector.getData()[ 0 ], dofs ); dofs_rho_u1.bind( &dofVector.getData()[ dofs ], dofs ); dofs_rho_u2.bind( &dofVector.getData()[ 2 * dofs ], dofs ); dofs_e.bind( &dofVector.getData()[ 3 * dofs ], dofs ); this->updatePhysicalQuantities( dofs_rho, dofs_rho_u1, dofs_rho_u2, dofs_e ); Vector< StaticVector< 2, RealType >, DeviceType, IndexType > u; u.setLike( u1 ); String fileName; for( IndexType i = 0; i < this->u1.getSize(); i++ ) u[ i ] = StaticVector< 2, RealType >( this->u1[ i ], this->u2[ i ] ); FileNameBaseNumberEnding( "u-", step, 5, ".tnl", fileName ); if( ! u.save( fileName ) ) return false; FileNameBaseNumberEnding( "rho-", step, 5, ".tnl", fileName ); if( ! this->rho.save( fileName ) ) return false; FileNameBaseNumberEnding( "p-", step, 5, ".tnl", fileName ); if( ! this->p.save( fileName ) ) return false; FileNameBaseNumberEnding( "e-", step, 5, ".tnl", fileName ); if( ! this->energy.save( fileName ) ) return false; return true; } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > bool NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::writeConservativeVariables( const RealType& t, const IndexType step ) { SharedVector< RealType, DeviceType, IndexType > dofs_rho, dofs_rho_u1, dofs_rho_u2, dofs_e; const IndexType& dofs = mesh->getDofs(); dofs_rho.bind( &dofVector.getData()[ 0 ], dofs ); dofs_rho_u1.bind( &dofVector.getData()[ dofs ], dofs ); dofs_rho_u2.bind( &dofVector.getData()[ 2 * dofs ], dofs ); dofs_e.bind( &dofVector.getData()[ 3 * dofs ], dofs ); String fileName; FileNameBaseNumberEnding( "rho-", step, 5, ".tnl", fileName ); if( ! dofs_rho.save( fileName ) ) return false; FileNameBaseNumberEnding( "rho-u1-", step, 5, ".tnl", fileName ); if( ! dofs_rho_u1.save( fileName ) ) return false; FileNameBaseNumberEnding( "rho-u2-", step, 5, ".tnl", fileName ); if( ! dofs_rho_u2.save( fileName ) ) return false; FileNameBaseNumberEnding( "e-", step, 5, ".tnl", fileName ); if( ! dofs_e.save( fileName ) ) return false; return true; } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > typename NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::RealType NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::computeEnergy( const RealType& rho, const RealType& pressure, const RealType& gamma, const RealType& u1, const RealType& u2 ) const { /*return rho * this->R * temperature / ( gamma - 1.0 ) + 0.5 * rho * ( u1*u1 + u2*u2 );*/ return pressure / ( gamma - 1.0 ) + 0.5 * rho * ( u1 * u1 + u2 * u2 ); } template< typename AdvectionScheme, typename DiffusionScheme, typename BoundaryConditions > template< typename DofVector > bool NavierStokesSolver< AdvectionScheme, DiffusionScheme, BoundaryConditions >::writeExplicitRhs( const RealType& t, const IndexType step, DofVector& rhs ) { SharedVector< RealType, DeviceType, IndexType > dofs_rho, dofs_rho_u1, dofs_rho_u2, dofs_e; const IndexType& dofs = mesh->getDofs(); dofs_rho.bind( &rhs.getData()[ 0 ], dofs ); dofs_rho_u1.bind( &rhs.getData()[ dofs ], dofs ); dofs_rho_u2.bind( &rhs.getData()[ 2 * dofs ], dofs ); dofs_e.bind( &rhs.getData()[ 3 * dofs ], dofs ); String fileName; FileNameBaseNumberEnding( "rho-t-", step, 5, ".tnl", fileName ); if( ! dofs_rho.save( fileName ) ) return false; FileNameBaseNumberEnding( "rho-u1-t-", step, 5, ".tnl", fileName ); if( ! dofs_rho_u1.save( fileName ) ) return false; FileNameBaseNumberEnding( "rho-u2-t-", step, 5, ".tnl", fileName ); if( ! dofs_rho_u2.save( fileName ) ) return false; FileNameBaseNumberEnding( "e-t-", step, 5, ".tnl", fileName ); if( ! dofs_e.save( fileName ) ) return false; return true; } } // namespace TNL
manage_radiation_calls.c
/* This source file is part of the Geophysical Fluids Modeling Framework (GAME), which is released under the MIT license. Github repository: https://github.com/OpenNWP/GAME */ /* This file manages the calls to the radiation routines. */ #include <stdlib.h> #include <stdio.h> #include "../game_types.h" #include "../radiation/radiation.h" int create_rad_array_scalar(double [], double [], int); int create_rad_array_scalar_h(double [], double [], int); int create_rad_array_mass_den(double [], double [], int); int create_rad_array_vector(double [], double [], int); int remap_to_original(double [], double [], int); int remap_to_original_scalar_h(double [], double [], int); int call_radiation(State *state, Soil *soil, Grid *grid, Dualgrid *dualgrid, State *state_tendency, Diagnostics *diagnostics, Forcings *forcings, Irreversible_quantities *irrev, Config *config, double delta_t, double time_coordinate) { printf("Starting update of radiative fluxes ...\n"); int no_of_scalars = NO_OF_SCALARS_RAD; int no_of_constituents = NO_OF_CONSTITUENTS; int no_of_condensed_constituents = NO_OF_CONDENSED_CONSTITUENTS; int no_of_layers = NO_OF_LAYERS; // loop over all radiation blocks #pragma omp parallel for for (int rad_block_index = 0; rad_block_index < NO_OF_RAD_BLOCKS; ++rad_block_index) { Radiation *radiation = calloc(1, sizeof(Radiation)); // remapping all the arrays create_rad_array_scalar_h(grid -> latitude_scalar, radiation -> lat_scal, rad_block_index); create_rad_array_scalar_h(grid -> longitude_scalar, radiation -> lon_scal, rad_block_index); create_rad_array_scalar_h(soil -> temperature, radiation -> temp_sfc, rad_block_index); create_rad_array_scalar_h(grid -> sfc_albedo, radiation -> sfc_albedo, rad_block_index); create_rad_array_scalar(grid -> z_scalar, radiation -> z_scal, rad_block_index); create_rad_array_vector(grid -> z_vector, radiation -> z_vect, rad_block_index); create_rad_array_mass_den(state -> rho, radiation -> rho, rad_block_index); create_rad_array_scalar(diagnostics -> temperature_gas, radiation -> temp, rad_block_index); // calling the radiation routine // RTE+RRTMGP if (config -> rad_on == 1) { calc_radiative_flux_convergence(radiation -> lat_scal, radiation -> lon_scal, radiation -> z_scal, radiation -> z_vect, radiation -> rho, radiation -> temp, radiation -> rad_tend, radiation -> temp_sfc, radiation -> sfc_sw_in, radiation -> sfc_lw_out, radiation -> sfc_albedo, &no_of_scalars, &no_of_layers, &no_of_constituents, &no_of_condensed_constituents, &time_coordinate); } // Held-Suarez if (config -> rad_on == 2) { held_suar(radiation -> lat_scal, radiation -> z_scal, radiation -> rho, radiation -> temp, radiation -> rad_tend); } // filling the actual radiation tendency remap_to_original(radiation -> rad_tend, forcings -> radiation_tendency, rad_block_index); remap_to_original_scalar_h(radiation -> sfc_sw_in, forcings -> sfc_sw_in, rad_block_index); remap_to_original_scalar_h(radiation -> sfc_lw_out, forcings -> sfc_lw_out, rad_block_index); free(radiation); } printf("Update of radiative fluxes completed.\n"); return 0; } int create_rad_array_scalar(double in[], double out[], int rad_block_index) { /* cuts out a slice of a scalar field for hand-over to the radiation routine (done for RAM efficiency reasons) */ int layer_index, h_index; // loop over all elements of the resulting array for (int i = 0; i < NO_OF_SCALARS_RAD; ++i) { layer_index = i/NO_OF_SCALARS_RAD_PER_LAYER; h_index = i - layer_index*NO_OF_SCALARS_RAD_PER_LAYER; out[i] = in[rad_block_index*NO_OF_SCALARS_RAD_PER_LAYER + h_index + layer_index*NO_OF_SCALARS_H]; } return 0; } int create_rad_array_scalar_h(double in[], double out[], int rad_block_index) { /* cuts out a slice of a horizontal scalar field for hand-over to the radiation routine (done for RAM efficiency reasons) */ // loop over all elements of the resulting array for (int i = 0; i < NO_OF_SCALARS_RAD_PER_LAYER; ++i) { out[i] = in[rad_block_index*NO_OF_SCALARS_RAD_PER_LAYER + i]; } return 0; } int create_rad_array_mass_den(double in[], double out[], int rad_block_index) { /* same thing as create_rad_array_scalar, only for a mass density field */ int layer_index, h_index; for (int const_id = 0; const_id < NO_OF_CONSTITUENTS; ++const_id) { // loop over all elements of the resulting array for (int i = 0; i < NO_OF_SCALARS_RAD; ++i) { layer_index = i/NO_OF_SCALARS_RAD_PER_LAYER; h_index = i - layer_index*NO_OF_SCALARS_RAD_PER_LAYER; out[const_id*NO_OF_SCALARS_RAD + i] = in[const_id*NO_OF_SCALARS + rad_block_index*NO_OF_SCALARS_RAD_PER_LAYER + h_index + layer_index*NO_OF_SCALARS_H]; } } return 0; } int create_rad_array_vector(double in[], double out[], int rad_block_index) { /* cuts out a slice of a vector field for hand-over to the radiation routine (done for RAM efficiency reasons), only the vertical vector points are taken into account since only they are needed by the radiation */ int layer_index, h_index; // loop over all elements of the resulting array for (int i = 0; i < NO_OF_SCALARS_RAD + NO_OF_SCALARS_RAD_PER_LAYER; ++i) { layer_index = i/NO_OF_SCALARS_RAD_PER_LAYER; h_index = i - layer_index*NO_OF_SCALARS_RAD_PER_LAYER; out[i] = in[rad_block_index*NO_OF_SCALARS_RAD_PER_LAYER + h_index + layer_index*NO_OF_VECTORS_PER_LAYER]; } return 0; } int remap_to_original(double in[], double out[], int rad_block_index) { /* reverses what create_rad_array_scalar has done */ int layer_index, h_index; // loop over all elements of the resulting array for (int i = 0; i < NO_OF_SCALARS_RAD; ++i) { layer_index = i/NO_OF_SCALARS_RAD_PER_LAYER; h_index = i - layer_index*NO_OF_SCALARS_RAD_PER_LAYER; out[rad_block_index*NO_OF_SCALARS_RAD_PER_LAYER + h_index + layer_index*NO_OF_SCALARS_H] = in[i]; } return 0; } int remap_to_original_scalar_h(double in[], double out[], int rad_block_index) { /* reverses what create_rad_array_scalar_h has done */ // loop over all elements of the resulting array for (int i = 0; i < NO_OF_SCALARS_RAD_PER_LAYER; ++i) { out[rad_block_index*NO_OF_SCALARS_RAD_PER_LAYER + i] = in[i]; } return 0; }
bfs.h
// This code is based on commit 6ac1af of https://github.com/sbeamer/gapbs/blob/master/src/bfs.cc . // The code is modified by the authors of Sppart so that it can be used with data structures of Sppart and it can compute the SSSP distance. // Copyright (c) 2015, The Regents of the University of California (Regents) // See LICENSE.txt for license details #pragma once #include "bitmap.h" #include "pvector.h" #include "sliding_queue.h" #include "graph.hpp" /* GAP Benchmark Suite Kernel: Breadth-First Search (BFS) Author: Scott Beamer Will return parent array for a BFS traversal from a source vertex This BFS implementation makes use of the Direction-Optimizing approach [1]. It uses the alpha and beta parameters to determine whether to switch search directions. For representing the frontier, it uses a SlidingQueue for the top-down approach and a Bitmap for the bottom-up approach. To reduce false-sharing for the top-down approach, thread-local QueueBuffer's are used. To save time computing the number of edges exiting the frontier, this implementation precomputes the degrees in bulk at the beginning by storing them in parent array as negative numbers. Thus the encoding of parent is: parent[x] < 0 implies x is unvisited and parent[x] = -out_degree(x) parent[x] >= 0 implies x been visited [1] Scott Beamer, Krste Asanović, and David Patterson. "Direction-Optimizing Breadth-First Search." International Conference on High Performance Computing, Networking, Storage and Analysis (SC), Salt Lake City, Utah, November 2012. */ namespace gapbs{ typedef int32_t NodeID; template<class XADJ_INT, class FLOAT> // assuming FLOAT is float or double int64_t BUStep(const Sppart::Graph<XADJ_INT> &g, pvector<NodeID> &parent, Bitmap &front, Bitmap &next, FLOAT* const dists, FLOAT depth) { int64_t awake_count = 0; next.reset(); // #pragma omp parallel for reduction(+ : awake_count) schedule(dynamic, 1024) // !!! This cause non-deterministic depth values #pragma omp parallel for reduction(+ : awake_count) for (NodeID u=0; u < g.nv; u++) { if (parent[u] < 0) { for (XADJ_INT k = g.xadj[u]; k < g.xadj[u+1]; ++k){ const int v = g.adjncy[k]; if (front.get_bit(v)) { parent[u] = v; dists[u] = depth; awake_count++; next.set_bit(u); break; } } } } return awake_count; } template<class XADJ_INT, class FLOAT> // assuming FLOAT is float or double int64_t TDStep(const Sppart::Graph<XADJ_INT> &g, pvector<NodeID> &parent, SlidingQueue<NodeID> &queue, FLOAT* const dists, FLOAT depth) { int64_t scout_count = 0; #pragma omp parallel { QueueBuffer<NodeID> lqueue(queue); #pragma omp for reduction(+ : scout_count) for (auto q_iter = queue.begin(); q_iter < queue.end(); q_iter++) { NodeID u = *q_iter; for (XADJ_INT k = g.xadj[u]; k < g.xadj[u+1]; ++k){ const int v = g.adjncy[k]; NodeID curr_val = parent[v]; if (curr_val < 0) { if (compare_and_swap(parent[v], curr_val, u)) { lqueue.push_back(v); dists[v] = depth; scout_count += -curr_val; } } } } lqueue.flush(); } return scout_count; } void QueueToBitmap(const SlidingQueue<NodeID> &queue, Bitmap &bm) { #pragma omp parallel for for (auto q_iter = queue.begin(); q_iter < queue.end(); q_iter++) { NodeID u = *q_iter; bm.set_bit_atomic(u); } } template<class XADJ_INT> void BitmapToQueue(const Sppart::Graph<XADJ_INT> &g, const Bitmap &bm, SlidingQueue<NodeID> &queue) { #pragma omp parallel { QueueBuffer<NodeID> lqueue(queue); #pragma omp for for (NodeID n=0; n < g.nv; n++) if (bm.get_bit(n)) lqueue.push_back(n); lqueue.flush(); } queue.slide_window(); } template<class XADJ_INT> pvector<NodeID> InitParent(const Sppart::Graph<XADJ_INT> &g) { pvector<NodeID> parent(g.nv); #pragma omp parallel for for (NodeID n=0; n < g.nv; n++) parent[n] = g.degree(n) != 0 ? -g.degree(n) : -1; return parent; } template<class XADJ_INT, class FLOAT> // assuming FLOAT is float or double pvector<NodeID> DOBFS(const Sppart::Graph<XADJ_INT> &g, NodeID source, FLOAT* const dists, const bool force_top_down, int alpha = 15, int beta = 18) { pvector<NodeID> parent = InitParent(g); parent[source] = source; SlidingQueue<NodeID> queue(g.nv); queue.push_back(source); queue.slide_window(); Bitmap curr(g.nv); curr.reset(); Bitmap front(g.nv); front.reset(); int64_t edges_to_check = g.xadj[g.nv]; int64_t scout_count = g.degree(source); FLOAT depth = 0.0; dists[source] = depth; while (!queue.empty()) { depth += 1.0; // if (scout_count > edges_to_check / alpha) { if ( !force_top_down && (scout_count > edges_to_check / alpha) ) { int64_t awake_count, old_awake_count; QueueToBitmap(queue, front); awake_count = queue.size(); queue.slide_window(); do { old_awake_count = awake_count; awake_count = BUStep(g, parent, front, curr, dists, depth); front.swap(curr); } while ((awake_count >= old_awake_count) || (awake_count > g.nv / beta)); BitmapToQueue(g, front, queue); scout_count = 1; } else { edges_to_check -= scout_count; scout_count = TDStep(g, parent, queue, dists, depth); queue.slide_window(); } } #pragma omp parallel for for (NodeID n = 0; n < g.nv; n++) if (parent[n] < -1) parent[n] = -1; return parent; } } // namespace
5239.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 "atax.h" /* Array initialization. */ static void init_array (int nx, int ny, DATA_TYPE POLYBENCH_2D(A,NX,NY,nx,ny), DATA_TYPE POLYBENCH_1D(x,NY,ny)) { int i, j; for (i = 0; i < ny; i++) x[i] = i * M_PI; for (i = 0; i < nx; i++) for (j = 0; j < ny; j++) A[i][j] = ((DATA_TYPE) i*(j+1)) / nx; } /* 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 nx, DATA_TYPE POLYBENCH_1D(y,NX,nx)) { int i; for (i = 0; i < nx; i++) { fprintf (stderr, DATA_PRINTF_MODIFIER, y[i]); if (i % 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_atax(int nx, int ny, DATA_TYPE POLYBENCH_2D(A,NX,NY,nx,ny), DATA_TYPE POLYBENCH_1D(x,NY,ny), DATA_TYPE POLYBENCH_1D(y,NY,ny), DATA_TYPE POLYBENCH_1D(tmp,NX,nx)) { int i, j; #pragma scop #pragma omp parallel num_threads(4) { #pragma omp for schedule(dynamic, 8) for (i = 0; i < _PB_NY; i++) y[i] = 0; #pragma omp for private (j) schedule(dynamic, 8) for (i = 0; i < _PB_NX; i++) { tmp[i] = 0; for (j = 0; j < _PB_NY; j++) tmp[i] = tmp[i] + A[i][j] * x[j]; for (j = 0; j < _PB_NY; j++) y[j] = y[j] + A[i][j] * tmp[i]; } } #pragma endscop } int main(int argc, char** argv) { /* Retrieve problem size. */ int nx = NX; int ny = NY; /* Variable declaration/allocation. */ POLYBENCH_2D_ARRAY_DECL(A, DATA_TYPE, NX, NY, nx, ny); POLYBENCH_1D_ARRAY_DECL(x, DATA_TYPE, NY, ny); POLYBENCH_1D_ARRAY_DECL(y, DATA_TYPE, NY, ny); POLYBENCH_1D_ARRAY_DECL(tmp, DATA_TYPE, NX, nx); /* Initialize array(s). */ init_array (nx, ny, POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(x)); /* Start timer. */ polybench_start_instruments; /* Run kernel. */ kernel_atax (nx, ny, POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(x), POLYBENCH_ARRAY(y), POLYBENCH_ARRAY(tmp)); /* 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(nx, POLYBENCH_ARRAY(y))); /* Be clean. */ POLYBENCH_FREE_ARRAY(A); POLYBENCH_FREE_ARRAY(x); POLYBENCH_FREE_ARRAY(y); POLYBENCH_FREE_ARRAY(tmp); return 0; }
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] = 16; tile_size[1] = 16; tile_size[2] = 32; tile_size[3] = 512; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); 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<=floord(Nt-1,2);t1++) { lbp=max(ceild(t1,2),ceild(4*t1-Nt+2,4)); ubp=min(floord(4*Nt+Nz-9,16),floord(8*t1+Nz+2,16)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(0,ceild(t1-3,4)),ceild(16*t2-Nz-19,32));t3<=min(min(min(floord(4*Nt+Ny-9,32),floord(8*t1+Ny+7,32)),floord(16*t2+Ny+3,32)),floord(16*t1-16*t2+Nz+Ny+5,32));t3++) { for (t4=max(max(max(0,ceild(t1-63,64)),ceild(16*t2-Nz-499,512)),ceild(32*t3-Ny-499,512));t4<=min(min(min(min(floord(4*Nt+Nx-9,512),floord(8*t1+Nx+7,512)),floord(16*t2+Nx+3,512)),floord(32*t3+Nx+19,512)),floord(16*t1-16*t2+Nz+Nx+5,512));t4++) { for (t5=max(max(max(max(max(0,ceild(16*t2-Nz+5,4)),ceild(32*t3-Ny+5,4)),ceild(512*t4-Nx+5,4)),2*t1),4*t1-4*t2+1);t5<=min(min(min(min(min(floord(16*t1-16*t2+Nz+10,4),Nt-1),2*t1+3),4*t2+2),8*t3+6),128*t4+126);t5++) { for (t6=max(max(16*t2,4*t5+4),-16*t1+16*t2+8*t5-15);t6<=min(min(16*t2+15,-16*t1+16*t2+8*t5),4*t5+Nz-5);t6++) { for (t7=max(32*t3,4*t5+4);t7<=min(32*t3+31,4*t5+Ny-5);t7++) { lbv=max(512*t4,4*t5+4); ubv=min(512*t4+511,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; }
9847.c
// this source is derived from CHILL AST originally from file '/uufs/chpc.utah.edu/common/home/u1142914/lib/ytopt_vinu/polybench/polybench-code/stencils/heat-3d/kernel.c' as parsed by frontend compiler rose void kernel_heat_3d(int tsteps, int n, double A[200 + 0][200 + 0][200 + 0], double B[200 + 0][200 + 0][200 + 0]) { int t12; int t10; int t8; int t6; int t4; int t2; for (t2 = 1; t2 <= 1000; t2 += 1) { #pragma omp parallel for private(t4,t6,t8,t10,t12,t14) for (t4 = 1; t4 <= n - 2; t4 += 32) for (t6 = t4; t6 <= (t4 + 31 < n - 2 ? t4 + 31 : n - 2); t6 += 1) for (t8 = 1; t8 <= n - 2; t8 += 16) for (t10 = t8; t10 <= (t8 + 15 < n - 2 ? t8 + 15 : n - 2); t10 += 1) for (t12 = 1; t12 <= n - 2; t12 += 1) B[t6][t10][t12] = 0.125 * (A[t6 + 1][t10][t12] - 2 * A[t6][t10][t12] + A[t6 - 1][t10][t12]) + 0.125 * (A[t6][t10 + 1][t12] - 2 * A[t6][t10][t12] + A[t6][t10 - 1][t12]) + 0.125 * (A[t6][t10][t12 + 1] - 2 * A[t6][t10][t12] + A[t6][t10][t12 - 1]) + A[t6][t10][t12]; #pragma omp parallel for private(t4,t6,t8,t10,t12,t14) for (t4 = 1; t4 <= n - 2; t4 += 32) for (t6 = t4; t6 <= (t4 + 31 < n - 2 ? t4 + 31 : n - 2); t6 += 1) for (t8 = 1; t8 <= n - 2; t8 += 16) for (t10 = t8; t10 <= (t8 + 15 < n - 2 ? t8 + 15 : n - 2); t10 += 1) for (t12 = 1; t12 <= n - 2; t12 += 1) A[t6][t10][t12] = 0.125 * (B[t6 + 1][t10][t12] - 2 * B[t6][t10][t12] + B[t6 - 1][t10][t12]) + 0.125 * (B[t6][t10 + 1][t12] - 2 * B[t6][t10][t12] + B[t6][t10 - 1][t12]) + 0.125 * (B[t6][t10][t12 + 1] - 2 * B[t6][t10][t12] + B[t6][t10][t12 - 1]) + B[t6][t10][t12]; } }
pmv-OpenMP-c.c
#include <stdlib.h> #include <stdio.h> #include <time.h> //#define PRINT_ALL #define VECTOR_GLOBAL //#define VECTOR_DYNAMIC #ifdef VECTOR_GLOBAL #define MAX 1073741824 //=2^10 double v[MAX], m[MAX][MAX], r[MAX]; #endif int main(int argc,char** argv){ if (argc<2){ printf("Faltan nº componentes del vector \n"); exit(-1); } struct timespec cgt1,cgt2; double ncgt; //para tiempo de ejecución int i, j; unsigned int N = atoi(argv[1]); // Máximo N =2^32 -1=4294967295 (sizeof(unsigned int) = 4 B) #ifdef VECTOR_GLOBAL if (N>MAX) N=MAX; #endif #ifdef VECTOR_DYNAMIC double *v, **m, *r; v = (double*) malloc(N*sizeof(double)); // malloc necesita el tamaño en bytes m = (double**) malloc(N*sizeof(double*)); //si no hay espacio suficiente malloc devuelve NULL for (i=0; i<N; i++) m[i] = (double*) malloc(N*sizeof(double)); r = (double*) malloc(N*sizeof(double)); if ((v==NULL) || (m==NULL) || (r==NULL)) { printf("Error en la reserva de espacio para los vectores\n"); exit(-2); } #endif //Inicializar vector y matriz #pragma omp parallel for for (i=0; i<N; i++) { v[i] = N*0.1+ i*0.1; for (j=0; j<N; j++) m[i][j] = v[i]*0.1+j*0.1; } //Comprobamos la incialización #ifdef PRINT_ALL printf(" Vector:\n"); for (i=0; i<N; i++) { printf("\t%f", v[i]); } printf("\n\n Matriz: \n"); for (i=0; i<N; i++) { for (j=0; j<N; j++) printf("\t%f", m[i][j]); printf("\n\n"); } #endif clock_gettime(CLOCK_REALTIME,&cgt1); //Calcular el producto int sum; for (i=0; i<N; i++) { sum = 0; #pragma omp parallel for reduction(+:sum) private(j) for (j=0; j<N; j++) sum += m[i][j]*v[j]; r[i] = sum; } clock_gettime(CLOCK_REALTIME, &cgt2); ncgt = (double) (cgt2.tv_sec - cgt1.tv_sec) + (double) ((cgt2.tv_nsec - cgt1.tv_nsec)/(1.e+9)); //Imprimir resultado del producto printf(" Resultado:\n"); #ifdef PRINT_ALL for (i=0; i<N; i++) { printf("\t%f", r[i]); } printf("\n"); #else printf("Primer valor: %f \t Último valor: %f \n", r[0], r[N-1]); #endif printf("\n Tiempo de ejecución(s): %11.9f\n", ncgt); #ifdef VECTOR_DYNAMIC free(v); // libera el espacio reservado para v free(m); // libera el espacio reservado para m free(r); #endif return 0; }
team.c
/* Copyright (C) 2005-2015 Free Software Foundation, Inc. Contributed by Richard Henderson <rth@redhat.com>. This file is part of the GNU Offloading and Multi Processing Library (libgomp). Libgomp 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. Libgomp 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/>. */ /* This file handles the maintainence of threads in response to team creation and termination. */ #include "libgomp.h" #include <stdlib.h> #include <string.h> /* This attribute contains PTHREAD_CREATE_DETACHED. */ pthread_attr_t gomp_thread_attr; /* This key is for the thread destructor. */ pthread_key_t gomp_thread_destructor; /* This is the libgomp per-thread data structure. */ #if defined HAVE_TLS || defined USE_EMUTLS __thread struct gomp_thread gomp_tls_data; #else pthread_key_t gomp_tls_key; #endif /* This structure is used to communicate across pthread_create. */ struct gomp_thread_start_data { void (*fn) (void *); void *fn_data; struct gomp_team_state ts; struct gomp_task *task; struct gomp_thread_pool *thread_pool; unsigned int place; bool nested; }; /* This function is a pthread_create entry point. This contains the idle loop in which a thread waits to be called up to become part of a team. */ static void * gomp_thread_start (void *xdata) { struct gomp_thread_start_data *data = xdata; struct gomp_thread *thr; struct gomp_thread_pool *pool; void (*local_fn) (void *); void *local_data; #if defined HAVE_TLS || defined USE_EMUTLS thr = &gomp_tls_data; #else struct gomp_thread local_thr; thr = &local_thr; pthread_setspecific (gomp_tls_key, thr); #endif gomp_sem_init (&thr->release, 0); /* Extract what we need from data. */ local_fn = data->fn; local_data = data->fn_data; thr->thread_pool = data->thread_pool; thr->ts = data->ts; thr->task = data->task; thr->place = data->place; thr->ts.team->ordered_release[thr->ts.team_id] = &thr->release; /* Make thread pool local. */ pool = thr->thread_pool; if (data->nested) { struct gomp_team *team = thr->ts.team; struct gomp_task *task = thr->task; gomp_barrier_wait (&team->barrier); local_fn (local_data); gomp_team_barrier_wait_final (&team->barrier); gomp_finish_task (task); gomp_barrier_wait_last (&team->barrier); } else { pool->threads[thr->ts.team_id] = thr; gomp_barrier_wait (&pool->threads_dock); do { struct gomp_team *team = thr->ts.team; struct gomp_task *task = thr->task; local_fn (local_data); gomp_team_barrier_wait_final (&team->barrier); gomp_finish_task (task); gomp_barrier_wait (&pool->threads_dock); local_fn = thr->fn; local_data = thr->data; thr->fn = NULL; } while (local_fn); } gomp_sem_destroy (&thr->release); thr->thread_pool = NULL; thr->task = NULL; return NULL; } /* Create a new team data structure. */ struct gomp_team * gomp_new_team (unsigned nthreads) { struct gomp_team *team; size_t size; int i; size = sizeof (*team) + nthreads * (sizeof (team->ordered_release[0]) + sizeof (team->implicit_task[0])); team = gomp_malloc (size); team->work_share_chunk = 8; #ifdef HAVE_SYNC_BUILTINS team->single_count = 0; #else gomp_mutex_init (&team->work_share_list_free_lock); #endif team->work_shares_to_free = &team->work_shares[0]; gomp_init_work_share (&team->work_shares[0], false, nthreads); team->work_shares[0].next_alloc = NULL; team->work_share_list_free = NULL; team->work_share_list_alloc = &team->work_shares[1]; for (i = 1; i < 7; i++) team->work_shares[i].next_free = &team->work_shares[i + 1]; team->work_shares[i].next_free = NULL; team->nthreads = nthreads; gomp_barrier_init (&team->barrier, nthreads); gomp_sem_init (&team->master_release, 0); team->ordered_release = (void *) &team->implicit_task[nthreads]; team->ordered_release[0] = &team->master_release; gomp_mutex_init (&team->task_lock); team->task_queue = NULL; team->task_count = 0; team->task_queued_count = 0; team->task_running_count = 0; team->work_share_cancelled = 0; team->team_cancelled = 0; return team; } /* Free a team data structure. */ static void free_team (struct gomp_team *team) { gomp_barrier_destroy (&team->barrier); gomp_mutex_destroy (&team->task_lock); free (team); } /* Allocate and initialize a thread pool. */ static struct gomp_thread_pool *gomp_new_thread_pool (void) { struct gomp_thread_pool *pool = gomp_malloc (sizeof(struct gomp_thread_pool)); pool->threads = NULL; pool->threads_size = 0; pool->threads_used = 0; pool->last_team = NULL; return pool; } static void gomp_free_pool_helper (void *thread_pool) { struct gomp_thread *thr = gomp_thread (); struct gomp_thread_pool *pool = (struct gomp_thread_pool *) thread_pool; gomp_barrier_wait_last (&pool->threads_dock); gomp_sem_destroy (&thr->release); thr->thread_pool = NULL; thr->task = NULL; pthread_exit (NULL); } /* Free a thread pool and release its threads. */ void gomp_free_thread (void *arg __attribute__((unused))) { struct gomp_thread *thr = gomp_thread (); struct gomp_thread_pool *pool = thr->thread_pool; if (pool) { if (pool->threads_used > 0) { int i; for (i = 1; i < pool->threads_used; i++) { struct gomp_thread *nthr = pool->threads[i]; nthr->fn = gomp_free_pool_helper; nthr->data = pool; } /* This barrier undocks threads docked on pool->threads_dock. */ gomp_barrier_wait (&pool->threads_dock); /* And this waits till all threads have called gomp_barrier_wait_last in gomp_free_pool_helper. */ gomp_barrier_wait (&pool->threads_dock); /* Now it is safe to destroy the barrier and free the pool. */ gomp_barrier_destroy (&pool->threads_dock); #ifdef HAVE_SYNC_BUILTINS __sync_fetch_and_add (&gomp_managed_threads, 1L - pool->threads_used); #else gomp_mutex_lock (&gomp_managed_threads_lock); gomp_managed_threads -= pool->threads_used - 1L; gomp_mutex_unlock (&gomp_managed_threads_lock); #endif } free (pool->threads); if (pool->last_team) free_team (pool->last_team); free (pool); thr->thread_pool = NULL; } if (thr->task != NULL) { struct gomp_task *task = thr->task; gomp_end_task (); free (task); } } /* Launch a team. */ void gomp_team_start (void (*fn) (void *), void *data, unsigned nthreads, unsigned flags, struct gomp_team *team) { struct gomp_thread_start_data *start_data; struct gomp_thread *thr, *nthr; struct gomp_task *task; struct gomp_task_icv *icv; bool nested; struct gomp_thread_pool *pool; unsigned i, n, old_threads_used = 0; pthread_attr_t thread_attr, *attr; unsigned long nthreads_var; char bind, bind_var; unsigned int s = 0, rest = 0, p = 0, k = 0; unsigned int affinity_count = 0; struct gomp_thread **affinity_thr = NULL; thr = gomp_thread (); nested = thr->ts.team != NULL; if (__builtin_expect (thr->thread_pool == NULL, 0)) { thr->thread_pool = gomp_new_thread_pool (); thr->thread_pool->threads_busy = nthreads; pthread_setspecific (gomp_thread_destructor, thr); } pool = thr->thread_pool; task = thr->task; icv = task ? &task->icv : &gomp_global_icv; if (__builtin_expect (gomp_places_list != NULL, 0) && thr->place == 0) gomp_init_affinity (); /* Always save the previous state, even if this isn't a nested team. In particular, we should save any work share state from an outer orphaned work share construct. */ team->prev_ts = thr->ts; thr->ts.team = team; thr->ts.team_id = 0; ++thr->ts.level; if (nthreads > 1) ++thr->ts.active_level; thr->ts.work_share = &team->work_shares[0]; thr->ts.last_work_share = NULL; #ifdef HAVE_SYNC_BUILTINS thr->ts.single_count = 0; #endif thr->ts.static_trip = 0; thr->task = &team->implicit_task[0]; nthreads_var = icv->nthreads_var; if (__builtin_expect (gomp_nthreads_var_list != NULL, 0) && thr->ts.level < gomp_nthreads_var_list_len) nthreads_var = gomp_nthreads_var_list[thr->ts.level]; bind_var = icv->bind_var; if (bind_var != omp_proc_bind_false && (flags & 7) != omp_proc_bind_false) bind_var = flags & 7; bind = bind_var; if (__builtin_expect (gomp_bind_var_list != NULL, 0) && thr->ts.level < gomp_bind_var_list_len) bind_var = gomp_bind_var_list[thr->ts.level]; gomp_init_task (thr->task, task, icv); team->implicit_task[0].icv.nthreads_var = nthreads_var; team->implicit_task[0].icv.bind_var = bind_var; if (nthreads == 1) return; i = 1; if (__builtin_expect (gomp_places_list != NULL, 0)) { /* Depending on chosen proc_bind model, set subpartition for the master thread and initialize helper variables P and optionally S, K and/or REST used by later place computation for each additional thread. */ p = thr->place - 1; switch (bind) { case omp_proc_bind_true: case omp_proc_bind_close: if (nthreads > thr->ts.place_partition_len) { /* T > P. S threads will be placed in each place, and the final REM threads placed one by one into the already occupied places. */ s = nthreads / thr->ts.place_partition_len; rest = nthreads % thr->ts.place_partition_len; } else s = 1; k = 1; break; case omp_proc_bind_master: /* Each thread will be bound to master's place. */ break; case omp_proc_bind_spread: if (nthreads <= thr->ts.place_partition_len) { /* T <= P. Each subpartition will have in between s and s+1 places (subpartitions starting at or after rest will have s places, earlier s+1 places), each thread will be bound to the first place in its subpartition (except for the master thread that can be bound to another place in its subpartition). */ s = thr->ts.place_partition_len / nthreads; rest = thr->ts.place_partition_len % nthreads; rest = (s + 1) * rest + thr->ts.place_partition_off; if (p < rest) { p -= (p - thr->ts.place_partition_off) % (s + 1); thr->ts.place_partition_len = s + 1; } else { p -= (p - rest) % s; thr->ts.place_partition_len = s; } thr->ts.place_partition_off = p; } else { /* T > P. Each subpartition will have just a single place and we'll place between s and s+1 threads into each subpartition. */ s = nthreads / thr->ts.place_partition_len; rest = nthreads % thr->ts.place_partition_len; thr->ts.place_partition_off = p; thr->ts.place_partition_len = 1; k = 1; } break; } } else bind = omp_proc_bind_false; /* We only allow the reuse of idle threads for non-nested PARALLEL regions. This appears to be implied by the semantics of threadprivate variables, but perhaps that's reading too much into things. Certainly it does prevent any locking problems, since only the initial program thread will modify gomp_threads. */ if (!nested) { old_threads_used = pool->threads_used; if (nthreads <= old_threads_used) n = nthreads; else if (old_threads_used == 0) { n = 0; gomp_barrier_init (&pool->threads_dock, nthreads); } else { n = old_threads_used; /* Increase the barrier threshold to make sure all new threads arrive before the team is released. */ gomp_barrier_reinit (&pool->threads_dock, nthreads); } /* Not true yet, but soon will be. We're going to release all threads from the dock, and those that aren't part of the team will exit. */ pool->threads_used = nthreads; /* If necessary, expand the size of the gomp_threads array. It is expected that changes in the number of threads are rare, thus we make no effort to expand gomp_threads_size geometrically. */ if (nthreads >= pool->threads_size) { pool->threads_size = nthreads + 1; pool->threads = gomp_realloc (pool->threads, pool->threads_size * sizeof (struct gomp_thread_data *)); } /* Release existing idle threads. */ for (; i < n; ++i) { unsigned int place_partition_off = thr->ts.place_partition_off; unsigned int place_partition_len = thr->ts.place_partition_len; unsigned int place = 0; if (__builtin_expect (gomp_places_list != NULL, 0)) { switch (bind) { case omp_proc_bind_true: case omp_proc_bind_close: if (k == s) { ++p; if (p == (team->prev_ts.place_partition_off + team->prev_ts.place_partition_len)) p = team->prev_ts.place_partition_off; k = 1; if (i == nthreads - rest) s = 1; } else ++k; break; case omp_proc_bind_master: break; case omp_proc_bind_spread: if (k == 0) { /* T <= P. */ if (p < rest) p += s + 1; else p += s; if (p == (team->prev_ts.place_partition_off + team->prev_ts.place_partition_len)) p = team->prev_ts.place_partition_off; place_partition_off = p; if (p < rest) place_partition_len = s + 1; else place_partition_len = s; } else { /* T > P. */ if (k == s) { ++p; if (p == (team->prev_ts.place_partition_off + team->prev_ts.place_partition_len)) p = team->prev_ts.place_partition_off; k = 1; if (i == nthreads - rest) s = 1; } else ++k; place_partition_off = p; place_partition_len = 1; } break; } if (affinity_thr != NULL || (bind != omp_proc_bind_true && pool->threads[i]->place != p + 1) || pool->threads[i]->place <= place_partition_off || pool->threads[i]->place > (place_partition_off + place_partition_len)) { unsigned int l; if (affinity_thr == NULL) { unsigned int j; if (team->prev_ts.place_partition_len > 64) affinity_thr = gomp_malloc (team->prev_ts.place_partition_len * sizeof (struct gomp_thread *)); else affinity_thr = gomp_alloca (team->prev_ts.place_partition_len * sizeof (struct gomp_thread *)); memset (affinity_thr, '\0', team->prev_ts.place_partition_len * sizeof (struct gomp_thread *)); for (j = i; j < old_threads_used; j++) { if (pool->threads[j]->place > team->prev_ts.place_partition_off && (pool->threads[j]->place <= (team->prev_ts.place_partition_off + team->prev_ts.place_partition_len))) { l = pool->threads[j]->place - 1 - team->prev_ts.place_partition_off; pool->threads[j]->data = affinity_thr[l]; affinity_thr[l] = pool->threads[j]; } pool->threads[j] = NULL; } if (nthreads > old_threads_used) memset (&pool->threads[old_threads_used], '\0', ((nthreads - old_threads_used) * sizeof (struct gomp_thread *))); n = nthreads; affinity_count = old_threads_used - i; } if (affinity_count == 0) break; l = p; if (affinity_thr[l - team->prev_ts.place_partition_off] == NULL) { if (bind != omp_proc_bind_true) continue; for (l = place_partition_off; l < place_partition_off + place_partition_len; l++) if (affinity_thr[l - team->prev_ts.place_partition_off] != NULL) break; if (l == place_partition_off + place_partition_len) continue; } nthr = affinity_thr[l - team->prev_ts.place_partition_off]; affinity_thr[l - team->prev_ts.place_partition_off] = (struct gomp_thread *) nthr->data; affinity_count--; pool->threads[i] = nthr; } else nthr = pool->threads[i]; place = p + 1; } else nthr = pool->threads[i]; nthr->ts.team = team; nthr->ts.work_share = &team->work_shares[0]; nthr->ts.last_work_share = NULL; nthr->ts.team_id = i; nthr->ts.level = team->prev_ts.level + 1; nthr->ts.active_level = thr->ts.active_level; nthr->ts.place_partition_off = place_partition_off; nthr->ts.place_partition_len = place_partition_len; #ifdef HAVE_SYNC_BUILTINS nthr->ts.single_count = 0; #endif nthr->ts.static_trip = 0; nthr->task = &team->implicit_task[i]; nthr->place = place; gomp_init_task (nthr->task, task, icv); team->implicit_task[i].icv.nthreads_var = nthreads_var; team->implicit_task[i].icv.bind_var = bind_var; nthr->fn = fn; nthr->data = data; team->ordered_release[i] = &nthr->release; } if (__builtin_expect (affinity_thr != NULL, 0)) { /* If AFFINITY_THR is non-NULL just because we had to permute some threads in the pool, but we've managed to find exactly as many old threads as we'd find without affinity, we don't need to handle this specially anymore. */ if (nthreads <= old_threads_used ? (affinity_count == old_threads_used - nthreads) : (i == old_threads_used)) { if (team->prev_ts.place_partition_len > 64) free (affinity_thr); affinity_thr = NULL; affinity_count = 0; } else { i = 1; /* We are going to compute the places/subpartitions again from the beginning. So, we need to reinitialize vars modified by the switch (bind) above inside of the loop, to the state they had after the initial switch (bind). */ switch (bind) { case omp_proc_bind_true: case omp_proc_bind_close: if (nthreads > thr->ts.place_partition_len) /* T > P. S has been changed, so needs to be recomputed. */ s = nthreads / thr->ts.place_partition_len; k = 1; p = thr->place - 1; break; case omp_proc_bind_master: /* No vars have been changed. */ break; case omp_proc_bind_spread: p = thr->ts.place_partition_off; if (k != 0) { /* T > P. */ s = nthreads / team->prev_ts.place_partition_len; k = 1; } break; } /* Increase the barrier threshold to make sure all new threads and all the threads we're going to let die arrive before the team is released. */ if (affinity_count) gomp_barrier_reinit (&pool->threads_dock, nthreads + affinity_count); } } if (i == nthreads) goto do_release; } if (__builtin_expect (nthreads + affinity_count > old_threads_used, 0)) { long diff = (long) (nthreads + affinity_count) - (long) old_threads_used; if (old_threads_used == 0) --diff; #ifdef HAVE_SYNC_BUILTINS __sync_fetch_and_add (&gomp_managed_threads, diff); #else gomp_mutex_lock (&gomp_managed_threads_lock); gomp_managed_threads += diff; gomp_mutex_unlock (&gomp_managed_threads_lock); #endif } attr = &gomp_thread_attr; if (__builtin_expect (gomp_places_list != NULL, 0)) { size_t stacksize; pthread_attr_init (&thread_attr); pthread_attr_setdetachstate (&thread_attr, PTHREAD_CREATE_DETACHED); if (! pthread_attr_getstacksize (&gomp_thread_attr, &stacksize)) pthread_attr_setstacksize (&thread_attr, stacksize); attr = &thread_attr; } start_data = gomp_alloca (sizeof (struct gomp_thread_start_data) * (nthreads-i)); /* Launch new threads. */ for (; i < nthreads; ++i) { pthread_t pt; int err; start_data->ts.place_partition_off = thr->ts.place_partition_off; start_data->ts.place_partition_len = thr->ts.place_partition_len; start_data->place = 0; if (__builtin_expect (gomp_places_list != NULL, 0)) { switch (bind) { case omp_proc_bind_true: case omp_proc_bind_close: if (k == s) { ++p; if (p == (team->prev_ts.place_partition_off + team->prev_ts.place_partition_len)) p = team->prev_ts.place_partition_off; k = 1; if (i == nthreads - rest) s = 1; } else ++k; break; case omp_proc_bind_master: break; case omp_proc_bind_spread: if (k == 0) { /* T <= P. */ if (p < rest) p += s + 1; else p += s; if (p == (team->prev_ts.place_partition_off + team->prev_ts.place_partition_len)) p = team->prev_ts.place_partition_off; start_data->ts.place_partition_off = p; if (p < rest) start_data->ts.place_partition_len = s + 1; else start_data->ts.place_partition_len = s; } else { /* T > P. */ if (k == s) { ++p; if (p == (team->prev_ts.place_partition_off + team->prev_ts.place_partition_len)) p = team->prev_ts.place_partition_off; k = 1; if (i == nthreads - rest) s = 1; } else ++k; start_data->ts.place_partition_off = p; start_data->ts.place_partition_len = 1; } break; } start_data->place = p + 1; if (affinity_thr != NULL && pool->threads[i] != NULL) continue; gomp_init_thread_affinity (attr, p); } start_data->fn = fn; start_data->fn_data = data; start_data->ts.team = team; start_data->ts.work_share = &team->work_shares[0]; start_data->ts.last_work_share = NULL; start_data->ts.team_id = i; start_data->ts.level = team->prev_ts.level + 1; start_data->ts.active_level = thr->ts.active_level; #ifdef HAVE_SYNC_BUILTINS start_data->ts.single_count = 0; #endif start_data->ts.static_trip = 0; start_data->task = &team->implicit_task[i]; gomp_init_task (start_data->task, task, icv); team->implicit_task[i].icv.nthreads_var = nthreads_var; team->implicit_task[i].icv.bind_var = bind_var; start_data->thread_pool = pool; start_data->nested = nested; err = pthread_create (&pt, attr, gomp_thread_start, start_data++); if (err != 0) gomp_fatal ("Thread creation failed: %s", strerror (err)); } if (__builtin_expect (gomp_places_list != NULL, 0)) pthread_attr_destroy (&thread_attr); do_release: gomp_barrier_wait (nested ? &team->barrier : &pool->threads_dock); /* Decrease the barrier threshold to match the number of threads that should arrive back at the end of this team. The extra threads should be exiting. Note that we arrange for this test to never be true for nested teams. If AFFINITY_COUNT is non-zero, the barrier as well as gomp_managed_threads was temporarily set to NTHREADS + AFFINITY_COUNT. For NTHREADS < OLD_THREADS_COUNT, AFFINITY_COUNT if non-zero will be always at least OLD_THREADS_COUNT - NTHREADS. */ if (__builtin_expect (nthreads < old_threads_used, 0) || __builtin_expect (affinity_count, 0)) { long diff = (long) nthreads - (long) old_threads_used; if (affinity_count) diff = -affinity_count; gomp_barrier_reinit (&pool->threads_dock, nthreads); #ifdef HAVE_SYNC_BUILTINS __sync_fetch_and_add (&gomp_managed_threads, diff); #else gomp_mutex_lock (&gomp_managed_threads_lock); gomp_managed_threads += diff; gomp_mutex_unlock (&gomp_managed_threads_lock); #endif } if (__builtin_expect (affinity_thr != NULL, 0) && team->prev_ts.place_partition_len > 64) free (affinity_thr); } /* Terminate the current team. This is only to be called by the master thread. We assume that we must wait for the other threads. */ void gomp_team_end (void) { struct gomp_thread *thr = gomp_thread (); struct gomp_team *team = thr->ts.team; /* This barrier handles all pending explicit threads. As #pragma omp cancel parallel might get awaited count in team->barrier in a inconsistent state, we need to use a different counter here. */ gomp_team_barrier_wait_final (&team->barrier); if (__builtin_expect (team->team_cancelled, 0)) { struct gomp_work_share *ws = team->work_shares_to_free; do { struct gomp_work_share *next_ws = gomp_ptrlock_get (&ws->next_ws); if (next_ws == NULL) gomp_ptrlock_set (&ws->next_ws, ws); gomp_fini_work_share (ws); ws = next_ws; } while (ws != NULL); } else gomp_fini_work_share (thr->ts.work_share); gomp_end_task (); thr->ts = team->prev_ts; if (__builtin_expect (thr->ts.team != NULL, 0)) { #ifdef HAVE_SYNC_BUILTINS __sync_fetch_and_add (&gomp_managed_threads, 1L - team->nthreads); #else gomp_mutex_lock (&gomp_managed_threads_lock); gomp_managed_threads -= team->nthreads - 1L; gomp_mutex_unlock (&gomp_managed_threads_lock); #endif /* This barrier has gomp_barrier_wait_last counterparts and ensures the team can be safely destroyed. */ gomp_barrier_wait (&team->barrier); } if (__builtin_expect (team->work_shares[0].next_alloc != NULL, 0)) { struct gomp_work_share *ws = team->work_shares[0].next_alloc; do { struct gomp_work_share *next_ws = ws->next_alloc; free (ws); ws = next_ws; } while (ws != NULL); } gomp_sem_destroy (&team->master_release); #ifndef HAVE_SYNC_BUILTINS gomp_mutex_destroy (&team->work_share_list_free_lock); #endif if (__builtin_expect (thr->ts.team != NULL, 0) || __builtin_expect (team->nthreads == 1, 0)) free_team (team); else { struct gomp_thread_pool *pool = thr->thread_pool; if (pool->last_team) free_team (pool->last_team); pool->last_team = team; } } /* Constructors for this file. */ static void __attribute__((constructor)) initialize_team (void) { #if !defined HAVE_TLS && !defined USE_EMUTLS static struct gomp_thread initial_thread_tls_data; pthread_key_create (&gomp_tls_key, NULL); pthread_setspecific (gomp_tls_key, &initial_thread_tls_data); #endif if (pthread_key_create (&gomp_thread_destructor, gomp_free_thread) != 0) gomp_fatal ("could not create thread pool destructor."); } static void __attribute__((destructor)) team_destructor (void) { /* Without this dlclose on libgomp could lead to subsequent crashes. */ pthread_key_delete (gomp_thread_destructor); } struct gomp_task_icv * gomp_new_icv (void) { struct gomp_thread *thr = gomp_thread (); struct gomp_task *task = gomp_malloc (sizeof (struct gomp_task)); gomp_init_task (task, NULL, &gomp_global_icv); thr->task = task; pthread_setspecific (gomp_thread_destructor, thr); return &task->icv; }