public void MergeTo(VDWidget targetWidget, ElementGroup elementGroup)
        {
            targetWidget.Children.Add(this);
            VDCodeSnippetBody body = this.Store.ElementFactory.CreateElement(VDCodeSnippetBody.DomainClassId) as VDCodeSnippetBody;

            this.Body = body;
        }
Example #2
0
        public void CreateSpriteFromGroup()
        {
            var group = new ElementGroup(0);

            group.CreateSprite("");
            Assert.AreEqual(1, group.ElementList.Count);
        }
Example #3
0
        /// <summary>
        /// Generate an outer glow for the provided rendering element. The glow is defined by the glow
        /// width and the stroke size.
        /// </summary>
        /// <param name="element">rendering element</param>
        /// <param name="color">color of the glow</param>
        /// <param name="glowWidth">the width of the glow</param>
        /// <param name="stroke">the stroke width</param>
        /// <returns>generated outer glow</returns>
        internal static IRenderingElement OuterGlow(IRenderingElement element, Color color, double glowWidth, double stroke)
        {
            switch (element)
            {
            case ElementGroup orgGroup:
                var newGroup = new ElementGroup();
                foreach (var child in orgGroup)
                {
                    newGroup.Add(OuterGlow(child, color, glowWidth, stroke));
                }
                return(newGroup);

            case LineElement lineElement:
                return(new LineElement(lineElement.FirstPoint, lineElement.SecondPoint, stroke + (2 * (glowWidth * stroke)), color));

            case GeneralPath org:
                if (org.Fill)
                {
                    return(org.Outline(2 * (glowWidth * stroke)).Recolor(color));
                }
                else
                {
                    return(org.Outline(stroke + (2 * (glowWidth * stroke))).Recolor(color));
                }

            default:
                throw new ArgumentException($"Cannot generate glow for rendering element,{element.GetType()}");
            }
        }
Example #4
0
        /// <summary>
        /// Allows the model element to configure itself immediately after the Merge process has related it to the target element.
        /// </summary>
        /// <param name="elementGroup">The group of source elements that have been added back into the target store.</param>
        protected override void MergeConfigure(ElementGroup elementGroup)
        {
            base.MergeConfigure(elementGroup);
            LayerPackage.Level = Level;

            DomainClassInfo.SetUniqueName(this,
                                          StrategyManager.GetInstance(Store).NamingStrategy.CreateLayerName(
                                              LayerPackage, this, Name));
            Namespace =
                StrategyManager.GetInstance(Store).NamingStrategy.CreateNamespace(Component.Namespace, Name, this);

            Layer mainLayer = SoftwareComponent.GetMainLayer();

            if (mainLayer == null)
            {
                mainLayer = SoftwareComponent.SuggestMainLayer(null);
                if (mainLayer == this)
                {
                    mainLayer.StartupProject = true;
                    mainLayer.HostingContext = HostingContext.Standalone;
                }
            }
            else if (mainLayer.Level < Level)
            {
                HostingContext = mainLayer.HostingContext;
            }
        }
Example #5
0
 /// <summary>
 /// Override to use our own name handling
 /// </summary>
 protected override void MergeConfigure(ElementGroup elementGroup)
 {
     // UNDONE: Consider providing an ElementNameProvider tied into the
     // appropriate named element dictionary.
     // Do nothing here. The base calls SetUniqueName, but we want
     // all unique name handling to go through our NamedElementDictionary
 }
        private static T CreateChildElement <T>(ModelElement parent, bool raiseInstantiateEvents) where T : ModelElement
        {
            var childClass = parent.Partition.DomainDataDirectory.DomainClasses
                             .FirstOrDefault(dci => typeof(T).IsAssignableFrom(dci.ImplementationClass) && !dci.ImplementationClass.IsAbstract);
            var elementOperations = new ElementOperations(parent.Store, parent.Partition);

            if (elementOperations != null)
            {
                var elementGroupPrototype = new ElementGroupPrototype(parent.Partition, childClass.Id);

                var partition    = elementOperations.ChooseMergeTarget(parent, elementGroupPrototype).Partition;
                var element      = (T)partition.ElementFactory.CreateElement(childClass);
                var elementGroup = new ElementGroup(partition);
                elementGroup.Add(element);
                elementGroup.MarkAsRoot(element);
                elementOperations.MergeElementGroup(parent, elementGroup);

                // Flag the element in the state so that the ProductStore class sees it and doesn't
                // raise the instantiation event.
                if (!raiseInstantiateEvents)
                {
                    element.Store.PropertyBag.Add(element, null);
                }

                return(element);
            }

            return(default(T));
        }
Example #7
0
        private string GetUIStatusCss()
        {
            string matchmodeCSS = GameState.Value.MatchType switch
            {
                MatchType.PlaceTheName => "--place-the-name",
                MatchType.PlaceTheSymbol => "--place-the-symbol",
                _ => throw new NotImplementedException(GameState.Value.MatchType.ToString())
            };

            string sceneTypeCss = NavigationState.Value.Scene switch
            {
                SceneType.ElementsMatchGameOver => "--game-over",
                SceneType.TransitionFromElementsMatchGameToGameOver => "--game-over-sequence",
                SceneType.ElementsMatchGame => "--gameplay",
                SceneType.MainMenu => "",
                _ => throw new NotImplementedException(NavigationState.Value.Scene.ToString())
            };

            string highlightedElementGroup = "";
            byte?  expectedAtomicNumber    = GameState.Value.ExpectedElement;

            if (GameState.Value.HighlighElementsInExpectedGroup && expectedAtomicNumber.HasValue)
            {
                ElementGroup expectedElementGroup =
                    TableOfElementsData.ElementByNumber[expectedAtomicNumber.Value].Group;
                highlightedElementGroup = "--highlight-group" + expectedElementGroup.GetAsCssClass();
            }

            return($"{matchmodeCSS} {sceneTypeCss} {highlightedElementGroup}");
        }
