Exemplo n.º 1
0
        public static IAgCrdnCalcScalarAngle GetCreateAngleCalcScalar(IAgCrdnProvider vgtPrv, IAgCrdnAngle inputAngle, string scalarName)
        {
            IAgCrdnCalcScalarAngle calcScalarAngle;

            if (vgtPrv.CalcScalars.Contains(scalarName))
            {
                calcScalarAngle = (IAgCrdnCalcScalarAngle)vgtPrv.CalcScalars[scalarName];
            }
            else
            {
                calcScalarAngle =
                    (IAgCrdnCalcScalarAngle)vgtPrv.CalcScalars.Factory.CreateCalcScalarAngle(scalarName, "");
            }
            calcScalarAngle.InputAngle = inputAngle;
            return(calcScalarAngle);
        }
Exemplo n.º 2
0
        public static IAgCrdnAngleBetweenVectors GetCreateAngleBetweenVectors(IAgCrdnProvider vgtPrv, IAgCrdnVector FromVector, IAgCrdnVector ToVector, string AngleName, string description)
        {
            IAgCrdnAngleBetweenVectors angle;

            if (vgtPrv.Angles.Contains(AngleName))
            {
                angle = vgtPrv.Angles[AngleName] as IAgCrdnAngleBetweenVectors;
            }
            else
            {
                angle = (IAgCrdnAngleBetweenVectors)vgtPrv.Angles.Factory.Create(AngleName, description, AgECrdnAngleType.eCrdnAngleTypeBetweenVectors);
            }
            angle.FromVector.SetVector(FromVector);
            angle.ToVector.SetVector(ToVector);

            return(angle);
        }
Exemplo n.º 3
0
        public static IAgCrdnVectorDisplacement GetCreateDisplacementVector(IAgCrdnProvider vgtPrv, IAgCrdnPoint OrginPoint, IAgCrdnPoint DestPoint, string VectorName)
        {
            IAgCrdnVectorDisplacement dispVector;

            if (vgtPrv.Vectors.Contains(VectorName))
            {
                dispVector = vgtPrv.Vectors[VectorName] as IAgCrdnVectorDisplacement;
                dispVector.Origin.SetPoint(OrginPoint);
                dispVector.Destination.SetPoint(DestPoint);
            }
            else
            {
                dispVector = vgtPrv.Vectors.Factory.CreateDisplacementVector(VectorName, OrginPoint, DestPoint);
            }

            return(dispVector);
        }
Exemplo n.º 4
0
        public static IAgCrdnPlaneNormal GetCreatePlaneNormal(IAgCrdnProvider vgtPrv, IAgCrdnPoint Orgin, IAgCrdnVector RefVector, IAgCrdnVector NormalVector, string PlaneName, string description)
        {
            IAgCrdnPlaneNormal plane;

            if (vgtPrv.Planes.Contains(PlaneName))
            {
                plane = (IAgCrdnPlaneNormal)vgtPrv.Planes[PlaneName];
            }
            else
            {
                plane = (IAgCrdnPlaneNormal)vgtPrv.Planes.Factory.Create(PlaneName,
                                                                         description, AgECrdnPlaneType.eCrdnPlaneTypeNormal);
            }
            plane.NormalVector.SetVector(NormalVector);
            plane.ReferencePoint.SetPoint(Orgin);
            plane.ReferenceVector.SetVector(RefVector);

            return(plane);
        }
Exemplo n.º 5
0
        public static IAgCrdnConditionScalarBounds GetCreateConditionScalarBounds(IAgCrdnProvider vgtPrv, IAgCrdnCalcScalar cScalar, string conditionName, AgECrdnConditionThresholdOption option)
        {
            IAgCrdnConditionScalarBounds condition;

            //create condition
            if (vgtPrv.Conditions.Contains(conditionName))
            {
                condition = (IAgCrdnConditionScalarBounds)vgtPrv.Conditions[conditionName];
            }
            else
            {
                condition = (IAgCrdnConditionScalarBounds)vgtPrv.Conditions.Factory
                            .CreateConditionScalarBounds(conditionName, "");
            }
            condition.Operation = option;
            condition.Scalar    = cScalar;

            return(condition);
        }
Exemplo n.º 6
0
        public static IAgCrdnEventArrayExtrema GetCreateEventArrayExtrema(IAgCrdnProvider vgtPrv, IAgCrdnCalcScalar cScalar, string extremaName, AgECrdnExtremumConstants extremaType, bool isGlobal)
        {
            IAgCrdnEventArrayExtrema extrema;

            if (vgtPrv.EventArrays.Contains(extremaName))
            {
                extrema = (IAgCrdnEventArrayExtrema)vgtPrv.EventArrays[extremaName];
            }
            else
            {
                extrema =
                    (IAgCrdnEventArrayExtrema)vgtPrv.EventArrays.Factory.CreateEventArrayExtrema(extremaName,
                                                                                                 "");
            }
            extrema.Calculation  = cScalar;
            extrema.ExtremumType = extremaType;
            extrema.IsGlobal     = isGlobal;

            return(extrema);
        }
