Exemplo n.º 1
0
        public List <StopLine> ReadStopLines()
        {
            List <StopLine> result            = new List <StopLine>();
            XmlNode         guideLineListNode = Doc["opencv_storage"]["Vstringslist"];
            XmlNode         PlaneTypeListNode = null;

            foreach (XmlNode glNode in guideLineListNode)
            {
                string stopText = glNode["Vectorname"].InnerText;
                if (stopText.Substring(0, 9) == "PlaneType")
                {
                    PlaneTypeListNode = glNode["strings"];
                    StopLine s = new StopLine(new Point(0, 0), new Point(0, 0), stopText,
                                              stopText.Substring(0, 10).Replace("PlaneType", "GuideLine"));
                    foreach (XmlNode ptNode in PlaneTypeListNode)
                    {
                        string t = ptNode["stringname"].InnerText;
                        if (t.StartsWith("stop") || t.StartsWith("guide"))
                        {
                            continue;
                        }
                        s.planeTypes.Add(t);
                    }
                    result.Add(s);
                }
            }
            return(result);
        }
Exemplo n.º 2
0
        /// <summary>
        ///     修改初始信息绑定
        /// </summary>
        private void updateInfo()
        {
            //停采线名称
            txtStopLineName.Text = stopLineEntity.StopLineName;

            //起点坐标X
            txtSCoordinateX.Text = stopLineEntity.SCoordinateX.ToString();

            //起点坐标Y
            txtSCoordinateY.Text = stopLineEntity.SCoordinateY.ToString();

            //起点坐标Z
            txtSCoordinateZ.Text = stopLineEntity.SCoordinateZ.ToString();

            //终点坐标X
            txtFCoordinateX.Text = stopLineEntity.FCoordinateX.ToString();

            //终点坐标Y
            txtFCoordinateY.Text = stopLineEntity.FCoordinateY.ToString();

            //终点坐标Z
            txtFCoordinateZ.Text = stopLineEntity.FCoordinateZ.ToString();

            _oldStopLineEntity = stopLineEntity; //记录修改前的实体
        }
Exemplo n.º 3
0
        /// <summary>
        ///     在地图上绘制一条停采线
        /// </summary>
        /// <param name="stopLineEntity">掘进的起点和终点</param>
        private bool DrawStopLine(StopLine stopLineEntity)
        {
            if (stopLineEntity == null)
            {
                return(false);
            }

            var featureLayer = GetStopLineFeatureLayer();

            if (featureLayer == null)
            {
                return(false);
            }

            IPoint startPoint = new PointClass();

            startPoint.PutCoords(stopLineEntity.SCoordinateX, stopLineEntity.SCoordinateY);
            startPoint.Z = stopLineEntity.SCoordinateZ;

            IPoint endPoint = new PointClass();

            endPoint.PutCoords(stopLineEntity.FCoordinateX, stopLineEntity.FCoordinateY);
            endPoint.Z = stopLineEntity.FCoordinateZ;

            IPolyline polyline = new PolylineClass();

            polyline.FromPoint = startPoint;
            polyline.ToPoint   = endPoint;

            var bSuccess = GIS.SpecialGraphic.DrawStopLine.CreateLineFeature(featureLayer, polyline, stopLineEntity);

            return(bSuccess);
        }
Exemplo n.º 4
0
        /// <summary>
        ///     构造方法
        /// </summary>
        /// <param name="stopLineEntity">停采线实体</param>
        public StopLineEntering(StopLine stopLineEntity)
        {
            this.stopLineEntity = stopLineEntity;

            InitializeComponent();
            //绑定修改初始信息
            updateInfo();

            //窗体属性设置
            FormDefaultPropertiesSetter.SetEnteringFormDefaultProperties(this, Const_MS.STOP_LINE_CHANGE);
        }
Exemplo n.º 5
0
        /// <summary>
        ///     更新地图上的停采线
        /// </summary>
        /// <param name="oldEntity">修改前的停采线实体</param>
        /// <param name="newEntity">修改后的停采线实体</param>
        /// <returns>成功返回true</returns>
        private bool UpdateStopLineOnMap(StopLine oldEntity, StopLine newEntity)
        {
            var featureLayer = GetStopLineFeatureLayer();

            if (featureLayer == null)
            {
                return(false);
            }

            //先删除原有的线要素
            GIS.SpecialGraphic.DrawStopLine.DeleteLineFeature(featureLayer, oldEntity.BindingId);

            //重新绘制一条新的停采线
            var bSuccess = DrawStopLine(newEntity);

            return(bSuccess);
        }
Exemplo n.º 6
0
    void MakeVisualLine(Line line, LineType type, out int retLinkID)
    {
        retLinkID = -1;

        var startPos = GetUnityPosition(new VectorMapPosition()
        {
            Bx = points[line.BPID - 1].Bx, Ly = points[line.BPID - 1].Ly, H = points[line.BPID - 1].H
        });
        var endPos = GetUnityPosition(new VectorMapPosition()
        {
            Bx = points[line.FPID - 1].Bx, Ly = points[line.FPID - 1].Ly, H = points[line.FPID - 1].H
        });

        if (type == LineType.STOP) //If it is stopline
        {
            int LinkID = FindNearestLaneId(GetVectorMapPosition((startPos + endPos) / 2), true);
            retLinkID = LinkID;
            var vmStopline = StopLine.MakeStopLine(stoplines.Count + 1, line.LID, 0, 0, LinkID);
            stoplines.Add(vmStopline);
        }
        else if (type == LineType.WHITE || type == LineType.YELLOW) //if it is whiteline
        {
            int LinkID = FindNearestLaneId(GetVectorMapPosition((startPos + endPos) / 2));
            retLinkID = LinkID;
            string color = "W";
            switch (type)
            {
            case LineType.WHITE:
                color = "W";
                break;

            case LineType.YELLOW:
                color = "Y";
                break;
            }
            var vmWhiteline = WhiteLine.MakeWhiteLine(whiteLines.Count + 1, line.LID, .15, color, 0, LinkID);
            whiteLines.Add(vmWhiteline);
        }
    }
