public virtual double DistanceInMeters(Topology.Geometries.IPoint p1, Topology.Geometries.IPoint p2)
        {
            double xdist = Math.Abs(p1.X - p2.X);
            double ydist = Math.Abs(p1.Y - p2.Y);

            return Math.Sqrt((xdist * xdist) + (ydist * ydist));            
        }
            public VoxelGrid_PolyRefractive(Topology[] T, int Domain)
            :base(T, Domain)
            {
                for (int x = 0; x < base.Voxel_Inv.GetUpperBound(0); x++)
                {
                    for (int y = 0; y < base.Voxel_Inv.GetUpperBound(1); y++)
                    {
                        for (int z = 0; z < base.Voxel_Inv.GetUpperBound(2); z++)
                        {
                                Velocities[x, y, z] = 1.0f;
                        }
                    }
                }

                XPlane_sect = new double[Domain - 1];
                YPlane_sect = new double[Domain - 1];
                ZPlane_sect = new double[Domain - 1];

                for (int i = 0; i < Domain-1; i++)
                {
                    XPlane_sect[i] = OBox.Min_PT.x + VoxelDims.x * i;
                    YPlane_sect[i] = OBox.Min_PT.y + VoxelDims.y * i;
                    ZPlane_sect[i] = OBox.Min_PT.z + VoxelDims.z * i;
                }
            }
 public override Topology.Geometries.IEnvelope AdjustBoundingBox(Topology.Geometries.IEnvelope bbox, double scale, System.Drawing.Size size)
 {
     double[] points = m_transform.MathTransform.Transform(new double[] { bbox.MinX, bbox.MinY, bbox.MaxX, bbox.MaxY });
     Topology.Geometries.IEnvelope localEnv = new Topology.Geometries.Envelope(points[0], points[2], points[1], points[3]);
     localEnv = base.AdjustBoundingBox(localEnv, scale, size);
     points = m_transform.MathTransform.Inverse().Transform(new double[] { localEnv.MinX, localEnv.MinY, localEnv.MaxX, localEnv.MaxY });
     return new Topology.Geometries.Envelope(points[0], points[2], points[1], points[3]);
 }
Beispiel #4
0
 /// <summary>
 /// Checks if a topology can be added to a list of topologies.
 /// </summary>
 /// <param name="topologies">
 /// The existing topologies.
 /// </param>
 /// <param name="newTopol">
 /// The topology to check for.
 /// </param>
 /// <returns>
 /// True if the topology could be added.
 /// False otherwise.
 /// </returns>
 public static bool Check(List<Topology>[] topologies, Topology newTopol)
 {
     int index = topologies[newTopol.Size].BinarySearch(newTopol);
     if (index >= 0) {
         return false;
     }
     return true;
 }
 /// <summary>
 /// Initializes an instance of a CoordinateTransformation
 /// </summary>
 /// <param name="sourceCS">Source coordinate system</param>
 /// <param name="targetCS">Target coordinate system</param>
 /// <param name="transformType">Transformation type</param>
 /// <param name="mathTransform">Math transform</param>
 /// <param name="name">Name of transform</param>
 /// <param name="authority">Authority</param>
 /// <param name="authorityCode">Authority code</param>
 /// <param name="areaOfUse">Area of use</param>
 /// <param name="remarks">Remarks</param>
 internal CoordinateTransformation(ICoordinateSystem sourceCS, ICoordinateSystem targetCS, Topology.CoordinateSystems.Transformations.TransformType transformType, IMathTransform mathTransform, string name, string authority, long authorityCode, string areaOfUse, string remarks)
 {
     this._TargetCS = targetCS;
     this._SourceCS = sourceCS;
     this._TransformType = transformType;
     this._MathTransform = mathTransform;
     this._Name = name;
     this._Authority = authority;
     this._AuthorityCode = authorityCode;
     this._AreaOfUse = areaOfUse;
     this._Remarks = remarks;
 }
Beispiel #6
0
        private void PlatformDispose(bool disposing)
        {
            if (_topology != null)
            {
                _topology.Dispose();
                _topology = null;
            }

            if (SampleGrabber != null)
            {
                SampleGrabber.Dispose();
                SampleGrabber = null;
            }
        }
Beispiel #7
0
 private static CoordinateSystem GetOrCreate(int epsgId, Topology topology)
 {
     CoordinateSystem system;
     lock (referencesLock)
     {
         if (References.TryGetValue(KeyFor(epsgId, topology), out system))
         {
             return system;
         }
         system = new CoordinateSystem(epsgId, "ID " + epsgId, topology);
         AddRef(system);
     }
     return system;
 }
        public ActualCoordinateSystem(Topology.CoordinateSystems.ICoordinateSystem coordinateSystem)
        {
            if (coordinateSystem == null)
                throw new ArgumentNullException("coordinateSystem");

            Topology.CoordinateSystems.Transformations.CoordinateTransformationFactory f = new Topology.CoordinateSystems.Transformations.CoordinateTransformationFactory();
            Topology.CoordinateSystems.CoordinateSystemFactory cf = new Topology.CoordinateSystems.CoordinateSystemFactory();

            /*Topology.CoordinateSystems.ICoordinateSystem local = cf.CreateLocalCoordinateSystem(
                "Non-Earth (Meter)",
                cf.CreateLocalDatum("Local Datum", Topology.CoordinateSystems.DatumType.VD_Normal),
                new Topology.CoordinateSystems.LinearUnit(1.0, "Meter", "", 0, "", "", ""),
                new List<Topology.CoordinateSystems.AxisInfo>(new Topology.CoordinateSystems.AxisInfo[] {
                    new Topology.CoordinateSystems.AxisInfo("X", Topology.CoordinateSystems.AxisOrientationEnum.East),
                    new Topology.CoordinateSystems.AxisInfo("Y", Topology.CoordinateSystems.AxisOrientationEnum.North)
                })
            );

            string s = cf.ToString();*/

            m_transform = f.CreateFromCoordinateSystems(coordinateSystem, cf.CreateFromWkt(XY_M));
        }
        public frmMap(IEnvelope envelope, Topology.CoordinateSystems.ICoordinateSystem coordSys, params IProvider[] layers) : this()
        {
            m_isLoading = true;
            m_layers = new List<IProvider>(layers);
            m_env = m_origEnv = envelope;
            m_coordSys = null;

            if (coordSys != null)
                try
                {
                    //This fails because the XY-M projection is not supported
                    m_coordSys = new LittleSharpRenderEngine.CoordinateSystem.ActualCoordinateSystem(coordSys);
                }
                catch { }

            if (m_coordSys == null && coordSys != null)
            {
                Topology.CoordinateSystems.IUnit unit = coordSys.GetUnits(0);
                if (unit is Topology.CoordinateSystems.IAngularUnit)
                {
                    double radians = (unit as Topology.CoordinateSystems.IAngularUnit).RadiansPerUnit;
                    m_coordSys = new LittleSharpRenderEngine.CoordinateSystem.DegreeBasedCoordinateSystem();
                }
                else if (unit is Topology.CoordinateSystems.ILinearUnit)
                    m_coordSys = new LittleSharpRenderEngine.CoordinateSystem.MeterBasedCoordsys(((Topology.CoordinateSystems.ILinearUnit)unit).MetersPerUnit, ((Topology.CoordinateSystems.ILinearUnit)unit).MetersPerUnit);
            }


            if (m_coordSys == null)
                m_coordSys = new LittleSharpRenderEngine.CoordinateSystem.MeterBasedCoordsys();


            foreach (IProvider l in m_layers)
                LayerListBox.Items.Add(l.DatasetName, CheckState.Checked);

            m_isLoading = false;
        }
Beispiel #10
0
        /// <summary>
        /// Restores (un-deletes) this line.
        /// </summary>
        /// <returns>True if line restored. False if the line wasn't marked as deleted.</returns>
        internal override bool Restore()
        {
            if (!base.Restore())
                return false;

            // If this was a polygon boundary, create an undefined divider, mark
            // affected polygons, and mark the line as "moved" (to force re-intersection
            // with the map).

            if (IsTopological)
            {
                m_Topology = Topology.CreateTopology(this);
                MarkPolygons();
                IsMoved = true;
            }

            return true;
        }
Beispiel #11
0
 /// <summary>
 /// Marks adjacent polygons (if any) for deletion, and nulls out <see cref="m_Topology"/>
 /// </summary>
 internal void RemoveTopology()
 {
     if (m_Topology!=null)
     {
         m_Topology.OnLineDeactivation();
         m_Topology = null;
     }
 }
Beispiel #12
0
        /// <summary>
        /// Creates a new <c>LineFeature</c>
        /// </summary>
        /// <param name="creator">The operation that created the feature (not null)</param>
        /// <param name="id">The internal ID of this feature within the
        /// project that created it.</param>
        /// <param name="e">The entity type for the feature (not null)</param>
        /// <param name="g">The geometry defining the shape of the line (not null)</param>
        /// <note>To ensure that the start and end of all lines are instances of <see cref="PointFeature"/>,
        /// this constructor should always remain private.</note>
        protected LineFeature(Operation creator, InternalIdValue id, IEntity e, PointFeature start, PointFeature end, LineGeometry g)
            : base(creator, id, e, null)
        {
            if (g==null)
                throw new ArgumentNullException();

            m_From = start;
            m_To = end;
            m_Geom = g;
            m_Topology = null;
            AddReferences();

            // If the entity type denotes a topological boundary, initialize the topology.
            if (e.IsPolygonBoundaryValid)
                SetTopology(true);
        }
Beispiel #13
0
        /// <summary>
        /// Sets or clears topological status. This override creates or nulls the object
        /// for holding topological data, then calls the implementation in the base class.
        /// </summary>
        /// <param name="topol">True to mark this feature as topological. False to clear topology flag.</param>
        internal override void SetTopology(bool topol)
        {
            if (topol)
                m_Topology = Topology.CreateTopology(this);
            else
                m_Topology = null;

            base.SetTopology(topol);
        }
Beispiel #14
0
        public void DatasetTest()
        {
            var outputs     = new List <double>();
            var inputs      = new List <double[]>();
            var inputsCount = 0;

            using (var sr = new StreamReader("datasets/heart.csv"))
            {
                var header = sr.ReadLine();                 // Заголовочная строка
                for (; !sr.EndOfStream;)
                {
                    var row    = sr.ReadLine();
                    var values = row.Split(',').Select(v => Convert.ToDouble(v.Replace('.', ','))).ToList();
                    var output = values.Last();                     // Ожидаемое значение

                    /* !!!!!
                     * В этом датасете - 1 здоров, 0 - болен
                     * !!!!!
                     */
                    var input = values.Take(values.Count - 1).ToArray(); // Массив входных параметров (без ожидаемого значения)
                    inputsCount = input.Length;                          // Считаем количество входных параметров В ОДНОЙ СТРОКЕ

                    outputs.Add(output);
                    inputs.Add(input);
                }
            }


            // Перемешиваем списки
            LinkedMix(ref inputs, ref outputs);
            LinkedMix(ref inputs, ref outputs);
            LinkedMix(ref inputs, ref outputs);
            LinkedMix(ref inputs, ref outputs);
            LinkedMix(ref inputs, ref outputs);



            // Перегоняю в двумерный массив
            var validInputs = new double[inputs.Count, inputsCount];

            for (int i = 0; i < validInputs.GetLength(0); i++)
            {
                for (int j = 0; j < validInputs.GetLength(1); j++)
                {
                    validInputs[i, j] = inputs[i][j];
                }
            }
            // Нормализуем данные
            var normalizedInputs = NeuralNetwork.Normalization(validInputs);

            Topology topology = new Topology(
                inputCount: inputsCount,
                outputCount: 1,
                learningRate: 1,
                hiddenLayersCount: new int[] { inputsCount / 2 }
                );
            NeuralNetwork neuralNetwork = new NeuralNetwork(topology);

            // Тренируем нейросеть
            double difference = 500;

            for (int i = 0; difference > 10; i++)
            {
                topology.LearningRate = 0.055 * Math.Pow(0.7, i / 1500.0);
                difference            = neuralNetwork.Learn(outputs.ToArray(), normalizedInputs, 1);
            }

            Debug.WriteLine("Квадратичное отклонение: " + difference.ToString());

            // Запуск нейросети
            var resultsAfterTraining = new List <double>();

            for (int i = 0; i < normalizedInputs.GetLength(0); i++)
            {
                var input = NeuralNetwork.GetRow(normalizedInputs, i);
                resultsAfterTraining.Add(neuralNetwork.Predict(input));
            }

            for (int i = 0; i < resultsAfterTraining.Count; i++)
            {
                var expected = Math.Round(outputs[i], 3);
                var actual   = Math.Round(resultsAfterTraining[i], 3);
                //Assert.AreEqual(expected, actual);
            }
        }
Beispiel #15
0
        public void FeedForwardTest()
        {
            var outputs = new double[] { 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1 };
            var inputs  = new double[, ]
            {
                // Результат - Пациент болен - 1
                //             Пациент Здоров - 0

                // Неправильная температура T
                // Хороший возраст A
                // Курит S
                // Правильно питается F
                //T  A  S  F
                { 0, 0, 0, 0 },
                { 0, 0, 0, 1 },
                { 0, 0, 1, 0 },
                { 0, 0, 1, 1 },
                { 0, 1, 0, 0 },
                { 0, 1, 0, 1 },
                { 0, 1, 1, 0 },
                { 0, 1, 1, 1 },
                { 1, 0, 0, 0 },
                { 1, 0, 0, 1 },
                { 1, 0, 1, 0 },
                { 1, 0, 1, 1 },
                { 1, 1, 0, 0 },
                { 1, 1, 0, 1 },
                { 1, 1, 1, 0 },
                { 1, 1, 1, 1 }
            };

            // 4 входных, 1 - выходной, 1 скрытый с 4 нейронами
            var topology = new Topology(
                inputCount: 4,
                outputCount: 1,
                learningRate: 0.1,
                hiddenLayersCount: new int[] { 4 }
                );
            var neuralNetwork = new NeuralNetwork(topology);

            // Обучение
            var difference = neuralNetwork.Learn(outputs, inputs, 100000);             // Ср. квадратичное отклонение

            // Использование после обучения
            var results      = new List <double>(outputs.Length);
            var inputsLength = inputs.GetLength(0);

            for (int i = 0; i < inputsLength; i++)
            {
                results.Add(neuralNetwork.Predict(NeuralNetwork.GetRow(inputs, i)));
            }

            Debug.WriteLine("Ср. квадратичное отклонение: " + difference);

            // Assert
            for (int i = 0; i < results.Count; i++)
            {
                var expected = Math.Round(outputs[i], 4);
                var actual   = Math.Round(results[i], 4);
                Assert.AreEqual(expected, actual, 0.001);
            }
        }
Beispiel #16
0
 internal CoordinateSystem(int epsgId, string name, Topology topology)
 {
     this.topology = topology;
     this.EpsgId = new int?(epsgId);
     this.Name = name;
 }
Beispiel #17
0
 /// <summary>
 /// Creates a mesh object using vertices, indices and the desired topology.
 /// </summary>
 public Mesh(V[] vertices, int[] indices, Topology topology = Topology.Triangles)
 {
     this.Vertices = vertices;
     this.Indices  = indices;
     this.Topology = topology;
 }