Exemplo n.º 7
0
        public static IAgCrdnAngleToPlane GetCreateAngleToPlane(IAgCrdnProvider vgtPrv, IAgCrdnPlane plane, IAgCrdnVector vector, string angleName, string description)
        {
            IAgCrdnAngleToPlane planeAngle;

            if (vgtPrv.Angles.Contains(angleName))
            {
                planeAngle = (IAgCrdnAngleToPlane)vgtPrv.Angles[angleName];
            }
            else
            {
                planeAngle = (IAgCrdnAngleToPlane)vgtPrv.Angles.Factory.Create(angleName,
                                                                               description,
                                                                               AgECrdnAngleType.eCrdnAngleTypeToPlane);
            }
            planeAngle.ReferencePlane.SetPlane(plane);
            planeAngle.ReferenceVector.SetVector(vector);
            planeAngle.Signed = AgECrdnSignedAngleType.eCrdnSignedAngleNone;

            return(planeAngle);
        }
        private void Calculate_Click(object sender, EventArgs e)
        {
            int check = FieldCheck();

            if (check == 0)
            {
                compComplete = false;
                AllPlaneCrossingsList.Clear();
                IAgCrdnPlaneNormal orbitPlane;
                IAgStkObject       crossObj;
                IAgCrdnProvider    crossVgt;
                IAgStkObject       satRefObj = CreatorFunctions.GetCreateSatellite(PlaneSatellite.Text);
                IAgSatellite       satRef    = (IAgSatellite)satRefObj;
                IAgCrdnProvider    vgtPrv    = satRefObj.Vgt;

                //Create reference plane
                string planeName = PlaneSatellite.Text + "_OrbitPlane";
                orbitPlane = AWBFunctions.GetCreatePlaneNormal(vgtPrv, vgtPrv.Points["Center"], vgtPrv.Vectors["Velocity"], vgtPrv.Vectors["Orbit_Normal"], planeName, "Orbit plane referencing orbit normal");

                //Loop for each crossing object. Create angle, calc scalar, extrema time array, and conditionals if required
                string angleName;
                string extremaName;
                string conditionName;
                string cScalName;
                string condEventArrayName;
                foreach (var cObject in crossingObjects)
                {
                    //Initialize new plane crossing group
                    PlaneCrossingGroup crossingGroup = new PlaneCrossingGroup();
                    IAgScenario        scenario      = CommonData.StkRoot.CurrentScenario as IAgScenario;
                    crossingGroup.AnalysisStartTime        = scenario.StartTime;
                    crossingGroup.AnalysisStopTime         = scenario.StopTime;
                    crossingGroup.PlaneReferenceObjectName = satRefObj.InstanceName;
                    crossingGroup.CrossingObjectName       = cObject;

                    //Compute required VGT component names
                    crossObj           = CommonData.StkRoot.GetObjectFromPath(ObjectClass.Text + "/" + cObject);
                    crossVgt           = crossObj.Vgt;
                    angleName          = crossObj.InstanceName + "x" + satRefObj.InstanceName + "_Angle";
                    cScalName          = angleName;
                    extremaName        = crossObj.InstanceName + "x" + satRefObj.InstanceName + "_CrossingTimes";
                    conditionName      = crossObj.InstanceName + "x" + satRefObj.InstanceName + "_CrossingBounds";
                    condEventArrayName = crossObj.InstanceName + "x" + satRefObj.InstanceName + "_BoundedCrossingTimes";

                    //Create angle from current crossing object position to reference plane
                    IAgCrdnAngleToPlane planeAngle = AWBFunctions.GetCreateAngleToPlane(crossVgt, vgtPrv.Planes[planeName], crossVgt.Vectors["Position"], angleName, "Angle from satellite position to" + satRefObj.InstanceName + "orbit plane");

                    //Create calc scalar of angle
                    IAgCrdnCalcScalarAngle calcScalarAngle = AWBFunctions.GetCreateAngleCalcScalar(crossVgt, (IAgCrdnAngle)planeAngle, cScalName);

                    //Create Extrema time array to find exact crossing times
                    IAgCrdnEventArrayExtrema extrema = AWBFunctions.GetCreateEventArrayExtrema(crossVgt, (IAgCrdnCalcScalar)calcScalarAngle, extremaName, AgECrdnExtremumConstants.eCrdnExtremumMinimum, false);

                    //If conditional then create condition and condition crossing event
                    IAgCrdnEventArrayConditionCrossings conditionCrossings = null;
                    if (ConditionalCrossing.Checked)
                    {
                        //create condition
                        IAgCrdnConditionScalarBounds condition = AWBFunctions.GetCreateConditionScalarBounds(crossVgt, (IAgCrdnCalcScalar)calcScalarAngle, conditionName, AgECrdnConditionThresholdOption.eCrdnConditionThresholdOptionInsideMinMax);
                        AWBFunctions.SetAngleConditionScalarBounds(condition, Double.Parse(ConditionalLB.Text), Double.Parse(ConditionalUB.Text));

                        //Create condition crossing event
                        if (crossVgt.EventArrays.Contains(condEventArrayName))
                        {
                            conditionCrossings = (IAgCrdnEventArrayConditionCrossings)crossVgt.EventArrays[condEventArrayName];
                        }
                        else
                        {
                            conditionCrossings = (IAgCrdnEventArrayConditionCrossings)crossVgt.EventArrays.Factory.CreateEventArrayConditionCrossings(condEventArrayName, "");
                        }
                        conditionCrossings.Condition            = condition as IAgCrdnCondition;
                        conditionCrossings.SatisfactionCrossing =
                            AgECrdnSatisfactionCrossing.eCrdnSatisfactionCrossingNone;
                        //if (OffOnSat.Checked && OnOffSat.Checked)
                        //{
                        //    conditionCrossings.SatisfactionCrossing =
                        //        AgECrdnSatisfactionCrossing.eCrdnSatisfactionCrossingNone;
                        //}
                        //else if (OffOnSat.Checked && !OnOffSat.Checked)
                        //{
                        //    conditionCrossings.SatisfactionCrossing =
                        //        AgECrdnSatisfactionCrossing.eCrdnSatisfactionCrossingIn;
                        //}
                        //else if (!OffOnSat.Checked && OnOffSat.Checked)
                        //{
                        //    conditionCrossings.SatisfactionCrossing =
                        //        AgECrdnSatisfactionCrossing.eCrdnSatisfactionCrossingOut;
                        //}
                    }
                    //Extract Data
                    IAgCrdnEventArray      extremaArray = (IAgCrdnEventArray)extrema;
                    IAgCrdnFindTimesResult extremaTimes = extremaArray.FindTimes();
                    IAgCrdnEventArray      boundedArray = null;
                    IAgCrdnFindTimesResult boundedTimes = null;
                    if (extremaTimes.IsValid)
                    {
                        int numTimes = extremaTimes.Times.Length;
                        if (ConditionalCrossing.Checked)
                        {
                            boundedArray = conditionCrossings as IAgCrdnEventArray;
                            boundedTimes = boundedArray.FindTimes();
                            if (boundedTimes.Times.Length != 2 * numTimes)
                            {
                                MessageBox.Show("A bounded crossing time may be outside the analysis interval. Check results.");
                            }
                        }
                        PlaneCrossing crossing;
                        for (int i = 0; i < numTimes; i++)
                        {
                            crossing = new PlaneCrossing();
                            crossing.CrossingTime = extremaTimes.Times.GetValue(i).ToString();
                            if (ConditionalCrossing.Checked)
                            {
                                crossing.IsBounded  = true;
                                crossing.LowerBound = Double.Parse(ConditionalLB.Text);
                                crossing.UpperBound = Double.Parse(ConditionalUB.Text);

                                if (boundedTimes.Times.Length != 2 * numTimes)
                                {
                                    try
                                    {
                                        crossing.LowerBoundCrossingTime = boundedTimes.Times.GetValue(2 * i).ToString();
                                        crossing.UpperBoundCrossingTime = boundedTimes.Times.GetValue(2 * i + 1).ToString();
                                    }
                                    catch (Exception) //Index out of range
                                    {
                                        crossing.LowerBoundCrossingTime = "";
                                        crossing.UpperBoundCrossingTime = "";
                                    }
                                }
                                else
                                {
                                    crossing.LowerBoundCrossingTime = boundedTimes.Times.GetValue(2 * i).ToString();
                                    crossing.UpperBoundCrossingTime = boundedTimes.Times.GetValue(2 * i + 1).ToString();
                                }
                            }
                            crossingGroup.PlaneCrossings.Add(crossing);
                        }
                    }
                    AllPlaneCrossingsList.Add(crossingGroup);
                    compComplete = true;

                    //Add components to timeline view
                    if (AddToTimeline.Checked)
                    {
                        string cmd1 = null;
                        string cmd2 = null;
                        if (ConditionalCrossing.Checked)
                        {
                            cmd1 = "Timeline * TimeComponent Remove ContentView \"Scenario Availability\"" + " \"" + ObjectClass.Text + "/" + crossObj.InstanceName + " " + condEventArrayName + " Time Array\"";
                            cmd2 = "Timeline * TimeComponent Add ContentView \"Scenario Availability\" DisplayName \"" + condEventArrayName + "\"" + " \"" + ObjectClass.Text + "/" + crossObj.InstanceName + " " + condEventArrayName + " Time Array\"";
                        }
                        else
                        {
                            cmd1 = "Timeline * TimeComponent Remove ContentView \"Scenario Availability\"" + " \"" + ObjectClass.Text + "/" + crossObj.InstanceName + " " + extremaName + " Time Array\"";
                            cmd2 = "Timeline * TimeComponent Add ContentView \"Scenario Availability\" DisplayName \"" + extremaName + "\"" + " \"" + ObjectClass.Text + "/" + crossObj.InstanceName + " " + extremaName + " Time Array\"";
                        }

                        try
                        {
                            CommonData.StkRoot.ExecuteCommand(cmd1);
                        }
                        catch (Exception)
                        {
                        }
                        try
                        {
                            CommonData.StkRoot.ExecuteCommand(cmd2);
                            CommonData.StkRoot.ExecuteCommand("Timeline * Refresh");
                        }
                        catch (Exception exception)
                        {
                            //likely no timeline exists
                        }
                    }
                }

                //Export options
                if (compComplete && ExportToTxt.Checked)
                {
                    ReadWrite.WritePlaneCrossingOutput(satRefObj.InstanceName, AllPlaneCrossingsList);
                }
                MessageBox.Show("Computation Complete!");
            }
        }
        private void Calculate_Click(object sender, EventArgs e)
        {
            int check = FieldCheck();

            if (check == 0)
            {
                IAgStkObject obj = null;
                IAgStkObject tar = null;
                foreach (var observer in CommonData.SelectedObservers)
                {
                    foreach (var target in CommonData.SelectedTargets)
                    {
                        if (observer != target)
                        {
                            if (TargetType.SelectedIndex == 0)
                            {
                                tar = CommonData.StkRoot.GetObjectFromPath("Satellite/" + target);
                            }
                            else if (TargetType.SelectedIndex == 1)
                            {
                                tar = CommonData.StkRoot.GetObjectFromPath("Missile/" + target);
                            }
                            else if (TargetType.SelectedIndex == 2)
                            {
                                tar = CommonData.StkRoot.GetObjectFromPath("Aircraft/" + target);
                            }

                            if (ObserverType.SelectedIndex == 0)
                            {
                                obj = CommonData.StkRoot.GetObjectFromPath("Satellite/" + observer);
                            }
                            else if (ObserverType.SelectedIndex == 1)
                            {
                                obj = CommonData.StkRoot.GetObjectFromPath("Facility/" + observer);
                            }
                            else
                            {
                                IAgExecCmdResult result = CommonData.StkRoot.ExecuteCommand("ShowNames * Class Sensor");
                                if (result[0] != "None")
                                {
                                    string[] sensorArray = result[0].Split(null);
                                    foreach (var item in sensorArray)
                                    {
                                        if (item.Contains(observer))
                                        {
                                            int scenarioPos          = item.LastIndexOf("/Scenario/");
                                            int scenarioNameSlashPos = item.IndexOf("/", scenarioPos + 10);
                                            item.Remove(0, scenarioNameSlashPos);
                                            obj = CommonData.StkRoot.GetObjectFromPath(item);
                                        }
                                    }
                                }
                            }
                            IAgCrdnProvider            objVgtPrv  = obj.Vgt;
                            IAgCrdnProvider            tarVgt     = tar.Vgt;
                            IAgCrdnAngleBetweenVectors angle      = null;
                            IAgCrdnVectorDisplacement  dispVector = AWBFunctions.GetCreateDisplacementVector(objVgtPrv, objVgtPrv.Points["Center"], tarVgt.Points["Center"], "To_" + target);

                            //Create either solar phase or beta angle depending on user specified selection
                            string angleName = null;
                            if (AngleType.SelectedIndex == 0)
                            {
                                angleName = "To_" + target + "BetaAngle";
                                angle     = AWBFunctions.GetCreateAngleBetweenVectors(objVgtPrv, dispVector as IAgCrdnVector, objVgtPrv.Vectors["Sun"], angleName, "");
                            }
                            else if (AngleType.SelectedIndex == 1)
                            {
                                angleName = "To_" + target + "SolarPhaseAngle";
                                angle     = AWBFunctions.GetCreateAngleBetweenVectors(objVgtPrv, dispVector as IAgCrdnVector, tarVgt.Vectors["Sun"], angleName, "");
                            }
                            //Create Calc Scalar of angle
                            IAgCrdnCalcScalarAngle cScalar = AWBFunctions.GetCreateAngleCalcScalar(objVgtPrv, angle as IAgCrdnAngle, angleName);

                            //If a conditional is requested, then create it here
                            if (EnableConstraint.Checked)
                            {
                                IAgCrdnConditionScalarBounds condition = AWBFunctions.GetCreateConditionScalarBounds(objVgtPrv, cScalar as IAgCrdnCalcScalar, angleName + "_Condition", AgECrdnConditionThresholdOption.eCrdnConditionThresholdOptionInsideMinMax);
                                AWBFunctions.SetAngleConditionScalarBounds(condition, Double.Parse(ConstraintMin.Text), Double.Parse(ConstraintMax.Text));
                            }
                        }
                    }
                }
                MessageBox.Show("Component Creation Completed");
            }
        }
