/// <summary>
 /// Sends a training request for a version of a specified LUIS app. This POST
 /// request initiates a request asynchronously. To determine whether the
 /// training request is successful, submit a GET request to get training
 /// status. Note: The application version is not fully trained unless all the
 /// models (intents and entities) are trained successfully or are up to date.
 /// To verify training success, get the training status at least once after
 /// training is complete.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='azureRegion'>
 /// Supported Azure regions for Cognitive Services endpoints. Possible values
 /// include: 'westus', 'westeurope', 'southeastasia', 'eastus2',
 /// 'westcentralus', 'westus2', 'eastus', 'southcentralus', 'northeurope',
 /// 'eastasia', 'australiaeast', 'brazilsouth', 'virginia'
 /// </param>
 /// <param name='azureCloud'>
 /// Supported Azure Clouds for Cognitive Services endpoints. Possible values
 /// include: 'com', 'us'
 /// </param>
 /// <param name='appId'>
 /// The application ID.
 /// </param>
 /// <param name='versionId'>
 /// The version ID.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <EnqueueTrainingResponse> TrainVersionAsync(this ITrain operations, AzureRegions azureRegion, AzureClouds azureCloud, System.Guid appId, string versionId, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.TrainVersionWithHttpMessagesAsync(azureRegion, azureCloud, appId, versionId, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Esempio n. 2
0
            internal override void MakeMove(
                PlayerEntity player,
                long tileId,
                ITrain train)
            {
                var tile = player
                           .Hand
                           .First(t => t.Id == tileId);

                var openDoubleIds = Games
                                    .Get(player.gameId)
                                    .GetOpenDoubleTileIds()
                                    .ToArray();

                if (openDoubleIds.Any() &&
                    !Games
                    .Get(player.gameId)
                    .GetPlayedTile(openDoubleIds.First())
                    .IsMatch(tile))
                {
                    throw new ApplicationException($"Illegal move. Must play on first present open double which is '{Games.Get(player.gameId).GetPlayedTile(openDoubleIds.First())}'. The played tile '{tile}' is not a match.");
                }

                train.AddTile(
                    tile,
                    player.Id);
                player.Hand =
                    new HashSet <DominoTileEntity>(
                        player.Hand.Where(t => t.Id != tile.Id));
            }
        public static int SaveNetwork(ITrain learnedNetwork)
        {
            if (learnedNetwork == null)
            {
                MessageBox.Show("Nie ma sieci neuronowej do zapisania");
                return(-1);
            }


            SaveFileDialog save = new SaveFileDialog();

            save.FileName         = "NeuralNetwork"; // Default file name
            save.DefaultExt       = ".ser";          // Default file extension
            save.Title            = "Save As...";
            save.Filter           = "Serialized File (*.ser)|*.ser";
            save.RestoreDirectory = true;
            save.InitialDirectory = System.Reflection.Assembly.GetExecutingAssembly().Location;

            Nullable <bool> result = save.ShowDialog();

            if (result == true)
            {
                string filename = save.FileName;
                Encog.Util.SerializeObject.Save(filename, learnedNetwork);
                //FileStream fs = new FileStream(filename, FileMode.Create);
                //BinaryFormatter bf = new BinaryFormatter();

                //bf.Serialize(fs, learnedNetwork);
                //BinaryWriter w = new BinaryWriter(fs);
                //w.Close();
                //fs.Close();
            }
            return(1);
        }
Esempio n. 4
0
        /// <summary>
        /// Train the network, using the specified training algorithm, and send the
        /// output to the console.
        /// </summary>
        /// <param name="train">The training method to use.</param>
        /// <param name="network">The network to train.</param>
        /// <param name="trainingSet">The training set.</param>
        /// <param name="minutes">The number of minutes to train for.</param>
        public static void TrainConsole(ITrain train,
                                        BasicNetwork network, INeuralDataSet trainingSet,
                                        int minutes)
        {
            int  epoch = 1;
            long remaining;

            Console.WriteLine("Beginning training...");
            long start = Environment.TickCount;

            do
            {
                train.Iteration();

                long current = Environment.TickCount;
                long elapsed = (current - start) / 1000;
                remaining = minutes - elapsed / 60;

                Console.WriteLine("Iteration #" + Format.FormatInteger(epoch)
                                  + " Error:" + Format.FormatPercent(train.Error)
                                  + " elapsed time = " + Format.FormatTimeSpan((int)elapsed)
                                  + " time left = "
                                  + Format.FormatTimeSpan((int)remaining * 60));
                epoch++;
            } while (remaining > 0 && !train.TrainingDone);
            train.FinishTraining();
        }
 /// <summary>
 /// Gets the training status of all models (intents and entities) for the
 /// specified LUIS app. You must call the train API to train the LUIS app
 /// before you call this API to get training status. "appID" specifies the LUIS
 /// app ID. "versionId" specifies the version number of the LUIS app. For
 /// example, "0.1".
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='azureRegion'>
 /// Supported Azure regions for Cognitive Services endpoints. Possible values
 /// include: 'westus', 'westeurope', 'southeastasia', 'eastus2',
 /// 'westcentralus', 'westus2', 'eastus', 'southcentralus', 'northeurope',
 /// 'eastasia', 'australiaeast', 'brazilsouth', 'virginia'
 /// </param>
 /// <param name='azureCloud'>
 /// Supported Azure Clouds for Cognitive Services endpoints. Possible values
 /// include: 'com', 'us'
 /// </param>
 /// <param name='appId'>
 /// The application ID.
 /// </param>
 /// <param name='versionId'>
 /// The version ID.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <IList <ModelTrainingInfo> > GetStatusAsync(this ITrain operations, AzureRegions azureRegion, AzureClouds azureCloud, System.Guid appId, string versionId, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.GetStatusWithHttpMessagesAsync(azureRegion, azureCloud, appId, versionId, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Esempio n. 6