Exemplo n.º 7
0
        void MakeVisualLine(Line line, LineType type, out int retLinkID)
        {
            retLinkID = 0;

            var startPos = VectorMapUtility.GetUnityPosition(new VectorMapPosition()
            {
                Bx = Points[line.BPID - 1].Bx, Ly = Points[line.BPID - 1].Ly, H = Points[line.BPID - 1].H
            }, MapAnnotationTool.EXPORT_SCALE_FACTOR);
            var endPos = VectorMapUtility.GetUnityPosition(new VectorMapPosition()
            {
                Bx = Points[line.FPID - 1].Bx, Ly = Points[line.FPID - 1].Ly, H = Points[line.FPID - 1].H
            }, MapAnnotationTool.EXPORT_SCALE_FACTOR);

            if (type == LineType.STOP) //If it is stopline
            {
                int LinkID = FindNearestLaneId(VectorMapUtility.GetVectorMapPosition((startPos + endPos) / 2, MapAnnotationTool.EXPORT_SCALE_FACTOR), true);
                retLinkID = LinkID;
                var vmStopline = StopLine.MakeStopLine(StopLines.Count + 1, line.LID, 0, 0, LinkID);
                StopLines.Add(vmStopline);
            }
            else if (type == LineType.WHITE || type == LineType.YELLOW) //if it is whiteline
            {
                int LinkID = FindNearestLaneId(VectorMapUtility.GetVectorMapPosition((startPos + endPos) / 2, MapAnnotationTool.EXPORT_SCALE_FACTOR));
                retLinkID = LinkID;
                string color = "W";
                switch (type)
                {
                case LineType.WHITE:
                    color = "W";
                    break;

                case LineType.YELLOW:
                    color = "Y";
                    break;
                }
                var vmWhiteline = WhiteLine.MakeWhiteLine(WhiteLines.Count + 1, line.LID, .15, color, 0, LinkID);
                WhiteLines.Add(vmWhiteline);
            }
        }
 public WaitingCar(CarController car, StopLine stopLine)
 {
     this.car = car;
     this.stopLine = stopLine;
 }