Example #8
0
        /// <inheritdoc/>
        public IRenderingElement Generate(IAtomContainer container, RendererModel model)
        {
            ElementGroup numbers = new ElementGroup();

            if (!model.GetWillDrawAtomNumbers())
            {
                return(numbers);
            }

            var     _offset = model.GetAtomNumberOffset();
            Vector2 offset  = new Vector2(_offset.X, -_offset.Y);

            offset *= (1 / model.GetScale());

            int number = 1;

            foreach (var atom in container.Atoms)
            {
                Vector2 point = atom.Point2D.Value + offset;
                numbers.Add(
                    new TextElement(ToPoint(point), number.ToString(),
                                    model.GetAtomNumberColorByType() ?
                                    model.GetAtomNumberColorer().GetAtomColor(atom) :
                                    model.GetAtomNumberTextColor()));
                number++;
            }
            return(numbers);
        }
Example #9
0
        /// <inheritdoc/>
        public IRenderingElement Generate(IReaction reaction, RendererModel model)
        {
            if (!model.GetShowReactionBoxes())
            {
                return(null);
            }
            var separation  = model.GetBondLength() / model.GetScale();
            var totalBounds = BoundsCalculator.CalculateBounds(reaction);

            if (totalBounds.IsEmpty)
            {
                return(null);
            }

            var diagram         = new ElementGroup();
            var foregroundColor = model.GetForegroundColor();

            diagram.Add(new RectangleElement(new Rect(totalBounds.Left - separation, totalBounds.Top - separation,
                                                      totalBounds.Right + separation, totalBounds.Bottom + separation),
                                             foregroundColor));
            if (reaction.Id != null)
            {
                diagram.Add(new TextElement(new Point((totalBounds.Left + totalBounds.Right) / 2, totalBounds.Top - separation),
                                            reaction.Id, foregroundColor));
            }
            return(diagram);
        }
Example #10
0
        /// <inheritdoc/>
        public IRenderingElement Generate(IReaction reaction, RendererModel model)
        {
            if (!model.GetShowReactionBoxes())
            {
                return(null);
            }
            if (reaction.Reactants.Count == 0)
            {
                return(new ElementGroup());
            }

            double separation  = model.GetBondLength() / model.GetScale() / 2;
            var    totalBounds = BoundsCalculator.CalculateBounds(reaction.Reactants);

            ElementGroup diagram         = new ElementGroup();
            double       minX            = totalBounds.Left;
            double       minY            = totalBounds.Top;
            double       maxX            = totalBounds.Right;
            double       maxY            = totalBounds.Bottom;
            var          foregroundColor = model.GetForegroundColor();

            diagram.Add(new RectangleElement(new Rect(minX - separation, minY - separation, maxX + separation, maxY + separation), foregroundColor));
            diagram.Add(new TextElement(new Point((minX + maxX) / 2, minY - separation), "Reactants", foregroundColor));
            return(diagram);
        }
Example #11
0
		/// <summary>
		/// Override to use our own name handling
		/// </summary>
		protected override void MergeConfigure(ElementGroup elementGroup)
		{
			// UNDONE: Consider providing an ElementNameProvider tied into the
			// appropriate named element dictionary.
			// Do nothing here. The base calls SetUniqueName, but we want
			// all unique name handling to go through our NamedElementDictionary
		}
Example #12
0
        /// <summary>
        /// Called by the Merge process to create a relationship between
        /// this target element and the specified source element.
        /// Typically, a parent-child relationship is established
        /// between the target element (the parent) and the source element
        /// (the child), but any relationship can be established.
        /// </summary>
        /// <param name="sourceElement">The element that is to be related to this model element.</param>
        /// <param name="elementGroup">The group of source ModelElements that have been rehydrated into the target state.</param>
        /// <remarks>
        /// This method is overriden to create the relationship between the target element and the specified source element.
        /// The base method does nothing.
        /// </remarks>
        protected override void MergeRelate(ModelElement sourceElement, ElementGroup elementGroup)
        {
            Guard.NotNull(() => sourceElement, sourceElement);
            Guard.NotNull(() => elementGroup, elementGroup);

            if (sourceElement is AbstractElementSchema)
            {
                var component = sourceElement as AbstractElementSchema;

                this.Store.GetCurrentDiagram().GetRepresentedView().Elements.Add(component);

                return;
            }
            else if (sourceElement is ExtensionPointSchema)
            {
                var component = sourceElement as ExtensionPointSchema;

                this.Store.GetCurrentDiagram().GetRepresentedView().ExtensionPoints.Add(component);

                return;
            }
            else if (sourceElement is ExtensionElement)
            {
                ////TODO: \o/ Remove this once DSL team fixes merging of MEXes
                return;
            }

            base.MergeRelate(sourceElement, elementGroup);
        }