0
        public void TrainGraphicConstructorTest()
        {
            ITrain       train  = null; // TODO: Initialize to an appropriate value
            TrainGraphic target = new TrainGraphic(train);

            Assert.Inconclusive("TODO: Implement code to verify target");
        }
        public void T4_trains_can_be_found_by_name()
        {
            ICity s = CityFactory.CreateCity("Paris");

            ICompany c1 = s.AddCompany("Transports de Lyon");
            ICompany c2 = s.AddCompany("Transports de Marseille");

            ITrain t1 = c1.AddTrain("RER1");

            c1.FindTrain("RER1").Should().BeSameAs(t1);
            c2.FindTrain("RER1").Should().BeNull();


            ITrain t2 = c2.AddTrain("RER1");

            c2.FindTrain("RER1").Should().BeSameAs(t2);
            c1.FindTrain("RER1").Should().NotBeSameAs(t2);


            ITrain t3 = c1.AddTrain("RER2");
            ITrain t4 = c1.AddTrain("RER3");
            ITrain t5 = c1.AddTrain("RER4");

            c1.FindTrain("RER2").Should().BeSameAs(t3);
            c1.FindTrain("RER3").Should().BeSameAs(t4);
            c1.FindTrain("RER4").Should().BeSameAs(t5);

            c2.FindTrain("RER2").Should().BeNull();
            c2.FindTrain("RER3").Should().BeNull();
            c2.FindTrain("RER4").Should().BeNull();
        }
Esempio n. 8
0
        private void TrainNetwork(DateTime trainFrom, DateTime trainTo, TrainingStatus status)
        {
            if (_input == null || _ideal == null)
            {
                CreateTrainingSets(trainFrom, trainTo);
            }
            _trainThread = Thread.CurrentThread;
            int    epoch = 1;
            ITrain train = null;

            try
            {
                var trainSet = new BasicNeuralDataSet(_input, _ideal);
                train = new ResilientPropagation(_network, trainSet);
                double error;
                do
                {
                    train.Iteration();
                    error = train.Error;
                    status?.Invoke(epoch, error, TrainingAlgorithm.Resilient);
                    epoch++;
                } while (error > MaxError);
            }
            catch (ThreadAbortException) { _trainThread = null; }
            finally
            {
                train?.FinishTraining();
            }
            _trainThread = null;
        }
 /// <summary>
 /// Create a training status utility.
 /// </summary>
 /// <param name="cloud">The cloud to report to.</param>
 /// <param name="train">The training object being used.</param>
 public TrainingStatusUtility(EncogCloud cloud, ITrain train)
 {
     this.cloud = cloud;
     this.train = train;
     this.lastUpdate = 0;
     this.iteration = 0;
 }
 /// <summary>
 /// Create a training status utility.
 /// </summary>
 /// <param name="cloud">The cloud to report to.</param>
 /// <param name="train">The training object being used.</param>
 public TrainingStatusUtility(EncogCloud cloud, ITrain train)
 {
     this.cloud      = cloud;
     this.train      = train;
     this.lastUpdate = 0;
     this.iteration  = 0;
 }