Beispiel #18
0
        public static void Initialize(TransmissionContext context)
        {
            context.Database.EnsureCreated();
            if (!context.RatedVoltage.Any())
            {
                var RatedVoltages = new RatedVoltage[]
                {
                    new RatedVoltage {
                        Name = "Низковольтные (до 1 кВ) линии"
                    },
                    new RatedVoltage {
                        Name = "Высоковольтные линии среднего (3–35кВ) напряжения"
                    },
                    new RatedVoltage {
                        Name = "Высоковольтные линии высокого (110–220 кВ) напряжения"
                    },
                    new RatedVoltage {
                        Name = "Высоковольтные линии сверхвысокого (330–750 кВ) напряжения"
                    },
                    new RatedVoltage {
                        Name = "Высоковольтные линии  ультравысокого (св. 1000 кВ) напряжения"
                    }
                };
                foreach (RatedVoltage b in RatedVoltages)
                {
                    context.RatedVoltage.Add(b);
                }
                context.SaveChanges();
            }

            if (!context.TypeOfCurrent.Any())
            {
                var TypesOfCurrent = new TypeOfCurrent[]
                {
                    new TypeOfCurrent {
                        Name = "Линии постоянного тока"
                    },
                    new TypeOfCurrent {
                        Name = "Линии трёхфазного переменного тока"
                    },
                    new TypeOfCurrent {
                        Name = "ЛЭП многофазного переменного тока"
                    }
                };
                foreach (TypeOfCurrent b in TypesOfCurrent)
                {
                    context.TypeOfCurrent.Add(b);
                }
                context.SaveChanges();
            }
            if (!context.ParallelCircuits.Any())
            {
                var ParallelCircuits = new ParallelCircuits[]
                {
                    new ParallelCircuits {
                        Name = "Одноцепные"
                    },
                    new ParallelCircuits {
                        Name = "Двухцепные"
                    },
                    new ParallelCircuits {
                        Name = "Многоцепные"
                    }
                };
                foreach (ParallelCircuits b in ParallelCircuits)
                {
                    context.ParallelCircuits.Add(b);
                }
                context.SaveChanges();
            }
            if (!context.Topology.Any())
            {
                var Topologies = new Topology[]
                {
                    new Topology {
                        Name = "Pадиальные"
                    },
                    new Topology {
                        Name = "Магистральные "
                    },
                    new Topology {
                        Name = "Ответвления"
                    }
                };
                foreach (Topology b in Topologies)
                {
                    context.Topology.Add(b);
                }
                context.SaveChanges();
            }

            if (!context.FunctionalPurpose.Any())
            {
                var FunctionalPurposes = new FunctionalPurpose[]
                {
                    new FunctionalPurpose {
                        Name = "Pаспределительные"
                    },
                    new FunctionalPurpose {
                        Name = "Питающие"
                    },
                    new FunctionalPurpose {
                        Name = "Системообразующие и межсистемные"
                    }
                };
                foreach (FunctionalPurpose b in FunctionalPurposes)
                {
                    context.FunctionalPurpose.Add(b);
                }
                context.SaveChanges();
            }
            if (!context.State.Any())
            {
                var States = new State[]
                {
                    new State {
                        Name = "Используется"
                    },
                    new State {
                        Name = "Строится"
                    },
                    new State {
                        Name = "На реконструкции"
                    },
                    new State {
                        Name = "Не используется (заброшено)"
                    },
                    new State {
                        Name = "Снесено"
                    },
                    new State {
                        Name = "Изменение адреса"
                    },
                    new State {
                        Name = "Перестроено"
                    },
                    new State {
                        Name = "Изменение назначения"
                    }
                };
                foreach (State b in States)
                {
                    context.State.Add(b);
                }
                context.SaveChanges();
            }

            if (!context.Project.Any())
            {
                var Projects = new Project[]
                {
                    new Project {
                        Name = "Распределительные устройства и трансформаторные подстанции"
                    },
                    new Project {
                        Name = "407-3-46"
                    },                               //2
                    new Project {
                        Name = "407-3-349.84"
                    },                                  //3
                    new Project {
                        Name = "4-07-67"
                    },                             //4
                    new Project {
                        Name = "4-07-70"
                    },                             //5
                    new Project {
                        Name = "4-07-650"
                    },                              //6
                    new Project {
                        Name = "407-3-166"
                    },                               //7
                    new Project {
                        Name = "4-07-826"
                    },                              //8
                    new Project {
                        Name = "407-3-50"
                    },                              //9
                    new Project {
                        Name = "407-3-648.94"
                    },                                  //10
                    new Project {
                        Name = "Неизв. проект трансформаторной подстанции (усл. лит. Р-50-1) (ІІ-я пол. 1950-х гг.)"
                    },                                                                                                         //11
                    new Project {
                        Name = "507-7"
                    },                           //12
                    new Project {
                        Name = "4-07-649"
                    },                              //13
                };
                foreach (Project b in Projects)
                {
                    context.Project.Add(b);
                }
                context.SaveChanges();
            }
            if (!context.Builder.Any())
            {
                var Builders = new Builder[]
                {
                    new Builder {
                        Name = "ОАО Ивгорэлектросеть"
                    },                                           //1
                    new Builder {
                        Name = "Трамвайное управление"
                    },                                           //2
                    new Builder {
                        Name = "Снурилов А. Ф."
                    },                                    //3
                    new Builder {
                        Name = "ИвГРЭС"
                    },                            //4
                    new Builder {
                        Name = "Трамвайно-троллейбусное управление"
                    },                                                        //5
                };
                foreach (Builder b in Builders)
                {
                    context.Builder.Add(b);
                }
                context.SaveChanges();
            }


            if (!context.TransformerSubstation.Any())
            {
                var TransformerSubstations = new TransformerSubstation[]
                {
                    new TransformerSubstation {
                        CoordinatesX = 56.99805856769737, CoordinatesY = 40.97873549999994, Address = "Иваново, Улица 10 Августа, 12*", BuilderId = 1, Floors = 1, YearFinish = 2013, StateId = 1, ProjectId = 1, Name = "ТП-1016"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.99729856769538, CoordinatesY = 40.979804499999894, Address = "Иваново, Улица 10 Августа, 16*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 1, Name = "ТП-139"
                    },                                                                                                                                                                                                   //builder null
                    new TransformerSubstation {
                        CoordinatesX = 57.040427183263574, CoordinatesY = 40.99294250000001, Address = "Иваново, 14-е почтовое отделение, ЗТП-22", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 2, Name = "ЗТП № 22"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.040427183263574, CoordinatesY = 40.99294250000001, Address = "Иваново, 14-е почтовое отделение, ЗТП-29", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 3, Name = "ЗТП №29"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.01795256768802, CoordinatesY = 40.97224999999988, Address = "Иваново, 2-я Сибирская улица, 9", BuilderId = 2, Floors = 1, YearFinish = 1958, StateId = 1, ProjectId = 1, Name = "Тяговая подстанция №2"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.98778106770112, CoordinatesY = 41.02445099999996, Address = "Иваново, 3-я Сосневская улица, 139*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 4, Name = "ТП-536"
                    },                                                                                                                                                                                                      //builder null
                    new TransformerSubstation {
                        CoordinatesX = 56.98569706769578, CoordinatesY = 40.96577299999995, Address = "Иваново, 4-й Лётный переулок, 4*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 1, Name = "ТП"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.98689356772909, CoordinatesY = 41.03704549999995, Address = "6-я Меланжевая улица, 1*", BuilderId = 1, Floors = 1, YearFinish = 1990, StateId = 1, ProjectId = 3, Name = "ТП-236"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.006137067687916, CoordinatesY = 40.981062499999986, Address = "Иваново, Улица 8 Марта, 17*", BuilderId = 1, Floors = 1, YearFinish = 1960, StateId = 1, ProjectId = 5, Name = "	ТП-379"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.0065340676889, CoordinatesY = 40.987081, Address = "Иваново, Улица 8 Марта, 31*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 6, Name = "ТП-499"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.99848056769845, CoordinatesY = 40.99438449999989, Address = "Иваново, Улица III Интернационала, 39*", BuilderId = 3, Floors = 1, YearFinish = 1915, StateId = 1, ProjectId = 1, Name = "ТП-18"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.99739156769562, CoordinatesY = 40.989497499999906, Address = "Иваново, Улица Арсения, 37*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 1, Name = "ТП-100"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.0187270676598, CoordinatesY = 41.02039949999998, Address = "Иваново, Улица Афанасьева, 9*", BuilderId = 1, Floors = 1, YearFinish = 1955, StateId = 1, ProjectId = 1, Name = "ТП-259"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.00443466415509, CoordinatesY = 40.97446051356121, Address = "Иваново, Улица Батурина, 6**", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 1, Name = "ТП-4"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.989409067705346, CoordinatesY = 40.97055200000002, Address = "Иваново, Улица Богдана Хмельницкого, 7*", BuilderId = 1, Floors = 1, YearFinish = 1985, StateId = 1, ProjectId = 3, Name = "ТП-74"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.99055206770829, CoordinatesY = 40.99010849999998, Address = "Иваново, Улица Бубнова, 40А", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 1, Name = "ТП-280"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.99724013660895, CoordinatesY = 40.99585088657753, Address = "Иваново, Улица Бубнова, 74*", BuilderId = 1, Floors = 1, YearFinish = 1963, StateId = 1, ProjectId = 5, Name = "ТП-462"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.997416333365976, CoordinatesY = 40.99650295370688, Address = "Иваново, Улица Бубнова, 76 стр. 1", BuilderId = 1, Floors = 1, YearStart = 1983, YearFinish = 1883, StateId = 1, ProjectId = 7, Name = "Насосная станция №4 и ТП-875"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.98516884190515, CoordinatesY = 40.9985097077194, Address = "Иваново, Варгинский переулок, 2", BuilderId = 2, Floors = 1, YearFinish = 1964, StateId = 1, ProjectId = 1, Name = "Тяговая подстанция №3"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.98280590705517, CoordinatesY = 40.96223160284047, Address = "Иваново, Велижская улица, 59А*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 1, Name = "ТП-475"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.98298456771902, CoordinatesY = 40.96225149999996, Address = "Иваново, Велижская улица, 59А*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 1, Name = "ТП-475"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.98666806769826, CoordinatesY = 40.9771725, Address = "Иваново, Улица Володарского, 3*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 1, Name = "ТП-249"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.00676477876178, CoordinatesY = 40.94313700169494, Address = "Иваново, Гаражный переулок, 10*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 1, Name = "ТП-53"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.013958450779185, CoordinatesY = 40.98423314418026, Address = "Иваново, Улица Генкиной, 60*", BuilderId = 1, Floors = 1, YearFinish = 1963, StateId = 1, ProjectId = 5, Name = "ТП-413"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.01189106770267, CoordinatesY = 40.981673499999935, Address = "Иваново, Улица Громобоя, 21*", BuilderId = 1, Floors = 1, YearFinish = 1967, StateId = 1, ProjectId = 1, Name = "ТП-618"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.01157256767163, CoordinatesY = 40.98372149999994, Address = "Иваново, Улица Громобоя, 25*", BuilderId = 1, Floors = 1, YearFinish = 1968, StateId = 1, ProjectId = 8, Name = "ТП-569"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.018296067658646, CoordinatesY = 40.961874499999944, Address = "Иваново, Улица Ермака, 15*", BuilderId = 1, Floors = 1, YearFinish = 1974, StateId = 1, ProjectId = 9, Name = "ТП-705"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.00137256770584, CoordinatesY = 40.9675784999999, Address = "Иваново, Улица Зверева, 11", BuilderId = 1, Floors = 2, YearFinish = 1934, StateId = 1, ProjectId = 1, Name = "Тяговая подстанция №1"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.00312256771038, CoordinatesY = 40.965880999999946, Address = "Иваново, Улица Зверева, 12", BuilderId = 4, Floors = 2, YearFinish = 1928, YearStart = 1926, StateId = 1, ProjectId = 1, Name = "Силовая подстанция №2"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.006044067687654, CoordinatesY = 40.979696999999916, Address = "Иваново, Улица Калинина, 3*", BuilderId = 1, Floors = 1, YearFinish = 1965, StateId = 1, ProjectId = 5, Name = "ТП-397"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.007745067692056, CoordinatesY = 40.979310499999976, Address = "Иваново, Улица Калинина, 7*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 1, Name = "ТП-97"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.007774067692104, CoordinatesY = 40.98037049999992, Address = "Иваново, Улица Калинина, 8*", BuilderId = 1, Floors = 1, YearFinish = 1936, StateId = 1, ProjectId = 1, Name = "ТП-160"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.01024906769851, CoordinatesY = 40.97904149999996, Address = "Иваново, Улица Калинина, 17*", BuilderId = 1, Floors = 1, YearFinish = 1935, StateId = 1, ProjectId = 1, Name = "ТП-130"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.01605156768314, CoordinatesY = 40.97640000000001, Address = "Иваново, Улица Карла Маркса, 32*", BuilderId = 1, Floors = 1, YearFinish = 1976, StateId = 1, ProjectId = 7, Name = "ТП-742"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.98335756772002, CoordinatesY = 40.99622599999998, Address = "Иваново, Улица Колесанова, 3*", BuilderId = 1, Floors = 1, YearFinish = 1967, StateId = 1, ProjectId = 7, Name = "ТП-220"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.995175567689955, CoordinatesY = 40.9986785, Address = "Иваново, Улица Колотилова, 36*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 1, Name = "ТП-31"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.00889656766476, CoordinatesY = 40.98516749999996, Address = "Иваново, Комсомольская улица, 41*", BuilderId = 1, Floors = 1, YearFinish = 1983, StateId = 1, ProjectId = 7, Name = "ТП-851"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.00235306767817, CoordinatesY = 40.952595, Address = "Иваново, Улица Красных Зорь, 12*", BuilderId = 1, Floors = 1, YearFinish = 1969, StateId = 1, ProjectId = 9, Name = "ТП-615"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.002485067678485, CoordinatesY = 40.98479049999997, Address = "Иваново, Крутицкая улица, 29*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 1, Name = "ТП-124"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.00991106769759, CoordinatesY = 40.94311749999989, Address = "Иваново, Улица Кузнецова, 112*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 1, Name = "ТП-187"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.97438106772714, CoordinatesY = 41.00743700000001, Address = "Иваново, Улица Куконковых, 82*", BuilderId = 1, Floors = 2, StateId = 1, ProjectId = 1, Name = "ТП-478"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.00223506767785, CoordinatesY = 40.93654199999996, Address = "Иваново, Улица Лебедева-Кумача, 2*", BuilderId = 1, Floors = 1, YearFinish = 1971, StateId = 1, ProjectId = 9, Name = "ТП-652"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.00160756770646, CoordinatesY = 40.932077499999984, Address = "Иваново, Улица Лебедева-Кумача, 3*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 5, Name = "ТП-357"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.96547156773445, CoordinatesY = 40.97089349999993, Address = "Иваново, Лежневская улица, 152*", BuilderId = 1, Floors = 1, YearFinish = 1965, StateId = 1, ProjectId = 5, Name = "ТП-418"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.00899456766501, CoordinatesY = 40.97316650000003, Address = "Иваново, Проспект Ленина, 64*", BuilderId = 1, Floors = 1, YearFinish = 1970, StateId = 1, ProjectId = 6, Name = "ТП-78"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.001387067675665, CoordinatesY = 40.94829199999994, Address = "Иваново, Ленинградская улица, 6*", BuilderId = 1, Floors = 1, YearFinish = 1963, StateId = 1, ProjectId = 6, Name = "ТП-51"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.9929591706653, CoordinatesY = 40.98608693961019, Address = "Иваново, Улица Марии Рябининой, 1*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 1, Name = "ТП-176"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.9987445676991, CoordinatesY = 40.99212050000002, Address = "Иваново, Улица Марии Рябининой, 29*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 1, Name = "ТП-293"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.99979406767159, CoordinatesY = 40.99480649999995, Address = "Иваново, Улица Марии Рябининой, 32*", BuilderId = 1, Floors = 1, YearFinish = 2011, StateId = 1, ProjectId = 10, Name = "ТП-727"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.00086756770459, CoordinatesY = 40.96385949999998, Address = "Иваново, Улица Мархлевского, 21*", BuilderId = 1, Floors = 1, YearFinish = 1972, StateId = 1, ProjectId = 9, Name = "ТП-689"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.00121727792756, CoordinatesY = 40.96250971363064, Address = "Иваново, Улица Мархлевского, 32*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 1, Name = "ТП-208"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.98947306770552, CoordinatesY = 40.97484599999995, Address = "Иваново, Улица Маяковского, 22*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 1, Name = "ТП-26"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.98990006770658, CoordinatesY = 40.97406449999995, Address = "Иваново, Улица Маяковского, 24*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 8, Name = "ТП-624"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.00098056770487, CoordinatesY = 40.95316049999999, Address = "Иваново, Улица Менделеева, 16*", BuilderId = 1, Floors = 1, YearFinish = 1955, StateId = 1, ProjectId = 11, Name = "ТП-303"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.98785506770132, CoordinatesY = 40.98036149999994, Address = "Иваново, Московская улица, 49*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 7, Name = "ТП-25"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.96724756773902, CoordinatesY = 40.985518000000006, Address = "Иваново, Московский микрорайон, 15*", BuilderId = 1, Floors = 1, YearFinish = 2010, StateId = 1, ProjectId = 1, Name = "ТП-6"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.96724756773902, CoordinatesY = 40.985518000000006, Address = "Иваново, Улица Наумова, 1*", BuilderId = 1, Floors = 1, YearFinish = 1975, StateId = 1, ProjectId = 9, Name = "ТП-707"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.020716067664914, CoordinatesY = 40.99361199999998, Address = "Иваново, Улица Носова, 49А*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 4, Name = "ТП"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.99768556769643, CoordinatesY = 40.94547999999996, Address = "Иваново, Улица Парижской Коммуны, 15А*", BuilderId = 1, Floors = 1, YearFinish = 1973, StateId = 1, ProjectId = 9, Name = "ТП-671"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.99912256770007, CoordinatesY = 40.94739349999998, Address = "Иваново, Улица Парижской Коммуны, 44*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 1, Name = "ТП-171"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.00007356770253, CoordinatesY = 40.93554449999993, Address = "Иваново, Улица Парижской Коммуны, 60*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 7, Name = "ТП-271"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.00454941395441, CoordinatesY = 40.97732832993254, Address = "Иваново, Пограничный переулок, 10А*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 6, Name = "ТП-507"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.03207156766386, CoordinatesY = 40.98002049999999, Address = "Иваново, Улица Полка Нормандия-Неман, 71*", BuilderId = 1, Floors = 1, YearFinish = 1965, StateId = 1, ProjectId = 1, Name = "ТП-531"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.98489256772397, CoordinatesY = 40.992677499999985, Address = "Иваново, Улица Постышева, 56*", BuilderId = 1, Floors = 1, YearFinish = 1969, StateId = 1, ProjectId = 9, Name = "ТП-178"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.98011056771168, CoordinatesY = 40.964515499999976, Address = "Иваново, Улица Поэта Лебедева, 23*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 1, Name = "ТП-417"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.98381412847225, CoordinatesY = 40.97091622289264, Address = "Иваново, Улица Поэта Майорова, 28*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 1, Name = "ТП"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.00046056770353, CoordinatesY = 40.990422999999986, Address = "Иваново, Улица Поэта Ноздрина, 11*", BuilderId = 1, Floors = 1, YearFinish = 1979, StateId = 1, ProjectId = 9, Name = "ТП-716"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.00015855832371, CoordinatesY = 40.97136788888545, Address = "Иваново, Площадь Пушкина, 9*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 1, Name = "ТП-182"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.99558256769098, CoordinatesY = 40.99172549999996, Address = "Иваново, Улица Пушкина, 47*", BuilderId = 1, Floors = 1, YearFinish = 1975, StateId = 1, ProjectId = 7, Name = "ТП-523"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.009912999754775, CoordinatesY = 40.95287994180296, Address = "Иваново, Рабфаковская улица, 4*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 1, Name = "ТП-14"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.99476356768888, CoordinatesY = 40.98049649999991, Address = "Иваново, Площадь Революции, 6*", BuilderId = 1, Floors = 1, YearFinish = 2012, StateId = 1, ProjectId = 1, Name = "ТП-416"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.99303370445199, CoordinatesY = 40.98881482209014, Address = "Иваново, Рыночный переулок, 2*", BuilderId = 1, Floors = 1, YearFinish = 1968, StateId = 1, ProjectId = 8, Name = "ТП-105"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.99954356770115, CoordinatesY = 40.98754849999998, Address = "Иваново, Садовая улица, 12*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 1, Name = "ТП-312"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.0131845676758, CoordinatesY = 40.99995399999992, Address = "Иваново, Улица Сарментовой, 15", BuilderId = 5, Floors = 1, YearFinish = 1975, StateId = 1, ProjectId = 12, Name = "Тяговая подстанция №10"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.96431806776176, CoordinatesY = 40.96735399999999, Address = "Иваново, Улица Станкостроителей, 1А", BuilderId = 5, Floors = 1, YearFinish = 1975, StateId = 1, ProjectId = 12, Name = "Тяговая подстанция №8"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.00028906767286, CoordinatesY = 40.955648999999944, Address = "Иваново, Строительная улица, 4*", BuilderId = 1, Floors = 1, YearFinish = 1955, StateId = 1, ProjectId = 1, Name = "ТП-242"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.98383356772122, CoordinatesY = 40.97333699999994, Address = "Иваново, Улица Танкиста Белороссова, 1*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 1, Name = "ТП-885"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.99516100180279, CoordinatesY = 40.97582446572188, Address = "Иваново, Театральная улица, 2*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 7, Name = "ТП-13"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.03206656766381, CoordinatesY = 40.96793799999996, Address = "Иваново, Улица Фрунзе, 17А*", BuilderId = 1, Floors = 1, YearFinish = 1965, StateId = 1, ProjectId = 13, Name = "ТП-534"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.03281656766574, CoordinatesY = 40.9693484999999, Address = "Иваново, Улица Фрунзе, 21*", BuilderId = 1, Floors = 1, YearFinish = 1955, StateId = 1, ProjectId = 1, Name = "ТП-186"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.01568406765197, CoordinatesY = 40.98223049999995, Address = "Иваново, Улица Фурманова, 27*", BuilderId = 1, Floors = 1, YearFinish = 1965, StateId = 1, ProjectId = 5, Name = "ТП"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 56.99052206770821, CoordinatesY = 40.927801499999994, Address = "Иваново, Шахтинский проезд, 88*", BuilderId = 1, Floors = 2, StateId = 1, ProjectId = 1, Name = "ТП-614"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.00095106767455, CoordinatesY = 40.987853499999964, Address = "Иваново, Шереметевский проспект, 18*", BuilderId = 1, Floors = 1, YearFinish = 1960, StateId = 1, ProjectId = 4, Name = "ТП-385"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.001828567707044, CoordinatesY = 40.989425499999896, Address = "Иваново, Шереметевский проспект, 26*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 9, Name = "ТП-651"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.00120556770545, CoordinatesY = 40.985976000000015, Address = "Иваново, Шереметевский проспект, 29*", BuilderId = 1, Floors = 1, YearFinish = 2010, StateId = 1, ProjectId = 1, Name = "Трансформаторная подстанция"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.00337756771101, CoordinatesY = 40.987898499999964, Address = "Иваново, Шереметевский проспект, 45*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 9, Name = "ТП-635"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.00417156771305, CoordinatesY = 40.989767000000015, Address = "Иваново, Шереметевский проспект, 53*", BuilderId = 1, Floors = 1, YearFinish = 2010, StateId = 1, ProjectId = 10, Name = "ТП-959"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.007735067691975, CoordinatesY = 40.98941649999991, Address = "Иваново, Шереметевский проспект, 85*", BuilderId = 1, Floors = 1, YearFinish = 1975, StateId = 1, ProjectId = 9, Name = "ТП-725"
                    },
                    new TransformerSubstation {
                        CoordinatesX = 57.00475506768432, CoordinatesY = 40.94364749999998, Address = "Иваново, Ярмарочная улица, 8*", BuilderId = 1, Floors = 1, StateId = 1, ProjectId = 1, Name = "ТП-52"
                    },
                    //new TransformerSubstation {CoordinatesX = , CoordinatesY = , Address="", BuilderId= 1,Floors=1,YearFinish=,StateId=1,ProjectId=1, Name=""},
                    //new TransformerSubstation {CoordinatesX = , CoordinatesY = , Address="", BuilderId= 1,Floors=1,YearFinish=,StateId=1,ProjectId=1, Name=""},
                    //new TransformerSubstation {CoordinatesX = , CoordinatesY = , Address="", BuilderId= 1,Floors=1,YearFinish=,StateId=1,ProjectId=1, Name=""},
                    //new TransformerSubstation {CoordinatesX = , CoordinatesY = , Address="", BuilderId= 1,Floors=1,YearFinish=,StateId=1,ProjectId=1, Name=""},
                    //new TransformerSubstation {CoordinatesX = , CoordinatesY = , Address="", BuilderId= 1,Floors=1,YearFinish=,StateId=1,ProjectId=1, Name=""},
                };
                foreach (TransformerSubstation b in TransformerSubstations)
                {
                    context.TransformerSubstation.Add(b);
                }
                context.SaveChanges();
            }
        }