Exemplo n.º 9
0
        /// <summary>
        /// Called on each bar update event (incoming tick)
        protected override void OnBarUpdate()
        {
            if (CurrentBar == 0)
            {
                displacement   = Math.Max(Displacement, -CurrentBar);
                priorUpTrend   = true;
                currentUpTrend = true;
                upTrend.Set(true);
                StopDot.Set(Close[0]);
                StopLine.Set(Close[0]);
                PlotColors[0][-displacement] = Color.Transparent;
                PlotColors[1][-displacement] = Color.Transparent;
                return;
            }
            if (FirstTickOfBar)
            {
                displacement   = Math.Max(Displacement, -CurrentBar);
                movingBase     = baseline[1];
                offset         = Math.Max(TickSize, offsetSeries[1]);
                trailingAmount = multiplier * offset;
                margin         = volatility[1];
                if (currentUpTrend)
                {
                    currentStopShort = movingBase + trailingAmount;
                    if (priorUpTrend)
                    {
                        currentStopLong = Math.Max(currentStopLong, movingBase - trailingAmount);
                    }
                    else
                    {
                        currentStopLong = movingBase - trailingAmount;
                    }
                    StopDot.Set(currentStopLong);
                    ReverseDot.Set(currentStopShort);
                    PlotColors[0][-displacement] = upColor;

                    if (showStopLine)
                    {
                        StopLine.Set(currentStopLong);
                        if (gap && !priorUpTrend)
                        {
                            PlotColors[1][-displacement] = Color.Transparent;
                        }
                        else
                        {
                            PlotColors[1][-displacement] = upColor;
                        }
                    }
                    else
                    {
                        StopLine.Reset();
                    }
                }
                else
                {
                    currentStopLong = movingBase - trailingAmount;
                    if (!priorUpTrend)
                    {
                        currentStopShort = Math.Min(currentStopShort, movingBase + trailingAmount);
                    }
                    else
                    {
                        currentStopShort = movingBase + trailingAmount;
                    }
                    StopDot.Set(currentStopShort);
                    ReverseDot.Set(currentStopLong);
                    PlotColors[0][-displacement] = downColor;
                    if (showStopLine)
                    {
                        StopLine.Set(currentStopShort);
                        if (gap && priorUpTrend)
                        {
                            PlotColors[1][-displacement] = Color.Transparent;
                        }
                        else
                        {
                            PlotColors[1][-displacement] = downColor;
                        }
                    }
                    else
                    {
                        StopLine.Reset();
                    }
                }
                if (showPaintBars)
                {
                    if (currentUpTrend)
                    {
                        trendColor = upColor;
                    }
                    else
                    {
                        trendColor = downColor;
                    }
                    CandleOutlineColorSeries[-displacement] = trendColor;
                    BarColorSeries[-displacement]           = trendColor;
                }
                if (showArrows)
                {
                    if (currentUpTrend && !priorUpTrend)
                    {
                        DrawArrowUp("arrow" + CurrentBar, true, -displacement, currentStopLong - 0.5 * margin, upColor);
                    }
                    else if (!currentUpTrend && priorUpTrend)
                    {
                        DrawArrowDown("arrow" + CurrentBar, true, -displacement, currentStopShort + 0.5 * margin, downColor);
                    }
                }
                priorUpTrend = currentUpTrend;
                stoppedOut   = false;
            }

            if (reverseIntraBar)            // only one trend change per bar is permitted
            {
                if (!stoppedOut)
                {
                    if (priorUpTrend && Low[0] < currentStopLong)
                    {
                        currentUpTrend = false;
                        stoppedOut     = true;
                    }
                    else if (!priorUpTrend && High[0] > currentStopShort)
                    {
                        currentUpTrend = true;
                        stoppedOut     = true;
                    }
                }
            }
            else
            {
                if (priorUpTrend && Close[0] < currentStopLong)
                {
                    currentUpTrend = false;
                }
                else if (!priorUpTrend && Close[0] > currentStopShort)
                {
                    currentUpTrend = true;
                }
                else
                {
                    currentUpTrend = priorUpTrend;
                }
            }

            // this information can be accessed by a strategy
            if (CalculateOnBarClose)
            {
                upTrend.Set(currentUpTrend);
            }
            else if (FirstTickOfBar && !reverseIntraBar)
            {
                upTrend.Set(priorUpTrend);
            }
            else if (reverseIntraBar)
            {
                upTrend.Set(currentUpTrend);
            }

            if (showPaintBars && candles)
            {
                if (Open[0] < Close[0])
                {
                    BarColorSeries[-displacement] = Color.FromArgb(alpha, trendColor);
                }
            }

            if (soundAlert && !Historical && IsConnected() && (CalculateOnBarClose || reverseIntraBar))
            {
                if (currentUpTrend && !priorUpTrend)
                {
                    try
                    {
                        Alert("NewUpTrend", NinjaTrader.Cbi.Priority.Medium, "NewUpTrend", confirmedUpTrend, rearmTime, Color.Black, upColor);
                    }
                    catch {}
                }
                else if (!currentUpTrend && priorUpTrend)
                {
                    try
                    {
                        Alert("NewDownTrend", NinjaTrader.Cbi.Priority.Medium, "NewDownTrend", confirmedDownTrend, rearmTime, Color.Black, downColor);
                    }
                    catch {}
                }
            }
            if (soundAlert && !Historical && IsConnected() && !CalculateOnBarClose && !reverseIntraBar)
            {
                if (currentUpTrend && !priorUpTrend)
                {
                    try
                    {
                        Alert("PotentialUpTrend", NinjaTrader.Cbi.Priority.Medium, "PotentialUpTrend", potentialUpTrend, rearmTime, Color.Black, upColor);
                    }
                    catch {}
                }
                else if (!currentUpTrend && priorUpTrend)
                {
                    try
                    {
                        Alert("PotentialDownTrend", NinjaTrader.Cbi.Priority.Medium, "PotentialDownTrend", potentialDownTrend, rearmTime, Color.Black, downColor);
                    }
                    catch {}
                }
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Called on each bar update event (incoming tick)
        protected override void OnBarUpdate()
        {
            if (CurrentBar == 0)
            {
                upTrend.Set(true);
                StopDot.Set(Close[0]);
                StopLine.Set(Close[0]);
                PlotColors[0][0] = neutralColor;
                PlotColors[1][0] = neutralColor;
                return;
            }
            if (FirstTickOfBar)
            {
                priorUpTrend = upTrend[1];
                priorStop    = StopLine[1];
                priorColor   = PlotColors[0][1];
                medianline   = MM[1];
                offset       = MAE[1];
            }
            if (Close[0] > priorStop)
            {
                upTrend.Set(true);
                newStop        = medianline - Multiplier * offset;
                currentUpTrend = true;
                if (!priorUpTrend)                 // trend change up
                {
                    StopDot.Set(newStop);
                    StopLine.Set(newStop);
                }
                else
                {
                    StopDot.Set(Math.Max(newStop, priorStop));
                    StopLine.Set(Math.Max(newStop, priorStop));
                }
            }
            else if (Close[0] < priorStop)
            {
                upTrend.Set(false);
                newStop        = medianline + Multiplier * offset;
                currentUpTrend = false;
                if (priorUpTrend)                 // trend change down
                {
                    StopDot.Set(newStop);
                    StopLine.Set(newStop);
                }
                else
                {
                    StopDot.Set(Math.Min(newStop, priorStop));
                    StopLine.Set(Math.Min(newStop, priorStop));
                }
            }
            else
            {
                upTrend.Set(priorUpTrend);
                currentUpTrend = priorUpTrend;
                StopDot.Set(priorStop);
                StopLine.Set(priorStop);
            }

            if (PaintBars)
            {
                if (currentUpTrend)
                {
                    CandleOutlineColor = upColor;
                    BarColor           = upColor;
                }
                else
                {
                    CandleOutlineColor = downColor;
                    BarColor           = downColor;
                }
                if (Open[0] < Close[0] && candles)
                {
                    BarColor = Color.Transparent;
                }
            }
            if (ShowArrows)
            {
                if (currentUpTrend && !priorUpTrend)
                {
                    DrawArrowUp("arrow" + CurrentBar, true, 0, newStop - 0.5 * offset, upColor);
                }
                else if (!currentUpTrend && priorUpTrend)
                {
                    DrawArrowDown("arrow" + CurrentBar, true, 0, newStop + 0.5 * offset, downColor);
                }
                else
                {
                    RemoveDrawObject("arrow" + CurrentBar);
                }
            }
            if (ShowStopDots)
            {
                if (currentUpTrend)
                {
                    PlotColors[0][0] = upColor;
                }
                else
                {
                    PlotColors[0][0] = downColor;
                }
            }
            if (ShowStopLine)
            {
                if (currentUpTrend && !priorUpTrend)
                {
                    if (gap)
                    {
                        PlotColors[1][0] = neutralColor;
                    }
                    else
                    {
                        PlotColors[1][0] = upColor;
                    }
                }
                else if (currentUpTrend)
                {
                    PlotColors[1][0] = upColor;
                }
                else if (!currentUpTrend && priorUpTrend)
                {
                    if (gap)
                    {
                        PlotColors[1][0] = neutralColor;
                    }
                    else
                    {
                        PlotColors[1][0] = downColor;
                    }
                }
                else
                {
                    PlotColors[1][0] = downColor;
                }
            }
        }
Exemplo n.º 11
0
 private void RefreshData()
 {
     gcStopLine.DataSource = StopLine.FindAll();
 }
Exemplo n.º 12
0
 /// <summary>
 ///     验证
 /// </summary>
 /// <returns></returns>
 private bool check()
 {
     //停采线名称非空验证
     if (!Check.isEmpty(txtStopLineName, Const_MS.STOP_LINE_NAME))
     {
         return(false);
     }
     //停采线名称特殊字符验证
     if (!Check.checkSpecialCharacters(txtStopLineName, Const_MS.STOP_LINE_NAME))
     {
         return(false);
     }
     //停采线名称重复
     if (txtStopLineName.Text != stopLineEntity.StopLineName)
     {
         if (StopLine.ExistsByStopLineName(txtStopLineName.Text))
         {
             Alert.alert(Const_MS.STOP_LINE + Const.MSG_ALREADY_HAVE + Const.SIGN_EXCLAMATION_MARK);
             return(false);
         }
     }
     //起点坐标X数字验证
     if (!Check.IsNumeric(txtSCoordinateX, Const_MS.SCOORDINATE + Const_MS.X))
     {
         return(false);
     }
     //起点坐标X非空验证
     if (!Check.isEmpty(txtSCoordinateX, Const_MS.SCOORDINATE + Const_MS.X))
     {
         return(false);
     }
     //起点坐标Y数字验证
     if (!Check.IsNumeric(txtSCoordinateY, Const_MS.SCOORDINATE + Const_MS.Y))
     {
         return(false);
     }
     //起点坐标Y非空验证
     if (!Check.isEmpty(txtSCoordinateY, Const_MS.SCOORDINATE + Const_MS.Y))
     {
         return(false);
     }
     //起点坐标Z数字验证
     if (!Check.IsNumeric(txtSCoordinateZ, Const_MS.SCOORDINATE + Const_MS.Z))
     {
         return(false);
     }
     //起点坐标Z非空验证
     if (!Check.isEmpty(txtSCoordinateZ, Const_MS.SCOORDINATE + Const_MS.Z))
     {
         return(false);
     }
     //终点坐标X数字验证
     if (!Check.IsNumeric(txtFCoordinateX, Const_MS.FCOORDINATE + Const_MS.X))
     {
         return(false);
     }
     //终点坐标X非空验证
     if (!Check.isEmpty(txtFCoordinateX, Const_MS.FCOORDINATE + Const_MS.X))
     {
         return(false);
     }
     //终点坐标Y数字验证
     if (!Check.IsNumeric(txtFCoordinateY, Const_MS.FCOORDINATE + Const_MS.Y))
     {
         return(false);
     }
     //终点坐标Y非空验证
     if (!Check.isEmpty(txtFCoordinateY, Const_MS.FCOORDINATE + Const_MS.Y))
     {
         return(false);
     }
     //终点坐标Z数字验证
     if (!Check.IsNumeric(txtFCoordinateZ, Const_MS.FCOORDINATE + Const_MS.Z))
     {
         return(false);
     }
     //终点坐标Z非空验证
     if (!Check.isEmpty(txtFCoordinateZ, Const_MS.FCOORDINATE + Const_MS.Z))
     {
         return(false);
     }
     return(true);
 }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            Console.WriteLine("Loading NaPTAN stops.");
            if (Directory.Exists("temp") == true)
            {
                Directory.Delete("temp", true);
            }
            Directory.CreateDirectory("temp");

            Console.WriteLine("Unzipping NaPTAN to a temporary folder.");
            ZipFile.ExtractToDirectory(@"stops.zip", "temp");
            List <NaptanStop> NaptanStops = new List <NaptanStop>();

            using (TextReader textReader = File.OpenText("temp/Stops.csv"))
            {
                CsvReader csvReader = new CsvReader(textReader, CultureInfo.InvariantCulture);
                csvReader.Configuration.Delimiter = ",";
                NaptanStops = csvReader.GetRecords <NaptanStop>().ToList();
            }

            Console.WriteLine("Creating ATCOcode keyed dictionary of NaPTAN stops.");
            Dictionary <string, NaptanStop> NaPTANStopsDictionary = new Dictionary <string, NaptanStop>();

            foreach (NaptanStop naptanStop in NaptanStops)
            {
                NaPTANStopsDictionary.Add(naptanStop.ATCOCode, naptanStop);
            }

            Console.WriteLine("Loading CIF stations and matching them to NaPTAN stops.");
            List <CIFStation> CIFStations = new List <CIFStation>();

            // .msn lines are fixed-width columns and look like this.
            // "A    WHITTLESFORD PARKWAY          0WTLESFDWLF   WLF15484 62473 5                 "
            // A reasonable approach would be to split at the correct position, then trim, then only store entries with all features
            ZipFile.ExtractToDirectory(@"ttis389.zip", "temp");
            List <string> StopsFileLines = new List <string>(File.ReadAllLines("temp/ttisf389.msn"));

            foreach (string StopLine in StopsFileLines)
            {
                string firstSlot  = StopLine.Substring(0, 5).Trim();
                string secondSlot = StopLine.Substring(5, 30).TrimEnd();
                string thirdSlot  = StopLine.Substring(35, 1);
                string fourthSlot = StopLine.Substring(36, 7).Trim();
                string fifthSlot  = StopLine.Substring(43, 3).Trim();
                string sixthSlot  = StopLine.Substring(49, 8).Trim();
                // The seventh slot is okay to be empty
                string seventhSlot = StopLine.Substring(57, 1).Trim();
                string eighthSlot  = StopLine.Substring(58, 5).Trim();
                string ninthSlot   = StopLine.Substring(65, 1).Trim();

                if (firstSlot == "A" && secondSlot.StartsWith(" ") == false)
                {
                    CIFStation Station = new CIFStation()
                    {
                        StationName      = secondSlot,
                        StationShortCode = fifthSlot,
                        StationLongCode  = fourthSlot
                    };

                    if (NaPTANStopsDictionary.ContainsKey("9100" + Station.StationLongCode))
                    {
                        Station.ATCOCode = NaPTANStopsDictionary["9100" + Station.StationLongCode].ATCOCode;
                    }
                    else
                    {
                        Console.WriteLine($"No ATCO code found for {Station.StationName} station.");
                    }

                    CIFStations.Add(Station);
                }
            }
            Console.WriteLine($"Read {CIFStations.Count} stations of which {CIFStations.Where(x => x.ATCOCode != null).Count()} have a matched NaPTAN code.");

            Console.WriteLine("Reading the timetable file.");
            List <string> TimetableFileLines = new List <string>(File.ReadAllLines("temp/ttisf389.mca"));
            Dictionary <string, List <StationStop> > StopTimesForJourneyIDDictionary      = new Dictionary <string, List <StationStop> >();
            Dictionary <string, JourneyDetail>       JourneyDetailsForJourneyIDDictionary = new Dictionary <string, JourneyDetail>();

            string   CurrentJourneyID     = "";
            string   CurrentOperatorCode  = "";
            string   CurrentTrainType     = "";
            string   CurrentTrainClass    = "";
            string   CurrentTrainMaxSpeed = "";
            Calendar CurrentCalendar      = null;

            foreach (string TimetableLine in TimetableFileLines)
            {
                if (TimetableLine.StartsWith("BS"))
                {
                    // THIS IS ALMOST CERTAINLY NOT THE CURRENT JOURNEY ID. BUT IT'S OKAY DURING DEVELOPMENT.
                    //CurrentJourneyID = TimetableLine;

                    // Example line is "BSNY244881905191912080000001 POO2D67    111821020 EMU333 100      S            P"
                    CurrentJourneyID = TimetableLine.Substring(2, 7);

                    string StartDateString       = TimetableLine.Substring(9, 6);
                    string EndDateString         = TimetableLine.Substring(15, 6);
                    string DaysOfOperationString = TimetableLine.Substring(21, 7);

                    // Since a single timetable can have a single Journey ID that is valid at different non-overlapping times a unique Journey ID includes the Date strings and the character at position 79.
                    CurrentJourneyID = CurrentJourneyID + StartDateString + EndDateString + TimetableLine.Substring(79, 1);

                    CurrentCalendar = new Calendar()
                    {
                        start_date = "20" + StartDateString,
                        end_date   = "20" + EndDateString,
                        service_id = CurrentJourneyID + "_service",
                        monday     = int.Parse(DaysOfOperationString.Substring(0, 1)),
                        tuesday    = int.Parse(DaysOfOperationString.Substring(1, 1)),
                        wednesday  = int.Parse(DaysOfOperationString.Substring(2, 1)),
                        thursday   = int.Parse(DaysOfOperationString.Substring(3, 1)),
                        friday     = int.Parse(DaysOfOperationString.Substring(4, 1)),
                        saturday   = int.Parse(DaysOfOperationString.Substring(5, 1)),
                        sunday     = int.Parse(DaysOfOperationString.Substring(6, 1))
                    };

                    CurrentTrainType     = TimetableLine.Substring(50, 3);
                    CurrentTrainClass    = TimetableLine.Substring(53, 3);
                    CurrentTrainMaxSpeed = TimetableLine.Substring(57, 3);
                }

                if (TimetableLine.StartsWith("BX"))
                {
                    CurrentOperatorCode = TimetableLine.Substring(11, 2);

                    JourneyDetail journeyDetail = new JourneyDetail()
                    {
                        JourneyID          = CurrentJourneyID,
                        OperatorCode       = CurrentOperatorCode,
                        OperationsCalendar = CurrentCalendar,
                        TrainClass         = CurrentTrainClass,
                        TrainMaxSpeed      = CurrentTrainMaxSpeed,
                        TrainType          = CurrentTrainType
                    };

                    JourneyDetailsForJourneyIDDictionary.Add(CurrentJourneyID, journeyDetail);
                }

                if (TimetableLine.StartsWith("LO") || TimetableLine.StartsWith("LI") || TimetableLine.StartsWith("LT"))
                {
                    string firstSlot  = TimetableLine.Substring(0, 2).Trim();
                    string secondSlot = TimetableLine.Substring(2, 7).Trim();
                    string thirdSlot  = TimetableLine.Substring(10, 4).Trim();
                    string fourthSlot = TimetableLine.Substring(15, 4).Trim();
                    string fifthSlot  = TimetableLine.Substring(25, 8).Trim();

                    if (fifthSlot != "00000000")
                    {
                        StationStop stationStop = new StationStop()
                        {
                            StopType        = firstSlot,
                            StationLongCode = secondSlot
                        };

                        if (NaPTANStopsDictionary.ContainsKey("9100" + stationStop.StationLongCode))
                        {
                            if (thirdSlot.Count() == 4 && fourthSlot.Count() == 4)
                            {
                                stationStop.WorkingTimetableDepartureTime = stringToTimeSpan(thirdSlot);
                                stationStop.PublicTimetableDepartureTime  = stringToTimeSpan(fourthSlot);
                                stationStop.NaPTANStop = NaPTANStopsDictionary["9100" + stationStop.StationLongCode];

                                if (StopTimesForJourneyIDDictionary.ContainsKey(CurrentJourneyID))
                                {
                                    List <StationStop> UpdatedStationStops = StopTimesForJourneyIDDictionary[CurrentJourneyID];
                                    UpdatedStationStops.Add(stationStop);
                                    StopTimesForJourneyIDDictionary.Remove(CurrentJourneyID);
                                    StopTimesForJourneyIDDictionary.Add(CurrentJourneyID, UpdatedStationStops);
                                }
                                else
                                {
                                    StopTimesForJourneyIDDictionary.Add(CurrentJourneyID, new List <StationStop>()
                                    {
                                        stationStop
                                    });
                                }
                            }
                        }
                    }
                }
            }


            Console.WriteLine($"Read {StopTimesForJourneyIDDictionary.Keys.Count} journeys.");

            Console.WriteLine("Creating GTFS output.");

            // We have two dictionaries that let us create all our GTFS output.
            // StopTimesForJourneyIDDictionary
            // JourneyDetailsForJourneyIDDictionary
            // CIFStations

            List <string> Agencies = JourneyDetailsForJourneyIDDictionary.Values.Select(x => x.OperatorCode).Distinct().ToList();

            // AgencyList will hold the GTFS agency.txt file contents
            List <Agency> AgencyList = new List <Agency>();

            // Get all unique agencies from our output
            foreach (string agency in Agencies)
            {
                Agency NewAgency = new Agency()
                {
                    agency_id       = agency,
                    agency_name     = agency,
                    agency_url      = "https://www.google.com/search?q=" + agency + "%20rail%20operator%20code", // google plus name of agency by default
                    agency_timezone = "Europe/London"                                                            // Europe/London by default
                };
                AgencyList.Add(NewAgency);
            }


            List <GTFSNaptanStop> GTFSStopsList = new List <GTFSNaptanStop>();

            foreach (CIFStation cIFStation in CIFStations.Where(x => x.ATCOCode != null))
            {
                var NaPTANEntry = NaPTANStopsDictionary["9100" + cIFStation.StationLongCode];

                GTFSNaptanStop gTFSNaptanStop = new GTFSNaptanStop()
                {
                    stop_id   = cIFStation.ATCOCode,
                    stop_name = cIFStation.StationName,
                    stop_code = cIFStation.StationShortCode,
                    stop_lat  = Math.Round(NaPTANEntry.Latitude, 5),
                    stop_lon  = Math.Round(NaPTANEntry.Longitude, 5)
                };

                GTFSStopsList.Add(gTFSNaptanStop);
            }

            List <Route> RoutesList = new List <Route>();

            foreach (string journeyID in JourneyDetailsForJourneyIDDictionary.Keys)
            {
                JourneyDetail journeyDetail = JourneyDetailsForJourneyIDDictionary[journeyID];
                Route         route         = new Route()
                {
                    agency_id        = journeyDetail.OperatorCode,
                    route_id         = journeyDetail.JourneyID + "_route",
                    route_type       = "2",
                    route_short_name = journeyDetail.OperatorCode + "_" + journeyDetail.JourneyID
                };
                RoutesList.Add(route);
            }

            List <Trip> tripList = new List <Trip>();

            foreach (JourneyDetail journeyDetail in JourneyDetailsForJourneyIDDictionary.Values)
            {
                Trip trip = new Trip()
                {
                    route_id   = journeyDetail.JourneyID + "_route",
                    service_id = journeyDetail.JourneyID + "_service",
                    trip_id    = journeyDetail.JourneyID + "_trip"
                };
                tripList.Add(trip);
            }

            // This export line is more complicated than it might at first seem sensible to be because of an understandable quirk in the GTFS format.
            // Stop times are only given as a time of day, and not a datetime. This causes problems when a service runs over midnight.
            // To fix this we express stop times on a service that started the previous day with times such as 24:12 instead of 00:12 and 25:20 instead of 01:20.
            // I assume that no journey runs into a third day.

            List <StopTime> stopTimesList = new List <StopTime>();

            foreach (string JourneyID in StopTimesForJourneyIDDictionary.Keys)
            {
                List <StationStop> StationStops = StopTimesForJourneyIDDictionary[JourneyID];
                int count = 1;

                bool     JourneyStartedYesterdayFlag = false;
                TimeSpan PreviousStopDepartureTime   = new TimeSpan(0);

                foreach (StationStop stationStop in StationStops)
                {
                    if (stationStop.PublicTimetableDepartureTime < PreviousStopDepartureTime)
                    {
                        JourneyStartedYesterdayFlag = true;
                    }

                    StopTime stopTime = new StopTime()
                    {
                        trip_id       = JourneyID + "_trip",
                        stop_id       = stationStop.NaPTANStop.ATCOCode,
                        stop_sequence = count
                    };

                    if (JourneyStartedYesterdayFlag == true)
                    {
                        stationStop.WorkingTimetableDepartureTime = stationStop.WorkingTimetableDepartureTime.Add(new TimeSpan(24, 0, 0));
                        stationStop.PublicTimetableDepartureTime  = stationStop.PublicTimetableDepartureTime.Add(new TimeSpan(24, 0, 0));
                        stopTime.arrival_time   = Math.Floor(stationStop.PublicTimetableDepartureTime.TotalHours).ToString() + stationStop.PublicTimetableDepartureTime.ToString(@"hh\:mm\:ss").Substring(2, 6);
                        stopTime.departure_time = Math.Floor(stationStop.PublicTimetableDepartureTime.TotalHours).ToString() + stationStop.PublicTimetableDepartureTime.ToString(@"hh\:mm\:ss").Substring(2, 6);
                    }
                    else
                    {
                        stopTime.arrival_time   = stationStop.PublicTimetableDepartureTime.ToString(@"hh\:mm\:ss");
                        stopTime.departure_time = stationStop.PublicTimetableDepartureTime.ToString(@"hh\:mm\:ss");
                    }
                    stopTimesList.Add(stopTime);

                    PreviousStopDepartureTime = stationStop.PublicTimetableDepartureTime;
                    count++;
                }
            }

            List <Calendar> calendarList = JourneyDetailsForJourneyIDDictionary.Values.Select(x => x.OperationsCalendar).ToList();

            Console.WriteLine("Writing agency.txt");
            // write GTFS txts.
            // agency.txt, calendar.txt, calendar_dates.txt, routes.txt, stop_times.txt, stops.txt, trips.txt
            if (Directory.Exists("output") == false)
            {
                Directory.CreateDirectory("output");
            }

            TextWriter agencyTextWriter = File.CreateText(@"output/agency.txt");
            CsvWriter  agencyCSVwriter  = new CsvWriter(agencyTextWriter, CultureInfo.InvariantCulture);

            agencyCSVwriter.WriteRecords(AgencyList);
            agencyTextWriter.Dispose();
            agencyCSVwriter.Dispose();

            Console.WriteLine("Writing stops.txt");
            TextWriter stopsTextWriter = File.CreateText(@"output/stops.txt");
            CsvWriter  stopsCSVwriter  = new CsvWriter(stopsTextWriter, CultureInfo.InvariantCulture);

            stopsCSVwriter.WriteRecords(GTFSStopsList);
            stopsTextWriter.Dispose();
            stopsCSVwriter.Dispose();

            Console.WriteLine("Writing routes.txt");
            TextWriter routesTextWriter = File.CreateText(@"output/routes.txt");
            CsvWriter  routesCSVwriter  = new CsvWriter(routesTextWriter, CultureInfo.InvariantCulture);

            routesCSVwriter.WriteRecords(RoutesList);
            routesTextWriter.Dispose();
            routesCSVwriter.Dispose();

            Console.WriteLine("Writing trips.txt");
            TextWriter tripsTextWriter = File.CreateText(@"output/trips.txt");
            CsvWriter  tripsCSVwriter  = new CsvWriter(tripsTextWriter, CultureInfo.InvariantCulture);

            tripsCSVwriter.WriteRecords(tripList);
            tripsTextWriter.Dispose();
            tripsCSVwriter.Dispose();

            Console.WriteLine("Writing calendar.txt");
            TextWriter calendarTextWriter = File.CreateText(@"output/calendar.txt");
            CsvWriter  calendarCSVwriter  = new CsvWriter(calendarTextWriter, CultureInfo.InvariantCulture);

            calendarCSVwriter.WriteRecords(calendarList);
            calendarTextWriter.Dispose();
            calendarCSVwriter.Dispose();

            Console.WriteLine("Writing stop_times.txt");
            TextWriter stopTimeTextWriter = File.CreateText(@"output/stop_times.txt");
            CsvWriter  stopTimeCSVwriter  = new CsvWriter(stopTimeTextWriter, CultureInfo.InvariantCulture);

            stopTimeCSVwriter.WriteRecords(stopTimesList);
            stopTimeTextWriter.Dispose();
            stopTimeCSVwriter.Dispose();

            Console.WriteLine("Creating a GTFS .zip file.");
            if (File.Exists("output.zip"))
            {
                File.Delete("output.zip");
            }
            ZipFile.CreateFromDirectory("output", "output.zip", CompressionLevel.Optimal, false, Encoding.UTF8);

            Console.WriteLine("You may wish to validate the GTFS output using a tool such as https://github.com/google/transitfeed/");

            /*
             * var OrderedStopTimesForJourneyDictionary = StopTimesForJourneyIDDictionary.OrderByDescending(x => x.Value.Count);
             * Console.WriteLine("Calculating average velocities for all journeys.");
             * List<JourneyVelocity> JourneyVelocities = new List<JourneyVelocity>();
             * foreach (var JourneyID in StopTimesForJourneyIDDictionary.Where(x => x.Value.Count > 1)) {
             *  var FirstStop = JourneyID.Value.First();
             *  var LastStop = JourneyID.Value.Last();
             *
             *  GeoCoordinate GeoFirstStop = new GeoCoordinate(FirstStop.NaPTANStop.Latitude, FirstStop.NaPTANStop.Longitude);
             *  GeoCoordinate GeoSecondStop = new GeoCoordinate(LastStop.NaPTANStop.Latitude, LastStop.NaPTANStop.Longitude);
             *  var Distance = GeoFirstStop.GetDistanceTo(GeoSecondStop) / 1000;
             *  var Time = LastStop.DepartureTime - FirstStop.DepartureTime;
             *
             *  // if a journey time is negative, add a day to it.
             *  while (Time.TotalSeconds < 0)
             *  {
             *      Time = Time.Add(new TimeSpan(24, 0, 0));
             *  }
             *  var Velocity = Math.Round(Distance / Time.TotalHours, 1);
             *
             *  JourneyVelocity journeyVelocity = new JourneyVelocity()
             *  {
             *      Velocity = Velocity,
             *      JourneyDetails = JourneyID
             *  };
             *  JourneyVelocities.Add(journeyVelocity);
             * }
             *
             * var orderedJourneyVelocities = JourneyVelocities.OrderByDescending(x => x.Velocity);
             */
        }
	public void Enqueue(CarController car, StopLine stopLine) {
		cars.Enqueue(new WaitingCar(car, stopLine));

        if (State == IntersectionState.Empty)
        {
            State = IntersectionState.ReleaseNextCar;
        }
	}
Exemplo n.º 15
0
 protected override void OnBarUpdate()
 {
     if (CurrentBar == 0)
     {
         upTrend.Set(true);
         StopDot.Set(Close[0]);
         StopLine.Set(Close[0]);
         PlotColors[0][0] = neutralColor;
         PlotColors[1][0] = neutralColor;
         return;
     }
     if (FirstTickOfBar)
     {
         priorUpTrend = upTrend[1];
         priorStop    = StopLine[1];
         offset       = mae[1];
     }
     if (Close[0] > priorStop)
     {
         upTrend.Set(true);
         newStop        = mm[0] - (Multiplier * offset);
         currentUpTrend = true;
         if (!priorUpTrend)
         {
             StopDot.Set(newStop);
             StopLine.Set(newStop);
         }
         else
         {
             StopDot.Set(Math.Max(newStop, priorStop));
             StopLine.Set(Math.Max(newStop, priorStop));
         }
     }
     else if (Close[0] < priorStop)
     {
         upTrend.Set(false);
         newStop        = mm[0] + (Multiplier * offset);
         currentUpTrend = false;
         if (priorUpTrend)
         {
             StopDot.Set(newStop);
             StopLine.Set(newStop);
         }
         else
         {
             StopDot.Set(Math.Min(newStop, priorStop));
             StopLine.Set(Math.Min(newStop, priorStop));
         }
     }
     else
     {
         currentUpTrend = priorUpTrend;
         upTrend.Set(priorUpTrend);
         StopDot.Set(priorStop);
         StopLine.Set(priorStop);
     }
     if (PaintBars)
     {
         if (currentUpTrend)
         {
             CandleOutlineColor = upColor;
             BarColor           = upColor;
         }
         else
         {
             CandleOutlineColor = downColor;
             BarColor           = downColor;
         }
     }
     if (colorbackground)
     {
         BackColor = Color.FromArgb(opacity, currentUpTrend ? backgroundcolorUp : backgroundcolorDn);
     }
     if (colorAllBackgrounds)
     {
         BackColorAll = Color.FromArgb(opacity, currentUpTrend ? backgroundcolorUp : backgroundcolorDn);
     }
     if (ShowArrows)
     {
         if (currentUpTrend && !priorUpTrend)
         {
             DrawArrowUp("arrow" + CurrentBar, true, 0, newStop - (0.5 * offset), upColor);
             PlaySound("Alert4.wav");
         }
         else if (!currentUpTrend && priorUpTrend)
         {
             DrawArrowDown("arrow" + CurrentBar, true, 0, newStop + (0.5 * offset), downColor);
             PlaySound("Alert4.wav");
         }
         else
         {
             RemoveDrawObject("arrow" + CurrentBar);
         }
     }
     if (ShowStopLine)
     {
         PlotColors[1][0] = currentUpTrend && !priorUpTrend ? (gap ? neutralColor : upColor) : (currentUpTrend ? upColor : (!currentUpTrend && priorUpTrend ? (gap ? neutralColor : downColor) : downColor));
     }
 }
Exemplo n.º 16
0
        public static void GetCsvData(this StopLine stopLine,
                                      PointOctree <CsvLane> finalLanes,
                                      out List <CsvPoint> csvPoints,
                                      out List <CsvLine> csvLines,
                                      out List <CsvVector> csvVectors,
                                      out List <CsvSignalLight> csvSignalLights,
                                      out List <CsvStopLine> csvStopLines)
        {
            csvPoints    = new List <CsvPoint>();
            csvLines     = new List <CsvLine>();
            csvStopLines = new List <CsvStopLine>();
            var csvSLPoints = new List <CsvPoint>();

            csvVectors      = new List <CsvVector>();
            csvSignalLights = new List <CsvSignalLight>();
            for (int i = 0; i < stopLine.Count; i++)
            {
                var csvPoint = new CsvPoint()
                {
                    Position = stopLine.LineRenderer.GetPosition(i)
                };
                csvPoints.Add(csvPoint);
                if (i > 0)
                {
                    var csvLine = new CsvLine()
                    {
                        PointBegin = csvPoints[i - 1], PointFinal = csvPoint
                    };
                    if (i > 1)
                    {
                        csvLine.LineLast = csvLines.Last();
                    }
                    csvLines.Add(csvLine);
                    var signalLight = stopLine.signalLights[i - 1];
                    var csvSLPoint  = new CsvPoint()
                    {
                        Position = signalLight.transform.position
                    };
                    csvSLPoints.Add(csvSLPoint);
                    var csvVector = new CsvVector()
                    {
                        Point = csvSLPoint, Rotation = signalLight.transform.rotation
                    };
                    csvVectors.Add(csvVector);
                    var csvSignalLight = new CsvSignalLight()
                    {
                        Vector = csvVector
                    };
                    csvSignalLights.Add(csvSignalLight);
                    var midPoint    = (csvLine.PointBegin.Position + csvLine.PointFinal.Position) / 2;
                    var csvStopLine = new CsvStopLine()
                    {
                        Line        = csvLine,
                        SignalLight = csvSignalLight,
                        Lane        = finalLanes
                                      .GetNearby(midPoint, Vector3.Distance(csvLine.PointBegin.Position, csvLine.PointFinal.Position))
                                      ?.OrderBy(_ => Vector3.Distance(_.FinalNode.Point.Position, midPoint))?
                                      .FirstOrDefault()
                    };
                    csvStopLines.Add(csvStopLine);
                }
            }
            csvPoints.AddRange(csvSLPoints);
        }
Exemplo n.º 17
0
	public void ChooseDirection(StopLine stopLine) {
        int myTurnIndex = 0;
        if (turnInstructions != null && turnInstructions.Count > 0) {
            myTurnIndex = (int)turnInstructions[0];
            turnInstructions.RemoveAt(0);

            switch (myTurnIndex) {
                case (int)TurnIndex.LeftTurn:
                    turnDestination = stopLine.GetLeftTurnDestination();
                    break;
                case (int)TurnIndex.Straight:
                    turnDestination = stopLine.GetStraightDestination();
                    break;
                case (int)TurnIndex.RightTurn:
                    turnDestination = stopLine.GetRightTurnDestination();
                    break;
                default:
                    break;
            }
        }
		else {
            List<Vector2> possibleDestinations = new List<Vector2>(3);
            if (stopLine.CanTurnLeft()) {
                possibleDestinations.Add(stopLine.GetLeftTurnDestination());
            }
            else {
                possibleDestinations.Add(Vector2.zero);
            }

            if (stopLine.CanGoStraight()) {
                possibleDestinations.Add(stopLine.GetStraightDestination());
            }
            else {
                possibleDestinations.Add(Vector2.zero);
            }

            if (stopLine.CanTurnRight()) {
                possibleDestinations.Add(stopLine.GetRightTurnDestination());
            }
            else {
                possibleDestinations.Add(Vector2.zero);
            }

            myTurnIndex = Random.Range(0, possibleDestinations.Count);
            while (possibleDestinations[myTurnIndex] == Vector2.zero) {
                myTurnIndex = Random.Range(0, possibleDestinations.Count);
            }
            turnDestination = possibleDestinations[myTurnIndex];
        }

        switch (myTurnIndex)
        {
           case (int)TurnIndex.LeftTurn:
                turnIndicator.TurnLeft();
                break;
            case (int)TurnIndex.Straight:
                turnIndicator.GoStraight();
                break;
            case (int)TurnIndex.RightTurn:
                turnIndicator.TurnRight();
                break;
            default:
                break;
        }
	}