Esempio n. 11
0
        public string?GetTrack(ITrain train, Station sta, TrainDirection dir, ArrDep timetableEntry, TrackQuery track)
        {
            var path = new TrainPathData(train.ParentTimetable, train);

            if (!path.ContainsStation(sta))
            {
                return(null);
            }

            var exitRoute = path.GetExitRoute(sta);

            if (track == TrackQuery.Departure)
            {
                return(Fallback(timetableEntry.DepartureTrack,
                                Fallback(timetableEntry.ArrivalTrack,
                                         Fallback(dir == TrainDirection.ti
                            ? sta.DefaultTrackRight.GetValue(exitRoute)
                            : sta.DefaultTrackLeft.GetValue(exitRoute), ""))));
            }

            return(Fallback(timetableEntry.ArrivalTrack,
                            Fallback(timetableEntry.DepartureTrack,
                                     Fallback(dir == TrainDirection.ti
                        ? sta.DefaultTrackRight.GetValue(exitRoute)
                        : sta.DefaultTrackLeft.GetValue(exitRoute), ""))));
        }
        public static ITrain LoadNetwork()
        {
            ITrain network = null;

            OpenFileDialog open = new OpenFileDialog();

            open.Title  = "Open File...";
            open.Filter = "Binary File (*.bin)|*.bin";
            if (open.ShowDialog() == true)
            {
                FileStream      fs = new FileStream(open.FileName, FileMode.Open);
                BinaryFormatter bf = new BinaryFormatter();
                BinaryReader    br = new BinaryReader(fs);

                var _varNetw = (ITrain)bf.Deserialize(fs);
                network = _varNetw;

                fs.Close();
                br.Close();
            }
            else
            {
                MessageBox.Show("Nie wybrano pliku !");
            }
            return(network);
        }
        public void T4_trains_are_created_by_companies_and_have_a_unique_name()
        {
            ICity    s = CityFactory.CreateCity("Paris");
            ICompany c = s.AddCompany("SNCF");

            Action a = () => c.AddTrain(null);

            a.ShouldThrow <ArgumentException>();


            ITrain p1 = c.AddTrain("train1");

            p1.Company.Should().BeSameAs(c);
            p1.Name.Should().BeEquivalentTo("train1");
            p1.Assignment.Should().BeNull();
            Action a1 = () => c.AddTrain("train1");

            a1.ShouldThrow <ArgumentException>();


            ITrain p2 = c.AddTrain("train2");

            p2.Company.Should().BeSameAs(c);
            p2.Name.Should().BeEquivalentTo("train2");
            p2.Assignment.Should().BeNull();
            Action a2 = () => c.AddTrain("train2");

            a2.ShouldThrow <ArgumentException>();

            p1.GetType().GetProperty("Name").GetSetMethod().Should().BeNull("Train.Name must NOT be writeable.");
            p1.GetType().GetProperty("Assignment").GetSetMethod().Should().BeNull("Train.Assignment must NOT be writeable.");
            p1.GetType().GetProperty("City").GetSetMethod().Should().BeNull("Train.City must NOT be writeable.");
            p1.GetType().GetConstructors(BindingFlags.Instance | BindingFlags.Public).Should().BeEmpty("Train must not expose any public constructors.");
        }
Esempio n. 14
0
 public bool IsIntersection(ITrain train)
 {
     return(
         train.arrival >= this.arrival &&
         this.departure <= train.departure &&
         train.arrival <= this.departure
         );
 }
Esempio n. 15
0
 /// <summary>
 /// Initialize this strategy.
 /// </summary>
 /// <param name="train">The training algorithm.</param>
 public void Init(ITrain train)
 {
     this.train           = train;
     this.setter          = (IMomentum)train;
     this.ready           = false;
     this.setter.Momentum = 0.0;
     this.currentMomentum = 0;
 }
Esempio n. 16
0
        /// <summary>
        /// Train, using the specified training method, display progress to a dialog
        /// box.
        /// </summary>
        /// <param name="train">The training method to use.</param>
        /// <param name="network">The network to train.</param>
        /// <param name="trainingSet">The training set to use.</param>
        public static void TrainDialog(ITrain train,
                                       BasicNetwork network, INeuralDataSet trainingSet)
        {
            TrainingDialog dialog = new TrainingDialog();

            dialog.Train = train;
            dialog.ShowDialog();
        }
Esempio n. 17
0
 public static void runLine(ITrain train, int n)
 {
     train.setLine(n);
     train.acceptPassengers();
     train.checkTrainTicket("train");
     train.drive();
     train.stop();
 }
Esempio n. 18
0
 /// <summary>
 /// Returns if a given train matches this pattern.
 /// </summary>
 /// <exception cref="InvalidOperationException">The type of this FilterRule is "StationType" (#). </exception>
 public bool Matches(ITrain t)
 {
     if (FilterType == FilterType.StationType)
     {
         throw new InvalidOperationException("Cannot apply StationType filter to train!");
     }
     return(Matches(t.TName));
 }
Esempio n. 19
0
 private void LoadNeural_Click(object sender, RoutedEventArgs e)
 {
     network = InputHelper.LoadNetwork();
     if (network != null)
     {
         Console.WriteLine("wczytano z binarki " + faces.Count + " danych");
     }
 }
Esempio n. 20
0
        public void BlinkTest()
        {
            ITrain       train  = null;                    // TODO: Initialize to an appropriate value
            TrainGraphic target = new TrainGraphic(train); // TODO: Initialize to an appropriate value

            target.Blink();
            Assert.Inconclusive("A method that does not return a value cannot be verified.");
        }
Esempio n. 21
0
 public static void ExecuteProgram(ITrain train)
 {
     RemoteControl remoteControl = new RemoteControl();
     train.Control = remoteControl;
     train.Start();
     train.Stop();
     //train.Control = null;     // memory leak
 }
