fault detection - uppsala universityfigure 2: seismic data set, without highlighted faults the...

92

Upload: others

Post on 31-Mar-2021

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Department of Scientific Computing

Fault Detection

Methods for automatic detectionof faults in seismic data

Magnus Hedlund, Patrik Holmstr�om, Mattias Nyberg

Report in Scienti�c Computing Advanced Course

June 2009

PROJECTREPORT

Page 2: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can
Page 3: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Abstract

The aim of the project is to solve the difficult problem of automaticfault detection in seismic images. Special attention is given to the task ofdetection of massive faults, an area where automatic methods have hadlimited success.

This report describes the methodology, different solutions tried andinteresting results achieved during the project. Emphasis is placed onthe most successful method, a cross correlation method (CCM) basedon a large tilting correlation kernel. The tilting kernel is used to avoidspurious detection of dipping sedimentary layer. The size of the kernelrenders the CCM relatively resistant to small areas of noise.

The project work was done as a part of the Advanced Course in Sci-entific Computing at Uppsala University. The problem formulation anddata was provided by Schlumberger Information Solutions, Oslo, Norway.

Keywords: fault detection, image analysis, crosscorrelation

1

Page 4: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

2

Page 5: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Contents

1 Introduction 51.1 Problem description . . . . . . . . . . . . . . . . . . . . . . . . . 5

2 Development strategy 62.1 Description of the tools . . . . . . . . . . . . . . . . . . . . . . . 7

2.1.1 MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . 72.1.2 MEX API . . . . . . . . . . . . . . . . . . . . . . . . . . . 72.1.3 Profiling tools . . . . . . . . . . . . . . . . . . . . . . . . . 7

2.2 Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

3 Theory 93.1 Cross-Correlation Method . . . . . . . . . . . . . . . . . . . . . . 9

3.1.1 Background . . . . . . . . . . . . . . . . . . . . . . . . . . 93.1.2 Standard Cross-Correlation . . . . . . . . . . . . . . . . . 93.1.3 Weighting . . . . . . . . . . . . . . . . . . . . . . . . . . . 103.1.4 Applied to an area . . . . . . . . . . . . . . . . . . . . . . 113.1.5 Fault or Bend? . . . . . . . . . . . . . . . . . . . . . . . . 113.1.6 Bilinear filtering . . . . . . . . . . . . . . . . . . . . . . . 133.1.7 Angle Estimation . . . . . . . . . . . . . . . . . . . . . . . 133.1.8 Minimized Angle Set (MAS) . . . . . . . . . . . . . . . . 143.1.9 Extended Kernel . . . . . . . . . . . . . . . . . . . . . . . 14

3.2 Segmentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183.2.1 Background . . . . . . . . . . . . . . . . . . . . . . . . . . 183.2.2 Basic segmentation versus Watershed segmentation . . . . 183.2.3 Crisp versus Fuzzy segmentation . . . . . . . . . . . . . . 193.2.4 Proof of concept implementation . . . . . . . . . . . . . . 19

3.3 Motion Estimation . . . . . . . . . . . . . . . . . . . . . . . . . . 213.3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . 213.3.2 Assumptions . . . . . . . . . . . . . . . . . . . . . . . . . 213.3.3 Block matching . . . . . . . . . . . . . . . . . . . . . . . . 223.3.4 Modified Levenshtein distance . . . . . . . . . . . . . . . . 23

4 Results 244.1 Cross-Correlation Method . . . . . . . . . . . . . . . . . . . . . . 24

4.1.1 Configuration . . . . . . . . . . . . . . . . . . . . . . . . . 244.1.2 Original Set . . . . . . . . . . . . . . . . . . . . . . . . . . 244.1.3 Afterprocessed Set . . . . . . . . . . . . . . . . . . . . . . 264.1.4 Other Data Sets . . . . . . . . . . . . . . . . . . . . . . . 274.1.5 Angle Estimation . . . . . . . . . . . . . . . . . . . . . . . 294.1.6 Performance . . . . . . . . . . . . . . . . . . . . . . . . . 294.1.7 Performance improvements . . . . . . . . . . . . . . . . . 32

4.2 Segmentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344.3 Motion Estimation . . . . . . . . . . . . . . . . . . . . . . . . . . 35

4.3.1 Block Matching . . . . . . . . . . . . . . . . . . . . . . . . 35

3

Page 6: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

5 Discussion 365.1 Cross-Correlation Method . . . . . . . . . . . . . . . . . . . . . . 36

5.1.1 Alghoritm implementation 3D . . . . . . . . . . . . . . . . 365.1.2 Continiuty restraints on faults . . . . . . . . . . . . . . . 365.1.3 Optimization . . . . . . . . . . . . . . . . . . . . . . . . . 365.1.4 Further performance improvements . . . . . . . . . . . . . 37

6 Conclusion 38

7 Acknowledgements 39

8 Appendix 418.1 CCM Profiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418.2 CCM-Implementation (m-file version) . . . . . . . . . . . . . . . 458.3 CCM-Implementation (MEX version) . . . . . . . . . . . . . . . 578.4 CCM Additional Profiling Data . . . . . . . . . . . . . . . . . . . 688.5 Segmentation Implementation . . . . . . . . . . . . . . . . . . . . 718.6 Angle Estimation Implementation . . . . . . . . . . . . . . . . . 868.7 Motion Estimation Implementation . . . . . . . . . . . . . . . . . 88

4

Page 7: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

1 Introduction

The analysis of fault lines has interesting applications in scientific and com-mercial fields. One large user of fault detection is the hydrocarbon explorationbusiness.

The seismic data The data sets used in these analyses is acquired by meansof reflection seismology where a controlled seismic pulse is generated and lin-ear arrays of hydrophones or seismographs record the reflected seismic waves.The data set is then reconstructed from this data as a three-dimensional im-age using convolution with a band-limited wavelet. To move from data to amodel is an inverse problem and the technique is similar to the one used for3D ultrasound images and computer axial tomography scans (CAT scan). Theimage constructed from the data represents the varying reflective properties ofsedimentary layers of different composition.

Old problem The problem of automatically classifying faults is still not com-pletely solved after 20 years of research. Faults are considered to be difficultto analyze due to their discontinuous nature. Especially the task of classifyinglong faults has been problematic. There exists a lot of prior art in the field using3D attributes such as variance, coherency, chaos, curvature, AntTracking, etc.

1.1 Problem description

The purpose of the project is to let a group of students without prior experiencein the seismic field approach the problem with “fresh eyes”. If possible it issuggested that they apply relevant experience from other fields of study to theproblem at hand. The aim of the project is to deliver an executable programthat takes a seismic image as input and generated an output image highlightingthe areas likely to be faults.

Figure 1: Seismic data set, with highlighted faults

5

Page 8: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Figure 2: Seismic data set, without highlighted faults

The challenge of fault detection lies in translating a task that the eye and thebrain can easily perform to the computer. To be able to do this it is importantto figure out what it is the eye and brain is actually looking for when detectingfaults.

After some thought we decided that the brain looks at large areas or eventhe entire image to find and correlate the discontinuities that the faults cause.It is however not immediately obvious how this can be translated into machinevision. We used this idea to focus on methods that considers a large area oreven the entire data set.

2 Development strategy

Since the project required us to rapidly evaluate many different algorithms andideas in a short period of time we put some thought into how we could beas productive as possible. Any strict development methodology would be tooconstricting so we choose instead to be inspired by the thoughts of the various‘Extreme Programming’ schools. The most important philosophy would be toimplement and evaluate as soon as possible to avoid wasting time on ideas thatdon’t work out. By using synthetic tests we could allow testing to start earlierin the process and then progress to real data.

This development strategy drove our selection of development platforms.Traditional low level languages like C or FORTRAN commonly used in sci-entific computing provide the programmer with a powerful tool that is onlylimited by the programmer’s skill and imagination. Such languages can withthe appropriate support libraries and optimizing compilers create programs withvery good performance. The speed however comes at the cost of a slower andmore difficult development process. This is especially apparent when it comesto visualization of the large data sets typically created in scientific computing.

The other option is to use a high level language like MATLAB or Python.The difference between these high level languages and more traditional lan-

6

Page 9: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

guages are that they are not precompiled into executable files but are insteadinterpreted at runtime. This process is slow and not well suited to the kind ofoptimization that is routinely done by a compiler to speed up the execution ofa program.

The advantages of the high level languages are that they are very flexible andsupport faster program development. This is mainly a result of removing theneed to handle low level details like memory allocation (a large source of timeconsuming code bugs) and providing lots of powerful libraries to support theprogrammer. These libraries usually have good performance if they are goodfit for your algorithm and when it comes to visualization you can do with a fewlines of code what would take pages of code and days of development in C orFORTRAN.

2.1 Description of the tools

We choose to use MATLAB as our primary development platform due to itswealth of support libraries and ease of development. If the initial results ofan algorithm where interesting but performance was found lacking we plannedto use the built in MATLAB profiling tool and the possibility of linking C orFORTRAN programs with MATLAB using the MEX (MATLAB Executable)application programming interface (API) to find and remove bottlenecks in thecode.

2.1.1 MATLAB

MATLAB needs little introduction as it is one of the most used tools in scienceand engineering. MATLAB is a high level language that contains a wide arrayof tools and libraries which makes it suitable for rapid development.

2.1.2 MEX API

The MEX application programming interface (API) provides a developer withthe option to call a dynamically linked external program from MATLAB in thesame way that built-in MATLAB functions are called. The opposite, to callMATLAB functions from within a C or FORTRAN program is also possibleusing the external interface functions and adds another layer of flexibility.

To be able to use MEX an external compiler supported by MATLAB must befound and integrated. We used GCC since it covers all development platformsand then also used Microsoft Visual C++ and SUN cc for better performanceon the platforms where they are supported.

By using MEX the developer has to shoulder the burden of dynamic memoryallocation and many other bookkeeping operations that are usually handledautomatically by MATLAB engine. The improvement in performance over pureMATLAB code varies a lot from case to case but is often substantial.

2.1.3 Profiling tools

The purpose of all profiling tools is to count the number of calls made to thedifferent functions in a program and to measure the time spent executing them.This gives the developer the needed information to understand the behaviorof the program during execution. Since optimization is a time consuming and

7

Page 10: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

complex task it would otherwise be easy to approach the problem the wrongway or spend time optimizing parts of the program that don not contributemuch to the total running time.

MATLAB Profiler The built in MATLAB profiler is a very powerful andeasy to use. The statistics gathered are presented in a HTML like format usinggraphs and tables. The hyperlinked structure can be traversed so that the dif-ferent levels of the program can be examined. Since MATLAB is an interpretedlanguage it can give very detailed information compared too many other profil-ers. It can even provide information on the time spent executing every singleline of the source code. It is however limited when it comes to compiled internallibraries and dynamically linked external libraries.

C Profilers The MEX functions cannot be profiled using the MATLAB Pro-filer since it is limited to profiling MATLAB source code. Many options areavailable but we choose to use the combination of the open source profiler GProfand the free Code Analyst profiler from AMD. The GProf profiler is less pow-erful than Code Analyst but works on all platforms used during the project(Solaris, MacOS X and Windows XP/Vista) while CodeAnalyst is limited toLinux and Windows machines with AMD processors.

Visual Studio C++ The free Visual C++ 2008 Express Edition develop-ment environment from Microsoft was used for the development work on MEXC code as it integrates well with MATLAB. The major advantage is the de-bugger included that can easily be used with MEX files called from MATLAB.Another advantage is that the CodeAnalyst profiler can be integrated.

2.2 Methodology

The aim of our development methodology is to attempt to use the strengthsof both low level and high level languages where they are most needed. Themost important property is to maintain fast development of algorithms so thebaseline is to use MATLAB as long as possible and only optimize when theexecution time becomes too long for efficient evaluation.

Step 1 The first step is to write clean straightforward code in MATLAB with-out considering the performance. This has the advantage of quickly producinga result that can be evaluated. Premature optimization at this step is only awaste of time and produces source code that is harder to understand.

Step 2 If the preliminary results are interesting enough to proceed with butthe performance is lacking the next step is to use a profiler on the program.This gives a good understanding of where in the code the program spends itsexecution time. It is important to remember that only the parts where a sub-stantial amount of time is spent are candidates for optimization. For now weonly focus on the optimizations that we can perform using only MATLAB code.This usually means that slow loop constructs are replaced with matrix or vectoroperation.

8

Page 11: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Step 3 The next step is to rewrite slow parts of the code using the MEXinterface. In well structured code this can be easily done by replacing a call toa MATAB function with a MEX version with the same functionality written inC. This can give a large gain for relatively little effort since we only focus on theparts of the code that most require it which is typically only a small fraction ofthe total.

Step 4 The final step is to write the entire core of the program in a low levellanguage. This minimizes the cost of transitioning between the MATLAB andMEX environments. MATLAB can still be used to ease development by pre-processing of input data, visualization of the output and as a source of powerfullibrary calls from within the MEX file. The C source code also becomes anexcellent resource of already debugged code if an implementation using only Cis later wanted.

At all steps in the process it is important to evaluate if the performance ofthe code warrants further work or if time is better spent elsewhere.

3 Theory

3.1 Cross-Correlation Method (CCM)

3.1.1 Background

Figure 3: Two kernels

This method is based upon the observation thatthe reflectivity layers in the data seem to havebecome vertically translated around faults. If welook at the two line pairs in figure 1, one caneasily see that the layers under the two red lineswill be almost identical. The green lines however,seem to fit better if the lines would be displacedvertically. The layers seem to be a little bit loweron the right side.

CCM uses these displacements to detect faults. Cross-correlation is a math-ematical function which rates how like two datasets are. The output is calledthe correlation r. One possible parameter is to time-lag one of the datasets ksamples. We denote this time-lag displacement since that is what really happensin our line pairs.

3.1.2 Standard Cross-Correlation

Figure 4: Sampled line

Cross-correlation is a measure ofhow similar two 1D datasets are asa function of displacement. It is de-fined as:

ra,b(k) =∑∞

i=−∞ a[i]b[k + i]

If we sample along the left red line infigure 3, the result will be something like in figure 4. A plot of cross-correlation

9

Page 12: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

of the red and green pair respectively is shown in figure 5. Note the red max-ima in origo, and the displacement of the green maxima. This displacementindicates a fault, and is the essence of CCM!

Figure 5: Crosscorrelation as a function of displacement

3.1.3 Weighting

The above method is very good at detecting the stasticially most likely dis-placement for two infinte datasets. When we try to detect faults, we will workwith about one-hundred samples at a time. Since this is a far from an infiniteset, the edge effects are very disruptive. Note how fast r(k) declines with k’sdistance from origo (figure 5). This is because every value outside the sampleset is zero-padded, which results in lesser amounts of non-zero products in theinfinite sum. To counteract this, we need to bias the standard cross-correlation.We used this variant:

ra,b(k) = 1N−|k|

∑Ni=1 a[i]b[k + i]

Figure 6: Weighted crosscorrelation as a function of displacement

10

Page 13: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Intuitively, this is cross-correlation per number of non-zero products. It’sa cross-correlation average of the available data. The same data sets will nowproduce a result like in figure 6. The measurements around zero will alwaysbe more accurate, since more data is available for the averaging. The extremecase, when we are on one of the edges will result in only one non-zero product,which can produce very large (and erroneous) answers. This effect made us puta restraint (denoted limit) on the displacement k:

k ≤ |N − limit|

This method now have two outputs. Firstly, the maximum correlation: rmax =max[r(k)]∀k

Also, we have the k which corresponds to the maximum r. r(kmax) = rmax

3.1.4 Applied to an area

Figure 7: Left image is raw data. right image showsthe maximum displacement k, computed for eachpoint of the left image.

If we collect line pairs(from now on denoted ker-nels) for every point in a2d dataset, we can see ifthis method is capable ofdetecting obvious faults.Figure 7 contains raw dataand a processed version.The processed version isa plot of kmax for eachpoint. It is obvious fromthis image, that correla-tion clearly can detect ifthe reflectivity field is sta-tionary. All the homoge-nous regions have little orno displacement, while the fault regions are well marked. Note the breadth ofthe detection line. This actually corresponds to the width of the kernel (and isone of the configuration variables in our implementation).

3.1.5 Fault or Bend?

Figure 8: Tilted kernel, with kmax = 0.

Consider figure 8. In this dataset,the layers of reflectivity can nolonger be assumed to be horisontal.We call this phenomenon groundbending. Displacement algorithmslike the one we’ve looked at so farwill detect two things:

• Faults, due to irregularities inpattern

11

Page 14: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

• Ground Bend (unwanted!)

To compensate for this inherentweakness, we must isolate the sig-nals from the faults somehow. Tilt-ing the kernel is one effective way to deal with this. This implied several newadditions to the algoritm. Firstly, when we tilt the kernel, we will ask for sam-ple information in points which are not defined in the data. Therefore, we usedBilinear Filtering to interpolate the information in between pixels. Possibilityof tilting adds another dimension to the problem, since we will produce valuesof rmax and kmax for each angle of the kernel tilt. We decided which angleswere most relevant by three different techniques: figure 6. a tilted kernel, withkmax about 0.

• Angle Estimation

• MAS

• Extended Kernel (efficient!)

12

Page 15: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

3.1.6 Bilinear filtering

Figure 9: Bilinearfiltering

Bilinear filtering in short is a weighted average of the fourclosest pixels.pavg(x, y) = y(xp3 + (1− x)p4) + (1− y)(xp1 + (1− x)p2)where x and y is the relative distance between the pixels.This method proves to be an efficient sample interpolator.

3.1.7 Angle Estimation

It is important to be able to determine the local directionof the sedimentary horizon to avoid classifying dips in thesedimentary layers as faults. One way of doing this isto estimate the angle beforehand and then calculate thecross correlation kernel using this angle.

The basis for this method is the realization that the striped pattern of thesedimentary layers causes a strong line in the Fourier transform that has adirection that is perpendicular to the direction of the layers. This is causedby the strong sinus wave characteristics of the alternating sedimentary layersand is similar to some of the techniques used in optical character recognitionto estimate orientation of lines of text. This line can then be detected usingstandard line detection algorithms. To remove the stronger influence of thelonger diagonals compared to horizontal or vertical lines [2] the a circular maskis applied to the Fourier transform (fig. 10b).

(a) A typical data windowused by the algorithm.

(b) Resulting Fourier trans-form after application of cir-cular mask. Notice theslightly angled vertical lineperpendicular to the angleof the sedimentary layers.

Figure 10: Angle estimation

To detect the line we choose to use the Radon transform[1] that performsan integral transform of the data by calculating the integral on the data alongseries of parameterized lines that cover the entire image. This integral will haveits maximum response at a line that goes through the center of the Fouriertransform.

Due to problems with this alghoritm (discussed in the results section), wedid not use this method and had try something else.

13

Page 16: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

3.1.8 Minimized Angle Set (MAS)

Figure 11: MAS do not always pickthe correct angle.

This method is basically this:

• For each point and angle of thedataset find kmax and rmax.

• For each point, select the angle thatproduces the smallest kmax.

This method is very straightforward andsimple, and produced surprisingly goodresults. One problem with this however,is that the angle produced is not alwaysaligned with the ground layers. This phe-nomenon is because the layers are peri-odic, and when sampled can actually havesmaller optimal displacement than the one with correct angle.

3.1.9 Extended Kernel

Figure 12: Extended Kernel.

So far, the CCM has only worked withsimple kernels (ie one line pair). An ex-tended kernel consists of two (or more)line pairs. See figure 7 for an example. Bycomparing the results from these two linepairs, we can more accurately determinethe correct angle. If this is accomplished,we can succesfully isolate the faults.

DAC-map To understand how weshould compare the extra outputs fromthe Extended Kernel, consider figure 8.We call this a DAC-map (because the axisare Displacement, Angle and Correlation). This is the correlation output forone point in the dataset, with displacement and angles as inputs.

14

Page 17: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Geometrical Observation We know that: r = r(k, angle). If we collectdata for two different line pairs, we will have two sets of r. The connectionbetween these two sets can be seen in figure 9. If the first line pair is placedL from origo, then the second one is placed dL from origo. Then, because ofuniformity, the displacement for the outer line pair should be d times larger.

Figure 13: The two line pairs are connected by similar triangles.

If we use this knowledge, we can combine the information from the twoDAC-maps the Double Kernel generate. By stretching the outer line pair DAC-map by a factor d along the displacement dimension, and then extracting themiddle part of the image, we will have two different DACs with comparableinformation.

See figure 10. It consists of two DAC-maps, for the different line pairs in adouble kernel. The view is now from above (top down from the z-axis). Notethat the strongest red line have different slopes.

An elementwise multiplication of these two maps result in the map shownin figure 11. The last step in this algoritm is just to to extract the rmax fromthis image.

This method outputs three different data per point.

• rmax.

15

Page 18: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

• kmax.

• Estimated angle

Figure 14: DAC-map.

Figure 15: DAC-map for inner resp. out line pairs. View from above.

16

Page 19: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Figure 16: Elementwise product of two DAC-images.

17

Page 20: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

3.2 Segmentation

3.2.1 Background

Segmentation is a technique from image analysis that is used to logically sep-arate different objects in an image from each other and from the background.The separated objects can then be further processed to extract metadata fromthe object. Examples of such metadata properties are length of perimeter, orien-tation, extreme points etc. The idea is to use segmentation to extract metadatathat can be used either detect directly or alternatively to enhance detection offaults detected by other means. The primary feature of interest studied duringthe project is the coordinates of the endpoints of the segmented objects butother features like curvature have also been considered.

The idea is to use segmentation to extract metadata that can be used ei-ther detect directly or alternatively to enhance detection of faults detected byother means. The primary feature of interest studied during the project is thecoordinates of the endpoints of the segmented objects but other features likecurvature have also been considered.

3.2.2 Basic segmentation versus Watershed segmentation

The sedimentary layers in the seismic data are very distinct and can easily besegmented using a simple threshold based segmentation method. The resultingsegmentation is however not able to separate overlapping or adjacent sedimen-tary layers that have the same reflective properties. This caused us to considera more advanced Watershed segmentation approach[4].

Figure 17: Simple segmentation technique cannot separate overlapping and ad-jacent sedimentary layers.

The watershed segmentation algorithm is widely used to perform segmenta-tion of partially overlapping objects. A threshold is used on the data to generatea binary image and a distance transform is applied on the binary image. Ob-jects are then separated based on local maxima in the distance transform. Themethod is however prone to over-segmentation and in this case the problemis severe. This is partially caused by the extreme elongation of the objectswhich increases the number of local maxima. If the parameters are changed in

18

Page 21: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

an attempt to avoid over-segmentation a pure watershed method exhibits noadvantage over basic segmentation while still showing some over-segmentation.

Figure 18: The watershed segmentation algorithm separates objects better buthas a high degree of over-segmentation.

The most robust approach to solve the over-segmentation problem would beto use post-processing techniques to merge related segments. One such tech-nique would be to use the Region Split and Merge[5] algorithm using preserva-tion or increase in elongation of objects as a primary criterion. This was lookedinto but implementation time was estimated to be very long so this was notproceeded with.

3.2.3 Crisp versus Fuzzy segmentation

Fuzzy set theory is a general applicable technique that is used instead of classicset theory (crisp sets) when it is desirable to avoid having to prematurely makefinal decisions about membership[13]. In contrast with crisp sets, elements infuzzy sets have a membership function that is able to impart different degreesof set membership instead of a bivalent condition.

Several approaches of using fuzzy set techniques to improve separation ofobjects were investigated or implemented[6][7][8][9]. However the advantage ofusing fuzzy logic to preserve data for later decision-making steps only presentedan advantage over other techniques if further processing steps like the RegionSplit and Merge algorithm was added. Thus we made no use of any fuzzy settechniques.

3.2.4 Proof of concept implementation

A limited test case was implemented to evaluate the algorithms ability to en-hance fault detection when used in addition with another algorithm. To mini-mize further development work the basic segmentation method using thresholdswas used and a simple but not entirely robust scheme to determine the leftand right extreme points of an object was devised. This implementation used asynthetic fault map that tried to simulate post-processing done on the outputof the cross correlation method.

This processed fault map was then used to mask out endpoints not associatedwith fault lines. A line matching algorithm was then implemented that takes

19

Page 22: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

these points and do a brute force calculation of how well supported differentparameterized lines are. This is similar to the Hough transform[3] but we usea measure based on the inverse square of the distance between the points andthe lines. The result of this attempt is described in 4.2 Segmentation.

Figure 19: The darker the area the better the support for that particular lineis.

This angle support map is then used to iteratively find the best estimatesof faults lines by finding the maximum value and the corresponding line pa-rameterization. The neighborhood around the maxima is then removed and theprocess is repeated. An automatic criterion for determining the number of iter-ations of this process would be necessary for a complete implementation but nosuch method has been developed. Instead a fixed value larger than the numberof actual fault lines in the image was selected as a test of the behavior of thealgorithm.

20

Page 23: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

3.3 Motion Estimation

3.3.1 Introduction

In this section a method, using motion estimation to find faults, will be pre-sented. The results from this approach are interesting but not useful. Basictheory, results and suggestions for future investigation will be presented.

To first motivate this approach one needs to look at the origin of the faults.What is the cause of this phenomenon? Motion in the ground causes the differentlayers of rock to shift which in turn causes faults when sections move in differentdirections.

Can the velocities of the sections be estimated using motion estimation asused in the area of image analysis? Can you make a good enough estimation ofthe original properties of the layer structure?

These are the two questions that pose this problem. No useful results havebeen produce as of yet but the method shows some promise. Improvementsare needed in both the motion estimation itself and the approximation of theoriginal layer structure.

3.3.2 Assumptions

To be able to continue with the work quickly some basic assumptions were made:

• The motion can be estimated in this fashion

• The velocities inside a section/block will be estimated to similar values

• An original layout of the layer structure can be approximated

Originally an additional assumption was made. The original layout should notneed to be estimated very accurately in order to get a decent result.

Original layer structure estimation As originally posed the problem wouldn’tneed any complex algorithm to approximate the original layer structure. Work-ing under this assumption a simple approximation was created using regularimage editing software. A line of pixels at the edge of the image was extendedto fit it entirely and then rotated slightly to make a better fit. Fig. 20 showsthe real world data image and the approximated original side by side.

Figure 20: The real data image and the approximated original.

21

Page 24: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

A-star search estimation The results using the first approximation havebeen insufficient and another approximation is needed to investigate this methodfurther. This is an untested suggestion to what can be done to find a bettermore suitable approximation.

An A-star search algorithm might be proven useful when finding an original.Such an algorithm can easily be adjusted to take a difference in levels intoaccount. By making many searches from one side of the image to the otherand matching the results against each other one should be able to receive aninteresting result.

3.3.3 Block matching

For motion estimation the method of block matching was used. This is a simpleyet fairly robust type of motion estimation. In this case it would be quite riskyto use any type of spatial derivative due to the nature of the data. This furthermotivates the use of block matching.

Method The method utilizes two kernels of different sizes. A large kernelsampled from the estimated original and a small kernel sampled from the realworld data.

Using a smaller kernel for the real world data makes it possible to take largermovement of the blocks into account without sacrificing too much resolution.

To match these two kernels the small kernel is inserted into a bigger, thesame size as the sample from the estimated original. Before this, a hammingwindow is applied to the data to reduce the effects of the sharp edges caused bythe zero data surrounding the smaller kernel.

Figure 21: A big and a small kernel with resulting correlation image.

The kernels are matched using phase correlation. For kernel kbig and ksmall

we use the Fourier transform to create Kbig and Ksmall.Corr = KbigK∗

small

|KbigK∗small

|

22

Page 25: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Use the inverse Fourier transform onto Corr get the resulting correlationmatrix, corr. Finding the index of the maximum value of this matrix will givevector which corresponds to the translation of the two kernels. Fig. 2 showstwo kernels and their resulting correlation image.

3.3.4 Modified Levenshtein distance

The modified Levenshtein distance is a method that has not been properlyinvestigated. Some work has been done but interesting results have yet to show.There are several ways to tweak this algorithm and this is where most work isneeded. Both the function f(P i, Sj) and g(x, y) are important for the methodto work.

Method The Levenshtein distance is a commonly used method for evaluatingthe differences between two sequences. It is most often used in the area ofcomputer science.

Assuming it is possible to find a good way to sequence the data, the Lev-enshtein distance works as follows. Using two sequences P i and Sj of where(1 <= i <= N) and (1 <= j <= M). We define the function f(P i, Sj) tobe the cost of matching P i, and Si. Defining F (P i

1, Sj1) as a recursive function

which determines the cost of pairing a subsequence P i1 with a subsequence Sj

1.

F (P i1, S

j1) = f(Pi, Pj) + min

F (P i

1, Sj−11 ) + g(0,−1)

F (P i−11 , Sj−1

1 ) + g(−1,−1)F (P i−1

1 , Sj1) + g(−1, 0)

Where g(x, y) is a penalty added to each action to control the expansion/-compression of of the sequence. The values of F are stored in an NtimesMmatrix Fmat. Along with all the values of F we store a pointer to the subse-quence preceeding the newly computed value.

To get the compression/expansion corresponding to the two matched se-quences we follow the pointers from element N, M of Fmat the stored pointervalues will tell us where to continue and we will stop at index 1, 1.

23

Page 26: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

4 Results

4.1 Cross-Correlation Method (CCM)

4.1.1 Configuration

This section contains results from our implementation of the CCM method, withthe following configuration. The outputs are the:

• Correlation map, rMap

• Angle map, angleMap

• Displacement map, kMap

These images was produced with the data the alghoritm was first tested on.

4.1.2 Original Set

Figure 22: Crosscorrelation map

24

Page 27: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Figure 23: Optimal Angle Map

Figure 24: Optimal Displacement Map

25

Page 28: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

4.1.3 Afterprocessed Set

Figure 25: Afterprocessed Displacement Map

For comparsion, here is the orginial set:

Figure 26: Input map

26

Page 29: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

4.1.4 Other Data Sets

Figure 27: Another input/output set

27

Page 30: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Figure 28: Yet another input/output set

28

Page 31: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

4.1.5 Angle Estimation

The performance of the code is not good since we use the Radon transformimplemented in MATLAB that is unable to perform the Radon transform injust one point. To get a good result the window the angle estimator uses mustnot be too large or too small; a window of 32x32 pixels works well.

