Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 11 additions & 29 deletions CodeGen/Generators/QuantityRelationsParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ internal static class QuantityRelationsParser
/// The relations are defined in UnitRelations.json
/// Each defined relation can be applied multiple times to one or two quantities depending on the operator and the operands.
///
/// The format of a relation definition is "Quantity.Unit operator Quantity.Unit = Quantity.Unit" (See examples below).
/// "double" can be used as a unitless operand.
/// The format of a relation definition is "Quantity.Unit = Quantity.Unit * Quantity.Unit" (See examples below).
/// "1" can be used as the result operand to define inverse relations.
///
/// Division relations are inferred from multiplication relations,
Expand All @@ -43,10 +42,8 @@ public static void ParseAndApplyRelations(string rootDir, Quantity[] quantities)
{
var quantityDictionary = quantities.ToDictionary(q => q.Name, q => q);

// Add double and 1 as pseudo-quantities to validate relations that use them.
var pseudoQuantity = new Quantity { Name = null!, Units = [new Unit { SingularName = null! }] };
quantityDictionary["double"] = pseudoQuantity with { Name = "double" };
quantityDictionary["1"] = pseudoQuantity with { Name = "1" };
// Add 1 as a pseudo-quantity to validate inverse relations.
quantityDictionary["1"] = new Quantity { Name = "1", Units = [new Unit()] };

var relations = ParseRelations(rootDir, quantityDictionary);

Expand All @@ -61,7 +58,7 @@ public static void ParseAndApplyRelations(string rootDir, Quantity[] quantities)
RightUnit = r.LeftUnit,
})
.ToList());

// We can infer division relations from multiplication relations.
relations.AddRange(relations
.Where(r => r is { Operator: "*", NoInferredDivision: false })
Expand All @@ -81,8 +78,8 @@ public static void ParseAndApplyRelations(string rootDir, Quantity[] quantities)
relations.Sort();

var duplicates = relations
.GroupBy(r => r.SortString)
.Where(g => g.Count() > 1)
.CountBy(r => r.SortString)
.Where(g => g.Value > 1)
.Select(g => g.Key)
.ToList();

Expand All @@ -91,10 +88,10 @@ public static void ParseAndApplyRelations(string rootDir, Quantity[] quantities)
var list = string.Join("\n ", duplicates);
throw new UnitsNetCodeGenException($"Duplicate inferred relations:\n {list}");
}

var ambiguous = relations
.GroupBy(r => $"{r.LeftQuantity.Name} {r.Operator} {r.RightQuantity.Name}")
.Where(g => g.Count() > 1)
.CountBy(r => r.DisambiguationString)
.Where(g => g.Value > 1)
.Select(g => g.Key)
.ToList();

Expand All @@ -106,23 +103,8 @@ public static void ParseAndApplyRelations(string rootDir, Quantity[] quantities)

foreach (var quantity in quantities)
{
var quantityRelations = new List<QuantityRelation>();

foreach (var relation in relations)
{
if (relation.LeftQuantity == quantity)
{
// The left operand of a relation is responsible for generating the operator.
quantityRelations.Add(relation);
}
else if (relation.RightQuantity == quantity && relation.LeftQuantity.Name is "double")
{
// Because we cannot add operators to double we make the right operand responsible in this case.
quantityRelations.Add(relation);
}
}

quantity.Relations = quantityRelations.ToArray();
// The left operand of a relation is responsible for generating the operator.
quantity.Relations = relations.Where(relation => relation.LeftQuantity == quantity).ToArray();
}
}

Expand Down
19 changes: 1 addition & 18 deletions CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -854,28 +854,11 @@ private void GenerateRelationalOperators()
var leftPart = $"{leftParameter}.{leftConversionProperty}";
var rightPart = $"{rightParameter}.{rightConversionProperty}";

if (leftParameter is "double")
{
leftParameter = leftPart = "value";
}

if (rightParameter is "double")
{
rightParameter = rightPart = "value";
}

var expression = $"{leftPart} {relation.Operator} {rightPart}";

if (relation.ResultQuantity.Name is not "double")
{
expression = $"{relation.ResultQuantity.Name}.From{relation.ResultUnit.PluralName}({expression})";
}

Writer.WL($@"
/// <summary>Get <see cref=""{relation.ResultQuantity.Name}""/> from <see cref=""{relation.LeftQuantity.Name}""/> {relation.Operator} <see cref=""{relation.RightQuantity.Name}""/>.</summary>
public static {relation.ResultQuantity.Name} operator {relation.Operator}({relation.LeftQuantity.Name} {leftParameter}, {relation.RightQuantity.Name} {rightParameter})
{{
return {expression};
return {relation.ResultQuantity.Name}.From{relation.ResultUnit.PluralName}({leftPart} {relation.Operator} {rightPart});
}}
");
}
Expand Down
12 changes: 5 additions & 7 deletions CodeGen/JsonTypes/QuantityRelation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,15 @@ internal record QuantityRelation : IComparable<QuantityRelation>
public Quantity ResultQuantity = null!;
public Unit ResultUnit = null!;