Esempio n. 22
0
        public void SetTrainInfoTest1()
        {
            InfoPanel target = new InfoPanel(); // TODO: Initialize to an appropriate value
            ITrain    train  = null;            // TODO: Initialize to an appropriate value

            target.SetTrainInfo(train);
            Assert.Inconclusive("A method that does not return a value cannot be verified.");
        }
        private static ICity CreateTestCity()
        {
            ICity    city    = CityFactory.CreateCity("Paris");
            ICompany company = city.AddCompany("ITICORP");
            ITrain   train   = company.AddTrain("TGV");

            return(city);
        }
Esempio n. 24
0
 public DataElement(ITrain tra, Station sta, ArrDep arrDep)
 {
     Train   = tra;
     ArrDeps = new Dictionary <Station, ArrDep>(1)
     {
         [sta] = arrDep
     };
     Station = sta;
 }
Esempio n. 25
0
 // METHOD: TrainController
 //--------------------------------------------------------------------------------------
 /// <summary>
 /// Primary constructor
 /// </summary>
 ///
 /// <param name="myTrain">The train associated with this controller</param>
 //--------------------------------------------------------------------------------------
 public TrainController(ITrain myTrain)
 {
     this.m_myTrain            = myTrain;
     this.m_currentState       = m_myTrain.GetState();
     this.m_trainID            = m_currentState.TrainID;
     this.m_currentBlock       = m_currentState.CurrentBlock;
     this.m_passengerGenerator = new Random((int)DateTime.Now.Ticks);
     this.ManualSpeed          = -1;
 }
Esempio n. 26
0
        public void RemoveTrainFromListTest_null()
        {
            ITrain train    = null;
            bool   expected = false;
            bool   actual;

            actual = m_ctcAccessor.RemoveTrainFromList(train);
            Assert.AreEqual(expected, actual);
        }
Esempio n. 27
0
 // METHOD: TrainController
 //--------------------------------------------------------------------------------------
 /// <summary>
 /// Primary constructor
 /// </summary>
 /// 
 /// <param name="myTrain">The train associated with this controller</param>
 //--------------------------------------------------------------------------------------
 public TrainController(ITrain myTrain)
 {
     this.m_myTrain = myTrain;
     this.m_currentState = m_myTrain.GetState();
     this.m_trainID = m_currentState.TrainID;
     this.m_currentBlock = m_currentState.CurrentBlock;
     this.m_passengerGenerator = new Random((int)DateTime.Now.Ticks);
     this.ManualSpeed = -1;
 }
Esempio n. 28
0
        /// <summary>
        /// Create a new linked train instance.
        /// </summary>
        /// <param name="link">Parent link object.</param>
        /// <param name="countingIndex">The counting index of this train, relative to <paramref name="link"/>.</param>
        public LinkedTrain(TrainLink link, int countingIndex) : base(link.ParentTrain.XMLEntity.XName, link.ParentTimetable)
        {
            this.link          = link;
            this.countingIndex = countingIndex;
            baseTrain          = link.ParentTrain;
            link._InternalInjectLinkedTrain(this, countingIndex);

            link.Apply(true, true);
        }
Esempio n. 29
0
        private bool GetTrainDirection(ITrain train)
        {
            if (tt.Type == TimetableType.Linear)
            {
                return(train.Direction == TrainDirection.ta);
            }

            return(GetTrains(TrainDirection.ta).Contains(train));
        }
Esempio n. 30
0
        public static void ExecuteProgram(ITrain train)
        {
            RemoteControl remoteControl = new RemoteControl();

            train.Control = remoteControl;
            train.Start();
            train.Stop();
            //train.Control = null;     // memory leak
        }
        private static ICity CreateTestCity()
        {
            ICity    city = CityFactory.CreateCity("First City");
            ICompany c1   = city.AddCompany("C01");
            ITrain   t1   = c1.AddTrain("T01");
            ICompany c2   = city.AddCompany("C02");
            ITrain   t2   = c2.AddTrain("T02");

            return(city);
        }
Esempio n. 32
0
 public bool CanArrive(ITrain train)
 {
     if (_isPlatformFree)
     {
         _isPlatformFree = false;
         return(true);
     }
     this._trainQueue.Enqueue(train);
     return(false);
 }
Esempio n. 33
0
 /// <summary>
 /// Create a hybrid strategy.
 /// </summary>
 /// <param name="altTrain">The alternate training algorithm.</param>
 /// <param name="minImprovement">The minimum improvement to switch algorithms.</param>
 /// <param name="tolerateMinImprovement">The number of cycles to tolerate the
 /// minimum improvement for.</param>
 /// <param name="alternateCycles">How many cycles should the alternate
 /// training algorithm be used for.</param>
 public HybridStrategy(ITrain altTrain, double minImprovement,
                       int tolerateMinImprovement, int alternateCycles)
 {
     this.altTrain               = altTrain;
     this.ready                  = false;
     this.lastHybrid             = 0;
     this.minImprovement         = minImprovement;
     this.tolerateMinImprovement = tolerateMinImprovement;
     this.alternateCycles        = alternateCycles;
 }