The angle estimation is rather accurate in most of the image, however inareas where there is lots of noise it will return bogus values (usually the minimumvalue allowed by the Radon Transform). A larger problem is that the samebehavior is also present to a lesser extent along faults which is unfortunate asthis invalidates the resulting correlation. Since this is a result of the combinationof the Fourier transform and the Radon transform the method was thus deemeduninteresting for further work.

Figure 29: The output of the angle estimator. Visible is areas of bogus values(black) caused by insufficient signal (e.g. lower left corner) and faults.

4.1.6 Performance

There are three major parameters that affect the performance of the cross cor-relation kernel. These are the number of points in evaluated, the number ofdifferent angles the kernel is tilted and the length and number of samples usedin the correlation data chains.

All performance measurements were run on the same test data set using anAMD Athlon X2 4800+ dual core processor running on Microsoft XP. MEX Ccode was compiled with Microsoft Visual C++ 2008 Express Edition.

All graphs show performance by normalizing the cost of the computationwith the size of the problem. A measurement that shows linear complexity willthis be a horizontal line.

29

Page 32: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Number of evaluated points The most important factor for the perfor-mance of the cross correlation method is the number of points in the data whatthe algorithm evaluates. The execution time of the test image was evaluatedusing a range of different distances between data points.

step length 6x6 5x5 4x4 3x3 2x2 1x1points 28288 40280 63221 112455 252502 1007923time (s) 21.81 31.14 48.70 86.19 193.10 772.43points/s 1297.21 1293.64 1298.15 1304.81 1207.60 1304.87

Figure 30: The normalized cost shows that the alghoritm has linear time com-plexity.

The data clearly shows that the execution time is proportional to the numberof points evaluated and the complexity of the algorithm is thus O(n) where n isthe number of evaluations of the correlation kernel.

Number of Angles The number of angles on the correlation kernel used inthe calculation is an important factor that has a large impact on the executiontime of the program.

#angles 1 2 4 6 12 24time (s) 10.31 18.14 33.72 49.63 97.35 193.90normalized 1.00 1.76 3.27 4.81 9.44 18.80

A theoretical study of the code suggests that the execution time should beproportional to the number of angles since in practice an increase in the num-ber of angles tested is almost identical to increasing the number of data pointsevaluated by the same amount. However the result suggests that the perfor-mance is slightly worse than linear for small values but approaches a value ofaround 8 seconds per angle as the amount angles computed is increased. Thiseffect is probably caused by an increase in cache hit rate as the additional sam-ples taken which results in better reuse of cached data. The additional cost ofadding more angles for the kernel to test has a linear complexity.

30

Page 33: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Figure 31: The normalized cost of computing additional angles approaches thehorizontal (linear cost) line asymptotically.

Data chain length The cost of performing the correlation computation isdependent on the number of elements in the vectors that are being compared.Another factor that also has an impact is if the vectors are over- or under sam-pled. These two factors are investigated by varying the number of data samplesused while the length if the data chains are either fixed or equal to the numberof samples taken.

31

Page 34: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Figure 32: The normalized sampling cost of fixed and variable length data chainusing different number of samples. Lower is better.

4.1.7 Performance improvements

The cross correlation method was the only method that required serious opti-mization work. We roughly follow the procedure described in 2.2 Methodologyand improved performance until performance was good enough to continue de-velopment work.

The code started its development as a rather unoptimized piece of MATLABcode and it is therefore not surprising that large performance improvements canbe made. Several rounds of improvement was made where new bottleneckswhere identified and removed. For more detailed information of these bottlenecks see 7.1 Appendix CCM Profiling.

Speed up The speed up can be almost equally split between the originalMATLAB improvements (25 times faster) and the later work using the MEXAPI to replace the core of the program with C code (another 25.4 times faster).

32

Page 35: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Figure 33: Graph showing the cumulative effect of each round of optimizations.

Final result We performed a profile of the final cross correlation implemen-tation where the entire computation of one sample point is implemented in C.The profiler used for this task was CodeAnalyst from AMD and the code wascompiled using Microsoft Visual C++ 2008 Express Edition. The profiler used a20 second profiling window. The computer was equipped with an AMD AthlonX2 4800+ dual core processor running on Windows XP.

Sampled CPU cycles % of execution time Function nameCorrelation kernel 6786 64.4 correlatorData sampling 3183 30.2 bilinLineDataOther 563 5.3Total 10533 100%

33

Page 36: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

4.2 Segmentation

The output of this proof of concept implementation is a seismic image wheresuspected fault lines are drawn in red. Most of the fault lines are detected and anumber of them also have both accurate position and angle. This result suggeststhat using this method with better a better segmentation algorithm and moreadvanced feature extraction and line detection methods could be developed intoa useful tool for refining fault position.

Figure 34: Combined segmentation and CCM method.

34

Page 37: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

4.3 Motion Estimation

4.3.1 Block Matching

Block matching seems to work for fabricated examples where the original layerstructure is predetermined and then distorted. The fabricated original and thedistorted image can be seen in Fig. 35, the resulting translation field is depictedin fig 36.

When tested on the real world data in combination with the simple estima-tion of the original layer structure the method fails to produce a similarly goodresult. It succeeds in segmenting some of the image when tweaked but there’smore noise than clear segments.

One might come to the conclusion that the approximation of the original usedis insufficient to solve the problem in this manner. This problem is addressedlightly in section 3.3. A way to improve the actual motion estimation is to avoidpicking only one maximum and instead using several maxima and evaluating thefinal result based on that. This should result in a more robust translation vectorat each test point.

Figure 35: The fabricated original and distorted image.

Figure 36: Resulting motion estimation from the fabricated images.

35

Page 38: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Figure 37: Results from a good run on the real data.

5 Discussion

5.1 Cross-Correlation Method (CCM)

5.1.1 Alghoritm implementation 3D

When we try to detect faults in 2D, not all faults are perpendicular to the imageplane. If we would look at a 3D set, this shortcoming of the 2D perspectivecan be overcome. The 3D-DAC-map problem with Extended Kernels could beapplied to a 3D data set as a 5D-problem. In 3D, it is also possible to use planepairs instead of line pairs.

5.1.2 Continiuty restraints on faults

We had thoughts of implementing an A-star pathfinding algoritm to be appliedon the CCM-maps seen in the result section above. This way of detecting wouldpick the most probable faults based on the conditions:

• A fault is often quite straight

• A fault ends when it reaches the end of the image, or it reaches anotherfault.

5.1.3 Optimization

As discussed in the 2.2 Methodology using a low level programming language isusually less flexible and more prone to bugs than high level languages. Duringthe development of the C MEX version of the cross correlation method this wascertainly true.

We encountered many of the typical problems of using a low level program-ming languages. Since we developed and ran the code on several different op-erating systems we experienced several incompatibilities where code would notcompile or crash due to differences in C libraries and operating system behav-ior. Some of these could be solved using compiler preprocessor commands (e.g.using %IFNDEF) and others had to be tracked down, which took a lot of time.

A large part of these problems were due to memory bugs; especially the in-teraction between C and MATLAB was troublesome in some more complicatedcases. Ultimately this was solved by disregarding the advice of the MEX devel-opment guide to deallocate memory manually and instead letting the MATLAB

36

Page 39: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

memory manager clean up the allocated structures after termination of the MEXfunction.

Even considering the problems mentioned above the optimization approachmust be considered successful. The person performing optimization could de-liver large and incremental improvements to the person developing the code.This was in no small part due to the flexible layout of both the original MAT-LAB code and the optimized MEX C code. Only once during the developmentprocess did algorithmic changes require that C code had to be rewritten andeven then the changes were minor.

5.1.4 Further performance improvements

There is a lot of performance still on the table. Very little low level optimiza-tions have been performed on the code since that usually takes a lot of effort.There also is still a significant amount of over- and reallocation of memory donedue to interactions with MATLAB’s dynamic memory allocator. Most of theseinteractions could be removed by letting the optimized MEX program handlean entire image instead of just one data point. This would avoid the need toreturn to the MATLAB environment between each data point.

There are also interesting algorithmic improvements available. As can beseen in the previous chapter 95% of the execution time is spent in only twofunctions. The tasks these two functions provide, bilinear sampling of datapoints and correlation calculations, both operate along vectors in the data.Further calls on nearby points that are situated on along the same vector willuse the same data. The result is that most of the calculations done will beredundant. This can be taken advantage of by precomputing or storing alreadycomputed data for later use. The computational grid used by the program ishowever rectangular so this method can only be used on vertical or horizontalvectors. This means that the tilting cross correlation kernel presents a problemas at most one iteration could use this technique.

Figure 38: Square grid. Sampling vectors do not overlap.

One solution would be to use a tilted grid. For every angle the cross cor-relation kernel is tilted the grid would be tilted by the same amount. This

37

Page 40: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

would allow the data sampling and correlation kernels to reuse almost all of thecomputations done in the previous step.

Figure 39: Tilted grid. Sampling vectors will now overlap.

The scope for improved performance using parallel computing is large. Thecross correlation method belongs to the set of “embarrassingly parallel prob-lems”. This means that there are no dependencies between evaluated pointsand parallelization can thus be easily accomplished just by splitting the dataset between different computers. The method is also suitable for implementingusing GPGPU (General Purpose Graphics Processing Unit) techniques. This isnot surprising since the two most time consuming tasks, bilinear filtering andoperations on streaming vectors, are operations very much suited to graphicshardware.

6 Conclusion

In seismic analysis the problem of automatically classifying massive faults re-mains an active area of research after 20 years of effort in the field. The projectdescription suggested an approach of the problem using fresh eyes and tryingto apply methods from unrelated fields. This result is an evaluation of severalmethods that try to solve the difficult problem of finding massive faults.

Of the approaches tried the cross correlation method using en tilting ex-tended kernel showed the most promise and represents an interesting avenue forfuture research.

38

Page 41: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

7 Acknowledgements

The authors would like to thank our supervisor Victor Aarre from SchlumbergerInformation Solution for support and guidance and course coordinator MayaNeytcheva for assistance during the course of the project.

We would also like to thank David Sandquist (from Swedish University ofAgricultural Sciences), Anders Brun, Gustaf Kylberg and Joakim Lindblad (allfrom the Center Image Analysis, Uppsala University) for their help with search-ing for applicable techniques from other fields of study.

39

Page 42: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

References

[1] Weisstein, Eric W. ”Radon Transform.” From MathWorld–A Wolfram WebResource. http://mathworld.wolfram.com/RadonTransform.html, June 62009.

[2] A general algorithm for document skew angle estimation Peake, G.S.; Tan,T.N. Image Processing, 1997. Proceedings., International Conference onVolume 2, Issue , 26-29 Oct 1997 Page(s):230 - 233 vol.2

[3] M. Sonka, V. Hlavac, R. Boyle. Image Processing, Analysis, and MachineVision, International Student Edition. Thomson, 2008. (212-221)

[4] M. Sonka, V. Hlavac, R. Boyle. Image Processing, Analysis, and MachineVision, International Student Edition. Thomson, 2008. (233-237, 687-691).

[5] M. Sonka, V. Hlavac, R. Boyle. Image Processing, Analysis, and MachineVision, International Student Edition. Thomson, 2008. (225-233).

[6] J. K. Udupa , S. Samarasekera . Fuzzy Connectedness and Object Def-inition: Theory, Algorithms, and Applications in Image Segmentation.GRAPHICAL MODELS AND IMAGE PROCESSING Vol. 58, No. 3, May,pp. 246–261, 1996.

[7] L. Zhang, M. Zhang, H.D. Cheng. An Extended Fuzzy Logic Method forWatershed. Proceedings of the 11th Joint Conference on Information Sci-ences (2008).

[8] P. K. Saha and J. K. Udupa. Iterative Relative Fuzzy Connectedness andObject Definition: Theory, Algorithms, and Applications in Image Seg-mentation. Mathematical Methods in Biomedical Image Analysis, 2000.Proceedings. IEEE Workshop on. (28-35)

[9] K. C. Ciesielski, J. K. Udupa, P. K. Saha, Y. Zhuge. Iterative relative fuzzyconnectedness for multiple objects with multiple seeds. Computer Visionand Image Understanding, Volume 107, Issue 3 (September 2007) (160-182)

[10] Delphine Nain1, Steven Haker2, W. Eric L. Grimson1, Eric Cosman Jr1,William W. Wells1,2 , Ron Kikinis2 , and Carl-Fredrik Westin1,2

[11] Artificial Intelligence Laboratory, http://www.ai.mit.edu, MassachusettsInstitute of Technology, Cambridge MA, USA.

[12] Surgical Planning Laboratory, http://www.spl.harvard.edu, Harvard Med-ical School and Brigham and Women’s Hospital.

[13] N. Sladoje, Reviews of Scientific Papers on Application of Fuzzy Set Theoryin Image Segmentation, Internal report No. 24, Centre for Image Analysis,Swedish University of Agricultural Sciences, Uppsala University, 43 pages,2002

40

Page 43: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

8 Appendix

8.1 CCM Profiling

MATLAB Profiler Results A quick walkthrough of the function names andwhat they do. For a longer discussion see the chapter on the cross correlationmethod.

• SinglePoint – The main function. The time reported is the various over-head not associated with CorrBox, Correlator, etc.

• Correlator – Performs the cross correlation calculations.

• CorrBox – Sets up the sampling box. Execution times does includes Line-Data when Linedata isn’t shown separately.

• LineData – The part of the CorrBox that samples the data for the corre-lation chains.

Figure 40

MATLAB Optimizations The first MATLAB version used a straight impli-mentation of the weighted cross correlation method using for loops. For-loopsare probably the slowest contruct in MATLAB but it was not easy to find amethod to rewrite the cross correlation efficiently. The cross correlation can bewritten as a multiplication of a vector with a triangular matrix but it took awhile to find a method to efficiently generate the triangular matrix.

41

Page 44: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Figure 41

Cross correlation using MEX The corrrelator function that performs thecross correlation step was the first function to be replaced by a MEX implimen-tation. As can be seen in the graph the performance improments where largeand the bottelneck shifted to lineData and corrbox that together handles thesampling of the data chains.

42

Page 45: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Figure 42

Sampling using MEX The functions lineData and corrCox was replaced intwo steps with a MEX implementation. Again there was a large performanceincrease but profiling the resulting code showed no single bottleneck. Never-theless we decided to replace the remaining MATLAB code with MEX C codeto remove the overhead in the singlePoint function and to remove many of thetransitions between the MATLAB and MEX environments.

43

Page 46: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Figure 43

Using CodeAnalyst to profile the final MEX version Rewriting theentire singlePoint function using MEX meant that we could no longer use theMATLAB Profiler and instead used the CodeAnalyst profiler from AMD. Tomake comparisons with the earlier graphs easier we have rescaled the CPU clockcount of the different functions to percentages of the total execution time. Wecan plainly see that the was majority of the work in the algorithm is done inthe lineData and correlator function that handle the data sampling and crosscorrelation respectively. Future attempt to improve performance will have tofocus on these two functions.

44

Page 47: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

8.2 CCM-Implementation (m-file version)

Listing 1: matlMapWrapper.mclear