Beispiel #19
0
 public Interval(T minimum, T maximum, Topology topology) : this()
 {
     Minimum  = minimum;
     Maximum  = maximum;
     Topology = topology;
 }
        /// <summary>
        /// Find articulation points.
        /// For an explanation, see:
        /// https://www.boristhebrave.com/2018/04/28/random-paths-via-chiseling/
        /// </summary>
        public static bool[] GetArticulationPoints(Topology topology, bool[] walkable, bool[] relevant)
        {
            var indices = walkable.Length;

            var low            = new int[indices];
            var num            = 1;
            var dfsNum         = new int[indices];
            var isArticulation = new bool[indices];

            Tuple <int, bool> cutvertex(int u)
            {
                var childCount = 0;
                var isRelevant = relevant != null && relevant[u];

                if (isRelevant)
                {
                    isArticulation[u] = true;
                }
                var isRelevantSubtree = isRelevant;

                low[u] = dfsNum[u] = num++;

                int ux, uy, uz;

                topology.GetCoord(u, out ux, out uy, out uz);
                for (var d = 0; d < topology.Directions.Count; d++)
                {
                    int v;
                    if (!topology.TryMove(ux, uy, uz, d, out v))
                    {
                        continue;
                    }
                    if (!walkable[v])
                    {
                        continue;
                    }
                    // v is a neighbour of u
                    var unvisited = dfsNum[v] == 0;
                    if (unvisited)
                    {
                        var childRelevantSubtree = cutvertex(v).Item2;
                        childCount++;
                        if (childRelevantSubtree)
                        {
                            isRelevantSubtree = true;
                        }
                        if (low[v] >= dfsNum[u])
                        {
                            if (relevant == null || childRelevantSubtree)
                            {
                                isArticulation[u] = true;
                            }
                        }
                        low[u] = Math.Min(low[u], low[v]);
                    }
                    else
                    {
                        low[u] = Math.Min(low[u], dfsNum[v]);
                    }
                }
                return(Tuple.Create(childCount, isRelevantSubtree));
            }

            // Find starting point
            for (var i = 0; i < indices; i++)
            {
                if (!walkable[i])
                {
                    continue;
                }
                if (relevant != null && !relevant[i])
                {
                    continue;
                }
                var childCount = cutvertex(i).Item1;
                isArticulation[i] = childCount > 1 || relevant != null;
                if (isArticulation[i])
                {
                    break;
                }
            }

            // Check we've visited every relevant point.
            // If not, there's no way to satisfy the constraint.
            for (var i = 0; i < indices; i++)
            {
                if (relevant != null && relevant[i] && dfsNum[i] == 0)
                {
                    return(null);
                }
            }

            return(isArticulation);
        }
Beispiel #21
0
        public SampleSet Load(string filename)
        {
            var srcFilename = filename;
            var map         = TiledUtil.Load(filename);
            // Scan tilesets for tiles with a custom property "name"
            var tilesByName = new Dictionary <string, Tile>();

            foreach (var tileset in map.Tilesets)
            {
                AddTileset(tilesByName, tileset);
            }
            ITopoArray <Tile> sample;

            if (map.Orientation == Orientation.hexagonal)
            {
                // Read a single layer
                var layer = (TileLayer)map.Layers[0];
                sample = TiledUtil.ReadLayer(map, layer);
            }
            else
            {
                // Read all the layers into a 3d array.
                var tileLayers = map.Layers
                                 .Where(x => x is TileLayer)
                                 .Cast <TileLayer>()
                                 .ToList();
                Tile[,,] results = null;
                Topology topology = null;
                for (var z = 0; z < tileLayers.Count; z++)
                {
                    var layer      = tileLayers[z];
                    var layerArray = TiledUtil.ReadLayer(map, layer);
                    if (z == 0)
                    {
                        topology = layerArray.Topology;
                        results  = new Tile[topology.Width, topology.Height, tileLayers.Count];
                    }
                    for (var y = 0; y < topology.Height; y++)
                    {
                        for (var x = 0; x < topology.Width; x++)
                        {
                            results[x, y, z] = layerArray.Get(x, y);
                        }
                    }
                }
                if (tileLayers.Count > 1 && topology.Directions.Type == DirectionSetType.Cartesian2d)
                {
                    topology = new Topology(DirectionSet.Cartesian3d, map.Width, map.Height, tileLayers.Count, false, false, false);
                }
                else
                {
                    topology = new Topology(topology.Directions, topology.Width, topology.Height, tileLayers.Count, false, false, false);
                }
                sample = TopoArray.Create(results, topology);
            }

            return(new SampleSet
            {
                Directions = sample.Topology.Directions,
                Samples = new[] { sample },
                TilesByName = tilesByName,
                ExportOptions = new TiledExportOptions
                {
                    Template = map,
                    SrcFileName = srcFilename,
                },
            });
        }
Beispiel #22
0
 public override void BuildTopology()
 {
     this.Topology = new RegularGridTopology();
     Topology.Build();
 }