Esempio n. 34
0
 public TrainForm(ITrain train)
 {
     InitializeComponent();
     this.train = train;
     // Add the event and the event handler for the method that will process the timer event to the timer.
     clock.Tick += UpdateState;
     // Set the timer interval to 100 ms.
     clock.Interval = 100;
     clock.Start();
 }
Esempio n. 35
0
        // METHOD: TrainOperator
        //--------------------------------------------------------------------------------------
        /// <summary>
        /// Secondary constructor, to be used by the CTC
        /// </summary>
        /// 
        /// <param name="myTrain">The train associated with this GUI</param>
        /// <param name="myTrainController">The train controller associated with this GUI</param>
        //--------------------------------------------------------------------------------------
        public TrainOperator(ITrain myTrain, TrainController myTrainController)
        {
            InitializeComponent();
            m_isDemo = false;
            this.m_myTrain = myTrain;
            this.m_myTrainState = m_myTrain.GetState();
            this.m_myTrainController = myTrainController;

            engineFailure.Enabled = false;
            brakeFailure.Enabled = false;
            powerFailure.Enabled = false;
            circuitFailure.Enabled = false;
        }
        /// <summary>
        /// Construct a cross validation trainer. 
        /// </summary>
        /// <param name="train">The training.</param>
        /// <param name="k">The number of folds.</param>
        public CrossValidationKFold(ITrain train, int k)
            : base(train.Network, (FoldedDataSet)train.Training)
        {
            this.train = train;
            Folded.Fold(k);

            this.flatNetwork = train.Network.Structure.Flat;

            this.networks = new NetworkFold[k];
            for (int i = 0; i < networks.Length; i++)
            {
                this.networks[i] = new NetworkFold(flatNetwork);
            }

        }
Esempio n. 37
0
        /// <summary>
        /// Sets the text information for a train
        /// </summary>
        /// <param name="train">Train</param>
        public void SetTrainInfo(ITrain train)
        {
            if (train == null) return;

            TrainState state = train.GetState();

            if (state == null) return;

            m_displayedBlock = null;
            m_displayedTrain = train;

            Dictionary<string, string> info = new Dictionary<string, string>();

            info.Add("Number of cars:", state.Cars.ToString());
            info.Add("Crew members:", state.Crew.ToString());
            info.Add("Direction:", state.Direction.ToString());
            info.Add("Door Status:", state.Doors.ToString());
            info.Add("Light Status:", state.Lights.ToString());
            info.Add("Mass:", state.Mass.ToString());
            info.Add("Passengers:", state.Passengers.ToString());
            info.Add("Speed:", string.Format("{0:0.00} {1}", state.Speed.ToString(), KPH));
            info.Add("Temperature:", state.Temperature.ToString());
            info.Add("Position:", string.Format("{0:0.00} , {1:0.00}", state.X.ToString(), state.Y.ToString()));

            if (state.TrainID != null)
            {
                SetInfo(state.TrainID.ToString(), info);
            }
            else
            {
                SetInfo(UNKNOWN_TEXT, info);
            }
        }