% Conf igura t ion Var iab l e sN = 80 ; % sample l en g t hsmpl = N; % number o f samples to i n t e r p o l a t e ( s im i l a r to N)d = 7 ; % di s t ance from po in t to l i n e ( determines k e rne l width )d mult i = 10/d ; % r e l a t i v e p o s i t i o n (d∗ d mu l t i ) o f second l i n e pa i rl i m i t = ce i l ( 0 . 6∗N) ;% se t s the l im i t f o r d i sp lacement ks tep = 1 ; % determines how f i n e the computat iongr id i s ( b e s t va lue = 1)p = 0 ; % i f true , shows a p l o t o f k e rne l

% ( only used f o r s i n g l e po in t debug )angle min = −15; % sma l l e s t ang l e to checkangle max = 15 ; % l a r g e s t ang l e to checka n g l e s t e p = 0 . 5 ; % ang le s t ep s i z e

% Load an image matrix .img = double ( imread ( ’ input .bmp ’ , ’bmp ’ ) ) ;img = ( img ( : , : , 1 ) + img ( : , : , 2 ) + img ( : , : , 3 ) ) /3 ;img = img − mean(mean( img ) ) ;

angle = angle min : a n g l e s t e p : angle max ;

% Define computation areai f 0

% Whole image[ xmax ymax ] = s ize ( img ) ;y o f f s e t = ce i l ( (N/2) + sin ( ( angle max /360) ∗2∗pi ) ∗( d mult i ∗d) ) ;x o f f s e t = ce i l ( ( d mult i ∗d) + sin ( ( angle max /360) ∗2∗pi ) ∗(N/2) ) ;xvec = x o f f s e t : s tep : ( xmax−x o f f s e t ) ;yvec = y o f f s e t : s tep : ( ymax−y o f f s e t ) ;

else% Subse t imagey min = 1000 ; y max = 1200 ; x min = 220 ; x max = 250 ;xvec = x min : s tep : x max ;yvec = y min : s tep : y max ;

end

% Pre−Al l o ca t e MemoryangleMap = zeros ( length ( xvec ) , length ( yvec ) ) ;kMap = zeros ( length ( xvec ) , length ( yvec ) ) ;rMap = zeros ( length ( xvec ) , length ( yvec ) ) ;

h = waitbar (0 , ’ Analyzing Image . . ’ ) ;

for i =1: length ( xvec )

45

Page 48: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

for j =1: length ( yvec )[ angle max k max r max ] = s i n g l e P o i n t ( [ xvec ( i ) yvec ( j ) ] , img ,N, l im i t , angle , d ,

d mult i , p , smpl ) ;angleMap ( i , j ) = angle max ;kMap( i , j ) = k max ;rMap( i , j ) = r max ;

endwaitbar ( i / length ( xvec ) ,h )

endclose (h)

save output . mat angleMap kMap rMap

f igure ;subplot ( 2 , 1 , 1 ) ; imshow ( img ( x min : x max , y min : y max ) , [ ] ) ;subplot ( 2 , 1 , 2 ) ; imshow (kMap , [ ] ) ;

46

Page 49: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Listing 2: singlePoint.mfunction [ angle max k max r max ] = s i n g l e P o i n t ( point , img , N, l im i t , angle , d ,

d mult i , plot , samples )

% Pre−compute we i gh t ing f o r c r o s s c o r r e l a t i on−f unc t i onv ik t = zeros (1 ,N) ;for k = 1 :N

v ik t ( k ) = 1/(N−k+1) ;endv ik t = [ f l i p l r ( v i k t ( 2 :N) ) v ik t ] ;

% Compute two DAC−maps[ r s e t 1 r s e t 2 ] = s i n g l e P o i n t o l d ( point , img , N, l im i t , angle , d , d mult i , plot ,

samples , v i k t ) ;

% Perform so l u t i o n o f the Extended Kernelsynte s = combineMatrices ( r s e t 1 , r s e t 2 , d mult i ) ;

% Return the c r o s s c o r r e l a t i o n maxima o f the matrix[ angle maxPos k maxPos r max2 ] = matrixMax ( synte s ) ;

% Store the opt imal ang l e .angle max = angle ( angle maxPos ) ;

% Store the opt imal d i sp lacement .k max = k maxPos ;

% Store the maximum c r o s s c o r r e l a t i o n va lue .r max = r s e t 1 ( angle maxPos , k maxPos ) ;

end

47

Page 50: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Listing 3: singlePointold.mfunction [ out1 out2 ] = s i n g l e P o i n t ( point , img ,N, l im i t , angle , d , d mult i , plot ,

samples , v i k t )

x = point (1 ) ;y = point (2 ) ;

% Al l o ca t e apropr i a t e amount o f memory .r s e t = zeros ( length ( angle ) ,2∗ (N−l i m i t )−1) ;r s e t 2 = zeros ( length ( angle ) ,2∗ (N−l i m i t )−1) ;

for i = 1 : length ( angle ) ;% Sample f i r s t l i n e pa i r[ a b ] = corrBox ( point , img ,N, d , angle ( i ) , plot ) ;% Send l i n e pa i r s in t o c r o s s c o r r e l a t o rr = mexCorrelator ( a , b , v ikt ,N, l i m i t ) ;% Store r e s u l t in DAC−mapr s e t ( i , : ) = r ;

% Sample the second l i n e pa i r ( Extended Kernel )[ a b ] = corrBox ( point , img ,N, d mult i ∗d , angle ( i ) , plot ) ;% Send l i n e pa i r s in t o c r o s s c o r r e l a t o rr = mexCorrelator ( a , b , v ikt ,N, l i m i t ) ;% Store r e s u l t in DAC−mapr s e t 2 ( i , : ) = r ;

end

% Return data .out1 = r s e t ;out2 = r s e t 2 ;

48

Page 51: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Listing 4: corrBox.mfunction [ l i n e 1 l i n e 2 ] = corrBox ( point , img , N, d , angle , p l o t t a )% Samples l i n e pa i r s in a k e rne l .% po in t − cen ter o f box , po in t = [ x y ]% p1 , p2 − l e f t l i n e% p3 , p4 − r i g h t l i n e

% Convert from degrees to rad ians .angle = 0.017453292519943∗ angle ;

% Pre−compute to save time .s i na = sin ( angle ) ;cosa = cos ( angle ) ;

pc1 = point +d ∗ [ s i na −cosa ] ;pc2 = point −d ∗ [ s i na −cosa ] ;d e l t a = −(N/2) ∗ [ cosa s ina ] ;

p1 = pc1 − d e l t a ;p2 = pc1 + d e l t a ;p3 = pc2 − d e l t a ;p4 = pc2 + d e l t a ;

% Samples between des i gna t ed po in t s in image img .l i n e 1 = mexLineData ( p2 , p1 , img ) ;l i n e 2 = mexLineData ( p4 , p3 , img ) ;

49

Page 52: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Listing 5: combineMatrices.mfunction out = combineMatrices ( a , b , d mult i )% Enhances the c h a r a c t e r i s t i c s o f two DAC−maps by combining t h e i r% informat ion .

% Find s i z e o f map a .tmp = s ize ( a ) ;c1 = tmp(1) ;v1 = tmp(2) ;

% St r e t ch map b h o r i s o n t a l l y by a f a c t o r d mu l t i o f the width o f map a ( due togeomet r i ca l o b s e r va t i on )

b = i m r e s i z e (b , s ize ( a ) . ∗ [ 1 d mult i ] ) ;

% Find s i z e o f map b .tmp = s ize (b) ;c2 = tmp(1) ;v2 = tmp(2) ;

% Pick out the inner par t o f the DAC.b = b ( 1 : c1 , ( ce i l ( v2/2−v1 /2) ) : ( ce i l ( v2/2+v1 /2) ) ) ;

% Elementwise mu l t i p l i c a t i o n w i l l now h i g h l i g h t ho t spo t areas .c = b ( 1 : c1 , 1 : v1 ) .∗ a ( 1 : c1 , 1 : v1 ) ;

out = c ;

50

Page 53: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Listing 6: matrixMax.mfunction [ y max out x max out z max out ] = matrixMax ( input )% Return the maximum of a matrix .

% Find maxima along the columns . i . e . a long y .[ y max y maxP ] = max( input ) ;

% y maxP conta ins which row has the maxima o f each column .

% Find column with g l o b a l max out o f y max[ x max x maxP ] = max( y max ) ;

y max out = y maxP(x maxP) ;x max out = x maxP ;z max out = x max ;

51

Page 54: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Listing 7: mexCorrelator.c#include ”mex . h”

/∗ Written by Patr i k Holmstrˆm in Spring 2009 as a par t o f the S c i e n t i f i cComputing

∗ Advanced Course ( Pro jec t in S c i e n t i f i c Computing ) .∗∗ This program rep l a c e s the c o r r a l a t o r .m f i l e∗ and i s des igned to be l i n k e d to Matlab as a MEX− f i l e .∗∗ Quick se tup he l p∗ 1 . mex −se tup to se tup e x t e rna l compi ler in matlab∗ 2 . mex −v ’ path+f i l ename ’ to compi le mex− f i l e∗ 3 . Replace o r i g i n a l f unc t i on name with the f i l ename o f the∗ mex−f unc t i on ( in t h i s case mexCorrelator ) in the Matlab source .∗ 4 . P ro f i t ! ! !∗/

#ifndef MAX#d e f i n e MAX( a , b) ( ( ( a ) > (b) ) ? ( a ) : (b ) )

#endif

#ifndef MIN#d e f i n e MIN( a , b) ( ( ( a ) < (b) ) ? ( a ) : (b ) )

#endif

/∗ Computational f unc t i on . A par t o f our c o r r e l a t i o n a l gor i thm . ∗/void c o r r e l a t o r (double r [ ] , /∗ doub le k [ ] , ∗/ double a [ ] , double b [ ] , double wt [ ] ,

int N, int l i m i t ) {

int i , j ; //Loop i n d i c i e sint l en ; //Outer loop s t a r t / s topint s t a r t , stop ; // Inner loop s top / s t a r t i n d i c i e sdouble acc ; // accumulator v a r i a b l e

l en = N−1− l i m i t ;

for ( i = −l en ; i<=len ; i++){

acc = 0 . 0 ;s t a r t = MAX(0 ,− i ) ;s top = MIN(N,N−i ) ;

for ( j=s t a r t ; j<stop ; j++){acc += a [ j ]∗b [ i+j ] ;

}

// r [ i+l en ]=acc /(N−abs ( i ) ) ; //Weight

52

Page 55: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

r [ i+l en ]= acc ∗wt [N−i ] ;}

}

/∗ MEX gateway func t i on . This i s c a l l e d from matlab . The we igh t v e c t o r wt i sc u r r en t l y unused . ∗/

void mexFunction ( int nlhs , mxArray ∗ plhs [ ] , int nrhs , const mxArray ∗prhs [ ] ) {

//Old schoo l C type parameter d e f i n i t i o ndouble ∗a , ∗b , ∗wt , ∗ r , ∗k ; // Input / output Matr icesint N, l i m i t ; // input parametersint l en ; // output matrix s i z e

/∗ Check f o r proper number o f arguments . ∗/i f ( nrhs !=5) {

mexErrMsgTxt ( ” Five inputs r equ i r ed . ” ) ;} else i f ( nlhs >1) {

mexErrMsgTxt ( ”Too many output arguments . ” ) ;}

/∗ Check input f o r v a l i d i t y . ∗/

// check i f arrays have co r r e c t s i z e

/∗ Assign po in t e r s to each input ∗/a = mxGetPr( prhs [ 0 ] ) ;b = mxGetPr( prhs [ 1 ] ) ;wt = mxGetPr( prhs [ 2 ] ) ;N = ( int ) ( mxGetScalar ( prhs [ 3 ] ) ) ;l i m i t = ( int ) ( mxGetScalar ( prhs [ 4 ] ) ) ;

/∗ Create matrix f o r the re turn arguments . ∗/l en = abs (2∗ (N−l i m i t )−1) ;p lhs [ 0 ] = mxCreateDoubleMatrix (1 , len , mxREAL) ; //

! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !// p l h s [ 1 ] = mxCreateDoubleMatrix (1 , len , mxREAL) ;

/∗ Assign po in t e r to output . ∗/r = mxGetPr( p lhs [ 0 ] ) ;//k = mxGetPr( p l h s [ 1 ] ) ;

/∗ Ca l l the c o r r e l a t i o n subrou t ine . ∗/c o r r e l a t o r ( r , /∗k , ∗/a , b , wt ,N, l i m i t ) ;

}

//Fungerar

53

Page 56: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

// vo id c o r r e l a t o r ( doub le r [ ] , doub le k [ ] , doub le a [ ] , doub le b [ ] , doub le wt [ ] ,i n t N, i n t l im i t ) {

//// i n t i , j , kk ;// doub le acc ;//// kk=N−1− l im i t ;//// f o r ( i=−kk ; i<kk ; i++){// acc =0.0;//// f o r ( j =0; j <(N−i ) ; j++){// i f ( j>=0 && j<N && ( i+j )>=0 && ( i+j )<N){// acc += a [ j ]∗ b [ i+j ] ;// }// }// r [ i+kk ]=acc /(N−abs ( i ) ) ;// k [ i+kk ]= i ;// }//}

54

Page 57: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Listing 8: mexLineData.c#include ”mex . h”#include ”math . h”#define MIN( a , b) ( ( ( a ) < (b) ) ? ( a ) : (b ) )#define MAX( a , b) ( ( ( a ) > (b) ) ? ( a ) : (b ) )

/∗ Written by Patr i k Holmstrˆm in Spring 2009 as a par t o f the S c i e n t i f i cComputing

∗ Advanced Course ( Pro jec t in S c i e n t i f i c Computing ) .∗∗ This program rep l a c e s the l ineData .m f i l e∗ and i s des igned to be l i n k e d to Matlab as a MEX− f i l e . ∗/

/∗ Computational f unc t i on . ∗/void l ineData (double l i n e [ ] , double p1 [ ] , double p2 [ ] , double image [ ] , int imM,

int s t ep s ) {

double xstep , ystep , px , py ;int i , x , y ;

// se tup s t a r t p o i n t and sampling s t eppx=p1 [ 0 ] −0 . 5 ; py=p1 [ 1 ] −0 . 5 ; //−0.5 f o r co r r e c t rounding us ing c e i lxstep = ( p2 [0]−p1 [ 0 ] ) / s t ep s ;ystep = ( p2 [1]−p1 [ 1 ] ) / s t ep s ;

//Sample neare s t ne ighbour a long the l i n efor ( i =0; i<s t ep s ; i ++, px+=xstep , py+=ystep ) {

x=( int ) f l o o r ( px ) ; //roundy=( int ) f l o o r ( py ) ; //roundl i n e [ i ] = image [ y∗imM+x ] ;

}}

