Ejemplo n.º 1
0
        //pulls data providers for the aircraft in ICRF frame
        public static List <Array> GetAttitudeData(IAgStkObject obj, double startTime, double timeStep)
        {
            List <Array>           attitudeData = new List <Array>();
            IAgScenario            scenario     = CommonData.StkRoot.CurrentScenario as IAgScenario;
            IAgDrDataSetCollection datasets     = null;

            if (CommonData.objectClass == "Aircraft")
            {
                IAgDataProviderGroup attitudeDP1 = obj.DataProviders["Body Axes Orientation:YPR 321"] as IAgDataProviderGroup;
                IAgDataPrvTimeVar    attitudeDP2 = attitudeDP1.Group["ICRF"] as IAgDataPrvTimeVar;
                IAgDrResult          result      = attitudeDP2.Exec(startTime, scenario.StopTime, timeStep);
                datasets = result.DataSets;
            }
            else if (CommonData.objectClass == "Satellite")
            {
                IAgDataProviderGroup attitudeDP1 = obj.DataProviders["Attitude YPR"] as IAgDataProviderGroup;
                IAgDataPrvTimeVar    attitudeDP2 = attitudeDP1.Group["Seq YPR"] as IAgDataPrvTimeVar;
                IAgDrResult          result      = attitudeDP2.Exec(startTime, scenario.StopTime, timeStep);
                datasets = result.DataSets;
            }

            for (int i = 0; i < datasets.Count; i++)
            {
                attitudeData.Add(datasets[i].GetValues());
            }

            return(attitudeData);
        }
        public static List <double> GetFomLimits(string oaName, string time)
        {
            List <double> limits = new List <double>();

            double maxDouble = -99999;
            double minDouble = -99999;
            double stdDev    = -99999;

            try
            {
                string            name     = "CoverageDefinition/" + oaName + "/FigureOfMerit/" + oaName + "_FOM";
                IAgStkObject      fom      = CommonData.StkRoot.GetObjectFromPath(name);
                IAgDataPrvTimeVar fomDp    = fom.DataProviders["Overall Value by Time"] as IAgDataPrvTimeVar;
                IAgDrResult       result   = fomDp.ExecSingle(time);
                Array             minLimit = result.DataSets.GetDataSetByName("Minimum").GetValues();
                minDouble = Double.Parse(minLimit.GetValue(0).ToString());

                Array maxLimit = result.DataSets.GetDataSetByName("Maximum").GetValues();
                maxDouble = Double.Parse(maxLimit.GetValue(0).ToString());

                Array std = result.DataSets.GetDataSetByName("Standard Deviation").GetValues();
                stdDev = Double.Parse(std.GetValue(0).ToString());
            }
            catch (Exception)
            {
            }
            limits.Add(Math.Round(minDouble, 3));
            limits.Add(Math.Round(maxDouble, 3));
            limits.Add(Math.Round(stdDev, 2));
            return(limits);
        }
Ejemplo n.º 3
0
        public static double[] GetRICDifferenceAtTCA(string sat1Path, string sat2Path, string epochISOYMD)
        {
            IAgStkObject primary, secondary;

            try
            {
                primary   = StkAssistant.Root.GetObjectFromPath(sat1Path);
                secondary = StkAssistant.Root.GetObjectFromPath(sat2Path);
            }
            catch
            {
                return(null);
            }
            IAgDataProviderInfo dpInfo = primary.DataProviders["RIC Coordinates"];

            IAgDataProvider dataProvider = primary.DataProviders["RIC Coordinates"] as IAgDataProvider;

            dataProvider.PreData = secondary.Path.Replace(StkAssistant.Root.CurrentScenario.Path, "");
            IAgDataPrvTimeVar dpTimeVarying = dataProvider as IAgDataPrvTimeVar;
            Array             elements      = new object[] { "Radial", "In-Track", "Cross-Track" };
            IAgDrResult       dpResult      = dpTimeVarying.ExecSingleElements(epochISOYMD, elements);

            double[] ric = new double[3];
            ric[0] = (double)dpResult.DataSets[0].GetValues().GetValue(0);
            ric[1] = (double)dpResult.DataSets[1].GetValues().GetValue(0);
            ric[2] = (double)dpResult.DataSets[2].GetValues().GetValue(0);

            return(ric);
        }
Ejemplo n.º 4
0
        private void computeAccess_Click(object sender, EventArgs e)
        {
            string accessToName   = cbAccessTo.GetItemText(cbAccessTo.SelectedItem);
            string accessFromName = cbAccessTo.GetItemText(cbAccessFrom.SelectedItem);

            IAgStkObject toObj   = CommonData.StkRoot.GetObjectFromPath(accessToName);
            IAgStkObject fromObj = CommonData.StkRoot.GetObjectFromPath(accessFromName);
            IAgStkAccess access  = toObj.GetAccessToObject(fromObj);

            access.ComputeAccess();

            // Get access results from data provider
            IAgIntervalCollection accessIntervals    = access.ComputedAccessIntervalTimes;
            IAgDataPrvTimeVar     accessDataProvider = access.DataProviders.GetDataPrvTimeVarFromPath("AER Data//Default");
            Array dataProviderElements = new object[] { "Time", "Azimuth", "Elevation", "Range" };

            dataGridViewAccess.Rows.Clear();
            dataGridViewAccess.Rows.Add();
            for (int i = 0; i < accessIntervals.Count; i++)
            {
                object startTime = null, stopTime = null;
                accessIntervals.GetInterval(i, out startTime, out stopTime);
                IAgDrResult dataProviderResult = accessDataProvider.ExecElements(startTime, stopTime, 1, ref dataProviderElements);
                Array       timeValues         = dataProviderResult.DataSets[0].GetValues();
                Array       azimuthValues      = dataProviderResult.DataSets[1].GetValues();
                Array       elevationValues    = dataProviderResult.DataSets[2].GetValues();
                Array       rangeValues        = dataProviderResult.DataSets[3].GetValues();


                for (int j = 0; j < timeValues.Length; j++)
                {
                    DataGridViewRow row = (DataGridViewRow)dataGridViewAccess.Rows[0].Clone();
                    row.Cells[0].Value = timeValues.GetValue(j).ToString();
                    row.Cells[1].Value = azimuthValues.GetValue(j).ToString();
                    row.Cells[2].Value = elevationValues.GetValue(j).ToString();
                    row.Cells[3].Value = rangeValues.GetValue(j).ToString();
                    dataGridViewAccess.Rows.Add(row);
                }
            }


            ////Get built in Calucation object from Analysis Workbench
            //// Could put into another dataGridView
            //var parameterSets = access.Vgt.ParameterSets["From-To-AER(Body)"];

            ////Get magnitude vector
            //IAgCrdnCalcScalar magnitude = ((IAgCrdn)parameterSets).EmbeddedComponents["From-To-AER(Body).Cartesian.Magnitude"] as IAgCrdnCalcScalar;

            ////Get times of the minimum value for each access interval
            //AgCrdnEventArrayExtrema minTimes = ((IAgCrdn)parameterSets).EmbeddedComponents["From-To-AER(Body).Cartesian.Magnitude.TimesOfLocalMin"] as AgCrdnEventArrayExtrema;
            //Array timeArray = minTimes.FindTimes().Times;
            //for (int i = 0; i < timeArray.Length; i++)
            //{
            //    double result = magnitude.Evaluate(timeArray.GetValue(i)).Value;
            //}
        }
Ejemplo n.º 5
0
        public static double GetSatellitePerigee(string satPath, string dateISOYMD)
        {
            IAgDataPrvTimeVar dpTimeVarying = GetClassicalElementsDP(satPath);
            Array             elements      = new object[] { "Perigee Radius" };
            IAgDrResult       dpResult      = dpTimeVarying.ExecSingleElements(dateISOYMD, elements);

            double perigee = (double)dpResult.DataSets.GetDataSetByName(elements.GetValue(0).ToString()).GetValues().GetValue(0);

            return(perigee);
        }
Ejemplo n.º 6
0
        private static IAgDataPrvTimeVar GetClassicalElementsDP(string satPath)
        {
            IAgStkObject primary = Root.GetObjectFromPath(satPath);

            IAgDataProviderGroup classical    = primary.DataProviders["Classical Elements"] as IAgDataProviderGroup;
            IAgDataProvider      dataProvider = classical.Group["ICRF"] as IAgDataProvider;
            //Time varyign data is given as an array of time based values
            IAgDataPrvTimeVar dpTimeVarying = dataProvider as IAgDataPrvTimeVar;

            return(dpTimeVarying);
        }
Ejemplo n.º 7
0
        public void CheckFlightEndurance(IAgAircraft flight, string enduranceUnit, double enduranceValue)
        {
            if (enduranceUnit.Equals("mi") || enduranceUnit.Equals("km") || enduranceUnit.Equals("nm"))
            {
                root.UnitPreferences["Distance"].SetCurrentUnit(enduranceUnit);
            }
            else
            {
                root.UnitPreferences["Time"].SetCurrentUnit(enduranceUnit);
            }
            bool tooLong = true;

            root.BeginUpdate();
            while (tooLong)
            {
                IAgDataPrvTimeVar dpDistance = ((IAgStkObject)flight).DataProviders["Distance"] as IAgDataPrvTimeVar;
                string            evalTime   = (flight.Route as IAgVePropagatorGreatArc).StopTime.ToString();
                evalTime = evalTime.Substring(0, evalTime.IndexOf("."));

                IAgDrResult dpResult = dpDistance.ExecSingle(evalTime);

                Array distance = dpResult.DataSets.GetDataSetByName("Dist from start").GetValues();
                Array duration = dpResult.DataSets.GetDataSetByName("Time from start").GetValues();

                double distanceTraveled = (double)distance.GetValue(0);
                double timeTraveled     = (double)duration.GetValue(0);

                if (enduranceUnit.Equals("mi") || enduranceUnit.Equals("km") || enduranceUnit.Equals("nm"))
                {
                    if (distanceTraveled < enduranceValue)
                    {
                        tooLong = false;
                    }
                }
                else if (timeTraveled < enduranceValue)
                {
                    tooLong = false;
                }

                if (tooLong)
                {
                    IAgVePropagatorGreatArc route = (IAgVePropagatorGreatArc)flight.Route;
                    route.Waypoints.RemoveAt(route.Waypoints.Count - 2);
                    route.Propagate();
                }
            }
            root.UnitPreferences.ResetUnits();
            root.EndUpdate();
        }