Beispiel #23
0
        public async Task process(IConfiguration config)
        {
            Console.WriteLine("Process");
            var sConfig = new StreamConfig <StringSerDes, StringSerDes>();


            sConfig.ApplicationId       = config["SPRING_CLOUD_APPLICATION_GROUP"];
            sConfig.BootstrapServers    = config["SPRING_CLOUD_STREAM_KAFKA_BINDER_BROKERS"];
            sConfig.AutoOffsetReset     = AutoOffsetReset.Earliest;
            sConfig.SchemaRegistryUrl   = config["SchemaRegistryUrl"];
            sConfig.AutoRegisterSchemas = true;
            sConfig.NumStreamThreads    = 1;
            sConfig.Acks = Acks.All;
            //sConfig.Debug = "consumer,cgrp,topic,fetch";
            sConfig.AddConsumerConfig("allow.auto.create.topics", "true");
            sConfig.MaxTaskIdleMs         = 50;
            sConfig.InnerExceptionHandler = (e) => ExceptionHandlerResponse.CONTINUE;


            var      timeout = TimeSpan.FromSeconds(10);
            DateTime dt      = DateTime.Now;

            OrderProduct op = new OrderProduct();

            var serializer = new SchemaAvroSerDes <OrderProduct>();

            StreamBuilder builder = new StreamBuilder();

            var table = builder.Table(config["simpleNetcoreProcessor.externaltopic"],
                                      new Int32SerDes(),
                                      new SchemaAvroSerDes <Product>(),
                                      InMemory <int, Product> .As(config["simpleNetcoreProcessor.table"]));

            builder.Stream <int, Order, Int32SerDes, SchemaAvroSerDes <Order> >(config["spring.cloud.stream.bindings.input.destination"])
            .Join(table, (order, product) =>
            {
                Console.WriteLine("Order: " + order?.order_id);
                Console.WriteLine("Product: " + product?.product_id);

                op = new OrderProduct
                {
                    order_id      = order.order_id,
                    price         = order.price,
                    product_id    = product.product_id,
                    product_name  = product.name,
                    product_price = product.price
                };
                return(op);
            })

            .To <Int32SerDes, SchemaAvroSerDes <OrderProduct> >(config["spring.cloud.stream.bindings.output.destination"]);
            Topology t = builder.Build();

            Console.WriteLine(t.Describe());



            KafkaStream stream = new KafkaStream(t, sConfig);

            bool isRunningState = false;

            stream.StateChanged += (old, @new) =>
            {
                if (@new.Equals(KafkaStream.State.RUNNING))
                {
                    isRunningState = true;
                }
            };

            await stream.StartAsync();

            while (!isRunningState)
            {
                Thread.Sleep(250);
                if (DateTime.Now > dt + timeout)
                {
                    break;
                }
            }

            if (isRunningState)
            {
                Console.WriteLine("Stream running state is " + isRunningState.ToString());
            }
        }
            private void Construct(List<Rhino.DocObjects.RhinoObject> ObjectList)
            {
                BoundingBox Box = ObjectList[0].Geometry.GetBoundingBox(true);
                for (int i = 1; i < ObjectList.Count; i++) Box.Union(ObjectList[i].Geometry.GetBoundingBox(true));

                List<GeometryBase> BList = new List<GeometryBase>();

                Brep_ids = new List<int>();

                List<Material> Mat_Layer = new List<Material>();
                List<Scattering> Scat_Layer = new List<Scattering>();
                List<Material> Mat_Obj = new List<Material>();
                List<Scattering> Scat_Obj = new List<Scattering>();
                List<double[]> Trans_Layer = new List<double[]>();
                List<double[]> Trans_Obj = new List<double[]>();
                List<bool> Finite_Layers = new List<bool>();
                List<bool> Finite_Obj = new List<bool>();
                //Organize the geometry into Breps
                //Get materials for each layer:
                for (int l = 0; l < Rhino.RhinoDoc.ActiveDoc.Layers.Count; l++)
                {
                    Rhino.DocObjects.Layer Layer = Rhino.RhinoDoc.ActiveDoc.Layers[l];
                    string abstype = Layer.GetUserString("ABSType");
                    if (abstype == "Buildup")
                    {
                        Finite_Layers.Add(false);
                        string BU = Layer.GetUserString("BuildUp");
                        string[] BU_split = BU.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        List<AbsorptionModels.ABS_Layer> Buildup = new List<AbsorptionModels.ABS_Layer>();
                        foreach (string swatch in BU_split) Buildup.Add(AbsorptionModels.ABS_Layer.LayerFromCode(swatch));
                        Mat_Layer.Add(new Environment.Smart_Material(Buildup, 44100, Env_Prop.Rho(0), Env_Prop.Sound_Speed(0), 2));

                        double[] Abs = new double[8], Scat = new double[8], Trans = new double[8];
                        Pachyderm_Acoustic.UI.PachydermAc_PlugIn.DecodeAcoustics(Layer.GetUserString("Acoustics"), ref Abs, ref Scat, ref Trans);
                        ///Other properties are still coefficient based...
                        Scat_Layer.Add(new Environment.Lambert_Scattering(Scat, SplitRatio));
                        Trans_Layer.Add(Trans);
                    }
                    else if (abstype == "Buildup_Finite")
                    {
                        Finite_Layers.Add(true);
                        string BU = Layer.GetUserString("BuildUp");
                        string[] BU_split = BU.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        List<AbsorptionModels.ABS_Layer> Buildup = new List<AbsorptionModels.ABS_Layer>();
                        foreach (string swatch in BU_split) Buildup.Add(AbsorptionModels.ABS_Layer.LayerFromCode(swatch));
                        Environment.Smart_Material sm = new Environment.Smart_Material(Buildup, 44100, Env_Prop.Rho(0), Env_Prop.Sound_Speed(0), 2);
                        Mat_Layer.Add(sm);
                        double[] Abs = new double[8], Scat = new double[8], Trans = new double[8];
                        Pachyderm_Acoustic.UI.PachydermAc_PlugIn.DecodeAcoustics(Layer.GetUserString("Acoustics"), ref Abs, ref Scat, ref Trans);
                        ///Other properties are still coefficient based...
                        Scat_Layer.Add(new Environment.Lambert_Scattering(Scat, SplitRatio));
                        Trans_Layer.Add(Trans);
                    }
                    else
                    {
                        Finite_Layers.Add(false);
                        string spec = Layer.GetUserString("Acoustics");

                        if (spec == "")
                        {
                            ///Layer is not used. As long as there is no geometry for pachyderm on this layer without object set properties, this is ok.
                            Mat_Layer.Add(null);
                            Scat_Layer.Add(null);
                            Trans_Layer.Add(null);
                            continue;
                        }

                        double[] Abs = new double[8], Scat = new double[8], Trans = new double[8];
                        Pachyderm_Acoustic.UI.PachydermAc_PlugIn.DecodeAcoustics(spec, ref Abs, ref Scat, ref Trans);
                        Mat_Layer.Add(new Environment.Basic_Material(Abs, new double[8] { 0, 0, 0, 0, 0, 0, 0, 0 }));
                        Scat_Layer.Add(new Environment.Lambert_Scattering(Scat, SplitRatio));
                        Trans_Layer.Add(Trans);
                    }
                }

                for (int q = 0; q <= ObjectList.Count - 1; q++)
                {
                    List<Brep> B = new List<Brep>();
                    if (ObjectList[q].ObjectType == Rhino.DocObjects.ObjectType.Brep)
                    {
                        Rhino.DocObjects.BrepObject BObj = ((Rhino.DocObjects.BrepObject)ObjectList[q]);
                        B.Add(BObj.BrepGeometry.DuplicateBrep());
                        //string m = ObjectList[q].Geometry.GetUserString("Acoustics_User");
                        if (ObjectList[q].Geometry.GetUserString("Acoustics_User") == "yes")
                        {
                            double[] ABS = new double[8], SCAT = new double[8], TRANS = new double[8];
                            Pachyderm_Acoustic.UI.PachydermAc_PlugIn.DecodeAcoustics(ObjectList[q].Geometry.GetUserString("Acoustics"), ref ABS, ref SCAT, ref TRANS);
                            Mat_Obj.Add(new Basic_Material(ABS, new double[] { 0, 0, 0, 0, 0, 0, 0, 0 }));
                            Finite_Obj.Add(false);
                            Scat_Obj.Add(new Lambert_Scattering(SCAT, SplitRatio));
                            Trans_Obj.Add(TRANS);
                        }
                        else
                        {
                            //Rhino.DocObjects.Layer Layer = Rhino.RhinoDoc.ActiveDoc.Layers[ObjectList[q].Attributes.LayerIndex];
                            //AcousticsData.Add(Layer.GetUserString("Acoustics"));
                            Mat_Obj.Add(Mat_Layer[ObjectList[q].Attributes.LayerIndex]);
                            Scat_Obj.Add(Scat_Layer[ObjectList[q].Attributes.LayerIndex]);
                            Trans_Obj.Add(Trans_Layer[ObjectList[q].Attributes.LayerIndex]);
                            Finite_Obj.Add(Finite_Layers[ObjectList[q].Attributes.LayerIndex]);
                        }
                    }
                    else if (ObjectList[q].ObjectType == Rhino.DocObjects.ObjectType.Extrusion)
                    {
                        Rhino.Geometry.Brep BObj = ((Rhino.DocObjects.ExtrusionObject)ObjectList[q]).ExtrusionGeometry.ToBrep();
                        for (int i = 0; i < BObj.Faces.Count; i++)
                        {
                            if (ObjectList[q].Geometry.GetUserString("Acoustics_User") == "yes")
                            {
                                //AcousticsData.Add(ObjectList[q].Geometry.GetUserString("Acoustics"));
                                double[] ABS = new double[8], SCAT = new double[8], TRANS = new double[8];
                                Pachyderm_Acoustic.UI.PachydermAc_PlugIn.DecodeAcoustics(ObjectList[q].Geometry.GetUserString("Acoustics"), ref ABS, ref SCAT, ref TRANS);
                                Mat_Obj.Add(new Basic_Material(ABS, new double[] { 0, 0, 0, 0, 0, 0, 0, 0 }));
                                Scat_Obj.Add(new Lambert_Scattering(SCAT, SplitRatio));
                                Trans_Obj.Add(TRANS);
                                Finite_Obj.Add(false);
                            }
                            else
                            {
                                //Rhino.DocObjects.Layer Layer = Rhino.RhinoDoc.ActiveDoc.Layers[ObjectList[q].Attributes.LayerIndex];
                                //AcousticsData.Add(Layer.GetUserString("Acoustics"));
                                //Rhino.DocObjects.Layer Layer = Rhino.RhinoDoc.ActiveDoc.Layers[ObjectList[q].Attributes.LayerIndex];
                                //AcousticsData.Add(Layer.GetUserString("Acoustics"));
                                Mat_Obj.Add(Mat_Layer[ObjectList[q].Attributes.LayerIndex]);
                                Scat_Obj.Add(Scat_Layer[ObjectList[q].Attributes.LayerIndex]);
                                Trans_Obj.Add(Trans_Layer[ObjectList[q].Attributes.LayerIndex]);
                                Finite_Obj.Add(Finite_Layers[ObjectList[q].Attributes.LayerIndex]);
                            }

                            //B.Add(BObj.Faces[0].ToBrep());
                            //for (int i = 1; i < BObj.Faces.Count; i++)
                            //{
                            //    if (ObjectList[q].Geometry.GetUserString("Acoustics_User") == "yes")
                            //    {
                            //        AcousticsData.Add(ObjectList[q].Geometry.GetUserString("Acoustics"));
                            //    }
                            //    else
                            //    {
                            //        Rhino.DocObjects.Layer Layer = Rhino.RhinoDoc.ActiveDoc.Layers[ObjectList[q].Attributes.LayerIndex];
                            //        AcousticsData.Add(Layer.GetUserString("Acoustics"));
                            //    }
                            B.Add(BObj.Faces[i].ToBrep());
                        }
                    }
                    else
                    {
                        continue;
                    }
                    BList.AddRange(B);
                }

                ////////////////////////////////////////
                Topo = new Hare.Geometry.Topology[1];
                Topo[0] = new Topology(Utilities.PachTools.RPttoHPt(Box.Min), Utilities.PachTools.RPttoHPt(Box.Max));
                ////////////////////////////////////////
                for (int q = 0; q < BList.Count; q++)
                {
                    for (int r = 0; r < ((Brep)BList[q]).Faces.Count; r++)
                    {
                        BrepList.Add(((Brep)BList[q]).Faces[r].DuplicateFace(false));

                        //Material Abs = null ;
                        //Scattering Scat = null;

                        //double[] Transparency = new double[8];
                        double[] Transmission = new double[8];

                        //double[] Scat = new double[8];
                        //if (!string.IsNullOrEmpty(AcousticsData[q]))
                        //if (Mat_Obj[q] != null)
                        //{
                        //    //double[] Absorption = new double[8];
                        //    //double[] phase = new double[8];
                        //    //double[] Scattering = new double[8];
                        //    ////double[,] Scattering = new double[8, 3];
                        //    //double[] Reflection = new double[8];
                        //    //UI.PachydermAc_PlugIn.DecodeAcoustics(AcousticsData[q], ref Absorption, ref Scattering, ref Transparency);
                        //    Abs = Mat_Obj[q];
                        //    Scat = Scat_Obj[q];
                        //    Transmission = Trans_Obj[q];
                        //}
                        //else
                        if ((Mat_Obj[q] == null) || (Scat_Obj[q] == null) || (Trans_Obj[q] == null))
                        {
                            if (!Custom_Method)
                            {
                                Status = System.Windows.Forms.MessageBox.Show("A material is not specified correctly. Please assign absorption and scattering to all layers in the model.", "Materials Error", System.Windows.Forms.MessageBoxButtons.OK);
                                Complete = false;
                                return;
                            }
                            ///Materials do not need to be specified, as it will not be used for an acoustical simulation... (hopefully...)
                        }

                        //for (int i = 0; i < 8; i++)
                        //{
                        //    Reflection[i] = (1 - Absorption[i]);
                        //    Transmission[i] = Transparency[i];
                        //    Scattering[i, 1] = Scat[i];
                        //    double Mod = ((Scattering[i, 1] < (1 - Scattering[i, 1])) ? (Scattering[i, 1] * SplitRatio / 2) : ((1 - Scattering[i, 1]) * SplitRatio / 2));
                        //    Scattering[i, 0] = Scattering[i, 1] - Mod;
                        //    Scattering[i, 2] = Scattering[i, 1] + Mod;
                        //    phase[i] = 0;
                        //}

                        Mesh[] meshes;
                        MeshingParameters mp = new MeshingParameters();
                        if (Finite_Obj[q])
                        {
                            mp.MinimumEdgeLength = 0.1;
                            mp.SimplePlanes = false;
                        }
                        else
                        {
                            mp.MinimumEdgeLength = 0.1;
                            mp.SimplePlanes = true;
                        }

                        meshes = Rhino.Geometry.Mesh.CreateFromBrep((Brep)BrepList[BrepList.Count - 1], mp);
                        if (meshes == null) throw new Exception("Problem with meshes");

                        for (int t = 0; t < meshes.Length; t++)
                        {
                            if (meshes[t].Faces.Count < 1)
                            {
                                Status = System.Windows.Forms.MessageBox.Show("A surface in the model does not generate a rendermesh. This surface will not be represented in the simulation. It is recommended that you cancel this simulation and repair the affected surface. It can be located in shaded view by finding the surface which generates boundary and isoparm lines, but does not generate a fill. It can sometimes be repaired by running the command 'ShrinkTrimmedSurface'. If this does not work, it will have to be replaced by some means which would generate a proper surface.", "Surface without Rendermesh", System.Windows.Forms.MessageBoxButtons.OKCancel);
                                if (Status == System.Windows.Forms.DialogResult.Cancel)
                                {
                                    Complete = false;
                                    return;
                                }
                                continue;
                            }

                            for (int u = 0; u < meshes[t].Faces.Count; u++)
                            {
                                Hare.Geometry.Point[] P;
                                if (meshes[t].Faces[u].IsQuad)
                                {
                                    P = new Hare.Geometry.Point[4];
                                    Point3f FP = meshes[t].Vertices[meshes[t].Faces[u][0]];
                                    P[0] = new Hare.Geometry.Point(FP.X, FP.Y, FP.Z);
                                    FP = meshes[t].Vertices[meshes[t].Faces[u][1]];
                                    P[1] = new Hare.Geometry.Point(FP.X, FP.Y, FP.Z);
                                    FP = meshes[t].Vertices[meshes[t].Faces[u][2]];
                                    P[2] = new Hare.Geometry.Point(FP.X, FP.Y, FP.Z);
                                    FP = meshes[t].Vertices[meshes[t].Faces[u][3]];
                                    P[3] = new Hare.Geometry.Point(FP.X, FP.Y, FP.Z);
                                }
                                else
                                {
                                    P = new Hare.Geometry.Point[3];
                                    Point3f FP = meshes[t].Vertices[meshes[t].Faces[u][0]];
                                    P[0] = new Hare.Geometry.Point(FP.X, FP.Y, FP.Z);
                                    FP = meshes[t].Vertices[meshes[t].Faces[u][1]];
                                    P[1] = new Hare.Geometry.Point(FP.X, FP.Y, FP.Z);
                                    FP = meshes[t].Vertices[meshes[t].Faces[u][2]];
                                    P[2] = new Hare.Geometry.Point(FP.X, FP.Y, FP.Z);
                                }

                                if (Finite_Obj[q])
                                {
                                    if (!(Mat_Obj[q] is Smart_Material)) throw new Exception("Finite Material must have a Smart_Material...");
                                    Smart_Material mat = Mat_Obj[q] as Smart_Material;
                                    AbsorptionData.Add(new Finite_Material(mat, BrepList[q], meshes[t], u, Env_Prop));
                                }
                                else AbsorptionData.Add(Mat_Obj[q]);
                                ScatteringData.Add(Scat_Obj[q]);
                                TransmissionData.Add(Trans_Obj[q]);

                                bool Trans = false;
                                for (int t_oct = 0; t_oct < 8; t_oct++)
                                {
                                    if (Transmission[t_oct] > 0)
                                    {
                                        Trans = true;
                                        break;
                                    }
                                }
                                Transmissive.Add(Trans);
                                if (BrepList[BrepList.Count - 1].Faces[t].IsPlanar())
                                {
                                    Topo[0].Add_Polygon(P);
                                    Brep_ids.Add(BrepList.Count - 1);
                                }
                                else
                                {
                                    Topo[0].Add_Polygon(new Hare.Geometry.Point[3] { P[0], P[1], P[2] });
                                    Brep_ids.Add(BrepList.Count - 1);
                                    if (P.Length > 3)
                                    {
                                        //break this quad into two polygons in order to avoid warping...
                                        if (Finite_Obj[q])
                                        {
                                            if (!(Mat_Obj[q] is Smart_Material)) throw new Exception("Finite Material must have a Smart_Material...");
                                            Smart_Material mat = Mat_Obj[q] as Smart_Material;
                                            AbsorptionData.Add(new Finite_Material(mat, BrepList[q], meshes[t], u, Env_Prop));
                                        }
                                        else AbsorptionData.Add(Mat_Obj[q]);
                                        ScatteringData.Add(Scat_Obj[q]);
                                        TransmissionData.Add(Trans_Obj[q]);
                                        Transmissive.Add(Trans);
                                        Topo[0].Add_Polygon(new Hare.Geometry.Point[3] { P[0], P[2], P[3] });
                                        Brep_ids.Add(BrepList.Count - 1);
                                    }
                                }
                            }
                        }
                    }
                }

                //Set up a system to find random points on planes.//
                Plane_Area = new double[Topo[0].Plane_Members.Length];
                PolyPlaneFract = new double[Topo[0].Plane_Members.Length][];

                for (int q = 0; q < Topo[0].Plane_Members.Length; q++)
                {
                    foreach (int t in Topo[0].Plane_Members[q])
                    {
                        Plane_Area[q] += Topo[0].Polygon_Area(t);
                    }
                }

                //////////////////////////
                for (int i = 0; i < Topo[0].planeList.Count; i++)
                    for (int j = 0; j < Topo[0].Plane_Members[i].Count; j++)
                    {
                        Point3d pt = Utilities.PachTools.HPttoRPt(Topo[0].Polygon_Centroid(Topo[0].Plane_Members[i][j]));
                        string n = Topo[0].Polys[Topo[0].Plane_Members[i][j]].Plane_ID.ToString();
                    }
                //////////////////////////

                for (int q = 0; q < Topo[0].Plane_Members.Length; q++)
                {
                    PolyPlaneFract[q] = new double[Topo[0].Plane_Members[q].Count];
                    PolyPlaneFract[q][0] = Topo[0].Polygon_Area(Topo[0].Plane_Members[q][0]) / Plane_Area[q];
                    for (int t = 1; t < Topo[0].Plane_Members[q].Count; t++)
                    {
                        PolyPlaneFract[q][t] += PolyPlaneFract[q][t - 1] + Topo[0].Polygon_Area(Topo[0].Plane_Members[q][t]) / Plane_Area[q];
                    }
                }
                Valid = true;

                //Utilities.PachTools.Plot_Hare_Topology(Topo[0]);
            }