/∗ MEX gateway func t i on . This i s c a l l e d from Matlab . ∗/void mexFunction ( int nlhs , mxArray ∗ plhs [ ] , int nrhs , const mxArray ∗prhs [ ] ) {

//Old schoo l C type parameter d e f i n i t i o ndouble ∗ l i n e ,∗ p1 ,∗ p2 ,∗ image ;double dx , dy ;int M, N, s t ep s ;

/∗ Check f o r proper number o f arguments . ∗/i f ( nrhs !=3) {

mexErrMsgTxt ( ”Three inputs r equ i r ed . ” ) ;} else i f ( nlhs >1) {

mexErrMsgTxt ( ”Too many output arguments . ” ) ;}

55

Page 58: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

/∗ Check input f o r v a l i d i t y . ∗/M = mxGetM( prhs [ 2 ] ) ;

/∗ Assign po in t e r s to each input ∗/p1 = mxGetPr( prhs [ 0 ] ) ;p2 = mxGetPr( prhs [ 1 ] ) ;image = mxGetPr( prhs [ 2 ] ) ;

/∗ Create matrix f o r the re turn argument . ∗/dx = p1 [0]−p2 [ 0 ] ;dy = p1 [1]−p2 [ 1 ] ;s t ep s = ( int ) c e i l ( s q r t ( dx∗dx+dy∗dy ) ) ;p lhs [ 0 ] = mxCreateDoubleMatrix (1 , s teps , mxREAL) ;//Assign po in t e r to outputl i n e = mxGetPr( p lhs [ 0 ] ) ;

/∗ Ca l l the t imestwo subrou t ine . ∗/l ineData ( l i n e , p1 , p2 , image ,M, s t ep s ) ;

}

56

Page 59: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

8.3 CCM-Implementation (MEX version)

Listing 9: mexMapWrapper.m% This wrapper genera t e s an image from an input image .% I t uses CCM method wih an Extended Kernel .% To run t h i s in matlab , f i r s t run :% mex −se tup% mex mexSing lePoint . c

clear

% Load an image matrix .%img = doub le ( imread ( ’ images/ s e i sm i c s i z e 1 50 . t i f ’ , ’ t i f ’ ) ) ;img = double ( imread ( ’ WestCam Faults Image BW−1.bmp ’ , ’bmp ’ ) ) ;img = ( img ( : , : , 1 ) + img ( : , : , 2 ) + img ( : , : , 3 ) ) /3 ;img = img − mean(mean( img ) ) ;

% Var iab l e sN = 50 ; % sample l en g t hsamples = N; % number o f samples to i n t e r p o l a t e (

s im i l a r to N)l i m i t = ce i l ( 0 . 6∗ samples ) ; % se t s the l im i t f o r d i sp lacement kd = 13 ; % di s t ance from po in t to l i n e ( determines

k e rne l width )d mult i = 18/d ; % r e l a t i v e p o s i t i o n (d∗ d mu l t i ) o f second

l i n e pa i rangle min = −10; % sma l l e s t ang l e to checkangle max = 10 ; % l a r g e s t ang l e to checka n g l e s t e p = 0 . 5 0 ; % ang le s t ep s i z es tep = 3 ; % determines how f i n e the computation

g r i d i s ( b e s t va lue = 1)plot = 0 ; % i f true , shows a p l o t o f k e rne l ( on ly

used f o r s i n g l e po in t debug )

[ xmax ymax ] = s ize ( img ) ;y o f f s e t = ce i l ( (N/2) + sin ( ( angle max /360) ∗2∗pi ) ∗( d mult i ∗d) ) ;x o f f s e t = ce i l ( ( d mult i ∗d) + sin ( ( angle max /360) ∗2∗pi ) ∗(N/2) ) ;angle = angle min : a n g l e s t e p : angle max ;xvec = x o f f s e t : s tep : ( xmax−x o f f s e t ) ;yvec = y o f f s e t : s tep : ( ymax−y o f f s e t ) ;

angleMap = zeros ( length ( xvec ) , length ( yvec ) ) ; % pre−a l l o c a t e memorykMap = zeros ( length ( xvec ) , length ( yvec ) ) ;rMap = zeros ( length ( xvec ) , length ( yvec ) ) ;

h = waitbar (0 , ’ Analyzing Image . . ’ ) ;

57

Page 60: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

for i =1: length ( xvec )for j =1: length ( yvec )

[ angle max k max r max ] = mexSinglePoint ( [ xvec ( i ) yvec ( j ) ] , img , N, l im i t, angle , d , d mult i , plot , samples ) ;

angleMap ( i , j ) = angle max ;kMap( i , j ) = k max ;rMap( i , j ) = r max ;

endwaitbar ( i / length ( xvec ) ,h )

endclose (h)

save output . mat angleMap kMap rMap ;

f igure ; imshow ( angleMap , [ ] ) ; t i t l e ( ’ angleMap ’ ) ;f igure ; imshow (kMap , [ ] ) ; t i t l e ( ’kMap ’ ) ;f igure ; imshow (rMap , [ ] ) ; t i t l e ( ’ rMap ’ ) ;

58

Page 61: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Listing 10: mexSinglePoint.c#include ”mex . h”#include ”math . h”

#ifndef M PI#d e f i n e M PI 3.14159265358979323846

#endif

#ifndef MAX#d e f i n e MAX( a , b) ( ( ( a ) > (b) ) ? ( a ) : (b ) )

#endif

#ifndef MIN#d e f i n e MIN( a , b) ( ( ( a ) < (b) ) ? ( a ) : (b ) )

#endif

/∗ Written by Patr i k Holmstrˆm in Spring 2009 as a par t o f the S c i e n t i f i cComputing

∗ Advanced Course ( Pro jec t in S c i e n t i f i c Computing ) .∗∗ This program rep l a c e s the corrBox .m f i l e∗ and i s des igned to be l i n k e d to Matlab as a MEX− f i l e .∗∗ V1.1 Added p l o t f u n c t i o n a l i t y , more dynamic memory managment and f i l t e r i n g .∗ V1.0 Mex ver s i on o f Magnus second MATLAB ver s i on . ∗/

void pr intVector (double v [ ] , int s t ep s ) {

int i ;

for ( i =0; i<s t ep s ; i++){mexPrintf ( ”%f ” , v [ i ] ) ;

}}

void b i l inL ineData (double l i n e [ ] , double p1 [ ] , double p2 [ ] , double image [ ] , intimM, int s t ep s ) {

double xstep , ystep , px , py , ds ;double p00 , p01 , p11 , p10 , dx , dy , dxdy ;

int i , x , y , x1 , y1 ;

// se tup s t a r t p o i n t and sampling s t epds =1.0/((double ) s teps −1.0) ;xstep = ( p2 [0]−p1 [ 0 ] ) ∗ds ;ystep = ( p2 [1]−p1 [ 1 ] ) ∗ds ;

59

Page 62: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

px=p1 [ 0 ] −1 . 0 ; py=p1 [ 1 ] −1 . 0 ; //−1 to compensate f o r matlab /c indexd i f f

//mexPrintf (”P1 : (%i ,% i ) P2 : (%i ,% i )\n” ,( i n t ) p1 [ 0 ] , ( i n t ) p1 [ 1 ] , ( i n t ) p2 [ 0 ] , ( i n t) p2 [ 1 ] ) ;

//mexPrintf (” Xstep : %f Ystep : %f \n” , xs tep , y s t ep ) ;

//Sample us ing b i l i n e a r sampling a long the l i n efor ( i =0; i<s t ep s ; i ++, px+=xstep , py+=ystep ) {

// b i l i n e a r we i gh t ing c o e f f dx , dydx = px−f l o o r ( px ) ;dy = py−f l o o r ( py ) ;//Coordinate o f l o c a l o r i g i n (0 ,0)x = ( int ) f l o o r ( px ) ;y = ( int ) f l o o r ( py ) ;y∗=imM; x1=x+1; y1=y+imM;// B i l i n ea r c o e f f i c i e n t sdxdy=dx∗dy ;p00 = (1.0−dx−dy+dxdy ) ∗ image [ y+x ] ;p01 = (dy−dxdy ) ∗ image [ y+x1 ] ;p10 = (dx−dxdy ) ∗ image [ y1+x ] ;p11 = dxdy∗ image [ y1+x1 ] ;l i n e [ i ] = p00+p01+p11+p10 ;//mexPrintf (” s t ep : %i , x : %f , y : %f , dx : %f , dy : %f , v a l : %f \n” , i , px+1.0 ,

py+1.0 , dx , dy , l i n e [ i ] ) ;}

}

/∗ Draws the l i n e s p2p1 and p4p3 and the po in t ’ po in t ’ ∗/void plotBox (double po int [ ] , double p1 [ ] , double p2 [ ] , double p3 [ ] , double p4 [ ] ) {

double ∗tmp ;

mxArray ∗ arg1 [ 3 ] , ∗ arg2 [ 3 ] , ∗ arg3 [ 3 ] , ∗ r e s u l t [ 1 ] ;mxArray ∗pp12x ,∗ pp12y ,∗ pp34x ,∗ pp34y ;mxArray ∗ppx ,∗ ppy ,∗ s t r1 ,∗ s t r2 ,∗ s t r 3 ;

//Create and i n i t i a l i z e the needed Matlab data s t r u c t u r e spp12x = mxCreateDoubleMatrix (1 , 2 , mxREAL) ;tmp = mxGetPr( pp12x ) ; tmp [ 0 ] = p1 [ 0 ] ; tmp [ 1 ] = p2 [ 0 ] ;pp12y = mxCreateDoubleMatrix (1 , 2 , mxREAL) ;tmp = mxGetPr( pp12y ) ; tmp [ 0 ] = p1 [ 1 ] ; tmp [ 1 ] = p2 [ 1 ] ;pp34x = mxCreateDoubleMatrix (1 , 2 , mxREAL) ;tmp = mxGetPr( pp34x ) ; tmp [ 0 ] = p3 [ 0 ] ; tmp [ 1 ] = p4 [ 0 ] ;pp34y = mxCreateDoubleMatrix (1 , 2 , mxREAL) ;tmp = mxGetPr( pp34y ) ; tmp [ 0 ] = p3 [ 1 ] ; tmp [ 1 ] = p4 [ 1 ] ;ppx = mxCreateDoubleMatrix (1 , 1 , mxREAL) ;tmp = mxGetPr( ppx ) ; tmp [ 0 ] = point [ 0 ] ;ppy = mxCreateDoubleMatrix (1 , 1 , mxREAL) ;

60

Page 63: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

tmp = mxGetPr( ppy ) ; tmp [ 0 ] = point [ 1 ] ;s t r 1 = mxCreateString ( ” red ∗” ) ;s t r 2 = mxCreateString ( ” red−<” ) ;s t r 3 = mxCreateString ( ” red−>” ) ;

// Or i g ina l Matlab source// p l o t ( po in t (2) , po in t (1) , ’ red ∗ ’ )// p l o t ( [ p1 (2) p2 (2) ] , [ p1 (1) p2 (1) ] , ’ red−<’)// p l o t ( [ p3 (2) p4 (2) ] , [ p3 (1) p4 (1) ] , ’ red−>’)

//Assemble arguments f o r the p l o t f unc t i on c a l l s and c a l l MATLABarg1 [ 0 ] = ppy , arg1 [ 1 ] = ppx , arg1 [ 2 ] = s t r 1 ;mexCallMATLAB(1 , r e s u l t , 3 , arg1 , ” p l o t ” ) ;arg2 [ 0 ] = pp12y , arg2 [ 1 ] = pp12x , arg2 [ 2 ] = s t r 2 ;mexCallMATLAB(1 , r e s u l t , 3 , arg2 , ” p l o t ” ) ;arg3 [ 0 ] = pp34y , arg3 [ 1 ] = pp34x , arg3 [ 2 ] = s t r 3 ;mexCallMATLAB(1 , r e s u l t , 3 , arg3 , ” p l o t ” ) ;

// f r e e memorymxDestroyArray ( pp12x ) ;mxDestroyArray ( pp12y ) ;mxDestroyArray ( pp34x ) ;mxDestroyArray ( pp34y ) ;mxDestroyArray ( ppx ) ;mxDestroyArray ( ppy ) ;mxDestroyArray ( s t r 1 ) ;mxDestroyArray ( s t r 2 ) ;mxDestroyArray ( s t r 3 ) ;mxDestroyArray ( r e s u l t [ 0 ] ) ;

}

/∗ Ca l cu l a t e s the sampling chains and depending on the p l o t v a r i a b l e e i t h e rsamples the chains or p l o t s them . ∗/

void corrBox (double l i n e 1 [ ] , double l i n e 2 [ ] , double po int [ ] , double image [ ] ,double N, double d , double angle , int M, int samples , int p lo t ) {

double s ina , cosa , px , py ; // coord ina te v a r i a b l e sdouble Xoff , Yoff , dx , dy ;

double p1 [ 2 ] , p2 [ 2 ] ; // l e f t chaindouble p3 [ 2 ] , p4 [ 2 ] ; // r i g h t chain

//Get cen ter po in tpx = point [ 0 ] ;py = point [ 1 ] ;

// c a l c u l a t e o f f s e t s from center po in tang le = ang le ∗M PI / 1 8 0 . 0 ;s i na = s i n ( ang le ) ;

61

Page 64: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

cosa = cos ( ang le ) ;Xoff = d∗ s i na ; //Xoff /Yoff equ i v to pc1/pc2 in MATLAB ver s i onYoff = −d∗ cosa ; //dx = −0.5∗N∗ cosa ; //dx/dy equ iv to d e l t a in MATLAB ver s i ondy = −0.5∗N∗ s i na ; //

// Ca l cu l a t e coord ina t e s o f s t a r t / endpo in t sp1 [ 0 ] = px − (dx−Xoff ) ;p1 [ 1 ] = py − (dy−Yoff ) ;p2 [ 0 ] = px + ( dx+Xoff ) ;p2 [ 1 ] = py + ( dy+Yoff ) ;p3 [ 0 ] = px − ( dx+Xoff ) ;p3 [ 1 ] = py − ( dy+Yoff ) ;p4 [ 0 ] = px + (dx−Xoff ) ;p4 [ 1 ] = py + (dy−Yoff ) ;

//Choose between samling and p l o t i n gi f ( p l o t==0){

//Get samples a long the l i n e s p2p1 and p4p3 .b i l inL ineData ( l i n e1 , p2 , p1 , image , M, samples ) ;b i l inL ineData ( l i n e2 , p4 , p3 , image , M, samples ) ;

} else {//Draw co r r e l a t i o n chainsplotBox ( point , p1 , p2 , p3 , p4 ) ;

}}

/∗ Computational f unc t i on . A par t o f our c o r r e l a t i o n a l gor i thm . ∗/void c o r r e l a t o r (double r [ ] , double a [ ] , double b [ ] , int N, int l i m i t ) {

int i , j ; //Loop i n d i c i e sint l en ; //Outer loop s t a r t / s topint s t a r t , stop ; // Inner loop s top / s t a r t i n d i c i e sdouble acc ; // accumulator v a r i a b l e

l en = N−1− l i m i t ; // Limits o f the c o r r e l a t i o n chains

for ( i = −l en ; i<=len ; i++){// f i nd s t a r t and s top f o r the inner loopacc = 0 . 0 ;s t a r t = MAX(0 ,− i ) ;s top = MIN(N,N−i ) ;

for ( j=s t a r t ; j<stop ; j++){acc += a [ j ]∗b [ i+j ] ;

}r [ i+l en ] = acc / ( ( double ) (N−abs ( i ) ) ) ; // ad j u s t f o r we igh t// r [ i+l en ]=acc∗wt [N−i ] ;

}}

62

Page 65: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