Ejemplo n.º 8
0
        private void RadioButtonOpen_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonOpen.Checked.Equals(true))
            {
                try
                {
                    if (comboBoxSatellite.SelectedItem == null)
                    {
                        throw new Exception("No satellite selected.");
                    }
                    if (comboBoxFacility.SelectedItem == null)
                    {
                        throw new Exception("No facility selected.");
                    }

                    // Disable combo boxes for now
                    comboBoxSatellite.Enabled = false;
                    comboBoxFacility.Enabled  = false;

                    // Disable any previous events initialized
                    try
                    {
                        m_root.OnAnimUpdate -= new IAgStkObjectRootEvents_OnAnimUpdateEventHandler(Root_OnAnimUpdate);
                    }
                    catch { }

                    // Compute access
                    IAgStkObject accessObject = m_root.GetObjectFromPath("Facility/" + comboBoxFacility.SelectedItem.ToString());
                    m_access = accessObject.GetAccess("Satellite/" + comboBoxSatellite.SelectedItem.ToString());
                    m_access.ComputeAccess();

                    // Get AER data provider
                    m_accessProviderIntervals = m_access.DataProviders.GetDataPrvTimeVarFromPath("AER Data/Default");

                    // Add the event handler we will need
                    m_root.OnAnimUpdate += new IAgStkObjectRootEvents_OnAnimUpdateEventHandler(Root_OnAnimUpdate);
                }
                catch (Exception exception)
                {
                    radioButtonOpen.Checked = false;
                    MessageBox.Show(exception.Message, "Error");
                }
            }
        }
Ejemplo n.º 9
0
        //public STKDataProvider(IAgStkObject object0,string Name, bool needPreData)
        //{
        //    m_selectedObject = object0;
        //    m_providerGroup = m_selectedObject.DataProviders["Cartesian Velocity"] as IAgDataProviderGroup;
        //    IAgDataProvider CartVel_provider= (m_providerGroup.Group["J2000"] as IAgDataProvider);

        //    ///Cast Appropiate Data Pro
        //    IAgDataPrvTimeVar Velocity = CartVel_provider as IAgDataPrvTimeVar;
        //    Array elem = new object[] { "x" };
        //    IAgDrResult Speed = Velocity.ExecElements("19 May 2019 22:00:00.000", "19 May 2019 22:10:00.000", 60, ref elem );

        //    m_dataSe = Speed.DataSets[0].GetValues();
        //    ///update_Dataset(26667, "Name", speed);
        //    ///Console.WriteLine(CartVel_providers)
        //}

        public System.Array acquireDataset(string startTime, string stopTime, double timeStep)
        {
            IAgDataProvider provider = null;

            if (m_parent != m_superParent)
            {
                m_providerGroup = m_StkObj.DataProviders[m_superParent] as IAgDataProviderGroup;
                provider        = (m_providerGroup.Group[m_parent] as IAgDataProvider); //m_parent
            }
            else if (m_parent == m_superParent)
            {
                provider = m_StkObj.DataProviders[m_parent] as IAgDataProvider;
            }
            ///Cast Appropiate Data Pro
            try
            {
                IAgDataPrvTimeVar Velocity = provider as IAgDataPrvTimeVar;
                Array             elem     = new object[] { m_DP2 };
                IAgDrResult       result   = Velocity.ExecElements(startTime, stopTime, timeStep, ref elem);
                m_dataArray = result.DataSets[0].GetValues();
            }
            catch
            {
                IAgDataPrvInterval Velocity = provider as IAgDataPrvInterval;
                if (Velocity != null)
                {
                    Array       elem   = new object[] { m_DP2 };
                    IAgDrResult result = Velocity.ExecElements(startTime, stopTime, ref elem);
                    m_dataArray = result.DataSets[0].GetValues();
                }
                else
                {
                    m_Error = true;
                }
            }



            return(m_dataArray);
        }
Ejemplo n.º 10
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);
        }
Ejemplo n.º 11
0
        public List <Waypoint> RasterSearchWaypointGenerator(
            string areaTargetPath, string heading, double speed, double altitude, double turnRadius,
            SwathWidthType swathType, double swathParameter)
        {
            List <Waypoint> waypoints = new List <Waypoint>();

            IAgStkObject areaTarget = root.GetObjectFromPath(areaTargetPath);

            IAgAreaTarget areaTargetObj      = (IAgAreaTarget)areaTarget;
            bool          areaTargetElActive = areaTarget.AccessConstraints.IsConstraintActive(AgEAccessConstraints.eCstrElevationAngle);
            double        restoreAngle       = 0;

            if (!areaTargetElActive)
            {
                IAgAccessCnstrAngle elevationMin = areaTarget.AccessConstraints.AddConstraint(AgEAccessConstraints.eCstrElevationAngle) as IAgAccessCnstrAngle;
                root.UnitPreferences["Angle"].SetCurrentUnit("deg");
                elevationMin.Angle = 90;
            }
            else
            {
                IAgAccessCnstrAngle elevationMin = areaTarget.AccessConstraints.GetActiveConstraint(AgEAccessConstraints.eCstrElevationAngle) as IAgAccessCnstrAngle;
                root.UnitPreferences["Angle"].SetCurrentUnit("deg");
                restoreAngle       = (double)elevationMin.Angle;
                elevationMin.Angle = 90;
            }

            double minLat = 90;
            double maxLat = -90;
            double minLon = 180;
            double maxLon = -180;

            root.UnitPreferences["Angle"].SetCurrentUnit("deg");
            switch (areaTargetObj.AreaType)
            {
            case AgEAreaType.eEllipse:
                IAgDataProviderGroup boundingProvider = areaTarget.DataProviders["Bounding Rectangle"] as IAgDataProviderGroup;
                IAgDataPrvFixed      dpElements       = boundingProvider.Group["Corner Points"] as IAgDataPrvFixed;
                IAgDrResult          atDataPrvResult  = dpElements.Exec();

                Array atLats = atDataPrvResult.DataSets.GetDataSetByName("Geodetic-Lat").GetValues();
                Array atLons = atDataPrvResult.DataSets.GetDataSetByName("Geodetic-Lon").GetValues();
                foreach (object item in atLats)
                {
                    if ((double)item > maxLat)
                    {
                        maxLat = (double)item;
                    }
                    if ((double)item < minLat)
                    {
                        minLat = (double)item;
                    }
                }
                foreach (object item in atLons)
                {
                    if ((double)item > maxLon)
                    {
                        maxLon = (double)item;
                    }
                    if ((double)item < minLon)
                    {
                        minLon = (double)item;
                    }
                }
                break;

            case AgEAreaType.ePattern:
                IAgAreaTypePatternCollection boundary = areaTargetObj.AreaTypeData as IAgAreaTypePatternCollection;

                foreach (IAgAreaTypePattern item in boundary)
                {
                    if ((double)item.Lat > maxLat)
                    {
                        maxLat = (double)item.Lat;
                    }
                    if ((double)item.Lat < minLat)
                    {
                        minLat = (double)item.Lat;
                    }

                    if ((double)item.Lon > maxLon)
                    {
                        maxLon = (double)item.Lon;
                    }
                    if ((double)item.Lon < minLon)
                    {
                        minLon = (double)item.Lon;
                    }
                }

                break;

            default:
                break;
            }
            double deltaLat = maxLat - minLat;
            double deltaLon = maxLon - minLon;

            IAgExecCmdResult cmdResult;

            switch (heading)
            {
            case "NorthSouth":
                cmdResult = root.ExecuteCommand("MeasureSurfaceDistance * " +
                                                minLat + " " + minLon + " " + minLat + " " + maxLon);
                break;

            case "EastWest":
                cmdResult = root.ExecuteCommand("MeasureSurfaceDistance * " +
                                                minLat + " " + minLon + " " + maxLat + " " + minLon);
                break;

            default:
                cmdResult = root.ExecuteCommand("MeasureSurfaceDistance * " +
                                                minLat + " " + minLon + " " + maxLat + " " + minLon);
                break;
            }



            double regionWidth = double.Parse(cmdResult[0]);

            int numPasses = DetermineNumPasses(swathType, swathParameter, altitude, regionWidth, null);

            if (numPasses < 1)
            {
                MessageBox.Show("No Passes.  Try Adjusting Swath Width Parameters");
                return(waypoints);
            }
            root.BeginUpdate();

            string           gvName        = uniqueName("gridTester", AgESTKObjectType.eGroundVehicle);
            IAgGroundVehicle groundVehicle = root.CurrentScenario.Children.New(AgESTKObjectType.eGroundVehicle, gvName) as IAgGroundVehicle;

            groundVehicle.Graphics.SetAttributesType(AgEVeGfxAttributes.eAttributesBasic);
            IAgVeGfxAttributesBasic gvGfx = groundVehicle.Graphics.Attributes as IAgVeGfxAttributesBasic;

            gvGfx.Inherit   = false;
            gvGfx.IsVisible = false;

            IAgVePropagatorGreatArc route = groundVehicle.Route as IAgVePropagatorGreatArc;

            //route.ArcGranularity = 51.333;
            route.SetAltitudeRefType(AgEVeAltitudeRef.eWayPtAltRefWGS84);
            route.Method = AgEVeWayPtCompMethod.eDetermineTimeAccFromVel;

            Waypoint waypoint1 = new Waypoint();
            Waypoint waypoint2 = new Waypoint();
            bool     headEast  = true;


            double loopMin;
            double loopMax;
            double gridAngleStep;

            switch (heading)
            {
            case "NorthSouth":
                loopMin       = minLon;
                loopMax       = maxLon;
                gridAngleStep = (maxLon - minLon) / numPasses;
                break;

            case "EastWest":
                loopMin       = minLat;
                loopMax       = maxLat;
                gridAngleStep = (maxLat - minLat) / numPasses;
                break;

            default:
                loopMin       = minLat;
                loopMax       = maxLat;
                gridAngleStep = .95 * (maxLat - minLat) / numPasses;
                break;
            }

            for (double eval = loopMin; eval <= loopMax; eval += gridAngleStep)
            {
                route.Waypoints.RemoveAll();
                IAgVeWaypointsElement thisWaypoint1;
                IAgVeWaypointsElement thisWaypoint2;
                switch (heading)
                {
                case "NorthSouth":
                    thisWaypoint1           = route.Waypoints.Add();
                    thisWaypoint1.Latitude  = minLat - gridAngleStep;
                    thisWaypoint1.Longitude = eval;
                    thisWaypoint1.Altitude  = 0;

                    thisWaypoint2           = route.Waypoints.Add();
                    thisWaypoint2.Latitude  = maxLat + gridAngleStep;
                    thisWaypoint2.Longitude = eval;
                    thisWaypoint2.Altitude  = 0;
                    break;

                case "EastWest":
                default:
                    thisWaypoint1           = route.Waypoints.Add();
                    thisWaypoint1.Latitude  = eval;
                    thisWaypoint1.Longitude = minLon - gridAngleStep;
                    thisWaypoint1.Altitude  = 0;

                    thisWaypoint2           = route.Waypoints.Add();
                    thisWaypoint2.Latitude  = eval;
                    thisWaypoint2.Longitude = maxLon + gridAngleStep;
                    thisWaypoint2.Altitude  = 0;
                    break;
                }
                route.Propagate();

                IAgStkAccess access = areaTarget.GetAccessToObject((IAgStkObject)groundVehicle);
                access.ComputeAccess();

                IAgDataPrvInterval dpAccess = access.DataProviders["Access Data"] as IAgDataPrvInterval;
                IAgScenario        scen     = root.CurrentScenario as IAgScenario;
                IAgDrResult        result   = dpAccess.Exec(scen.StartTime, scen.StopTime);


                if (result.DataSets.Count > 0)
                {
                    Array startTimes = result.DataSets.GetDataSetByName("Start Time").GetValues();
                    Array stopTimes  = result.DataSets.GetDataSetByName("Stop Time").GetValues();

                    string startTime = (string)startTimes.GetValue(0);
                    string stopTime  = (string)stopTimes.GetValue(stopTimes.GetLength(0) - 1);

                    IAgDataProviderGroup dpLLA         = ((IAgStkObject)groundVehicle).DataProviders["LLA State"] as IAgDataProviderGroup;
                    IAgDataPrvTimeVar    dpElements    = dpLLA.Group["Fixed"] as IAgDataPrvTimeVar;
                    IAgDrResult          DataPrvResult = dpElements.ExecSingle(startTime);

                    Array Lats = DataPrvResult.DataSets.GetDataSetByName("Lat").GetValues();
                    Array Lons = DataPrvResult.DataSets.GetDataSetByName("Lon").GetValues();

                    waypoint1                 = new Waypoint();
                    waypoint1.Latitude        = (double)Lats.GetValue(0);
                    waypoint1.Longitude       = (double)Lons.GetValue(0);
                    waypoint1.Altitude        = altitude;
                    waypoint1.SurfaceAltitude = 0;
                    waypoint1.Speed           = speed;
                    waypoint1.TurnRadius      = turnRadius;


                    IAgDataProviderGroup dpLLA1         = ((IAgStkObject)groundVehicle).DataProviders["LLA State"] as IAgDataProviderGroup;
                    IAgDataPrvTimeVar    dpElements1    = dpLLA1.Group["Fixed"] as IAgDataPrvTimeVar;
                    IAgDrResult          DataPrvResult1 = dpElements1.ExecSingle(stopTime);

                    Array Lats1 = DataPrvResult1.DataSets.GetDataSetByName("Lat").GetValues();
                    Array Lons1 = DataPrvResult1.DataSets.GetDataSetByName("Lon").GetValues();

                    waypoint2                 = new Waypoint();
                    waypoint2.Latitude        = (double)Lats1.GetValue(0);
                    waypoint2.Longitude       = (double)Lons1.GetValue(0);
                    waypoint2.Altitude        = altitude;
                    waypoint2.SurfaceAltitude = 0;
                    waypoint2.Speed           = speed;
                    waypoint2.TurnRadius      = turnRadius;


                    if (headEast)
                    {
                        waypoints.Add(waypoint1);
                        waypoints.Add(waypoint2);
                    }
                    else
                    {
                        waypoints.Add(waypoint2);
                        waypoints.Add(waypoint1);
                    }
                    headEast = !headEast;
                }
                access.RemoveAccess();
            }

            ((IAgStkObject)groundVehicle).Unload();

            if (!areaTargetElActive)
            {
                areaTarget.AccessConstraints.RemoveConstraint(AgEAccessConstraints.eCstrElevationAngle);
            }
            else
            {
                IAgAccessCnstrAngle elevationMin = areaTarget.AccessConstraints.GetActiveConstraint(AgEAccessConstraints.eCstrElevationAngle) as IAgAccessCnstrAngle;
                root.UnitPreferences["Angle"].SetCurrentUnit("deg");
                elevationMin.Angle = restoreAngle;
            }

            root.EndUpdate();
            root.UnitPreferences.ResetUnits();
            return(waypoints);
        }
