public override IImage <double> CloneSize(int newWidth, int newHeight) { IRegularGrid2D gridClone = grid.CloneSize(newWidth, newHeight); GridImage clone = new GridImage(gridClone); return(clone); }
/// <summary> /// Compute the Root Mean Square difference betweeen two grids of the same dimensions. /// Nodes which are null in either grid will be ignored. /// </summary> /// <param name="otherGrid">The grid against which this grid will be compared.</param> /// <param name="beginI">The minimumI</param> /// <param name="endI">One beyond the maximumI (half-open range)</param> /// <param name="beginJ">The minimumJ</param> /// <param name="endJ">One beyond the maximumJ (half-open range)</param> /// <returns>The Root Mean Square difference of the z values.</returns> public double?RmsDifference(IRegularGrid2D otherGrid, int beginI, int endI, int beginJ, int endJ) { Debug.Assert(this.SizeI == otherGrid.SizeI); Debug.Assert(this.SizeJ == otherGrid.SizeJ); Debug.Assert(beginI >= 0 && beginI < SizeI); Debug.Assert(beginJ >= 0 && beginJ < SizeJ); Debug.Assert(endI > 0 && endI <= SizeI); Debug.Assert(endJ > 0 && endJ <= SizeJ); double total = 0.0; int count = 0; for (int i = beginI; i < endI; ++i) { for (int j = beginJ; j < endJ; ++j) { if (this[i, j].HasValue && otherGrid[i, j].HasValue) { double diff = this[i, j].Value - otherGrid[i, j].Value; Debug.Assert(!double.IsNaN(diff)); Debug.Assert(!double.IsInfinity(diff)); total += diff * diff; ++count; } } } if (count == 0) { return(null); } double mean = total / count; return(Math.Sqrt(mean)); }
public Histogram CreateDipAzimuthHistogram(int numberOfClasses) { Histogram histogram = new Histogram(numberOfClasses, -Math.PI, +Math.PI); IRegularGrid2D dZdX = CreatePartialDerivativeIGrid(); IRegularGrid2D dZdY = CreatePartialDerivativeJGrid(); for (int i = 0; i < SizeI; ++i) { for (int j = 0; j < SizeJ; ++j) { double?x = dZdX[i, j]; double?y = dZdY[i, j]; if (x.HasValue && y.HasValue) { if (x != 0.0 && y != 0.0) { double dipAzimuth = Math.Atan2(-y.Value, -x.Value); // Negate x and y to give down-dip rather than up-dip histogram.Accumulate(dipAzimuth); } } } } return(histogram); }
public override IImage <double> CloneSize() { IRegularGrid2D gridClone = grid.CloneSize(); GridImage clone = new GridImage(gridClone); return(clone); }
public override object Clone() { IRegularGrid2D gridClone = (IRegularGrid2D)this.grid.Clone(); GridImage clone = new GridImage(gridClone); return(clone); }
public Grid2DPhenotype(Grid2DDomain domain) : base(domain) { Point2D origin = domain.Min; Vector2D diagonal = domain.Max - domain.Min; Vector2D spacing = new Vector2D(diagonal.DeltaX / domain.SizeI, diagonal.DeltaY / domain.SizeJ); this.grid = new RegularGrid2D(origin, spacing, domain.SizeI, domain.SizeJ, 0.0); }
public Grid2DDomain(IRegularGrid2D grid) : base(new Grid2DPhenotype(grid)) { Target.Domain = this; Min = new Point2D(grid.MinX, grid.MinY); Max = new Point2D(grid.MaxX, grid.MaxY); this.sizeI = grid.SizeI; this.sizeJ = grid.SizeJ; }
private static void WriteBinaryImageSurfer6Grid(IRegularGrid2D prototypeGrid, IImage <bool> image, string uri) { IRegularGrid2D thresholdGrid = prototypeGrid.CloneSize(image.Width, image.Height); for (int i = 0; i < image.Width; ++i) { for (int j = 0; j < image.Height; ++j) { thresholdGrid[i, j] = image[i, j] ? 1.0 : 0.0; } } thresholdGrid.WriteSurfer6BinaryFile(uri); }
// usage : Training: C:\Users\rjs\Documents\dev\p4workspace\sandbox\geodyssey\proto\Athena\testdata\training.irap // Expected: C:\Users\rjs\Documents\dev\p4workspace\sandbox\geodyssey\proto\Athena\testdata\expected.grd // Grid for analysis: F:\sapere_aude\data\IrapClassic\grid_surface\ASCII\RMS\analysis.irap static int Main(string[] args) { // Get a URI from the command line argument Uri trainingInputUri = UriFromArg(args, 0); Uri trainingExpectedUri = UriFromArg(args, 1); Uri analysisUri = UriFromArg(args, 2); GeodysseyModel model = new GeodysseyModel(); LoaderController.Instance.Open(trainingInputUri, model); IRegularGrid2D trainingInputGrid = model[0]; // The first grid LoaderController.Instance.Open(trainingExpectedUri, model); IRegularGrid2D trainingExpectedGrid = model[1]; // The second grid LoaderController.Instance.Open(analysisUri, model); IRegularGrid2D analysisGrid = model[2]; // The third grid // Replaces blanks with 0.0 for (int j = 0; j < trainingExpectedGrid.SizeJ; ++j) { for (int i = 0; i < trainingExpectedGrid.SizeI; ++i) { if (!trainingExpectedGrid[i, j].HasValue) { trainingExpectedGrid[i, j] = 0.0; } else { if (trainingExpectedGrid[i, j] < 0.0) { trainingExpectedGrid[i, j] = 0.0; } else if (trainingExpectedGrid[i, j] > 1.0) { trainingExpectedGrid[i, j] = 1.0; } } } } int matrixWidth = 5; FaultInHorizonClassifer classifier = new FaultInHorizonClassifer(matrixWidth); classifier.Learn(trainingInputGrid, trainingExpectedGrid); IRegularGrid2D predictedGrid = classifier.CreateFaultProbability(analysisGrid); predictedGrid.WriteSurfer6BinaryFile("predicted.grd"); return(0); }
public double RandomHistogramDipAzimuth() { if (dipAzimuthHistogramGenerator == null) { Grid2DPhenotype p = (Grid2DPhenotype)Target; IRegularGrid2D g = p.Grid; Histogram dipAzimuthHistogram = g.CreateDipAzimuthHistogram(24); dipAzimuthHistogramGenerator = new ContinuousHistogramGenerator(dipAzimuthHistogram); } double value = dipAzimuthHistogramGenerator.NextDouble(); //Console.WriteLine("randomAzimuth = {0}", Angle.RadiansToDegrees(value)); return(value); }
public void MaskFrom(IRegularGrid2D maskGrid) { Debug.Assert(this.SizeI == maskGrid.SizeI); Debug.Assert(this.SizeJ == maskGrid.SizeJ); for (int i = 0; i < SizeI; ++i) { for (int j = 0; j < SizeJ; ++j) { if (!maskGrid[i, j].HasValue) { this[i, j] = null; } } } }
public IRegularGrid2D CreateFaultProbability(IRegularGrid2D horizon) { // TODO: This is a little hacky and wasteful - replace this // with a Transform method on the Grid class IRegularGrid2D probabilityGrid = (IRegularGrid2D)horizon.Clone(); for (int j = 0; j < horizon.SizeJ; ++j) { for (int i = 0; i < horizon.SizeI; ++i) { double[] matrix = MatrixInput(horizon, i, j, false); double prediction = network.Run(matrix)[0]; // TODO : Assumes only one result probabilityGrid[i, j] = prediction; } } return(probabilityGrid); }
/// <summary> /// Compute a normalized correspondence value between two grids of the same dimensions. /// </summary> /// <param name="otherGrid">The grid against which this grid will be compared.</param> /// <returns> /// A number between 0.0 and 1.0 indicating the proportion of corresponding /// grid nodes which either both contain a value, or both contain a null. /// </returns> public double Correspondence(IRegularGrid2D otherGrid) { Debug.Assert(this.SizeI == otherGrid.SizeI); Debug.Assert(this.SizeJ == otherGrid.SizeJ); int correspondence = 0; for (int i = 0; i < SizeI; ++i) { for (int j = 0; j < SizeJ; ++j) { if (this[i, j].HasValue == otherGrid[i, j].HasValue) { correspondence += 1; } } } return((double)correspondence / (double)zs.Length); }
private static void RecordBest(IRegularGrid2D targetGrid, Population population, int generation, RectangularDomain domain) { List <Individual> best = population.Best; for (int j = 0; j < best.Count; ++j) { Console.Write("best[{0}] = [", j); foreach (double f in best[j].Fitness) { Console.Write(f); Console.Write(" "); } Console.WriteLine("] with {0} genes", best[j].Genome.Count); // Express the genome to create a grid Individual bestIndividual = (Individual)best[j].Clone(); Grid2DPhenotype bestPhenotype = (Grid2DPhenotype)bestIndividual.Phenome; bestPhenotype.Grid.MaskFrom(targetGrid); StringBuilder gridFileName = new StringBuilder(); gridFileName.AppendFormat("evolved_{0}_{1}.grd", generation + 1, j); bestPhenotype.Grid.WriteSurfer6BinaryFile(gridFileName.ToString()); ReportLogger.Instance.Writer.WriteStartElement("Grid"); ReportLogger.Instance.Writer.WriteStartAttribute("file"); ReportLogger.Instance.Writer.WriteValue(gridFileName.ToString()); ReportLogger.Instance.Writer.WriteEndAttribute(); ReportLogger.Instance.Writer.WriteEndElement(); // Express the genome to create a fault polygon map OutlineMapDomain mapDomain = new OutlineMapDomain(domain); OutlineMapPhenotype mapPhenotype = (OutlineMapPhenotype)bestIndividual.Genome.Express(mapDomain); StringBuilder polygonFileName = new StringBuilder(); polygonFileName.AppendFormat("evolved_{0}_{1}.poly", generation + 1, j); using (StreamWriter writer = File.CreateText(polygonFileName.ToString())) { writer.Write(mapPhenotype.ToString()); } ReportLogger.Instance.Writer.WriteStartElement("Polygons"); ReportLogger.Instance.Writer.WriteStartAttribute("file"); ReportLogger.Instance.Writer.WriteValue(polygonFileName.ToString()); ReportLogger.Instance.Writer.WriteEndAttribute(); ReportLogger.Instance.Writer.WriteEndElement(); } }
public void Learn(IRegularGrid2D input, IRegularGrid2D expected) { // Build the training samples for (int j = 0; j < input.SizeJ; ++j) { for (int i = 0; i < input.SizeI; ++i) { double[] inValues = MatrixInput(input, i, j, true); double[] expectedValues = TrainingExpected(expected, i, j); network.TrainingSamples.Add(new TrainingSample(inValues, expectedValues)); } } network.Learn(); network.Save("athena.net"); //double[] validate1 = network.Run(new double[] { 0.013, -0.026, -0.060, 0.043, 0.0, -0.037, 0.013, -0.026, -0.060 }); // 0.0 //double[] validate2 = network.Run(new double[] { 0.134, 0.050, -0.004, 0.078, 0.0, -0.034, 0.031, -0.044, -0.062 }); // 0.49 //double[] validate3 = network.Run(new double[] { -0.060, 0.071, 0.246, -0.170, 0.0, 0.296, -0.277, 0.327, 0.943 }); // 0.94 }
/// <summary> /// Returns the array of normalised training values for the /// specified grid node, or null if the specified grid node /// has no value. /// </summary> /// <param name="i"></param> /// <param name="j"></param> /// <returns>Either an array of numInputNodes doubles, or null.</returns> private double[] MatrixInput(IRegularGrid2D grid, int i, int j, bool deBias) { Debug.Assert(grid != null); if (!grid[i, j].HasValue) { return(null); } double zCentre = grid[i, j].Value; int centre = (matrixWidth - 1) / 2; // Must return a 1D array, since that's what training sample requires double[] matrix = new double[matrixWidth * matrixWidth]; for (int q = 0; q < matrixWidth; ++q) { for (int p = 0; p < matrixWidth; ++p) { int relativeI = p - centre; int relativeJ = q - centre; int absoluteI = i + relativeI; int absoluteJ = j + relativeJ; int index = q * matrixWidth + p; double?z = PaddedGridValue(grid, absoluteI, absoluteJ); Debug.Assert(z.HasValue); // TODO: Assumes square cells double zDiff = z.Value - zCentre; double zNorm = zDiff / grid.Spacing.DeltaX; matrix[index] = zNorm; } } if (deBias) { DeBiasMatrix(matrix, centre, matrixWidth); } return(matrix); }
/// <summary> /// Returns the value for the specified grid cell, padding data off the image /// boundaries to allow matrix sampling to work right up to the image edges. /// This version reflects the data at the image boundaries. /// </summary> /// <param name="grid">The grid</param> /// <param name="absoluteI">The column coordinate</param> /// <param name="absoluteJ">The row coodinate</param> /// <returns>Either a real grid value, for in-range i and j, or an interpolated value</returns> private double?PaddedGridValue(IRegularGrid2D grid, int absoluteI, int absoluteJ) { // Modify i co-ordinate if necessary if (absoluteI < 0) { absoluteI = 0 - absoluteI; } else if (absoluteI > grid.SizeI - 1) { absoluteI = 2 * (grid.SizeI - 1) - absoluteI; } // Modify j co-ordinate if necessary if (absoluteJ < 0) { absoluteJ = 0 - absoluteJ; } else if (absoluteJ > grid.SizeJ - 1) { absoluteJ = 2 * (grid.SizeJ - 1) - absoluteJ; } return(grid[absoluteI, absoluteJ]); }
private double[] TrainingExpected(IRegularGrid2D grid, int i, int j) { Debug.Assert(grid[i, j].HasValue); return(new double[] { grid[i, j].Value }); }
static void Main(string[] args) { Uri faultProbabilityUri = UriFromArg(args, 0); Uri horizonUri = UriFromArg(args, 1); GeodysseyModel model = new GeodysseyModel(); LoaderController.Instance.Open(faultProbabilityUri, model); IRegularGrid2D pFaultGrid = model[0]; // The first grid LoaderController.Instance.Open(horizonUri, model); IRegularGrid2D horizon = model[1]; // Horizon grid GridImage pFaultImage = new GridImage(pFaultGrid); GridImage pFaultImageX = (GridImage)pFaultImage.Clone(); pFaultImageX.Clear(); GridImage pFaultImageY = (GridImage)pFaultImage.Clone(); pFaultImageY.Clear(); Convolver.GaussianGradient(pFaultImage, pFaultImageX, pFaultImageY, 1.0); GridImage pFaultImageXX = (GridImage)pFaultImage.Clone(); pFaultImageXX.Clear(); GridImage pFaultImageYY = (GridImage)pFaultImage.Clone(); pFaultImageYY.Clear(); GridImage pFaultImageXY = (GridImage)pFaultImage.Clone(); pFaultImageXY.Clear(); Convolver.HessianMatrixOfGaussian(pFaultImage, pFaultImageXX, pFaultImageYY, pFaultImageXY, 1.0); //GridImage pFaultImageBeta = (GridImage) RidgeDetector.PrincipleCurvatureDirection(pFaultImageXX, pFaultImageYY, pFaultImageXY); //GridImage pFaultImagePQ = (GridImage) RidgeDetector.LocalLpq(pFaultImageXX, pFaultImageYY, pFaultImageXY, pFaultImageBeta); //GridImage pFaultImageP = (GridImage) RidgeDetector.LocalLp(pFaultImageX, pFaultImageY, pFaultImageBeta); //GridImage pFaultImageQ = (GridImage) RidgeDetector.LocalLq(pFaultImageX, pFaultImageY, pFaultImageBeta); //GridImage pFaultImagePP = (GridImage) RidgeDetector.LocalLpp(pFaultImageXX, pFaultImageYY, pFaultImageXY, pFaultImageBeta); //GridImage pFaultImageQQ = (GridImage) RidgeDetector.LocalLqq(pFaultImageXX, pFaultImageYY, pFaultImageXY, pFaultImageBeta); Trace.WriteLine("Ridge detector"); GridImage pFaultImageRidge = (GridImage)RidgeDetector.Detect(pFaultImageX, pFaultImageY, pFaultImageXX, pFaultImageYY, pFaultImageXY); IImage <bool> ridge = pFaultImageRidge.CreateBinaryImage(0.0); Trace.WriteLine("Pepper filter"); IImage <bool> filtered = Morphology.PepperFiltering(5, ridge); Trace.WriteLine("Closing gaps"); IImage <bool> closed = Morphology.Closing(filtered); Trace.WriteLine("Thinning until convergence"); IImage <bool> thinned = Morphology.ThinUntilConvergence(closed); Trace.WriteLine("Thinning blocks until convergence"); IImage <bool> blockthinned = Morphology.ThinBlockUntilConvergence(thinned); Trace.WriteLine("Filling"); IImage <bool> filled = Morphology.Fill(blockthinned); Trace.WriteLine("Connectivity"); IImage <int> connectivity = BitImage.Analysis.Connectivity(filled); Trace.WriteLine("Connected components"); IImage <int> components = BitImage.Analysis.ConnectedComponents(filled); Trace.WriteLine("Mapping faults"); FaultNetwork network = FaultNetworkMapper.MapFaultNetwork(filled, horizon); Trace.WriteLine("Mapping displacements"); FaultDisplacementMapper displacementMapper = new FaultDisplacementMapper(network); var mesh = displacementMapper.GetResult(); // Output files of mesh Trace.WriteLine("Writing faults"); string faultSegmentsPath = faultProbabilityUri.LocalPath.Replace(".grd", "_faults.poly"); string monoSegmentsPath = faultProbabilityUri.LocalPath.Replace(".grd", "_mono.poly"); using (StreamWriter faultFile = new StreamWriter(faultSegmentsPath)) using (StreamWriter monoFile = new StreamWriter(monoSegmentsPath)) { foreach (EdgeBase edge in mesh.Edges) { StreamWriter file = edge is FaultEdge ? faultFile : monoFile; Point2D source = ((PositionedVertexBase)edge.Source).Position; Point2D target = ((PositionedVertexBase)edge.Target).Position; file.WriteLine("{0}\t{1}", source.X, source.Y); file.WriteLine("{0}\t{1}", target.X, target.Y); file.WriteLine("%"); } } // Establish order in the mesh Trace.WriteLine("Build planar subdivision - Ordering mesh and inserting faces"); var orderer = new Orderer2D <PositionedVertexBase, EdgeBase, FaceBase>(mesh); var orderedMesh = orderer.GetResult(); Debug.Assert(orderedMesh.Euler == 2); // Triangulate the mesh // Copy the list of monotone faces, so we can iterate over it it // whilst modifying the faces in the mesh during triangulation. Trace.WriteLine("Triangulating"); List <FaceBase> faces = new List <FaceBase>(orderedMesh.Faces); foreach (FaceBase face in faces) { var triangulator = new MonotonePolygonTriangulator <PositionedVertexBase, EdgeBase, FaceBase>(orderedMesh, face); triangulator.GetResult(); } // Improve triangulation quality var improver = new TriangulationQualityImprover <PositionedVertexBase, EdgeBase, FaceBase>(mesh); // TODO: Add a flippable critera improver.Improve(); Trace.WriteLine("Writing mesh"); // Output the mesh Random rng = new Random(); string facesPath = faultProbabilityUri.LocalPath.Replace(".grd", "_faces.poly"); using (StreamWriter facesFile = new StreamWriter(facesPath)) { // All faces except the last one... foreach (FaceBase face in orderedMesh.Faces.Take(orderedMesh.FaceCount - 1)) { foreach (VertexBase vertex in face.Vertices) { PositionedVertexBase pos = (PositionedVertexBase)vertex; Point2D point = pos.Position; facesFile.WriteLine("{0}\t{1}", point.X, point.Y); } int red = rng.Next(255); int green = rng.Next(255); int blue = rng.Next(255); facesFile.WriteLine("% -W0/{0}/{1}/{2} -G{0}/{1}/{2}", red, green, blue); } } // Convert images to grids for convenient output //GridImage filteredGrid = (GridImage) pFaultImageRidge.Clone(); //for (int i = 0; i < filteredGrid.Width; ++i) //{ // for (int j = 0; j < filteredGrid.Height; ++j) // { // filteredGrid[i, j] = filtered[i, j] ? 1.0 : 0.0; // } //} //GridImage closedGrid = (GridImage) pFaultImageRidge.Clone(); //for (int i = 0; i < closedGrid.Width; ++i) //{ // for (int j = 0; j < closedGrid.Height; ++j) // { // closedGrid[i, j] = closed[i, j] ? 1.0 : 0.0; // } //} //GridImage thinnedGrid = (GridImage) pFaultImageRidge.Clone(); //for (int i = 0; i < thinnedGrid.Width; ++i) //{ // for (int j = 0; j < thinnedGrid.Height; ++j) // { // thinnedGrid[i, j] = thinned[i, j] ? 1.0 : 0.0; // } //} //GridImage blockThinnedGrid = (GridImage) pFaultImageRidge.Clone(); //for (int i = 0; i < blockThinnedGrid.Width; ++i) //{ // for (int j = 0; j < blockThinnedGrid.Height; ++j) // { // blockThinnedGrid[i, j] = blockthinned[i, j] ? 1.0 : 0.0; // } //} GridImage filledGrid = (GridImage)pFaultImageRidge.Clone(); for (int i = 0; i < filledGrid.Width; ++i) { for (int j = 0; j < filledGrid.Height; ++j) { filledGrid[i, j] = filled[i, j] ? 1.0 : 0.0; } } //GridImage connectivityGrid = (GridImage) pFaultImageRidge.Clone(); //for (int i = 0; i < filledGrid.Width; ++i) //{ // for (int j = 0; j < filledGrid.Height; ++j) // { // connectivityGrid[i, j] = connectivity[i, j]; // } //} //GridImage componentsGrid = (GridImage) pFaultImageRidge.Clone(); //for (int i = 0; i < componentsGrid.Width; ++i) //{ // for (int j = 0; j < componentsGrid.Height; ++j) // { // componentsGrid[i, j] = components[i, j]; // } //} //string pathX = faultProbabilityUri.LocalPath.Replace(".", "_x."); //string pathY = faultProbabilityUri.LocalPath.Replace(".", "_y."); //string pathXX = faultProbabilityUri.LocalPath.Replace(".", "_xx."); //string pathYX = faultProbabilityUri.LocalPath.Replace(".", "_yy."); //string pathXY = faultProbabilityUri.LocalPath.Replace(".", "_xy."); //string pathBeta = faultProbabilityUri.LocalPath.Replace(".", "_beta."); //string pathPQ = faultProbabilityUri.LocalPath.Replace(".", "_pq."); //string pathP = faultProbabilityUri.LocalPath.Replace(".", "_p."); //string pathQ = faultProbabilityUri.LocalPath.Replace(".", "_q."); //string pathPP = faultProbabilityUri.LocalPath.Replace(".", "_pp."); //string pathQQ = faultProbabilityUri.LocalPath.Replace(".", "_qq."); //string pathRidge = faultProbabilityUri.LocalPath.Replace(".", "_ridge."); //string pathFiltered = faultProbabilityUri.LocalPath.Replace(".", "_filtered."); //string pathClosed = faultProbabilityUri.LocalPath.Replace(".", "_closed."); //string pathThinned = faultProbabilityUri.LocalPath.Replace(".", "_thinned."); //string pathBlockThinned = faultProbabilityUri.LocalPath.Replace(".", "_blockthinned."); string pathFilled = faultProbabilityUri.LocalPath.Replace(".", "_filled."); //string pathConnectivity = faultProbabilityUri.LocalPath.Replace(".", "_connectivity."); //string pathComponents = faultProbabilityUri.LocalPath.Replace(".", "_components."); //string pathFaultLines = faultProbabilityUri.LocalPath.Replace(".grd", "_faults.poly"); string pathBisectors = faultProbabilityUri.LocalPath.Replace(".grd", "_bisectors.poly"); string pathLabels = faultProbabilityUri.LocalPath.Replace(".grd", "_labels.xy"); string pathStrands = faultProbabilityUri.LocalPath.Replace(".grd", "_strands.poly"); //pFaultImageX.Grid.WriteSurfer6BinaryFile(pathX); //pFaultImageY.Grid.WriteSurfer6BinaryFile(pathY); //pFaultImageXX.Grid.WriteSurfer6BinaryFile(pathXX); //pFaultImageYY.Grid.WriteSurfer6BinaryFile(pathXY); //pFaultImageXY.Grid.WriteSurfer6BinaryFile(pathXY); //pFaultImageBeta.Grid.WriteSurfer6BinaryFile(pathBeta); //pFaultImagePQ.Grid.WriteSurfer6BinaryFile(pathPQ); //pFaultImageP.Grid.WriteSurfer6BinaryFile(pathP); //pFaultImageQ.Grid.WriteSurfer6BinaryFile(pathQ); //pFaultImagePP.Grid.WriteSurfer6BinaryFile(pathPP); //pFaultImageQQ.Grid.WriteSurfer6BinaryFile(pathQQ); //pFaultImageRidge.Grid.WriteSurfer6BinaryFile(pathRidge); //filteredGrid.Grid.WriteSurfer6BinaryFile(pathFiltered); //closedGrid.Grid.WriteSurfer6BinaryFile(pathClosed); //thinnedGrid.Grid.WriteSurfer6BinaryFile(pathThinned); //blockThinnedGrid.Grid.WriteSurfer6BinaryFile(pathBlockThinned); filledGrid.Grid.WriteSurfer6BinaryFile(pathFilled); //connectivityGrid.Grid.WriteSurfer6BinaryFile(pathConnectivity); //componentsGrid.Grid.WriteSurfer6BinaryFile(pathComponents); //mapper.OutputPolygons(pathFaultLines); //displacementMapper.OutputBisectors(pathBisectors); //displacementMapper.OutputLabels(pathLabels); //displacementMapper.OutputStrands(pathStrands); }
public void Add(IRegularGrid2D grid) { grids.Add(grid); //Console.WriteLine(grid.ToString()); }
public Grid2DPhenotype(IRegularGrid2D grid) : base(null) { this.grid = grid; }
/// <summary> /// Construct from a grid. The grid is not copied. The image serves as /// an adaptor for the grid. /// </summary> /// <param name="grid"></param> public GridImage(IRegularGrid2D grid) { this.grid = grid; }
/// <summary> /// Compute the Root Mean Square difference betweeen two grids of the same dimensions. /// Nodes which are null in either grid will be ignored. /// </summary> /// <param name="otherGrid">The grid against which this grid will be compared.</param> /// <returns>The Root Mean Square difference of the z values.</returns> public double?RmsDifference(IRegularGrid2D otherGrid) { return(RmsDifference(otherGrid, 0, SizeI, 0, SizeJ)); }
static void Main(string[] args) { Uri horizonUri = UriFromArg(args, 0); GeodysseyModel model = new GeodysseyModel(); LoaderController.Instance.Open(horizonUri, model); IRegularGrid2D horizon = model[0]; //string pathOriginal = horizonUri.LocalPath.Replace(".dat", ".grd"); //horizon.WriteSurfer6BinaryFile(pathOriginal); // TODO: Make IRegularGrid IEnumerable var extentMap = new FastImage <bool>(horizon.SizeI, horizon.SizeJ, horizon.Select(item => item.HasValue)); IImage <bool> faultMap = Morphology.Invert(extentMap); IImage <double> distanceMap = DistanceMap.EuclideanTransform(extentMap); // Remove anything above a threshold distance from data const double threshold = 50; var clippedFaultMap = extentMap.CloneTransform((i, j) => distanceMap[i, j] < threshold && faultMap[i, j]); Trace.WriteLine("Pepper filter"); IImage <bool> filtered = Morphology.PepperFiltering(5, clippedFaultMap); Trace.WriteLine("Closing gaps"); IImage <bool> closed = Morphology.Closing(filtered); Trace.WriteLine("Thinning until convergence"); IImage <bool> thinned = Morphology.ThinUntilConvergence(closed); Trace.WriteLine("Thinning blocks until convergence"); IImage <bool> blockthinned = Morphology.ThinBlockUntilConvergence(thinned); Trace.WriteLine("Filling"); IImage <bool> filled = Morphology.Fill(blockthinned); WriteBinaryImageSurfer6Grid(horizon, filled, horizonUri.LocalPath.Replace(".grd", "_filled.grd")); //// Create a double valued 'binary' image showing the extent of the horizon data //FastImage<double> extentMap = new FastImage<double>(horizon.SizeI, horizon.SizeJ); //for (int i = 0; i < horizon.SizeI; ++i) //{ // for (int j = 0; j < horizon.SizeJ; ++j) // { // bool hasValue = horizon[i, j].HasValue; // extentMap[i, j] = hasValue ? 1.0 : 0.0; // } //} //int extent = extentMap.Where(v => v == 1.0).Count(); //double extentProportion = (double) extent / (extentMap.Width * extentMap.Height); //IImage<double> scaledExtentMap = Scaler.Downscale(extentMap, 5); //IImage<double> smoothedExtentMap = scaledExtentMap.CloneSize(); //Convolver.GaussianSmooth(scaledExtentMap, smoothedExtentMap, 3.0); //IRegularGrid2D smoothedGrid = horizon.CloneSize(smoothedExtentMap.Width, smoothedExtentMap.Height); //for (int i = 0 ; i < smoothedGrid.SizeI; ++i) //{ // for (int j = 0 ; j < smoothedGrid.SizeJ; ++j) // { // smoothedGrid[i, j] = smoothedExtentMap[i, j]; // } //} //PriorityQueue<double> orderedIntensities = PriorityQueue<double>.CreateHighFirstOut(smoothedExtentMap); //int k = (int) (extentProportion * orderedIntensities.Count); //Debug.Assert(k >= 0); //for (int i = 0 ; i < k - 1; ++i) //{ // orderedIntensities.Dequeue(); //} //double threshold = orderedIntensities.Dequeue(); //string pathSmoothed = horizonUri.LocalPath.Replace(".grd", "_smoothed.grd"); //smoothedGrid.WriteSurfer6BinaryFile(pathSmoothed); //IImage<bool> thresholdMap = BitImage.Analysis.Threshold(smoothedExtentMap, threshold * 2.0); //int actual = thresholdMap.Where(v => v).Count(); //double actualProportion = (double) actual / (thresholdMap.Width * thresholdMap.Height); //IRegularGrid2D thresholdGrid = horizon.CloneSize(thresholdMap.Width, thresholdMap.Height); //for (int i = 0; i < smoothedGrid.SizeI; ++i) //{ // for (int j = 0; j < smoothedGrid.SizeJ; ++j) // { // thresholdGrid[i, j] = thresholdMap[i, j] ? 1.0 : 0.0; // } //} //string pathThresholded = horizonUri.LocalPath.Replace(".grd", "_thresholded.grd"); //thresholdGrid.WriteSurfer6BinaryFile(pathThresholded); //IImage<double> distanceMap = DistanceMap.EuclideanTransform(scaledExtentMap); // Convert the image back to a grid for convenient output IRegularGrid2D distanceGrid = horizon.CloneSize(distanceMap.Width, distanceMap.Height); for (int i = 0; i < distanceMap.Width; ++i) { for (int j = 0; j < distanceMap.Height; ++j) { distanceGrid[i, j] = distanceMap[i, j]; } } string pathDistance = horizonUri.LocalPath.Replace(".grd", "_distance.grd"); distanceGrid.WriteSurfer6BinaryFile(pathDistance); }
static int Main(string[] args) { // Get a URI from the command line argument Uri uri; try { uri = new Uri(args[0]); } catch (UriFormatException) { string absPath = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + args[0]; try { uri = new Uri(absPath); } catch (UriFormatException) { return(1); } } ReportLogger.Instance.Create("report.xml"); ReportLogger.Instance.Writer.WriteStartDocument(); ReportLogger.Instance.Writer.WriteStartElement("GeodysseyRun"); Stopwatch overallWatch = new Stopwatch(); overallWatch.Start(); //Console.WriteLine("Start!"); int initialMinimumGenomeLength = 50; int initialMaximumGenomeLength = 100; int initialPopulationSize = 1000; int finalPopulationSize = 100; int numberOfGenerations = 100; double populationPowerBase = Math.Pow((double)finalPopulationSize / (double)initialPopulationSize, 1.0 / numberOfGenerations); int totalNumberOfIndividuals = 0; // Determine how many individuals will be produced in this run for (int i = 0; i < numberOfGenerations; ++i) { int inc = (int)Math.Round(initialPopulationSize * Math.Pow(populationPowerBase, i + 1)); //Console.WriteLine(inc); totalNumberOfIndividuals += inc; } Console.WriteLine("Total Number of Individuals = {0}", totalNumberOfIndividuals); Console.WriteLine("Mean Invididuals per Generation = {0}", totalNumberOfIndividuals / numberOfGenerations); // Load a target grid //RegularGrid2D targetGrid; //using (StreamReader reader = File.OpenText("target.grd")) //{ // targetGrid = RegularGrid2D.Create(reader); //} GeodysseyModel model = new GeodysseyModel(); LoaderController.Instance.Open(uri, model); IRegularGrid2D targetGrid = model[0]; // The first grid Debug.Assert(targetGrid != null); Grid2DDomain domain = new Grid2DDomain(targetGrid); Stopwatch stopWatch = new Stopwatch(); Population population = new Population(domain, initialPopulationSize, initialMinimumGenomeLength, initialMaximumGenomeLength); for (int i = 0; i < numberOfGenerations; ++i) { stopWatch.Reset(); stopWatch.Start(); population.ComputeFitnesses(); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; ReportLogger.Instance.Writer.WriteStartElement("Generation"); ReportLogger.Instance.Writer.WriteStartAttribute("number"); ReportLogger.Instance.Writer.WriteValue(i + 1); ReportLogger.Instance.Writer.WriteEndAttribute(); ReportLogger.Instance.Writer.WriteStartAttribute("elapsedTime"); ReportLogger.Instance.Writer.WriteValue(ts); ReportLogger.Instance.Writer.WriteEndAttribute(); RecordBest(targetGrid, population, i, domain); population.LogSummaryStatistics(); ReportLogger.Instance.Writer.WriteEndElement(); Console.WriteLine("Generation {0} of {1} with size {2} in {3}) ", i + 1, numberOfGenerations, population.Count, ts); int nextGenerationSize = (int)Math.Round(initialPopulationSize * Math.Pow(populationPowerBase, i + 1)); population.Evolve(nextGenerationSize); } population.ComputeFitnesses(); RecordBest(targetGrid, population, numberOfGenerations, domain); Console.WriteLine("Generation {0} of {1} with size {2}) ", numberOfGenerations, numberOfGenerations, population.Count); overallWatch.Stop(); Console.WriteLine("Running time : {0}", overallWatch.Elapsed); ReportLogger.Instance.Writer.WriteEndElement(); ReportLogger.Instance.Writer.WriteEndDocument(); ReportLogger.Instance.Close(); Console.ReadKey(); return(0); }