Exemplo n.º 10
0
        private void Calculate_Click(object sender, EventArgs e)
        {
            IAgStkObject obj = null;
            IAgStkObject tar = null;

            foreach (var observer in CommonData.SelectedObservers)
            {
                foreach (var target in CommonData.SelectedTargets)
                {
                    if (observer != target)
                    {
                        if (TargetType.SelectedIndex == 0)
                        {
                            tar = CommonData.StkRoot.GetObjectFromPath("Satellite/" + target);
                        }
                        else if (TargetType.SelectedIndex == 1)
                        {
                            tar = CommonData.StkRoot.GetObjectFromPath("Missile/" + target);
                        }
                        else if (TargetType.SelectedIndex == 2)
                        {
                            tar = CommonData.StkRoot.GetObjectFromPath("Aircraft/" + target);
                        }

                        if (ObserverType.SelectedIndex == 0)
                        {
                            obj = CommonData.StkRoot.GetObjectFromPath("Satellite/" + observer);
                        }
                        else if (ObserverType.SelectedIndex == 1)
                        {
                            obj = CommonData.StkRoot.GetObjectFromPath("Facility/" + observer);
                        }
                        else
                        {
                            IAgExecCmdResult result = CommonData.StkRoot.ExecuteCommand("ShowNames * Class Sensor");
                            if (result[0] != "None")
                            {
                                string[] sensorArray = result[0].Split(null);
                                foreach (var item in sensorArray)
                                {
                                    if (item.Contains(observer))
                                    {
                                        int scenarioPos          = item.LastIndexOf("/Scenario/");
                                        int scenarioNameSlashPos = item.IndexOf("/", scenarioPos + 10);
                                        item.Remove(0, scenarioNameSlashPos);
                                        obj = CommonData.StkRoot.GetObjectFromPath(item);
                                    }
                                }
                            }
                        }
                        IAgCrdnProvider           objVgtPrv = obj.Vgt;
                        IAgCrdnProvider           tarVgt    = tar.Vgt;
                        IAgCrdnVectorDisplacement dispVector;
                        if (objVgtPrv.Vectors.Contains("To_" + target))
                        {
                            dispVector = objVgtPrv.Vectors["To_" + target] as IAgCrdnVectorDisplacement;
                        }
                        else
                        {
                            dispVector = objVgtPrv.Vectors.Factory.CreateDisplacementVector("To_" + target, objVgtPrv.Points["Center"], tarVgt.Points["Center"]);
                        }
                        if (!objVgtPrv.Angles.Contains("To_" + target + "SolarPhaseAngle"))
                        {
                            IAgCrdnAngleBetweenVectors angle = (IAgCrdnAngleBetweenVectors)objVgtPrv.Angles.Factory.Create("To_" + target + "SolarPhaseAngle", "", AgECrdnAngleType.eCrdnAngleTypeBetweenVectors);
                            angle.FromVector.SetVector(dispVector as IAgCrdnVector);
                            angle.ToVector.SetVector(objVgtPrv.Vectors["Sun"]);
                        }
                    }
                }
            }
        }