Ejemplo n.º 12
0
        //Main Function
        private void Generate_Click(object sender, EventArgs e)
        {
            int check = FieldCheck();

            if (check == 0)
            {
                RemoveProximityGeometry();
                try
                {
                    CommonData.StkRoot.UnitPreferences.SetCurrentUnit("Distance", "km");
                    CommonData.RunList.Clear();
                    CommonData.TargetName = TargetSat.Text;
                    CommonData.ActorName  = ActorSat.Text;
                    //Set user bounds for safety
                    double userMinRange = Double.Parse(SphericalMag.Text) / 1000;
                    double userMinR     = Double.Parse(RMag.Text) / 1000;
                    double userMinI     = Double.Parse(IMag.Text) / 1000;
                    double userMinC     = Double.Parse(CMag.Text) / 1000;

                    IAgScenario  scenario = CommonData.StkRoot.CurrentScenario as IAgScenario;
                    IAgStkObject satObj   = CommonData.StkRoot.GetObjectFromPath("Satellite/" + ActorSat.Text);
                    IAgSatellite sat      = satObj as IAgSatellite;

                    //Get all maneuver end times for actor satellite
                    IAgDataProviderGroup   maneuverDpGroup = satObj.DataProviders["Astrogator Maneuver Ephemeris Block Final"] as IAgDataProviderGroup;
                    IAgDataPrvTimeVar      maneuverDp      = maneuverDpGroup.Group["Cartesian Elems"] as IAgDataPrvTimeVar;
                    IAgDrResult            result          = maneuverDp.Exec(scenario.StartTime, scenario.StopTime, 60);
                    IAgDrDataSetCollection maneuverData    = result.DataSets;



                    //If there is maneuvers, run iterations for each maneuver. If no maneuvers then just pull closest RIC data for entire trajectory
                    if (maneuverData.Count != 0)
                    {
                        CommonData.HasManeuvers = true;

                        //Get maneuver numbers
                        IAgDataPrvInterval summaryDp     = satObj.DataProviders["Maneuver Summary"] as IAgDataPrvInterval;
                        IAgDrResult        summaryResult = summaryDp.Exec(scenario.StartTime, scenario.StopTime);
                        Array maneuverNumbers            = summaryResult.DataSets.GetDataSetByName("Maneuver Number").GetValues();
                        int   maxManeuverNum             = maneuverNumbers.Length;

                        //Get handles to cartesian position and velocity to seed passive safety runs
                        IAgDataProviderGroup cartPos   = satObj.DataProviders["Cartesian Position"] as IAgDataProviderGroup;
                        IAgDataPrvTimeVar    cartPosDP = cartPos.Group["ICRF"] as IAgDataPrvTimeVar;

                        IAgDataProviderGroup cartVel   = satObj.DataProviders["Cartesian Velocity"] as IAgDataProviderGroup;
                        IAgDataPrvTimeVar    cartVelDP = cartVel.Group["ICRF"] as IAgDataPrvTimeVar;

                        //Create passive safety satellite. Set to Astrogator and pull handles to initial state and propagate segments
                        IAgStkObject passiveSatObj = CreatorFunctions.GetCreateSatellite("PassiveCheck");
                        IAgSatellite passiveSat    = passiveSatObj as IAgSatellite;
                        passiveSat.SetPropagatorType(AgEVePropagatorType.ePropagatorAstrogator);
                        IAgVADriverMCS passiveDriver = passiveSat.Propagator as IAgVADriverMCS;

                        IAgVAMCSInitialState          intState = passiveDriver.MainSequence[0] as IAgVAMCSInitialState;
                        IAgVAMCSPropagate             prop     = passiveDriver.MainSequence[1] as IAgVAMCSPropagate;
                        IAgVAStoppingConditionElement sc1      = prop.StoppingConditions[0];
                        IAgVAStoppingCondition        sc       = sc1.Properties as IAgVAStoppingCondition;
                        sc.Trip = PropTime.Text;

                        AgVAElementCartesian element = intState.Element as AgVAElementCartesian;
                        Array    epoch;
                        Array    vx;
                        Array    vy;
                        Array    vz;
                        Array    x;
                        Array    y;
                        Array    z;
                        String   epochCur;
                        DateTime dateCur;
                        //Assign cartesian elements to PassiveCheck satellite from actor maneuver maneuver data. Run each iteration to see if resulting trajectory violates constraints
                        for (int i = 0; i < maxManeuverNum; i++)
                        {
                            //Get maneuver time and offset in time by 0.25 sec to account for boundrary conditions around impulsive maneuvers
                            epoch    = maneuverData[0 + (i * 7)].GetValues();
                            epochCur = epoch.GetValue(0).ToString();
                            dateCur  = DateTime.Parse(epochCur);
                            dateCur  = dateCur.AddMilliseconds(250);
                            //dateCur = DateTime.ParseExact(epochCur, "dd MMM yyyy HH:mm:ss.fff", CultureInfo.InvariantCulture);
                            epochCur = dateCur.ToString("dd MMM yyyy HH:mm:ss.fff");

                            //Get cartesian state vector for given time
                            result = cartPosDP.ExecSingle(epochCur);
                            x      = result.DataSets.GetDataSetByName("x").GetValues();
                            y      = result.DataSets.GetDataSetByName("y").GetValues();
                            z      = result.DataSets.GetDataSetByName("z").GetValues();

                            result = cartVelDP.ExecSingle(epochCur);
                            vx     = result.DataSets.GetDataSetByName("x").GetValues();
                            vy     = result.DataSets.GetDataSetByName("y").GetValues();
                            vz     = result.DataSets.GetDataSetByName("z").GetValues();

                            //Create passive run output to be used in visualization
                            PassiveRun run = new PassiveRun();
                            run.UserMinRange    = Double.Parse(SphericalMag.Text) / 1000;
                            run.UserMinR        = Double.Parse(RMag.Text) / 1000;
                            run.UserMinI        = Double.Parse(IMag.Text) / 1000;
                            run.UserMinC        = Double.Parse(CMag.Text) / 1000;
                            intState.OrbitEpoch = epochCur;
                            element.Vx          = Double.Parse(vx.GetValue(0).ToString());
                            element.Vy          = Double.Parse(vy.GetValue(0).ToString());
                            element.Vz          = Double.Parse(vz.GetValue(0).ToString());
                            element.X           = Double.Parse(x.GetValue(0).ToString());
                            element.Y           = Double.Parse(y.GetValue(0).ToString());
                            element.Z           = Double.Parse(z.GetValue(0).ToString());

                            passiveDriver.RunMCS();

                            run.Vx       = Double.Parse(vx.GetValue(0).ToString());
                            run.Vy       = Double.Parse(vy.GetValue(0).ToString());
                            run.Vz       = Double.Parse(vz.GetValue(0).ToString());
                            run.X        = Double.Parse(x.GetValue(0).ToString());
                            run.Y        = Double.Parse(y.GetValue(0).ToString());
                            run.Z        = Double.Parse(z.GetValue(0).ToString());
                            run.PropTime = Double.Parse(PropTime.Text);

                            //Pull closest point to target for each iteration and save to passive run output
                            IAgDataProvider psatDp = passiveSatObj.DataProviders["RIC Coordinates"] as IAgDataProvider;
                            psatDp.PreData = "Satellite/" + TargetSat.Text;
                            IAgDataPrvTimeVar psatDpTimeVar = psatDp as IAgDataPrvTimeVar;
                            IAgDrResult       psatDp2       = psatDpTimeVar.Exec(scenario.StartTime, scenario.StopTime, Double.Parse(TimeStep.Text));
                            run.Range         = psatDp2.DataSets.GetDataSetByName("Range").GetValues();
                            run.Intrack       = psatDp2.DataSets.GetDataSetByName("In-Track").GetValues();
                            run.Crosstrack    = psatDp2.DataSets.GetDataSetByName("Cross-Track").GetValues();
                            run.Radial        = psatDp2.DataSets.GetDataSetByName("Radial").GetValues();
                            run.MinRange      = MathFunctions.ArrayMin(run.Range);
                            run.MinIntrack    = MathFunctions.ArrayMinAbs(run.Intrack);
                            run.MinCrosstrack = MathFunctions.ArrayMinAbs(run.Crosstrack);
                            run.MinRadial     = MathFunctions.ArrayMinAbs(run.Radial);
                            //run.ManeuverTime = epoch.GetValue(0).ToString();
                            run.ManeuverTime = epochCur;

                            //spherical
                            if (radioButton1.Checked)
                            {
                                run.IsSpherical = true;
                                if (run.MinRange < userMinRange)
                                {
                                    run.Safe = false;
                                }
                                else
                                {
                                    run.Safe = true;
                                }
                            }
                            //independent axis
                            else
                            {
                                run.IsSpherical = false;
                                if (Math.Abs(run.MinIntrack) < userMinI && Math.Abs(run.MinRadial) < userMinR && Math.Abs(run.MinCrosstrack) < userMinC)
                                {
                                    bool tripped = false;
                                    for (int j = 0; j < run.Range.Length; j++)
                                    {
                                        if (Math.Abs(Double.Parse(run.Intrack.GetValue(j).ToString())) < userMinI && Math.Abs(Double.Parse(run.Radial.GetValue(j).ToString())) < userMinR && Math.Abs(Double.Parse(run.Crosstrack.GetValue(j).ToString())) < userMinC)
                                        {
                                            run.Safe = false;
                                            tripped  = true;
                                            break;
                                        }
                                    }
                                    if (!tripped)
                                    {
                                        run.Safe = true;
                                    }
                                }
                                else
                                {
                                    run.Safe = true;
                                }
                            }

                            CommonData.RunList.Add(run);
                        }
                    }
                    else
                    {
                        CommonData.HasManeuvers = false;
                        PassiveRun      run   = new PassiveRun();
                        IAgDataProvider satDp = satObj.DataProviders["RIC Coordinates"] as IAgDataProvider;
                        satDp.PreData = "Satellite/" + TargetSat.Text;
                        IAgDataPrvTimeVar satDpTimeVar = satDp as IAgDataPrvTimeVar;
                        IAgDrResult       satDp2       = satDpTimeVar.Exec(scenario.StartTime, scenario.StopTime, Double.Parse(TimeStep.Text));
                        run.Range         = satDp2.DataSets.GetDataSetByName("Range").GetValues();
                        run.Intrack       = satDp2.DataSets.GetDataSetByName("In-Track").GetValues();
                        run.Crosstrack    = satDp2.DataSets.GetDataSetByName("Cross-Track").GetValues();
                        run.Radial        = satDp2.DataSets.GetDataSetByName("Radial").GetValues();
                        run.MinRange      = MathFunctions.ArrayMin(run.Range);
                        run.MinIntrack    = MathFunctions.ArrayMinAbs(run.Intrack);
                        run.MinCrosstrack = MathFunctions.ArrayMinAbs(run.Crosstrack);
                        run.MinRadial     = MathFunctions.ArrayMinAbs(run.Radial);
                        run.ManeuverTime  = "N/A";

                        //spherical
                        if (radioButton1.Checked)
                        {
                            run.IsSpherical = true;
                            if (run.MinRange < userMinRange)
                            {
                                run.Safe = false;
                            }
                            else
                            {
                                run.Safe = true;
                            }
                        }
                        //independent axis
                        else
                        {
                            run.IsSpherical = false;
                            if (Math.Abs(run.MinIntrack) < userMinI && Math.Abs(run.MinRadial) < userMinR && Math.Abs(run.MinCrosstrack) < userMinC)
                            {
                                bool tripped = false;
                                for (int j = 0; j < run.Range.Length; j++)
                                {
                                    if (Math.Abs(Double.Parse(run.Intrack.GetValue(j).ToString())) < userMinI && Math.Abs(Double.Parse(run.Radial.GetValue(j).ToString())) < userMinR && Math.Abs(Double.Parse(run.Crosstrack.GetValue(j).ToString())) < userMinC)
                                    {
                                        run.Safe = false;
                                        tripped  = true;
                                        break;
                                    }
                                }
                                if (!tripped)
                                {
                                    run.Safe = true;
                                }
                            }
                            else
                            {
                                run.Safe = true;
                            }
                        }

                        CommonData.RunList.Add(run);
                    }
                    CommonData.BeenRun = true;
                }
                catch (Exception)
                {
                    MessageBox.Show("Passive Safety Check Failed");
                }
            }
        }
