Skip to content
This repository has been archived by the owner on Aug 5, 2024. It is now read-only.

Commit

Permalink
Fix/memoryfix (#92)
Browse files Browse the repository at this point in the history
* Fix memory leaks
  • Loading branch information
sylvain-guillet authored Apr 26, 2024
1 parent aa89d65 commit f256901
Show file tree
Hide file tree
Showing 15 changed files with 55 additions and 102 deletions.
2 changes: 1 addition & 1 deletion IO.Astrodynamics.CLI/IO.Astrodynamics.CLI.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<FileVersion>0.0.1</FileVersion>
<PackAsTool>true</PackAsTool>
<ToolCommandName>astro</ToolCommandName>
<Version>0.1.4</Version>
<Version>0.1.5</Version>
<Title>Astrodynamics command line interface</Title>
<Authors>Sylvain Guillet</Authors>
<Description>This CLI allows end user to exploit IO.Astrodynamics framework </Description>
Expand Down
6 changes: 0 additions & 6 deletions IO.Astrodynamics.Tests/APITest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -482,12 +482,6 @@ void GetCelestialBodyInformationWithoutJ()
Assert.Equal(double.NaN, res.J4);
}

[Fact]
void GetInvalidCelestialBodyInformation()
{
Assert.Throws<InvalidOperationException>(() => API.Instance.GetCelestialBodyInfo(398));
}

[Fact]
void TransformFrame()
{
Expand Down
2 changes: 1 addition & 1 deletion IO.Astrodynamics.Tests/Body/CelestialBodyTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ public void GeosynchronousOrbit2()
Assert.Equal(42164171.961220242, orbit.ToStateVector().Position.Magnitude(), 3);
Assert.Equal(3074.6599898500763, orbit.ToStateVector().Velocity.Magnitude(), 3);
Assert.Equal(Frames.Frame.ICRF, orbit.Frame);
Assert.Equal(42164171.961220235, orbit.SemiMajorAxis());
Assert.Equal(42164171.961220235, orbit.SemiMajorAxis(),6);
Assert.Equal(0.0, orbit.Eccentricity());
Assert.Equal(1.0, orbit.Inclination(), 2);
Assert.Equal(1.1804318466570587, orbit.AscendingNode(), 2);
Expand Down
22 changes: 11 additions & 11 deletions IO.Astrodynamics.Tests/OrbitalParameters/KeplerianElementsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,12 +125,12 @@ public void SingularityZeroEccentricity()
{
KeplerianElements original = new KeplerianElements(42000000, 0.0, 1.0, 2.0, 1.0, 0.5, TestHelpers.EarthAtJ2000, DateTimeExtension.J2000, Frames.Frame.ICRF);
KeplerianElements transformed = original.ToStateVector().ToKeplerianElements();
Assert.Equal(original.A, transformed.A,3);
Assert.Equal(original.A, transformed.A, 3);
Assert.Equal(original.E, transformed.E, 6);
Assert.Equal(original.I, transformed.I, 6);
Assert.Equal(original.RAAN, transformed.RAAN);
Assert.Equal(original.MeanLongitude(), transformed.MeanLongitude());
Assert.Equal(original.AOP + original.M, (transformed.AOP + transformed.M)%Astrodynamics.Constants._2PI);
Assert.Equal(original.AOP + original.M, (transformed.AOP + transformed.M) % Astrodynamics.Constants._2PI);
}

[Fact]
Expand All @@ -139,7 +139,7 @@ public void SingularityZeroEccentricityZeroInclination()
KeplerianElements original = new KeplerianElements(42000000, 0.0, 0.0, 2.0, 1.0, 0.5, TestHelpers.EarthAtJ2000, DateTimeExtension.J2000, Frames.Frame.ICRF);
var originalSv = original.ToStateVector();
KeplerianElements transformed = originalSv.ToKeplerianElements();
Assert.Equal(original.A, transformed.A,3);
Assert.Equal(original.A, transformed.A, 3);
Assert.Equal(original.E, transformed.E, 6);
Assert.Equal(original.I, transformed.I, 6);
Assert.Equal(original.MeanLongitude(), transformed.MeanLongitude(), 6);
Expand Down Expand Up @@ -208,10 +208,10 @@ public void ExcentricityVector()
0.0 * IO.Astrodynamics.Constants.Deg2Rad,
earth, DateTime.UtcNow, Frames.Frame.ICRF);
Vector3 ev = ke.EccentricityVector();
Assert.Equal(0.09180000000000033, ev.Magnitude(),3);
Assert.Equal(0.09180000000000033, ev.X,3);
Assert.Equal(0.0, ev.Y,3);
Assert.Equal(0.0, ev.Z,3);
Assert.Equal(0.09180000000000033, ev.Magnitude(), 3);
Assert.Equal(0.09180000000000033, ev.X, 3);
Assert.Equal(0.0, ev.Y, 3);
Assert.Equal(0.0, ev.Z, 3);
}