Esempio n. 38
0
        // METHOD: CreateTrain_Click
        //--------------------------------------------------------------------------------------
        /// <summary>
        /// Start the GUI, and create a train and train controller if in a demo
        /// </summary>
        /// 
        /// <param name="sender">Sender</param>
        /// <param name="e">Event Arguments</param>
        //--------------------------------------------------------------------------------------
        private void CreateTrain_Click(object sender, EventArgs e)
        {
            if (m_isDemo)
            {
                m_startingBlock = new TrackBlock("Block1", TrackOrientation.EastWest, new Point(0, 0), 1650, 0, 0, false, false, 70, TrackAllowedDirection.Both, false, "controller1", "controller2", "Block0", "Block2");
                m_startingBlock.NextBlock = new TrackBlock("Block2", TrackOrientation.EastWest, new Point(1650, 0), 50, 0, 0, true, false, 70, TrackAllowedDirection.Both, false, "controller1", "controller2", "Block1", "Block3");
                m_startingBlock.Authority = new BlockAuthority(70, 3);
                m_startingBlock.NextBlock.Authority = new BlockAuthority(70, 2);
                m_startingBlock.NextBlock.NextBlock = new TrackBlock("Block3", TrackOrientation.EastWest, new Point(1700, 0), 1000, 0, 0, true, false, 70, TrackAllowedDirection.Both, false, "controller1", "controller2", "Block2", "Block4");
                m_startingBlock.NextBlock.NextBlock.NextBlock = new TrackBlock("Block4", TrackOrientation.EastWest, new Point(2700, 0), 100, 0, 0, false, false, 70, TrackAllowedDirection.Both, false, "controller1", "controller2", "Block3", "Block5");
                m_startingBlock.NextBlock.NextBlock.NextBlock.NextBlock = new TrackBlock("Block5", TrackOrientation.EastWest, new Point(2800, 0), 100, 0, 0, false, false, 70, TrackAllowedDirection.Both, false, "controller1", "controller2", "Block4", "Block6");
                m_startingBlock.NextBlock.NextBlock.NextBlock.NextBlock.NextBlock = new TrackBlock("Block6", TrackOrientation.EastWest, new Point(2800, 0), 100, 0, 0, false, false, 70, TrackAllowedDirection.Both, false, "controller1", "controller2", "Block5", "Block7");
                m_startingBlock.NextBlock.NextBlock.Authority = new BlockAuthority(70, 1);

                m_startingBlock.NextBlock.NextBlock.NextBlock.Authority = new BlockAuthority(40, 0);
                m_startingBlock.NextBlock.NextBlock.NextBlock.NextBlock.Authority = new BlockAuthority(40, 0);
                m_startingBlock.NextBlock.NextBlock.NextBlock.NextBlock.NextBlock.Authority = new BlockAuthority(40, 0);

                m_startingBlock.Transponder = new Transponder("SHADYSIDE", 1);
                m_startingBlock.NextBlock.Transponder = new Transponder("SHADYSIDE", 0);

                m_myTrain = new TrainLib.Train("train1", m_startingBlock, Direction.East);
                m_myTrainState = m_myTrain.GetState();
                m_myTrainController = new TrainController(m_myTrain);
                m_myTrainController.Schedule = GetRedlineSchedule();

                Timer updateTimer = new Timer();
                updateTimer.Tick += new EventHandler(Update);
                updateTimer.Interval = 40;
                updateTimer.Enabled = true;
                updateTimer.Start();
            }

            m_myTimer = new Timer();
            m_myTimer.Tick += new EventHandler(UpdateDisplay);
            m_myTimer.Interval = 500;
            m_myTimer.Enabled = true;
            m_myTimer.Start();
        }
        /// <summary>
        /// Initialize this strategy.
        /// </summary>
        /// <param name="train">The training algorithm.</param>
        public void Init(ITrain train)
        {
            this.train = train;
            this.ready = false;
            this.setter = (ILearningRate)train;
            this.trainingSize = DetermineTrainingSize();
            this.currentLearningRate = 1.0 / this.trainingSize;
#if logging
            if (this.logger.IsInfoEnabled)
            {
                this.logger.Info("Starting learning rate: " +
                        this.currentLearningRate);
            }
#endif
            this.setter.LearningRate = this.currentLearningRate;
        }
Esempio n. 40
0
 /// <summary>
 /// Initialize this strategy.
 /// </summary>
 /// <param name="train">The training algorithm.</param>
 public void Init(ITrain train)
 {
     this.train = train;
     this.ready = false;
 }
 /// <inheritdoc/>
 public void Init(ITrain train)
 {
     this.started = true;
     this.watch.Start();
 }
Esempio n. 42
0
 /// <summary>
 /// Simulates a train pickup failure
 /// </summary>
 /// <param name="train">Train to simulate on</param>
 /// <param name="failure">True to invoke failure or false to clear it</param>
 public void SimulatePickupFailure(ITrain train, bool failure)
 {
     if (train != null)
     {
         try
         {
             m_log.LogInfoFormat("Setting signal pickup failure of train {0}", failure);
             train.SetSignalPickupFailure(failure);
         }
         catch (Exception)
         {
             m_log.LogError("Error in setting signal pickup failure");
         }
     }
 }
Esempio n. 43
0
 /// <summary>
 /// Create a hybrid strategy.
 /// </summary>
 /// <param name="altTrain">The alternate training algorithm.</param>
 /// <param name="minImprovement">The minimum improvement to switch algorithms.</param>
 /// <param name="tolerateMinImprovement">The number of cycles to tolerate the 
 /// minimum improvement for.</param>
 /// <param name="alternateCycles">How many cycles should the alternate 
 /// training algorithm be used for.</param>
 public HybridStrategy(ITrain altTrain, double minImprovement,
          int tolerateMinImprovement, int alternateCycles)
 {
     this.altTrain = altTrain;
     this.ready = false;
     this.lastHybrid = 0;
     this.minImprovement = minImprovement;
     this.tolerateMinImprovement = tolerateMinImprovement;
     this.alternateCycles = alternateCycles;
 }
Esempio n. 44
0
        /// <summary>
        /// Train to a specific error, using the specified training method, send the
        /// output to the console.
        /// </summary>
        /// <param name="train">The training method.</param>
        /// <param name="trainingSet">The training set to use.</param>
        /// <param name="error">The desired error level.</param>
        public static void TrainToError(ITrain train,
                INeuralDataSet trainingSet,
                double error)
        {

            int epoch = 1;

            Console.WriteLine("Beginning training...");

            do
            {
                train.Iteration();

                Console.WriteLine("Iteration #" + Format.FormatInteger(epoch)
                        + " Error:" + Format.FormatPercent(train.Error)
                        + " Target Error: " + Format.FormatPercent(error));
                epoch++;
            } while (train.Error > error && !train.TrainingDone);
            train.FinishTraining();
        }