Ejemplo n.º 13
0
        public void Orbit_generation()
        {
            //load_orbit_file();
            scenarioCheck();
            var format = new NumberFormatInfo();

            format.NegativeSign           = "-";
            format.NumberDecimalSeparator = ".";
            // planetodetic.Lat = Double.Parse(lat2[i], format);

            for (int i = 0; i < orbitmissioncount; i++)
            {
                //debug infomation///////
                if (orbitdata[i].misnum == orbitdata[i].cod_id && orbitdata[i].used == 1 && orbitdata[i].efileused == false)
                {
                    //generate the timeline file
                    TL_file_generator(orbitdata[i].name, orbitdata[i].name);

                    Console.Write("Misnum == cod_id\n");

                    Console.Write("Mission= " + orbitdata[i].name + "\n" + orbitdata[i].epoch + " " + orbitdata[i].epoch_time + " ");
                    Console.Write(orbitdata[i].sma + " " + orbitdata[i].ecc + " " + orbitdata[i].inc + " " + orbitdata[i].raan + " " + orbitdata[i].aop + " " + orbitdata[i].ma + "\n");

                    string centerbodyname;
                    if (orbitdata[i].centerbody == 1)
                    {
                        centerbodyname = "Earth";
                    }
                    else if (orbitdata[i].centerbody == 2)
                    {
                        centerbodyname = "Moon";
                    }
                    else
                    {
                        centerbodyname = "Earth";
                    }


                    // AGI.STKObjects.IAgSatellite sat = (IAgSatellite)m_oApplication.CurrentScenario.Children.New(AGI.STKObjects.AgESTKObjectType.eSatellite, mission2[i]);
                    //sat.SetPropagatorType(AGI.STKObjects.AgEVePropagatorType.ePropagatorTwoBody);

                    try
                    {
                        //create a new sat with the cod orbit details;
                        orbitdata[i].MisSat = (IAgSatellite)m_oApplication.CurrentScenario.Children.NewOnCentralBody(AGI.STKObjects.AgESTKObjectType.eSatellite, orbitdata[i].name, centerbodyname);
                        //AGI.STKObjects.IAgSatellite sat = (IAgSatellite)m_oApplication.CurrentScenario.Children.NewOnCentralBody(AGI.STKObjects.AgESTKObjectType.eSatellite, orbitdata[i].name, centerbodyname);
                    }catch
                    {
                        //sat already exists reset the scenario;
                        this.m_oApplication.CloseScenario();
                        scenarioCheck();
                        Orbit_generation();
                        return;
                    }
                    //disable the leading ground track
                    groundtrack_set(orbitdata[i].MisSat, groundtrack_displayed);

                    //set the propagator type to HPOP
                    orbitdata[i].MisSat.SetPropagatorType(AGI.STKObjects.AgEVePropagatorType.ePropagatorHPOP);

                    //TODO update below code to use sat not hpop;
                    AGI.STKObjects.IAgVePropagatorHPOP hpop = (AGI.STKObjects.IAgVePropagatorHPOP)orbitdata[i].MisSat.Propagator;

                    IAgOrbitState orbit = hpop.InitialState.Representation;
                    //create the string to hold the missions epoch date & time
                    string cmb_epoch = orbitdata[i].epoch;
                    cmb_epoch += " ";
                    cmb_epoch += orbitdata[i].epoch_time;
                    DateTime epochDT = Convert.ToDateTime(orbitdata[i].epoch);
                    DateTime startDT = Convert.ToDateTime(orbitdata[i].start_date);
                    DateTime endDT;

                    if (orbitdata[i].endopt == 0)
                    {
                        endDT = startDT;
                        endDT = endDT.AddDays((double)orbitdata[i].duration);
                        orbitdata[i].end_time = orbitdata[i].start_time;
                    }
                    else
                    {
                        endDT = Convert.ToDateTime(orbitdata[i].end_date);
                    }

                    //hpop.ForceModel.EclipsingBodies.AssignEclipsingBody( centerbodyname);
                    //check the centerbody of the provided orbit data;
                    if (orbitdata[i].centerbody == 1)
                    {// centerbody == EARTH
                        Console.Write("centerbody2[i]) == 1 \n");
                        Console.Write("\n Centralbodyfile=" + hpop.ForceModel.CentralBodyGravity.File + "\n");

                        hpop.ForceModel.Drag.Use = false;
                        hpop.ForceModel.SolarRadiationPressure.Use = false;
                    }
                    else if (orbitdata[i].centerbody == 2)
                    {//CenterBody == Moon
                        Console.Write("centerbody2[i]) == 2 \n");
                        hpop.ForceModel.Drag.Use = false;
                        hpop.ForceModel.SolarRadiationPressure.Use = false;

                        Console.Write("\n Centralbodyfile=" + hpop.ForceModel.CentralBodyGravity.File + "\n");
                        //change gravity file for HPOP use with the moon
                        hpop.ForceModel.CentralBodyGravity.File = "STKData\\CentralBodies\\Moon\\LP100K.grv";
                    }
                    //hpop.InitialState.Representation.Assign(orbit);
                    Console.Write("set epochtime = " + epochDT.ToString("dd MMM yyyy ") + orbitdata[i].epoch_time + "\n");
                    //set the epoch date/time from the orbit bin file
                    hpop.InitialState.Representation.Epoch = (epochDT.ToString("dd MMM yyyy ") + orbitdata[i].epoch_time);

                    Console.Write("set start/stop times = " + (startDT.ToString("dd MMM yyyy ") + orbitdata[i].start_time) + " / " + startDT.AddDays(1).ToString("dd MMM yyyy ") + "\n");
                    //only proagate the orbit 1 day from the start date/time to get the required data to convert to a Fixed coordnate system
                    hpop.EphemerisInterval.SetStartAndStopTimes((startDT.ToString("dd MMM yyyy ") + orbitdata[i].start_time), startDT.AddDays(1).ToString("dd MMM yyyy "));
                    //hpop.EphemerisInterval.SetStartAndStopTimes((startDT.ToString("dd MMM yyyy ") + orbitdata[i].start_time), (endDT.ToString("dd MMM yyyy ") + orbitdata[i].end_time));
                    hpop.InitialState.Representation.AssignClassical(AgECoordinateSystem.eCoordinateSystemJ2000, orbitdata[i].sma, orbitdata[i].ecc, orbitdata[i].inc, orbitdata[i].aop, orbitdata[i].raan, orbitdata[i].ma);

                    hpop.Propagate();
                    //check if the orbit is earth centered and that the
                    //     orbit start date is different from the Mission model date
                    if (orbitdata[i].centerbody == 1 && orbitdata[i].start_date != startdate)
                    {
                        Console.Write("Startdate != orbit_start date converting to Cartesian elements for fixed system" + "\n");

                        IAgStkObject sat = m_oApplication.CurrentScenario.Children[orbitdata[i].name];

                        // Get the satellite's ICRF cartesian position at 180 EpSec using the data provider interface
                        IAgDataProviderGroup dpGroup = sat.DataProviders["Cartesian Position"] as IAgDataProviderGroup;
                        Array elements = new object[] { "x", "y", "z" };
                        //***TODO*** find J2000 group instead of ICRF
                        IAgDataPrvTimeVar dp = dpGroup.Group["ICRF"] as IAgDataPrvTimeVar;

                        //get the elements at the start date/time of the orbit using in NPAS
                        IAgDrResult dpResult = dp.ExecSingleElements(hpop.StartTime, ref elements);

                        Console.Write("hpop.startTime=" + hpop.StartTime + "\n");


                        double xICRF = (double)dpResult.DataSets[0].GetValues().GetValue(0);
                        double yICRF = (double)dpResult.DataSets[1].GetValues().GetValue(0);
                        double zICRF = (double)dpResult.DataSets[2].GetValues().GetValue(0);

                        // Get the satellite's ICRF cartesian velocity at 180 EpSec using the data provider interface
                        dpGroup = sat.DataProviders["Cartesian Velocity"] as IAgDataProviderGroup;

                        //***TODO*** find J2000 group instead of ICRF
                        dp = dpGroup.Group["ICRF"] as IAgDataPrvTimeVar;

                        //get the elements at the start date/time of the orbit using in NPAS
                        dpResult = dp.ExecSingleElements(hpop.StartTime, ref elements);

                        double xvelICRF = (double)dpResult.DataSets[0].GetValues().GetValue(0);
                        double yvelICRF = (double)dpResult.DataSets[1].GetValues().GetValue(0);
                        double zvelICRF = (double)dpResult.DataSets[2].GetValues().GetValue(0);

                        Console.Write("J2000 cartesian vectors\n");
                        Console.Write("X=" + xICRF + " Y=" + yICRF + " Z=" + zICRF + "\n");
                        Console.Write("Xd=" + xvelICRF + " Yd=" + yvelICRF + " Zd=" + zvelICRF + "\n");

                        // Create a position vector using the ICRF coordinates
                        IAgCrdnAxes         axesICRF   = sat.Vgt.WellKnownAxes.Earth.ICRF;
                        IAgCartesian3Vector vectorICRF = m_oApplication.ConversionUtility.NewCartesian3Vector();

                        vectorICRF.Set(xICRF, yICRF, zICRF);

                        // Create a velocity vector using the ICRF coordinates
                        IAgCartesian3Vector vectorvelICRF = m_oApplication.ConversionUtility.NewCartesian3Vector();
                        vectorvelICRF.Set(xvelICRF, yvelICRF, zvelICRF);


                        // Use the TransformWithRate method to transform ICRF to Fixed
                        IAgCrdnAxes axesFixed = sat.Vgt.WellKnownAxes.Earth.Fixed;
                        IAgCrdnAxesTransformWithRateResult result = axesICRF.TransformWithRate(hpop.StartTime, axesFixed, vectorICRF, vectorvelICRF);

                        // Get the Fixed position and velocity coordinates
                        double xFixed    = result.Vector.X;
                        double yFixed    = result.Vector.Y;
                        double zFixed    = result.Vector.Z;
                        double xvelFixed = result.Velocity.X;
                        double yvelFixed = result.Velocity.Y;
                        double zvelFixed = result.Velocity.Z;

                        Console.Write("converted cartesian vectors" + "\n");
                        Console.Write("X=" + xFixed + " Y=" + yFixed + " Z=" + zFixed + "\n");
                        Console.Write("Xd=" + xvelFixed + " Yd=" + yvelFixed + " Zd=" + zvelFixed + "\n");

                        DateTime start, stop;
                        start = Convert.ToDateTime(startdate);
                        stop  = Convert.ToDateTime(enddate);

                        //set the epoch and start date/time to the selected scenario date/time
                        hpop.InitialState.Representation.Epoch = (start.ToString("dd MMM yyyy "));
                        hpop.EphemerisInterval.SetStartAndStopTimes((start.ToString("dd MMM yyyy ")), (stop.ToString("dd MMM yyyy ")));

                        hpop.InitialState.Representation.AssignCartesian(AgECoordinateSystem.eCoordinateSystemFixed, xFixed, yFixed, zFixed, xvelFixed, yvelFixed, zvelFixed);

                        hpop.InitialState.Representation.Epoch = (start.ToString("dd MMM yyyy "));
                        hpop.EphemerisInterval.SetStartAndStopTimes((start.ToString("dd MMM yyyy ")), (stop.ToString("dd MMM yyyy ")));

                        //propagate new orbit
                        hpop.Propagate();
                    }

                    orbitdata[i].Missensor = generate_sensor(orbitdata[i].name, "Stations");
                    orbitdata[i].MisChain  = generate_chain(orbitdata[i].name, "Stations", orbitdata[i].name + "_sensor");
                }
                else if (orbitdata[i].used == 1 && orbitdata[i].efileused == false)
                {
                    //generate the missions timeline file inside the orignial cod mis name
                    //don't generate multiple orbits on top of each other;
                    TL_file_generator(orbitdata[i].name, missionindex[orbitdata[i].cod_id]);
                    orbitdata[i].MisChain = null;
                    Console.Write("Misnum != cod_id && orbitdata[i].used == 1 for " + orbitdata[i].name + "\n");
                }
                else if (orbitdata[i].used == 1 && orbitdata[i].efileused == true)
                {
                    TL_file_generator(orbitdata[i].name, missionindex[orbitdata[i].cod_id]);

                    orbitdata[i].MisSat = (IAgSatellite)m_oApplication.CurrentScenario.Children.New(AGI.STKObjects.AgESTKObjectType.eSatellite, orbitdata[i].name);
                    //disable the leading ground track
                    groundtrack_set(orbitdata[i].MisSat, groundtrack_displayed);

                    //set the propagator type to STK E file
                    orbitdata[i].MisSat.SetPropagatorType(AGI.STKObjects.AgEVePropagatorType.ePropagatorStkExternal);

                    AGI.STKObjects.IAgVePropagatorStkExternal EFileProp = (AGI.STKObjects.IAgVePropagatorStkExternal)orbitdata[i].MisSat.Propagator;

                    //strip the file name from the entire director name;
                    EFileProp.Filename = (Efile_directory + orbitdata[i].efilename.Split('/').Last().ToString());
                    //propagate the efile orbit
                    EFileProp.Propagate();

                    //add new sensor to the current sat and change the sensor type to target
                    orbitdata[i].Missensor = generate_sensor(orbitdata[i].name, "Stations");

                    //add a new chain for the current sat
                    orbitdata[i].MisChain = generate_chain(orbitdata[i].name, "Stations", orbitdata[i].name + "_sensor");
                }
                else
                {
                    orbitdata[i].MisChain = null;
                    Console.Write("Misnum != cod_id for " + orbitdata[i].name + "\n");
                }
            }
        }
