feat: quantity aliases support addded

This commit is contained in:
Mateusz Pusz
2021-04-15 19:13:25 +02:00
parent 813197021f
commit 70bff31d06
116 changed files with 2956 additions and 742 deletions
+1 -1
View File
@@ -39,7 +39,7 @@ if(NOT UNITS_LIBCXX)
add_subdirectory(glide_computer)
endif()
add_subdirectory(alternative_namespaces)
add_subdirectory(aliases)
add_subdirectory(kalman_filter)
add_subdirectory(literals)
add_subdirectory(references)
+51
View File
@@ -0,0 +1,51 @@
# The MIT License (MIT)
#
# Copyright (c) 2018 Mateusz Pusz
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
cmake_minimum_required(VERSION 3.2)
#
# add_example(target <depependencies>...)
#
function(add_example target)
add_executable(${target}-aliases ${target}.cpp)
target_link_libraries(${target}-aliases PRIVATE ${ARGN})
target_compile_definitions(${target}-aliases PRIVATE UNITS_ALIASES)
endfunction()
add_example(avg_speed mp-units::core-io mp-units::si mp-units::si-cgs mp-units::si-international)
add_example(box_example mp-units::core-fmt mp-units::si)
add_example(capacitor_time_curve mp-units::core-io mp-units::si)
add_example(clcpp_response mp-units::core-fmt mp-units::core-io mp-units::si mp-units::si-iau mp-units::si-imperial mp-units::si-international mp-units::si-typographic mp-units::si-us)
add_example(experimental_angle mp-units::core-fmt mp-units::core-io mp-units::si)
add_example(foot_pound_second mp-units::core-fmt mp-units::si-fps)
add_example(measurement mp-units::core-io mp-units::si)
add_example(total_energy mp-units::core-io mp-units::si mp-units::isq-natural)
add_example(unknown_dimension mp-units::core-io mp-units::si)
if(NOT UNITS_LIBCXX)
add_example(glide_computer_example mp-units::core-fmt mp-units::si-international glide_computer)
target_compile_definitions(glide_computer_example-aliases PRIVATE UNITS_REFERENCES)
find_package(linear_algebra CONFIG REQUIRED)
add_example(linear_algebra mp-units::core-fmt mp-units::core-io mp-units::si)
target_link_libraries(linear_algebra-aliases PRIVATE linear_algebra::linear_algebra)
endif()
+197
View File
@@ -0,0 +1,197 @@
// The MIT License (MIT)
//
// Copyright (c) 2018 Mateusz Pusz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <units/isq/si/cgs/length.h>
#include <units/isq/si/cgs/speed.h> // IWYU pragma: keep
#include <units/isq/si/international/length.h>
#include <units/isq/si/international/speed.h> // IWYU pragma: keep
#include <units/isq/si/length.h> // IWYU pragma: keep
#include <units/isq/si/time.h>
#include <units/isq/si/speed.h>
#include <units/quantity_io.h>
#include <exception>
#include <iostream>
namespace {
using namespace units::isq;
constexpr si::speed<si::metre_per_second, int>
fixed_int_si_avg_speed(si::length<si::metre, int> d,
si::time<si::second, int> t)
{
return d / t;
}
constexpr si::speed<si::metre_per_second>
fixed_double_si_avg_speed(si::length<si::metre> d,
si::time<si::second> t)
{
return d / t;
}
template<typename U1, typename R1, typename U2, typename R2>
constexpr Speed auto si_avg_speed(si::length<U1, R1> d,
si::time<U2, R2> t)
{
return d / t;
}
constexpr Speed auto avg_speed(Length auto d, Time auto t)
{
return d / t;
}
template<Length D, Time T, Speed V>
void print_result(D distance, T duration, V speed)
{
const auto result_in_kmph = units::quantity_cast<si::speed<si::kilometre_per_hour>>(speed);
std::cout << "Average speed of a car that makes " << distance << " in "
<< duration << " is " << result_in_kmph << ".\n";
}
void example()
{
// SI (int)
{
using namespace units::aliases::isq::si;
constexpr auto distance = km<int>(220);
constexpr auto duration = h<int>(2);
std::cout << "SI units with 'int' as representation\n";
print_result(distance, duration, fixed_int_si_avg_speed(distance, duration));
print_result(distance, duration, fixed_double_si_avg_speed(distance, duration));
print_result(distance, duration, si_avg_speed(distance, duration));
print_result(distance, duration, avg_speed(distance, duration));
}
// SI (double)
{
using namespace units::aliases::isq::si;
constexpr auto distance = km<double>(220.);
constexpr auto duration = h<double>(2.);
std::cout << "\nSI units with 'double' as representation\n";
// conversion from a floating-point to an integral type is a truncating one so an explicit cast is needed
print_result(distance, duration, fixed_int_si_avg_speed(quantity_cast<int>(distance), quantity_cast<int>(duration)));
print_result(distance, duration, fixed_double_si_avg_speed(distance, duration));
print_result(distance, duration, si_avg_speed(distance, duration));
print_result(distance, duration, avg_speed(distance, duration));
}
// Customary Units (int)
{
using namespace units::aliases::isq::si::international;
using namespace units::aliases::isq::si;
constexpr auto distance = mi<int>(140);
constexpr auto duration = h<int>(2);
std::cout << "\nUS Customary Units with 'int' as representation\n";
// it is not possible to make a lossless conversion of miles to meters on an integral type
// (explicit cast needed)
print_result(distance, duration, fixed_int_si_avg_speed(quantity_cast<si::metre>(distance), duration));
print_result(distance, duration, fixed_double_si_avg_speed(distance, duration));
print_result(distance, duration, si_avg_speed(distance, duration));
print_result(distance, duration, avg_speed(distance, duration));
}
// Customary Units (double)
{
using namespace units::aliases::isq::si::international;
using namespace units::aliases::isq::si;
constexpr auto distance = mi<double>(140.);
constexpr auto duration = h<double>(2.);
std::cout << "\nUS Customary Units with 'double' as representation\n";
// conversion from a floating-point to an integral type is a truncating one so an explicit cast is needed
// also it is not possible to make a lossless conversion of miles to meters on an integral type
// (explicit cast needed)
print_result(distance, duration, fixed_int_si_avg_speed(quantity_cast<si::length<si::metre, int>>(distance), quantity_cast<int>(duration)));
print_result(distance, duration, fixed_double_si_avg_speed(distance, duration));
print_result(distance, duration, si_avg_speed(distance, duration));
print_result(distance, duration, avg_speed(distance, duration));
}
// CGS (int)
{
using namespace units::aliases::isq::si::cgs;
using namespace units::aliases::isq::si::time;
constexpr auto distance = cm<int>(22'000'000);
constexpr auto duration = h<int>(2);
std::cout << "\nCGS units with 'int' as representation\n";
// it is not possible to make a lossless conversion of centimeters to meters on an integral type
// (explicit cast needed)
print_result(distance, duration, fixed_int_si_avg_speed(quantity_cast<si::metre>(distance), duration));
print_result(distance, duration, fixed_double_si_avg_speed(distance, duration));
// not possible to convert both a dimension and a unit with implicit cast
print_result(distance, duration, si_avg_speed(quantity_cast<si::dim_length>(distance), duration));
print_result(distance, duration, avg_speed(distance, duration));
}
// CGS (double)
{
using namespace units::aliases::isq::si::cgs;
using namespace units::aliases::isq::si::time;
constexpr auto distance = cm<double>(22'000'000.);
constexpr auto duration = h<double>(2.);
std::cout << "\nCGS units with 'double' as representation\n";
// conversion from a floating-point to an integral type is a truncating one so an explicit cast is needed
// it is not possible to make a lossless conversion of centimeters to meters on an integral type
// (explicit cast needed)
print_result(distance, duration, fixed_int_si_avg_speed(quantity_cast<si::length<si::metre, int>>(distance), quantity_cast<int>(duration)));
print_result(distance, duration, fixed_double_si_avg_speed(distance, duration));
// not possible to convert both a dimension and a unit with implicit cast
print_result(distance, duration, si_avg_speed(quantity_cast<si::dim_length>(distance), duration));
print_result(distance, duration, avg_speed(distance, duration));
}
}
} // namespace
int main()
{
try {
example();
}
catch (const std::exception& ex) {
std::cerr << "Unhandled std exception caught: " << ex.what() << '\n';
}
catch (...) {
std::cerr << "Unhandled unknown exception caught\n";
}
}
+105
View File
@@ -0,0 +1,105 @@
// The MIT License (MIT)
//
// Copyright (c) 2018 Mateusz Pusz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <units/format.h>
#include <units/generic/dimensionless.h>
#include <units/isq/si/amount_of_substance.h>
#include <units/isq/si/area.h>
#include <units/isq/si/constants.h>
#include <units/isq/si/density.h>
#include <units/isq/si/force.h>
#include <units/isq/si/length.h>
#include <units/isq/si/mass.h>
#include <units/isq/si/speed.h> // IWYU pragma: keep
#include <units/isq/si/time.h>
#include <units/isq/si/volume.h>
#include <cassert>
#include <iostream>
#include <utility>
namespace {
using namespace units::aliases::isq::si;
inline constexpr auto g = units::isq::si::si2019::standard_gravity<>;
inline constexpr auto air_density = kg_per_m3<>(1.225);
class Box {
area::m2<> base_;
length::m<> height_;
density::kg_per_m3<> density_ = air_density;
public:
constexpr Box(const length::m<>& length, const length::m<>& width, length::m<> height): base_(length * width), height_(std::move(height)) {}
[[nodiscard]] constexpr force::N<> filled_weight() const
{
const volume::m3<> volume = base_ * height_;
const mass::kg<> mass = density_ * volume;
return mass * g;
}
[[nodiscard]] constexpr length::m<> fill_level(const mass::kg<>& measured_mass) const
{
return height_ * measured_mass * g / filled_weight();
}
[[nodiscard]] constexpr volume::m3<> spare_capacity(const mass::kg<>& measured_mass) const
{
return (height_ - fill_level(measured_mass)) * base_;
}
constexpr void set_contents_density(const density::kg_per_m3<>& density_in)
{
assert(density_in > air_density);
density_ = density_in;
}
};
} // namespace
int main()
{
using namespace units;
using namespace units::isq;
const length::m<> height(mm<>(200.0));
auto box = Box(mm<>(1000.0), mm<>(500.0), height);
box.set_contents_density(kg_per_m3<>(1000.0));
const auto fill_time = s<>(200.0); // time since starting fill
const auto measured_mass = kg<>(20.0); // measured mass at fill_time
const Length auto fill_level = box.fill_level(measured_mass);
const Dimensionless auto fill_percent = quantity_cast<percent>(fill_level / height);
const Volume auto spare_capacity = box.spare_capacity(measured_mass);
const auto input_flow_rate = measured_mass / fill_time; // unknown dimension
const Speed auto float_rise_rate = fill_level / fill_time;
const Time auto fill_time_left = (height / fill_level - 1) * fill_time;
std::cout << "mp-units box example...\n";
std::cout << fmt::format("fill height at {} = {} ({} full)\n", fill_time, fill_level, fill_percent);
std::cout << fmt::format("spare_capacity at {} = {}\n", fill_time, spare_capacity);
std::cout << fmt::format("input flow rate after {} = {}\n", fill_time, input_flow_rate);
std::cout << fmt::format("float rise rate = {}\n", float_rise_rate);
std::cout << fmt::format("box full E.T.A. at current flow rate = {}\n", fill_time_left);
}
@@ -20,42 +20,44 @@
physical_quantities
*/
#include <units/generic/dimensionless.h>
#include <units/isq/dimensions/electric_current.h>
#include <units/isq/si/capacitance.h>
#include <units/isq/si/resistance.h>
#include <units/isq/si/time.h>
#include <units/math.h>
#include <units/isq/si/voltage.h>
#include <units/math.h> // IWYU pragma: keep
#include <units/quantity_io.h>
#include "./voltage.h"
#include <iostream>
using namespace units::experimental;
using namespace units::isq::si::literals;
int main()
{
std::cout << "mpusz/units capacitor time curve example...\n";
using namespace units::isq;
using namespace units::aliases::isq::si;
std::cout << "mp-units capacitor time curve example...\n";
std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
std::cout.precision(3);
constexpr auto C = 0.47_q_uF;
constexpr auto V0 = 5.0_q_V;
constexpr auto R = 4.7_q_kR;
constexpr auto C = capacitance::uF<>(0.47);
constexpr auto V0 = voltage::V<>(5.0);
constexpr auto R = resistance::kR<>(4.7);
for (auto t = 0_q_ms; t <= 50_q_ms; ++t) {
const auto Vt = V0 * units::exp(-t / (R * C));
for (auto t = ms<int>(0); t <= ms<int>(50); ++t) {
const Voltage auto Vt = V0 * units::exp(-t / (R * C));
std::cout << "at " << t << " voltage is ";
if (Vt >= 1_q_V)
if (Vt >= V<>(1))
std::cout << Vt;
else if (Vt >= 1_q_mV)
std::cout << voltage::mV<>{Vt};
else if (Vt >= 1_q_uV)
std::cout << voltage::uV<>{Vt};
else if (Vt >= 1_q_nV)
std::cout << voltage::nV<>{Vt};
else if (Vt >= mV<>(1))
std::cout << mV<>(Vt);
else if (Vt >= uV<>(1))
std::cout << uV<>(Vt);
else if (Vt >= nV<>(1))
std::cout << nV<>(Vt);
else
std::cout << voltage::pV<>{Vt};
std::cout << pV<>(Vt);
std::cout << "\n";
}
}
+151
View File
@@ -0,0 +1,151 @@
/*
Copyright (c) 2003-2019 Andy Little.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses./
*/
#include <units/format.h>
#include <units/isq/si/area.h>
#include <units/isq/si/iau/length.h>
#include <units/isq/si/imperial/length.h>
#include <units/isq/si/international/length.h>
#include <units/isq/si/length.h>
#include <units/isq/si/time.h>
#include <units/isq/si/typographic/length.h>
#include <units/isq/si/us/length.h>
#include <units/quantity_io.h>
#include <iostream>
namespace {
using namespace units;
void simple_quantities()
{
using namespace units::aliases::isq;
using namespace units::aliases::isq::si;
using namespace units::aliases::isq::si::international;
using distance = si::length::m<>;
using duration = time::s<>;
constexpr distance km = si::length::km<>(1.0);
constexpr distance miles = mi<>(1.0);
constexpr duration sec = s<>(1);
constexpr duration min = time::min<>(1);
constexpr duration hr = h<>(1);
std::cout << "A physical quantities library can choose the simple\n";
std::cout << "option to provide output using a single type for each base unit:\n\n";
std::cout << km << '\n';
std::cout << miles << '\n';
std::cout << sec << '\n';
std::cout << min << '\n';
std::cout << hr << "\n\n";
}
void quantities_with_typed_units()
{
using namespace units::aliases::isq;
using namespace units::aliases::isq::si;
using namespace units::aliases::isq::si::international;
constexpr si::length::km<> km = si::km<>(1.0);
constexpr si::international::length::mi<> miles = mi<>(1.0);
std::cout.precision(6);
constexpr time::s<> sec = s<>(1);
constexpr time::min<> min = si::min<>(1);
constexpr time::h<> hr = h<>(1);
std::cout << "A more flexible option is to provide separate types for each unit,\n\n";
std::cout << km << '\n';
std::cout << miles << '\n';
std::cout << sec << '\n';
std::cout << min << '\n';
std::cout << hr << "\n\n";
constexpr si::length::m<> meter = m<>(1);
std::cout << "then a wide range of pre-defined units can be defined and converted,\n"
" for consistency and repeatability across applications:\n\n";
std::cout << meter << '\n';
std::cout << " = " << au<>(meter) << '\n';
std::cout << " = " << iau::angstrom<>(meter) << '\n';
std::cout << " = " << imperial::ch<>(meter) << '\n';
std::cout << " = " << international::fathom<>(meter) << '\n';
std::cout << " = " << quantity_cast<units::isq::si::us::fathom>(meter) << '\n'; // `us` system namespace collides with a microsecond (si::time::us)
std::cout << " = " << international::ft<>(meter) << '\n';
std::cout << " = " << quantity_cast<units::isq::si::us::foot>(meter) << '\n'; // `us` system namespace collides with a microsecond (si::time::us)
std::cout << " = " << international::in<>(meter) << '\n';
std::cout << " = " << iau::ly<>(meter) << '\n';
std::cout << " = " << international::mi<>(meter) << '\n';
std::cout << " = " << international::mi_naut<>(meter) << '\n';
std::cout << " = " << iau::pc<>(meter) << '\n';
std::cout << " = " << typographic::pica_comp<>(meter) << '\n';
std::cout << " = " << typographic::pica_prn<>(meter) << '\n';
std::cout << " = " << typographic::point_comp<>(meter) << '\n';
std::cout << " = " << typographic::point_prn<>(meter) << '\n';
std::cout << " = " << imperial::rd<>(meter) << '\n';
std::cout << " = " << international::yd<>(meter) << '\n';
}
void calcs_comparison()
{
using namespace units::aliases::isq::si;
std::cout << "\nA distinct unit for each type is efficient and accurate\n"
"when adding two values of the same very big\n"
"or very small type:\n\n";
length::fm<float> L1A = fm<>(2.f);
length::fm<float> L2A = fm<>(3.f);
length::fm<float> LrA = L1A + L2A;
fmt::print("{:%.30Q %q}\n + {:%.30Q %q}\n = {:%.30Q %q}\n\n", L1A, L2A, LrA);
std::cout << "The single unit method must convert large\n"
"or small values in other units to the base unit.\n"
"This is both inefficient and inaccurate\n\n";
length::m<float> L1B = L1A;
length::m<float> L2B = L2A;
length::m<float> LrB = L1B + L2B;
fmt::print("{:%.30Q %q}\n + {:%.30Q %q}\n = {:%.30Q %q}\n\n", L1B, L2B, LrB);
std::cout << "In multiplication and division:\n\n";
area::fm2<float> ArA = L1A * L2A;
fmt::print("{:%.30Q %q}\n * {:%.30Q %q}\n = {:%.30Q %q}\n\n", L1A, L2A, ArA);
std::cout << "similar problems arise\n\n";
area::m2<float> ArB = L1B * L2B;
fmt::print("{:%.30Q %q}\n * {:%.30Q %q}\n = {:%.30Q %q}\n\n", L1B, L2B, ArB);
}
} // namespace
int main()
{
std::cout << "This demo was originally posted on com.lang.c++.moderated in 2006\n";
std::cout << "http://compgroups.net/comp.lang.c++.moderated/dimensional-analysis-units/51712\n";
std::cout << "Here converted to use mp-units library.\n\n";
simple_quantities();
quantities_with_typed_units();
calcs_comparison();
}
+40
View File
@@ -0,0 +1,40 @@
// The MIT License (MIT)
//
// Copyright (c) 2018 Mateusz Pusz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <units/generic/angle.h>
#include <units/isq/si/energy.h>
#include <units/isq/si/torque.h>
#include <units/quantity_io.h>
#include <iostream>
int main()
{
using namespace units::isq;
using namespace units::aliases::isq::si;
const auto torque = N_m_per_rad<>(20.0);
const auto energy = J<>(20.0);
units::Angle auto angle = energy / torque;
std::cout << angle << '\n';
}
+98
View File
@@ -0,0 +1,98 @@
// The MIT License (MIT)
//
// Copyright (c) 2018 Mateusz Pusz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <units/format.h>
#include <units/isq/si/fps/density.h>
#include <units/isq/si/fps/length.h>
#include <units/isq/si/fps/mass.h>
#include <units/isq/si/fps/power.h>
#include <units/isq/si/fps/speed.h>
#include <units/isq/si/length.h>
#include <units/isq/si/mass.h>
#include <units/isq/si/power.h>
#include <units/isq/si/speed.h>
#include <units/isq/si/volume.h>
#include <iostream>
#include <string_view>
using namespace units::aliases::isq;
// Some basic specs for the warship
struct Ship {
si::fps::length::ft<> length;
si::fps::length::ft<> draft;
si::fps::length::ft<> beam;
si::fps::speed::ft_per_s<> speed;
si::fps::mass::lb<> mass;
si::fps::length::in<> mainGuns;
si::fps::mass::lb<> shellMass;
si::fps::speed::ft_per_s<> shellSpeed;
si::fps::power::ft_pdl_per_s<> power;
};
// Print 'a' in its current units and print its value cast to the units in each of Args
template<class ...Args, units::Quantity Q>
auto fmt_line(const Q a)
{
return fmt::format("{:22}", a) + (fmt::format(",{:20}", units::quantity_cast<Args>(a)) + ...);
}
// Print the ship details in the units as defined in the Ship struct, in other si::imperial units, and in SI
void print_details(std::string_view description, const Ship& ship)
{
const auto waterDensity = si::fps::density::lb_per_ft3<>(62.4);
std::cout << fmt::format("{}\n", description);
std::cout << fmt::format("{:20} : {}\n", "length", fmt_line<si::fps::length::yd<>, si::length::m<>>(ship.length))
<< fmt::format("{:20} : {}\n", "draft", fmt_line<si::fps::length::yd<>, si::length::m<>>(ship.draft))
<< fmt::format("{:20} : {}\n", "beam", fmt_line<si::fps::length::yd<>, si::length::m<>>(ship.beam))
<< fmt::format("{:20} : {}\n", "mass", fmt_line<si::fps::mass::lton<>, si::mass::t<>>(ship.mass))
<< fmt::format("{:20} : {}\n", "speed", fmt_line<si::fps::speed::knot<>, si::speed::km_per_h<>>(ship.speed))
<< fmt::format("{:20} : {}\n", "power", fmt_line<si::fps::power::hp<>, si::power::kW<>>(ship.power))
<< fmt::format("{:20} : {}\n", "main guns", fmt_line<si::fps::length::in<>, si::length::mm<>>(ship.mainGuns))
<< fmt::format("{:20} : {}\n", "fire shells weighing",fmt_line<si::fps::mass::lton<>, si::mass::kg<>>(ship.shellMass))
<< fmt::format("{:20} : {}\n", "fire shells at",fmt_line<si::fps::speed::mph<>, si::speed::km_per_h<>>(ship.shellSpeed))
<< fmt::format("{:20} : {}\n", "volume underwater", fmt_line<si::volume::m3<>, si::volume::l<>>(ship.mass / waterDensity));
}
int main()
{
using namespace units::aliases::isq::si;
using namespace units::aliases::isq::si::fps;
using units::aliases::isq::si::fps::length::ft; // to disambiguate from si::femptotonne
// KMS Bismark, using the units the Germans would use, taken from Wiki
auto bismark = Ship{.length{m<>(251.)}, .draft{m<>(9.3)}, .beam{m<>(36)}, .speed{km_per_h<>(56)}, .mass{t<>(50'300)}, .mainGuns{mm<>(380)}, .shellMass{kg<>(800)}, .shellSpeed{m_per_s<>(820.)}, .power{kW<>(110.45)}};
// USS Iowa, using units from the foot-pound-second system
auto iowa = Ship{.length{ft<>(860.)}, .draft{ft<>(37.) + in<>(2.)}, .beam{ft<>(108.) + in<>(2.)}, .speed{knot<>(33)}, .mass{lton<>(57'540)}, .mainGuns{in<>(16)}, .shellMass{lb<>(2700)}, .shellSpeed{ft_per_s<>(2690.)}, .power{hp<>(212'000)}};
// HMS King George V, using units from the foot-pound-second system
auto kgv = Ship{.length{ft<>(745.1)}, .draft{ft<>(33.) + in<>(7.5)}, .beam{ft<>(103.2) + in<>(2.5)}, .speed{knot<>(28.3)}, .mass{lton<>(42'245)}, .mainGuns{in<>(14)}, .shellMass{lb<>(1'590)}, .shellSpeed{ft_per_s<>(2483)}, .power{hp<>(110'000)}};
print_details("KMS Bismark, defined in appropriate units from the SI system", bismark);
std::cout << "\n\n";
print_details("USS Iowa, defined in appropriate units foot-pound-second system", iowa);
std::cout << "\n\n";
print_details("HMS King George V, defined in appropriate units foot-pound-second system", kgv);
}
+202
View File
@@ -0,0 +1,202 @@
// The MIT License (MIT)
//
// Copyright (c) 2018 Mateusz Pusz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "glide_computer.h"
#include <units/bits/external/hacks.h>
#include <units/chrono.h>
#include <units/generic/dimensionless.h>
#include <units/isq/si/international/length.h>
UNITS_DIAGNOSTIC_PUSH
UNITS_DIAGNOSTIC_IGNORE_UNREACHABLE
#include <fmt/format.h>
UNITS_DIAGNOSTIC_POP
#include <array>
#include <exception>
#include <iostream>
#include <iterator>
#include <string>
#include <utility>
#include <vector>
namespace {
using namespace glide_computer;
using namespace units::isq;
auto get_gliders()
{
using namespace units::aliases::isq::si;
UNITS_DIAGNOSTIC_PUSH
UNITS_DIAGNOSTIC_IGNORE_MISSING_BRACES
static const std::array gliders = {
glider{"SZD-30 Pirat", {velocity(km_per_h<>(83)), rate_of_climb(m_per_s<>(-0.7389))}},
glider{"SZD-51 Junior", {velocity(km_per_h<>(80)), rate_of_climb(m_per_s<>(-0.6349))}},
glider{"SZD-48 Jantar Std 3", {velocity(km_per_h<>(110)), rate_of_climb(m_per_s<>(-0.77355))}},
glider{"SZD-56 Diana", {velocity(km_per_h<>(110)), rate_of_climb(m_per_s<>(-0.63657))}}};
UNITS_DIAGNOSTIC_POP
return gliders;
}
auto get_weather_conditions()
{
using namespace units::aliases::isq::si;
static const std::array weather_conditions = {
std::pair("Good", weather{height(m<>(1900)), rate_of_climb(m_per_s<>(4.3))}),
std::pair("Medium", weather{height(m<>(1550)), rate_of_climb(m_per_s<>(2.8))}),
std::pair("Bad", weather{height(m<>(850)), rate_of_climb(m_per_s<>(1.8))})};
return weather_conditions;
}
auto get_waypoints()
{
using namespace geographic::literals;
using namespace units::aliases::isq::si::international;
static const std::array waypoints = {
waypoint{"EPPR", {54.24772_N, 18.6745_E}, altitude(ft<>(16))}, // N54°14'51.8" E18°40'28.2"
waypoint{"EPGI", {53.52442_N, 18.84947_E}, altitude(ft<>(115))} // N53°31'27.9" E18°50'58.1"
};
return waypoints;
}
template<std::ranges::forward_range R>
requires std::same_as<std::ranges::range_value_t<R>, glider>
void print(const R& gliders)
{
std::cout << "Gliders:\n";
std::cout << "========\n";
for (const auto& g : gliders) {
std::cout << "- Name: " << g.name << "\n";
std::cout << "- Polar:\n";
for (const auto& p : g.polar)
fmt::print(" * {:%.4Q %q} @ {:%.1Q %q} -> {:%.1Q %q}\n", p.climb, p.v, units::quantity_cast<units::one>(glide_ratio(g.polar[0])));
std::cout << "\n";
}
}
template<std::ranges::forward_range R>
requires std::same_as<std::ranges::range_value_t<R>, std::pair<const char*, weather>>
void print(const R& conditions)
{
std::cout << "Weather:\n";
std::cout << "========\n";
for (const auto& c : conditions) {
std::cout << "- " << c.first << "\n";
const auto& w = c.second;
std::cout << " * Cloud base: " << fmt::format("{:%.0Q %q}", w.cloud_base) << " AGL\n";
std::cout << " * Thermals strength: " << fmt::format("{:%.1Q %q}", w.thermal_strength) << "\n";
std::cout << "\n";
}
}
template<std::ranges::forward_range R>
requires std::same_as<std::ranges::range_value_t<R>, waypoint>
void print(const R& waypoints)
{
std::cout << "Waypoints:\n";
std::cout << "==========\n";
for (const auto& w : waypoints)
std::cout << fmt::format("- {}: {} {}, {:%.1Q %q}\n", w.name, w.pos.lat, w.pos.lon, w.alt);
std::cout << "\n";
}
void print(const task& t)
{
std::cout << "Task:\n";
std::cout << "=====\n";
std::cout << "- Start: " << t.get_start().name << "\n";
std::cout << "- Finish: " << t.get_finish().name << "\n";
std::cout << "- Length: " << fmt::format("{:%.1Q %q}", t.get_length()) << "\n";
std::cout << "- Legs: " << "\n";
for (const auto& l : t.get_legs())
std::cout << fmt::format(" * {} -> {} ({:%.1Q %q})\n", l.begin().name, l.end().name, l.get_length());
std::cout << "\n";
}
void print(const safety& s)
{
std::cout << "Safety:\n";
std::cout << "=======\n";
std::cout << "- Min AGL separation: " << fmt::format("{:%.0Q %q}", s.min_agl_height) << "\n";
std::cout << "\n";
}
void print(const aircraft_tow& tow)
{
std::cout << "Tow:\n";
std::cout << "====\n";
std::cout << "- Type: aircraft\n";
std::cout << "- Height: " << fmt::format("{:%.0Q %q}", tow.height_agl) << "\n";
std::cout << "- Performance: " << fmt::format("{:%.1Q %q}", tow.performance) << "\n";
std::cout << "\n";
}
void example()
{
using namespace units::aliases::isq::si;
const safety sfty = {height(m<>(300))};
const auto gliders = get_gliders();
const auto waypoints = get_waypoints();
const auto weather_conditions = get_weather_conditions();
const task t = {waypoints[0], waypoints[1], waypoints[0]};
const aircraft_tow tow = {height(m<>(400)), rate_of_climb(m_per_s<>(1.6))};
// TODO use C++20 date library when available
// set `start_time` to 11:00 am today
const timestamp start_time(std::chrono::system_clock::now());
print(sfty);
print(gliders);
print(waypoints);
print(weather_conditions);
print(t);
print(tow);
for (const auto& g : gliders) {
for (const auto& c : weather_conditions) {
std::string txt = "Scenario: Glider = " + g.name + ", Weather = " + c.first;
std::cout << txt << "\n";
fmt::print("{0:=^{1}}\n\n", "", txt.size());
estimate(start_time, g, c.second, t, sfty, tow);
std::cout << "\n\n";
}
}
}
} // namespace
int main()
{
try {
example();
} catch (const std::exception& ex) {
std::cerr << "Unhandled std exception caught: " << ex.what() << '\n';
} catch (...) {
std::cerr << "Unhandled unknown exception caught\n";
}
}
+362
View File
@@ -0,0 +1,362 @@
// The MIT License (MIT)
//
// Copyright (c) 2018 Mateusz Pusz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <units/isq/si/energy.h> // IWYU pragma: keep
#include <units/isq/si/force.h>
#include <units/isq/si/length.h>
#include <units/isq/si/speed.h> // IWYU pragma: keep
#include <units/format.h>
#include <units/quantity_io.h>
#include <linear_algebra.hpp>
#include <iostream>
namespace STD_LA {
template<class ET, class OT>
std::ostream& operator<<(std::ostream& os, const vector<ET, OT>& v)
{
os << "|";
for (auto i = 0U; i < v.size(); ++i) {
os << fmt::format(" {:>9}", v(i));
}
os << " |";
return os;
}
template<class ET, class OT>
std::ostream& operator<<(std::ostream& os, const matrix<ET, OT>& v)
{
for (auto i = 0U; i < v.rows(); ++i) {
os << "|";
for (auto j = 0U; j < v.columns(); ++j) {
os << fmt::format(" {:>9}", v(i, j));
}
os << (i != v.rows() - 1U ? " |\n" : " |");
}
return os;
}
} // namespace STD_LA
namespace {
using namespace units::aliases::isq::si;
template<typename Rep = double>
using vector = std::math::fs_vector<Rep, 3>;
template<typename Rep = double>
using matrix = std::math::fs_matrix<Rep, 3, 3>;
void vector_of_quantity_add()
{
std::cout << "\nvector_of_quantity_add:\n";
vector<length::m<>> v = { m<>(1), m<>(2), m<>(3) };
vector<length::m<>> u = { m<>(3), m<>(2), m<>(1) };
vector<length::km<>> t = { km<>(3), km<>(2), km<>(1) };
std::cout << "v = " << v << "\n";
std::cout << "u = " << u << "\n";
std::cout << "t = " << t << "\n";
std::cout << "v + u = " << v + u << "\n";
std::cout << "v + t = " << v + t << "\n";
std::cout << "t[m] = " << vector<length::m<>>(t) << "\n";
}
void vector_of_quantity_multiply_same()
{
std::cout << "\nvector_of_quantity_multiply_same:\n";
vector<length::m<>> v = { m<>(1), m<>(2), m<>(3) };
vector<length::m<>> u = { m<>(3), m<>(2), m<>(1) };
std::cout << "v = " << v << "\n";
std::cout << "u = " << u << "\n";
std::cout << "v * u = " << v * u << "\n";
std::cout << "m<>(2) * v = " << m<>(2.) * v << "\n";
}
void vector_of_quantity_multiply_different()
{
std::cout << "\nvector_of_quantity_multiply_different:\n";
vector<force::N<>> v = { N<>(1), N<>(2), N<>(3) };
vector<length::m<>> u = { m<>(3), m<>(2), m<>(1) };
std::cout << "v = " << v << "\n";
std::cout << "u = " << u << "\n";
std::cout << "v * u = " << v * u << "\n";
std::cout << "N<>(2) * u = " << N<>(2.) * u << "\n";
std::cout << "2 * u = " << 2 * u << "\n";
}
void vector_of_quantity_divide_by_scalar()
{
std::cout << "\nvector_of_quantity_divide_by_scalar:\n";
vector<length::m<>> v = { m<>(4), m<>(8), m<>(12) };
std::cout << "v = " << v << "\n";
// TODO Uncomment when bug in the LA is fixed
// std::cout << "v / s<>(2) = " << v / s<>(2) << "\n";
// std::cout << "v / 2 = " << v / 2 << "\n";
}
void vector_of_quantity_tests()
{
vector_of_quantity_add();
vector_of_quantity_multiply_same();
vector_of_quantity_multiply_different();
vector_of_quantity_divide_by_scalar();
}
void matrix_of_quantity_add()
{
std::cout << "\nmatrix_of_quantity_add:\n";
matrix<length::m<>> v = {{ m<>(1), m<>(2), m<>(3) }, { m<>(4), m<>(5), m<>(6) }, { m<>(7), m<>(8), m<>(9) }};
matrix<length::m<>> u = {{ m<>(3), m<>(2), m<>(1) }, { m<>(3), m<>(2), m<>(1) }, { m<>(3), m<>(2), m<>(1) }};
matrix<length::mm<>> t = {{ mm<>(3), mm<>(2), mm<>(1) }, { mm<>(3), mm<>(2), mm<>(1) }, { mm<>(3), mm<>(2), mm<>(1) }};
std::cout << "v =\n" << v << "\n";
std::cout << "u =\n" << u << "\n";
std::cout << "t =\n" << t << "\n";
std::cout << "v + u =\n" << v + u << "\n";
std::cout << "v + t =\n" << v + t << "\n";
// TODO Uncomment when fixed in the LA lib
// std::cout << "v[mm] =\n" << matrix<length::mm<>>(v) << "\n";
}
void matrix_of_quantity_multiply_same()
{
std::cout << "\nmatrix_of_quantity_multiply_same:\n";
matrix<length::m<>> v = {{ m<>(1), m<>(2), m<>(3) }, { m<>(4), m<>(5), m<>(6) }, { m<>(7), m<>(8), m<>(9) }};
vector<length::m<>> u = { m<>(3), m<>(2), m<>(1) };
std::cout << "v =\n" << v << "\n";
std::cout << "u =\n" << u << "\n";
std::cout << "v * u =\n" << v * u << "\n";
std::cout << "m<>(2) * u =\n" << m<>(2.) * u << "\n";
}
void matrix_of_quantity_multiply_different()
{
std::cout << "\nmatrix_of_quantity_multiply_different:\n";
vector<force::N<>> v = { N<>(1), N<>(2), N<>(3) };
matrix<length::m<>> u = {{ m<>(1), m<>(2), m<>(3) }, { m<>(4), m<>(5), m<>(6) }, { m<>(7), m<>(8), m<>(9) }};
std::cout << "v =\n" << v << "\n";
std::cout << "u =\n" << u << "\n";
std::cout << "v * u =\n" << v * u << "\n";
std::cout << "N<>(2) * u =\n" << N<>(2.) * u << "\n";
std::cout << "2 * u =\n" << 2 * u << "\n";
}
void matrix_of_quantity_divide_by_scalar()
{
std::cout << "\nmatrix_of_quantity_divide_by_scalar:\n";
matrix<length::m<>> v = {{ m<>(2), m<>(4), m<>(6) }, { m<>(4), m<>(6), m<>(8) }, { m<>(8), m<>(4), m<>(2) }};
std::cout << "v =\n" << v << "\n";
// TODO Uncomment when bug in the LA is fixed
// std::cout << "v / s<>(2) =\n" << v / s<>(2) << "\n";
// std::cout << "v / 2 =\n" << v / 2 << "\n";
}
void matrix_of_quantity_tests()
{
matrix_of_quantity_add();
matrix_of_quantity_multiply_same();
matrix_of_quantity_multiply_different();
matrix_of_quantity_divide_by_scalar();
}
using namespace units::isq;
template<units::Unit U = si::metre, units::Representation Rep = double>
using length_v = si::length<U, vector<Rep>>;
template<units::Unit U = si::newton, units::Representation Rep = double>
using force_v = si::force<U, vector<Rep>>;
void quantity_of_vector_add()
{
std::cout << "\nquantity_of_vector_add:\n";
length_v<> v(vector<>{ 1, 2, 3 });
length_v<> u(vector<>{ 3, 2, 1 });
length_v<si::kilometre> t(vector<>{ 3, 2, 1 });
std::cout << "v = " << v << "\n";
std::cout << "u = " << u << "\n";
std::cout << "t = " << t << "\n";
std::cout << "v + u = " << v + u << "\n";
std::cout << "v + t = " << v + t << "\n";
std::cout << "t[m] = " << quantity_cast<si::metre>(t) << "\n";
}
void quantity_of_vector_multiply_same()
{
std::cout << "\nquantity_of_vector_multiply_same:\n";
length_v<> v(vector<>{ 1, 2, 3 });
length_v<> u(vector<>{ 3, 2, 1 });
std::cout << "v = " << v << "\n";
std::cout << "u = " << u << "\n";
std::cout << "v * u = " << v * u << "\n";
std::cout << "m<>(2) * v = " << m<>(2.) * v << "\n";
}
void quantity_of_vector_multiply_different()
{
std::cout << "\nquantity_of_vector_multiply_different:\n";
force_v<> v(vector<>{ 1, 2, 3 });
length_v<> u(vector<>{ 3, 2, 1 });
std::cout << "v = " << v << "\n";
std::cout << "u = " << u << "\n";
std::cout << "v * u = " << v * u << "\n";
std::cout << "N<>(2) * u = " << N<>(2.) * u << "\n";
std::cout << "2 * u = " << 2 * u << "\n";
}
void quantity_of_vector_divide_by_scalar()
{
std::cout << "\nquantity_of_vector_divide_by_scalar:\n";
length_v<> v(vector<>{ 4, 8, 12 });
std::cout << "v = " << v << "\n";
// TODO Uncomment when bug in the LA is fixed
// std::cout << "v / s<>(2) = " << v / s<>(2) << "\n";
// std::cout << "v / 2 = " << v / 2 << "\n";
}
void quantity_of_vector_tests()
{
quantity_of_vector_add();
quantity_of_vector_multiply_same();
quantity_of_vector_multiply_different();
quantity_of_vector_divide_by_scalar();
}
template<units::Unit U = si::metre, units::Representation Rep = double>
using length_m = si::length<U, matrix<Rep>>;
void quantity_of_matrix_add()
{
std::cout << "\nquantity_of_matrix_add:\n";
length_m<> v(matrix<>{{ 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }});
length_m<> u(matrix<>{{ 3, 2, 1 }, { 3, 2, 1 }, { 3, 2, 1 }});
length_m<si::kilometre> t(matrix<>{{ 3, 2, 1 }, { 3, 2, 1 }, { 3, 2, 1 }});
std::cout << "v =\n" << v << "\n";
std::cout << "u =\n" << u << "\n";
std::cout << "t =\n" << t << "\n";
std::cout << "v + u =\n" << v + u << "\n";
std::cout << "v + t =\n" << v + t << "\n";
// TODO Uncomment when fixed in the LA lib
// std::cout << "v[mm] =\n" << matrix<length::mm<>>(v) << "\n";
}
void quantity_of_matrix_multiply_same()
{
std::cout << "\nquantity_of_matrix_multiply_same:\n";
length_m<> v(matrix<>{{ 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }});
length_v<> u(vector<>{ 3, 2, 1 });
std::cout << "v =\n" << v << "\n";
std::cout << "u =\n" << u << "\n";
std::cout << "v * u =\n" << v * u << "\n";
std::cout << "m<>(2) * u =\n" << m<>(2.) * u << "\n";
}
void quantity_of_matrix_multiply_different()
{
std::cout << "\nquantity_of_matrix_multiply_different:\n";
force_v<> v(vector<>{ 1, 2, 3 });
length_m<> u(matrix<>{{ 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }});
std::cout << "v =\n" << v << "\n";
std::cout << "u =\n" << u << "\n";
std::cout << "v * u =\n" << v * u << "\n";
std::cout << "N<>(2) * u =\n" << N<>(2.) * u << "\n";
std::cout << "2 * u =\n" << 2 * u << "\n";
}
void quantity_of_matrix_divide_by_scalar()
{
std::cout << "\nquantity_of_matrix_divide_by_scalar:\n";
length_m<> v(matrix<>{{ 2, 4, 6 }, { 4, 6, 8 }, { 8, 4, 2 }});
std::cout << "v =\n" << v << "\n";
// TODO Uncomment when bug in the LA is fixed
// std::cout << "v / s<>(2) =\n" << v / s<>(2) << "\n";
// std::cout << "v / 2 =\n" << v / 2 << "\n";
}
void quantity_of_matrix_tests()
{
quantity_of_matrix_add();
quantity_of_matrix_multiply_same();
quantity_of_matrix_multiply_different();
quantity_of_matrix_divide_by_scalar();
}
} // namespace
int main()
{
vector_of_quantity_tests();
matrix_of_quantity_tests();
quantity_of_vector_tests();
quantity_of_matrix_tests();
}
+157
View File
@@ -0,0 +1,157 @@
// The MIT License (MIT)
//
// Copyright (c) 2018 Mateusz Pusz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <units/isq/si/acceleration.h>
#include <units/isq/si/length.h>
#include <units/isq/si/speed.h>
#include <units/isq/si/time.h>
#include <units/quantity_io.h>
#include <cmath>
#include <exception>
#include <iostream>
namespace {
template<class T>
class measurement {
public:
using value_type = T;
measurement() = default;
constexpr explicit measurement(const value_type& val, const value_type& err = {}) :
value_(val)
{
// it sucks that using declaration cannot be provided for a constructor initializer list
using namespace std;
uncertainty_ = abs(err);
}
constexpr const value_type& value() const { return value_; }
constexpr const value_type& uncertainty() const { return uncertainty_; }
constexpr value_type relative_uncertainty() const { return uncertainty() / value(); }
constexpr value_type lower_bound() const { return value() - uncertainty(); }
constexpr value_type upper_bound() const { return value() + uncertainty(); }
[[nodiscard]] constexpr measurement operator-() const { return measurement(-value(), uncertainty()); }
[[nodiscard]] friend constexpr measurement operator+(const measurement& lhs, const measurement& rhs)
{
using namespace std;
return measurement(lhs.value() + rhs.value(), hypot(lhs.uncertainty(), rhs.uncertainty()));
}
[[nodiscard]] friend constexpr measurement operator-(const measurement& lhs, const measurement& rhs)
{
using namespace std;
return measurement(lhs.value() - rhs.value(), hypot(lhs.uncertainty(), rhs.uncertainty()));
}
[[nodiscard]] friend constexpr measurement operator*(const measurement& lhs, const measurement& rhs)
{
const auto val = lhs.value() * rhs.value();
using namespace std;
return measurement(val, val * hypot(lhs.relative_uncertainty(), rhs.relative_uncertainty()));
}
[[nodiscard]] friend constexpr measurement operator*(const measurement& lhs, const value_type& value)
{
const auto val = lhs.value() * value;
return measurement(val, val * lhs.relative_uncertainty());
}
[[nodiscard]] friend constexpr measurement operator*(const value_type& value, const measurement& rhs)
{
const auto val = rhs.value() * value;
return measurement(val, val * rhs.relative_uncertainty());
}
[[nodiscard]] friend constexpr measurement operator/(const measurement& lhs, const measurement& rhs)
{
const auto val = lhs.value() / rhs.value();
using namespace std;
return measurement(val, val * hypot(lhs.relative_uncertainty(), rhs.relative_uncertainty()));
}
[[nodiscard]] friend constexpr measurement operator/(const measurement& lhs, const value_type& value)
{
const auto val = lhs.value() / value;
return measurement(val, val * lhs.relative_uncertainty());
}
[[nodiscard]] friend constexpr measurement operator/(const value_type& value, const measurement& rhs)
{
const auto val = value / rhs.value();
return measurement(val, val * rhs.relative_uncertainty());
}
[[nodiscard]] constexpr auto operator<=>(const measurement&) const = default;
friend std::ostream& operator<<(std::ostream& os, const measurement& v)
{
return os << v.value() << " ± " << v.uncertainty();
}
private:
value_type value_{};
value_type uncertainty_{};
};
} // namespace
namespace {
static_assert(units::Representation<measurement<double>>);
void example()
{
using namespace units::isq;
using namespace units::aliases::isq::si;
const auto a = acceleration::m_per_s2<measurement<double>>(measurement(9.8, 0.1));
const auto t = time::s<measurement<double>>(measurement(1.2, 0.1));
const Speed auto v1 = a * t;
#if UNITS_DOWNCAST_MODE == 0
std::cout << a << " * " << t << " = " << v1 << " = " << km_per_h<measurement<double>>(v1) << '\n';
#else
std::cout << a << " * " << t << " = " << v1 << " = " << km_per_h<measurement<double>>(v1) << '\n';
#endif
length::m<measurement<double>> length(measurement(123., 1.));
std::cout << "10 * " << length << " = " << 10 * length << '\n';
}
} // namespace
int main()
{
try {
example();
} catch (const std::exception& ex) {
std::cerr << "Unhandled std exception caught: " << ex.what() << '\n';
} catch (...) {
std::cerr << "Unhandled unknown exception caught\n";
}
}
+102
View File
@@ -0,0 +1,102 @@
// The MIT License (MIT)
//
// Copyright (c) 2018 Mateusz Pusz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <units/isq/natural/natural.h>
#include <units/isq/si/energy.h>
#include <units/isq/si/mass.h>
#include <units/isq/si/momentum.h>
#include <units/isq/si/speed.h> // IWYU pragma: keep
#include <units/isq/si/constants.h>
#include <units/math.h>
#include <units/quantity_io.h>
#include <exception>
#include <iostream>
namespace {
using namespace units::isq;
Energy auto total_energy(Momentum auto p, Mass auto m, Speed auto c)
{
return sqrt(pow<2>(p * c) + pow<2>(m * pow<2>(c)));
}
void si_example()
{
using namespace units::aliases::isq::si;
constexpr Speed auto c = units::isq::si::si2019::speed_of_light<>;
std::cout << "\n*** SI units (c = " << c << ") ***\n";
const Momentum auto p = GeV<>(4.) / c;
const Mass auto m = GeV<>(3.) / pow<2>(c);
const Energy auto E = total_energy(p, m, c);
std::cout << "[in GeV]\n"
<< "p = " << p << "\n"
<< "m = " << m << "\n"
<< "E = " << E << "\n";
const momentum::kg_m_per_s<> p_si = p;
const mass::kg<> m_si = m;
const energy::J<> E_si = total_energy(p_si, m_si, c);
std::cout << "\n[in SI units]\n"
<< "p = " << p_si << "\n"
<< "m = " << m_si << "\n"
<< "E = " << E_si << "\n";
std::cout << "\n[converted from SI units back to GeV]\n"
<< "E = " << GeV<>(E_si) << "\n";
}
void natural_example()
{
using namespace units::aliases::isq::natural;
constexpr Speed auto c = units::isq::natural::speed_of_light<>;
const momentum::GeV<> p(4);
const mass::GeV<> m(3);
const Energy auto E = total_energy(p, m, c);
std::cout << "\n*** Natural units (c = " << c << ") ***\n"
<< "p = " << p << "\n"
<< "m = " << m << "\n"
<< "E = " << E << "\n";
}
} // namespace
int main()
{
try {
si_example();
natural_example();
}
catch (const std::exception& ex) {
std::cerr << "Unhandled std exception caught: " << ex.what() << '\n';
}
catch (...) {
std::cerr << "Unhandled unknown exception caught\n";
}
}
+72
View File
@@ -0,0 +1,72 @@
// The MIT License (MIT)
//
// Copyright (c) 2018 Mateusz Pusz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <units/isq/si/length.h>
#include <units/isq/si/speed.h> // IWYU pragma: keep
#include <units/isq/si/time.h>
#include <units/quantity_io.h>
#include <exception>
#include <iostream>
namespace {
template<units::isq::Length D, units::isq::Time T>
constexpr units::isq::Speed auto avg_speed(D d, T t)
{
return d / t;
}
void example()
{
using namespace units::isq;
using namespace units::aliases::isq::si;
Length auto d1 = m<>(123);
Time auto t1 = s<>(10);
Speed auto v1 = avg_speed(d1, t1);
auto temp1 = v1 * m<>(50); // produces intermediate unknown dimension with 'unknown_coherent_unit' as its 'coherent_unit'
Speed auto v2 = temp1 / m<>(100); // back to known dimensions again
Length auto d2 = v2 * s<>(60);
std::cout << "d1 = " << d1 << '\n';
std::cout << "t1 = " << t1 << '\n';
std::cout << "v1 = " << v1 << '\n';
std::cout << "temp1 = " << temp1 << '\n';
std::cout << "v2 = " << v2 << '\n';
std::cout << "d2 = " << d2 << '\n';
}
} // namespace
int main()
{
try {
example();
}
catch (const std::exception& ex) {
std::cerr << "Unhandled std exception caught: " << ex.what() << '\n';
}
catch (...) {
std::cerr << "Unhandled unknown exception caught\n";
}
}
@@ -1,35 +0,0 @@
# The MIT License (MIT)
#
# Copyright (c) 2018 Mateusz Pusz
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
cmake_minimum_required(VERSION 3.2)
function(add_example target)
add_executable(${target}_alt ${target}.cpp)
target_link_libraries(${target}_alt PRIVATE mp-units::mp-units)
target_compile_definitions(${target}_alt PRIVATE UNITS_LITERALS)
endfunction()
add_example(box_example mp-units::si)
add_example(capacitor_time_curve mp-units::si)
add_example(clcpp_response mp-units::si)
add_example(conversion_factor mp-units::si)
add_example(timer mp-units::si)
@@ -1,19 +0,0 @@
#pragma once
#include <units/isq/si/acceleration.h>
namespace units{
namespace experimental{
namespace acceleration {
template<typename Rep = double>
using m_per_s2 = units::isq::si::acceleration<units::isq::si::metre_per_second_sq, Rep>;
template<typename Rep = double>
constexpr m_per_s2<Rep> g{static_cast<Rep>(9.80665)};
} // namespace acceleration
}} // units::experimental
-14
View File
@@ -1,14 +0,0 @@
#pragma once
#include <units/isq/si/area.h>
namespace area {
template<typename Rep = double>
using m2 = units::isq::si::area<units::isq::si::square_metre, Rep>;
template<typename Rep = double>
using fm2 = units::isq::si::area<units::isq::si::square_femtometre, Rep>;
} // namespace area
@@ -1,74 +0,0 @@
#include <units/quantity_io.h>
#include "./length.h"
#include "./acceleration.h"
#include "./density.h"
#include "./force.h"
#include "./mass.h"
#include "./time.h"
#include "./volume.h"
#include <cassert>
using namespace units::experimental;
struct Box {
static constexpr auto air_density = density::kg_per_m3<>{1.225};
length::m<> length;
length::m<> width;
length::m<> height;
constexpr Box(const length::m<>& l, const length::m<>& w, const length::m<>& h) : length{l}, width{w}, height{h} {}
struct contents {
density::kg_per_m3<> density = air_density;
} contents;
constexpr force::N<> filled_weight() const
{
const volume::m3<> volume = length * width * height;
const mass::kg<> mass = contents.density * volume;
return mass * acceleration::g<>;
}
constexpr length::m<> fill_level(const mass::kg<>& measured_mass) const
{
return height * (measured_mass * acceleration::g<>) / filled_weight();
}
constexpr volume::m3<> spare_capacity(const mass::kg<>& measured_mass) const
{
return (height - fill_level(measured_mass)) * width * length;
}
constexpr void set_contents_density(const density::kg_per_m3<>& density_in)
{
assert(density_in > air_density);
contents.density = density_in;
}
};
#include <iostream>
using namespace units::isq::si::literals;
int main()
{
auto box = Box{1000.0_q_mm, 500.0_q_mm, 200.0_q_mm};
box.set_contents_density(1000.0_q_kg_per_m3);
auto fill_time = 200.0_q_s; // time since starting fill
auto measured_mass = 20.0_q_kg; // measured mass at fill_time
std::cout << "mpusz/units box example ( using experimental alternative syntax for defining quantities) ...\n";
std::cout << "fill height at " << fill_time << " = " << box.fill_level(measured_mass) << " ("
<< (box.fill_level(measured_mass) / box.height) * 100 << "% full)\n";
std::cout << "spare_capacity at " << fill_time << " = " << box.spare_capacity(measured_mass) << '\n';
std::cout << "input flow rate after " << fill_time << " = " << measured_mass / fill_time << '\n';
std::cout << "float rise rate = " << box.fill_level(measured_mass) / fill_time << '\n';
auto fill_time_left = (box.height / box.fill_level(measured_mass) - 1) * fill_time;
std::cout << "box full E.T.A. at current flow rate = " << fill_time_left << '\n';
}
@@ -1,135 +0,0 @@
/*
Copyright (c) 2003-2019 Andy Little.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses./
*/
#include <iostream>
#include <units/format.h>
#include <units/quantity_io.h>
#include "./length.h"
#include "./volume.h"
#include "./time.h"
#include "./area.h"
#include "./units_str.h"
using namespace units::isq::si::literals;
using namespace units::isq::si::international;
using namespace units::experimental;
void simple_quantities()
{
using distance = length::m<>;
using q_time = q_time::s<>;
constexpr distance km = 1.0_q_km;
constexpr distance miles = 1.0_q_mi;
constexpr q_time sec = 1_q_s;
constexpr q_time min = 1_q_min;
constexpr q_time hr = 1_q_h;
std::cout << "A physical quantities library can choose the simple\n";
std::cout << "option to provide output using a single type for each base unit:\n\n";
std::cout << km << '\n';
std::cout << miles << '\n';
std::cout << sec << '\n';
std::cout << min << '\n';
std::cout << hr << "\n\n";
}
void quantities_with_typed_units()
{
constexpr length::km<> km = 1.0_q_km;
constexpr length::mi<> miles = 1.0_q_mi;
constexpr q_time::s<> sec = 1_q_s;
constexpr q_time::min<> min = 1_q_min;
constexpr q_time::h<> hr = 1_q_h;
std::cout << "A more flexible option is to provide separate types for each unit,\n\n";
std::cout << km << '\n';
std::cout << miles << '\n';
std::cout << sec << '\n';
std::cout << min << '\n';
std::cout << hr << "\n\n";
constexpr length::m<> meter = 1_q_m;
std::cout << "then a wide range of pre-defined units can be defined and converted,\n"
" for consistency and repeatability across applications:\n\n";
std::cout << meter << '\n';
std::cout << " = " << length::AU<>(meter) << '\n';
std::cout << " = " << length::angstrom<>(meter) << '\n';
std::cout << " = " << length::ch<>(meter) << '\n';
std::cout << " = " << length::fathom<>(meter) << '\n';
std::cout << " = " << length::fathom_us<>(meter) << '\n';
std::cout << " = " << length::ft<>(meter) << '\n';
std::cout << " = " << length::ft_us<>(meter) << '\n';
std::cout << " = " << length::in<>(meter) << '\n';
std::cout << " = " << length::ly<>(meter) << '\n';
std::cout << " = " << length::mi<>(meter) << '\n';
std::cout << " = " << length::mi_naut<>(meter) << '\n';
std::cout << " = " << length::pc<>(meter) << '\n';
std::cout << " = " << length::pica_comp<>(meter) << '\n';
std::cout << " = " << length::pica_prn<>(meter) << '\n';
std::cout << " = " << length::point_comp<>(meter) << '\n';
std::cout << " = " << length::point_prn<>(meter) << '\n';
std::cout << " = " << length::rd<>(meter) << '\n';
std::cout << " = " << length::yd<>(meter) << '\n';
}
void calcs_comparison()
{
std::cout << "\nA distinct unit for each type is efficient and accurate\n"
"when adding two values of the same very big\n"
"or very small type:\n\n";
length::fm<float> L1A = 2._q_fm;
length::fm<float> L2A = 3._q_fm;
length::fm<float> LrA = L1A + L2A;
fmt::print("{:%.30Q %q}\n + {:%.30Q %q}\n = {:%.30Q %q}\n\n",L1A,L2A,LrA);
std::cout << "The single unit method must convert large\n"
"or small values in other units to the base unit.\n"
"This is both inefficient and inaccurate\n\n";
length::m<float> L1B = L1A;
length::m<float> L2B = L2A;
length::m<float> LrB = L1B + L2B;
fmt::print("{:%.30Q %q}\n + {:%.30Q %q}\n = {:%.30Q %q}\n\n",L1B,L2B,LrB);
std::cout << "In multiplication and division:\n\n";
area::fm2<float> ArA = L1A * L2A;
fmt::print("{:%.30Q %q}\n * {:%.30Q %q}\n = {:%.30Q %q}\n\n",L1A,L2A,ArA);
std::cout << "similar problems arise\n\n";
area::m2<float> ArB = L1B * L2B;
fmt::print("{:%.30Q %q}\n * {:%.30Q %q}\n = {:%.30Q %q}\n\n",L1B,L2B,ArB);
}
int main()
{
std::cout << "This demo was originally posted on comp.lang.c++.moderated in 2006\n";
std::cout << "http://compgroups.net/comp.lang.c++.moderated/dimensional-analysis-units/51712\n";
std::cout << "Here converted to use mpusz/units library.\n\n";
simple_quantities();
quantities_with_typed_units();
calcs_comparison();
}
@@ -1,63 +0,0 @@
/*
Copyright (c) 2003-2020 Andy Little.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses./
*/
#include "./units_str.h"
#include "./length.h"
#include <units/quantity_io.h>
#include <iostream>
/*
get conversion factor from one dimensionally equivalent
quantity type to another
*/
namespace {
template<units::Quantity Target, units::Quantity Source>
requires units::equivalent<typename Source::dimension, typename Target::dimension>
inline constexpr std::common_type_t<typename Target::rep, typename Source::rep> conversion_factor(Target, Source)
{
// get quantities looking like inputs but with Q::rep that doesn't have narrowing conversion
typedef std::common_type_t<typename Target::rep, typename Source::rep> rep;
typedef units::quantity<typename Source::dimension, typename Source::unit, rep> source;
typedef units::quantity<typename Target::dimension, typename Target::unit, rep> target;
return target{source{1}}.number();
}
} // namespace
using namespace units::isq::si::literals;
using namespace units::experimental;
int main()
{
std::cout << "conversion factor in mpusz/units...\n\n";
constexpr length::m<> lengthA = 2.0_q_m;
constexpr length::mm<> lengthB = lengthA;
std::cout << "lengthA( " << lengthA << " ) and lengthB( " << lengthB << " )\n"
<< "represent the same length in different units.\n\n";
std::cout << "therefore ratio lengthA / lengthB == " << lengthA / lengthB << "\n\n";
std::cout << "conversion factor from lengthA::unit of "
<< units_str(lengthA).standard() << " to lengthB::unit of " << units_str(lengthB).standard() << " :\n\n"
<< "lengthB.number( " << lengthB.number() << " ) == lengthA.number( " << lengthA.number()
<< " ) * conversion_factor( " << conversion_factor(lengthB, lengthA) << " )\n";
}
-19
View File
@@ -1,19 +0,0 @@
#pragma once
#include <units/isq/si/density.h>
namespace units{
namespace experimental{
namespace density {
template<typename Rep = double>
using kg_per_m3 = units::isq::si::density<units::isq::si::kilogram_per_metre_cub, Rep>;
}
}} // units::experimental
-16
View File
@@ -1,16 +0,0 @@
#pragma once
#include <units/isq/si/force.h>
namespace units{
namespace experimental{
namespace force {
template<typename Rep = double>
using N = units::isq::si::force<units::isq::si::newton, Rep>;
}
}} // units::experimental
-88
View File
@@ -1,88 +0,0 @@
#pragma once
#include <units/isq/si/length.h>
#include <units/isq/si/imperial/length.h>
#include <units/isq/si/international/length.h>
#include <units/isq/si/typographic/length.h>
#include <units/isq/si/us/length.h>
#include <units/isq/si/iau/length.h>
namespace units{
namespace experimental{
namespace length {
template<typename Rep = double>
using m = units::isq::si::length<units::isq::si::metre, Rep>;
template<typename Rep = double>
using mm = units::isq::si::length<units::isq::si::millimetre, Rep>;
template<typename Rep = double>
using fm = units::isq::si::length<units::isq::si::femtometre, Rep>;
template<typename Rep = double>
using km = units::isq::si::length<units::isq::si::kilometre, Rep>;
template<typename Rep = double>
using AU = units::isq::si::length<units::isq::si::astronomical_unit, Rep>;
template<typename Rep = double>
using in = units::isq::si::length<units::isq::si::international::inch, Rep>;
template<typename Rep = double>
using angstrom = units::isq::si::length<units::isq::si::iau::angstrom, Rep>;
template<typename Rep = double>
using ch = units::isq::si::length<units::isq::si::imperial::chain, Rep>;
template<typename Rep = double>
using fathom = units::isq::si::length<units::isq::si::international::fathom, Rep>;
template<typename Rep = double>
using fathom_us = units::isq::si::length<units::isq::si::us::fathom, Rep>;
template<typename Rep = double>
using ft = units::isq::si::length<units::isq::si::international::foot, Rep>;
template<typename Rep = double>
using ft_us = units::isq::si::length<units::isq::si::us::foot, Rep>;
template<typename Rep = double>
using ly = units::isq::si::length<units::isq::si::iau::light_year, Rep>;
template<typename Rep = double>
using mi = units::isq::si::length<units::isq::si::international::mile, Rep>;
template<typename Rep = double>
using mi_naut = units::isq::si::length<units::isq::si::international::nautical_mile, Rep>;
template<typename Rep = double>
using pc = units::isq::si::length<units::isq::si::iau::parsec, Rep>;
template<typename Rep = double>
using pica_comp = units::isq::si::length<units::isq::si::typographic::pica_comp, Rep>;
template<typename Rep = double>
using pica_prn = units::isq::si::length<units::isq::si::typographic::pica_prn, Rep>;
template<typename Rep = double>
using point_comp = units::isq::si::length<units::isq::si::typographic::point_comp, Rep>;
template<typename Rep = double>
using point_prn = units::isq::si::length<units::isq::si::typographic::point_prn, Rep>;
template<typename Rep = double>
using rd = units::isq::si::length<units::isq::si::imperial::rod, Rep>;
template<typename Rep = double>
using yd = units::isq::si::length<units::isq::si::international::yard, Rep>;
} // namespace length
}} // units::experimental
-19
View File
@@ -1,19 +0,0 @@
#pragma once
#include <units/isq/si/mass.h>
namespace units{
namespace experimental{
namespace mass {
template<typename Rep = double>
using kg = units::isq::si::mass<units::isq::si::kilogram, Rep>;
}
}} // units::experimental
-21
View File
@@ -1,21 +0,0 @@
#pragma once
#include <units/isq/si/time.h>
// named qtime due to conflict with time_t time(time_t*)
namespace q_time {
template<typename Rep = double>
using s = units::isq::si::time<units::isq::si::second, Rep>;
template<typename Rep = double>
using ms = units::isq::si::time<units::isq::si::millisecond, Rep>;
template<typename Rep = double>
using min = units::isq::si::time<units::isq::si::minute, Rep>;
template<typename Rep = double>
using h = units::isq::si::time<units::isq::si::hour, Rep>;
} // namespace time
-36
View File
@@ -1,36 +0,0 @@
#include <units/quantity_io.h>
#include <iostream>
#include "./timer.h"
/*
simple timer, useful for perf timing etc
*/
using namespace units::experimental;
using namespace units::isq::si::literals;
int main()
{
std::cout << "Simple timer using mpusz/units ...\n";
auto const period = 0.5_q_s;
auto const duration = 10 * period;
timer t;
auto const start_time = t();
std::cout << "Started at " << start_time <<'\n';
auto prev = start_time;
for (auto now = t(); (now - start_time) < duration; now = t() ) {
if ( (now - prev ) >= period ){
prev = now;
std::cout << "tick (" << now << ")\n";;
}
}
t.stop();
std::cout << "finished at " << t() << '\n';
}
-64
View File
@@ -1,64 +0,0 @@
#pragma once
/*
Copyright (c) 2003-2020 Andy Little.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses./
*/
#include "./time.h"
#include <ctime>
namespace units{ namespace experimental{
class timer{
public:
timer(): running(true)
{
start_time = std::clock();
}
void restart()
{
running = true;
start_time = std::clock();
}
void stop()
{
if (running){
stop_time = std::clock();
running = false;
}
}
q_time::ms<> operator ()()const
{
std::clock_t const wanted = running ? std::clock() : stop_time;
static constexpr auto divider = 1000.0 / CLOCKS_PER_SEC;
return q_time::ms<>(
static_cast<double>(wanted - start_time)
) * divider;
}
bool is_running() const {return running;}
bool is_stopped() const {return !running;}
private:
bool running;
std::clock_t start_time,stop_time;
};
} }//units::experimental
@@ -1,12 +0,0 @@
#pragma once
#include <units/bits/unit_text.h>
#include <units/isq/si/prefixes.h>
#include <units/quantity.h>
// get at the units text of the quantity, without its numeric value
inline auto constexpr units_str(const units::Quantity auto& q)
{
typedef std::remove_cvref_t<decltype(q)> qtype;
return units::detail::unit_text<typename qtype::dimension, typename qtype::unit>();
}
-31
View File
@@ -1,31 +0,0 @@
#pragma once
#include <units/isq/si/voltage.h>
namespace units{
namespace experimental{
namespace voltage {
template<typename Rep = double>
using V = units::isq::si::voltage<units::isq::si::volt, Rep>;
template<typename Rep = double>
using mV = units::isq::si::voltage<units::isq::si::millivolt, Rep>;
template<typename Rep = double>
using uV = units::isq::si::voltage<units::isq::si::microvolt, Rep>;
template<typename Rep = double>
using nV = units::isq::si::voltage<units::isq::si::nanovolt, Rep>;
template<typename Rep = double>
using pV = units::isq::si::voltage<units::isq::si::picovolt, Rep>;
} // namespace voltage
}} // units::experimental
-18
View File
@@ -1,18 +0,0 @@
#pragma once
#include <units/isq/si/volume.h>
namespace units{
namespace experimental{
namespace volume {
template<typename Rep = double>
using m3 = units::isq::si::volume<units::isq::si::cubic_metre, Rep>;
}
}} // units::experimental
+17 -13
View File
@@ -20,8 +20,9 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#define UNITS_REFERENCES
#define UNITS_ALIASES
#define UNITS_LITERALS
#define UNITS_REFERENCES
#include <units/format.h>
#include <units/isq/si/international/length.h>
@@ -43,23 +44,26 @@ int main()
{
using namespace units::isq::si::literals;
using namespace units::isq::si::references;
using namespace units::aliases::isq::si::international;
constexpr Speed auto v1 = 110 * (km / h);
constexpr Speed auto v2 = avg_speed(220_q_km, 2_q_h);
constexpr Speed auto v3 = avg_speed(si::length<si::international::mile>(140), si::time<si::hour>(2));
constexpr Speed auto v2 = mi_per_h<>(70.);
constexpr Speed auto v3 = avg_speed(220_q_km, 2_q_h);
constexpr Speed auto v4 = avg_speed(si::length<si::international::mile>(140), si::time<si::hour>(2));
#if UNITS_DOWNCAST_MODE == 0
constexpr Speed auto v4 = quantity_cast<si::speed<si::metre_per_second>>(v2);
constexpr Speed auto v5 = quantity_cast<si::dim_speed, si::metre_per_second>(v3);
constexpr Speed auto v5 = quantity_cast<si::speed<si::metre_per_second>>(v3);
constexpr Speed auto v6 = quantity_cast<si::dim_speed, si::metre_per_second>(v4);
#else
constexpr Speed auto v4 = quantity_cast<si::speed<si::metre_per_second>>(v2);
constexpr Speed auto v5 = quantity_cast<si::metre_per_second>(v3);
constexpr Speed auto v5 = quantity_cast<si::speed<si::metre_per_second>>(v3);
constexpr Speed auto v6 = quantity_cast<si::metre_per_second>(v4);
#endif
constexpr Speed auto v6 = quantity_cast<int>(v5);
constexpr Speed auto v7 = quantity_cast<int>(v6);
std::cout << v1 << '\n'; // 110 km/h
std::cout << fmt::format("{}", v2) << '\n'; // 110 km/h
std::cout << fmt::format("{:*^14}", v3) << '\n'; // ***70 mi/h****
std::cout << fmt::format("{:%Q in %q}", v4) << '\n'; // 30.5556 in m/s
std::cout << fmt::format("{0:%Q} in {0:%q}", v5) << '\n'; // 31.2928 in m/s
std::cout << fmt::format("{:%Q}", v6) << '\n'; // 31
std::cout << v2 << '\n'; // 70 mi/h
std::cout << fmt::format("{}", v3) << '\n'; // 110 km/h
std::cout << fmt::format("{:*^14}", v4) << '\n'; // ***70 mi/h****
std::cout << fmt::format("{:%Q in %q}", v5) << '\n'; // 30.5556 in m/s
std::cout << fmt::format("{0:%Q} in {0:%q}", v6) << '\n'; // 31.2928 in m/s
std::cout << fmt::format("{:%Q}", v7) << '\n'; // 31
}
+8 -8
View File
@@ -111,28 +111,28 @@ void calcs_comparison()
"when adding two values of the same very big\n"
"or very small type:\n\n";
length<femtometre, float> L1A = 2._q_fm;
length<femtometre, float> L2A = 3._q_fm;
length<femtometre, float> LrA = L1A + L2A;
const length<femtometre, float> L1A = 2._q_fm;
const length<femtometre, float> L2A = 3._q_fm;
const length<femtometre, float> LrA = L1A + L2A;
fmt::print("{:%.30Q %q}\n + {:%.30Q %q}\n = {:%.30Q %q}\n\n", L1A, L2A, LrA);
std::cout << "The single unit method must convert large\n"
"or small values in other units to the base unit.\n"
"This is both inefficient and inaccurate\n\n";
length<metre, float> L1B = L1A;
length<metre, float> L2B = L2A;
length<metre, float> LrB = L1B + L2B;
const length<metre, float> L1B = L1A;
const length<metre, float> L2B = L2A;
const length<metre, float> LrB = L1B + L2B;
fmt::print("{:%.30Q %q}\n + {:%.30Q %q}\n = {:%.30Q %q}\n\n", L1B, L2B, LrB);
std::cout << "In multiplication and division:\n\n";
area<square_femtometre, float> ArA = L1A * L2A;
const area<square_femtometre, float> ArA = L1A * L2A;
fmt::print("{:%.30Q %q}\n * {:%.30Q %q}\n = {:%.30Q %q}\n\n", L1A, L2A, ArA);
std::cout << "similar problems arise\n\n";
area<square_metre, float> ArB = L1B * L2B;
const area<square_metre, float> ArB = L1B * L2B;
fmt::print("{:%.30Q %q}\n * {:%.30Q %q}\n = {:%.30Q %q}\n\n", L1B, L2B, ArB);
}
+6 -5
View File
@@ -43,7 +43,6 @@ Energy auto total_energy(Momentum auto p, Mass auto m, Speed auto c)
void si_example()
{
using namespace units::isq::si;
using GeV = gigaelectronvolt;
constexpr Speed auto c = si2019::speed_of_light<>;
@@ -68,17 +67,19 @@ void si_example()
<< "E = " << E_si << "\n";
std::cout << "\n[converted from SI units back to GeV]\n"
<< "E = " << quantity_cast<GeV>(E_si) << "\n";
<< "E = " << quantity_cast<gigaelectronvolt>(E_si) << "\n";
}
void natural_example()
{
using namespace units::isq::natural;
using GeV = gigaelectronvolt;
// TODO Typical UDLs will not work here as the same units are reused by many quantities.
// Should we define some strange ones (i.e. _q_mass_GeV)?
constexpr Speed auto c = speed_of_light<>;
const momentum<GeV> p(4);
const mass<GeV> m(3);
const momentum<gigaelectronvolt> p(4);
const mass<gigaelectronvolt> m(3);
const Energy auto E = total_energy(p, m, c);
std::cout << "\n*** Natural units (c = " << c << ") ***\n"
+29 -26
View File
@@ -32,49 +32,52 @@ namespace {
void simple_quantities()
{
using namespace units::isq;
using namespace units::isq::si;
using namespace units::isq::si::references;
using namespace units::isq::si::international::references;
using distance = si::length<si::metre>;
using duration = si::time<si::second>;
constexpr distance kilometers = 1.0 * km;
constexpr distance km = 1.0 * references::km;
constexpr distance miles = 1.0 * mi;
constexpr duration seconds = 1 * s;
constexpr duration minutes = 1 * min;
constexpr duration hours = 1 * h;
constexpr duration sec = 1 * s;
constexpr duration min = 1 * references::min;
constexpr duration hr = 1 * h;
std::cout << "A physical quantities library can choose the simple\n";
std::cout << "option to provide output using a single type for each base unit:\n\n";
std::cout << kilometers << '\n';
std::cout << km << '\n';
std::cout << miles << '\n';
std::cout << seconds << '\n';
std::cout << minutes << '\n';
std::cout << hours << "\n\n";
std::cout << sec << '\n';
std::cout << min << '\n';
std::cout << hr << "\n\n";
}
void quantities_with_typed_units()
{
using namespace units::isq;
using namespace units::isq::si;
using namespace units::isq::si::references;
using namespace units::isq::si::international;
using namespace units::isq::si::international::references;
constexpr auto kilometers = 1.0 * km;
constexpr auto miles = 1.0 * mi;
constexpr length<kilometre> km = 1.0 * si::references::km;
constexpr length<mile> miles = 1.0 * mi;
std::cout.precision(6);
constexpr auto seconds = 1 * s;
constexpr auto minutes = 1 * min;
constexpr auto hours = 1 * h;
constexpr si::time<second> sec = 1 * s;
constexpr si::time<minute> min = 1 * si::references::min;
constexpr si::time<hour> hr = 1 * h;
std::cout << "A more flexible option is to provide separate types for each unit,\n\n";
std::cout << kilometers << '\n';
std::cout << km << '\n';
std::cout << miles << '\n';
std::cout << seconds << '\n';
std::cout << minutes << '\n';
std::cout << hours << "\n\n";
std::cout << sec << '\n';
std::cout << min << '\n';
std::cout << hr << "\n\n";
constexpr auto meter = 1 * m;
std::cout << "then a wide range of pre-defined units can be defined and converted,\n"
@@ -104,35 +107,35 @@ void quantities_with_typed_units()
void calcs_comparison()
{
using namespace units::isq;
using namespace units::isq::si;
using namespace units::isq::si::references;
std::cout << "\nA distinct unit for each type is efficient and accurate\n"
"when adding two values of the same very big\n"
"or very small type:\n\n";
const auto L1A = 2.f * fm;
const auto L2A = 3.f * fm;
const Length auto LrA = L1A + L2A;
const length<femtometre, float> L1A = 2.f * fm;
const length<femtometre, float> L2A = 3.f * fm;
const length<femtometre, float> LrA = L1A + L2A;
fmt::print("{:%.30Q %q}\n + {:%.30Q %q}\n = {:%.30Q %q}\n\n", L1A, L2A, LrA);
std::cout << "The single unit method must convert large\n"
"or small values in other units to the base unit.\n"
"This is both inefficient and inaccurate\n\n";
const auto L1B = quantity_cast<si::metre>(L1A);
const auto L2B = quantity_cast<si::metre>(L2A);
const Length auto LrB = L1B + L2B;
const length<metre, float> L1B = L1A;
const length<metre, float> L2B = L2A;
const length<metre, float> LrB = L1B + L2B;
fmt::print("{:%.30Q %q}\n + {:%.30Q %q}\n = {:%.30Q %q}\n\n", L1B, L2B, LrB);
std::cout << "In multiplication and division:\n\n";
const Area auto ArA = L1A * L2A;
const area<square_femtometre, float> ArA = L1A * L2A;
fmt::print("{:%.30Q %q}\n * {:%.30Q %q}\n = {:%.30Q %q}\n\n", L1A, L2A, ArA);
std::cout << "similar problems arise\n\n";
const Area auto ArB = L1B * L2B;
const area<square_metre, float> ArB = L1B * L2B;
fmt::print("{:%.30Q %q}\n * {:%.30Q %q}\n = {:%.30Q %q}\n\n", L1B, L2B, ArB);
}
+3 -2
View File
@@ -74,10 +74,11 @@ void si_example()
void natural_example()
{
using namespace units::isq::natural;
using namespace units::isq::natural::references;
constexpr Speed auto c = speed_of_light<>;
const momentum<gigaelectronvolt> p(4);
const mass<gigaelectronvolt> m(3);
const auto p = 4. * momentum_references::GeV;
const auto m = 3. * mass_references::GeV;
const Energy auto E = total_energy(p, m, c);
std::cout << "\n*** Natural units (c = " << c << ") ***\n"