Beispiel #25
0
        /// <summary>
        /// <para>Only Availible on NVidia 8800's (Time of writing).</para> 
        /// <para>Draws buffers as instanced. Primitive
        /// Count refers to the amount of times the object is drawn. inside a shader. 
        /// The instance can be looked up via the gl_InstanceId sematic.</para>
        /// </summary>
        /// <param name="topology"></param>
        /// <param name="primitiveCount"></param>
        public void DrawInstanced(Topology topology, int primitiveCount)
        {
            this.EnableTextures();

            this.EnableVertexDeclaration();

            Gl.glBindBuffer(Gl.GL_ELEMENT_ARRAY_BUFFER, this.indexBuffer.Handle);

            

            Gl.glDrawElementsInstancedEXT((int)topology, this.indexBuffer.Count, Gl.GL_UNSIGNED_INT, (IntPtr)0, primitiveCount);

            this.DisableVertexDeclaration();

            this.DisableTextures();
        }
Beispiel #26
0
        public void TweakTriangles(float ratio, Random rand)
        {
            NeedsUpdate = true;

            // Assumptions: minimised mesh. Shared edges won't work without shared verts.
            Topology.GenerateEdges();

            // How many edges do we have? exchange some percentage of them...
            int          numPerturbations = (int)((float)Topology.Edges.Count * ratio);
            int          numTriangles     = mesh.vertices.Length;
            List <Int64> keys             = new List <Int64>(Topology.Edges.Keys);

            List <int> visitedTris = new List <int>();

            for (int i = 0; i < numPerturbations; ++i)
            {
                // Choose a random edge:
                int edgeIndex = rand.Next(Topology.Edges.Count);
                // Check out the tris around the edge.
                Int64 key  = keys[edgeIndex];
                Edge  edge = Topology.Edges[key];

                // TODO - add flag to triangle to avoid n2/2 lookup.
                bool r = false;
                foreach (var visited in visitedTris)
                {
                    if (edge.triangle1 == visited || edge.triangle2 == visited)
                    {
                        r = true;
                        break;
                    }
                }
                if (r)
                {
                    continue;
                }

                visitedTris.Add(edge.triangle1);
                visitedTris.Add(edge.triangle2);

                if (IsObtuse(edge.triangle1) || IsObtuse(edge.triangle2))
                {
                    continue;
                }

                uint index1 = (uint)(key & 0xffffffff);
                uint index2 = (uint)((key >> 32) & 0xffffffff);
                uint index3;
                uint index4;
                uint a = index1;

                int cornerA = GetTriOffset(edge.triangle1, a);
                // get the next coord in the triangle (in ccw order)
                uint b = indices[edge.triangle1 * 3 + ((cornerA + 1) % 3)];
                uint c = indices[edge.triangle1 * 3 + ((cornerA + 2) % 3)];
                uint d = 0;
                if (b == index2)
                {
                    d      = indices[edge.triangle2 * 3 + ((GetTriOffset(edge.triangle2, a) + 1) % 3)];
                    index3 = c;
                    index4 = d;
                }
                else
                {
                    d      = indices[edge.triangle2 * 3 + ((GetTriOffset(edge.triangle2, a) + 2) % 3)];
                    index3 = b;
                    index4 = d;
                }

                if (Topology.TrianglesPerVertex[index1] <= 5 || Topology.TrianglesPerVertex[index2] <= 5 ||
                    Topology.TrianglesPerVertex[index3] >= 7 || Topology.TrianglesPerVertex[index4] >= 7)
                {
                    continue;
                }
                // Check edge lengths
                Vector3 pos1 = MeshAttr.GetPosition(ref mesh.vertices[index1]);
                Vector3 pos2 = MeshAttr.GetPosition(ref mesh.vertices[index2]);
                Vector3 pos3 = MeshAttr.GetPosition(ref mesh.vertices[index3]);
                Vector3 pos4 = MeshAttr.GetPosition(ref mesh.vertices[index4]);

                float oldLength = new Vector3(pos2 - pos1).Length;
                float newLength = new Vector3(pos4 - pos3).Length;
                if (oldLength / newLength >= 2 || oldLength / newLength <= 0.5f)
                {
                    continue;
                }

                Topology.TrianglesPerVertex[index1]--;
                Topology.TrianglesPerVertex[index2]--;
                Topology.TrianglesPerVertex[index3]++;
                Topology.TrianglesPerVertex[index4]++;

                // Need to keep tris in CCW order.
                if (b == index2)
                {
                    // order is a b c; c is the non-shared vertex.
                    // new tris are: ADC, DBC
                    // tri2 order is a d b
                    indices[edge.triangle1 * 3]     = a;
                    indices[edge.triangle1 * 3 + 1] = d;
                    indices[edge.triangle1 * 3 + 2] = c;
                    indices[edge.triangle2 * 3]     = d;
                    indices[edge.triangle2 * 3 + 1] = b;
                    indices[edge.triangle2 * 3 + 2] = c;
                }
                else
                {
                    // order is a b c; b is the non-shared value
                    // new tris are ACD, CBD
                    // tri2 order is a b d
                    indices[edge.triangle1 * 3]     = a;
                    indices[edge.triangle1 * 3 + 1] = b;
                    indices[edge.triangle1 * 3 + 2] = d;
                    indices[edge.triangle2 * 3]     = c;
                    indices[edge.triangle2 * 3 + 1] = d;
                    indices[edge.triangle2 * 3 + 2] = b;
                }
            }

            Topology.Regenerate();
        }
Beispiel #27
0
        /// <summary>
        /// Create a <see cref="KafkaStream"/> instance with your own <see cref="IKafkaSupplier" />
        /// Please DO NOT FORGET to call Close to avoid resources leak !
        /// </summary>
        /// <param name="topology">the topology specifying the computational logic</param>
        /// <param name="configuration">configuration about this stream</param>
        /// <param name="kafkaSupplier">the Kafka clients supplier which provides underlying producer and consumer clients for the new <see cref="KafkaStream"/> instance</param>
        public KafkaStream(Topology topology, IStreamConfig configuration, IKafkaSupplier kafkaSupplier)
        {
            this.topology      = topology;
            this.kafkaSupplier = kafkaSupplier;

            // check if ApplicationId & BootstrapServers has been set
            if (string.IsNullOrEmpty(configuration.ApplicationId) || string.IsNullOrEmpty(configuration.BootstrapServers))
            {
                throw new StreamConfigException($"Stream configuration is not correct. Please set ApplicationId and BootstrapServers as minimal.");
            }

            var processID = Guid.NewGuid();

            clientId  = string.IsNullOrEmpty(configuration.ClientId) ? $"{configuration.ApplicationId.ToLower()}-{processID}" : configuration.ClientId;
            logPrefix = $"stream-application[{configuration.ApplicationId}] ";

            logger.Info($"{logPrefix} Start creation of the stream application with this configuration: {configuration}");

            // re-write the physical topology according to the config
            topology.Builder.RewriteTopology(configuration);

            // sanity check
            var processorTopology = topology.Builder.BuildTopology();

            int numStreamThreads = topology.Builder.HasNoNonGlobalTopology ? 0 : configuration.NumStreamThreads;

            threads = new IThread[numStreamThreads];
            var threadState = new Dictionary <long, Processors.ThreadState>();

            ProcessorTopology globalTaskTopology = topology.Builder.BuildGlobalStateTopology();
            bool hasGlobalTopology = globalTaskTopology != null;

            if (numStreamThreads == 0 && !hasGlobalTopology)
            {
                throw new TopologyException("Topology has no stream threads and no global threads, " +
                                            "must subscribe to at least one source topic or global table.");
            }

            GlobalThreadState globalThreadState = null;

            if (hasGlobalTopology)
            {
                string globalThreadId = $"{clientId}-GlobalStreamThread";
                GlobalStreamThreadFactory globalStreamThreadFactory = new GlobalStreamThreadFactory(globalTaskTopology,
                                                                                                    globalThreadId,
                                                                                                    kafkaSupplier.GetGlobalConsumer(configuration.ToGlobalConsumerConfig(globalThreadId)),
                                                                                                    configuration,
                                                                                                    kafkaSupplier.GetAdmin(configuration.ToAdminConfig(clientId)));
                globalStreamThread = globalStreamThreadFactory.GetGlobalStreamThread();
                globalThreadState  = globalStreamThread.State;
            }

            List <StreamThreadStateStoreProvider> stateStoreProviders = new List <StreamThreadStateStoreProvider>();

            for (int i = 0; i < numStreamThreads; ++i)
            {
                var threadId = $"{configuration.ApplicationId.ToLower()}-stream-thread-{i}";

                var adminClient = this.kafkaSupplier.GetAdmin(configuration.ToAdminConfig(StreamThread.GetSharedAdminClientId(clientId)));

                threads[i] = StreamThread.Create(
                    threadId,
                    clientId,
                    this.topology.Builder,
                    configuration,
                    this.kafkaSupplier,
                    adminClient,
                    i);

                threadState.Add(threads[i].Id, threads[i].State);

                stateStoreProviders.Add(new StreamThreadStateStoreProvider(threads[i], this.topology.Builder));
            }

            var manager = new StreamStateManager(this, threadState, globalThreadState);

            if (hasGlobalTopology)
            {
                globalStreamThread.StateChanged += manager.OnGlobalThreadStateChange;
            }
            foreach (var t in threads)
            {
                t.StateChanged += manager.OnChange;
            }

            var globalStateStoreProvider = new GlobalStateStoreProvider(topology.Builder.GlobalStateStores);

            queryableStoreProvider = new QueryableStoreProvider(stateStoreProviders, globalStateStoreProvider);

            StreamState = State.CREATED;
        }