Ejemplo n.º 14
0
        private void ExportUMTFile()
        {
            SaveFileDialog saveDialog = new SaveFileDialog();

            saveDialog.Filter           = "UMT files (*.umt)|*.umt";
            saveDialog.FilterIndex      = 0;
            saveDialog.RestoreDirectory = true;
            string fileName = "";

            if (saveDialog.ShowDialog() == DialogResult.OK)
            {
                fileName = saveDialog.FileName;
            }

            if (fileName == "")
            {
                return;
            }

            //
            // init
            //
            m_root.UnitPreferences.SetCurrentUnit("Time", "sec");
            m_root.UnitPreferences.SetCurrentUnit("DateFormat", "EpSec");
            m_root.UnitPreferences.SetCurrentUnit("LatitudeUnit", "rad");
            m_root.UnitPreferences.SetCurrentUnit("LongitudeUnit", "rad");
            m_root.UnitPreferences.SetCurrentUnit("AngleUnit", "rad");
            m_root.UnitPreferences.SetCurrentUnit("DistanceUnit", "m");
            m_root.ExecuteCommand("SetUnits / EpSec");

            //
            // get select obj
            //
            IAgStkObject mySelObj = m_root.GetObjectFromPath(m_psite.Selection[0].Path);


            //
            // get obj class, and roll-offset
            //
            double rOffset = 0.0;

            if ((mySelObj.ClassName == "Ship") || (mySelObj.ClassName == "GroundVehicle"))
            {
                rOffset = Math.PI;
            }


            Console.WriteLine("Create times..." + DateTime.Now.ToString());
            //
            // get object start/stop times
            //
            // If I use ObjModel properties, this would be class specific, so I will use connect
            //
            string[] times = m_root.ExecuteCommand("GetTimePeriod " + mySelObj.Path)[0].Replace("\"", "").Split(',');
            //step = 1; // set = 0 to use native ephemeris time step

            //DAN - Changing this to UTCG times
            string startTime = m_root.ConversionUtility.ConvertDate("EpSec", "UTCG", times[0]);
            string stopTime  = m_root.ConversionUtility.ConvertDate("EpSec", "UTCG", times[1]);

            //DAN - Update the object model to expect UTCG dates
            m_root.UnitPreferences.SetCurrentUnit("DateFormat", "UTCG");


            IAgDataPrvTimeVar dp         = mySelObj.DataProviders.GetDataPrvTimeVarFromPath("Cartesian Position/Fixed");
            Array             elements   = new object[] { "Time" };
            IAgDrResult       result     = dp.ExecElements(startTime, stopTime, 1.0, elements);
            Array             timesArray = result.DataSets.GetDataSetByName("Time").GetValues();


            Console.WriteLine("Data Providers..." + DateTime.Now.ToString());
            //
            // get position data
            //
            elements = new object[] { "x", "y", "z" };
            dp       = mySelObj.DataProviders.GetDataPrvTimeVarFromPath("Cartesian Position/Fixed");
            IAgDrResult results = dp.ExecElements(startTime, stopTime, 1.0, ref elements);
            Array       x       = results.DataSets.GetDataSetByName("x").GetValues();
            Array       y       = results.DataSets.GetDataSetByName("y").GetValues();
            Array       z       = results.DataSets.GetDataSetByName("z").GetValues();



            //
            // get velocity
            //
            elements = new object[] { "x", "y", "z" };
            dp       = mySelObj.DataProviders.GetDataPrvTimeVarFromPath("Cartesian Velocity/Fixed");
            results  = dp.ExecElements(startTime, stopTime, 1.0, ref elements);
            Array xd = results.DataSets.GetDataSetByName("x").GetValues();
            Array yd = results.DataSets.GetDataSetByName("y").GetValues();
            Array zd = results.DataSets.GetDataSetByName("z").GetValues();



            //
            // get acceleration
            //
            dp      = mySelObj.DataProviders.GetDataPrvTimeVarFromPath("Cartesian Acceleration/Fixed");
            results = dp.ExecElements(startTime, stopTime, 1.0, ref elements);
            Array xdd = results.DataSets.GetDataSetByName("x").GetValues();
            Array ydd = results.DataSets.GetDataSetByName("y").GetValues();
            Array zdd = results.DataSets.GetDataSetByName("z").GetValues();


            //
            // get jerk - need to calcualate this: dA/dT
            //
            List <string> xddd = new List <string>();
            List <string> yddd = new List <string>();
            List <string> zddd = new List <string>();

            for (int j = 0; j <= timesArray.Length - 1; j++)
            {
                xddd.Add("0");
                yddd.Add("0");
                zddd.Add("0");
            }


            //
            // get heading, elevation, bank (rad)
            //
            dp = mySelObj.DataProviders.GetDataPrvTimeVarFromPath("Body Axes Orientation/NorthEastDown");
            Array eulerElements = new object[] { "Euler321 precession", "Euler321 nutation", "Euler321 spin" };

            results = dp.ExecElements(startTime, stopTime, 1.0, ref eulerElements);
            Array h = results.DataSets.GetDataSetByName("Euler321 precession").GetValues();
            Array e = results.DataSets.GetDataSetByName("Euler321 nutation").GetValues();
            Array b = results.DataSets.GetDataSetByName("Euler321 spin").GetValues();



            //
            // get angular vel about x,y,z body axes (rad/s)
            //
            dp = mySelObj.DataProviders.GetDataPrvTimeVarFromPath("Body Axes Orientation/Earth Fixed");
            Array avElements = new object[] { "wx", "wy", "wz" };

            results = dp.ExecElements(startTime, stopTime, 1.0, ref avElements);
            Array avel_x = results.DataSets.GetDataSetByName("wx").GetValues();
            Array avel_y = results.DataSets.GetDataSetByName("wy").GetValues();
            Array avel_z = results.DataSets.GetDataSetByName("wz").GetValues();



            //
            // calcualate angular acc about x,y,z body axes (rad/s^2) - from angVel
            //
            List <string> aacc_x = new List <string>();
            List <string> aacc_y = new List <string>();
            List <string> aacc_z = new List <string>();

            for (int j = 0; j <= timesArray.Length - 1; j++)
            {
                aacc_x.Add("0");
                aacc_y.Add("0");
                aacc_z.Add("0");
            }


            //
            // calcualate angular jerk about x,y,z body axes (rad/s^3)  - from angAcc
            //
            List <string> ajerk_x = new List <string>();;
            List <string> ajerk_y = new List <string>();;
            List <string> ajerk_z = new List <string>();;

            for (int j = 0; j <= timesArray.Length - 1; j++)
            {
                ajerk_x.Add("0");
                ajerk_y.Add("0");
                ajerk_z.Add("0");
            }



            //
            // format data (convert time from secs to hh:mm:ss.sss)
            //
            Console.WriteLine("Data Loop... " + DateTime.Now.ToString());
            string[] data = new string[timesArray.Length];
            for (int j = 0; j <= timesArray.Length - 1; j++)
            {
                DateTime iTime = DateTime.Parse(timesArray.GetValue(j).ToString());

                string t = iTime.ToString("HH:mm:ss.fff");
                data[j] = t + ",mot,V1_M1," + Convert.ToString(x.GetValue(j)) + "," + Convert.ToString(y.GetValue(j)) + "," + Convert.ToString(z.GetValue(j)) + "," + Convert.ToString(xd.GetValue(j)) + "," + Convert.ToString(yd.GetValue(j)) + "," + Convert.ToString(zd.GetValue(j)) + "," + Convert.ToString(xdd.GetValue(j)) + "," + Convert.ToString(ydd.GetValue(j)) + "," + Convert.ToString(zdd.GetValue(j)) + "," + xddd[j] + "," + yddd[j] + "," + zddd[j] + "," + Convert.ToString(h.GetValue(j)) + "," + Convert.ToString(e.GetValue(j)) + "," + Convert.ToString(((double)b.GetValue(j) + rOffset)) + "," + Convert.ToString(avel_x.GetValue(j)) + "," + Convert.ToString(avel_y.GetValue(j)) + "," + Convert.ToString(avel_z.GetValue(j)) + "," + aacc_x[j] + "," + aacc_y[j] + "," + aacc_z[j] + "," + ajerk_x[j] + "," + ajerk_y[j] + "," + ajerk_z[j];
            }
            Console.WriteLine("Writing File..." + DateTime.Now.ToString());
            System.IO.File.WriteAllLines(fileName, data);
            Console.WriteLine("Complete. " + DateTime.Now.ToString());
        }
