/// <summary> /// Only works on English, as it is hard coded for using the /// Morphology class, which is English-only /// </summary> public virtual IList <CoreLabel> Lemmatize <_T0>(IList <_T0> tokens) where _T0 : IHasWord { IList <TaggedWord> tagged; if (GetOp().testOptions.preTag) { IFunction <IList <IHasWord>, IList <TaggedWord> > tagger = LoadTagger(); tagged = tagger.Apply(tokens); } else { Tree tree = Parse(tokens); tagged = tree.TaggedYield(); } Morphology morpha = new Morphology(); IList <CoreLabel> lemmas = Generics.NewArrayList(); foreach (TaggedWord token in tagged) { CoreLabel label = new CoreLabel(); label.SetWord(token.Word()); label.SetTag(token.Tag()); morpha.Stem(label); lemmas.Add(label); } return(lemmas); }
/// <summary> /// Create a new /// <c>WordLemmaTag</c> /// from a Label. The value of /// the Label corresponds to the word of the WordLemmaTag. /// </summary> /// <param name="word">This word is passed to the supertype constructor</param> /// <param name="tag"> /// The /// <c>value()</c> /// of this Label is set as the /// tag of this Label /// </param> public WordLemmaTag(ILabel word, ILabel tag) : this(word) { WordTag wT = new WordTag(word, tag); this.lemma = Morphology.StemStatic(wT).Word(); SetTag(tag.Value()); }
/// <summary> /// If a token is a phrasal verb with an underscore between a verb and a /// particle, return the phrasal verb lemmatized. /// </summary> /// <remarks> /// If a token is a phrasal verb with an underscore between a verb and a /// particle, return the phrasal verb lemmatized. If not, return null /// </remarks> private static string PhrasalVerb(Morphology morpha, string word, string tag) { // must be a verb and contain an underscore System.Diagnostics.Debug.Assert((word != null)); System.Diagnostics.Debug.Assert((tag != null)); if (!tag.StartsWith("VB") || !word.Contains("_")) { return(null); } // check whether the last part is a particle string[] verb = word.Split("_"); if (verb.Length != 2) { return(null); } string particle = verb[1]; if (particles.Contains(particle)) { string @base = verb[0]; string lemma = morpha.Lemma(@base, tag); return(lemma + '_' + particle); } return(null); }
///// <summary> ///// Computes the augmented rotation matrix for an augmented 2D point around the origin ///// </summary> ///// <param name="theta">The clockwise rotation angle in radians</param> ///// <returns>The augmented (3x3) 2D rotation matrix</returns> //public static Matrix<double> RotationMatrix(double theta) //{ // return DenseMatrix.OfArray(new double[,] // { // {Math.Cos(theta), Math.Sin(theta), 0 }, // {-1*Math.Sin(theta), Math.Cos(theta), 0 }, // {0, 0, 1 } // }); //} ///// <summary> ///// Computes the augmented translation matrix for an augmented 2D point ///// </summary> ///// <param name="dx">Translation amount in x direction</param> ///// <param name="dy">Translation amount in y direction</param> ///// <returns>The augmented (3x3) 2D translation matrix</returns> //public static Matrix<double> TranslationMatrix(double dx, double dy) //{ // return DenseMatrix.OfArray(new double[,] // { // {1, 0, dx }, // {0, 1, dy }, // {0, 0, 1 } // }); //} ///// <summary> ///// Augments a 2D coordinate point ///// </summary> ///// <param name="px">The x-coordinate</param> ///// <param name="py">The y-coordinate</param> ///// <returns>A 3 element vector comprising the point</returns> //public static Vector<double> Augment2DCoordinate(double px, double py) //{ // return DenseVector.OfArray(new double[] { px, py, 1 }); //} ///// <summary> ///// Composes (multiplies) a list of transformation matrices in order ///// NOTE: List should be ordered in order of application which needs to be reversed for the composition! ///// </summary> ///// <param name="matrices">List of transformations to compose</param> ///// <returns>The composed matrix</returns> //public static Matrix<double> Compose(List<Matrix<double>> matrices) //{ // Matrix<double> m = DenseMatrix.CreateIdentity(3); // for(int i = matrices.Count-1; i>=0; i--) // m *= matrices[i]; // return m; //} ///// <summary> ///// Applies transformation to given point ///// </summary> ///// <param name="p"></param> ///// <param name="T"></param> ///// <returns></returns> //public static IppiPoint TransformPoint(IppiPoint p, Matrix<double> T) //{ // Vector<double> result = Augment2DCoordinate(p.x, p.y) * T; // return new IppiPoint((int)result[0], (int)result[1]); //} ///// <summary> ///// Applies transformation to given point ///// </summary> ///// <param name="p"></param> ///// <param name="T"></param> ///// <returns></returns> //public static IppiPoint_32f TransformPoint(IppiPoint_32f p, Matrix<double> T) //{ // Vector<double> result = T * Augment2DCoordinate(p.x, p.y); // return new IppiPoint_32f((float)result[0], (float)result[1]); //} /// <summary> /// Method for creating image background /// </summary> /// <param name="frameNumber">The current camera frame number</param> /// <param name="camImage">The camera image</param> /// <param name="poi">A detected centroid (all null)</param> protected void BuildBackground(int frameNumber, Image8 camImage, out IppiPoint?poi) { _laser.LaserPower = 0; poi = null; if (frameNumber == 0 || _bgModel == null) { _bgModel = new DynamicBackgroundModel(camImage, 1.0f / Properties.Settings.Default.FrameRate); _fgModel = new DynamicBackgroundModel(camImage, 5.0f / Properties.Settings.Default.FrameRate); //Create image intermediates _calc = new Image8(camImage.Size); _foreground = new Image8(camImage.Size); _strel3x3 = Morphology.Generate3x3Mask(camImage.Size); //Initialize buffer for label markers int bufferSize = 0; cv.ippiLabelMarkersGetBufferSize_8u_C1R(camImage.Size, &bufferSize); if (_markerBuffer != null) { Marshal.FreeHGlobal((IntPtr)_markerBuffer); _markerBuffer = null; } _markerBuffer = (byte *)Marshal.AllocHGlobal(bufferSize); } else { _bgModel.UpdateBackground(camImage); } if (frameNumber >= Properties.Settings.Default.FrameRate * 5) { _experimentPhase = ExperimentPhases.ThreePoint; _threePointFrame = 0; _threePointPoints = new CalibrationPoints(); } }
public Tracker90mmDish(int imageWidth, int imageHeight, IppiPoint dishCenter) { _foreground = new Image8(imageWidth, imageHeight); _bgSubtracted = new Image8(imageWidth, imageHeight); _calc = new Image8(imageWidth, imageHeight); _dishCenter = dishCenter; int bufferSize = 0; IppHelper.IppCheckCall(cv.ippiLabelMarkersGetBufferSize_8u_C1R(new IppiSize(imageWidth, imageHeight), &bufferSize)); _markerBuffer = (byte *)Marshal.AllocHGlobal(bufferSize); int momentSize = 0; IppHelper.IppCheckCall(ip.ippiMomentGetStateSize_64f(IppHintAlgorithm.ippAlgHintNone, &momentSize)); _momentState = (IppiMomentState_64f *)Marshal.AllocHGlobal(momentSize); //let ipp decide whether to give accurate or fast results IppHelper.IppCheckCall(ip.ippiMomentInit_64f(_momentState, IppHintAlgorithm.ippAlgHintNone)); _frame = 0; //populate tracking parameters with default values _threshold = 6; _minArea = 11; _maxAllowedArea = 120; _minEccentricity = 0.3; _fullTrustMinArea = 20; _imageROI = new IppiROI(0, 0, imageWidth, imageHeight); _searchRegionSize = 90; _removeCMOSISBrightLineArtefact = false; _strel3x3 = Morphology.Generate3x3Mask(_foreground.Size); //The following calculation for FramesInBackground means that after ~30s of movie //a stationary object will have dissappeared into the background (at 63% level) FramesInBackground = (int)((30 * 250)); FramesInitialBackground = 2 * 30 * 250; BGUpdateEvery = 2; }
public virtual void Annotate(Annotation annotation) { if (Verbose) { log.Info("Finding lemmas ..."); } Morphology morphology = new Morphology(); if (annotation.ContainsKey(typeof(CoreAnnotations.SentencesAnnotation))) { foreach (ICoreMap sentence in annotation.Get(typeof(CoreAnnotations.SentencesAnnotation))) { IList <CoreLabel> tokens = sentence.Get(typeof(CoreAnnotations.TokensAnnotation)); //log.info("Lemmatizing sentence: " + tokens); foreach (CoreLabel token in tokens) { string text = token.Get(typeof(CoreAnnotations.TextAnnotation)); string posTag = token.Get(typeof(CoreAnnotations.PartOfSpeechAnnotation)); AddLemma(morphology, typeof(CoreAnnotations.LemmaAnnotation), token, text, posTag); } } } else { throw new Exception("Unable to find words/tokens in: " + annotation); } }
public static Bitmap Filter(Bitmap bmp, Morphology type) { MethodInfo method = typeof(ImageFiltering).GetMethod(type.ToString()); Bitmap newBmp = (Bitmap)method.Invoke(null, new object[] { bmp }); return(newBmp); //ImageUtil.SaveImage(filename, newBmp, type.ToString()); }
public virtual Tree TransformTree(Tree t) { Morphology morphology = new Morphology(); IList <TaggedWord> tagged = null; int index = 0; foreach (Tree leaf in t.GetLeaves()) { ILabel label = leaf.Label(); if (label == null) { continue; } string tag; if (!(label is IHasTag) || ((IHasTag)label).Tag() == null) { if (tagged == null) { tagged = t.TaggedYield(); } tag = tagged[index].Tag(); } else { tag = ((IHasTag)label).Tag(); } if (!(label is IHasLemma)) { throw new ArgumentException("Got a tree with labels which do not support lemma"); } ((IHasLemma)label).SetLemma(morphology.Lemma(label.Value(), tag, true)); ++index; } return(t); }
public virtual void SetFromString(string labelStr, string divider) { int first = labelStr.IndexOf(divider); int second = labelStr.LastIndexOf(divider); if (first == second) { SetWord(Sharpen.Runtime.Substring(labelStr, 0, first)); SetTag(Sharpen.Runtime.Substring(labelStr, first + 1)); SetLemma(Morphology.LemmaStatic(Sharpen.Runtime.Substring(labelStr, 0, first), Sharpen.Runtime.Substring(labelStr, first + 1))); } else { if (first >= 0) { SetWord(Sharpen.Runtime.Substring(labelStr, 0, first)); SetLemma(Sharpen.Runtime.Substring(labelStr, first + 1, second)); SetTag(Sharpen.Runtime.Substring(labelStr, second + 1)); } else { SetWord(labelStr); SetLemma(null); SetTag(null); } } }
/// <summary> /// Create a new /// <c>WordLemmaTag</c> /// . /// </summary> /// <param name="word">This word is set as the word of this Label</param> /// <param name="tag"> /// The /// <c>value()</c> /// of this Label is set as the /// tag of this Label /// </param> public WordLemmaTag(string word, string tag) { WordTag wT = new WordTag(word, tag); this.word = word; this.lemma = Morphology.StemStatic(wT).Word(); SetTag(tag); }
/// <param name="t">a tree</param> /// <returns> /// the WordTags corresponding to the leaves of the tree, /// stemmed according to their POS tags in the tree. /// </returns> private static IList <WordTag> GetStemmedWordTagsFromTree(Tree t) { IList <WordTag> stemmedWordTags = Generics.NewArrayList(); List <TaggedWord> s = t.TaggedYield(); foreach (TaggedWord w in s) { WordTag wt = Morphology.StemStatic(w.Word(), w.Tag()); stemmedWordTags.Add(wt); } return(stemmedWordTags); }
protected override void Dispose(bool disposing) { base.Dispose(disposing); if (_bgModel != null) { _bgModel.Dispose(); _bgModel = null; } if (_fgModel != null) { _fgModel.Dispose(); _fgModel = null; } if (_calc != null) { _calc.Dispose(); _calc = null; } if (_foreground != null) { _foreground.Dispose(); _foreground = null; } if (_markerBuffer != null) { Marshal.FreeHGlobal((IntPtr)_markerBuffer); _markerBuffer = null; } if (_laser != null) { _laser.Dispose(); _laser = null; } if (_scanner != null) { _scanner.Hit(new IppiPoint_32f(0.0f, 0.0f)); _scanner.Dispose(); _scanner = null; } if (_strel3x3 != null) { _strel3x3.Dispose(); _strel3x3 = null; } }
private static void ProcessTree(Tree t, string tag, Morphology morpha) { if (t.IsPreTerminal()) { tag = t.Label().Value(); } if (t.IsLeaf()) { t.Label().SetValue(morpha.Lemma(t.Label().Value(), tag)); } else { foreach (Tree kid in t.Children()) { ProcessTree(kid, tag, morpha); } } }
public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as BodyStructure; if (dest == null) { throw new ArgumentException("Can only copy to an object of the same type", "other"); } base.CopyTo(dest); if (Identifier != null) { dest.Identifier = new List <Hl7.Fhir.Model.Identifier>(Identifier.DeepCopy()); } if (ActiveElement != null) { dest.ActiveElement = (Hl7.Fhir.Model.FhirBoolean)ActiveElement.DeepCopy(); } if (Morphology != null) { dest.Morphology = (Hl7.Fhir.Model.CodeableConcept)Morphology.DeepCopy(); } if (Location != null) { dest.Location = (Hl7.Fhir.Model.CodeableConcept)Location.DeepCopy(); } if (LocationQualifier != null) { dest.LocationQualifier = new List <Hl7.Fhir.Model.CodeableConcept>(LocationQualifier.DeepCopy()); } if (DescriptionElement != null) { dest.DescriptionElement = (Hl7.Fhir.Model.FhirString)DescriptionElement.DeepCopy(); } if (Image != null) { dest.Image = new List <Hl7.Fhir.Model.Attachment>(Image.DeepCopy()); } if (Patient != null) { dest.Patient = (Hl7.Fhir.Model.ResourceReference)Patient.DeepCopy(); } return(dest); }
private static void AddLemma(Morphology morpha, Type ann, ICoreMap map, string word, string tag) { if (!tag.IsEmpty()) { string phrasalVerb = PhrasalVerb(morpha, word, tag); if (phrasalVerb == null) { map.Set(ann, morpha.Lemma(word, tag)); } else { map.Set(ann, phrasalVerb); } } else { map.Set(ann, morpha.Stem(word)); } }
/// <summary> /// Creates a new tail tracker /// </summary> /// <param name="regionToTrack">The ROI in which we should track the tail</param> /// <param name="tailStart">The designated starting point of the tail</param> /// <param name="tailEnd">The designated end point of the tail</param> /// <param name="nsegments">The number of tail segments to track btw. start and end</param> public TailTracker(IppiSize imageSize, IppiPoint tailStart, IppiPoint tailEnd, int nsegments) { _threshold = 20; _morphSize = 8; _frameRate = 200; _strel = Morphology.GenerateDiskMask(_morphSize, imageSize); _strel3x3 = Morphology.Generate3x3Mask(imageSize); _nSegments = 5; _imageSize = imageSize; _tailStart = tailStart; _tailEnd = tailEnd; //set up our track regions based on the tail positions DefineTrackRegions(); NSegments = nsegments; InitializeImageBuffers(); //set up image buffers InitializeScanPoints(); //create scan points appropriate for the tail parameters //Initialize our angle store for tracking (size never changes) _angleStore = (int *)System.Runtime.InteropServices.Marshal.AllocHGlobal(900 * 4); }
protected void Dispose(bool IsDisposing) { if (_background != null) { _background.Dispose(); _background = null; } if (_foreground != null) { _foreground.Dispose(); _foreground = null; } if (_thresholded != null) { _thresholded.Dispose(); _thresholded = null; } if (_calc1 != null) { _calc1.Dispose(); _calc1 = null; } if (_strel != null) { _strel.Dispose(); _strel = null; } if (_strel3x3 != null) { _strel3x3.Dispose(); _strel = null; } if (_angleStore != null) { System.Runtime.InteropServices.Marshal.FreeHGlobal((IntPtr)_angleStore); _angleStore = null; } }
private void Dispose(bool disposing) { if (_bgModel != null) { _bgModel.Dispose(); _bgModel = null; } if (_calc != null) { _calc.Dispose(); _calc = null; } if (_foreground != null) { _foreground.Dispose(); _foreground = null; } if (_bgSubtracted != null) { _bgSubtracted.Dispose(); _bgSubtracted = null; } if (_markerBuffer != null) { Marshal.FreeHGlobal((IntPtr)_markerBuffer); _markerBuffer = null; } if (_momentState != null) { Marshal.FreeHGlobal((IntPtr)_momentState); _momentState = null; } if (_strel3x3 != null) { _strel3x3.Dispose(); _strel3x3 = null; } }
private static State <FilterChainState, IEnumerable <XElement> > BuildMorphologyFilter(Morphology morphology, CoordinatesConverter converter) { var svgRadiusX = converter.ScaleDistance(morphology.RadiusX); var svgRadiusY = converter.ScaleDistance(morphology.RadiusY); var core = XElementBuilder.WithName("feMorphology") .Add( new XAttribute("radius", $"{svgRadiusX} {svgRadiusY}"), new XAttribute("operator", morphology.MorphologyType.ToString()) ); return(BuildIOFilter(core).Select(x => x.Build()).Select(x => new[] { x }.AsEnumerable())); }
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 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); }
/// <summary> /// Create a new word, where the label is formed from /// the /// <c>String</c> /// passed in. The String is divided according /// to the divider character. We assume that we can always just /// divide on the rightmost divider character, rather than trying to /// parse up escape sequences. If the divider character isn't found /// in the word, then the whole string becomes the word, and lemma and tag /// are /// <see langword="null"/> /// . /// We assume that if only one divider character is found, word and tag are presents in /// the String, and lemma will be computed. /// </summary> /// <param name="labelStr"> /// The word that will go into the /// <c>Word</c> /// </param> /// <returns>The new WordLemmaTag</returns> public virtual ILabel NewLabelFromString(string labelStr) { int first = labelStr.IndexOf(divider); int second = labelStr.LastIndexOf(divider); if (first == second) { return(new WordLemmaTag(Sharpen.Runtime.Substring(labelStr, 0, first), Morphology.LemmaStatic(Sharpen.Runtime.Substring(labelStr, 0, first), Sharpen.Runtime.Substring(labelStr, first + 1)), Sharpen.Runtime.Substring(labelStr, first + 1))); } else { if (first >= 0) { return(new WordLemmaTag(Sharpen.Runtime.Substring(labelStr, 0, first), Sharpen.Runtime.Substring(labelStr, first + 1, second), Sharpen.Runtime.Substring(labelStr, second + 1))); } else { return(new WordLemmaTag(labelStr)); } } }
/// <summary> /// Serialize to a JSON object /// </summary> public new void SerializeJson(Utf8JsonWriter writer, JsonSerializerOptions options, bool includeStartObject = true) { if (includeStartObject) { writer.WriteStartObject(); } if (!string.IsNullOrEmpty(ResourceType)) { writer.WriteString("resourceType", (string)ResourceType !); } ((fhirCsR4.Models.DomainResource) this).SerializeJson(writer, options, false); if ((Identifier != null) && (Identifier.Count != 0)) { writer.WritePropertyName("identifier"); writer.WriteStartArray(); foreach (Identifier valIdentifier in Identifier) { valIdentifier.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if (Active != null) { writer.WriteBoolean("active", (bool)Active !); } if (Morphology != null) { writer.WritePropertyName("morphology"); Morphology.SerializeJson(writer, options); } if (Location != null) { writer.WritePropertyName("location"); Location.SerializeJson(writer, options); } if ((LocationQualifier != null) && (LocationQualifier.Count != 0)) { writer.WritePropertyName("locationQualifier"); writer.WriteStartArray(); foreach (CodeableConcept valLocationQualifier in LocationQualifier) { valLocationQualifier.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if (!string.IsNullOrEmpty(Description)) { writer.WriteString("description", (string)Description !); } if (_Description != null) { writer.WritePropertyName("_description"); _Description.SerializeJson(writer, options); } if ((Image != null) && (Image.Count != 0)) { writer.WritePropertyName("image"); writer.WriteStartArray(); foreach (Attachment valImage in Image) { valImage.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if (Patient != null) { writer.WritePropertyName("patient"); Patient.SerializeJson(writer, options); } if (includeStartObject) { writer.WriteEndObject(); } }
public TranslationController() { morphology = new Morphology(db); }
public String Stem(String word, string POS) { return(Morphology.stemStatic(word.ToLower(), POS).word()); }
public static string LemmatizeWord(string word, string tag) => Morphology.lemmaStatic(word, tag);