Beispiel #28
0
        // Alternative algorithm
        // for each triangle
        //   find normal
        //      find centroid radius
        //        Tilt triangle towards centroid radius
        //        moving edges towards symmetry.
        //        generate new point for each tri vert
        // for each vert, calc average of all new verts, normalise and apply
        // Algorithm is nearly there, but on some triangles, there is a potential that converging on
        // centroid tilts through random moves away from centroidal radius, and they become thin / start overlapping.
        public float RelaxTriangles1(float multiplier)
        {
            NeedsUpdate = true;

            double totalSurfaceArea        = 4.0 * Math.PI;
            double idealFaceArea           = totalSurfaceArea / (indices.Length / 3);
            double idealEdgeLength         = Math.Sqrt(idealFaceArea * 4.0 / Math.Sqrt(3.0));
            double idealDistanceToCentroid = idealEdgeLength * Math.Sqrt(3) / 3.0 * 0.9;

            int numIndices = indices.Length;

            Vector3[] shiftPositions = new Vector3[mesh.vertices.Length];
            for (int i = 0; i < mesh.vertices.Length; ++i)
            {
                shiftPositions[i] = new Vector3(Vector3.Zero);
            }

            for (int i = 0; i < numIndices; i += 3)
            {
                if (1 == 1)//TooThin(i))
                {
                    Vector3 centroid = Topology.CalculateCentroid(i / 3);
                    centroid.Normalize();

                    // Compare each corner to the centroid
                    // if too far off some ideal length ( the centroid of an equilateral triangle ),
                    // pull vertex closer to centroid, (without buggering up the other triangles using
                    // this point.)
                    Vector3[] oldPositions = new Vector3[3]
                    {
                        new Vector3(MeshAttr.GetPosition(ref mesh.vertices[indices[i]])),
                        new Vector3(MeshAttr.GetPosition(ref mesh.vertices[indices[i + 1]])),
                        new Vector3(MeshAttr.GetPosition(ref mesh.vertices[indices[i + 2]])),
                    };
                    Vector3[] newPositions = new Vector3[3];
                    for (int j = 0; j < 3; ++j)
                    {
                        TVertex v1    = mesh.vertices[indices[i + j]];
                        Vector3 v1Pos = MeshAttr.GetPosition(ref v1);
                        Vector3 e1    = centroid - v1Pos;

                        if (e1.Length > idealDistanceToCentroid * 1.1)
                        {
                            // Move vertex closer to centroid
                            float factor   = 1.0f - (float)idealDistanceToCentroid / e1.Length;
                            float fraction = (multiplier * (1.0f - (float)idealDistanceToCentroid / e1.Length));
                            factor = factor * fraction;
                            v1Pos  = Vector3.Normalize(v1Pos + e1 * factor);
                        }
                        else if (e1.Length < idealDistanceToCentroid * 0.9)
                        {
                            // Move vertex away from the centroid
                            float factor   = 1 - e1.Length / (float)idealDistanceToCentroid;
                            float fraction = (multiplier * (e1.Length / (float)idealDistanceToCentroid));
                            factor = factor * fraction;
                            v1Pos  = Vector3.Normalize(v1Pos - e1 * factor);
                        }
                        newPositions[j] = v1Pos;
                    }

                    // If this makes the triangle less parallel to the sphere, don't do it.
                    Vector3 a      = newPositions[1] - newPositions[0];
                    Vector3 b      = newPositions[2] - newPositions[1];
                    Vector3 normal = Vector3.Cross(a, b);
                    normal.Normalize();
                    float  dot = Vector3.Dot(centroid, normal);
                    double phi = Math.Acos(dot);

                    a      = oldPositions[1] - oldPositions[0];
                    b      = oldPositions[2] - oldPositions[1];
                    normal = Vector3.Cross(a, b);
                    normal.Normalize();
                    dot = Vector3.Dot(centroid, normal);
                    double theta = Math.Acos(dot);
                    if (phi < dot)
                    {
                        for (int j = 0; j < 3; ++j)
                        {
                            //SetPosition(ref mesh.vertices[indices[i + j]], ref newPositions[j]);
                            shiftPositions[indices[i + j]] = newPositions[j];
                        }
                    }

                    // If any surrounding triangles would be less parallel to the sphere than
                    // this is more parallel, don't do it.
                }
            }

            TVertex[] vertices   = new TVertex[mesh.vertices.Length];
            float     totalShift = 0;

            for (int i = 0; i < mesh.vertices.Length; ++i)
            {
                Vector3 delta = shiftPositions[i] - MeshAttr.GetPosition(ref mesh.vertices[i]);
                MeshAttr.SetPosition(ref mesh.vertices[i], ref shiftPositions[i]);
                totalShift += delta.Length;
            }

            Topology.Regenerate();
            return(totalShift);
        }
Beispiel #29
0
 /// <summary>
 /// Create a new test diver instance.
 /// </summary>
 /// <param name="topology">Topology to be tested</param>
 /// <param name="config">Configuration for topology. One property will be modified : <see cref="IStreamConfig.NumStreamThreads"/> will set to 1</param>
 /// <param name="mode">Topology driver mode</param>
 public TopologyTestDriver(Topology topology, IStreamConfig config, Mode mode = Mode.SYNC_TASK)
     : this(topology.Builder, config, mode)
 {
 }
Beispiel #30
0
        public float RelaxTriangles(float multiplier)
        {
            NeedsUpdate = true;

            double totalSurfaceArea        = 4.0 * Math.PI;
            double idealFaceArea           = totalSurfaceArea / (indices.Length / 3);
            double idealEdgeLength         = Math.Sqrt(idealFaceArea * 4.0 / Math.Sqrt(3.0));
            double idealDistanceToCentroid = idealEdgeLength * Math.Sqrt(3) / 3.0 * 0.9;

            Vector3[] shiftPositions = new Vector3[mesh.vertices.Length];
            for (int i = 0; i < mesh.vertices.Length; ++i)
            {
                shiftPositions[i] = new Vector3(Vector3.Zero);
            }
            int numIndices = indices.Length;

            TVertex[] centroidVerts  = new TVertex[numIndices / 3];
            TVertex   centroidVertex = new TVertex();

            for (int i = 0; i < numIndices; i += 3)
            {
                Vector3 centroid = Topology.CalculateCentroid(i / 3);
                centroid.Normalize();
                MeshAttr.SetPosition(ref centroidVertex, ref centroid);

                Vector3[] oldPositions = new Vector3[3]
                {
                    new Vector3(MeshAttr.GetPosition(ref mesh.vertices[indices[i]])),
                    new Vector3(MeshAttr.GetPosition(ref mesh.vertices[indices[i + 1]])),
                    new Vector3(MeshAttr.GetPosition(ref mesh.vertices[indices[i + 2]])),
                };

                for (int j = 0; j < 3; ++j)
                {
                    Vector3 midLine   = centroid - oldPositions[j];
                    float   midLength = midLine.Length;
                    midLine *= (float)(multiplier * (midLength - idealDistanceToCentroid) / midLength);
                    shiftPositions[indices[i + j]] += midLine;
                }
            }

            var   origin = Vector3.Zero;
            Plane p      = new Plane(Vector3.UnitY, Vector3.Zero);

            for (int i = 0; i < mesh.vertices.Length; ++i)
            {
                Vector3 vertexPosition = MeshAttr.GetPosition(ref mesh.vertices[i]);
                p.Redefine(vertexPosition, origin);
                shiftPositions[i] = vertexPosition + p.ProjectPoint(shiftPositions[i]);
                shiftPositions[i].Normalize();
            }

            // Stop poylgons rotating about their centroid.
            // Doesn't stop triangles flipping.
            float[] rotationSuppressions = new float[mesh.vertices.Length];
            rotationSuppressions.Initialize();

            Topology.GenerateEdges();
            float minEdgeLength = (float)idealEdgeLength * 0.8f;
            float maxEdgeLength = (float)idealEdgeLength * 1.2f;

            foreach (var iter in Topology.Edges)
            {
                Int64   key     = iter.Key;
                int     index1  = (int)(key & 0xffffffff);
                int     index2  = (int)((key >> 32) & 0xffffffff);
                Vector3 oldPos1 = MeshAttr.GetPosition(ref mesh.vertices[index1]);
                Vector3 oldPos2 = MeshAttr.GetPosition(ref mesh.vertices[index2]);
                Vector3 newPos1 = shiftPositions[index1];
                Vector3 newPos2 = shiftPositions[index2];
                Vector3 oldEdge = oldPos2 - oldPos1;
                Vector3 newEdge = newPos2 - newPos1;
                if (newEdge.Length < minEdgeLength)
                {
                    // Move shift positions back out to ensure that the edge is never too small.
                    Vector3 midPt = newPos1 + 0.5f * newEdge;
                    newEdge.Normalize();
                    newEdge *= minEdgeLength * 0.5f;
                    shiftPositions[index1] = midPt - newEdge;
                    shiftPositions[index2] = midPt + newEdge;
                    newEdge = shiftPositions[index2] - shiftPositions[index1];
                }
                if (newEdge.Length > maxEdgeLength)
                {
                    // Move shift positions back in to ensure that the edge is never too large.
                    Vector3 midPt = newPos1 + 0.5f * newEdge;
                    newEdge.Normalize();
                    newEdge *= (maxEdgeLength * 0.5f);
                    shiftPositions[index1] = midPt - newEdge;
                    shiftPositions[index2] = midPt + newEdge;
                    newEdge = shiftPositions[index2] - shiftPositions[index1];
                }
                oldEdge.Normalize();
                newEdge.Normalize();
                float suppression = (1.0f - Vector3.Dot(oldEdge, newEdge)) * 0.5f;
                rotationSuppressions[index1] = Math.Max(suppression, rotationSuppressions[index1]);
                rotationSuppressions[index2] = Math.Max(suppression, rotationSuppressions[index2]);
            }

            for (int i = 0; i < mesh.vertices.Length; ++i)
            {
                Vector3 pos   = MeshAttr.GetPosition(ref mesh.vertices[i]);
                Vector3 delta = pos;
                pos = Math2.Lerp(pos, shiftPositions[i], (float)(1.0f - Math.Sqrt(rotationSuppressions[i])));
                pos.Normalize();
                shiftPositions[i] = pos;
            }

            float totalShift = 0;

            for (int i = 0; i < mesh.vertices.Length; ++i)
            {
                Vector3 delta = MeshAttr.GetPosition(ref mesh.vertices[i]);
                MeshAttr.SetPosition(ref mesh.vertices[i], ref shiftPositions[i]);
                delta      -= shiftPositions[i];
                totalShift += delta.Length;
            }

            Topology.Regenerate();

            return(totalShift);
        }
Beispiel #31
0
        public void FindBestLearningRate()
        {
            var outputs     = new List <double>();
            var inputs      = new List <double[]>();
            var inputsCount = 0;

            using (var sr = new StreamReader("datasets/heart.csv"))
            {
                var header = sr.ReadLine();                 // Заголовочная строка
                for (; !sr.EndOfStream;)
                {
                    var row    = sr.ReadLine();
                    var values = row.Split(',').Select(v => Convert.ToDouble(v.Replace('.', ','))).ToList();
                    var output = values.Last();                     // Ожидаемое значение

                    /* !!!!!
                     * В этом датасете - 1 здоров, 0 - болен
                     * !!!!!
                     */
                    var input = values.Take(values.Count - 1).ToArray(); // Массив входных параметров (без ожидаемого значения)
                    inputsCount = input.Length;                          // Считаем количество входных параметров В ОДНОЙ СТРОКЕ

                    outputs.Add(output);
                    inputs.Add(input);
                }
            }

            // Перемешиваем списки
            LinkedMix(ref inputs, ref outputs);
            LinkedMix(ref inputs, ref outputs);
            LinkedMix(ref inputs, ref outputs);
            LinkedMix(ref inputs, ref outputs);
            LinkedMix(ref inputs, ref outputs);

            // Перегоняю в двумерный массив
            var validInputs = new double[inputs.Count, inputsCount];

            for (int i = 0; i < validInputs.GetLength(0); i++)
            {
                for (int j = 0; j < validInputs.GetLength(1); j++)
                {
                    validInputs[i, j] = inputs[i][j];
                }
            }
            // Нормализуем данные
            var normalizedInputs = NeuralNetwork.Scalling(validInputs);

            //                         differ  learnR hidden epoch
            var    datas         = new List <Tuple <double, double, int[], int> >();
            double minDifference = 100;
            double bestLearningRate;

            int[]        bestHidden;
            int          bestEpoch;
            List <int[]> hiddenLayers = new List <int[]>
            {
                new int[] { 26 },
                new int[] { 26, 13 },
                new int[] { 26, 13, 6 },
                new int[] { 26, 13, 6, 3 },
                new int[] { 13 },
                new int[] { 13, 6 },
                new int[] { 13, 6, 3 },
                new int[] { 8 },
                new int[] { 8, 4 },
                new int[] { 8, 4, 2 },
                new int[] { 6 },
                new int[] { 6, 3 },
                new int[] { 6, 4, 2 },
                new int[] { 4 },
                new int[] { 4, 2 },
                new int[] { 2 },
            };

            for (int i = 0; i < hiddenLayers.Count; i++)
            {
                for (double learningRate = 0.002; learningRate == 0.002; learningRate++)
                {
                    for (int epoch = 1400; epoch == 1400; epoch++)
                    {
                        Topology topology = new Topology(
                            inputCount: inputsCount,
                            outputCount: 1,
                            learningRate: learningRate,
                            hiddenLayersCount: hiddenLayers[i]
                            );
                        NeuralNetwork neuralNetwork = new NeuralNetwork(topology);
                        double        difference    = neuralNetwork.Learn(outputs.ToArray(), normalizedInputs, epoch);

                        if (difference < minDifference)
                        {
                            minDifference    = difference;
                            bestLearningRate = learningRate;
                            bestHidden       = hiddenLayers[i];
                            bestEpoch        = epoch;
                        }
                        datas.Add(new Tuple <double, double, int[], int>(difference, learningRate, hiddenLayers[i], epoch));
                    }
                }
            }
            int a = 0;
        }
Beispiel #32
0
 public static bool IsMaximumInclusive(this Topology topology)
 {
     return(topology is Topology.MinimumExclusiveMaximumInclusive or Topology.Inclusive);
 }
