<commit_before>/* -------------------------------------------------------------------------- *
 * OpenSim: IKToolModel.java                                                  *
 * -------------------------------------------------------------------------- *
 * OpenSim is a toolkit for musculoskeletal modeling and simulation,          *
 * developed as an open source project by a worldwide community. Development  *
 * and support is coordinated from Stanford University, with funding from the *
 * U.S. NIH and DARPA. See http://opensim.stanford.edu and the README file    *
 * for more information including specific grant numbers.                     *
 *                                                                            *
 * Copyright (c) 2005-2017 Stanford University and the Authors                *
 * Author(s): <NAME>                                                     *
 *                                                                            *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may    *
 * not use this file except in compliance with the License. You may obtain a  *
 * copy of the License at http://www.apache.org/licenses/LICENSE-2.0          *
 *                                                                            *
 * Unless required by applicable law or agreed to in writing, software        *
 * distributed under the License is distributed on an "AS IS" BASIS,          *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *
 * See the License for the specific language governing permissions and        *
 * limitations under the License.                                             *
 * -------------------------------------------------------------------------- */

package org.opensim.tracking;

import java.io.File;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.util.Cancellable;
import org.opensim.modeling.InverseKinematicsTool;
import org.opensim.modeling.InterruptCallback;
//import org.opensim.modeling.InterruptingIntegCallback;
import org.opensim.modeling.Model;
import org.opensim.modeling.OpenSimContext;
import org.opensim.modeling.Storage;
import org.opensim.view.motions.MotionsDB;
import org.opensim.swingui.SwingWorker;
import org.opensim.tracking.tools.SimulationDB;
import org.opensim.utils.ErrorDialog;
import org.opensim.utils.FileUtils;
import org.opensim.view.motions.JavaMotionDisplayerCallback;
import org.opensim.view.pub.OpenSimDB;

//==================================================================
// IKToolModel
//==================================================================
// Only deals with a single (the first) IKTrial in the IKTrialSet of IKTool
public class IKToolModel extends Observable implements Observer {
   //========================================================================
   // IKToolWorker
   //========================================================================
   class IKToolWorker extends SwingWorker {
      private ProgressHandle progressHandle = null;
      private JavaMotionDisplayerCallback animationCallback = null;
      private InterruptCallback interruptingCallback = null;
      boolean result = false;
      boolean promptToKeepPartialResult = true;
      boolean cleanup=true;
      //private Model modelCopy = null;
      final OpenSimContext context=OpenSimDB.getInstance().getContext(getOriginalModel());
      
      IKToolWorker() throws Exception {
         // Give the thread a nudge so that we're not much slower than command line'
         setPriority(Thread.MAX_PRIORITY);
         
         updateIKTool();

         // Operate on a copy of the model -- this way if users play with parameters in the GUI it won't affect the model we're actually computing on
         ikTool.setModel(getOriginalModel());

         // Make no motion be currently selected (so model doesn't have extraneous ground forces/experimental markers from
         // another motion show up on it)
         MotionsDB.getInstance().clearCurrent();

         // Initialize progress bar, given we know the number of frames to process
         double startTime = ikTool.getStartTime();
         double endTime = ikTool.getEndTime();
         progressHandle = ProgressHandleFactory.createHandle("Executing inverse kinematics...",
                              new Cancellable() {
                                 public boolean cancel() {
                                    interrupt(true);
                                    SimulationDB.getInstance().fireToolFinish();
                                    return true;
                                 }
                              });

         // Animation callback will update the display during IK solve
         animationCallback = new JavaMotionDisplayerCallback(getOriginalModel(),null/* ikTool.getOutputStorage()*/, progressHandle, true);
         //OpenSim20 animationCallback.setRenderMuscleActivations(false);
         //OpenSim20 animationCallback.setModelForDisplaySetConfiguration(false);
         getOriginalModel().addAnalysis(animationCallback);
         animationCallback.setStepInterval(1);
         animationCallback.startProgressUsingTime(startTime, endTime);

         // Do this manouver (there's gotta be a nicer way) to create the object so that C++ owns it and not Java (since 
         // removeIntegCallback in finished() will cause the C++-side callback to be deleted, and if Java owned this object
         // it would then later try to delete it yet again)
         interruptingCallback = new InterruptCallback(getOriginalModel());
         getOriginalModel().addAnalysis(interruptingCallback);
         setExecuting(true);
         SimulationDB.getInstance().fireToolStart();

      }

