public Listening(Gateway.Event.IMediator eventMediator, ITransition transition, Packet.Endpoint.IFactory packetEndpointFactory, Context.IListen context) { _eventMediator = eventMediator; _transition = transition; _packetEndpointFactory = packetEndpointFactory; _context = context; }
public IArc AddArc(IPlace place, ITransition transition) { IArc arc=new Arc(version++,place,transition); this.arcs.Add(arc); this.graph.AddEdge(arc); return arc; }
public Connecting(ITransition transition, Command.Endpoint.IFactory commandEndpointFactory, Context.IConnection context) { _transition = transition; _commandEndpointFactory = commandEndpointFactory; _context = context; }
public Factory(Gateway.Event.IMediator eventMediator, ITransition transition, Command.Endpoint.IFactory commandEndpointFactory, Packet.Endpoint.IFactory packetEndpointFactory) { _eventMediator = eventMediator; _transition = transition; _commandEndpointFactory = commandEndpointFactory; _packetEndpointFactory = packetEndpointFactory; }
public Arc(int id,ITransition transition,IPlace place) : base(id,transition,place) { this.place=place; this.transition=transition; this.isInputArc=false; }
public Arc(int id,IPlace place, ITransition transition) : base(id,place,transition) { this.place=place; this.transition=transition; this.isInputArc=true; }
public IArc AddArc(ITransition transition, IPlace place) { IArc arc = new Arc(this.version++, transition, place); this.arcs.Add(arc); this.graph.AddEdge(transition, place); return arc; }
public Arc(int id, ITransition transition, IPlace place) : base(id, transition, place) { this.annotation = new IdentityExpression(); this.place = place; this.transition = transition; this.isInputArc = false; }
void transitionManager1_AfterTransitionEnds(ITransition transition, System.EventArgs e) { if(!IsHandleCreated) return; var method = new MethodInvoker(() => { // bottomPanelBase1.Enabled = true; // var moduleControl = viewModel.SelectedModule as DevExpress.DevAV.Modules.BaseModuleControl; // if(moduleControl != null) moduleControl.OnTransitionCompleted(); }); if(InvokeRequired) BeginInvoke(method); else method(); }
private void BuildPageTransition() { var transition = new SlideTransition { Mode = SlideTransitionMode.SlideLeftFadeIn }; _pageTransition = transition.GetTransition(LayoutRoot); _pageTransition.Completed += (sender, args) => _pageTransition.Stop(); }
public void DoTransition(object newContent, ITransition transition) { if(newContent == null) { Children.Clear(); return; } UIElement view; if(ContentTemplate != null) { var template = ContentTemplate.LoadContent(); var fe = template as FrameworkElement; if(fe != null) fe.DataContext = newContent; view = template as UIElement; } else view = newContent as UIElement; if(view == null) return; if (Children.Contains(view)) { Children.Clear(); Children.Add(view); return; } if(Children.Count > 0) { if(transition.RequiresNewContentTopmost) { Children.Add(view); transition.BeginTransition(this, Children[0], view); } else { Children.Insert(0, view); transition.BeginTransition(this, Children[1], view); } } else { Children.Add(view); TransitionEnded(transition, null, view); } }
/// <summary> /// Initializes a new instance of the <see cref="TransitionMutableCore"/> class. /// </summary> /// <param name="transitionType"> /// The transition type. /// </param> public TransitionMutableCore(ITransition transitionType) : base(transitionType) { this._conditions = new List<ITextTypeWrapperMutableObject>(); this._targetStep = transitionType.TargetStep.Id; if (transitionType.Condition != null) { foreach (ITextTypeWrapper textTypeWrapper in transitionType.Condition) { this._conditions.Add(new TextTypeWrapperMutableCore(textTypeWrapper)); } } this._localId = transitionType.LocalId; }
/// <summary> /// Starts the specified transition. /// </summary> /// <param name="previousContent"></param> /// <param name="newContent"></param> /// <param name="transition"></param> public void DoTransition(UIElement previousContent, UIElement newContent, ITransition transition) { Children.Clear(); Children.Add(previousContent); if (transition.RequiresNewContentTopmost) { if (newContent != null) Children.Add(newContent); transition.BeginTransition(this, Children.Cast<UIElement>().First(), Children.Cast<UIElement>().Last()); } else { if (newContent != null) Children.Insert(0, newContent); transition.BeginTransition(this, Children.Cast<UIElement>().Last(), Children.Cast<UIElement>().First()); } }
public Asteroid(Scene scene, String assetName, Vector3 rotationAmount, Single scale, TimeSpan lifetime, ExplosionManager explosionManager) : base(scene, assetName) { _rotationAmount = rotationAmount; _lifetime = lifetime; _explosionManager = explosionManager; _transition = BuildTransition.Between(0.0f, 1.0f) .Within(TimeSpan.FromSeconds(0.8f)) .InterpolateWith(MathHelper.Lerp) .Instance(); _scale = scale; _world = Matrix.Identity; }
public virtual void ChangeState(ITransition transition) { if (transition == null) { throw new ArgumentNullException(nameof(transition), "Cannot change state with a null transition"); } var oldState = this.State; var newState = this.GetDestinationState(transition); if (newState == null) { throw new InvalidTransitionException(oldState, transition); } FireChanging(newState); // Exit old State try { State.Exit(transition); } catch (Exception e) { throw new StateFailedToExitException(oldState, transition, e); } // Change State State = newState; // Enter new State try { State.Enter(transition); } catch (Exception e) { throw new StateFailedToEnterException(oldState, transition, newState, e); } FireChanged(); State.Action(this); }
protected override void OnDestroyed () { if (current != null) { current.Dispose (); current = null; } if (next != null) { next.Dispose (); next = null; } Transition = null; if (effect != null) effect.Dispose (); base.OnDestroyed (); }
private void BuildTransition() { var tr = new SlideTransition { Mode = SlideTransitionMode.SlideRightFadeIn }; _transition = tr.GetTransition(LayoutRoot); _transition.Completed += (sender, args) => _transition.Stop(); var trLeft = new SlideTransition { Mode = SlideTransitionMode.SlideLeftFadeIn }; _leftTransition = trLeft.GetTransition(LayoutRoot); _leftTransition.Completed += (sender, args) => _leftTransition.Stop(); }
/// <summary> /// Transitions the new <see cref="T:System.Windows.UIElement"/>. /// </summary> /// <param name="newTransition">The <see cref="T:Microsoft.Phone.Controls.ITransition"/> for the new <see cref="T:System.Windows.UIElement"/>.</param> /// <param name="navigationInTransition">The <see cref="T:Microsoft.Phone.Controls.NavigationInTransition"/> for the new <see cref="T:System.Windows.UIElement"/>.</param> private void TransitionNewElement(ITransition newTransition, NavigationInTransition navigationInTransition) { _oldContentPresenter.Visibility = Visibility.Collapsed; _oldContentPresenter.Content = null; if (newTransition == null) { _newContentPresenter.IsHitTestVisible = true; _newContentPresenter.Opacity = 1; return; } if (newTransition.GetCurrentState() != ClockState.Stopped) { newTransition.Stop(); } newTransition.Completed += delegate { newTransition.Stop(); _newContentPresenter.CacheMode = null; _newContentPresenter.IsHitTestVisible = true; if (navigationInTransition != null) { navigationInTransition.OnEndTransition(); } }; Dispatcher.BeginInvoke(delegate { if (navigationInTransition != null) { navigationInTransition.OnBeginTransition(); } _newContentPresenter.Opacity = 1; newTransition.Begin(); }); }
internal bool TryCreateSignal(G signalName, S sourceState, S destinationState, out ISignal signal, out ITransition transition) { Transition <S, int, G> _transition = GetOrCreateTransition(sourceState, destinationState); transition = _transition; return(SM.ConnectSignal(signalName, _transition, out signal)); }
/// <summary> /// Called after a transition exception is handled. /// </summary> /// <param name="stateMachine">The state machine.</param> /// <param name="transition">The transition.</param> /// <param name="transitionContext">The transition context.</param> /// <param name="exception">The exception.</param> public virtual void HandledTransitionException(IStateMachineInformation <TState, TEvent> stateMachine, ITransition <TState, TEvent> transition, ITransitionContext <TState, TEvent> transitionContext, Exception exception) { }
protected StateMachineEvent DeadEnd(ITransition transition) => new StateMachineDeadEnd(transition);
private void ValidateTransition(ITransition transition) { ValidateTransition(_currentContext, transition); }
/// <summary> /// コンストラクタ /// </summary> /// <param name="c">カテゴリ</param> /// <param name="n">インスタンス名</param> public GameObserver(ITransition i, string c, string n) : base(i, c, n) { }
void transitionManager1_BeforeTransitionStarts(ITransition transition, System.ComponentModel.CancelEventArgs e) { bottomPanelBase1.Enabled = true; }
public abstract bool IsTransitionAllowed(ITransition transition);
/// <summary> /// This method is invoked after a Workflow advanced through a Transition /// </summary> /// <param name="transtion">The transtion that Workflow advanced through</param> /// <param name="session">The session that must be used to perform tasks on additional objects</param> /// <remarks>When this action is invoked, none of the object involved were saved to Content Store yet.</remarks> public void OnAfterWorkflowAdvance(ITransition transtion, IUserWriteSession session) { }
public override void HandlingTransitionException(IStateMachineInformation <States, Events> stateMachine, ITransition <States, Events> transition, ITransitionContext <States, Events> context, ref Exception exception) { if (this.OverriddenException != null) { exception = this.OverriddenException; } }
/// <summary> /// 执行转换 /// </summary> /// <param name="transition"></param> protected virtual void DoTransition(ITransition transition) { Parent.CurState.OnExit(transition.ToState); Parent.SetCurState(transition.ToState); Parent.CurState.OnEnter(transition.FromState); }
/// <summary> /// Called after a transition exception is handled. /// </summary> /// <param name="stateMachine">The state machine.</param> /// <param name="transition">The transition.</param> /// <param name="transitionContext">The transition context.</param> /// <param name="exception">The exception.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public virtual Task HandledTransitionException(IStateMachineInformation <TState, TEvent> stateMachine, ITransition <TState, TEvent> transition, ITransitionContext <TState, TEvent> transitionContext, Exception exception) { return(TaskEx.Completed); }
public IPanelHideLauncher WithTransition(ITransition transition) { this.transition = transition; return(this); }
public void ExecutedTransition(IStateMachineInformation <NodeState, GossipEvent> stateMachineInformation, ITransition <NodeState, GossipEvent> transition, ITransitionContext <NodeState, GossipEvent> context) { }
public void setBackground(string asset, ITransition intro, ITransition revert, ITransition select, ITransition exit) { BackgroundComponent background = new BackgroundComponent(asset); background.setTransitions(intro, revert, select, exit); addComponent(background); }
/// <summary> /// Performs a transition when given the appropriate components, /// includes calling the appropriate start event and ensuring opacity /// on the content presenter. /// </summary> /// <param name="navigationTransition">The navigation transition.</param> /// <param name="presenter">The content presenter.</param> /// <param name="transition">The transition instance.</param> private static void PerformTransition(NavigationTransition navigationTransition, ContentPresenter presenter, ITransition transition) { if (navigationTransition != null) { navigationTransition.OnBeginTransition(); } if (presenter != null && presenter.Opacity != 1) { presenter.Opacity = 1; } if (transition != null) { transition.Begin(); } }
public void setTitle(TitleComponent title, ITransition intro, ITransition revert, ITransition select, ITransition exit) { title.setTransitions(intro, revert, select, exit); addComponent(title); }
public void TransitionEnded(ITransition transition, UIElement oldContent, UIElement newContent) { if (oldContent != null && Children.Count > 1) Children.Remove(oldContent); TransitionCompleted(this, EventArgs.Empty); }
public void setDisplayList(string fontAsset, string highlighterAsset, Rectangle boudingBox, Color color, Vector2 highlighterLocation, int optionFactor, ITransition intro, ITransition revert, ITransition select, ITransition exit) { ScrollOptionsComponent optionList = new ScrollOptionsComponent(fontAsset, boudingBox); for (int i = 0; i < genreCollection.Count; i++) { OptionType option = new OptionType(genreCollection[i].Name, new Vector2(boudingBox.X, boudingBox.Y + optionFactor * i), color, new Rectangle(boudingBox.X, boudingBox.Y + optionFactor * i, boudingBox.Width, optionFactor), OptionAction.next, "Collection Songs", highlighterAsset, new Vector2(highlighterLocation.X, highlighterLocation.Y + i * optionFactor)); option.Selected += SetSubMenu; optionList.addOption(option); } optionList.setTransitions(intro, revert, select, exit); addComponent(optionList); }
public Stage1(ITransition i) : base(i, "InGame", "Stage1") { }
public void setBack(string fontAsset, Vector2 location, Color color, string highlighterAsset, Vector2 highlighterLocation, TextAlignment alignment, ITransition intro, ITransition revert, ITransition select, ITransition exit) { OptionsComponent options = new OptionsComponent(fontAsset); OptionType option = new OptionType("Back", location, color, OptionAction.previous, true, true, highlighterAsset, highlighterLocation); option.setAlignment(alignment); options.addOption(option); options.setTransitions(intro, revert, select, exit); addComponent(options); }
public static TransitionAwaiter GetAwaiter(this ITransition transition) { return(new TransitionAwaiter(transition)); }
/// <summary> /// Called when a transition was executed. /// </summary> public virtual void ExecutedTransition( IStateMachineInformation <TState, TEvent> stateMachineInformation, ITransition <TState, TEvent> transition, ITransitionContext <TState, TEvent> context) { }
public Registering(Gateway.Event.IMediator mediator, ITransition transition, Context.IRegistration context) { _mediator = mediator; _transition = transition; _context = context; }
public TransitionAwaiter(ITransition transition) { this.transition = transition; }
/// <summary> /// Handles the completion of the exit transition, automatically /// continuing to bring in the new element's transition as well if it is /// ready. /// </summary> /// <param name="sender">The source object.</param> /// <param name="e">The event arguments.</param> private void OnExitTransitionCompleted(object sender, EventArgs e) { _readyToTransitionToNewContent = true; _performingExitTransition = false; CompleteTransition(_storedNavigationOutTransition, /*_oldContentPresenter*/ null, _storedOldTransition); _storedNavigationOutTransition = null; _storedOldTransition = null; if (_contentReady) { ITransition newTransition = _storedNewTransition; NavigationInTransition navigationInTransition = _storedNavigationInTransition; _storedNewTransition = null; _storedNavigationInTransition = null; TransitionNewContent(newTransition, navigationInTransition); } }
protected StateMachineEvent Transition(ITransition transition) => new StateMachineTransition(transition);
/// <summary> /// Transitions the new <see cref="T:System.Windows.UIElement"/>. /// </summary> /// <param name="newTransition">The <see cref="T:Microsoft.Phone.Controls.ITransition"/> /// for the new <see cref="T:System.Windows.UIElement"/>.</param> /// <param name="navigationInTransition">The <see cref="T:Microsoft.Phone.Controls.NavigationInTransition"/> /// for the new <see cref="T:System.Windows.UIElement"/>.</param> private void TransitionNewContent(ITransition newTransition, NavigationInTransition navigationInTransition) { if (_oldContentPresenter != null) { _oldContentPresenter.Visibility = Visibility.Collapsed; _oldContentPresenter.Content = null; } if (null == newTransition) { RestoreContentPresenterInteractivity(_newContentPresenter); return; } EnsureStoppedTransition(newTransition); newTransition.Completed += delegate { CompleteTransition(navigationInTransition, _newContentPresenter, newTransition); }; _readyToTransitionToNewContent = false; _storedNavigationInTransition = null; _storedNewTransition = null; PerformTransition(navigationInTransition, _newContentPresenter, newTransition); }
//private void PrefetchChildModules() { // if(System.Diagnostics.Debugger.IsAttached) return; // viewModel.GetModule(ModuleType.Opportunities); // viewModel.GetModule(ModuleType.Tasks); // viewModel.GetModule(ModuleType.Products); // viewModel.GetModule(ModuleType.CustomersModule); // viewModel.GetModule(ModuleType.Dashboard); // viewModel.GetModule(ModuleType.Sales); //} //void viewModel_ModuleAdded(object sender, EventArgs e) { // var moduleControl = sender as Control; // moduleControl.Dock = DockStyle.Fill; // moduleControl.Size = modulesContainer.ClientSize; // moduleControl.Parent = modulesContainer; //} //void viewModel_ModuleRemoved(object sender, EventArgs e) { // var moduleControl = sender as Control; // moduleControl.Parent = null; //} void transitionManager1_BeforeTransitionStarts(ITransition transition, System.ComponentModel.CancelEventArgs e) { // bottomPanelBase1.Enabled = true; }
public void HandledTransitionException(IStateMachineInformation <NodeState, GossipEvent> stateMachine, ITransition <NodeState, GossipEvent> transition, ITransitionContext <NodeState, GossipEvent> transitionContext, Exception exception) { }
/// <summary> /// Handles the Navigating event of the frame, the immediate way to /// begin a transition out before the new page has loaded or had its /// layout pass. /// </summary> /// <param name="sender">The source object.</param> /// <param name="e">The event arguments.</param> private void OnNavigating(object sender, NavigatingCancelEventArgs e) { _isForwardNavigation = e.NavigationMode != NavigationMode.Back; var oldElement = Content as UIElement; if (oldElement == null) { return; } FlipPresenters(); TransitionElement oldTransitionElement = null; NavigationOutTransition navigationOutTransition = null; ITransition oldTransition = null; navigationOutTransition = TransitionService.GetNavigationOutTransition(oldElement); if (navigationOutTransition != null) { oldTransitionElement = _isForwardNavigation ? navigationOutTransition.Forward : navigationOutTransition.Backward; } if (oldTransitionElement != null) { oldTransition = oldTransitionElement.GetTransition(oldElement); } if (oldTransition != null) { EnsureStoppedTransition(oldTransition); _storedNavigationOutTransition = navigationOutTransition; _storedOldTransition = oldTransition; oldTransition.Completed += OnExitTransitionCompleted; _performingExitTransition = true; PerformTransition(navigationOutTransition, _oldContentPresenter, oldTransition); PrepareContentPresenterForCompositor(_oldContentPresenter); } else { _readyToTransitionToNewContent = true; } }
protected ITransition GetTransition() => _transition ?? (_transition = CreateTransition());
/// <summary> /// Called when the value of the /// <see cref="P:System.Windows.Controls.ContentControl.Content"/> /// property changes. /// </summary> /// <param name="oldContent">The old <see cref="T:System.Object"/>.</param> /// <param name="newContent">The new <see cref="T:System.Object"/>.</param> protected override void OnContentChanged(object oldContent, object newContent) { base.OnContentChanged(oldContent, newContent); _contentReady = true; UIElement oldElement = oldContent as UIElement; UIElement newElement = newContent as UIElement; // Require the appropriate template parts plus a new element to // transition to. if (_firstContentPresenter == null || _secondContentPresenter == null || newElement == null) { return; } NavigationInTransition navigationInTransition = null; ITransition newTransition = null; if (newElement != null) { navigationInTransition = TransitionService.GetNavigationInTransition(newElement); TransitionElement newTransitionElement = null; if (navigationInTransition != null) { newTransitionElement = _isForwardNavigation ? navigationInTransition.Forward : navigationInTransition.Backward; } if (newTransitionElement != null) { newElement.UpdateLayout(); newTransition = newTransitionElement.GetTransition(newElement); PrepareContentPresenterForCompositor(_newContentPresenter); } } _newContentPresenter.Opacity = 0; _newContentPresenter.Visibility = Visibility.Visible; _newContentPresenter.Content = newElement; _oldContentPresenter.Opacity = 1; _oldContentPresenter.Visibility = Visibility.Visible; _oldContentPresenter.Content = oldElement; if (_readyToTransitionToNewContent) { TransitionNewContent(newTransition, navigationInTransition); } else { _storedNewTransition = newTransition; _storedNavigationInTransition = navigationInTransition; } }
/// <summary> /// This checks to make sure that, if the transition not be in the clock /// state of Stopped, that is will be stopped. /// </summary> /// <param name="transition">The transition instance.</param> private static void EnsureStoppedTransition(ITransition transition) { if (transition != null && transition.GetCurrentState() != ClockState.Stopped) { transition.Stop(); } }
/// <summary> /// Completes a transition operation by stopping it, restoring /// interactivity, and then firing the OnEndTransition event. /// </summary> /// <param name="navigationTransition">The navigation transition.</param> /// <param name="presenter">The content presenter.</param> /// <param name="transition">The transition instance.</param> private static void CompleteTransition(NavigationTransition navigationTransition, ContentPresenter presenter, ITransition transition) { if (transition != null) { transition.Stop(); } RestoreContentPresenterInteractivity(presenter); if (navigationTransition != null) { navigationTransition.OnEndTransition(); } }
public OrthogonalTransition <TState, TTransition, TSignal> Begin(ITransition <TTransition> transition) { return(this.Machine.Begin(transition, this.OfState)); }
private void CreateTransition() { this.currentTransition = this.factory.CreateTransition(); this.state.Transitions.Add(this.currentEventId, this.currentTransition); }
public override void OnResourceReady(Object resource, ITransition transition) { try { switch (MAdapter.AttachmentList?.Count) { case > 0: { var item = MAdapter.AttachmentList[Position]; if (item != null && string.IsNullOrEmpty(item.Thumb?.FileUrl)) { var fileName = item.FileUrl.Split('/').Last(); var fileNameWithoutExtension = fileName.Split('.').First(); var pathImage = Methods.Path.FolderDcimImage + "/" + fileNameWithoutExtension + ".png"; var videoImage = Methods.MultiMedia.GetMediaFrom_Gallery(Methods.Path.FolderDcimImage, fileNameWithoutExtension + ".png"); switch (videoImage) { case "File Dont Exists": { switch (resource) { case Bitmap bitmap: { Methods.MultiMedia.Export_Bitmap_As_Image(bitmap, fileNameWithoutExtension, Methods.Path.FolderDcimImage); File file2 = new File(pathImage); var photoUri = FileProvider.GetUriForFile(MAdapter.ActivityContext, MAdapter.ActivityContext.PackageName + ".fileprovider", file2); Glide.With(MAdapter.ActivityContext).Load(photoUri).Apply(new RequestOptions()).Into(ViewHolder.Image); item.Thumb = new Attachments.VideoThumb { FileUrl = photoUri.ToString() }; break; } } break; } default: { File file2 = new File(pathImage); var photoUri = FileProvider.GetUriForFile(MAdapter.ActivityContext, MAdapter.ActivityContext.PackageName + ".fileprovider", file2); Glide.With(MAdapter.ActivityContext).Load(photoUri).Apply(new RequestOptions()).Into(ViewHolder.Image); item.Thumb = new Attachments.VideoThumb { FileUrl = photoUri.ToString() }; break; } } } break; } } } catch (Exception e) { Methods.DisplayReportResultTrack(e); } }
/// <summary> /// Load either from the cache on internet /// </summary> private void LoadData(int numberOfStarts, ITransition transition = null) { IndicateStartedLoading(numberOfStarts); var loadContext = new DayLoadContext(CurrentDateForWiki, AppSettings.ShowNewestItemsFirst); this.DataContext = DataManager.Current.Load <DayViewModel>( loadContext, vm => { if (App.ReloadRequired) { App.ReloadRequired = false; } else if (App.FontSizeChanged) { vm.UpdateLayout(); App.FontSizeChanged = false; } if (App.ReverseRequired) { vm.Highlights = new ObservableCollection <Entry>(vm.Highlights.Reverse()); vm.Events.Events = new ObservableCollection <GroupedEntries>(vm.Events.Events.Reverse()); vm.Births.Births = new ObservableCollection <GroupedEntries>(vm.Births.Births.Reverse()); vm.Deaths.Deaths = new ObservableCollection <GroupedEntries>(vm.Deaths.Deaths.Reverse()); App.ReverseRequired = false; } if (!App.IsMemoryLimited && App.FirstLoad) { SetUpLiveTile(numberOfStarts); } if (App.IsMemoryLimited) { ((ApplicationBarMenuItem)ApplicationBar.MenuItems[3]).IsEnabled = false; } IndicateStoppedLoading(); if (!inTransition && transition != null) { inTransition = true; transition.Begin(); } AdPanel.Opacity = 100; }, ex => { GlobalLoading.Instance.IsLoading = false; GlobalLoading.Instance.LoadingText = null; if (NetworkInterface.GetIsNetworkAvailable()) { var extraData = new Collection <CrashExtraData> { new CrashExtraData { Key = "Date", Value = CurrentDateForWiki } }; BugSenseHandler.Instance.SendExceptionMap(ex, extraData); } else { MessageBox.Show(Strings.ErrorInternetConnection); } if (!inTransition && transition != null) { inTransition = true; transition.Begin(); } }); SetPivotTitle(); }
private Pair <int, int> TrainTree(int index, IList <Tree> binarizedTrees, IList <IList <ITransition> > transitionLists, IList <PerceptronModel.Update> updates, Oracle oracle) { int numCorrect = 0; int numWrong = 0; Tree tree = binarizedTrees[index]; ReorderingOracle reorderer = null; if (op.TrainOptions().trainingMethod == ShiftReduceTrainOptions.TrainingMethod.ReorderOracle || op.TrainOptions().trainingMethod == ShiftReduceTrainOptions.TrainingMethod.ReorderBeam) { reorderer = new ReorderingOracle(op); } // TODO. This training method seems to be working in that it // trains models just like the gold and early termination methods do. // However, it causes the feature space to go crazy. Presumably // leaving out features with low weights or low frequencies would // significantly help with that. Otherwise, not sure how to keep // it under control. if (op.TrainOptions().trainingMethod == ShiftReduceTrainOptions.TrainingMethod.Oracle) { State state = ShiftReduceParser.InitialStateFromGoldTagTree(tree); while (!state.IsFinished()) { IList <string> features = featureFactory.Featurize(state); ScoredObject <int> prediction = FindHighestScoringTransition(state, features, true); if (prediction == null) { throw new AssertionError("Did not find a legal transition"); } int predictedNum = prediction.Object(); ITransition predicted = transitionIndex.Get(predictedNum); OracleTransition gold = oracle.GoldTransition(index, state); if (gold.IsCorrect(predicted)) { numCorrect++; if (gold.transition != null && !gold.transition.Equals(predicted)) { int transitionNum = transitionIndex.IndexOf(gold.transition); if (transitionNum < 0) { // TODO: do we want to add unary transitions which are // only possible when the parser has gone off the rails? continue; } updates.Add(new PerceptronModel.Update(features, transitionNum, -1, learningRate)); } } else { numWrong++; int transitionNum = -1; if (gold.transition != null) { transitionNum = transitionIndex.IndexOf(gold.transition); } // TODO: this can theoretically result in a -1 gold // transition if the transition exists, but is a // CompoundUnaryTransition which only exists because the // parser is wrong. Do we want to add those transitions? updates.Add(new PerceptronModel.Update(features, transitionNum, predictedNum, learningRate)); } state = predicted.Apply(state); } } else { if (op.TrainOptions().trainingMethod == ShiftReduceTrainOptions.TrainingMethod.Beam || op.TrainOptions().trainingMethod == ShiftReduceTrainOptions.TrainingMethod.ReorderBeam) { if (op.TrainOptions().beamSize <= 0) { throw new ArgumentException("Illegal beam size " + op.TrainOptions().beamSize); } IList <ITransition> transitions = Generics.NewLinkedList(transitionLists[index]); PriorityQueue <State> agenda = new PriorityQueue <State>(op.TrainOptions().beamSize + 1, ScoredComparator.AscendingComparator); State goldState = ShiftReduceParser.InitialStateFromGoldTagTree(tree); agenda.Add(goldState); // int transitionCount = 0; while (transitions.Count > 0) { ITransition goldTransition = transitions[0]; ITransition highestScoringTransitionFromGoldState = null; double highestScoreFromGoldState = 0.0; PriorityQueue <State> newAgenda = new PriorityQueue <State>(op.TrainOptions().beamSize + 1, ScoredComparator.AscendingComparator); State highestScoringState = null; State highestCurrentState = null; foreach (State currentState in agenda) { bool isGoldState = (op.TrainOptions().trainingMethod == ShiftReduceTrainOptions.TrainingMethod.ReorderBeam && goldState.AreTransitionsEqual(currentState)); IList <string> features = featureFactory.Featurize(currentState); ICollection <ScoredObject <int> > stateTransitions = FindHighestScoringTransitions(currentState, features, true, op.TrainOptions().beamSize, null); foreach (ScoredObject <int> transition in stateTransitions) { State newState = transitionIndex.Get(transition.Object()).Apply(currentState, transition.Score()); newAgenda.Add(newState); if (newAgenda.Count > op.TrainOptions().beamSize) { newAgenda.Poll(); } if (highestScoringState == null || highestScoringState.Score() < newState.Score()) { highestScoringState = newState; highestCurrentState = currentState; } if (isGoldState && (highestScoringTransitionFromGoldState == null || transition.Score() > highestScoreFromGoldState)) { highestScoringTransitionFromGoldState = transitionIndex.Get(transition.Object()); highestScoreFromGoldState = transition.Score(); } } } // This can happen if the REORDER_BEAM method backs itself // into a corner, such as transitioning to something that // can't have a FinalizeTransition applied. This doesn't // happen for the BEAM method because in that case the correct // state (eg one with ROOT) isn't on the agenda so it stops. if (op.TrainOptions().trainingMethod == ShiftReduceTrainOptions.TrainingMethod.ReorderBeam && highestScoringTransitionFromGoldState == null) { break; } State newGoldState = goldTransition.Apply(goldState, 0.0); // if highest scoring state used the correct transition, no training // otherwise, down the last transition, up the correct if (!newGoldState.AreTransitionsEqual(highestScoringState)) { ++numWrong; IList <string> goldFeatures = featureFactory.Featurize(goldState); int lastTransition = transitionIndex.IndexOf(highestScoringState.transitions.Peek()); updates.Add(new PerceptronModel.Update(featureFactory.Featurize(highestCurrentState), -1, lastTransition, learningRate)); updates.Add(new PerceptronModel.Update(goldFeatures, transitionIndex.IndexOf(goldTransition), -1, learningRate)); if (op.TrainOptions().trainingMethod == ShiftReduceTrainOptions.TrainingMethod.Beam) { // If the correct state has fallen off the agenda, break if (!ShiftReduceUtils.FindStateOnAgenda(newAgenda, newGoldState)) { break; } else { transitions.Remove(0); } } else { if (op.TrainOptions().trainingMethod == ShiftReduceTrainOptions.TrainingMethod.ReorderBeam) { if (!ShiftReduceUtils.FindStateOnAgenda(newAgenda, newGoldState)) { if (!reorderer.Reorder(goldState, highestScoringTransitionFromGoldState, transitions)) { break; } newGoldState = highestScoringTransitionFromGoldState.Apply(goldState); if (!ShiftReduceUtils.FindStateOnAgenda(newAgenda, newGoldState)) { break; } } else { transitions.Remove(0); } } } } else { ++numCorrect; transitions.Remove(0); } goldState = newGoldState; agenda = newAgenda; } } else { if (op.TrainOptions().trainingMethod == ShiftReduceTrainOptions.TrainingMethod.ReorderOracle || op.TrainOptions().trainingMethod == ShiftReduceTrainOptions.TrainingMethod.EarlyTermination || op.TrainOptions().trainingMethod == ShiftReduceTrainOptions.TrainingMethod .Gold) { State state = ShiftReduceParser.InitialStateFromGoldTagTree(tree); IList <ITransition> transitions = transitionLists[index]; transitions = Generics.NewLinkedList(transitions); bool keepGoing = true; while (transitions.Count > 0 && keepGoing) { ITransition transition = transitions[0]; int transitionNum = transitionIndex.IndexOf(transition); IList <string> features = featureFactory.Featurize(state); int predictedNum = FindHighestScoringTransition(state, features, false).Object(); ITransition predicted = transitionIndex.Get(predictedNum); if (transitionNum == predictedNum) { transitions.Remove(0); state = transition.Apply(state); numCorrect++; } else { numWrong++; // TODO: allow weighted features, weighted training, etc updates.Add(new PerceptronModel.Update(features, transitionNum, predictedNum, learningRate)); switch (op.TrainOptions().trainingMethod) { case ShiftReduceTrainOptions.TrainingMethod.EarlyTermination: { keepGoing = false; break; } case ShiftReduceTrainOptions.TrainingMethod.Gold: { transitions.Remove(0); state = transition.Apply(state); break; } case ShiftReduceTrainOptions.TrainingMethod.ReorderOracle: { keepGoing = reorderer.Reorder(state, predicted, transitions); if (keepGoing) { state = predicted.Apply(state); } break; } default: { throw new ArgumentException("Unexpected method " + op.TrainOptions().trainingMethod); } } } } } } } return(Pair.MakePair(numCorrect, numWrong)); }