/∗ Ca l l s MATLAB’ s b u i l t in f i l t e r f unc t i on to perform f i l t e r i n g on a vec t o r . ∗/void f i l t e r D a t a ( mxArray ∗ l i n e1 , mxArray ∗ l i n e2 , mxArray ∗ B f i l t e r ) {

//MATLAB matr ices f o r input / outputmxArray ∗ in1 [ 3 ] , ∗ in2 [ 3 ] ;mxArray ∗out1 [ 1 ] , ∗out2 [ 1 ] ;mxArray ∗A f i l t e r ;

// Pointers to datadouble ∗pr1 , ∗pr2 , ∗pt1 , ∗pt2 ;double ∗aPtr ;

//Don ’ t use the ’A’ f i l t e rA f i l t e r = mxCreateDoubleMatrix (1 , 1 ,mxREAL) ;aPtr = mxGetPr( A f i l t e r ) ;∗aPtr = 1 . 0 ;

//Assemble input argumentsin1 [ 0 ] = B f i l t e r ; in1 [ 1 ] = A f i l t e r ; in1 [ 2 ] = l i n e 1 ;in2 [ 0 ] = B f i l t e r ; in2 [ 1 ] = A f i l t e r ; in2 [ 2 ] = l i n e 2 ;// Ca l l MATLABmexCallMATLAB(1 , out1 , 3 , in1 , ” f i l t e r ” ) ;mexCallMATLAB(1 , out2 , 3 , in2 , ” f i l t e r ” ) ;

// save o ld po in t e r spt1 = mxGetPr( l i n e 1 ) ;pt2 = mxGetPr( l i n e 2 ) ;// ge t new ( f i l t e r e d ) po in t e r spr1 = mxGetPr( out1 [ 0 ] ) ;pr2 = mxGetPr( out2 [ 0 ] ) ;// use new po in t e r s f o r l i n emxSetPr ( l i n e1 , pr1 ) ;mxSetPr ( l i n e2 , pr2 ) ;// d e a l l o c a t e o ld po in t e r s//mxFree ( pt1 ) ;//mxFree ( pt2 ) ;//mxDestroyArray ( A f i l t e r ) ;

}

/∗ S t r e t ch the rows ( columns in matlab ) o f B and do po in tw i s e mu l t i p l i c a t i o n wi thA. ∗/

void combine (double C[ ] , double A[ ] , double B [ ] , double s t r e t ch , int s izeA [ ] , ints i zeB [ ] ) {

int co l , row , ind , colM ;int Brow0 , Brow1 , M, N;double Brow , de l ta , step , Bstart ;double sample0 , sample1 , Bsample ;

63

Page 66: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

// Ca l cu l a t e sampling parameterss tep = 1.0/ s t r e t c h ;Bstart = 0 . 5∗ ( double ) ( s i zeB [0 ] −1 .0 ) ∗(1.0− s tep ) ;Brow = Bstart ;i f (Brow < 0 . 0 ) {

mexPrintf ( ”B: %ix%i \ nStart : %f Middle :% f .\n” , s i zeB [ 0 ] , s i zeB [ 1 ] , 0 . 5 ∗ (double ) ( s i zeB [0 ] −1 .0 ) ,Brow) ;

Brow = 0 . 0 ;}

//Do s t r e ch by l i n e a r i n t e r p o l a t i o n one row at the time (MATLAB columnwise )M = sizeA [ 0 ] , N = sizeA [ 1 ] ; // S i z e o f A and C matr icesfor ( c o l =0,colM=0; co l<N; c o l++,colM+=M) { //Column

// S t r e t ch one columnfor ( row=0,Brow=Bstart ; row<M; row++,Brow+=step ) { //Row

// Ca l cu l a t e we igh t ’ d e l t a ’ and curren t sampling rows Brow0/Brow1 .d e l t a = Brow−f l o o r (Brow) ;Brow0 = ( int ) f l o o r (Brow) ;Brow1 = Brow0 + 1 ;i f (Brow1 >= M) { // avoid sampling ou t s i d e o f matrix .

Brow1 = Brow0 ;}

//Take samples and do a weigh ted average .sample0 = B[ colM+Brow0 ] ;sample1 = B[ colM+Brow1 ] ;Bsample = (1.0− d e l t a ) ∗ sample0 + d e l t a ∗ sample1 ;ind = colM+row ;C[ ind ] = A[ ind ]∗Bsample ;

}}

}

/∗ Finds the maximum va lue and coord ina t e s o f the MxN matrix A. The r e s u l t i sre turned us ing the po in t e r s xPos , yPos and maxval . ∗/

void matrixMax (double ∗A, int M, int N, int ∗xPos , int ∗yPos , double ∗maxval ) {

int i , j , x , y ;double curr , mval =0.0 ;

//Search f o r max va lue and i t s p o s i t i o nfor ( i =0; i<N; i++){

for ( j =0; j<M; j++){curr = A[ i ∗M+j ] ;i f ( curr > mval ) { //New max => s t o r e

x = i ;y = j ;

64

Page 67: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

mval = curr ;}

}}

// re turn va l u e s∗xPos = x ;∗yPos = y ;∗maxval = mval ;

}

/∗ MEX gateway func t i on . This i s c a l l e d from Matlab . ∗/void mexFunction ( int nlhs , mxArray ∗ plhs [ ] , int nrhs , const mxArray ∗prhs [ ] ) {

//Old schoo l C type parameter d e f i n i t i o ndouble ∗point , ∗ image , ∗ angle , ∗ r s e t1 , ∗ r s e t2 , ∗combset ;double ∗ l i n e1 , ∗ l i n e 2 ;double d , dmulti , maxval ;int i , p lot , f i l t e r , imM, ang l e s t eps , samples , N, l im i t , c h a i n l e n ;int s izeA [ 2 ] , s i zeB [ 2 ] ;int anglePos , kPos ;double ∗maxAngle , ∗maxK, ∗maxR;mxArray ∗L1 , ∗L2 , ∗ B f i l t e r ;

/∗ Check f o r proper number o f arguments . ∗/i f ( nrhs <9) {

mexErrMsgTxt ( ”At l e a s t 9 inputs r equ i r ed . ” ) ;} else i f ( nrhs >10) {

mexErrMsgTxt ( ”At most 10 inputs ” ) ;} else i f ( nlhs >6) {

mexErrMsgTxt ( ”At most s i x outputs . ” ) ;}

/∗ Assign v a r i a b l e s to each input ∗/po int = mxGetPr( prhs [ 0 ] ) ;image = mxGetPr( prhs [ 1 ] ) ;imM = mxGetM( prhs [ 1 ] ) ;N = ( int ) mxGetScalar ( prhs [ 2 ] ) ;l i m i t = ( int ) mxGetScalar ( prhs [ 3 ] ) ;ang le = mxGetPr( prhs [ 4 ] ) ;a n g l e s t e p s = mxGetN( prhs [ 4 ] ) ;d = mxGetScalar ( prhs [ 5 ] ) ;dmulti = mxGetScalar ( prhs [ 6 ] ) ;p l o t = ( int ) mxGetScalar ( prhs [ 7 ] ) ;samples = ( int ) mxGetScalar ( prhs [ 8 ] ) ;i f ( nrhs > 9) {

f i l t e r = 1 ;B f i l t e r = mxDuplicateArray ( prhs [ 9 ] ) ;

} else {f i l t e r = 0 ;

65

Page 68: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

}

/∗ Check input f o r v a l i d i t y . ∗/

//Get image row l en g t h

/∗ Create matr ices f o r output ∗/plhs [ 0 ] = mxCreateDoubleMatrix (1 , 1 ,mxREAL) ;maxAngle = mxGetPr( p lhs [ 0 ] ) ;p lhs [ 1 ] = mxCreateDoubleMatrix (1 , 1 ,mxREAL) ;maxK = mxGetPr( p lhs [ 1 ] ) ;p lhs [ 2 ] = mxCreateDoubleMatrix (1 , 1 ,mxREAL) ;maxR = mxGetPr( p lhs [ 2 ] ) ;

/∗ Create matrix f o r c o r r e l a t i o n chains . ∗/L1 = mxCreateDoubleMatrix ( samples , 1 , mxREAL) ;L2 = mxCreateDoubleMatrix ( samples , 1 , mxREAL) ;l i n e 1 = mxGetPr(L1) ;l i n e 2 = mxGetPr(L2) ;

//Opt iona l output / temporary s t o ragec h a i n l e n = 2∗(N−l i m i t )−1;p lhs [ 3 ] = mxCreateDoubleMatrix ( cha in l en , ang l e s t eps , mxREAL) ;p lhs [ 4 ] = mxCreateDoubleMatrix ( cha in l en , ang l e s t eps , mxREAL) ;s izeA [ 0 ] = mxGetM( plhs [ 4 ] ) ; s i zeA [ 1 ] = mxGetN( p lhs [ 4 ] ) ;p lhs [ 5 ] = mxCreateDoubleMatrix ( cha in l en , ang l e s t eps , mxREAL) ;s i zeB [ 0 ] = mxGetM( plhs [ 5 ] ) ; s i zeB [ 1 ] = mxGetN( p lhs [ 5 ] ) ;//Get po in t e r scombset = mxGetPr( p lhs [ 3 ] ) ;r s e t 1 = mxGetPr( p lhs [ 4 ] ) ;r s e t 2 = mxGetPr( p lhs [ 5 ] ) ;

/∗ Ca l l the c a l c u l a t i o n sub rou t ine s . ∗/for ( i =0; i<a n g l e s t e p s ; i++){

// F i r s t c o r r e l a t i o n chaincorrBox ( l i n e1 , l i n e2 , point , image ,N, d , ang le [ i ] , imM, samples , 0 ) ;i f ( f i l t e r ==1){

f i l t e r D a t a (L1 , L2 , B f i l t e r ) ;}c o r r e l a t o r (& r s e t 1 [ i ∗ c h a i n l e n ] , l i n e1 , l i n e2 ,N, l i m i t ) ;

//Second co r r a l a t i o n chaincorrBox ( l i n e1 , l i n e2 , point , image ,N, d∗dmulti , ang le [ i ] , imM, samples , 0 ) ;i f ( f i l t e r ==1){

f i l t e r D a t a (L1 , L2 , B f i l t e r ) ;}c o r r e l a t o r (& r s e t 2 [ i ∗ c h a i n l e n ] , l i n e1 , l i n e2 ,N, l i m i t ) ;

}

66

Page 69: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

// S t r e t ch r s e t 2 and then mu l t i p l y e lementwisecombine ( combset , r s e t1 , r s e t2 , dmulti , s izeA , s i zeB ) ;

//Find max va lue and po s i t i o n in the combined matrixmatrixMax ( combset , s izeA [ 0 ] , s i zeA [1 ] ,& anglePos ,&kPos ,&maxval ) ;∗maxAngle = angle [ anglePos ] ;∗maxK = (double ) ( kPos+1−(N−l i m i t ) ) ;//∗maxR = rs e t 1 [ anglePos ∗ s izeA [0]+ kPos ] ;∗maxR = maxval ;

// Plo t s e l e c t e d sampling box i f r e qu i r edi f ( p l o t !=0){

mexEvalString ( ” f i g u r e (1 ) ; imshow ( img , [ ] ) ; hold on” ) ;corrBox ( l i n e1 , l i n e2 , point , image ,N, d ,∗maxAngle , imM, samples , p l o t ) ;corrBox ( l i n e1 , l i n e2 , point , image ,N, d∗dmulti ,∗maxAngle , imM, samples , p l o t ) ;mexEvalString ( ” hold o f f ” ) ;

}

//Clean up memoryi f ( nlhs <4)

mxDestroyArray ( p lhs [ 3 ] ) ;i f ( nlhs <5)

mxDestroyArray ( p lhs [ 4 ] ) ;i f ( nlhs <6)

mxDestroyArray ( p lhs [ 5 ] ) ;

mxDestroyArray (L1) ;mxDestroyArray (L2) ;// i f ( f i l t e r ==1)// mxDestroyArray ( B f i l t e r ) ;

return ;}

67

Page 70: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

8.4 CCM Additional Profiling Data

Listing 11: additional data

Addi t iona l CCM t e s t data

Test data used in graphs in the r epor t but not presented in the main text .

Defau l t S e t t i n g sI f no else i s s p e c i f i e d the t e s t runs where made us ing 265 x451 = 119515 data

po in t s and 11 d i f f e r e n t ang l e s .

Performance Sca l i ng with number o f data po in t s

s tep l ength 6x6 5x5 4x4 3x3 2x2 1x2 1x1po in t s 28288 40280 63221 112455 252502 504343 1007923time in seconds 21 .81 31 .14 48 .70 86 .19 193 .10 386 .48 772 .43

Cost o f computing t i l t i n g ke rne l

#ang l e s computed 1 2 4 6 12 24tome in seconds 10 .31 18 .14 33 .72 49 .63 97 .35 193 .90

Cost o f sampling

Chain l ength ( p i x e l s ) 60 60 60 60 60Samples 35 45 60 90 120Time 60 .20 70 .53 87 .40 121 .22 161 .89

Chain l ength ( p i x e l s ) 45 60 90 120Samples 45 60 90 120Time 74 .91 87 .41 107 .11 124 .57

MATLAB P r o f i l e r data

The number o f t e s t i t e r a t i o n s was var i ed for the purpose o f keeping the execut iontime long enough to get v a l i d r e s u l t s . The number o f ang l e s used the t i l t i n g

ke rne lwas i n c r e a s e d to 41 for the same reason .

MATLAB o r i g i n a l

Execution time : 139 .687 s Test i t e r a t i o n s : 10

68

Page 71: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Function time % of time time for 1M e v a l u a t i o n sCor r e l a to r 137.077 98 .13 67859.90Other 2 .670 1 .87 1291.89Total 139 .687 100 .00 69151.79

∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗MATLAB optimized c o r r e l a t o r .

Execution time : 55 .827 s Test i t e r a t i o n s : 100

Function time % of time time for 1M e v a l u a t i o n sc o r r e l a t o r 41 .131 73 .68 2036.19l ineData 8 .579 15 .37 424 .70corrBox 3 .392 6 .11 167 .92Other 2 .725 4 .88 134 .92Total 55 .827 100 .00 2763.73

∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗MEX optimized c o r r e l a t o r .

Execution time : 14 .280 s Test i t e r a t i o n s : 100

Function time % of time time for 1M e v a l u a t i o n sl ineData 7 .668 53 .70 379 .60mexCorrelator (MEX) 1 .373 9 .61 67 .97corrBox 3 .508 24 .57 173 .66s i n g l e P o i n t 0 .967 6 .77 47 .87Other 0 .764 5 .35 37 .83Total 14 .280 100 .00 706 .94

∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗MEX optimized c o r r e l a t o r and l ineData .

Execution time : 24 .830 s Test i t e r a t i o n s : 400

Function time % of time time for 1M e v a l u a t i o n scorrBox2 8 .018 32 .291 99 .23mexCorrelator (MEX) 5 .177 20 .85 64 .07mexLineData (MEX) 4.254 17 .13 52 .65s i n g l e P o i n t 3 .542 14 .26 43 .84Other 3 .840 15 .46 47 .52Total 24 .830 100 .00 307 .31

∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗MEX optimized c o r r e l a t o r + corrBox + l ineData .

Execution time : 15 .907 s Test i t e r a t i o n s : 400

Function time % of time time for 1M e v a l u a t i o n s

69

Page 72: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

mexCorrelator (MEX) 5 .345 33 .60 66 .15s i n g l e P o i n t 4 .274 26 .86 52 .90mexCorrBox2 (MEX) 3 .055 19 .20 37 .81combineMatrices 2 .858 17 .97 35 .37Other 0 .375 2 .36 4 .65Total 15 .907 100 .00 196 .87

∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗

MEX optimzed c o r r e l a t o r + corrBox + l ineData + combineMatr ic ies

Execution time : 12 .941 s Test i t e r a t i o n s : 400

Function time % of time time for 1M e v a l u a t i o n smexCorrelator (MEX) 5 .199 40 .17 64 .34s i n g l e P o i n t 4 .237 32 .74 52 .44mexCorrBox3 (MEX) 3 .067 23 .70 37 .96matrixMax 0.253 1 .95 3 .13mexCombineMatrices (MEX) 0.156 1 .21 1 .93Other 0 .029 0 .23 0 .37Total 12 .941 100 .00 160 .17

∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗Fina l MEX implementation

Execution time : 8 .805 s Test i t e r a t i o n s : 400

Function time % of time time for 1M e v a l u a t i o n smexSinglePoint (MEX) 8 .793 99 .86 108 .82Other 0 .012 0 .14 0 .16Total 8 .805 100 .00 108 .98

70

Page 73: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

8.5 Segmentation Implementation

Listing 12: projectLine.mfunction [ map ] = pr o j e c t L i ne ( coords , pos , midx , ang l e s )%Ca lcu l a t e suppor t f o r the e x i s t an c e o f f a u l t s by l oo k in g at the d i s t ance%from the endpo in t s o f sedimentary l a y e r s to a s e t i n f i n i t e l i n e s .

%move a long the image a long a ho r i s on t a l l i n e and c a l c u l a t e a l l ang l e s in everypo in t .

h = waitbar (0 , ’ Wasteing time . . . ’ ) ;for i =1: length ( pos )

for j =1: length ( ang l e s )po int = [ midx pos ( i ) ] ;angle = [ cos ( ang l e s ( j ) ) sin ( ang l e s ( j ) ) ] ;acc = l i n e 2 p o i n t ( point , po int+angle , coords , 5 . 0 ) ;%acc = mexLine2Point ( point , po in t+angle , coords , 5 . 0 ) ;map( i , j ) = acc ;

endwaitbar ( i / length ( pos ) ,h )

endclose (h)

71

Page 74: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Listing 13: extractMaxima.mfunction [ maxima ] = extractMaxima (map, i t e r , yblot , ab lo t )%Finds ’ i t e r ’ maxima and removes them from the l o c a l neighbourhood .%The s i z e o f the neighbourhood i s ( y b l o t x a b l o t ) .

maxima = zeros (2 , i t e r ) ;

%Finds maxima and remove the l o c a l neighbourhoodb l o t s i z e = [ yblot , ab lo t ] ;for i =1: i t e r

[ ypos apos ] = matrixMax (map)maxima (1 , i ) = ypos ;maxima (2 , i ) = apos ;map = b lo t (map , [ ypos apos ] , b l o t s i z e ) ; %removes area around maxima

end

72

Page 75: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Listing 14: getEndpoints.mfunction [ l e f t r i g h t ] = getEndpoints ( I )%Est imates endpo in t s o f sedimentary l a y e r s us ing segmantat ion and f e a t u r e%ex t r a c t i on .

%Thresho ld ingbLo = im2bw( double ( I ( : , : , 1 ) ) /256 .0 , 0 . 4 0 ) ;bHi = im2bw(1.0− double ( I ( : , : , 1 ) ) /256 .0 , 0 . 4 0 ) ;

%Morph and complimentbLo2 = bwmorph(bLo , ’ f i l l ’ ) ;bHi2 = bwmorph( bHi , ’ f i l l ’ ) ;bLo2 = bwmorph( bLo2 , ’ erode ’ ) ;bHi2 = bwmorph( bHi2 , ’ erode ’ ) ;bLo2 = bwmorph( bLo2 , ’ c l ean ’ ) ;bHi2 = bwmorph( bHi2 , ’ c l ean ’ ) ;bLo2 = bwmorph( bLo2 , ’ d i l a t e ’ ) ;bHi2 = bwmorph( bHi2 , ’ d i l a t e ’ ) ;

%Labe llLo = bwlabel (˜ bLo2 , 4 ) ;lH i = bwlabel (˜ bHi2 , 4 ) ;

%reg ionprops f o r f e a t u r e e x t r a c t i on .fLo = reg ionprops ( lLo , ’ Extrema ’ ) ;fHi = reg ionprops ( lHi , ’ Extrema ’ ) ;

% Extrac t coord ina t e slowC = length ( fLo ) ;hiC = length ( fHi ) ;l e f t = zeros ( lowC+hiC , 2 ) ;r i g h t = zeros ( lowC+hiC , 2 ) ;weight = zeros ( lowC+hiC ) ;

%l e f t coordsfor i =1:lowC

asc = sort ( fLo ( i ) . Extrema , 1 , ’ ascend ’ ) ;l e f t ( i , 1 ) = mean( asc ( 1 : 2 , 1 ) ) ;l e f t ( i , 2 ) = mean( asc ( 1 : 4 , 2 ) ) ;r i g h t ( i , 1 ) = mean( asc ( 7 : 8 , 1 ) ) ;r i g h t ( i , 2 ) = mean( asc ( 5 : 8 , 2 ) ) ;

end

%r i g h t coordsfor i =1: length ( fHi )

asc = sort ( fHi ( i ) . Extrema , 1 , ’ ascend ’ ) ;l e f t ( i+lowC , 1 ) = mean( asc ( 1 : 2 , 1 ) ) ;l e f t ( i+lowC , 2 ) = mean( asc ( 1 : 4 , 2 ) ) ;r i g h t ( i+lowC , 1 ) = mean( asc ( 7 : 8 , 1 ) ) ;

73

Page 76: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

r i g h t ( i+lowC , 2 ) = mean( asc ( 5 : 8 , 2 ) ) ;end

74

Page 77: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Listing 15: blot.mfunction B = blo t (A, coord , b l o t s i z e )%Removes an area de f ined by b l o t s i z e around the coord ina t e s coord in the%matrix A.

%Define areaAsize = s ize (A) ;b l o t s i z e = ce i l ( b l o t s i z e /2) ;c1 = max( coord−b l o t s i z e , 1 ) ;c2 = min( coord+b l o t s i z e , As ize ) ;

%remove areaA( c1 (1 ) : c2 (1 ) , c1 (2 ) : c2 (2 ) ) = 0 . 0 ;B=A;end

75

Page 78: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Listing 16: endpointtest.m

I = imread ( ’ data bw .bmp ’ ) ;f a u l t s = imread ( ’ f a u l t s .bmp ’ ) ;mask = ˜im2bw( f a u l t s , g raythresh ( f a u l t s ) ) ;

%Segment image and e x t r a c t endpo in t s[ l e f t r i g h t ] = getEndpoints ( I ) ;

%Get only endpo in t s wi th f a u l t l i n e suppor t[ coords count ] = maskCoords ( [ l e f t r i g h t ] , mask ) ;imshow (mask , [ ] ) ; hold on ; plot ( coords ( : , 2 ) , coords ( : , 1 ) , ’ r . ’ ) ; hold o f f ;

%Pro jec t l i n e s and ge t the map with ang l e suppor tang l e s = deg2rad ( 0 : 0 . 5 : 1 8 0 ) ; length ( ang l e s )pos = 1 : 2 : 1 4 4 0 ; length ( pos )midx = 441 ;%t i c ;map = pro j e c tL ine ( coords , pos , midx , ang l e s ) ; toct ic ; map = mexProjectLine ( [ 1 2 1440 ] , midx , deg2rad ( [ 0 0 . 5 1 8 0 ] ) , coords , count , 5 . 0 ) ;

toc

figure ; imshow (map ’ , [ ] ) ; xlabel ( ’ x coord inate ’ ) ; ylabel ( ’ ang le ’ ) ;

tmp = map ;tmp ( : , 1 0 0 : 2 6 0 ) = 0 . 0 ; %remove area between 55 and 125 deg ree s si t e r = 7 ; %number o f f a u l t s to e x t r a c t

%Extrac t maximasmaxima = extractMaxima (tmp , i t e r , 2 0 , 4 0 ) ;

%d i s p l a y e x t r a c t e d f u a l t sdrawFaults ( I , maxima , midx , i t e r , pos , ang l e s ) ;

76

Page 79: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Listing 17: maskCoords.mfunction [ outCoord count ] = maskCoords ( inCoord , mask )%Takes a s e t o f coord ina t e s and a p p l i e s a mask .

count = 0 ;[ midp ] = round( s ize (mask ) /2) ;[ stopx stopy ] = s ize (mask ) ;

for i= 1 : length ( inCoord )y = midp (1 )+f ix ( inCoord ( i , 1 )−midp (1) ) ;x = midp (2 )+f ix ( inCoord ( i , 2 )−midp (2) ) ;

i f (x<1 | | y < 1 | | x > stopx | | y > stopy )%discard i f ou t s i d e image

else i f (mask (x , y )==1) %mask i n t e r i o r po in t scount = count +1;outCoord ( count , : ) = [ x y ] ;

endend

end

77

Page 80: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Listing 18: line2point.mfunction [ d i s t ] = l i n e 2 p o i n t (Q0, Q1, po ints ,min)%l i n e 2 p o i n t Ca l cu l a t e s the d i s t ance between an paramet r i c i s ed l i n e (Q0 Q1) and%a c o l l e c t i o n o f po in t s in a column vec to r . Than computes the in v e r s e%square o f the cons t ra ined d i s t ance .

%Prepare un i t v e c t o r sVL = (Q0−Q1) ;UL = VL. / sqrt (VL∗VL’ ) ;

%Measure f o r a l l po in t sfor i =1: length ( po in t s )

W = po in t s ( i , : )−Q0;d i s t ( i ) = abs ( det ( [UL;W] ) ) ;

end

%Accumulate d i s t anc e sd i s t = max( d i s t ,min) ;d i s t = sum( 1 . 0 . / ( d i s t .∗ d i s t ) ) ;

78

Page 81: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Listing 19: drawFaults.mfunction [ ] = drawFaults ( I , maxima , midx , i t e r , pos , ang l e s )%Draws l i n e s a long suspec t ed f a u l t s .

f igure ; imshow ( I , [ ] ) ; hold on ;for i =1: i t e r

y = pos (maxima (1 , i ) ) ;a = ang l e s (maxima (2 , i ) ) ;p0 = [ midx y ] ;o f f = [ cos ( a ) sin ( a ) ] ;p1 = p0+2000∗ o f f ;p2 = p0−2000∗ o f f ;plot ( [ p1 (2 ) p2 (2 ) ] , [ p1 (1 ) p2 (1 ) ] , ’ red ’ , ’ LineWidth ’ , 3 )

endhold o f f ;

79

Page 82: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Listing 20: projectLine.mfunction [ map ] = pr o j e c t L i ne ( coords , pos , midx , ang l e s )%Ca lcu l a t e suppor t f o r the e x i s t an c e o f f a u l t s by l oo k in g at the d i s t ance%from the endpo in t s o f sedimentary l a y e r s to a s e t i n f i n i t e l i n e s .

%move a long the image a long a ho r i s on t a l l i n e and c a l c u l a t e a l l ang l e s in everypo in t .

h = waitbar (0 , ’ Wasteing time . . . ’ ) ;for i =1: length ( pos )

for j =1: length ( ang l e s )po int = [ midx pos ( i ) ] ;angle = [ cos ( ang l e s ( j ) ) sin ( ang l e s ( j ) ) ] ;acc = l i n e 2 p o i n t ( point , po int+angle , coords , 5 . 0 ) ;%acc = mexLine2Point ( point , po in t+angle , coords , 5 . 0 ) ;map( i , j ) = acc ;

endwaitbar ( i / length ( pos ) ,h )

endclose (h)

80

Page 83: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Listing 21: mexProjectLine.c#include ”mex . h”#include ”math . h”

/∗ Written by Patr i k Holmstrˆm in Spring 2009 as a par t o f the S c i e n t i f i cComputing

∗ Advanced Course ( Pro jec t in S c i e n t i f i c Computing ) . ∗/

#ifndef MAX#d e f i n e MAX( a , b) ( ( ( a ) > (b) ) ? ( a ) : (b ) )

#endif

/∗ Ca l cu l a t e s the d i s t ance between an paramet r i c i s ed l i n e (Q0 Q1) anda c o l l e c t i o n o f po in t s in a column vec to r . Than computes the in v e r s esquare o f the cons t ra ined d i s t ance . ∗/

double l i n e 2 p o i n t (double Q1 [ ] , double Q2 [ ] , double po in t s [ ] , double max , int N) {

double ULx, ULy,Wx,Wy;double det , wt , sum , l en ;int i ;

//PrecomputedULx = Q2 [ 0 ] ;ULy = Q2 [ 1 ] ;l en = 1.0/ s q r t (ULx∗ULx+ULy∗ULy) ;ULx ∗= len , ULy ∗= len ;

//Compute d i s t ance f o r a l l po in ts , c a l c u l a t e the cons t ra ined inv e r s e// square o f d i s t ance and accumulate the r e s u l t .for ( i =0,sum=0.0; i<N; i++){

Wx = Q1[0]− po in t s [ i ] ;Wy = Q1[1]− po in t s [ i+N ] ;det = (ULx∗Wy−ULy∗Wx) ;wt = MAX( det ∗det , max∗max) ;sum += 1.0/ wt ;

}return sum ;

}/∗Ca l cu l a t e suppor t f o r the e x i s t an c e o f f a u l t s by l o o k in g at the d i s t ancefrom the endpo in t s o f sedimentary l a y e r s to a s e t i n f i n i t e l i n e s . ∗/void p r o j e c t L i n e ( mxArray ∗out , double pos [ ] , int midx , double ang l e s [ ] , double

po in t s [ ] , int nr po int s , double min ) {

int i , j , y ,M,N;int startY , stepY , stopY ;double angle , startA , stepA , stopA ;double cosa , s i na ;double Q1 [ 2 ] , Q2 [ 2 ] ;double ∗map ;

81

Page 84: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

startY = ( int ) pos [ 0 ] ;stepY = ( int ) pos [ 1 ] ;stopY = ( int ) pos [ 2 ] ;

s tartA = ang l e s [ 0 ] ;stepA = ang l e s [ 1 ] ;stopA = ang l e s [ 2 ] ;

map = mxGetPr( out ) ;M = mxGetM( out ) ;N = mxGetN( out ) ;

//move a long the image a long a ho r i s on t a l l i n e and c a l c u l a t e a l l ang l e s inevery po in t .

Q1[0]= midx ;for ( j =0, ang le=startA ; angle<stopA ; j ++,ang le+=stepA ) {

Q2 [ 0 ] = cos ( ang le ) ;Q2 [ 1 ] = s i n ( ang le ) ;for ( i =0,y=startY ; y<stopY ; i ++,y+=stepY ) {

Q1[1]= y ;map [ i+j ∗M] = l i n e 2 p o i n t (Q1, Q2, po ints , min , n r p o i n t s ) ;

}}

}