      public void interrupt(boolean promptToKeepPartialResult)  {
         this.promptToKeepPartialResult = promptToKeepPartialResult;
         if(interruptingCallback!=null){
              interruptingCallback.interrupt();
         }
      }

      public Object construct() {
         try {
           ikTool.run();
         }
         catch(Exception ex) {
            progressHandle.finish();
            SimulationDB.getInstance().fireToolFinish();
            worker=null;
            cleanup=false;
            getOriginalModel().removeAnalysis(interruptingCallback, false);
            
         }
         return this;
      }

        public void finished() {
            progressHandle.finish();
            SimulationDB.getInstance().fireToolFinish();
            if (!cleanup) {
                setExecuting(false);
                return;
            }
            // Clean up motion displayer (this is necessary!)
            animationCallback.cleanupMotionDisplayer();

            getOriginalModel().removeAnalysis(animationCallback, false);
            getOriginalModel().removeAnalysis(interruptingCallback, false);
            interruptingCallback = null;

            if (result) {
                resetModified();
            }

            boolean addMotion = true;
            if (!result) {
                boolean havePartialResult = false;//OpenSim23 ikTool.getOutputStorage()!=null && ikTool.getOutputStorage().getSize()>0;
                if (havePartialResult && promptToKeepPartialResult) {
                    Object answer = DialogDisplayer.getDefault().notify(new NotifyDescriptor.Confirmation("Inverse kinematics did not complete.  Keep partial result?", NotifyDescriptor.YES_NO_OPTION));
                    if (answer == NotifyDescriptor.NO_OPTION) {
                        addMotion = false;
                    }
                } else {
                    addMotion = false;
                }
            }
            // Create a new States storage and load it in GUI 
            // We don't create full state to avoid polluting results
            Storage ikmotion = new Storage(animationCallback.getStorage()); // Java-side copy
            ikmotion.setName("IKResults");
            updateMotion(ikmotion);

            setExecuting(false);

            //modelCopy = null;
            worker = null;
        }
    }
   private IKToolWorker worker = null;
   //========================================================================
   // END IKToolWorker<commit_msg>Clear up comment on IKToolModel<commit_after>/* -------------------------------------------------------------------------- *
 * OpenSim: IKToolModel.java                                                  *
 * -------------------------------------------------------------------------- *
 * OpenSim is a toolkit for musculoskeletal modeling and simulation,          *
 * developed as an open source project by a worldwide community. Development  *
 * and support is coordinated from Stanford University, with funding from the *
 * U.S. NIH and DARPA. See http://opensim.stanford.edu and the README file    *
 * for more information including specific grant numbers.                     *
 *                                                                            *
 * Copyright (c) 2005-2017 Stanford University and the Authors                *
 * Author(s): <NAME>                                                     *
 *                                                                            *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may    *
 * not use this file except in compliance with the License. You may obtain a  *
 * copy of the License at http://www.apache.org/licenses/LICENSE-2.0          *
 *                                                                            *
 * Unless required by applicable law or agreed to in writing, software        *
 * distributed under the License is distributed on an "AS IS" BASIS,          *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *
 * See the License for the specific language governing permissions and        *
 * limitations under the License.                                             *
 * -------------------------------------------------------------------------- */

package org.opensim.tracking;

import java.io.File;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.util.Cancellable;
import org.opensim.modeling.InverseKinematicsTool;
import org.opensim.modeling.InterruptCallback;
//import org.opensim.modeling.InterruptingIntegCallback;
import org.opensim.modeling.Model;
import org.opensim.modeling.OpenSimContext;
import org.opensim.modeling.Storage;
import org.opensim.view.motions.MotionsDB;
import org.opensim.swingui.SwingWorker;
import org.opensim.tracking.tools.SimulationDB;
import org.opensim.utils.ErrorDialog;
import org.opensim.utils.FileUtils;
import org.opensim.view.motions.JavaMotionDisplayerCallback;
import org.opensim.view.pub.OpenSimDB;

//==================================================================
// IKToolModel
//==================================================================
// Only deals with a single (the first) IKTrial in the IKTrialSet of IKTool
public class IKToolModel extends Observable implements Observer {
   //========================================================================
   // IKToolWorker
   //========================================================================
   class IKToolWorker extends SwingWorker {
      private ProgressHandle progressHandle = null;
      private JavaMotionDisplayerCallback animationCallback = null;
      private InterruptCallback interruptingCallback = null;
      boolean result = false;
      boolean promptToKeepPartialResult = true;
      boolean cleanup=true;
      //private Model modelCopy = null;
      final OpenSimContext context=OpenSimDB.getInstance().getContext(getOriginalModel());
      