[Fact]
Expand Down Expand Up @@ -280,7 +280,7 @@ public void SpecificOrbitalEnergyMomentum()
46.029 * IO.Astrodynamics.Constants.Deg2Rad, earth,
DateTime.UtcNow, Frames.Frame.ICRF);
double energy = ke.SpecificOrbitalEnergy();
Assert.Equal(-29305357.070616387, energy);
Assert.Equal(-29305357.070616387, energy, 6);
}

[Fact]
Expand All @@ -295,9 +295,9 @@ public void PerigeeVectorAnomaly()
Frames.Frame.ICRF);
var pv = ke.PerigeeVector();
Assert.Equal(10000.0, pv.Magnitude(), 9);
Assert.Equal(659.6961052988253, pv.X,3);
Assert.Equal(9213.804796489718, pv.Y,3);
Assert.Equal(3830.2222155948903, pv.Z,3);
Assert.Equal(659.6961052988253, pv.X, 3);
Assert.Equal(9213.804796489718, pv.Y, 3);
Assert.Equal(3830.2222155948903, pv.Z, 3);
}

[Fact]
Expand Down
38 changes: 12 additions & 26 deletions IO.Astrodynamics/API.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ private API()
public static API Instance { get; } = new();

[DllImport(@"IO.Astrodynamics", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern string GetSpiceVersionProxy();
private static extern IntPtr GetSpiceVersionProxy();

[DllImport(@"IO.Astrodynamics", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern void LaunchProxy([In] [Out] ref Launch launch);
Expand Down Expand Up @@ -147,7 +147,10 @@ public string GetSpiceVersion()
{
lock (lockObject)
{
return GetSpiceVersionProxy();
var strptr = GetSpiceVersionProxy();
var str = Marshal.PtrToStringAnsi(strptr);
Marshal.FreeHGlobal(strptr);
return str;
}
}

Expand All @@ -167,19 +170,22 @@ public void LoadKernels(FileSystemInfo path)
{
return;
}

lock (lockObject)
{
var existingKernels = _kernels.Where(x => x.FullName.Contains(path.FullName)).ToArray();
foreach (var existingKernel in existingKernels)
{
UnloadKernels(existingKernel);
}

if (path.Exists)
{
if (!LoadKernelsProxy(path.FullName))
{
throw new InvalidOperationException($"Kernel {path.FullName} can't be loaded. You can have more details on standard output");
}

_kernels.Add(path);
}
}
Expand All @@ -201,7 +207,7 @@ public void UnloadKernels(FileSystemInfo path)
throw new InvalidOperationException($"Kernel {path.FullName} can't be unloaded. You can have more details on standard output");
}

_kernels.RemoveAll(x=>x.FullName.Contains(path.FullName));
_kernels.RemoveAll(x => x.FullName.Contains(path.FullName));
}
}
}
Expand All @@ -227,11 +233,6 @@ public IEnumerable<LaunchWindow> FindLaunchWindows(Maneuver.Launch launch,
//Execute request
LaunchProxy(ref launchDto);

if (launchDto.HasError())
{
throw new InvalidOperationException($"Operation failed to find launch windows : {launchDto.Error}");
}

//Filter result
var windows = launchDto.Windows.Where(x => x.Start != 0 && x.End != 0).ToArray();

Expand Down Expand Up @@ -688,7 +689,7 @@ public bool WriteEphemeris(FileInfo filePath, INaifObject naifObject,
var enumerable = stateVectors as OrbitalParameters.StateVector[] ?? stateVectors.ToArray();
if (!enumerable.Any())
throw new ArgumentException("Value cannot be an empty collection.", nameof(stateVectors));
bool res = WriteEphemerisProxy(filePath.FullName, naifObject.NaifId, stateVectors.Select(x=>x.Convert()).ToArray(),
bool res = WriteEphemerisProxy(filePath.FullName, naifObject.NaifId, stateVectors.Select(x => x.Convert()).ToArray(),
(uint)enumerable.Length);
if (res == false)
{
Expand All @@ -710,7 +711,7 @@ public bool WriteOrientation(FileInfo filePath, INaifObject naifObject, IEnumera
var enumerable = stateOrientations as OrbitalParameters.StateOrientation[] ?? stateOrientations.ToArray();
if (!enumerable.Any())
throw new ArgumentException("Value cannot be an empty collection.", nameof(stateOrientations));
bool res = WriteOrientationProxy(filePath.FullName, naifObject.NaifId, stateOrientations.Select(x=>x.Convert()).ToArray(), (uint)enumerable.Length);
bool res = WriteOrientationProxy(filePath.FullName, naifObject.NaifId, stateOrientations.Select(x => x.Convert()).ToArray(), (uint)enumerable.Length);
if (res == false)
{
throw new InvalidOperationException(
Expand All @@ -730,14 +731,7 @@ public CelestialBody GetCelestialBodyInfo(int naifId)
{
lock (lockObject)
{
var res = GetCelestialBodyInfoProxy(naifId);
if (res.HasError())
{
throw new InvalidOperationException(
$"An error occured while reading celestial celestialItem information : {res.Error}");
}

return res;
return GetCelestialBodyInfoProxy(naifId);
}
}

Expand All @@ -756,10 +750,6 @@ public OrbitalParameters.StateOrientation TransformFrame(Frame fromFrame, Frame
if (fromFrame == null) throw new ArgumentNullException(nameof(fromFrame));
if (toFrame == null) throw new ArgumentNullException(nameof(toFrame));
var res = TransformFrameProxy(fromFrame.Name, toFrame.Name, epoch.ToTDB().SecondsFromJ2000TDB());
if (res.HasError())
{
throw new InvalidOperationException($"An error occured during frame transformation : {res.Error}");
}

return new OrbitalParameters.StateOrientation(
new Quaternion(res.Rotation.W, res.Rotation.X, res.Rotation.Y, res.Rotation.Z),
Expand Down Expand Up @@ -799,10 +789,6 @@ public TLE CreateTLE(string line1, string line2, string line3)
lock (lockObject)
{
var res = GetTLEElementsProxy(line1, line2, line3);
if (res.HasError())
{
throw new InvalidOperationException($"An error occured during TLE creation : {res.Error}");
}

return new TLE(line1, line2, line3, res.BalisticCoefficient, res.DragTerm, res.SecondDerivativeOfMeanMotion,
res.A, res.E, res.I, res.O, res.W, res.M,
Expand Down
41 changes: 21 additions & 20 deletions IO.Astrodynamics/DTO/CelestialBody.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,28 @@
namespace IO.Astrodynamics.DTO;

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public readonly struct CelestialBody
public struct CelestialBody
{
public int Id { get; }
public int CenterOfMotionId { get; }
public int BarycenterOfMotionId { get; }
public string Name { get; }
public Vector3D Radii { get; }
public double GM { get; }
public string FrameName { get; }
public int FrameId { get; }
public string Error { get; } = string.Empty;
public double J2 { get; }
public double J3 { get; }
public double J4 { get; }

public CelestialBody(int id, int centerOfMotionId, int barycenterOfMotionId, string name, Vector3D radii, double gm, string frameName, int frameId, double j2, double j3, double j4)
public int Id;
public int CenterOfMotionId;
public int BarycenterOfMotionId;

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string Name;

public Vector3D Radii;
public double GM;

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string FrameName;

public int FrameId;
public double J2 = 0.0;
public double J3 = 0.0;
public double J4 = 0.0;

public CelestialBody(int id, int centerOfMotionId, int barycenterOfMotionId, string name, Vector3D radii, double gm, string frameName, int frameId, double j2, double j3,
double j4)
{
Id = id;
CenterOfMotionId = centerOfMotionId;
Expand All @@ -34,9 +40,4 @@ public CelestialBody(int id, int centerOfMotionId, int barycenterOfMotionId, str
J4 = j4;
BarycenterOfMotionId = barycenterOfMotionId;
}

public bool HasError()
{
return !string.IsNullOrEmpty(Error);
}
}
6 changes: 0 additions & 6 deletions IO.Astrodynamics/DTO/FrameTransformation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,4 @@ public readonly struct FrameTransformation
{
public Quaternion Rotation { get; }
public Vector3D AngularVelocity { get; }
public string Error { get; }

public bool HasError()
{
return !string.IsNullOrEmpty(Error);
}
}
6 changes: 0 additions & 6 deletions IO.Astrodynamics/DTO/Launch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ public struct Launch
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 100)]
public Window[] Windows;

public string Error { get; } = string.Empty;

public Launch(Site launchSite, Site recoverySite, bool launchByDay, double initialStepSize, StateVector targetOrbit,
Window window)
Expand All @@ -46,9 +45,4 @@ public Launch(Site launchSite, Site recoverySite, bool launchByDay, double initi
NonInertialAzimuth = default;
NonInertialInsertionVelocity = default;
}

public bool HasError()
{
return !string.IsNullOrEmpty(Error);
}
}
13 changes: 3 additions & 10 deletions IO.Astrodynamics/DTO/Site.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,17 @@ namespace IO.Astrodynamics.DTO;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct Site
{
private const int AZIMUTH_RANGE_SIZE = 10;

public int Id = 0;
public string Name = null;
public int BodyId = -1;

public Planetodetic Coordinates = default;

[MarshalAs(UnmanagedType.ByValArray, SizeConst = AZIMUTH_RANGE_SIZE)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
public AzimuthRange[] Ranges;

public string DirectoryPath = null;
public string Error { get; } = string.Empty;


public Site(int naifId, int bodyId, Planetodetic coordinates, string name, string directoryPath) : this()
{
Expand All @@ -28,11 +26,6 @@ public Site(int naifId, int bodyId, Planetodetic coordinates, string name, strin
Coordinates = coordinates;
Name = name;
DirectoryPath = directoryPath;
Ranges = ArrayBuilder.ArrayOf<AzimuthRange>(AZIMUTH_RANGE_SIZE);
}

public bool HasError()
{
return !string.IsNullOrEmpty(Error);
Ranges = ArrayBuilder.ArrayOf<AzimuthRange>(10);
}
}
1 change: 1 addition & 0 deletions IO.Astrodynamics/DTO/StateOrientation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ public struct StateOrientation
public Quaternion Rotation;
public Vector3D AngularVelocity;
public double Epoch;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string Frame;

public StateOrientation(Quaternion orientation, Vector3D angularVelocity, double epoch, string frame)
Expand Down
12 changes: 4 additions & 8 deletions IO.Astrodynamics/DTO/StateVector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@
namespace IO.Astrodynamics.DTO;

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public readonly struct StateVector
public struct StateVector
{
public double Epoch { get; }
public Vector3D Position { get; }
public Vector3D Velocity { get; }
public int CenterOfMotionId { get; }
public string Frame { get; }
public string Error { get; } = string.Empty;

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string Frame;

public StateVector(int centerOfMotionId, double epoch, string frame, in Vector3D position, in Vector3D velocity)
{
Expand All @@ -22,9 +23,4 @@ public StateVector(int centerOfMotionId, double epoch, string frame, in Vector3D
Position = position;
Velocity = velocity;
}

public bool HasError()
{
return !string.IsNullOrEmpty(Error);
}
}
6 changes: 0 additions & 6 deletions IO.Astrodynamics/DTO/TLEElements.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ public readonly struct TLEElements
public double W { get; }
public double O { get; }
public double M { get; }
public string Error { get; } = string.Empty;

public TLEElements(double balisticCoefficient, double secondDerivativeOfMeanMotion, double dragTerm, double epoch, double a, double e, double i, double w, double o, double m)
{
Expand All @@ -32,9 +31,4 @@ public TLEElements(double balisticCoefficient, double secondDerivativeOfMeanMoti
O = o;
M = m;
}

public bool HasError()
{
return !string.IsNullOrEmpty(Error);
}
}
Loading

0 comments on commit f256901

Please sign in to comment.