Esempio n. 45
0
        /// <summary>
        /// Event handler for the track block clicked event
        /// </summary>
        /// <param name="b">Track block that was clicked</param>
        private void OnTrackBlockClicked(TrackBlock b)
        {
            m_log.LogInfo("Track block was clicked");
            m_selectedTrain = null;
            m_selectedTrackBlock = b;

            if (m_trainGUI != null)
            {
                m_trainGUI.Close();
                m_trainGUI = null;
            }

            if (m_simulatorWindow == null || m_simulatorWindow.IsDisposed || m_simulatorWindow.Disposing)
            {
                m_simulatorWindow = new SimulatorWindow(); //User may have closed the simulator
                m_simulatorWindow.Show();
            }

            m_simulatorWindow.SetSelectedTrackBlock(m_selectedTrackBlock);

            if (b != null)
            {
                bool trainYard = false;
                if (b.HasTransponder)
                {
                    if (!string.IsNullOrEmpty(b.Transponder.StationName))
                    {
                        if (b.Transponder.StationName.Contains(Constants.TRAINYARD) && b.Transponder.DistanceToStation == 0)
                        {
                            //This is a train yard, handle it specially
                            infoPanel.SetTrainYardInfo(b);
                            commandPanel.ShowTrainYardCommands();
                            trainYard = true;
                        }
                    }
                }

                if (!trainYard)
                {
                    //Normal track block
                    infoPanel.SetTrackBlockInfo(b);
                    commandPanel.ShowTrackBlockCommands(b);
                }
            }

            CloseOpenPopups();
        }
Esempio n. 46
0
 /// <summary>
 /// Train, using the specified training method, display progress to a dialog
 /// box.
 /// </summary>
 /// <param name="train">The training method to use.</param>
 /// <param name="network">The network to train.</param>
 /// <param name="trainingSet">The training set to use.</param>
 public static void TrainDialog(ITrain train,
         BasicNetwork network, INeuralDataSet trainingSet)
 {
     TrainingDialog dialog = new TrainingDialog();
     dialog.Train = train;
     dialog.ShowDialog();
 }
 /// <summary>
 /// Initialize this strategy.
 /// </summary>
 /// <param name="train">The training algorithm.</param>
 public void Init(ITrain train)
 {
     this.train = train;
     this.shouldStop = false;
     this.ready = false;
 }
 /// <summary>
 /// Initialize this strategy.
 /// </summary>
 /// <param name="train">The training algorithm.</param>
 public void Init(ITrain train)
 {
     this.train = train;
 }
Esempio n. 49
0
        /// <summary>
        /// Initialize this strategy.
        /// </summary>
        /// <param name="train">The training algorithm.</param>
        public void Init(ITrain train)
        {
            this.train = train;
            this.setter = (IMomentum)train;
            this.ready = false;
            this.setter.Momentum = 0.0;
            this.currentMomentum = 0;

        }
Esempio n. 50
0
 /// <summary>
 /// Construct a hybrid strategy with the default minimum improvement
 /// and toleration cycles.
 /// </summary>
 /// <param name="altTrain">The alternative training strategy.</param>
 public HybridStrategy(ITrain altTrain)
     : this(altTrain, HybridStrategy.DEFAULT_MIN_IMPROVEMENT,
         HybridStrategy.DEFAULT_TOLERATE_CYCLES,
         HybridStrategy.DEFAULT_ALTERNATE_CYCLES)
 {
 }
Esempio n. 51
0
        /// <summary>
        /// Sets the text information for a track block
        /// </summary>
        /// <param name="block">Track block</param>
        public void SetTrackBlockInfo(TrackBlock block)
        {
            if (block == null) return;

            m_displayedBlock = block;
            m_displayedTrain = null;

            Dictionary<string, string> info = new Dictionary<string, string>();
            if (block.Authority != null)
            {
                info.Add("Authority:", block.Authority.Authority.ToString());
            }

            if (block.Authority != null)
            {
                info.Add("CTC Speed Limit:", block.Authority.SpeedLimitKPH.ToString() + " " + KPH);
            }

            info.Add("Static Speed Limit:", block.StaticSpeedLimit.ToString() + " " + KPH);

            if (block.Status.TrainPresent)
            {
                info.Add("Train present:", "yes");
            }
            else
            {
                info.Add("Train present:", "no");
            }

            info.Add("Signal:", block.Status.SignalState.ToString());

            info.Add("Start Elevation:", block.StartElevationMeters.ToString() + " " + METERS);

            info.Add("End Elevation", block.EndElevationMeters.ToString() + " " + METERS);

            info.Add("Grade", block.Grade.ToString() + "%");

            info.Add("Length:", block.LengthMeters.ToString() + " " + METERS);

            if (block.HasTunnel)
            {
                info.Add("Has Tunnel:", "yes");
            }
            else
            {
                info.Add("Has Tunnel:", "no");
            }

            if (block.RailroadCrossing)
            {
                info.Add("Has RR Crossing:", "yes");
            }
            else
            {
                info.Add("Has RR Crossing:", "no");
            }

            if (block.Transponder != null) //Could use block.HasTransponder property, but check for null to be on the safe side...
            {
                if (block.Transponder.DistanceToStation != 0)
                {
                    info.Add("Transponder:", block.Transponder.StationName + "in " + block.Transponder.DistanceToStation.ToString() + " block(s)");
                }
                else
                {
                    info.Add("Transponder:", "At " + block.Transponder.StationName);
                }
            }
            else
            {
                info.Add("Transponder:", "none");
            }

            KeyValuePair<string, string> failure = GetBlockFailureStateString(block);
            info.Add(failure.Key, failure.Value);

            #if DEBUG
            info.Add("Start Point", block.StartPoint.X + ", " + block.StartPoint.Y);
            info.Add("End Point", block.EndPoint.X + ", " + block.EndPoint.Y);
            #endif
            SetInfo(block.Name, info);
        }
 /// <inheritdoc/>
 public void Init(ITrain train)
 {
     this.train = train;
     this.started = false;
 }
Esempio n. 53
0
        /// <summary>
        /// Gets a reference to the train controller of the train
        /// </summary>
        /// <param name="train"></param>
        /// <returns></returns>
        public TrainController GetTrainController(ITrain train)
        {
            TrainController controller = null;
            if (m_trainControllerTable.ContainsKey(train))
            {
                controller = m_trainControllerTable[train];
            }

            return controller;
        }
Esempio n. 54
0
 /// <summary>
 /// Displays info about the train yard
 /// </summary>
 /// <param name="b">Track block</param>
 public void SetTrainYardInfo(TrackBlock b)
 {
     //Just show the block name
     m_displayedTrain = null;
     m_displayedBlock = b;
     SetInfo(b.Name, null);
 }
Esempio n. 55
0
        /// <summary>
        /// Sets the text information for a train
        /// </summary>
        /// <param name="train">Train</param>
        public void SetTrainInfo(ITrain train)
        {
            if (train == null) return;

            TrainState state = train.GetState();

            if (state == null) return;

            Dictionary<string, string> info = new Dictionary<string, string>();

            info.Add("Number of cars:", state.Cars.ToString());
            info.Add("Crew members:", state.Crew.ToString());
            info.Add("Direction:", state.Direction.ToString());
            info.Add("Door Status:", state.Doors.ToString());
            info.Add("Light Status:", state.Lights.ToString());
            info.Add("Mass:", state.Mass.ToString());
            info.Add("Passengers:", state.Passengers.ToString());
            info.Add("Speed:", state.Speed.ToString() + " " + KPH);
            info.Add("Temperature:", state.Temperature.ToString());
            info.Add("Position:", state.X.ToString() + ", " + state.Y.ToString());

            SetInfo(state.TrainID.ToString(), info);
        }
Esempio n. 56
0
        /// <summary>
        /// Event handler for the train clicked event
        /// </summary>
        /// <param name="train">Train that was clicked</param>
        private void OnTrainClicked(ITrain train)
        {
            m_log.LogInfo("Train was clicked");
            m_selectedTrackBlock = null;
            m_selectedTrain = train;
            infoPanel.SetTrainInfo(train);
            commandPanel.ShowTrainCommands();

            if (m_trainGUI != null)
            {
                m_trainGUI.Close();
            }

            TrainController trainController = Simulator.GetSimulator().GetTrainController(train);
            if (trainController != null)
            {
                m_trainGUI = new TrainOperator(train, trainController);
                m_trainGUI.Show();
            }

            CloseOpenPopups();
        }
Esempio n. 57
0
        /// <summary>
        /// Train the network, using the specified training algorithm, and send the
        /// output to the console.
        /// </summary>
        /// <param name="train">The training method to use.</param>
        /// <param name="network">The network to train.</param>
        /// <param name="trainingSet">The training set.</param>
        /// <param name="minutes">The number of minutes to train for.</param>
        public static void TrainConsole(ITrain train,
                 BasicNetwork network, INeuralDataSet trainingSet,
                 int minutes)
        {

            int epoch = 1;
            long remaining;

            Console.WriteLine("Beginning training...");
            long start = Environment.TickCount;
            do
            {
                train.Iteration();

                long current = Environment.TickCount;
                long elapsed = (current - start) / 1000;
                remaining = minutes - elapsed / 60;

                Console.WriteLine("Iteration #" + Format.FormatInteger(epoch)
                        + " Error:" + Format.FormatPercent(train.Error)
                        + " elapsed time = " + Format.FormatTimeSpan((int)elapsed)
                        + " time left = "
                        + Format.FormatTimeSpan((int)remaining * 60));
                epoch++;
            } while (remaining > 0 && !train.TrainingDone);
            train.FinishTraining();
        }
Esempio n. 58
0
 /// <summary>
 /// Default constructor
 /// </summary>
 public TrainGraphic(ITrain train)
 {
     InitializeComponent();
     m_train = train;
 }