      IKToolWorker() throws Exception {
         // Give the thread a nudge so that we're not much slower than command line'
         setPriority(Thread.MAX_PRIORITY);
         
         updateIKTool();

         // Operate on a copy of the model -- this way if users play with parameters in the GUI it won't affect the model we're actually computing on
         ikTool.setModel(getOriginalModel());

         // Make no motion be currently selected (so model doesn't have extraneous ground forces/experimental markers from
         // another motion show up on it)
         MotionsDB.getInstance().clearCurrent();

         // Initialize progress bar, given we know the number of frames to process
         double startTime = ikTool.getStartTime();
         double endTime = ikTool.getEndTime();
         progressHandle = ProgressHandleFactory.createHandle("Executing inverse kinematics...",
                              new Cancellable() {
                                 public boolean cancel() {
                                    interrupt(true);
                                    SimulationDB.getInstance().fireToolFinish();
                                    return true;
                                 }
                              });

         // Animation callback will update the display during IK solve
         animationCallback = new JavaMotionDisplayerCallback(getOriginalModel(),null/* ikTool.getOutputStorage()*/, progressHandle, true);
         //OpenSim20 animationCallback.setRenderMuscleActivations(false);
         //OpenSim20 animationCallback.setModelForDisplaySetConfiguration(false);
         getOriginalModel().addAnalysis(animationCallback);
         animationCallback.setStepInterval(1);
         animationCallback.startProgressUsingTime(startTime, endTime);

         // Do this manouver (there's gotta be a nicer way) to create the object so that C++ owns it and not Java (since 
         // removeIntegCallback in finished() will cause the C++-side callback to be deleted, and if Java owned this object
         // it would then later try to delete it yet again)
         interruptingCallback = new InterruptCallback(getOriginalModel());
         getOriginalModel().addAnalysis(interruptingCallback);
         setExecuting(true);
         SimulationDB.getInstance().fireToolStart();

      }

      public void interrupt(boolean promptToKeepPartialResult)  {
         this.promptToKeepPartialResult = promptToKeepPartialResult;
         if(interruptingCallback!=null){
              interruptingCallback.interrupt();
         }
      }

      public Object construct() {
         try {
           ikTool.run();
         }
         catch(Exception ex) {
            progressHandle.finish();
            SimulationDB.getInstance().fireToolFinish();
            worker=null;
            cleanup=false;
            getOriginalModel().removeAnalysis(interruptingCallback, false);
            
         }
         return this;
      }

        public void finished() {
            progressHandle.finish();
            SimulationDB.getInstance().fireToolFinish();
            if (!cleanup) {
                setExecuting(false);
                return;
            }
            // Clean up motion displayer (this is necessary!)
            animationCallback.cleanupMotionDisplayer();

            getOriginalModel().removeAnalysis(animationCallback, false);
            getOriginalModel().removeAnalysis(interruptingCallback, false);
            interruptingCallback = null;

            if (result) {
                resetModified();
            }

            boolean addMotion = true;
            if (!result) {
                boolean havePartialResult = false;//OpenSim23 ikTool.getOutputStorage()!=null && ikTool.getOutputStorage().getSize()>0;
                if (havePartialResult && promptToKeepPartialResult) {
                    Object answer = DialogDisplayer.getDefault().notify(new NotifyDescriptor.Confirmation("Inverse kinematics did not complete.  Keep partial result?", NotifyDescriptor.YES_NO_OPTION));
                    if (answer == NotifyDescriptor.NO_OPTION) {
                        addMotion = false;
                    }
                } else {
                    addMotion = false;
                }
            }
            // We don't create full state to avoid polluting results
            // This will be done internally in MotionDisplayer
            Storage ikmotion = new Storage(animationCallback.getStorage()); // Java-side copy
            ikmotion.setName("IKResults");
            updateMotion(ikmotion);

            setExecuting(false);

            //modelCopy = null;
            worker = null;
        }
    }
   private IKToolWorker worker = null;
   //========================================================================
   // END IKToolWorker
{'fraction_non_alphanumeric': 0.13942816801976704, 'fraction_numerical': 0.0023532180256500765, 'mean_word_length': 1.9890979426762792, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 42, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5562236', 'n_tokens_mistral': 3811, 'n_tokens_neox': 3592, 'n_words': 1072}