Example #13
0
    private static void internalEventHandler(FeedbackInput sender, ElementGroup group, object value, Func <ButtonPressedEvent, ColorCode> handler)
    {
        var ret = new ButtonPressedEvent()
        {
            Sender         = sender,
            Value          = value,
            ComponentGroup = group,
            SystemTime     = DateTime.Now,
            UnityTime      = new Time()
        };


        switch (handler(ret))
        {
        case ColorCode.Success:
            group.VisibleText.color = SuccessColor;
            break;

        case ColorCode.Hint:
            group.VisibleText.color = HintColor;
            break;

        default:
            group.VisibleText.color = MistakeColor;
            break;
        }
    }
Example #14
0
 /// <inheritdoc/>
 public override IRenderingElement GenerateRingElements(IBond bond, IRing ring, RendererModel model)
 {
     if (RingIsAromatic(ring) &&
         model.GetShowAromaticity() &&
         ring.Atoms.Count < model.GetMaxDrawableAromaticRing())
     {
         var pair = new ElementGroup();
         if (model.GetCDKStyleAromaticity())
         {
             pair.Add(GenerateBondElement(bond, BondOrder.Single, model));
             base.SetOverrideColor(WPF.Media.Colors.LightGray);
             pair.Add(GenerateInnerElement(bond, ring, model));
             base.SetOverrideColor(null);
         }
         else
         {
             pair.Add(GenerateBondElement(bond, BondOrder.Single, model));
             if (!painted_rings.Contains(ring))
             {
                 painted_rings.Add(ring);
                 pair.Add(GenerateRingRingElement(bond, ring, model));
             }
         }
         return(pair);
     }
     else
     {
         return(base.GenerateRingElements(bond, ring, model));
     }
 }
Example #15
0
        private static List <Element> MakeGroup(List <Element> element_list)
        {
            List <Element> grouping_list = new List <Element>();

            for (int i = 0; i < element_list.Count; ++i)
            {
                int j;
                for (j = i + 1; j < element_list.Count; ++j)
                {
                    if (!element_list[j].IsContinue())
                    {
                        break;
                    }
                }
                if (j > i + 1) // Group を作る
                {
                    ElementGroup group = new ElementGroup();
                    group.AddElementRange(element_list.GetRange(i, j - i));
                    grouping_list.Add(group);
                    i = j - 1;
                }
                else // Group を作らない
                {
                    grouping_list.Add(element_list[i]);
                }
            }
            return(grouping_list);
        }
Example #16
0
        public static void GetMotiffs(GetMotiffsParams pars, ElementGroup[] elPeaks, ElementGroup[] elNoise, out Motiff[] mfPeaks, out Motiff[] mfNoise)
        {
            var peakClustering = new Clustering(elPeaks);
            var emptyClustering = new Clustering(elNoise);

            var peakClusters = peakClustering.Work3(pars.CutWeight, pars.Seed, pars.SetCoreWeights);
            var emptyClusters = emptyClustering.Work3(pars.CutWeight, pars.Seed, pars.SetCoreWeights);

            var peakClusters2 = peakClusters.Where(p => p.TotalCount > pars.SkipClusterSize).Select(p => p.Align()).ToArray();
            var emptyClusters2 = emptyClusters.Where(p => p.TotalCount > pars.SkipClusterSize).Select(p => p.Align()).ToArray();

            var peakMotifs = peakClusters2.Select(p => Motiff.ExtractMotiff(p.Map, p.MapFactors)).ToArray();
            var emptyMotifs = emptyClusters2.Select(p => Motiff.ExtractMotiff(p.Map, p.MapFactors)).ToArray();

            if (pars.CrossTest)
            {
                TransMotiffTest(peakMotifs, peakClusters2, "peaks vs peaks");
                TransMotiffTest(peakMotifs, emptyClusters2, "peaks vs empty");

                TransMotiffTest(emptyMotifs, emptyClusters2, "empty vs empty");
                TransMotiffTest(emptyMotifs, peakClusters2, "empty vs peaks");
            }

            mfPeaks = peakMotifs;
            mfNoise = emptyMotifs;
        }