Beispiel #33
0
        /// <summary>
        /// Cuts up a divider that covers this line (or a portion of this line)
        /// </summary>
        /// <param name="arePolygonsBuilt">Has polygon topology been built (false if the split
        /// is being done as part of the initial load).</param>
        /// <param name="div">The divider covering the line (or a portion of this line)</param>
        /// <param name="xres">The places where intersections have been detected on
        /// the divider</param>
        /// <param name="retrims">Lines that need to be re-trimmed (the line associated
        /// with the divider will be appended if an intersection is made on an invisible
        /// portion of the divider). Not currently used.</param>
        void Cut(bool arePolygonsBuilt, IDivider div, IntersectionResult xres, List<LineFeature> retrims)
        {
            Debug.Assert(div.Line == this);

            // Should never need to cut anything that represents an overlap (they're
            // supposed to be treated as non-topological)
            Debug.Assert(!div.IsOverlap);

            // Return if nothing to do
            List<IntersectionData> data = xres.Intersections;
            if (data == null || data.Count == 0)
                return;

            // Ensure that any polygons known to this boundary have been
            // marked for deletion (need to do this in case the intersects
            // we have are only at the line end points, in which case we
            // wouldn't actually change anything).
            if (arePolygonsBuilt)
                Topology.MarkPolygons(div);

            // We'll need the map for creating intersection points
            CadastralMapModel map = CadastralMapModel.Current;

            // Create list of resultant sections
            List<IDivider> result = new List<IDivider>();
            ITerminal from, to;
            from = to = div.From;

            for (int i = 0; i < data.Count; i++, from = to)
            {
                // Get the intersection data.
                IntersectionData x = data[i];

                if (x.IsGraze)
                {
                    // There are 4 sorts of graze to deal with:
                    // 1. The graze covers the complete line.
                    // 2. The graze is at the start of the line.
                    // 3. The graze is along some interior portion of the line.
                    // 4. The graze is at the end of the line.

                    // If it's a total graze, there should only be ONE intersection.
                    if (x.IsTotalGraze)
                    {
                        Debug.Assert(data.Count == 1);
                        if (data.Count != 1)
                            throw new Exception("LineFeature.Cut - Multiple overlaps detected");

                        // Mark all polygons incident on the terminals.
                        Topology.MarkPolygons(div.From);
                        Topology.MarkPolygons(div.To);

                        // Define overlap for the entire divider
                        if (div is LineTopology)
                            result.Add(new LineOverlap(div.Line));
                        else
                            result.Add(new SectionOverlap(this, div.From, div.To));

                        to = div.To;
                    }
                    else if (x.IsStartGraze)
                    {
                        Debug.Assert(i == 0);
                        Debug.Assert(from == div.From);

                        // Mark all polygons incident at the start terminal
                        if (arePolygonsBuilt)
                            Topology.MarkPolygons(div.From);

                        // Create an overlap at the start of this divider
                        to = map.GetTerminal(x.P2);
                        if (from != to)
                            result.Add(new SectionOverlap(this, from, to));
                    }
                    else if (x.IsInteriorGraze)
                    {
                        // Add a section from the current tail to the start of the graze
                        // 05-APR-2003 (somehow got a simple x-sect followed by a graze, so ensure we don't add a null section)
                        to = map.GetTerminal(x.P1);
                        if (from != to)
                            result.Add(new SectionDivider(this, from, to));

                        // Add the overlap
                        from = to;
                        to = map.GetTerminal(x.P2);
                        if (from != to)
                            result.Add(new SectionOverlap(this, from, to));
                    }
                    else if (x.IsEndGraze)
                    {
                        // Mark all polygons incident on the end terminal
                        if (arePolygonsBuilt)
                            Topology.MarkPolygons(div.To);

                        // Add a topological section up to the start of the graze
                        to = map.GetTerminal(x.P1);
                        if (from != to)
                            result.Add(new SectionDivider(this, from, to));

                        // Add overlap all the way to the end of this divider
                        from = to;
                        to = div.To;
                        if (from != to)
                            result.Add(new SectionOverlap(this, from, to));

                        // That should be the LAST cut.
                        Debug.Assert((i + 1) == data.Count);
                    }
                    else
                    {
                        throw new Exception("LineFeature.Cut - Unexpected graze");
                    }
                }
                else if (!x.IsEnd)
                {
                    // If the intersection is not at either end of the
                    // divider, make a split (both portions topological).

                    to = map.GetTerminal(x.P1);
                    if (from != to)
                        result.Add(new SectionDivider(this, from, to));
                }
            }

            // Add the last section if we're not already at the end (we'll be at the end if
            // an overlap ran to the end)
            from = to;
            to = div.To;
            if (from != to)
            {
                // Just return if the terminals correspond to the two ends of this line. This
                // is intended to cover the case where we have a single interesection at the
                // start or end of the line.
                if (from.IsCoincident(StartPoint) && to.IsCoincident(EndPoint))
                {
                    Debug.Assert(result.Count==0);
                    return;
                }

                result.Add(new SectionDivider(this, from, to));
            }

            // Refer the associated line to the new sections
            if (result.Count > 0)
            {
                if (m_Topology is LineTopology)
                    m_Topology = new SectionTopologyList(this, result);
                else
                {
                    SectionTopologyList container = (SectionTopologyList)m_Topology;
                    container.ReplaceDivider(div, result);
                }
            }
        }
Beispiel #34
0
 /// <summary>
 /// Determines if two adjacent topologies would allow their endpoints to be
 /// equal if the endpoints had the same value.
 /// </summary>
 /// <param name="left">The topology of the interval that is lower than the other.</param>
 /// <param name="right"The topology of the interval that is greater than the other.></param>
 /// <returns></returns>
 public static bool IsCompatibleWith(this Topology left, Topology right)
 {
     return(left.IsMaximumInclusive() || right.IsMinimumInclusive());
 }
Beispiel #35
0
        /// <summary>
        /// Initializes a new instance of the <see cref="LineFeature"/> class, and records it
        /// as part of the map model.
        /// </summary>
        /// <param name="iid">The internal ID for the feature.</param>
        /// <param name="fid">The (optional) user-perceived ID for the feature. If not null,
        /// this will be modified by cross-referencing it to the newly created feature.</param>
        /// <param name="ent">The entity type for the feature (not null)</param>
        /// <param name="creator">The operation creating the feature (not null). Expected to
        /// refer to an editing session that is consistent with the session ID that is part
        /// of the feature's internal ID.</param>
        /// <param name="start">The point at the start of the line (not null)</param>
        /// <param name="end">The point at the end of the line (not null)</param>
        /// <param name="g">The geometry for the line (could be null, although this is only really
        /// expected during deserialization)</param>
        /// <param name="isTopological">Does the line form part of a polygon boundary?</param>
        /// <exception cref="ArgumentNullException">If either <paramref name="ent"/> or
        /// <paramref name="creator"/> or <paramref name="start"/> or <paramref name="end"/> is null.
        /// </exception>
        protected LineFeature(IFeature f, PointFeature start, PointFeature end, LineGeometry g, bool isTopological)
            : base(f)
        {
            if (start == null || end == null)
                throw new ArgumentNullException();

            m_From = start;
            m_To = end;
            m_Geom = g;
            m_Topology = null;

            // Don't cross-reference if we're dealing with a temporary feature
            if (!f.InternalId.IsEmpty)
                AddReferences();

            if (isTopological)
                SetTopology(true);
        }
Beispiel #36
0
        /// <summary>
        /// Changes a mesh to another object with different topology. For instance, from a triangle mesh to a wireframe (lines).
        /// </summary>
        public static Mesh <V> ConvertTo <V>(this Mesh <V> mesh, Topology topology) where V : struct, IVertex <V>
        {
            switch (topology)
            {
            case Topology.Triangles:
                switch (mesh.Topology)
                {
                case Topology.Triangles:
                    return(mesh.Clone());        // No necessary change

                case Topology.Lines:
                    // This problem is NP.
                    // Try to implement a greedy, that means, recognize the small triangle and so on...
                    throw new NotImplementedException("Missing implementing line-to-triangle conversion.");

                case Topology.Points:
                    throw new NotImplementedException("Missing implementing point-to-triangle conversion.");
                }
                break;

            case Topology.Lines:
                switch (mesh.Topology)
                {
                case Topology.Points:
                    // Get the wireframe from surface reconstruction
                    return(mesh.ConvertTo(Topology.Triangles).ConvertTo(Topology.Lines));

                case Topology.Lines:
                    return(mesh.Clone());        // nothing to do

                case Topology.Triangles:
                {
                    // This is repeating edges for adjacent triangles.... use a hash table to prevent for double linking vertices.
                    V[]   newVertices = mesh.Vertices.Clone() as V[];
                    int[] newIndices  = new int[mesh.Indices.Length * 2];
                    int   index       = 0;
                    for (int i = 0; i < mesh.Indices.Length / 3; i++)
                    {
                        newIndices[index++] = mesh.Indices[i * 3 + 0];
                        newIndices[index++] = mesh.Indices[i * 3 + 1];

                        newIndices[index++] = mesh.Indices[i * 3 + 1];
                        newIndices[index++] = mesh.Indices[i * 3 + 2];

                        newIndices[index++] = mesh.Indices[i * 3 + 2];
                        newIndices[index++] = mesh.Indices[i * 3 + 0];
                    }
                    return(new Mesh <V>(newVertices, newIndices, Topology.Lines));
                }
                }
                break;

            case Topology.Points:
            {
                V[]   newVertices = mesh.Vertices.Clone() as V[];
                int[] indices     = new int[newVertices.Length];
                for (int i = 0; i < indices.Length; i++)
                {
                    indices[i] = i;
                }
                return(new Mesh <V>(newVertices, indices, Topology.Points));
            }
            }

            throw new ArgumentException("Wrong topology.");
        }
Beispiel #37
0
 internal void ResetTopology()
 {
     if (m_Topology != null)
     {
         RemoveTopology();
         m_Topology = Topology.CreateTopology(this);
         IsMoved = true;
     }
 }
Beispiel #38
0
 private static CompositeKey<int, Topology> KeyFor(int epsgId, Topology topology)
 {
     return new CompositeKey<int, Topology>(epsgId, topology);
 }
 [DllImport("FbxExporterCore")] static extern void fbxeAddMeshSubmesh(Context ctx, Node node,
                                                                      Topology topology, int num_indices, int[] indices, int material);
    // TODO: Replace hardcoded 1000s with a scale variable.
    public void GeneratePlanetTopology()
    {
        List<Corner> corners = new List<Corner>(this.faces.Count);
        List<Border> borders = new List<Border>(this.edges.Count);
        List<Tile> tiles = new List<Tile>(this.nodes.Count);
        int i;
        for(i = 0; i < this.faces.Count; ++i)
        {
            var face = this.faces[i];
            corners.Add(new Corner(i, face.centroid /** 1000*/, face.e.Count, face.e.Count, face.n.Count));
        }

        for(i = 0; i < this.edges.Count; ++i)
        {
            var edge = this.edges[i];
            borders.Add(new Border(i, 2, 4, 2)); //edge.f.Count, this.faces[edge.f[0]].e.Count + this.faces[edge.f[1]].e.Count - 2, edge.n.Count
        }
        
        for(i = 0; i < this.nodes.Count; ++i)
        {
            var node = this.nodes[i];
            tiles.Add(new Tile(i, node.p /** 1000*/, node.f.Count, node.e.Count, node.e.Count));
        }

        for(i = 0; i < corners.Count; ++i)
        {
            var corner = corners[i];
            var face = this.faces[i];
            for(var j = 0; j < face.e.Count; ++j)
            {
                corner.borders[j] = (borders[face.e[j]]);
            }
            for(var j = 0; j < face.n.Count; ++j)
            {
                corner.tiles[j] = (tiles[face.n[j]]);
            }
        }

        for(i = 0; i < borders.Count; ++i)
        {
			var border = borders[i];
			var edge = this.edges[i];
			var averageCorner = new Vector3(0, 0, 0);
			var n = 0;
			for (var j = 0; j < edge.f.Count; ++j)
			{
				var corner = corners[edge.f[j]];
				averageCorner += corner.position;
				border.corners[j] = corner;
				for (var k = 0; k < corner.borders.Length; ++k)
				{
					if (corner.borders[k] != border) border.borders[n++] = corner.borders[k];
				}
			}
			border.midpoint = averageCorner / border.corners.Length;
			for (var j = 0; j < edge.n.Length; ++j)
			{
				border.tiles[j] = tiles[edge.n[j]];
			}
        }
        
		for (i = 0; i < corners.Count; ++i)
		{
			var corner = corners[i];
			for (var j = 0; j < corner.borders.Length; ++j)
			{
				corner.corners[j] = corner.borders[j].OppositeCorner(corner);
			}
		}

        for (i = 0; i < tiles.Count; ++i)
		{
			var tile = tiles[i];
			var node = this.nodes[i];
			for (var j = 0; j < node.f.Count; ++j)
			{
				tile.corners[j] = corners[node.f[j]];
			}
			for (var j = 0; j < node.e.Count; ++j)
			{
				var border = borders[node.e[j]];
				if (border.tiles[0] == tile)
				{
					for (var k = 0; k < tile.corners.Length; ++k)
					{
						var corner0 = tile.corners[k];
						var corner1 = tile.corners[(k + 1) % tile.corners.Length];
						if (border.corners[1] == corner0 && border.corners[0] == corner1)
						{
							border.corners[0] = corner0;
							border.corners[1] = corner1;
						}
						else if (border.corners[0] != corner0 || border.corners[1] != corner1)
						{
							continue;
						}
						tile.borders[k] = border;
						tile.tiles[k] = border.OppositeTile(tile);
						break;
					}
				}
				else
				{
					for (var k = 0; k < tile.corners.Length; ++k)
					{
						var corner0 = tile.corners[k];
						var corner1 = tile.corners[(k + 1) % tile.corners.Length];
						if (border.corners[0] == corner0 && border.corners[1] == corner1)
						{
							border.corners[1] = corner0;
							border.corners[0] = corner1;
						}
						else if (border.corners[1] != corner0 || border.corners[0] != corner1)
						{
							continue;
						}
						tile.borders[k] = border;
						tile.tiles[k] = border.OppositeTile(tile);
						break;
					}
				}
			}

			tile.averagePosition = new Vector3(0, 0, 0);
			for (var j = 0; j < tile.corners.Length; ++j)
			{
				tile.averagePosition += tile.corners[j].position;
			}
			tile.averagePosition /= tile.corners.Length;
			
			var maxDistanceToCorner = 0f;
			for (var j = 0; j < tile.corners.Length; ++j)
			{
				maxDistanceToCorner = Math.Max(maxDistanceToCorner, Vector3.Distance(tile.corners[j].position, tile.averagePosition));
			}
			
			var area = 0f;
			for (var j = 0; j < tile.borders.Length; ++j)
			{
				area += Utils.CalculateTriangleArea(tile.position, tile.borders[j].corners[0].position, tile.borders[j].corners[1].position);
			}
			tile.area = area;
			
			tile.normal = tile.position.normalized;
            tile.radius = maxDistanceToCorner;
		}

        for (i = 0; i < corners.Count; ++i)
		{
			var corner = corners[i];
			corner.area = 0;
			for (var j = 0; j < corner.tiles.Length; ++j)
			{
				corner.area += corner.tiles[j].area / corner.tiles[j].corners.Length;
			}
		}

        this.topology = new Topology(this.planet, corners, borders, tiles);
    }
Beispiel #41
0
        /// <summary>
        /// <para>Draws the currently bound source objects associated with this device.</para>
        /// <para>A valid VertexDeclaration, VertexBuffer, IndexBuffer and Optional Texture 
        /// must be bound before calling this method.</para>
        /// </summary>
        /// <param name="topology"></param>
        public void Draw     (Topology topology)
        {
            this.EnableStates();

            this.EnableTextures();
            
            this.EnableVertexDeclaration();

            if (this.indexBuffer != null)
            {
                Gl.glBindBuffer(Gl.GL_ELEMENT_ARRAY_BUFFER, this.indexBuffer.Handle);

                Gl.glDrawElements((int)topology, this.indexBuffer.Count, Gl.GL_UNSIGNED_INT, (IntPtr)0);
            }

            this.DisableVertexDeclaration();
            
            this.DisableTextures();
        }