Ejemplo n.º 15
0
        public Array GetDataProviders(string stkObjectPath, string DataProviderName,
                                      string GroupName, string ElementName)
        {
            string startTime = scen.StartTime.ToString();
            string stopTime  = scen.StopTime.ToString();
            double stepSize  = 60;

            IAgStkObject stkObject = root.GetObjectFromPath(stkObjectPath);

            IAgDataProviderInfo dpInfo = stkObject.DataProviders[DataProviderName];

            IAgDataProvider dataProvider = stkObject.DataProviders[DataProviderName] as IAgDataProvider;

            if (dpInfo.IsGroup())
            {
                IAgDataProviderGroup dpGroup     = dpInfo as IAgDataProviderGroup;
                IAgDataProviders     dpAvailable = dpGroup.Group;

                for (int i = 0; i < dpAvailable.Count; ++i)
                {
                    if (dpAvailable[i].Name == GroupName)
                    {
                        dataProvider = dpAvailable[i] as IAgDataProvider;
                        break;
                    }
                }
            }

            IAgDrResult dpResult = null;

            switch (dpInfo.Type)
            {
            case AgEDataProviderType.eDrFixed:
                //Fixed data doesnt change over time
                IAgDataPrvFixed dpFixed = dataProvider as IAgDataPrvFixed;
                dpResult = dpFixed.Exec();
                break;

            case AgEDataProviderType.eDrIntvl:
                //Interval data is given as a list of intervals with start, stop and duration
                IAgDataPrvInterval dpInterval = dataProvider as IAgDataPrvInterval;
                //Must provide analysis start and stop time

                dpResult = dpInterval.Exec(startTime, stopTime);
                break;

            case AgEDataProviderType.eDrTimeVar:
                //Time varyign data is given as an array of time based values
                IAgDataPrvTimeVar dpTimeVarying = dataProvider as IAgDataPrvTimeVar;
                //Must provide analysis start and stop time plus an evaluation step size
                dpResult = dpTimeVarying.Exec(startTime, stopTime, stepSize);
                break;

            default:
                break;
            }

            Array dataValues = null;

            IAgDrDataSetCollection datasets = dpResult.DataSets;

            if (datasets.Count > 0)
            {
                IAgDrDataSet thisDataset = datasets.GetDataSetByName(ElementName);

                dataValues = thisDataset.GetValues();
            }
            return(dataValues);
        }