Exemplo n.º 11
0
        public static PropagationResults PropagateAstrogatorSatellite(AgStkObjectRoot root, AgUiApplication app, InitialState state, TLE tle, Data satData, Uncertainty uncertainty, int runId, int nRuns, string propName)
        {
            PropagationResults propResults = new PropagationResults();

            propResults.RunNumber = runId.ToString().PadLeft(3, '0');
            IAgSatellite sat = root.CurrentScenario.Children.New(AgESTKObjectType.eSatellite, tle.GetSatNumber() + "Astrogator") as IAgSatellite;

            //Set the propagator to Astrogator
            sat.SetPropagatorType(AgEVePropagatorType.ePropagatorAstrogator);
            //get the Driver for the Propagator
            IAgVADriverMCS driver = sat.Propagator as IAgVADriverMCS;

            //Clear all segments from the MCS
            driver.MainSequence.RemoveAll();

            //// Target Sequence ////
            IAgVAMCSTargetSequence ts = driver.MainSequence.Insert(AgEVASegmentType.eVASegmentTypeTargetSequence, "SetupState", "-") as IAgVAMCSTargetSequence;

            ts.Action = AgEVATargetSeqAction.eVATargetSeqActionRunActiveProfiles;

            // add the initial state segment in the target sequence
            IAgVAMCSInitialState initState = ts.Segments.Insert(AgEVASegmentType.eVASegmentTypeInitialState, "InitialState", "-") as IAgVAMCSInitialState;

            initState.OrbitEpoch = ((IAgScenario)root.CurrentScenario).StartTime;
            // define elements
            initState.SetElementType(AgEVAElementType.eVAElementTypeCartesian);
            IAgVAElementCartesian cart = initState.Element as IAgVAElementCartesian;

            cart.X  = Convert.ToDouble(state.CartesianPosX);
            cart.Y  = Convert.ToDouble(state.CartesianPosY);
            cart.Z  = Convert.ToDouble(state.CartesianPosZ);
            cart.Vx = Convert.ToDouble(state.CartesianVelX);
            cart.Vy = Convert.ToDouble(state.CartesianVelY);
            cart.Vz = Convert.ToDouble(state.CartesianVelZ);

            // spacecraft parameters
            IAgVASpacecraftParameters spacecraftParameters = (IAgVASpacecraftParameters)initState.SpacecraftParameters;

            spacecraftParameters.DryMass  = satData.Mass;
            spacecraftParameters.Cd       = satData.Cd;
            spacecraftParameters.DragArea = satData.DragArea;
            spacecraftParameters.Cr       = satData.Cr;
            spacecraftParameters.SolarRadiationPressureArea = satData.SunArea;
            spacecraftParameters.RadiationPressureArea      = 1e-10;
            IAgVAFuelTank fuelTank = (IAgVAFuelTank)initState.FuelTank;

            fuelTank.FuelMass = 0;

            // enable the control parameter for the state variables
            initState.EnableControlParameter(AgEVAControlInitState.eVAControlInitStateCartesianX);
            initState.EnableControlParameter(AgEVAControlInitState.eVAControlInitStateCartesianY);
            initState.EnableControlParameter(AgEVAControlInitState.eVAControlInitStateCartesianZ);
            initState.EnableControlParameter(AgEVAControlInitState.eVAControlInitStateCartesianVx);
            initState.EnableControlParameter(AgEVAControlInitState.eVAControlInitStateCartesianVy);
            initState.EnableControlParameter(AgEVAControlInitState.eVAControlInitStateCartesianVz);

            // add the results
            ((IAgVAMCSSegment)initState).Results.Add("Relative Motion/InTrack");
            IAgVAStateCalcRelMotion intrackRel = ((IAgVAMCSSegment)initState).Results[0] as IAgVAStateCalcRelMotion;

            intrackRel.ReferenceSelection = AgEVACalcObjectReference.eVACalcObjectReferenceSpecified;
            IAgLinkToObject link_1 = intrackRel.Reference as IAgLinkToObject;

            link_1.BindTo("Satellite/" + tle.GetSatNumber().ToString());

            ((IAgVAMCSSegment)initState).Results.Add("Relative Motion/Radial");
            IAgVAStateCalcRelMotion radialRel = ((IAgVAMCSSegment)initState).Results[1] as IAgVAStateCalcRelMotion;

            radialRel.ReferenceSelection = AgEVACalcObjectReference.eVACalcObjectReferenceSpecified;
            IAgLinkToObject link_2 = radialRel.Reference as IAgLinkToObject;

            link_2.BindTo("Satellite/" + tle.GetSatNumber().ToString());

            ((IAgVAMCSSegment)initState).Results.Add("Relative Motion/CrossTrack");
            IAgVAStateCalcRelMotion crosstrackRel = ((IAgVAMCSSegment)initState).Results[2] as IAgVAStateCalcRelMotion;

            crosstrackRel.ReferenceSelection = AgEVACalcObjectReference.eVACalcObjectReferenceSpecified;
            IAgLinkToObject link_3 = crosstrackRel.Reference as IAgLinkToObject;

            link_3.BindTo("Satellite/" + tle.GetSatNumber().ToString());

            ((IAgVAMCSSegment)initState).Results.Add("Relative Motion/InTrackRate");
            IAgVAStateCalcRelMotion intrackrateRel = ((IAgVAMCSSegment)initState).Results[3] as IAgVAStateCalcRelMotion;

            intrackrateRel.ReferenceSelection = AgEVACalcObjectReference.eVACalcObjectReferenceSpecified;
            IAgLinkToObject link_4 = intrackrateRel.Reference as IAgLinkToObject;

            link_4.BindTo("Satellite/" + tle.GetSatNumber().ToString());

            ((IAgVAMCSSegment)initState).Results.Add("Relative Motion/RadialRate");
            IAgVAStateCalcRelMotion radialrateRel = ((IAgVAMCSSegment)initState).Results[4] as IAgVAStateCalcRelMotion;

            radialrateRel.ReferenceSelection = AgEVACalcObjectReference.eVACalcObjectReferenceSpecified;
            IAgLinkToObject link_5 = radialrateRel.Reference as IAgLinkToObject;

            link_5.BindTo("Satellite/" + tle.GetSatNumber().ToString());

            ((IAgVAMCSSegment)initState).Results.Add("Relative Motion/CrossTrackRate");
            IAgVAStateCalcRelMotion crosstrackrateRel = ((IAgVAMCSSegment)initState).Results[5] as IAgVAStateCalcRelMotion;

            crosstrackrateRel.ReferenceSelection = AgEVACalcObjectReference.eVACalcObjectReferenceSpecified;
            IAgLinkToObject link_6 = crosstrackrateRel.Reference as IAgLinkToObject;

            link_6.BindTo("Satellite/" + tle.GetSatNumber().ToString());

            /// differential corrector setup ///
            IAgVAProfileDifferentialCorrector dc = ts.Profiles["Differential Corrector"] as IAgVAProfileDifferentialCorrector;

            // control parameters
            IAgVADCControl xControlParam = dc.ControlParameters.GetControlByPaths("InitialState", "InitialState.Cartesian.X");

            xControlParam.Enable       = true;
            xControlParam.MaxStep      = 1;
            xControlParam.Perturbation = 0.1;
            IAgVADCControl yControlParam = dc.ControlParameters.GetControlByPaths("InitialState", "InitialState.Cartesian.Y");

            yControlParam.Enable       = true;
            yControlParam.MaxStep      = 1;
            yControlParam.Perturbation = 0.1;
            IAgVADCControl zControlParam = dc.ControlParameters.GetControlByPaths("InitialState", "InitialState.Cartesian.Z");

            zControlParam.Enable       = true;
            zControlParam.MaxStep      = 1;
            zControlParam.Perturbation = 0.1;
            IAgVADCControl vxControlParam = dc.ControlParameters.GetControlByPaths("InitialState", "InitialState.Cartesian.Vx");

            vxControlParam.Enable       = true;
            vxControlParam.MaxStep      = 0.001;
            vxControlParam.Perturbation = 1e-04;
            IAgVADCControl vyControlParam = dc.ControlParameters.GetControlByPaths("InitialState", "InitialState.Cartesian.Vy");

            vyControlParam.Enable       = true;
            vyControlParam.MaxStep      = 0.001;
            vyControlParam.Perturbation = 1e-04;
            IAgVADCControl vzControlParam = dc.ControlParameters.GetControlByPaths("InitialState", "InitialState.Cartesian.Vz");

            vzControlParam.Enable       = true;
            vzControlParam.MaxStep      = 0.001;
            vzControlParam.Perturbation = 1e-04;

            // results
            double[] deviations = uncertainty.GetRandomDeviation();

            IAgVADCResult intrackResult = dc.Results.GetResultByPaths("InitialState", "InTrack");

            intrackResult.Enable       = true;
            intrackResult.DesiredValue = deviations[0];
            intrackResult.Tolerance    = 0.01;
            IAgVADCResult radialResult = dc.Results.GetResultByPaths("InitialState", "Radial");

            radialResult.Enable       = true;
            radialResult.DesiredValue = deviations[1];
            radialResult.Tolerance    = 0.01;
            IAgVADCResult crosstrackResult = dc.Results.GetResultByPaths("InitialState", "CrossTrack");

            crosstrackResult.Enable       = true;
            crosstrackResult.DesiredValue = deviations[2];
            crosstrackResult.Tolerance    = 0.01;
            IAgVADCResult intrackRateResult = dc.Results.GetResultByPaths("InitialState", "InTrackRate");

            intrackRateResult.Enable       = true;
            intrackRateResult.DesiredValue = deviations[3] / 1000;
            intrackRateResult.Tolerance    = 0.001;
            IAgVADCResult radialRateResult = dc.Results.GetResultByPaths("InitialState", "RadialRate");

            radialRateResult.Enable       = true;
            radialRateResult.DesiredValue = deviations[4] / 1000;
            radialRateResult.Tolerance    = 0.001;
            IAgVADCResult crosstrackRateResult = dc.Results.GetResultByPaths("InitialState", "CrossTrackRate");

            crosstrackRateResult.Enable       = true;
            crosstrackRateResult.DesiredValue = deviations[5] / 1000;
            crosstrackRateResult.Tolerance    = 0.001;

            /// Propagator ///
            IAgVAMCSPropagate propagate = driver.MainSequence.Insert(AgEVASegmentType.eVASegmentTypePropagate, "ToGround", "-") as IAgVAMCSPropagate;

            ((IAgVAMCSSegment)propagate).Properties.Color = Color.Red;
            //propagate.PropagatorName = "CustomProp";
            propagate.PropagatorName = propName;

            // add an Epoch stopping condition
            IAgVAStoppingConditionCollection propStoppingConditions = propagate.StoppingConditions as IAgVAStoppingConditionCollection;
            IAgVAStoppingConditionElement    epochElement           = propStoppingConditions.Add("Epoch");
            IAgVAStoppingCondition           epoch = (IAgVAStoppingCondition)epochElement.Properties;

            epoch.Trip = ((IAgScenario)root.CurrentScenario).StopTime;
            // add an Altitude stopping condition
            IAgVAStoppingConditionElement altitudeElement = propStoppingConditions.Add("Altitude");
            IAgVAStoppingCondition        altitude        = (IAgVAStoppingCondition)altitudeElement.Properties;

            altitude.Trip = 0;
            // remove the original stopping condition
            propagate.StoppingConditions.Remove("Duration");

            // run the MCS
            driver.RunMCS();
            driver.ClearDWCGraphics();


            // get the stop time
            IAgDataPrvInterval dp          = ((IAgStkObject)sat).DataProviders.GetDataPrvIntervalFromPath("Astrogator MCS Ephemeris Segments") as IAgDataPrvInterval;
            IAgDrResult        result      = dp.Exec(((IAgScenario)root.CurrentScenario).StartTime, ((IAgScenario)root.CurrentScenario).StopTime);
            string             satStopTime = result.DataSets[3].GetValues().GetValue(1).ToString();

            if (satStopTime.Equals((Convert.ToString(((IAgScenario)root.CurrentScenario).StopTime))))
            {
                // the satellite does not decay (it is propagated until the scenario stop time)
                propResults.IsDecayed = false;
            }
            else
            {
                propResults.IsDecayed   = true;
                propResults.ImpactEpoch = satStopTime;
                // remove the millisecond part
                satStopTime = satStopTime.Split('.')[0];

                //ask for LLA data at stop time
                IAgDataPrvTimeVar dpInfo  = ((IAgStkObject)sat).DataProviders.GetDataPrvInfoFromPath("LLA State//Fixed") as IAgDataPrvTimeVar;
                IAgDrResult       resInfo = dpInfo.ExecSingle(satStopTime);
                string            lat     = resInfo.DataSets[1].GetValues().GetValue(0).ToString();
                string            lon     = resInfo.DataSets[2].GetValues().GetValue(0).ToString();
                string            alt     = resInfo.DataSets[3].GetValues().GetValue(0).ToString();
                propResults.ImpactLat = lat;
                propResults.ImpactLon = lon;
                propResults.ImpactAlt = alt;

                // create a target object
                IAgTarget target = root.CurrentScenario.Children.New(AgESTKObjectType.eTarget, "Target" + (runId).ToString().PadLeft(3, '0')) as IAgTarget;
                target.Graphics.Color        = Color.Red;
                target.Graphics.LabelVisible = false;
                IAgPosition pos = target.Position;
                pos.AssignGeodetic(lat, lon, 0);

                // create and display the time event
                IAgCrdnProvider   provider   = root.CurrentScenario.Children["Target" + (runId).ToString().PadLeft(3, '0')].Vgt;
                IAgCrdnEventEpoch eventEpoch = provider.Events.Factory.CreateEventEpoch(runId.ToString().PadLeft(3, '0') + "_Impact", "Impact Epoch") as IAgCrdnEventEpoch;
                eventEpoch.Epoch = satStopTime;
                try { root.ExecuteCommand("Timeline * TimeComponent Add ContentView \"Scenario Availability\" \"Target/Target" + (runId).ToString().PadLeft(3, '0') + " " + runId.ToString().PadLeft(3, '0') + "_Impact Time Instant\""); }
                catch (Exception) { }
                root.ExecuteCommand("Timeline * Refresh");

                // create a unique ephemeris file for each Astrogator run
                DateTime now = DateTime.Now;
                string   satEphemerisPath = Directory.GetCurrentDirectory() + "\\Ephemeris\\Reentry_run_" + (runId).ToString().PadLeft(3, '0') + ".e";
                root.ExecuteCommand("ExportDataFile */Satellite/" + tle.GetSatNumber() + "Astrogator Ephemeris \"" + satEphemerisPath + "\" Type STK CoordSys ICRF CentralBody Earth InterpBoundaries Include");
                propResults.EphemerisFilePath = satEphemerisPath;
                // unload Astrogator satellite
                root.CurrentScenario.Children[tle.GetSatNumber() + "Astrogator"].Unload();

                if (runId == nRuns)
                {
                    // remove the TLE sat
                    // root.CurrentScenario.Children[tle.GetSatNumber()].Unload();
                }
            }

            try
            {
                AGI.Ui.Core.IAgUiWindowsCollection windows = app.Windows;
                foreach (dynamic window in app.Windows)
                {
                    string windowCaption = (string)window.Caption;
                    if (windowCaption.Contains("Setup"))
                    {
                        window.Close();
                    }
                }
            }
            catch (Exception ex)
            {
            }

            return(propResults);
        }