/∗ MEX gateway func t i on . This i s c a l l e d from Matlab . ∗/void mexFunction ( int nlhs , mxArray ∗ plhs [ ] , int nrhs , const mxArray ∗prhs [ ] ) {

//Old schoo l C type parameter d e f i n i t i o ndouble ∗pos , ∗ angle , ∗ po in t s ;double min ;int midx , M, N, n r p o i n t s ;

/∗ Check f o r proper number o f arguments . ∗/i f ( nrhs !=6) {

mexErrMsgTxt ( ” Six inputs r equ i r ed . ” ) ;} else i f ( nlhs >1) {

mexErrMsgTxt ( ”Too many output arguments . ” ) ;}

/∗ Check input f o r v a l i d i t y . ∗/

/∗ Assign po in t e r s to each input ∗/pos = mxGetPr( prhs [ 0 ] ) ;midx = ( int ) mxGetScalar ( prhs [ 1 ] ) ;ang le = mxGetPr( prhs [ 2 ] ) ;po in t s = mxGetPr( prhs [ 3 ] ) ;

82

Page 85: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

n r p o i n t s = ( int ) mxGetScalar ( prhs [ 4 ] ) ;min = mxGetScalar ( prhs [ 5 ] ) ;

/∗ Create matrix f o r the re turn argument . ∗/M = ( int ) ( c e i l ( ( pos [2]− pos [ 0 ] ) /pos [ 1 ] ) ) ;N = ( int ) ( c e i l ( ( ang le [2]− ang le [ 0 ] ) / ang le [ 1 ] ) ) +1;mexPrintf ( ”MxN: %ix%i \n” ,M,N) ;p lhs [ 0 ] = mxCreateDoubleMatrix (M,N,mxREAL) ;//Assign po in t e r to output

/∗ Ca l l the t imestwo subrou t ine . ∗/p r o j e c t L i n e ( p lhs [ 0 ] , pos , midx , angle , po ints , n r po in t s , min ) ;

}

83

Page 86: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Listing 22: mexLine2Point.c#include ”mex . h”#include ”math . h”

/∗ Written by Patr i k Holmstrˆm in Spring 2009 as a par t o f the S c i e n t i f i cComputing

∗ Advanced Course ( Pro jec t in S c i e n t i f i c Computing ) . ∗/

#ifndef MAX#d e f i n e MAX( a , b) ( ( ( a ) > (b) ) ? ( a ) : (b ) )

#endif

/∗ Ca l cu l a t e s the d i s t ance between an paramet r i c i s ed l i n e (Q0 Q1) anda c o l l e c t i o n o f po in t s in a column vec to r . Than computes the in v e r s esquare o f the cons t ra ined d i s t ance . ∗/

double l i n e 2 p o i n t (double Q1 [ ] , double Q2 [ ] , double po in t s [ ] , double max , int N) {

double ULx, ULy,Wx,Wy;double det , wt , sum , l en ;int i ;

//PrecomputedULx = Q1[0]−Q2 [ 0 ] ;ULy = Q1[1]−Q2 [ 1 ] ;l en = 1.0/ s q r t (ULx∗ULx+ULy∗ULy) ;ULx ∗= len , ULy ∗= len ;

//Compute d i s t ance f o r a l l po in ts , c a l c u l a t e the cons t ra ined inv e r s e// square o f d i s t ance and accumulate the r e s u l t .for ( i =0,sum=0.0; i<N; i++){

Wx = Q1[0]− po in t s [ i ] ;Wy = Q1[1]− po in t s [ i+N ] ;det = (ULx∗Wy−ULy∗Wx) ;wt = MAX( det ∗det , max∗max) ;sum += 1.0/ wt ;

}return sum ;

}

/∗ MEX gateway func t i on . This i s c a l l e d from Matlab . ∗/void mexFunction ( int nlhs , mxArray ∗ plhs [ ] , int nrhs , const mxArray ∗prhs [ ] ) {

//Old schoo l C type parameter d e f i n i t i o ndouble ∗P1 , ∗P2 , ∗points , ∗out , min ;int n r p o i n t s ;

/∗ Check f o r proper number o f arguments . ∗/i f ( nrhs !=4) {

mexErrMsgTxt ( ”Four inputs r equ i r ed . ” ) ;

84

Page 87: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

} else i f ( nlhs >1) {mexErrMsgTxt ( ”Too many output arguments . ” ) ;

}

/∗ Check input f o r v a l i d i t y . ∗/

/∗ Assign po in t e r s to each input ∗/P1 = mxGetPr( prhs [ 0 ] ) ;P2 = mxGetPr( prhs [ 1 ] ) ;po in t s = mxGetPr( prhs [ 2 ] ) ;min = mxGetScalar ( prhs [ 3 ] ) ;n r p o i n t s = mxGetM( prhs [ 2 ] ) ;

/∗ Create matrix f o r the re turn argument . ∗/// p l h s [ 0 ] = mxCreateDoubleMatrix ( s t eps , 1 , mxREAL) ;plhs [ 0 ] = mxCreateDoubleMatrix (1 , 1 ,mxREAL) ;//Assign po in t e r to outputout = mxGetPr( p lhs [ 0 ] ) ;

/∗ Ca l l the t imestwo subrou t ine . ∗/∗out = l i n e 2 p o i n t (P1 , P2 , po ints , min , n r p o i n t s ) ;

}

85

Page 88: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

8.6 Angle Estimation Implementation

Listing 23: angleinterpol.mfunction [ A ] = a n g l e i n t e r p o l ( I , h , d )%%Perfomes the ang le es t imaion on an image I . An hxh window i s used wi th a%dxd computat iona l g r i d .

[ xmax ymax ] = s ize ( I ) ;

%Ca lcu l a t e area and po in t s o f i n t e r e sh=h/d ;xs teps = d∗ ce i l ( ( xmax−h) /h) ;y s teps = d∗ ce i l ( ( ymax−h) /h) ;

Agrid = zeros ( xsteps , y s teps ) ;

%ca l c u l a t e a l l data po in t sfor i =1: xs t eps

for j =1: ys tepsx2=min(h∗ i+h , xmax) ; y2=min(h∗ j+h , ymax) ;x1= x2−2∗h+1;y1=y2−2∗h+1;Agrid ( i , j ) = a n g l e e s t ( I , [ x1 y1 ] , [ x2 y2 ] ) ;

endend

%r e s i z e image to compensade f o r computat iona l g r i dAgrid = padarray ( Agrid , 1 , ’ both ’ , ’ r e p l i c a t e ’ ) ;A = i m r e s i z e ( Agrid , h) ;A = A(h+1:xmax+h , h+1:ymax+h) ;

end

86

Page 89: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

Listing 24: angleest.mfunction angle = a n g l e e s t ( I , a , b )%Est imates the ang le o f a c o l l e c t i o n o f approx . p a r a l l e l l i n e s us ing the%radon transform on the f o u r i e r transform of the image . The ang le i s%measured on the un i t c i r c l e .

%Def in ing areax1 = a (1) ;y1 = a (2) ;x2 = b (1) ;y2 = b (2) ;

x = x1 : 1 : x2 ;y = y1 : 1 : y2 ;

%Def in ing c i r c l er = min( x2−x1 , y2−y1 ) ∗0 . 4 5 ;%0.375 ;cx = ( x1+x2 ) /2 ;cy = ( y1+y2 ) /2 ;

%ge t a subsample o f the imageA = double ( I (x , y ) ) ;

%do f a s t FTF = f f t2 (A) ;

% transform FFT fo r v iewing / b e t t e r con t ra s tF = log (1 + abs (F) ) ;

% s h i f t low f r e q . to cen ter o f imageF = f f t s h i f t (F) ;

%Ci r c e l i z e to remove i n f l u en c e o f d i a gona l s[X,Y] = meshgrid (x , y ) ;F = F.∗ double ( sqrt ( (X−cx ) . ˆ2 + (Y−cy ) . ˆ 2 ) <= r ∗0 . 75 ) ;

%Do Radon transformtheta = −20 :0 . 25 :20 ;[R, xp ] = radon (F , theta ) ;

%Find max va lue and ge t ang l e[maxV, i ] = max(max(R) ) ;angle = theta ( i ) ;i f ( angle > 16 | angle < −16)

angle = 0 ;end

end

87

Page 90: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

8.7 Motion Estimation Implementation

Listing 25: correlationFunc.mfunction [ p o s i t i o n ] = cor r e l a t i onFunc ( o r i g i n a l , moved , s ca l e , dimensions , pos )% Function runs a c o r r e l a t i o n on two b l o c k s from an image .% o r i g i n a l : i s the base image% moved : i s the image where motion has occured% s ca l e : i s a s c a l e f a c t o r which determines the r e a l s i z e o f the b l o c k sample

from the o r i g i n a l% dimensions : s e t s the dimension f o r the sma l l e r k e rne l sampled from moved% pos : i s the p o s i t i o n around which we sample the k e rn e l s .

% Puts the dimensions in new v a r i a b l e sblockWidth = dimensions (1 ) ;b lockHeight = dimensions (2 ) ;

% Puts the p o s i t i o n s in new v a r i a b l e sposx = pos (1 ) ;posy = pos (2 ) ;

% Ca l cu l a t e s s i z e o f h a l f a b l o c kbHalfBlockx = f loor ( s c a l e (1 ) ∗blockWidth /2) ;bHalfBlocky = f loor ( s c a l e (2 ) ∗blockHeight /2) ;

% The po s i t i o n from where to s t a r t p i c k i n g the sma l l k e rne lsBegx = max(1 , 1 − blockWidth /2 + posx ) ;sBegy = max(1 , 1 − blockHeight /2 + posy ) ;

% The po s i t i o n where to end p i c k i n g the sma l l k e rne lsEndx = min( s ize ( o r i g i n a l , 2) , posx + blockWidth /2) ;sEndy = min( s ize ( o r i g i n a l , 1) , posy + blockHeight /2) ;

% The po s i t i o n from where to s t a r t p i c k i n g the b i g k e rne lbBegx = max(1 , 1 − bHalfBlockx + posx ) ;bBegy = max(1 , 1 − bHalfBlocky + posy ) ;

% The po s i t i o n where to end p i c k i n g the b i g k e rne lbEndx = min( s ize ( o r i g i n a l , 2) , posx + bHalfBlockx ) ;bEndy = min( s ize ( o r i g i n a l , 1) , posy + bHalfBlocky ) ;

% Create a k e rne l from the o r i g i n a l imagebKernel = uint8 ( zeros ( bHalfBlocky ∗2 , bHalfBlockx ∗2) ) ;bPosx = bHalfBlockx + bBegx − posx ;bPosy = bHalfBlocky + bBegy − posy ;bWidth = bEndx − bBegx ;bHeight = bEndy − bBegy ;

88

Page 91: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

bKernel ( bPosy : bPosy+bHeight , bPosx : bPosx+bWidth ) = o r i g i n a l ( bBegy : bEndy ,bBegx : bEndx) ;

% Create and app ly a window to the b i g k e rne lhamwin = hamming( s ize ( bKernel , 1) ) ∗ hamming( s ize ( bKernel , 2) ) ’ ;bKernel = uint8 ( double ( bKernel ) .∗hamwin) ;

% Create a k e rne l f o r the d i s t o r t e d imagehamwin = hamming( blockHeight ) ∗ hamming( blockWidth ) ’ ;

% Create a window fo r the sma l l k e rne lhamwin = hamwin( blockHeight−sEndy+sBegy : blockHeight , blockWidth−sEndx+sBegx :

blockWidth ) ;

sKerne l = uint8 ( zeros ( bHalfBlocky ∗2 , bHalfBlockx ∗2) ) ;sPosx = bHalfBlockx + sBegx − posx ;sPosy = bHalfBlocky + sBegy − posy ;sWidth = sEndx − sBegx ;sHeight = sEndy − sBegy ;sKerne l ( sPosy : sPosy+sHeight , sPosx : sPosx+sWidth ) = uint8 ( double (moved( sBegy :

sEndy , sBegx : sEndx ) ) .∗hamwin) ;

% Sta r t the c o r r e l a t i o nga = bKernel ;gb = sKerne l ;

%Do f f t f o r both matr icesGa = f f t2 ( ga ) ;Gb = f f t2 ( gb ) ;

% Mul t i p l y the f f s and normal izenGG = Ga.∗ conj (Gb) ;nGG = sqrt (nGG.∗ conj (nGG) ) ;R = (Ga.∗ conj (Gb) ) . /nGG;

% Use inve r s e f f t to g e t the c o r r e l a t i o n imager = i f f t 2 (R) ;r = f f t s h i f t ( r ) /max(max(abs ( r ) ) ) ;

% Blur and app ly a window func t i on to make i t more s t a b l e .% We expec t i t to be l e s s p robab l e t h a t the motion i s l a r g e .hamBlur = hamming (5 ) ∗hamming (5 ) ’ ;r = i m f i l t e r ( r , hamBlur/sum(sum( hamBlur ) ) ) ;r = r . ∗ ( hamming( s ize ( r , 1) ) ∗hamming( s ize ( r , 2) ) ’ ) ;

% Find the index o f the maximum an re turn i t .[m, ind ] = max( r ) ;[m, ind2 ] = max(m) ;p o s i t i o n = [ ind2 − bHalfBlockx , ind ( ind2 ) − bHalfBlocky ] ;

89

Page 92: Fault Detection - Uppsala UniversityFigure 2: Seismic data set, without highlighted faults The challenge of fault detection lies in translating a task that the eye and the brain can

end

Listing 26: doMotion.m% Loading the images to use motion es t ima t iono r i g i n a l = imread ( ’ . . / PhaseCorr/ r e a l 9 .bmp ’ ) ;moved = imread ( ’ . . / PhaseCorr/ r e a l 2 .bmp ’ ) ;

%Turning them in to a usab l e formato r i g i n a l = o r i g i n a l ( 1 : s ize ( o r i g i n a l , 1) , 1 : s ize ( o r i g i n a l , 2 ) ) ;moved = moved ( 1 : s ize (moved , 1) , 1 : s ize (moved , 2 ) ) ;

% Configure the s t e p s i z e to g e t the r e s o l u t i o n you want% b l o c kS i z e = s t e pS i z eb lo ckS i z e = 5 ;numBlocksX = f loor ( s ize ( o r i g i n a l , 1) / b l o ckS i z e )numBlocksY = f loor ( s ize ( o r i g i n a l , 2) / b l o ckS i z e )

% Set up the matr ices where to s t o r e the t r a n s l a t i o nd i s t o r t 1 = zeros ( numBlocksX , numBlocksY ) ;d i s t o r t 2 = zeros ( numBlocksX , numBlocksY ) ;

% Sta r t the loopfor k = 0 : numBlocksX−1

for j = 0 : numBlocksY−1% Use the c o r r e l a t i o n func t i on on one b l o c k o f datap o s i t i o n = cor r e l a t i onFunc ( o r i g i n a l , moved , [ 1 , 1 . 1 ] , [ 2 0 , 6 0 ] , [ j ∗

blockS ize , k ∗ b lo ckS i z e ] ) ;d i s t o r t 1 ( k+1, j +1) = p o s i t i o n (2 ) ;d i s t o r t 2 ( k+1, j +1) = p o s i t i o n (1 ) ;

endk

end

% Plot the r e s u l t sf igure ; imshow ( d i s t o r t 1 , [ ] ) ;f igure ; imshow ( d i s t o r t 2 , [ ] ) ;

% Plot the r e s u l t sf igure ;subplot (2 , 1 , 1) ; surf ( med f i l t 2 ( d i s t o r t 1 , [ 5 5 ] ) ) ;subplot (2 , 1 , 2) ; surf ( med f i l t 2 ( d i s t o r t 1 , [ 5 5 ] ) )

90