Beispiel #42
0
        void BuildTopology(MediaSource source, Topology topology)
        {
            using (var presentationDescriptor = source.CreatePresentationDescriptor())
                foreach (var stream in presentationDescriptor.Streams.Where(s => s.IsSelected))
                    using (var sourceNode = TopologyNode.Create(MFTopologyType.SourcestreamNode))
                    {
                        if (!stream.MediaType.IsAudio && !stream.MediaType.IsVideo)
                            throw new Exception("Unknown stream format!");

                        sourceNode.TopNodeSource = source;
                        sourceNode.TopNodePresentationDescriptor = presentationDescriptor;
                        sourceNode.TopNodeStreamDescriptor = stream;

                        using (var outputNode = TopologyNode.Create(MFTopologyType.OutputNode))
                        {
                            outputNode.Object = stream.MediaType.IsAudio ? Activate.CreateAudioRenderer() : Activate.CreateVideoRenderer(hwndVideo);

                            topology.Add(sourceNode);
                            topology.Add(outputNode);
                            sourceNode.ConnectOutput(0, outputNode, 0);
                        }
                    }
        }
            public SurfaceSource(IEnumerable<Brep> Surfaces, List<String> CodeList, int el_m, int SrcID, Phase_Regime ph)
                :base(new double[8]{0, 0, 0, 0, 0, 0, 0, 0}, new Point3d(0,0,0), ph, SrcID)
            {
                samplespermeter = el_m;
                
                Srfs = Surfaces.ToList<Brep>();
                Samples = new Point3d[Srfs.Count][];
                
                MeshingParameters mp = new MeshingParameters();
                mp.MaximumEdgeLength = 1.0 / (double)samplespermeter;
                mp.MinimumEdgeLength = 1.0 / (double)samplespermeter;

                Sub_A = new double[Srfs.Count];
                SubDomains = new double[Srfs.Count][];
                T = new Topology[Srfs.Count];

                //for(int i = 0; i < Curves.Count; i++)
                System.Threading.Tasks.Parallel.For(0, Srfs.Count, ips =>
                {
                    int i = (int)ips;
                    
                    
                    //Divide each curve up in ~equal length segments.
                    Mesh[] m = Mesh.CreateFromBrep(Srfs[i],mp);
                    BoundingBox Box = m[0].GetBoundingBox(true);
                    for (int j = 1; j < m.Length; j++) Box.Union(m[j].GetBoundingBox(true));
                    T[i] = new Topology(Utilities.PachTools.RPttoHPt(Box.Min), Utilities.PachTools.RPttoHPt(Box.Max));
                    
                    List<Point3d> pts = new List<Point3d>();
                    SubDomains[i] = new double[m[i].Faces.Count + 1];
                    for (int j = 0; j < m[i].Faces.Count; j++)
                    {
                        double u,v;
                        ComponentIndex ci;
                        Point3d no;
                        Vector3d V;
                        Point3d A = m[i].Vertices[m[i].Faces[j].A];
                        Srfs[i].ClosestPoint(A, out no, out ci, out u, out v, 1, out V);
                        A += V;
                        Point3d B = m[i].Vertices[m[i].Faces[j].B];
                        Srfs[i].ClosestPoint(B, out no, out ci, out u, out v, 1, out V);
                        B += V;
                        Point3d C = m[i].Vertices[m[i].Faces[j].C];
                        Srfs[i].ClosestPoint(C, out no, out ci, out u, out v, 1, out V);
                        C += V;
                        Point3d D = m[i].Vertices[m[i].Faces[j].D];
                        Srfs[i].ClosestPoint(D, out no, out ci, out u, out v, 1, out V);
                        D += V;
                        
                        if (m[i].Faces[j].IsQuad)
                        {
                            Hare.Geometry.Point[] poly = new Hare.Geometry.Point[4];
                            poly[0] = new Hare.Geometry.Point(A.X, A.Y, A.Z);
                            poly[1] = new Hare.Geometry.Point(B.X, B.Y, B.Z);
                            poly[2] = new Hare.Geometry.Point(C.X, C.Y, C.Z);
                            poly[3] = new Hare.Geometry.Point(D.X, D.Y, D.Z);
                            T[i].Add_Polygon(poly);
                        }
                        else
                        {
                            Hare.Geometry.Point[] poly = new Hare.Geometry.Point[3];
                            poly[0] = new Hare.Geometry.Point(A.X, A.Y, A.Z);
                            poly[1] = new Hare.Geometry.Point(B.X, B.Y, B.Z);
                            poly[2] = new Hare.Geometry.Point(C.X, C.Y, C.Z);
                            T[i].Add_Polygon(poly);
                        }

                        pts.Add(m[i].Faces[j].IsQuad ? new Point3d(A.X + B.X + C.X + D.X, A.Y + B.Y + C.Y + D.Y, A.Z + B.Z + C.Z + D.Z) / 4 : new Point3d(A.X + B.X + C.X, A.Y + B.Y + C.Y, A.Z + B.Z + C.Z) / 3);

                        SubDomains[i][j + 1] = Sub_A[i] += T[i].Polygon_Area(j);
                    }
                    Samples[i] = pts.ToArray();
                });

                Domains = new double[Srfs.Count+1];
                DomainLevel = new double[Srfs.Count][];
                DomainPower = new double[Srfs.Count][];
                Total_A = 0;
                
                for (int i = 0; i < Srfs.Count; i++)
                {
                    for (int j = 0; j < SubDomains[i].Length; j++) SubDomains[i][j] /= Sub_A[i];
                    double A = Srfs[i].GetArea();
                    Domains[i + 1] = Total_A += A;
                    DomainLevel[i] = Utilities.PachTools.DecodeSourcePower(CodeList[i]);
                    DomainPower[i] = new double[8];
                    double PowerMod = A;
                    for (int oct = 0; oct < 8; oct++) DomainPower[i][oct] = 1E-12 * Math.Pow(10, .1 * DomainLevel[i][oct]) / PowerMod;
                }

                for (int i = 0; i < Domains.Length; i++)
                {
                    Domains[i] /= Total_A;
                }
            }
        /// <summary>
        /// Load a new music into the media session. That is create a new session and a new topology and set the topology of the session.
        /// </summary>
        /// <param name="music"></param>
        private void LoadNewMusic(SoundMusic music)
        {
            if (currentMusic != null || mediaSession != null)
                throw new AudioSystemInternalException("State of the audio engine invalid at the entry of LoadNewMusic.");

            music.Stream.Position = 0;
            mediaInputByteStream = new ByteStream(music.Stream);
            topology = CreateTopology(mediaInputByteStream, out mediaSource);
            MediaFactory.CreateMediaSession(null, out mediaSession);
            mediaSessionCallback = new MediaSessionCallback(mediaSession, OnMediaSessionEvent);
            mediaSession.SetTopology(SessionSetTopologyFlags.None, topology);

            currentMusic = music;
        }
Beispiel #45
0
        public static global::Topologic.Face ToTopologic(this BrepFace brepFace)
        {
            global::Rhino.Geometry.Surface ghSurface = brepFace?.UnderlyingSurface();
            if (ghSurface == null)
            {
                return(null);
            }

            global::Topologic.Face untrimmedFace = ghSurface.ToTopologic();

            BrepLoop     ghOuterLoop = brepFace.OuterLoop;
            Wire         outerWire   = null;
            BrepLoopList ghLoops     = brepFace.Loops;
            List <Wire>  innerWires  = new List <Wire>();

            foreach (BrepLoop ghLoop in ghLoops)
            {
                BrepTrimList ghTrims       = ghLoop.Trims;
                List <Edge>  trimmingEdges = new List <Edge>();
                foreach (BrepTrim ghTrim in ghTrims)
                {
                    BrepEdge ghEdge = ghTrim.Edge;
                    if (ghEdge == null)
                    {
                        continue;
                        //throw new Exception("An invalid Rhino edge is encountered.");
                    }

                    Topology topology = ghEdge.DuplicateCurve().ToTopologic();
                    if (topology == null)
                    {
                        continue;
                    }

                    // Edge or Wire?
                    Edge trimmingEdge = topology as Edge;
                    if (trimmingEdge != null)
                    {
                        trimmingEdges.Add(trimmingEdge);
                    }

                    Wire partialTrimmingWire = topology as Wire;
                    if (partialTrimmingWire != null)
                    {
                        IList <Edge> partialTrimmingEdges = partialTrimmingWire.Edges;
                        trimmingEdges.AddRange(partialTrimmingEdges);
                    }
                }

                Wire trimmingWire = Wire.ByEdges(trimmingEdges);
                if (ghLoop == ghOuterLoop)
                {
                    outerWire = trimmingWire;
                }
                else
                {
                    innerWires.Add(trimmingWire);
                }
            }

            global::Topologic.Face outerTrimmedFace = global::Topologic.Utilities.FaceUtility.TrimByWire(untrimmedFace, outerWire, true);
            global::Topologic.Face finalFace        = outerTrimmedFace.AddInternalBoundaries(innerWires);

            return(finalFace);
        }
Beispiel #46
0
 /// <summary>
 /// Create a <see cref="KafkaStream"/> instance.
 /// Please DO NOT FORGET to call Close to avoid resources leak !
 /// </summary>
 /// <param name="topology">the topology specifying the computational logic</param>
 /// <param name="configuration">configuration about this stream</param>
 public KafkaStream(Topology topology, IStreamConfig configuration)
     : this(topology, configuration, new DefaultKafkaClientSupplier(new KafkaLoggerAdapter(configuration)))
 {
 }
Beispiel #47
0
 internal bool TopologyIs(Topology expected)
 {
     return (this.topology == expected);
 }
Beispiel #48
0
 /// <summary>
 ///   For tests only. Identifies whether the coordinate system is of the designated topology.
 /// </summary>
 /// <param name = "expected">The expected topology.</param>
 /// <returns>True if this coordinate system is of the expected topology.</returns>
 internal bool TopologyIs(Topology expected)
 {
     return(this.topology == expected);
 }
Beispiel #49
0
        public Shader(Device device)
        {
            this.device            = device;
            this.texturecount      = 0;
            this.programHandle     = Gl.glCreateProgram();
            this.vertexHandle      = 0;
            this.fragmentHandle    = 0;
            this.geometryHandle    = 0;
            
            this.vertexSource      = string.Empty;
            this.fragmentSource    = string.Empty;
            this.geometrySource    = string.Empty;

            this.inputTopology     = Topology.Triangles;
            this.outputTopology    = Topology.Triangles;
            this.outputVertexCount = 3;
        }
Beispiel #50
0
 /// <summary>
 ///   Gets the key for a coordinate system
 /// </summary>
 /// <param name = "epsgId">ID</param>
 /// <param name = "topology">topology</param>
 /// <returns>The key to use with the references dict.</returns>
 private static CompositeKey <int, Topology> KeyFor(int epsgId, Topology topology)
 {
     return(new CompositeKey <int, Topology>(epsgId, topology));
 }
Beispiel #51
0
 public STM(int id, Topology.Node source, Topology.Node target, string sourcePort, string targetPort, int sourceVpi, int targetVpi, int capacity, string name)
     : base(source, target, sourcePort, targetPort, capacity, name)
 {
     this.Id = id;
     this.SourceSlot = sourceVpi;
     this.TargetSlot = targetVpi;
     this.Path = new List<LinkConnection>();
 }
Beispiel #52
0
 internal CoordinateSystem(int epsgId, string name, Topology topology)
 {
     this.topology = topology;
     this.EpsgId   = epsgId;
     this.Name     = name;
 }
Beispiel #53
0
 /// <summary>
 /// Initializes a new instance of a Datum object
 /// </summary>
 /// <param name="type">Datum type</param>
 /// <param name="name">Name</param>
 /// <param name="authority">Authority name</param>
 /// <param name="code">Authority-specific identification code.</param>
 /// <param name="alias">Alias</param>
 /// <param name="abbreviation">Abbreviation</param>
 /// <param name="remarks">Provider-supplied remarks</param>
 internal Datum(Topology.CoordinateSystems.DatumType type, string name, string authority, long code, string alias, string remarks, string abbreviation)
     : base(name, authority, code, alias, abbreviation, remarks)
 {
     this._DatumType = this.DatumType;
 }
Beispiel #54
0
        /// <summary>
        /// Constructs a TilePropagator.
        /// </summary>
        /// <param name="tileModel">The model to guide the generation.</param>
        /// <param name="topology">The dimensions of the output to generate</param>
        /// <param name="backtrack">If true, store additional information to allow rolling back choices that lead to a contradiction.</param>
        /// <param name="constraints">Extra constraints to control the generation process.</param>
        /// <param name="random">Source of randomness</param>
        public TilePropagator(TileModel tileModel, Topology topology, bool backtrack = false,
                              ITileConstraint[] constraints = null,
                              Random random = null)
        {
            this.tileModel = tileModel;
            this.topology  = topology;

            var patternTopology = topology;

            if (!(topology.PeriodicX && topology.PeriodicY && topology.PeriodicZ) && tileModel is OverlappingModel overlapping)
            {
                // Shrink the topology as patterns can cover multiple tiles.
                patternTopology = topology.WithSize(
                    topology.PeriodicX ? topology.Width : topology.Width - overlapping.NX + 1,
                    topology.PeriodicY ? topology.Height : topology.Height - overlapping.NY + 1,
                    topology.PeriodicZ ? topology.Depth : topology.Depth - overlapping.NZ + 1);

                mappingType = MappingType.Overlapping;
                mappingNX   = overlapping.NX;
                mappingNY   = overlapping.NY;
                mappingNZ   = overlapping.NZ;

                // Compute tilesToPatterns and patternsToTiles
                var patternArrays = overlapping.PatternArrays;
                tilesToPatternsByOffset = new Dictionary <int, IReadOnlyDictionary <Tile, ISet <int> > >();
                patternsToTilesByOffset = new Dictionary <int, IReadOnlyDictionary <int, Tile> >();
                for (int ox = 0; ox < overlapping.NX; ox++)
                {
                    for (int oy = 0; oy < overlapping.NY; oy++)
                    {
                        for (int oz = 0; oz < overlapping.NZ; oz++)
                        {
                            var o = CombineOffsets(ox, oy, oz);
                            var tilesToPatterns = new Dictionary <Tile, ISet <int> >();
                            tilesToPatternsByOffset[o] = tilesToPatterns;
                            var patternsToTiles = new Dictionary <int, Tile>();
                            patternsToTilesByOffset[o] = patternsToTiles;
                            for (var pattern = 0; pattern < patternArrays.Count; pattern++)
                            {
                                var patternArray = patternArrays[pattern];
                                var tile         = patternArray.Values[ox, oy, oz];
                                patternsToTiles[pattern] = tile;
                                if (!tilesToPatterns.TryGetValue(tile, out var patternSet))
                                {
                                    patternSet = tilesToPatterns[tile] = new HashSet <int>();
                                }
                                patternSet.Add(pattern);
                            }
                        }
                    }
                }
            }
            else
            {
                mappingType             = MappingType.OneToOne;
                tilesToPatternsByOffset = new Dictionary <int, IReadOnlyDictionary <Tile, ISet <int> > >()
                {
                    { 0, tileModel.TilesToPatterns.ToDictionary(g => g.Key, g => (ISet <int>) new HashSet <int>(g)) }
                };
                patternsToTilesByOffset = new Dictionary <int, IReadOnlyDictionary <int, Tile> >
                {
                    { 0, tileModel.PatternsToTiles },
                };
            }

            var waveConstraints =
                (constraints?.Select(x => new TileConstraintAdaptor(x, this)).ToArray() ?? Enumerable.Empty <IWaveConstraint>())
                .ToArray();

            this.wavePropagator = new WavePropagator(tileModel.GetPatternModel(), patternTopology, backtrack, waveConstraints, random, clear: false);
            wavePropagator.Clear();
        }
        private void ProcessPlayerClosed()
        {
            // The session finished to close, we have to dispose all related object.
            currentMusic = null;

            mediaSessionCallback.Dispose();

            if (mediaSource != null) mediaSource.Shutdown();
            if (mediaSession != null) mediaSession.Shutdown();

            if (streamVolume != null) streamVolume.Dispose();
            if (mediaSource != null) mediaSource.Dispose();
            if (topology != null) topology.Dispose();
            if (mediaSession != null) mediaSession.Dispose();
            if (mediaInputByteStream != null) mediaInputByteStream.Dispose();

            topology = null;
            streamVolume = null;
            mediaSession = null;
            mediaSource = null;
            mediaInputByteStream = null;
            mediaSessionCallback = null;
            isMusicPlayerReady = false;
        }
Beispiel #56
0
 /// <summary>
 /// Gets the number of primitives rendered with the given topology.
 /// </summary>
 /// <param name="topology">The topology whose primitive count should be returned.</param>
 /// <returns>The number of primitives rendered.</returns>
 public int GetPrimitiveCount(Topology topology)
 {
     return((int)data->NumPrims[(int)topology]);
 }