Ejemplo n.º 16
0
        public static void MergeEphemeris(IAgStkObject[] objectArray, string outputFilePath)
        {
            Dictionary <double, IAgStkObject> ephems = new Dictionary <double, IAgStkObject>();

            Root.UnitPreferences.SetCurrentUnit("DateFormat", "EpSec");
            foreach (IAgStkObject stkObject in objectArray)
            {
                if (stkObject is IAgSatellite &&
                    (stkObject as IAgSatellite).PropagatorType == AgEVePropagatorType.ePropagatorStkExternal)
                {
                    IAgVePropagatorStkExternal exProp =
                        (stkObject as IAgSatellite).Propagator as IAgVePropagatorStkExternal;
                    if (!ephems.ContainsKey(double.Parse(exProp.StartTime.ToString())))
                    {
                        ephems.Add(double.Parse(exProp.StartTime.ToString()), stkObject);
                    }
                }
            }

            List <KeyValuePair <double, IAgStkObject> > testing = ephems.OrderBy(i => i.Key).ToList();
            List <string> ephemLines = new List <string>();

            for (int i = 0; i < testing.Count(); i++)
            {
                IAgDataProviderGroup dp            = (IAgDataProviderGroup)testing[i].Value.DataProviders["Cartesian Position"];
                IAgDataProvider      dpICRF        = (IAgDataProvider)dp.Group["ICRF"];
                IAgDataPrvTimeVar    dpTimeVarying = (IAgDataPrvTimeVar)dpICRF;

                string stopTime = i < (testing.Count() - 1)
                    ? testing[i + 1].Key.ToString()
                    : ((testing[i].Value as IAgSatellite).Propagator as IAgVePropagatorStkExternal).StopTime.ToString();
                string      startTime = testing[i].Key.ToString();
                IAgDrResult results   = dpTimeVarying.ExecNativeTimes(startTime, stopTime);
                Array       times     = results.DataSets.GetDataSetByName("Time").GetValues();
                Array       xs        = results.DataSets.GetDataSetByName("x").GetValues();
                Array       ys        = results.DataSets.GetDataSetByName("y").GetValues();
                Array       zs        = results.DataSets.GetDataSetByName("z").GetValues();

                dp            = (IAgDataProviderGroup)testing[i].Value.DataProviders["Cartesian Velocity"];
                dpICRF        = (IAgDataProvider)dp.Group["ICRF"];
                dpTimeVarying = (IAgDataPrvTimeVar)dpICRF;

                results = dpTimeVarying.ExecNativeTimes(startTime, stopTime);
                Array xds = results.DataSets.GetDataSetByName("x").GetValues();
                Array yds = results.DataSets.GetDataSetByName("y").GetValues();
                Array zds = results.DataSets.GetDataSetByName("z").GetValues();

                for (int j = 0; j < (times.Length - 2); j++)
                {
                    ephemLines.Add(string.Format("{0}     {1}     {2}     {3}     {4}     {5}     {6}",
                                                 times.GetValue(j), xs.GetValue(j), ys.GetValue(j), zs.GetValue(j), xds.GetValue(j),
                                                 yds.GetValue(j), zds.GetValue(j)));
                }
                //MessageBox.Show("stored values");
            }
            int count = ephemLines.Count;

            ephemLines.Insert(0, "stk.v.10.0");
            ephemLines.Insert(1, "BEGIN Ephemeris");
            ephemLines.Insert(2, "NumberOfEphemerisPoints " + count);
            ephemLines.Insert(3, "InterpolationMethod     Lagrange");
            ephemLines.Insert(4, "InterpolationOrder  5");
            ephemLines.Insert(5,
                              "ScenarioEpoch " +
                              Root.ConversionUtility.ConvertDate(Root.UnitPreferences.GetCurrentUnitAbbrv("DateFormat"), "UTCG",
                                                                 (Root.CurrentScenario as IAgScenario).Epoch.ToString()));
            ephemLines.Insert(6, "CentralBody             Earth");
            ephemLines.Insert(7, "CoordinateSystem        ICRF");
            ephemLines.Insert(8, "DistanceUnit        Meters");
            ephemLines.Insert(9, "EphemerisTimePosVel");

            ephemLines.Add("END Ephemeris");

            File.WriteAllLines(outputFilePath, ephemLines.ToArray());
        }
Ejemplo n.º 17
0
        public static RICResults GetRICDifferenceOverTime(string sat1Path, string sat2Path, string epochISOYMD)
        {
            IAgDate tca = StkAssistant.Root.ConversionUtility.NewDate("ISO-YMD", epochISOYMD);

            IAgStkObject primary, secondary;

            try
            {
                primary   = StkAssistant.Root.GetObjectFromPath(sat1Path);
                secondary = StkAssistant.Root.GetObjectFromPath(sat2Path);
            }
            catch
            {
                return(new RICResults());
            }

            double period1 = StkAssistant.GetSatellitePeriod(primary.Path, epochISOYMD);
            double period2 = StkAssistant.GetSatellitePeriod(secondary.Path, epochISOYMD);

            double period = (period1 + period2) / 2;

            IAgDataProviderInfo dpInfo = primary.DataProviders["RIC Coordinates"];

            IAgDataProvider dataProvider = primary.DataProviders["RIC Coordinates"] as IAgDataProvider;

            dataProvider.PreData = secondary.Path.Replace(StkAssistant.Root.CurrentScenario.Path, "");
            IAgDataPrvTimeVar dpTimeVarying = dataProvider as IAgDataPrvTimeVar;
            Array             elements      = new object[] { "Time", "Radial", "In-Track", "Cross-Track", "Range" };
            IAgDrResult       dpResult      = dpTimeVarying.ExecElements(
                tca.Subtract("sec", .5 * period).Format("ISO-YMD"),
                tca.Add("sec", .5 * period).Format("ISO-YMD"),
                10, elements);
            RICResults ricResults = new RICResults();

            foreach (IAgDrDataSet dataset in dpResult.DataSets)
            {
                if (dataset.ElementName.Equals("Time"))
                {
                    List <string> times = new List <string>();
                    foreach (object item in dataset.GetValues())
                    {
                        times.Add(item.ToString());
                    }
                    ricResults.Times = times.ToArray();
                }
                else
                {
                    List <double> values = new List <double>();
                    foreach (object item in dataset.GetValues())
                    {
                        values.Add((double)item);
                    }

                    switch (dataset.ElementName)
                    {
                    case "Radial":
                        ricResults.R = values.ToArray();
                        break;

                    case "In-Track":
                        ricResults.I = values.ToArray();
                        break;

                    case "Cross-Track":
                        ricResults.C = values.ToArray();
                        break;

                    case "Range":
                        ricResults.Range = values.ToArray();
                        break;

                    default:
                        break;
                    }
                }
            }

            return(ricResults);
        }
