Skip to content

Commit

Permalink
Refactored settings (#61)
Browse files Browse the repository at this point in the history
* removed settings.py
* calculator specific global constants moved to trajectory_calc.py/.pyx
* config loader moved to __init__.py
* added pybc.calculator section to config loader
* added functions to reset defaults
* py_ballisticcalc_exts/setup.py fix
  • Loading branch information
o-murphy authored Apr 6, 2024
1 parent 05f1082 commit b911c57
Show file tree
Hide file tree
Showing 22 changed files with 392 additions and 189 deletions.
54 changes: 40 additions & 14 deletions .github/workflows/python-publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -70,35 +70,61 @@ jobs:
deploy:
needs: build
runs-on: ${{ matrix.os }}

strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
python-version: ["3.9", "3.10", "3.11", "3.12"]

runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3

- name: Set up Python
uses: actions/setup-python@v3
with:
python-version: ${{ matrix.python-version }}
python-version: "3.9"

- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install build twine
- name: Build package
run: python -m build

- name: Build extensions package
run: |
cd py_ballisticcalc_exts
python -m build --outdir ../dist
cd ..
- name: Publish package to PyPI
run: |
python -m twine upload dist/* --skip-existing --verbose --non-interactive
env:
TWINE_USERNAME: __token__
TWINE_PASSWORD: ${{ secrets.PYPI_API_TOKEN }}

deploy-exts:
needs: [build, deploy]
runs-on: ${{ matrix.os }}

strategy:
matrix:
os: [ ubuntu-latest, windows-latest, macos-latest ]
python-version: [ "3.9", "3.10", "3.11", "3.12" ]

steps:
- uses: actions/checkout@v4

- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}

- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install build twine
- name: Build extensions package
run: |
cd py_ballisticcalc_exts
python -m build --outdir ../dist
cd ..
- name: Publish package to PyPI
run: |
python -m twine upload dist/* --skip-existing --verbose --non-interactive
env:
TWINE_USERNAME: __token__
TWINE_PASSWORD: ${{ secrets.PYPI_API_TOKEN }}
11 changes: 8 additions & 3 deletions .pybc.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Config template for py_ballisticcalc

title = "standard py_ballisticcalc config template"
version = "2.0.0b3"
version = "2.0.0b4"

[pybc.preferred_units]
angular = 'Degree'
Expand All @@ -21,5 +21,10 @@ target_height = 'Inch'
twist = 'Inch'

[pybc.calculator]
max_calc_step_size = [0.5, "Foot"]
use_powder_sensitivity = true
max_calc_step_size = { value = 0.5, units = "Foot" }
use_powder_sensitivity = false

# # or use:
# [pybc.calculator.max_calc_step_size]
# value = 0.5
# units = "Foot"
13 changes: 7 additions & 6 deletions Example.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
"from py_ballisticcalc import TableG7, TableG1\n",
"from py_ballisticcalc import Ammo, Atmo, Wind\n",
"from py_ballisticcalc import Weapon, Shot, Calculator\n",
"from py_ballisticcalc import Settings, PreferredUnits\n",
"from py_ballisticcalc import PreferredUnits, set_global_use_powder_sensitivity\n",
"from py_ballisticcalc.drag_model import *\n",
"from py_ballisticcalc.unit import *\n",
"\n",
Expand Down Expand Up @@ -268,7 +268,8 @@
"PreferredUnits.velocity = Unit.MPS\n",
"PreferredUnits.drop = Unit.Meter\n",
"PreferredUnits.sight_height = Unit.Centimeter\n",
"Settings.USE_POWDER_SENSITIVITY = True\n",
"\n",
"set_global_use_powder_sensitivity(True)\n",
"\n",
"# Standard .50BMG\n",
"dm = DragModel(0.62, TableG1, 661, 0.51, 2.3)\n",
Expand Down Expand Up @@ -394,14 +395,14 @@
"outputs": [],
"source": [
"# Single G1 BC\n",
"dm1 = DragModelMultiBC([BCpoint(.462, Mach=1)], TableG1, weight=168, diameter=.308)\n",
"dm1 = DragModelMultiBC([BCPoint(.462, Mach=1)], TableG1, weight=168, diameter=.308)\n",
"# Sierra's G1 BC: 0.462 above 2600 fps, 0.447 above 2100 fps, 0.424 above 1600 fps, and .405 below that.\n",
"dm2 = DragModelMultiBC([BCpoint(.462, V=Velocity.FPS(2600)), BCpoint(.462-(.462-.447)/2, V=Velocity.FPS(2350)), BCpoint(.424-(.424-.405)/2, V=Velocity.FPS(1850)), BCpoint(.405, V=Velocity.FPS(1600))],\n",
"dm2 = DragModelMultiBC([BCPoint(.462, V=Velocity.FPS(2600)), BCPoint(.462-(.462-.447)/2, V=Velocity.FPS(2350)), BCPoint(.424-(.424-.405)/2, V=Velocity.FPS(1850)), BCPoint(.405, V=Velocity.FPS(1600))],\n",
" TableG1, weight=168, diameter=.308)\n",
"# Single G7 BC\n",
"dm3 = DragModelMultiBC([BCpoint(.224, Mach=1)], TableG7, weight=168, diameter=.308)\n",
"dm3 = DragModelMultiBC([BCPoint(.224, Mach=1)], TableG7, weight=168, diameter=.308)\n",
"# Litz's G7 multi-BC:\n",
"dm4 = DragModelMultiBC([BCpoint(.211, V=Velocity.FPS(1500)), BCpoint(.214, V=Velocity.FPS(2000)), BCpoint(.222, V=Velocity.FPS(2500)), BCpoint(.226, V=Velocity.FPS(3000))],\n",
"dm4 = DragModelMultiBC([BCPoint(.211, V=Velocity.FPS(1500)), BCPoint(.214, V=Velocity.FPS(2000)), BCPoint(.222, V=Velocity.FPS(2500)), BCPoint(.226, V=Velocity.FPS(3000))],\n",
" TableG7, weight=168, diameter=.308)\n",
"ax = pandas.DataFrame(dm1.drag_table).plot(x='Mach', y='CD', ylabel='Drag Coefficient', label='G1 Single BC (Baseline)')\n",
"pandas.DataFrame(dm2.drag_table).plot(x='Mach', y='CD', label='G1 Multiple BC (Sierra)', linestyle='dashed', linewidth=2, ax=ax)\n",
Expand Down
6 changes: 3 additions & 3 deletions assets/.pybc-imperial.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Config template for py_ballisticcalc

title = "py_ballisticcalc config"
version = "2.0.0b3"
version = "2.0.0b4"

[pybc.preferred_units]
angular = 'Degree'
Expand All @@ -21,5 +21,5 @@ target_height = 'Inch'
twist = 'Inch'

[pybc.calculator]
max_calc_step_size = [0.5, "Foot"]
use_powder_sensitivity = true
max_calc_step_size = { value = 0.5, units = "Foot" }
use_powder_sensitivity = false
6 changes: 3 additions & 3 deletions assets/.pybc-metrics.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Config template for py_ballisticcalc

title = "py_ballisticcalc config"
version = "2.0.0b3"
version = "2.0.0b4"

[pybc.preferred_units]
angular = 'Degree'
Expand All @@ -21,5 +21,5 @@ target_height = 'Meter'
twist = 'Centimeter'

[pybc.calculator]
max_calc_step_size = [0.5, "Foot"]
use_powder_sensitivity = true
max_calc_step_size = { value = 0.5, units = "Foot" }
use_powder_sensitivity = false
9 changes: 6 additions & 3 deletions assets/.pybc-mixed.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Config template for py_ballisticcalc

title = "py_ballisticcalc config"
version = "2.0.0b3"
version = "2.0.0b4"

[pybc.preferred_units]
angular = 'Degree'
Expand All @@ -21,5 +21,8 @@ target_height = 'Meter'
twist = 'Inch'

[pybc.calculator]
max_calc_step_size = [0.5, "Foot"]
use_powder_sensitivity = true
use_powder_sensitivity = false

[pybc.calculator.max_calc_step_size]
value = 0.5
units = "Foot"
2 changes: 1 addition & 1 deletion examples/canik_50bmg.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from py_ballisticcalc import DragModel, TableG1
from py_ballisticcalc import Ammo
from py_ballisticcalc import Weapon, Shot, Calculator
from py_ballisticcalc import Settings as Set


PreferredUnits.distance = Unit.METER
PreferredUnits.velocity = Unit.MPS
Expand Down
4 changes: 2 additions & 2 deletions examples/ukrop_338lm_300gr_smk.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Example of library usage"""

from py_ballisticcalc import *
from py_ballisticcalc import Settings as Set


# set global library settings
PreferredUnits.velocity = Velocity.MPS
Expand All @@ -11,7 +11,7 @@
PreferredUnits.sight_height = Distance.Centimeter
PreferredUnits.drop = Distance.Centimeter

Set.USE_POWDER_SENSITIVITY = True # enable muzzle velocity correction my powder temperature
set_global_use_powder_sensitivity(True) # enable muzzle velocity correction my powder temperature

# define params with default prefer_units
weight, diameter = 300, 0.338
Expand Down
134 changes: 133 additions & 1 deletion py_ballisticcalc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,144 @@

__credits__ = ["o-murphy", "dbookstaber"]

import os

from .backend import *
from .drag_tables import *
from .drag_model import *
from .settings import *
from .interface import *
from .logger import logger
from .trajectory_data import *
from .conditions import *
from .munition import *
from .unit import *

try:
import tomllib
except ImportError:
import tomli as tomllib


def _load_config(filepath=None):

def find_pybc_toml(start_dir=os.getcwd()):
"""
Search for the pyproject.toml file starting from the specified directory.
:param start_dir: (str) The directory to start searching from. Default is the current working directory.
:return: str: The absolute path to the pyproject.toml file if found, otherwise None.
"""
current_dir = os.path.abspath(start_dir)
while True:
# Check if pybc.toml or .pybc.toml exists in the current directory
pybc_paths = [
os.path.join(current_dir, '.pybc.toml'),
os.path.join(current_dir, 'pybc.toml'),
]
for pypc_path in pybc_paths:
if os.path.exists(pypc_path):
return os.path.abspath(pypc_path)

# Move to the parent directory
parent_dir = os.path.dirname(current_dir)

# If we have reached the root directory, stop searching
if parent_dir == current_dir:
return None

current_dir = parent_dir

if filepath is None:
if (filepath := find_pybc_toml()) is None:
find_pybc_toml(os.path.dirname(__file__))

logger.info(f"Found {os.path.basename(filepath)} at {os.path.dirname(filepath)}")

with open(filepath, "rb") as fp:
_config = tomllib.load(fp)

if _pybc := _config.get('pybc'):
if preferred_units := _pybc.get('preferred_units'):
PreferredUnits.set(**preferred_units)
else:
logger.warning("Config has not `pybc.preferred_units` section")

if calculator := _pybc.get('calculator'):
if max_calc_step_size := calculator.get('max_calc_step_size'):
try:
_val = max_calc_step_size.get("value")
_units = Unit[max_calc_step_size.get("units")]
set_global_max_calc_step_size(_units(_val))
except (KeyError, TypeError, ValueError):
logger.warning("Wrong max_calc_step_size units or value")

if use_powder_sensitivity := calculator.get('use_powder_sensitivity'):
set_global_use_powder_sensitivity(use_powder_sensitivity)
else:
logger.warning("Config has not `pybc.calculator` section")
else:
logger.warning("Config has not `pybc` section")


def _basic_config(filename=None,
max_calc_step_size: [float, Distance] = None,
use_powder_sensitivity: bool = False,
preferred_units: dict[str, Unit] = None):

"""
Method to load preferred units from file or Mapping
"""
if filename and (preferred_units or max_calc_step_size or use_powder_sensitivity):
raise ValueError("Can't use preferred_units and config file at same time")
if not filename and (preferred_units or max_calc_step_size or use_powder_sensitivity):
if preferred_units:
PreferredUnits.set(**preferred_units)
if max_calc_step_size:
set_global_max_calc_step_size(max_calc_step_size)
if use_powder_sensitivity:
set_global_use_powder_sensitivity(use_powder_sensitivity)
else:
# trying to load definitions from pybc.toml
_load_config(filename)


basicConfig = _basic_config

__all__ = [
'Calculator',
'basicConfig',
'logger',
'TrajectoryCalc',
'get_global_max_calc_step_size',
'get_global_use_powder_sensitivity',
'set_global_max_calc_step_size',
'set_global_use_powder_sensitivity',
'reset_globals',
'DragModel',
'DragDataPoint',
'BCPoint',
'DragModelMultiBC',
'TrajectoryData',
'HitResult',
'TrajFlag',
'Atmo',
'Wind',
'Shot',
'Weapon',
'Ammo',
'Unit',
'AbstractUnit',
'AbstractUnitType',
'UnitProps',
'UnitPropsDict',
'Distance',
'Velocity',
'Angular',
'Temperature',
'Pressure',
'Energy',
'Weight',
'Dimension',
'PreferredUnits'
]

__all__ += ["TableG%s" % n for n in (1, 7, 2, 5, 6, 8, 'I', 'S')]
Loading

0 comments on commit b911c57

Please sign in to comment.