Example #17
0
        public void MergeTo(VDWidget targetWidget, ElementGroup elementGroup)
        {
            targetWidget.Children.Add(this);

            // the order of creating children is import, why??
            // first children, then grand-children???
            VDHoriContainer headContainer = this.Store.ElementFactory.CreateElement(VDHoriContainer.DomainClassId,
                new PropertyAssignment(VDContainer.TagDomainPropertyId, HEADS_CONTAINER_TAG),
                new PropertyAssignment(VDContainer.HasLeftAnchorDomainPropertyId, true),
                new PropertyAssignment(VDContainer.HasRightAnchorDomainPropertyId, true),
                new PropertyAssignment(VDContainer.HasTopAnchorDomainPropertyId, true)) as VDHoriContainer;
            VDFullFilledContainer bodyContainer = this.Store.ElementFactory.CreateElement(VDFullFilledContainer.DomainClassId,
                new PropertyAssignment(VDContainer.TagDomainPropertyId, BODYS_CONTAINER_TAG),
                new PropertyAssignment(VDContainer.HasLeftAnchorDomainPropertyId, true),
                new PropertyAssignment(VDContainer.HasRightAnchorDomainPropertyId, true),
                new PropertyAssignment(VDContainer.HasBottomAnchorDomainPropertyId, true)) as VDFullFilledContainer;

            VDHoriSeparator hSeparator = this.Store.ElementFactory.CreateElement(VDHoriSeparator.DomainClassId,
                new PropertyAssignment(VDHoriSeparator.DefaultYDomainPropertyId, 0.5)) as VDHoriSeparator;
            hSeparator.TopWidget = headContainer;
            hSeparator.BottomWidget = bodyContainer;

            this.Children.Add(headContainer);
            this.Children.Add(bodyContainer);
            this.Children.Add(hSeparator);

            VDTabHead head = this.Store.ElementFactory.CreateElement(
                VDTabHead.DomainClassId,
                new PropertyAssignment(VDTabHead.TabTitleDomainPropertyId, "New Tab")) as VDTabHead;
            VDTabBody body = this.Store.ElementFactory.CreateElement(VDTabBody.DomainClassId) as VDTabBody;
            this.ActiveHead = head;
            head.Body = body;
            headContainer.Children.Add(head);
            bodyContainer.Children.Add(body);
        }
        /// <summary>
        /// Called on copy, cut or drag.
        /// For a copy or cut, the supplied elements are the model elements, and the call comes, via AddGroupFormat, from ClipboardCommands.ProcessOnMenuCopy().
        /// For a drag operation, the elements are the selected shapes and connectors, and the call comes from Diagram.DoDragDrop, if CanMove or CanCopy are true.
        /// In the drag case, we want to add the model elements so that we can do a copy
        /// if the user presses CTRL while dragging.
        ///
        /// See http://msdn.microsoft.com/library/ff521398.aspx
        /// </summary>
        /// <param name="shapeOrModelElements">The shape or model elements being copied - usually the current selection.</param>
        /// <param name="closureType">Copy or Delete</param>
        /// <returns>Group to be stored in the clipboard.</returns>
        protected override ElementGroup CreateElementGroup(ICollection <ModelElement> shapeOrModelElements, ClosureType closureType)
        {
            // CreateElementGroup respects the settings of PropagateCopy.
            // Notice that we have set PropagateCopy on the roles from components to the terminals,
            // so that terminals will always be copied along with their parents.

            // Add the specified group of shapes or elements:
            ElementGroup group = base.CreateElementGroup(shapeOrModelElements, closureType);

            // If this a set of shapes, add their model elements:
            if (shapeOrModelElements.FirstOrDefault() is PresentationElement)
            {
                // Get the model elements of the shapes:
                ICollection <ModelElement> modelElements =
                    shapeOrModelElements.OfType <PresentationElement>()
                    // Filter out shapes such as labels that don't have model elements:
                    .Where(pel => pel.ModelElement != null)
                    .Select(pel => pel.ModelElement).ToList();

                ElementGroup melGroup = base.CreateElementGroup(modelElements, closureType);
                group.AddRange(melGroup.GetElements());
            }

            return(group);

            // 2011-03-21 Thanks to Joeul in VMSDK Forum for a bug fix here.
            // http://social.msdn.microsoft.com/Forums/en-US/dslvsarchx/thread/0b0b16d4-6014-4b35-9e5a-e27ea02e0ee3
        }
Example #19
0
        private static ElementGroupPrototype MakePrototype(GadgeteerHardware element)
        {
            var elementGroup = new ElementGroup(element.Store.DefaultPartition);

            elementGroup.AddGraph(element, true);
            return(elementGroup.CreatePrototype());
        }
Example #20
0
        /// <summary>
        /// Merges the relate interface layer.
        /// </summary>
        /// <param name="sourceElement">The source element.</param>
        /// <param name="elementGroup">The element group.</param>
        private void MergeRelateInterfaceLayer(ModelElement sourceElement, ElementGroup elementGroup)
        {
            InterfaceLayer iLayer = sourceElement as InterfaceLayer;

            InterfaceLayer = iLayer;
            iLayer.Level   = LayerLevel;
            Component.Layers.Add(iLayer);
        }
Example #21
0
        /// <summary>
        /// Generate the Sgroup elements for the provided atom contains.
        /// </summary>
        /// <param name="container">molecule</param>
        /// <returns>Sgroup rendering elements</returns>
        IRenderingElement GenerateSgroups(IAtomContainer container, AtomSymbol[] symbols)
        {
            var result  = new ElementGroup();
            var sgroups = container.GetCtabSgroups();

            if (sgroups == null || !sgroups.Any())
            {
                return(result);
            }

            var symbolMap = new Dictionary <IAtom, AtomSymbol>();

            for (int i = 0; i < symbols.Length; i++)
            {
                if (symbols[i] != null)
                {
                    symbolMap[container.Atoms[i]] = symbols[i];
                }
            }

            foreach (var sgroup in sgroups)
            {
                switch (sgroup.Type)
                {
                case SgroupType.CtabAbbreviation:
                    result.Add(GenerateAbbreviationSgroup(container, sgroup));
                    break;

                case SgroupType.CtabMultipleGroup:
                    result.Add(GenerateMultipleSgroup(sgroup));
                    break;

                case SgroupType.CtabAnyPolymer:
                case SgroupType.CtabMonomer:
                case SgroupType.CtabCrossLink:
                case SgroupType.CtabCopolymer:
                case SgroupType.CtabStructureRepeatUnit:
                case SgroupType.CtabMer:
                case SgroupType.CtabGraft:
                case SgroupType.CtabModified:
                    result.Add(GeneratePolymerSgroup(sgroup, symbolMap));
                    break;

                case SgroupType.CtabComponent:
                case SgroupType.CtabMixture:
                case SgroupType.CtabFormulation:
                    result.Add(GenerateMixtureSgroup(sgroup));
                    break;

                case SgroupType.CtabGeneric:
                    // not strictly a polymer but okay to draw as one
                    result.Add(GeneratePolymerSgroup(sgroup, null));
                    break;
                }
            }

            return(result);
        }
Example #22
0
        /// <summary>
        /// Provide default name of element, based upon the DisplayName property.
        /// </summary>
        protected override void MergeConfigure(ElementGroup elementGroup)
        {
            if (DomainClassInfo.HasNameProperty(this))
            {
                DomainClassInfo.SetUniqueName(this, SanitizeName(this.GetDomainClass().DisplayName));
            }

            base.MergeConfigure(elementGroup);
        }
        /// <summary>
        /// Provide default name of element, based upon the DisplayName property.
        /// </summary>
        protected override void MergeConfigure(ElementGroup elementGroup)
        {
            if (DomainClassInfo.HasNameProperty(this))
            {
                DomainClassInfo.SetUniqueName(this, SanitizeName(this.GetDomainClass().DisplayName));
            }

            base.MergeConfigure(elementGroup);
        }
        private IRenderingElement GenerateAbbreviationSgroup(IAtomContainer mol, Sgroup sgroup)
        {
            string label = sgroup.Subscript;

            // already handled by symbol remapping
            if (sgroup.Bonds.Count > 0 || string.IsNullOrEmpty(label))
            {
                return(new ElementGroup());
            }
            if (!CheckAbbreviationHighlight(mol, sgroup))
            {
                return(new ElementGroup());
            }
            // we're showing a label where there were no atoms before, we put it in the
            // middle of all of those which were hidden
            var sgroupAtoms = sgroup.Atoms;

            Debug.Assert(sgroupAtoms.Any());

            var highlight = sgroupAtoms.First().GetProperty <Color>(StandardGenerator.HighlightColorKey);
            var style     = parameters.GetHighlighting();
            var glowWidth = parameters.GetOuterGlowWidth();

            Vector2 labelCoords = GeometryUtil.Get2DCenter(sgroupAtoms);

            ElementGroup labelgroup = new ElementGroup();

            foreach (var outline in atomGenerator.GenerateAbbreviatedSymbol(label, HydrogenPosition.Right)
                     .Resize(1 / scale, 1 / -scale)
                     .GetOutlines())
            {
                if (highlight != null && style == HighlightStyle.Colored)
                {
                    labelgroup.Add(GeneralPath.ShapeOf(outline, highlight));
                }
                else
                {
                    labelgroup.Add(GeneralPath.ShapeOf(outline, foreground));
                }
            }

            if (highlight != null && style == HighlightStyle.OuterGlow)
            {
                ElementGroup group = new ElementGroup
                {
                    // outer glow needs to be being the label
                    StandardGenerator.OuterGlow(labelgroup, highlight, glowWidth, stroke),
                    labelgroup
                };
                return(group);
            }
            else
            {
                return(MarkedElement.MarkupAtom(labelgroup, null));
            }
        }
Example #25
0
        /// <summary>
        /// The main method of the renderer, that uses each of the generators
        /// to create a different set of <see cref="IRenderingElement"/>s grouped
        /// together into a tree.
        /// </summary>
        /// <param name="obj">the object of type T to draw</param>
        /// <returns>the diagram as a tree of <see cref="IRenderingElement"/>s</returns>
        public virtual IRenderingElement GenerateDiagram(T obj)
        {
            var diagram = new ElementGroup();

            foreach (var generator in this.generators)
            {
                diagram.Add(generator.Generate(obj, this.rendererModel));
            }
            return(diagram);
        }
Example #26
0
        /// <inheritdoc/>
        public virtual IRenderingElement Generate(IAtomContainer container, RendererModel model)
        {
            ElementGroup elementGroup = new ElementGroup();

            foreach (var atom in container.Atoms)
            {
                elementGroup.Add(MarkedElement.MarkupAtom(this.Generate(container, atom, model), atom));
            }
            return(elementGroup);
        }
Example #27
0
        /// <inheritdoc/>
        public override IRenderingElement GenerateDiagram(IChemObjectSet <IAtomContainer> molecules)
        {
            ElementGroup diagram = new ElementGroup();

            foreach (var molecule in molecules)
            {
                diagram.Add(atomContainerRenderer.GenerateDiagram(molecule));
            }
            return(diagram);
        }
Example #28
0
        public void LoadStoryboard(string dir, OsuFile osu)
        {
            ClearLayer();

            List <Element> backEle = null;
            List <Element> foreEle = null;
            Stopwatch      sw      = new Stopwatch();

            Console.WriteLine(@"Parsing..");
            sw.Start();
            string osbFile = Path.Combine(dir, osu.OsbFileName);

            if (osu.Events.ElementGroup != null)
            {
                var osb = osu.Events.ElementGroup;

                sw.Restart();
                osb.Expand();
                Console.WriteLine($@"Osu's osb expanded done in {sw.ElapsedMilliseconds} ms");

                FillLayerList(ref backEle, ref foreEle, osb);
            }

            if (File.Exists(osbFile))
            {
                sw.Restart();
                var osb = ElementGroup.Parse(osbFile);
                Console.WriteLine($@"Parse osb done in {sw.ElapsedMilliseconds} ms");

                sw.Restart();
                osb.Expand();
                Console.WriteLine($@"Osb expanded done in {sw.ElapsedMilliseconds} ms");

                FillLayerList(ref backEle, ref foreEle, osb);
            }

            sw.Stop();
            Directory = dir;
            if (backEle == null && foreEle == null)
            {
                return;
            }
            StoryboardTiming.Reset();
            if (foreEle != null)
            {
                backEle?.AddRange(foreEle);
            }
            HwndRenderBase.AddLayers(new CustomLayer[]
            {
                new StoryboardLayer(HwndRenderBase.RenderTarget, backEle ?? foreEle, StoryboardTiming),
                new FpsLayer(HwndRenderBase.RenderTarget),
            });
            StoryboardTiming.Start();
        }
Example #29
0
        /// <inheritdoc/>
        public IRenderingElement Generate(IAtomContainer ac, RendererModel model)
        {
            ElementGroup diagram = new ElementGroup
            {
                this.sceneGenerator.Generate(ac, model),
                this.bondGenerator.Generate(ac, model),
                this.atomGenerator.Generate(ac, model)
            };

            return(diagram);
        }
Example #30
0
        /// <summary>
        /// Called by the Merge process to create a relationship between
        /// this target element and the specified source element.
        /// Typically, a parent-child relationship is established
        /// between the target element (the parent) and the source element
        /// (the child), but any relationship can be established.
        /// </summary>
        /// <param name="sourceElement">The element that is to be related to this model element.</param>
        /// <param name="elementGroup">The group of source ModelElements that have been rehydrated into the target state.</param>
        /// <remarks>
        /// This method is overriden to create the relationship between the target element and the specified source element.
        /// The base method does nothing.
        /// </remarks>
        protected override void MergeRelate(ModelElement sourceElement, ElementGroup elementGroup)
        {
            ////TODO: \o/ Remove this once DSL team fixes merging of MEXes

            if (sourceElement is ExtensionElement)
            {
                return;
            }

            base.MergeRelate(sourceElement, elementGroup);
        }
Example #31
0
 /// <summary>
 /// Allows the model element to configure itself immediately after the Merge process has related it to the target element.
 /// </summary>
 /// <param name="elementGroup">The group of source elements that have been added back into the target store.</param>
 protected override void MergeConfigure(ElementGroup elementGroup)
 {
     base.MergeConfigure(elementGroup);
     if (Layer.Packages.Count == 1)
     {
         Name = Layer.Namespace;
     }
     else
     {
         Name = String.Format("{0}.{1}", Layer.Namespace, Name);
     }
 }
Example #32
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            ElementGroup elementGroup = null;

            DA.GetData(0, ref elementGroup);

            DA.SetData(0, elementGroup.Amount);
            DA.SetData(1, elementGroup.Material);
            DA.SetData(2, elementGroup.Volume);
            DA.SetData(3, elementGroup.Mass);
            DA.SetData(4, elementGroup.ElementType);
        }
Example #33
0
        /// <summary>
        /// 将元素编组
        /// </summary>
        /// <param name="elements">需要编组的元素</param>
        /// <param name="host">当前的layoutHost</param>
        /// <returns></returns>
        public static IElementGroup ElementsToGroup(IElement[] elements, ILayoutHost host)
        {
            if (elements == null || elements.Length == 0)
            {
                return(null);
            }
            int           count = elements.Length;
            IElementGroup group = new ElementGroup();

            IElement[] parents = new IElement[count];
            IElement   parent;

            //将所选element从其父节点中移除
            for (int i = 0; i < count; i++)
            {
                parent = host.LayoutRuntime.Layout.FindParent(elements[i]);
                //parent = group.FindParent(elements[i]);
                if (parent == null)
                {
                    return(null);
                }
                parents[i] = parent;
                (parents[i] as IElementGroup).Elements.Remove(elements[i]);
                group.Elements.Add(elements[i]);
            }

            //统计所选element的父节点的深度级数
            int[]      levels     = new int[count];
            IElement[] parentClon = parents.Clone() as IElement[];
            for (int i = 0; i < count; i++)
            {
                while (parentClon[i] != null)
                {
                    parentClon[i] = (parentClon[i] as IElementGroup).FindParent(parentClon[i]);
                    levels[i]++;
                }
            }
            //查找深度最大的父节点
            int maxLevelIndex = 0;

            for (int i = 0; i < count - 1; i++)
            {
                if (levels[i] < levels[i + 1])
                {
                    maxLevelIndex = i + 1;
                }
                maxLevelIndex = i;
            }
            //将group加入深度最大的父节点中
            (parents[maxLevelIndex] as IElementGroup).Elements.Add(group);
            return(group);
        }
Example #34
0
        public static async Task <string> SerializeObjectAsync(ElementGroup group)
        {
            var sb = new StringBuilder();

            foreach (var element in group.ElementList)
            {
                var result = await SerializeObjectAsync(element);

                sb.AppendLine(result);
            }

            return(sb.ToString().TrimEnd('\n', '\r'));;
        }
Example #35
0
        /// <summary>
        /// Для регионов активности и неактивности строит по своему суф.массиву и в результате получает слитые цепочки.
        /// </summary>
        private static void GetCandidateElements(GetCandidateElementsParams pars, IEnumerable<Region> peaks, IEnumerable<Region> noises,
            out ElementGroup[] elPeaks, out ElementGroup[] elNoise)
        {
            var t = DateTime.Now;
            var chrDic = new Dictionary<ChromosomeEnum, Chromosome>();

            // peaks
            var peaksTmp = peaks.Select(p =>
            {
                if (!chrDic.ContainsKey(p.Chr))
                    chrDic.Add(p.Chr, ChrManager.GetChromosome(p.Chr));
                return chrDic[p.Chr].GetPack(p.Start, p.Size);
            }).ToArray();
            TextComparer sfxPeaks = SuffixBuilder.BuildMany2(peaksTmp, pars.MinGroupSize);
            elPeaks = sfxPeaks.GetElementGroups().ToArray();
            Console.WriteLine("Peaks sfx build, dt=" + (DateTime.Now - t) + ", size=" + sfxPeaks.StrokeSize +
                              ", elCnt=" + elPeaks.Length + ", elTotal=" + elPeaks.Sum(p => p.Count));
            // noise
            var noiseTmp = noises.Select(p =>
            {
                if (!chrDic.ContainsKey(p.Chr))
                    chrDic.Add(p.Chr, ChrManager.GetChromosome(p.Chr));
                return chrDic[p.Chr].GetPack(p.Start, p.Size);
            }).ToArray();
            TextComparer sfxNoise = SuffixBuilder.BuildMany2(noiseTmp, pars.MinGroupSize);
            elNoise = sfxNoise.GetElementGroups().ToArray();
            Console.WriteLine("Noise sfx build, dt=" + (DateTime.Now - t) + ", size=" + sfxNoise.StrokeSize +
                              ", elCnt=" + elNoise.Length + ", elTotal=" + elNoise.Sum(p => p.Count));
            Array.Sort(elPeaks);
            Array.Sort(elNoise);
            if (pars.PrintCross)
            {
                Console.WriteLine("TransTest (peaks on peaks)");
                TransTest(sfxPeaks.StrokeSize, elPeaks.Take(10), sfxPeaks);
                Console.WriteLine("TransTest (peaks on empty)");
                TransTest(sfxPeaks.StrokeSize, elPeaks.Take(10), sfxNoise);
                Console.WriteLine("TransTest (empty on peaks)");
                TransTest(sfxNoise.StrokeSize, elNoise.Take(10), sfxPeaks);
            }
            if (pars.DropCross)
            {
                var pc = elPeaks.Length;
                var nc = elNoise.Length;
                Console.WriteLine("Drop cross elements:");
                //elPeaks = elPeaks.Where(p => sfxNoise.GetAllCites(p.Chain, p.Chain.Length).Count() < p.Count/2).ToArray();
                //Console.WriteLine("\tpeaks - was:" + pc + ", now:" + elPeaks.Length + ", dropped=" + (pc - elPeaks.Length));
                elNoise = elNoise.Where(p => sfxPeaks.GetAllCites(p.Chain, p.Chain.Length).Count() < /*p.Count / 2*/1).ToArray();
                Console.WriteLine("\tnoise - was:" + nc + ", now:" + elNoise.Length + ", dropped=" + (nc - elNoise.Length));
            }
        }
Example #36
0
		/// <summary>See <see cref="ORMShapeToolboxHelperBase.CreateElementToolPrototype"/>.</summary>
		protected sealed override ElementGroupPrototype CreateElementToolPrototype(Store store, Guid domainClassId)
		{
			// WARNING: This method is _extremely_ order-sensitive. If the order that the toolbox items are listed
			// in the .dsl file changes, or if the DSL Tools text template that is used to generate ORMShapeModelToolboxHelperBase
			// changes, this method will most likely need to be changed as well.

			ElementGroup group = null;
			bool unknownItem = false;

			if (domainClassId.Equals(ObjectType.DomainClassId))
			{
				group = new ElementGroup(store);
				ObjectType objectType = new ObjectType(store);
				group.AddGraph(objectType, true);
				switch (myObjectTypeCount++)
				{
					case 0:
						// EntityType - We don't need to do anything else...
						break;
					case 1:
						// ValueType
						// Do not try to set the IsValueType property here. IsValueType picks
						// up the default data type for the model, which can only be done
						// when the model is known. Instead, flag the element so that it
						// can be set during MergeRelate on the model.
						group.UserData = ORMModel.ValueTypeUserDataKey;
						break;
					case 2:
						// ObjectifiedFactType
						group.AddGraph(new Objectification(objectType, AddFactType(store, group, 2)), false);
						break;
					default:
						unknownItem = true;
						break;
				}
			}
			else if (domainClassId.Equals(FactType.DomainClassId))
			{
				group = new ElementGroup(store);
				Debug.Assert(myFactTypeCount < 3);
				AddFactType(store, group, ++myFactTypeCount);
			}
			else if (domainClassId.Equals(ExclusiveOrConstraintCoupler.DomainClassId))
			{
				group = new ElementGroup(store);
				MandatoryConstraint mandatory = new MandatoryConstraint(store, null);
				group.AddGraph(mandatory, true);
				ExclusionConstraint exclusion = new ExclusionConstraint(store, null);
				group.AddGraph(exclusion, true);
				group.AddGraph(new ExclusiveOrConstraintCoupler(mandatory, exclusion), false);
			}
			else if (domainClassId.Equals(UniquenessConstraint.DomainClassId))
			{
				group = new ElementGroup(store);
				if (myUniquenessConstraintCount == 0)
				{
					// Add this here so that we can distinguish between internal and external uniqueness
					// constraints without unpacking the model. We want to merge internals into a fact
					// and externals into the model.
					group.UserData = ORMModel.InternalUniquenessConstraintUserDataKey;
					group.AddGraph(UniquenessConstraint.CreateInternalUniquenessConstraint(store), true);
				}
				else
				{
					Debug.Assert(myUniquenessConstraintCount == 1);
					group.AddGraph(new UniquenessConstraint(store), true);
				}
				myUniquenessConstraintCount++;
			}
			return (group == null || unknownItem) ? base.CreateElementToolPrototype(store, domainClassId) : group.CreatePrototype();
		}
Example #37
0
		/// <summary>
		/// Creates a new <see cref="FactType"/> with the specified <paramref name="arity"/>.
		/// </summary>
		/// <param name="store">
		/// The <see cref="Store"/> in which the new <see cref="FactType"/> should be created.
		/// </param>
		/// <param name="group">
		/// The <see cref="ElementGroup"/> to which the new <see cref="FactType"/> and its <see cref="Role"/>s should
		/// be added.
		/// </param>
		/// <param name="arity">
		/// The number of <see cref="Role"/>s that the new <see cref="FactType"/> should contain.
		/// </param>
		/// <returns>
		/// The newly created <see cref="FactType"/>.
		/// </returns>
		/// <remarks>
		/// The new <see cref="FactType"/> is added to <paramref name="group"/> as a root element.
		/// </remarks>
		private static FactType AddFactType(Store store, ElementGroup group, int arity)
		{
			FactType factType = new FactType(store, null);
			group.AddGraph(factType, true);
			LinkedElementCollection<RoleBase> roles = factType.RoleCollection;
			for (int i = 0; i < arity; i++)
			{
				Role role = new Role(store);
				roles.Add(role);
				group.AddGraph(role);
			}
			return factType;
		}
Example #38
0
 public List<Cluster> Work3(int cut = 3, int seed = 1, bool setCoreWeights = false)
 {
     InitEdges();
     Console.WriteLine("Запущена кластеризация второго типа для " + _nodes.Length + " узлов");
     var sw = Stopwatch.StartNew();
     var weights = new int[_nodes.Length][];
     for (int i = 0; i < weights.Length; i++)
     {
         weights[i] = new int[_nodes.Length];
         for (int j = 0; j < _nodes.Length; j++)
             weights[i][j] = i != j ? GetEdge(i, j).Weight - cut : (setCoreWeights ? _nodes[i].Count : 0);//_nodes[i].Chain.Length;
     }
     var m = new Modularity(_nodes, weights, seed);
     Console.WriteLine("Start with:" + m.CalcTotalModularity());
     var iter = 1;
     while (m.Iterate())
         Console.WriteLine("Iter[" + iter++ + "]:" + m.CalcTotalModularity());
     Console.WriteLine("Result:" + m.CalcTotalModularity());
     sw.Stop();
     Console.WriteLine("Кластеризация завершена за " + sw.Elapsed);
     var clusterIds = m.ClasterIds;
     var ret = new List<Cluster>();
     for (int i = 0; i < m.NodesCount; i++)
     {
         // переобозначим элементы каждого кластера
         int id = 0;
         var dic = new Dictionary<int, int>();
         for (int j = 0; j < clusterIds.Length; j++)
         {
             if(clusterIds[j] != i)
                 continue;
             dic.Add(id++,j);
         }
         var nodes = new ElementGroup[dic.Count];
         var edges = new AlignmentResult[dic.Count][];
         for (int j = 0; j < dic.Count; j++)
         {
             nodes[j] = _nodes[dic[j]];
             edges[j] = new AlignmentResult[j];
             for (int k = 0; k < j; k++)
             {
                 edges[j][k] = _edges[dic[j]][dic[k]];
                 if (k == 0)
                 {
                     var tt = Alignment.Align(nodes[j].NucleoChain, nodes[k].NucleoChain, 0, 0);
                     Debug.Assert(tt.Mask == edges[j][k].Mask);
                 }
             }
         }
         ret.Add(new Cluster(ret.Count, nodes, edges));
     }
     return ret;
 }
 public static void Bind(UIElement owner, ElementGroup target)
 {
     owner.MouseClick += (o, e) => ElementGroup.NavigateTo(target);
 }
Example #40
0
 public Cluster(int clusterId, ElementGroup[] nodes, AlignmentResult[][] edges)
 {
     ClusterId = clusterId;
     Nodes = nodes;
     Edges = edges;
 }
Example #41
0
 private void ProcessGroup(LcpTree interval)
 {
     var size = interval.Lcp; // размер совпадения
     var cnt = interval.RightBound - interval.LeftBound + 1; // число совпавших
     if (size < _minGroupSize || size > 100)
         return;
     Debug.Assert(cnt > 1);
     // определим позиции совпавших кусков ДНК
     var pos = new uint[cnt];
     Array.Copy(_suftab, interval.LeftBound, pos, 0, cnt);
     // определим сам совпавший кусок
     var str = CutAndCheck(pos[0], size);
     if (str == null)
         return;
     if (_elementGroups.Count > 0)
     {
         // проверим, не стоит ли слить с предыдущей группой
         var last = _elementGroups.Last();
         if (last.Count < cnt && str.Length < last.Chain.Length && str.SequenceEqual(last.Chain.Take(str.Length)))
         {
             _elementGroups[_elementGroups.Count-1] =new ElementGroup(str, pos);
             return;
         }
     }
     // сформируем группу и сохраним её
     var group = new ElementGroup(str, pos);
     _elementGroups.Add(group);
 }