Ejemplo n.º 18
0
        public static void CreateScenarioFromTle(ref AgStkObjectRoot root, double duration, ref InitialState initState, TLE currentTle)
        {
            root.NewScenario(currentTle.GetSatNumber() + "_Reentry");
            DateTime startDate = currentTle.GetTleEpoch();
            DateTime stopDate  = startDate.AddDays(duration);

            IAgScenario scenario = root.CurrentScenario as IAgScenario;

            // Set scenario start and stop times
            scenario.SetTimePeriod(startDate.ToString("dd MMM yyyy hh:mm:ss.fff"), stopDate.ToString("dd MMM yyyy hh:mm:ss.fff"));

            // remove the terrain option
            root.ExecuteCommand("Terrain * TerrainServer UseTerrainForAnalysis No");

            // create the SGP4 object from the TLE
            IAgSatellite decayingSat = (IAgSatellite)root.CurrentScenario.Children.New(AgESTKObjectType.eSatellite, currentTle.GetSatNumber());

            decayingSat.SetPropagatorType(AgEVePropagatorType.ePropagatorSGP4);
            IAgVePropagatorSGP4 sgp4 = decayingSat.Propagator as IAgVePropagatorSGP4;

            sgp4.CommonTasks.AddSegsFromFile(currentTle.GetSatNumber(), currentTle.GetFilePath());
            IAgVeGfxAttributesBasic att = decayingSat.Graphics.Attributes as IAgVeGfxAttributesBasic;

            att.Color = Color.Yellow;

            // Configure time period
            sgp4.EphemerisInterval.SetExplicitInterval(scenario.StartTime, scenario.StopTime);
            sgp4.Step = 60.0;
            // Propagate
            sgp4.Propagate();

            // change the 3D model
            try
            {
                root.ExecuteCommand("VO */Satellite/" + currentTle.GetSatNumber() + " Model File \"C:\\Program Files\\AGI\\STK 11\\STKData\\VO\\Models\\Misc\\explosion.mdl\"");
            }
            catch (Exception)
            {
            }

            //// get the initial state from the TLE
            initState.Epoch = scenario.StartTime;

            IAgDataPrvTimeVar      dpPos       = ((IAgStkObject)decayingSat).DataProviders.GetDataPrvTimeVarFromPath("Cartesian Position//ICRF");
            IAgDrResult            resultPos   = dpPos.Exec(scenario.StartTime, scenario.StartTime, 60.0);
            IAgDrDataSetCollection datasetsPos = resultPos.DataSets;

            if (resultPos.DataSets.Count > 0)
            {
                initState.CartesianPosX = datasetsPos[1].GetValues().GetValue(0).ToString();
                initState.CartesianPosY = datasetsPos[2].GetValues().GetValue(0).ToString();
                initState.CartesianPosZ = datasetsPos[3].GetValues().GetValue(0).ToString();
            }

            IAgDataPrvTimeVar      dpVel       = ((IAgStkObject)decayingSat).DataProviders.GetDataPrvTimeVarFromPath("Cartesian Velocity//ICRF");
            IAgDrResult            resultVel   = dpVel.Exec(scenario.StartTime, scenario.StartTime, 60.0);
            IAgDrDataSetCollection datasetsVel = resultVel.DataSets;

            if (resultVel.DataSets.Count > 0)
            {
                initState.CartesianVelX = datasetsVel[1].GetValues().GetValue(0).ToString();
                initState.CartesianVelY = datasetsVel[2].GetValues().GetValue(0).ToString();
                initState.CartesianVelZ = datasetsVel[3].GetValues().GetValue(0).ToString();
            }

            // configure the 2D graphics
            root.ExecuteCommand("Graphics * BackgroundImage Show Off");
            root.ExecuteCommand("MapDetails * LatLon Lon On 15");
            root.ExecuteCommand("MapDetails * Map RWDB2_Islands State On Color green");
            root.ExecuteCommand("MapDetails * Map RWDB2_International_Borders State On ");
            root.ExecuteCommand("MapDetails * Map RWDB2_Lakes State On");

            try
            {
                root.ExecuteCommand("VO * Globe Show On File \"C:\\Program Files\\AGI\\STK 11\\STKData\\VO\\Globes\\Earth\\WhiteOnBlue.glb\"");
            }
            catch (Exception)
            {
            }

            // configure the 3D graphics
            root.ExecuteCommand("VO * GlobeDetails MapDetail Show On Map RWDB2_Coastlines ShowDetail On");
            root.ExecuteCommand("VO * GlobeDetails MapDetail Show On Map RWDB2_Islands ShowDetail On DetailColor green");
            root.ExecuteCommand("VO * GlobeDetails MapDetail Show On Map RWDB2_Lakes ShowDetail On DetailColor lightblue");


            //dynamic uiApp = System.Runtime.InteropServices.Marshal.GetActiveObject("STK11.Application");
            //try
            //{
            //    foreach (dynamic window in uiApp.Windows)
            //    {
            //        string windowCaption = (string)window.Caption;
            //        if (windowCaption.Contains("2D"))
            //        {
            //            window.DockStyle = 3;
            //        }
            //    }

            //}
            //catch (Exception ex)
            //{
            //    string error = ex.Message;
            //}
        }
Ejemplo n.º 19
0
        public static TLE CreateScenarioFromSatcat(ref AgStkObjectRoot root, double duration, ref InitialState initState, string satId)
        {
            root.NewScenario(satId + "_Reentry");
            //DateTime startDate = currentTle.GetTleEpoch();
            //DateTime stopDate = startDate.AddDays(duration);

            IAgScenario scenario = root.CurrentScenario as IAgScenario;

            // remove the terrain option
            root.ExecuteCommand("Terrain * TerrainServer UseTerrainForAnalysis No");

            // import the satellite from the catalog
            root.ExecuteCommand("ImportFromDB * Satellite AGIServer Propagate On TimePeriod UseScenarioInterval SSCNumber " + satId + " \"");

            // get the satellite start time
            IAgStkObject        satObj      = root.CurrentScenario.Children[0];
            IAgSatellite        decayingSat = satObj as IAgSatellite;
            IAgVePropagatorSGP4 sgp4        = decayingSat.Propagator as IAgVePropagatorSGP4;
            //IAgCrdnEventSmartEpoch startEpoch = sgp4.EphemerisInterval.GetStartEpoch();
            dynamic startEpoch = sgp4.Segments[0].SwitchTime;
            // Set scenario start and stop times
            DateTime startDate = STK.GetDateTimeFromStkTimeFormat(Convert.ToString(startEpoch));
            DateTime stopDate  = startDate.AddDays(duration);

            scenario.SetTimePeriod(startDate.ToString("dd MMM yyyy hh:mm:ss.fff"), stopDate.ToString("dd MMM yyyy hh:mm:ss.fff"));

            // get the TLE data back from STK
            TLE tle = new TLE(startDate, sgp4.Segments[0].SSCNum, Convert.ToString(sgp4.Segments[0].Inclination),
                              Convert.ToString(sgp4.Segments[0].Eccentricity), Convert.ToString(sgp4.Segments[0].RevNumber),
                              Convert.ToString(sgp4.Segments[0].MeanMotion));

            IAgVeGfxAttributesBasic att = decayingSat.Graphics.Attributes as IAgVeGfxAttributesBasic;

            att.Color = Color.Yellow;

            // Configure time period
            sgp4.EphemerisInterval.SetExplicitInterval(scenario.StartTime, scenario.StopTime);
            sgp4.Step = 60.0;

            // change the 3D model
            try
            {
                root.ExecuteCommand("VO */Satellite/" + root.CurrentScenario.Children[0].InstanceName + " Model File \"C:\\Program Files\\AGI\\STK 11\\STKData\\VO\\Models\\Misc\\explosion.mdl\"");
            }
            catch (Exception)
            {
            }

            //// get the initial state from the TLE
            initState.Epoch = scenario.StartTime;

            IAgDataPrvTimeVar      dpPos       = ((IAgStkObject)decayingSat).DataProviders.GetDataPrvTimeVarFromPath("Cartesian Position//ICRF");
            IAgDrResult            resultPos   = dpPos.Exec(scenario.StartTime, scenario.StartTime, 60.0);
            IAgDrDataSetCollection datasetsPos = resultPos.DataSets;

            if (resultPos.DataSets.Count > 0)
            {
                initState.CartesianPosX = datasetsPos[1].GetValues().GetValue(0).ToString();
                initState.CartesianPosY = datasetsPos[2].GetValues().GetValue(0).ToString();
                initState.CartesianPosZ = datasetsPos[3].GetValues().GetValue(0).ToString();
            }

            IAgDataPrvTimeVar      dpVel       = ((IAgStkObject)decayingSat).DataProviders.GetDataPrvTimeVarFromPath("Cartesian Velocity//ICRF");
            IAgDrResult            resultVel   = dpVel.Exec(scenario.StartTime, scenario.StartTime, 60.0);
            IAgDrDataSetCollection datasetsVel = resultVel.DataSets;

            if (resultVel.DataSets.Count > 0)
            {
                initState.CartesianVelX = datasetsVel[1].GetValues().GetValue(0).ToString();
                initState.CartesianVelY = datasetsVel[2].GetValues().GetValue(0).ToString();
                initState.CartesianVelZ = datasetsVel[3].GetValues().GetValue(0).ToString();
            }

            // configure the 2D graphics
            root.ExecuteCommand("Graphics * BackgroundImage Show Off");
            root.ExecuteCommand("MapDetails * LatLon Lon On 15");
            root.ExecuteCommand("MapDetails * Map RWDB2_Islands State On Color green");
            root.ExecuteCommand("MapDetails * Map RWDB2_International_Borders State On ");
            root.ExecuteCommand("MapDetails * Map RWDB2_Lakes State On");

            try
            {
                root.ExecuteCommand("VO * Globe Show On File \"C:\\Program Files\\AGI\\STK 11\\STKData\\VO\\Globes\\Earth\\WhiteOnBlue.glb\"");
            }
            catch (Exception)
            {
            }

            // configure the 3D graphics
            root.ExecuteCommand("VO * GlobeDetails MapDetail Show On Map RWDB2_Coastlines ShowDetail On");
            root.ExecuteCommand("VO * GlobeDetails MapDetail Show On Map RWDB2_Islands ShowDetail On DetailColor green");
            root.ExecuteCommand("VO * GlobeDetails MapDetail Show On Map RWDB2_Lakes ShowDetail On DetailColor lightblue");


            return(tle);
        }