public string SortString => ResultQuantity.Name + PrependDot(ResultUnit.SingularName)
+ " = "
+ LeftQuantity.Name + PrependDot(LeftUnit.SingularName)
+ " " + Operator + " "
+ RightQuantity.Name + PrependDot(RightUnit.SingularName);
public string DisambiguationString => $"{LeftQuantity.Name} {Operator} {RightQuantity.Name}";

public string SortString => $"{ResultQuantity.Name}.{ResultUnit.SingularName} = "
+ $"{LeftQuantity.Name}.{LeftUnit.SingularName} {Operator} "
+ $"{RightQuantity.Name}.{RightUnit.SingularName}";

public int CompareTo(QuantityRelation? other)
{
return string.Compare(SortString, other?.SortString, StringComparison.Ordinal);
}

private static string PrependDot(string? s) => s == null ? string.Empty : "." + s;
}
}
2 changes: 1 addition & 1 deletion Common/UnitRelations.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
"Area.SquareMeter = Length.Meter * Length.Meter",
"Area.SquareMeter = Volume.CubicMeter * ReciprocalLength.InverseMeter",
"AreaMomentOfInertia.MeterToTheFourth = Volume.CubicMeter * Length.Meter",
"double = SpecificEnergy.JoulePerKilogram * BrakeSpecificFuelConsumption.KilogramPerJoule",
"DynamicViscosity.NewtonSecondPerMeterSquared = Density.KilogramPerCubicMeter * KinematicViscosity.SquareMeterPerSecond",
"ElectricCharge.AmpereHour = ElectricCurrent.Ampere * Duration.Hour",
"ElectricCurrent.Ampere = ElectricCurrentGradient.AmperePerSecond * Duration.Second",
Expand Down Expand Up @@ -69,6 +68,7 @@
"ReciprocalArea.InverseSquareMeter = ReciprocalLength.InverseMeter * ReciprocalLength.InverseMeter",
"ReciprocalLength.InverseMeter = Length.Meter * ReciprocalArea.InverseSquareMeter",
"RotationalStiffness.NewtonMeterPerRadian = RotationalStiffnessPerLength.NewtonMeterPerRadianPerMeter * Length.Meter",
"Scalar.Amount = SpecificEnergy.JoulePerKilogram * BrakeSpecificFuelConsumption.KilogramPerJoule",
"SpecificEnergy.JoulePerKilogram = SpecificEntropy.JoulePerKilogramKelvin * TemperatureDelta.Kelvin",
"SpecificEnergy.JoulePerKilogram = Speed.MeterPerSecond * Speed.MeterPerSecond",
"SpecificWeight.NewtonPerCubicMeter = Acceleration.MeterPerSecondSquared * Density.KilogramPerCubicMeter",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,17 @@ public void PowerTimesBrakeSpecificFuelConsumptionEqualsMassFlow()
}

[Fact]
public void DoubleDividedByBrakeSpecificFuelConsumptionEqualsSpecificEnergy()
public void ScalarDividedByBrakeSpecificFuelConsumptionEqualsSpecificEnergy()
{
SpecificEnergy massFlow = 2 / BrakeSpecificFuelConsumption.FromKilogramsPerJoule(4);
SpecificEnergy massFlow = Scalar.FromAmount(2) / BrakeSpecificFuelConsumption.FromKilogramsPerJoule(4);
Assert.Equal(SpecificEnergy.FromJoulesPerKilogram(0.5), massFlow);
}

[Fact]
public void BrakeSpecificFuelConsumptionTimesSpecificEnergyEqualsEnergy()
{
var value = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(20) * SpecificEnergy.FromJoulesPerKilogram(10);
Assert.Equal(200, value);
Assert.Equal(Scalar.FromAmount(200), value);
}
}
}
6 changes: 3 additions & 3 deletions UnitsNet.Tests/CustomCode/SpecificEnergyTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,9 @@ public void SpecificEnergyTimesMassEqualsEnergy()
}

[Fact]
public void DoubleDividedBySpecificEnergyEqualsBrakeSpecificFuelConsumption()
public void ScalarDividedBySpecificEnergyEqualsBrakeSpecificFuelConsumption()
{
BrakeSpecificFuelConsumption bsfc = 2 / SpecificEnergy.FromJoulesPerKilogram(4);
BrakeSpecificFuelConsumption bsfc = Scalar.FromAmount(2) / SpecificEnergy.FromJoulesPerKilogram(4);
Assert.Equal(BrakeSpecificFuelConsumption.FromKilogramsPerJoule(0.5), bsfc);
}

Expand All @@ -77,7 +77,7 @@ public void SpecificEnergyTimesMassFlowEqualsPower()
public void SpecificEnergyTimesBrakeSpecificFuelConsumptionEqualsEnergy()
{
var value = SpecificEnergy.FromJoulesPerKilogram(10) * BrakeSpecificFuelConsumption.FromKilogramsPerJoule(20);
Assert.Equal(200, value);
Assert.Equal(Scalar.FromAmount(200), value);
}

[Fact]
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 18 additions & 0 deletions UnitsNet/GeneratedCode/Quantities/Scalar.g.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 7 additions & 13 deletions UnitsNet/GeneratedCode/Quantities/SpecificEnergy.g.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading