pax_global_header 0000666 0000000 0000000 00000000064 15005301746 0014513 g ustar 00root root 0000000 0000000 52 comment=e09044f5839aa7b4a612d697453dca165ce7e2d6
openmotor-0.6.0/ 0000775 0000000 0000000 00000000000 15005301746 0013540 5 ustar 00root root 0000000 0000000 openmotor-0.6.0/.github/ 0000775 0000000 0000000 00000000000 15005301746 0015100 5 ustar 00root root 0000000 0000000 openmotor-0.6.0/.github/workflows/ 0000775 0000000 0000000 00000000000 15005301746 0017135 5 ustar 00root root 0000000 0000000 openmotor-0.6.0/.github/workflows/tests.yml 0000664 0000000 0000000 00000001771 15005301746 0021030 0 ustar 00root root 0000000 0000000 name: Unit Tests
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ['3.8', '3.9', '3.10']
steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install flake8 pytest
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
- name: Lint with flake8
run: |
# stop the build if there are Python syntax errors or undefined names
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
# exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
- name: Run unit tests
run: |
PYTHONPATH=. python test/unit.py
openmotor-0.6.0/.gitignore 0000664 0000000 0000000 00000002603 15005301746 0015531 0 ustar 00root root 0000000 0000000 # Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# openMotor user files
preferences.yaml
propellants.yaml
# autogenerated UI files
*_ui.py openmotor-0.6.0/.pylintrc 0000664 0000000 0000000 00000042110 15005301746 0015403 0 ustar 00root root 0000000 0000000 [MASTER]
# A comma-separated list of package or module names from where C extensions may
# be loaded. Extensions are loading into the active Python interpreter and may
# run arbitrary code.
extension-pkg-whitelist=PyQt5
# Add files or directories to the blacklist. They should be base names, not
# paths.
ignore=CVS
# Add files or directories matching the regex patterns to the blacklist. The
# regex matches against base names, not paths.
ignore-patterns=
# Python code to execute, usually for sys.path manipulation such as
# pygtk.require().
#init-hook=
# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
# number of processors available to use.
jobs=1
# Control the amount of potential inferred values when inferring a single
# object. This can help the performance when dealing with large functions or
# complex, nested conditions.
limit-inference-results=100
# List of plugins (as comma separated values of python modules names) to load,
# usually to register additional checkers.
load-plugins=
# Pickle collected data for later comparisons.
persistent=yes
# Specify a configuration file.
#rcfile=
# When enabled, pylint would attempt to guess common misconfiguration and emit
# user-friendly hints instead of false-positive error messages.
suggestion-mode=yes
# Allow loading of arbitrary C extensions. Extensions are imported into the
# active Python interpreter and may run arbitrary code.
unsafe-load-any-extension=no
[MESSAGES CONTROL]
# Only show warnings with the listed confidence levels. Leave empty to show
# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED.
confidence=
# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifiers separated by comma (,) or put this
# option multiple times (only on the command line, not in the configuration
# file where it should appear only once). You can also use "--disable=all" to
# disable everything first and then reenable specific checks. For example, if
# you want to run only the similarities checker, you can use "--disable=all
# --enable=similarities". If you want to run only the classes checker, but have
# no Warning level messages displayed, use "--disable=all --enable=classes
# --disable=W".
disable=print-statement,
parameter-unpacking,
unpacking-in-except,
old-raise-syntax,
backtick,
long-suffix,
old-ne-operator,
old-octal-literal,
import-star-module-level,
non-ascii-bytes-literal,
raw-checker-failed,
bad-inline-option,
locally-disabled,
file-ignored,
suppressed-message,
useless-suppression,
deprecated-pragma,
use-symbolic-message-instead,
apply-builtin,
basestring-builtin,
buffer-builtin,
cmp-builtin,
coerce-builtin,
execfile-builtin,
file-builtin,
long-builtin,
raw_input-builtin,
reduce-builtin,
standarderror-builtin,
unicode-builtin,
xrange-builtin,
coerce-method,
delslice-method,
getslice-method,
setslice-method,
no-absolute-import,
old-division,
dict-iter-method,
dict-view-method,
next-method-called,
metaclass-assignment,
indexing-exception,
raising-string,
reload-builtin,
oct-method,
hex-method,
nonzero-method,
cmp-method,
input-builtin,
round-builtin,
intern-builtin,
unichr-builtin,
map-builtin-not-iterating,
zip-builtin-not-iterating,
range-builtin-not-iterating,
filter-builtin-not-iterating,
using-cmp-argument,
eq-without-hash,
div-method,
idiv-method,
rdiv-method,
exception-message-attribute,
invalid-str-codec,
sys-max-int,
bad-python3-import,
deprecated-string-function,
deprecated-str-translate-call,
deprecated-itertools-function,
deprecated-types-field,
next-method-defined,
dict-items-not-iterating,
dict-keys-not-iterating,
dict-values-not-iterating,
deprecated-operator-function,
deprecated-urllib-function,
xreadlines-attribute,
deprecated-sys-function,
exception-escape,
comprehension-escape
# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once). See also the "--disable" option for examples.
enable=c-extension-no-member
[REPORTS]
# Python expression which should return a note less than 10 (10 is the highest
# note). You have access to the variables errors warning, statement which
# respectively contain the number of errors / warnings messages and the total
# number of statements analyzed. This is used by the global evaluation report
# (RP0004).
evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
# Template used to display messages. This is a python new-style format string
# used to format the message information. See doc for all details.
#msg-template=
# Set the output format. Available formats are text, parseable, colorized, json
# and msvs (visual studio). You can also give a reporter class, e.g.
# mypackage.mymodule.MyReporterClass.
output-format=text
# Tells whether to display a full report or only the messages.
reports=no
# Activate the evaluation score.
score=yes
[REFACTORING]
# Maximum number of nested blocks for function / method body
max-nested-blocks=5
# Complete name of functions that never returns. When checking for
# inconsistent-return-statements if a never returning function is called then
# it will be considered as an explicit return statement and no message will be
# printed.
never-returning-functions=sys.exit
[SPELLING]
# Limits count of emitted suggestions for spelling mistakes.
max-spelling-suggestions=4
# Spelling dictionary name. Available dictionaries: none. To make it working
# install python-enchant package..
spelling-dict=
# List of comma separated words that should not be checked.
spelling-ignore-words=
# A path to a file that contains private dictionary; one word per line.
spelling-private-dict-file=
# Tells whether to store unknown words to indicated private dictionary in
# --spelling-private-dict-file option instead of raising a message.
spelling-store-unknown-words=no
[BASIC]
# Naming style matching correct argument names.
argument-naming-style=camelCase
# Regular expression matching correct argument names. Overrides argument-
# naming-style.
#argument-rgx=
# Naming style matching correct attribute names.
attr-naming-style=camelCase
# Regular expression matching correct attribute names. Overrides attr-naming-
# style.
#attr-rgx=
# Bad variable names which should always be refused, separated by a comma.
bad-names=foo,
bar,
baz,
toto,
tutu,
tata
# Naming style matching correct class attribute names.
class-attribute-naming-style=any
# Regular expression matching correct class attribute names. Overrides class-
# attribute-naming-style.
#class-attribute-rgx=
# Naming style matching correct class names.
class-naming-style=PascalCase
# Regular expression matching correct class names. Overrides class-naming-
# style.
#class-rgx=
# Naming style matching correct constant names.
const-naming-style=UPPER_CASE
# Regular expression matching correct constant names. Overrides const-naming-
# style.
#const-rgx=
# Minimum line length for functions/classes that require docstrings, shorter
# ones are exempt.
docstring-min-length=-1
# Naming style matching correct function names.
function-naming-style=camelCase
# Regular expression matching correct function names. Overrides function-
# naming-style.
#function-rgx=
# Good variable names which should always be accepted, separated by a comma.
good-names=i,
j,
k,
ex,
Run,
_
# Include a hint for the correct naming format with invalid-name.
include-naming-hint=no
# Naming style matching correct inline iteration names.
inlinevar-naming-style=any
# Regular expression matching correct inline iteration names. Overrides
# inlinevar-naming-style.
#inlinevar-rgx=
# Naming style matching correct method names.
method-naming-style=camelCase
# Regular expression matching correct method names. Overrides method-naming-
# style.
#method-rgx=
# Naming style matching correct module names.
module-naming-style=camelCase
# Regular expression matching correct module names. Overrides module-naming-
# style.
#module-rgx=
# Colon-delimited sets of names that determine each other's naming style when
# the name regexes allow several styles.
name-group=
# Regular expression which should only match function or class names that do
# not require a docstring.
no-docstring-rgx=^_
# List of decorators that produce properties, such as abc.abstractproperty. Add
# to this list to register other decorators that produce valid properties.
# These decorators are taken in consideration only for invalid-name.
property-classes=abc.abstractproperty
# Naming style matching correct variable names.
variable-naming-style=camelCase
# Regular expression matching correct variable names. Overrides variable-
# naming-style.
#variable-rgx=
[MISCELLANEOUS]
# List of note tags to take in consideration, separated by a comma.
notes=FIXME,
XXX,
TODO
[VARIABLES]
# List of additional names supposed to be defined in builtins. Remember that
# you should avoid defining new builtins when possible.
additional-builtins=
# Tells whether unused global variables should be treated as a violation.
allow-global-unused-variables=yes
# List of strings which can identify a callback function by name. A callback
# name must start or end with one of those strings.
callbacks=cb_,
_cb
# A regular expression matching the name of dummy variables (i.e. expected to
# not be used).
dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
# Argument names that match this expression will be ignored. Default to name
# with leading underscore.
ignored-argument-names=_.*|^ignored_|^unused_
# Tells whether we should check for unused import in __init__ files.
init-import=no
# List of qualified module names which can have objects that can redefine
# builtins.
redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
[FORMAT]
# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
expected-line-ending-format=
# Regexp for a line that is allowed to be longer than the limit.
ignore-long-lines=^\s*(# )??$
# Number of spaces of indent required inside a hanging or continued line.
indent-after-paren=4
# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
# tab).
indent-string=' '
# Maximum number of characters on a single line.
max-line-length=120
# Maximum number of lines in a module.
max-module-lines=1000
# List of optional constructs for which whitespace checking is disabled. `dict-
# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}.
# `trailing-comma` allows a space between comma and closing bracket: (a, ).
# `empty-line` allows space-only lines.
no-space-check=trailing-comma,
dict-separator
# Allow the body of a class to be on the same line as the declaration if body
# contains single statement.
single-line-class-stmt=no
# Allow the body of an if to be on the same line as the test if there is no
# else.
single-line-if-stmt=no
[LOGGING]
# Format style used to check logging format string. `old` means using %
# formatting, while `new` is for `{}` formatting.
logging-format-style=old
# Logging modules to check that the string format arguments are in logging
# function parameter format.
logging-modules=logging
[TYPECHECK]
# List of decorators that produce context managers, such as
# contextlib.contextmanager. Add to this list to register other decorators that
# produce valid context managers.
contextmanager-decorators=contextlib.contextmanager
# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E1101 when accessed. Python regular
# expressions are accepted.
generated-members=
# Tells whether missing members accessed in mixin class should be ignored. A
# mixin class is detected if its name ends with "mixin" (case insensitive).
ignore-mixin-members=yes
# Tells whether to warn about missing members when the owner of the attribute
# is inferred to be None.
ignore-none=yes
# This flag controls whether pylint should warn about no-member and similar
# checks whenever an opaque object is returned when inferring. The inference
# can return multiple potential results while evaluating a Python object, but
# some branches might not be evaluated, which results in partial inference. In
# that case, it might be useful to still emit no-member and other checks for
# the rest of the inferred objects.
ignore-on-opaque-inference=yes
# List of class names for which member attributes should not be checked (useful
# for classes with dynamically set attributes). This supports the use of
# qualified names.
ignored-classes=optparse.Values,thread._local,_thread._local
# List of module names for which member attributes should not be checked
# (useful for modules/projects where namespaces are manipulated during runtime
# and thus existing member attributes cannot be deduced by static analysis. It
# supports qualified module names, as well as Unix pattern matching.
ignored-modules=
# Show a hint with possible names when a member name was not found. The aspect
# of finding the hint is based on edit distance.
missing-member-hint=yes
# The minimum edit distance a name should have in order to be considered a
# similar match for a missing member name.
missing-member-hint-distance=1
# The total number of similar names that should be taken in consideration when
# showing a hint for a missing member.
missing-member-max-choices=1
[STRING]
# This flag controls whether the implicit-str-concat-in-sequence should
# generate a warning on implicit string concatenation in sequences defined over
# several lines.
check-str-concat-over-line-jumps=no
[SIMILARITIES]
# Ignore comments when computing similarities.
ignore-comments=yes
# Ignore docstrings when computing similarities.
ignore-docstrings=yes
# Ignore imports when computing similarities.
ignore-imports=no
# Minimum lines number of a similarity.
min-similarity-lines=4
[CLASSES]
# List of method names used to declare (i.e. assign) instance attributes.
defining-attr-methods=__init__,
__new__,
setUp
# List of member names, which should be excluded from the protected access
# warning.
exclude-protected=_asdict,
_fields,
_replace,
_source,
_make
# List of valid names for the first argument in a class method.
valid-classmethod-first-arg=cls
# List of valid names for the first argument in a metaclass class method.
valid-metaclass-classmethod-first-arg=cls
[DESIGN]
# Maximum number of arguments for function / method.
max-args=5
# Maximum number of attributes for a class (see R0902).
max-attributes=7
# Maximum number of boolean expressions in an if statement.
max-bool-expr=5
# Maximum number of branch for function / method body.
max-branches=12
# Maximum number of locals for function / method body.
max-locals=15
# Maximum number of parents for a class (see R0901).
max-parents=7
# Maximum number of public methods for a class (see R0904).
max-public-methods=20
# Maximum number of return / yield for function / method body.
max-returns=6
# Maximum number of statements in function / method body.
max-statements=50
# Minimum number of public methods for a class (see R0903).
min-public-methods=2
[IMPORTS]
# Allow wildcard imports from modules that define __all__.
allow-wildcard-with-all=no
# Analyse import fallback blocks. This can be used to support both Python 2 and
# 3 compatible code, which means that the block might have code that exists
# only in one or another interpreter, leading to false positives when analysed.
analyse-fallback-blocks=no
# Deprecated modules which should not be used, separated by a comma.
deprecated-modules=optparse,tkinter.tix
# Create a graph of external dependencies in the given file (report RP0402 must
# not be disabled).
ext-import-graph=
# Create a graph of every (i.e. internal and external) dependencies in the
# given file (report RP0402 must not be disabled).
import-graph=
# Create a graph of internal dependencies in the given file (report RP0402 must
# not be disabled).
int-import-graph=
# Force import order to recognize a module as part of the standard
# compatibility libraries.
known-standard-library=
# Force import order to recognize a module as part of a third party library.
known-third-party=enchant
[EXCEPTIONS]
# Exceptions that will emit a warning when being caught. Defaults to
# "BaseException, Exception".
overgeneral-exceptions=BaseException,
Exception
openmotor-0.6.0/LICENSE 0000664 0000000 0000000 00000104515 15005301746 0014553 0 ustar 00root root 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
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 .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
openmotor-0.6.0/MANIFEST.in 0000664 0000000 0000000 00000000236 15005301746 0015277 0 ustar 00root root 0000000 0000000 # include .ui forms
recursive-include uilib/views/forms *
# include resource files
recursive-include resources *
# include pyuic config
include pyuic.json
openmotor-0.6.0/README.md 0000664 0000000 0000000 00000011212 15005301746 0015014 0 ustar 00root root 0000000 0000000 openMotor
==========

Overview
--------
openMotor is an open-source internal ballistics simulator for rocket motor experimenters. The software estimates a rocket motor's chamber pressure and thrust based on propellant properties, grain geometry, and nozzle specifications. It uses the Fast Marching Method to determine how a propellant grain regresses, which allows the use of arbitrary core geometries.
Current Features:
* Metric and imperial units
* Support for common grain geometries such as BATES, Finocyl, Star and more
* Loading custom grain geometry from DXF files
* A propellant editor that allows the user to enter the properties of as many propellants as they wish
* The grain editor displays how a grain will regress to cut down on the guesswork involved in tweaking geometry
* ENG file exporting
* Burnsim importing and exporting
* A UI that supports saving and loading designs along with undo and redo
Planned Features:
* Erosive burning simulation
* Detailed output of every calculated parameter at any time and position along the motor
The calculations involved were sourced from Rocket Propulsion Elements by George Sutton and from [Richard Nakka's website](https://www.nakka-rocketry.net/rtheory.html).

Download
-------
You can download the latest version for your system [here](https://github.com/reilleya/openMotor/releases/latest). From there, just unzip the file and run it. Alternatively, you can run it from source code to get the latest features.
Building from Source
--------------------
The program is currently being developed using python 3.10. The dependencies are outlined in `requirements.txt`, the main ones include `PyQt6`, `matplot`, `numpy`, `scipy`, `scikit-fmm`, and `scikit-image`. Because the PyQt6 bindings are used for the GUI, Qt6 must also be installed.
The easiest way to build/run from source code is to clone the repository and install the required dependencies into a virtual enviornment:
```
$ git clone https://github.com/reilleya/openMotor
$ cd openMotor
$ python3 -m venv .venv
$ source .venv/bin/activate
$ pip install -r requirements.txt
```
If you are using a version of python that does not have a prebuilt version of one of the dependencies, the `pip` command above might fail with an error like:
```
Failed building wheel for scikit-fmm
skfmm/fmm.cpp:4:10: fatal error: Python.h: No such file or directory
```
The fix is to install `python3-dev` or the equivalent with your system package manager.
#### UI Files:
openMotor uses Qt Designer to lay out the GUI, which generates `.ui` files describing the user interface.
We use `pyuic5` to compile these files into Python source code which is then included in the program as ordinary source code.
Because these autogenerated files are not committed to the source tree, you must build them by running:
```
$ python setup.py build_ui
```
Note that if you make changes to the UI using the `.ui` forms, you must re-build using the same command.
Once everything is set up, you can start openMotor by running: `python main.py`
###### Note: On some systems, Python 2 and 3 are installed simultaneously, so you may have to specify which version to run when creating the venv. After the venv has been activated, the programs `python` and `pip` are aliased to the python runtime specific for your venv, so use those (instead of `pip3` and `python3`, on e.g. Debian Linux)
Data Files
-----------
openMotor uses [YAML](https://en.wikipedia.org/wiki/YAML) for data storage. Motor files have the extension `.ric` to differentiate them, but internally they are YAML and can be edited in a text editor if desired. The recommended MIME type for these files is `application/vnd.openmotor+yaml`.
The remaining user information, like propellant data and preferences, is stored in plain YAML files in `\Local\openMotor` on Windows, `/Users//Library/Application Support/openMotor` on Mac OS, and `/home//.local/share/openMotor` on Linux.
License
-------
openMotor is released under the GNU GPL v3 license. The source code is distributed so you can build cool stuff with it, and so you don't have to trust the calculations are being done correctly. Check for yourself (and file an issue ticket!) if you doubt the results.
Contributing
------------
As openMotor is open source, one of the goals of the project is to have as many eyes on the code as possible. I believe this is the best way to avoid bugs and also the easiest way to get new features added to the software. If you have ideas on how to improve the program or find an error, please open an issue ticket for discussion or file a pull request if possible.
openmotor-0.6.0/app.py 0000664 0000000 0000000 00000012602 15005301746 0014673 0 ustar 00root root 0000000 0000000 import sys
import matplotlib.pyplot as plt
import matplotlib as mpl
from PyQt6.QtWidgets import QApplication, QMessageBox
from PyQt6.QtGui import QIcon
from PyQt6.QtCore import Qt
import motorlib
from motorlib import simResult
from uilib import preferencesManager, propellantManager, simulationManager, fileManager, toolManager
from uilib import importExportManager
import uilib.widgets.mainWindow
from uilib.logger import logger
class App(QApplication):
def __init__(self, args):
super().__init__(args)
self.icon = QIcon('resources/oMIconCyclesSmall.png')
self.headless = '-h' in args
if not self.headless and self.isDarkMode():
# Change these settings before any graph widgets are built, so they apply everywhere
plt.style.use('dark_background')
mpl.rcParams['axes.facecolor'] = '1e1e1e'
mpl.rcParams['figure.facecolor'] = '1e1e1e'
self.preferencesManager = uilib.preferencesManager.PreferencesManager()
self.propellantManager = uilib.propellantManager.PropellantManager()
self.preferencesManager.preferencesChanged.connect(self.propellantManager.setPreferences)
self.simulationManager = uilib.simulationManager.SimulationManager()
self.preferencesManager.preferencesChanged.connect(self.simulationManager.setPreferences)
self.fileManager = uilib.fileManager.FileManager(self)
startupFileLoaded = False
if len(args) > 1 and args[-1][0] != '-':
startupFileLoaded = self.fileManager.load(args[-1])
self.propellantManager.updated.connect(self.fileManager.updatePropellant)
self.toolManager = uilib.toolManager.ToolManager(self)
self.preferencesManager.preferencesChanged.connect(self.toolManager.setPreferences)
self.importExportManager = uilib.importExportManager.ImportExportManager(self)
self.preferencesManager.preferencesChanged.connect(self.importExportManager.setPreferences)
self.simulationManager.newSimulationResult.connect(self.importExportManager.acceptSimRes)
self.fileManager.newMotor.connect(self.importExportManager.acceptNewMotor)
if self.headless:
if len(args) < 3:
print('Not enough arguments. Headless mode requires an input file.')
elif not startupFileLoaded:
print('Could not load motor file')
sys.exit(1)
else:
motor = self.fileManager.getCurrentMotor()
simulationResult = motor.runSimulation()
for alert in simulationResult.alerts:
print('{} ({}, {}): {}'.format(motorlib.simResult.alertLevelNames[alert.level],
motorlib.simResult.alertTypeNames[alert.type],
alert.location,
alert.description))
print()
if '-o' in args:
with open(args[args.index('-o') + 1], 'w') as outputFile:
outputFile.write(simulationResult.getCSV(self.preferencesManager.preferences))
else:
print(simulationResult.getCSV(self.preferencesManager.preferences))
sys.exit(0)
else:
usingDarkMode = self.isDarkMode()
currentTheme = self.style().objectName()
logger.log('Opening window (dark mode: {}, default theme: "{}")'.format(usingDarkMode, currentTheme))
# Windows 10 and before don't have dark mode versions of their themes, so if the user wants dark mode, we have to switch to fusion
if usingDarkMode and currentTheme in ['windows', 'windowsvista']:
logger.log('Overriding theme to fusion to get dark mode')
self.setStyle('fusion')
self.window = uilib.widgets.mainWindow.Window(self)
self.preferencesManager.publishPreferences()
if startupFileLoaded:
self.fileManager.sendTitleUpdate()
self.window.show()
logger.log('Window opened')
def isDarkMode(self):
if self.headless:
return False
return self.styleHints().colorScheme() == Qt.ColorScheme.Dark
def outputMessage(self, content, title='openMotor'):
if self.headless:
print(content)
else:
logger.log(content)
msg = QMessageBox()
msg.setWindowIcon(self.icon)
msg.setText(content)
msg.setWindowTitle(title)
msg.exec()
def promptYesNo(self, content, title='openMotor'):
if self.headless:
return input('{} (y/n): '.format(content)) == 'y'
else:
logger.log(content)
msg = QMessageBox()
msg.setWindowIcon(self.icon)
msg.setText(content)
msg.setWindowTitle(title)
msg.setStandardButtons(QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
return msg.exec() == QMessageBox.StandardButton.Yes
def outputException(self, exception, text, title='openMotor - Error'):
if self.headless:
print(text + " " + str(exception))
else:
logger.error(text)
logger.error(exception)
msg = QMessageBox()
msg.setWindowIcon(self.icon)
msg.setText(text)
msg.setInformativeText(str(exception))
msg.setWindowTitle(title)
msg.exec()
openmotor-0.6.0/docs/ 0000775 0000000 0000000 00000000000 15005301746 0014470 5 ustar 00root root 0000000 0000000 openmotor-0.6.0/docs/Makefile 0000664 0000000 0000000 00000001172 15005301746 0016131 0 ustar 00root root 0000000 0000000 # Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = .
BUILDDIR = _build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
openmotor-0.6.0/docs/_static/ 0000775 0000000 0000000 00000000000 15005301746 0016116 5 ustar 00root root 0000000 0000000 openmotor-0.6.0/docs/_static/.gitkeep 0000664 0000000 0000000 00000000000 15005301746 0017535 0 ustar 00root root 0000000 0000000 openmotor-0.6.0/docs/_templates/ 0000775 0000000 0000000 00000000000 15005301746 0016625 5 ustar 00root root 0000000 0000000 openmotor-0.6.0/docs/_templates/.gitkeep 0000664 0000000 0000000 00000000000 15005301746 0020244 0 ustar 00root root 0000000 0000000 openmotor-0.6.0/docs/building.rst 0000664 0000000 0000000 00000004016 15005301746 0017020 0 ustar 00root root 0000000 0000000 Building openMotor from source
==============================
1. Install prerequisites
------------------------
``openMotor`` uses ``PyQt``, which in turn relies on Qt 5. To compile the UI
views, you will need to have Qt installed. The easiest way to do this is by
installing QtCreator, which will also give you access to the Qt Designer to
edit the view files. You can download `QtCreator here `_.
You also need to install openMotor's dependencies. The easiest way to do this
is with pip, inside a virtual environment:
\*nix
^^^^^
.. code-block:: console
$ python3 -m venv .venv
$ source .venv/bin/activate
$ pip install -r requirements.txt
Windows
^^^^^^^
.. code-block:: powershell
PS> python -m venv .venv
PS> .venv/Scripts/Activate.ps1
(.venv) PS> pip install -r requirements.txt
If you get a security error, try using `Set-ExecutionPolicy `_
to loosen your environment security settings.
2. Build Qt Views
-----------------
With QtCreator installed, compile the UI files:
.. code-block:: console
$ python setup.py build_ui
3. Install openMotor in development mode
----------------------------------------
This will let you import the Python modules as if it were a normal package, but
is not necessary for the UI to work.
.. code-block:: console
$ pip install -e .
Running openMotor
=================
Launching the UI is very easy:
.. code-block:: console
$ python ./main.py
Building the Documentation
==========================
The documentation is written with Sphinx, and uses reStructuredText. The
necessary dependencies are included in the requirements file, so if you've
built from source you should be all set to build.
Run the following steps to build the docs:
.. code-block:: console
$ cd ./docs
$ sphinx-build -b html . _build
The build artifacts should now be present in ./docs/_build, and can be opened
in a normal web browser.
openmotor-0.6.0/docs/conf.py 0000664 0000000 0000000 00000003731 15005301746 0015773 0 ustar 00root root 0000000 0000000 # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
# -- Project information -----------------------------------------------------
project = 'openMotor'
copyright = '2019, Andrew Reilley, tuxxi, Pjotr Lengkeek, Joe Quigley'
author = 'Andrew Reilley, tuxxi, Pjotr Lengkeek, Joe Quigley'
# The full version, including alpha/beta/rc tags
release = '0.3.0'
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
"sphinx.ext.autodoc"
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
openmotor-0.6.0/docs/index.rst 0000664 0000000 0000000 00000001226 15005301746 0016332 0 ustar 00root root 0000000 0000000 .. openMotor documentation master file, created by
sphinx-quickstart on Sat Jul 13 18:21:32 2019.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to openMotor's documentation!
=====================================
.. toctree::
:maxdepth: 2
:caption: User documentation:
.. TODO: "Getting Started" guide, tutorial, etc.
.. toctree::
:maxdepth: 2
:caption: Python documentation:
motorlib
.. toctree::
:maxdepth: 1
:caption: Developer documentation:
building
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
openmotor-0.6.0/docs/make.bat 0000664 0000000 0000000 00000001370 15005301746 0016076 0 ustar 00root root 0000000 0000000 @ECHO OFF
pushd %~dp0
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=.
set BUILDDIR=_build
if "%1" == "" goto help
%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end
:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
:end
popd
openmotor-0.6.0/docs/motorlib.rst 0000664 0000000 0000000 00000001343 15005301746 0017052 0 ustar 00root root 0000000 0000000 ``motorlib.geometry``
=====================
.. automodule:: motorlib.geometry
:members:
``motorlib.grain``
==================
.. automodule:: motorlib.grain
:members:
``motorlib.motor``
==================
.. automodule:: motorlib.motor
:members:
``motorlib.nozzle``
===================
.. automodule:: motorlib.nozzle
:members:
``motorlib.propellant``
=======================
.. automodule:: motorlib.propellant
:members:
``motorlib.properties``
=======================
.. automodule:: motorlib.properties
:members:
``motorlib.simResult``
======================
.. automodule:: motorlib.simResult
:members:
``motorlib.units``
==================
.. automodule:: motorlib.units
:members:
openmotor-0.6.0/installers/ 0000775 0000000 0000000 00000000000 15005301746 0015720 5 ustar 00root root 0000000 0000000 openmotor-0.6.0/installers/windows.iss 0000664 0000000 0000000 00000000554 15005301746 0020136 0 ustar 00root root 0000000 0000000 [Setup]
AppName=openMotor
AppVersion=0.5.0
WizardStyle=modern
DefaultDirName={autopf}\openMotor
DefaultGroupName=openMotor
UninstallDisplayIcon={app}\openMotor.exe
Compression=lzma2
SolidCompression=yes
[Files]
Source: "../pyinstaller/dist/openMotor/*"; DestDir: "{app}"; Flags: recursesubdirs
[Icons]
Name: "{group}\openMotor"; Filename: "{app}\openMotor.exe"
openmotor-0.6.0/main.py 0000664 0000000 0000000 00000000145 15005301746 0015036 0 ustar 00root root 0000000 0000000 import sys
from app import App
from PyQt6.QtCore import Qt
app = App(sys.argv)
sys.exit(app.exec())
openmotor-0.6.0/motorlib/ 0000775 0000000 0000000 00000000000 15005301746 0015367 5 ustar 00root root 0000000 0000000 openmotor-0.6.0/motorlib/__init__.py 0000664 0000000 0000000 00000000000 15005301746 0017466 0 ustar 00root root 0000000 0000000 openmotor-0.6.0/motorlib/constants.py 0000664 0000000 0000000 00000000305 15005301746 0017753 0 ustar 00root root 0000000 0000000 """Conains constants needed for motor calculations."""
# R, in units of J/(kmol*K)
gasConstant = 8314.462618
# Standard gravitation acceleration (g), in units of m/s**2
standardGravity = 9.80665
openmotor-0.6.0/motorlib/geometry.py 0000664 0000000 0000000 00000006155 15005301746 0017603 0 ustar 00root root 0000000 0000000 """This module includes the geometry methods that openMotor uses in its calculations"""
import math
import numpy as np
def circleArea(dia):
"""Returns the area of a circle with diameter dia"""
return ((dia / 2) ** 2) * math.pi
def circlePerimeter(dia):
"""Returns the perimeter (circumference) of a circle with diameter dia"""
return dia * math.pi
def circleDiameterFromArea(area):
"""Returns the diameter of a circle with area 'area'"""
return 2 * ((area / math.pi) ** 0.5)
def tubeArea(dia, height):
"""Returns the surface area of a tube (cylinder without endcaps) with diameter 'dia' and height 'height'"""
return dia * math.pi * height
def cylinderArea(dia, height):
"""Returns the surface area of a cylinder with diameter 'dia' and height 'height'"""
return (2 * circleArea(dia)) + (tubeArea(dia, height))
def cylinderVolume(dia, height):
"""Returns the volume of a cylinder with diameter 'dia' and height 'height'"""
return height * circleArea(dia)
def frustumLateralSurfaceArea(diameterA, diameterB, length):
"""Returns the surface area of a frustum (truncated cone) with end diameters A and B and length 'length'"""
radiusA = diameterA / 2
radiusB = diameterB / 2
return math.pi * (radiusA + radiusB) * (abs(radiusA - radiusB) ** 2 + length ** 2) ** 0.5
def frustumVolume(diameterA, diameterB, length):
"""Returns the volume of a frustum (truncated cone) with end diameters A and B and length 'length'"""
radiusA = diameterA / 2
radiusB = diameterB / 2
return math.pi * (length / 3) * (radiusA ** 2 + radiusA * radiusB + radiusB ** 2)
def splitFrustum(diameterA, diameterB, length, splitPosition):
"""Takes in info about a frustum (truncated cone) and a position measured from the "diameterA" and returns
a tuple of frustums representing the two halves of the original frustum if it were split on the plane at
distance "position" from the face with diameter "diameterA"
"""
splitDiameter = diameterA + (diameterB - diameterA) * (splitPosition / length)
return (diameterA, splitDiameter, splitPosition), (splitDiameter, diameterB, length - splitPosition)
def length(contour, mapSize, tolerance=3):
"""Returns the total length of all segments in a contour that aren't within 'tolerance' of the edge of a
circle with diameter 'mapSize'"""
offset = np.roll(contour.T, 1, axis=1)
lengths = np.linalg.norm(contour.T - offset, axis=0)
centerOffset = np.array([[mapSize / 2, mapSize / 2]])
radius = np.linalg.norm(contour - centerOffset, axis=1)
valid = radius < (mapSize / 2) - tolerance
return np.sum(lengths[valid])
def clean(contour, mapSize, tolerance):
"""Returns a contour with the same points as the input, omitting any within 'tolerace' of a circle of
diameter 'mapSize'"""
offset = np.array([[mapSize / 2, mapSize / 2]])
lengths = np.linalg.norm(contour - offset, axis=1)
return contour[lengths < (mapSize / 2) - tolerance]
def dist(point1, point2):
"""Returns the distance between two points [x1, y1], [x2, y2]"""
return ((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2) ** 0.5
openmotor-0.6.0/motorlib/grain.py 0000664 0000000 0000000 00000036656 15005301746 0017061 0 ustar 00root root 0000000 0000000 """This module includes the base classes from which all grain classes should inherit. None of these objects
should be instantiated directly."""
from abc import abstractmethod
import numpy as np
import skfmm
from skimage import measure
from scipy.signal import savgol_filter
from scipy import interpolate
from . import geometry
from .simResult import SimAlert, SimAlertLevel, SimAlertType
from .properties import FloatProperty, EnumProperty, PropertyCollection
class Grain(PropertyCollection):
"""A basic propellant grain. This is the class that all grains inherit from. It provides a few properties and
composed methods but otherwise it is up to the subclass to make a functional grain."""
geomName = None
def __init__(self):
super().__init__()
self.props['diameter'] = FloatProperty('Diameter', 'm', 0, 1)
self.props['length'] = FloatProperty('Length', 'm', 0, 3)
def getVolumeSlice(self, regDist, dRegDist):
"""Returns the amount of propellant volume consumed as the grain regresses from a distance of 'regDist' to
regDist + dRegDist"""
return self.getVolumeAtRegression(regDist) - self.getVolumeAtRegression(regDist + dRegDist)
@abstractmethod
def getSurfaceAreaAtRegression(self, regDist):
"""Returns the surface area of the grain after it has regressed a linear distance of 'regDist'"""
@abstractmethod
def getVolumeAtRegression(self, regDist):
"""Returns the volume of propellant in the grain after it has regressed a linear distance 'regDist'"""
@abstractmethod
def getWebLeft(self, regDist):
"""Returns the shortest distance the grain has to regress to burn out"""
def isWebLeft(self, regDist, burnoutThres=0.00001):
"""Returns True if the grain has propellant left to burn after it has regressed a distance of 'regDist'"""
return self.getWebLeft(regDist) > burnoutThres
@abstractmethod
def getMassFlux(self, massIn, dTime, regDist, dRegDist, position, density):
"""Returns the mass flux at a point along the grain. Takes in the mass flow into the grain, a timestep, the
distance the grain has regressed so far, the additional distance it will regress during the timestep, a
position along the grain measured from the head end, and the density of the propellant."""
def getPeakMassFlux(self, massIn, dTime, regDist, dRegDist, density):
"""Uses the grain's mass flux method to return the max. Assumes that it will be at the port of the grain!"""
return self.getMassFlux(massIn, dTime, regDist, dRegDist, self.getEndPositions(regDist)[1], density)
@abstractmethod
def getEndPositions(self, regDist):
"""Returns the positions of the grain ends relative to the original (unburned) grain top"""
@abstractmethod
def getPortArea(self, regDist):
"""Returns the area of the grain's port when it has regressed a distance of 'regDist'"""
def getRegressedLength(self, regDist):
"""Returns the length of the grain when it has regressed a distance of 'regDist', taking any possible
inhibition into account."""
endPos = self.getEndPositions(regDist)
return endPos[1] - endPos[0]
def getDetailsString(self, lengthUnit='m'):
"""Returns a short string describing the grain, formatted using the units that is passed in"""
return 'Length: {}'.format(self.props['length'].dispFormat(lengthUnit))
@abstractmethod
def simulationSetup(self, config):
"""Do anything needed to prepare this grain for simulation"""
def getGeometryErrors(self):
"""Returns a list of simAlerts that detail any issues with the geometry of the grain. Errors should be
used for any condition that prevents simulation of the grain, while warnings can be used to notify the
user of possible non-fatal mistakes in their entered numbers. Subclasses should still call the superclass
method, as it performs checks that still apply to its subclasses."""
errors = []
if self.props['diameter'].getValue() == 0:
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.GEOMETRY, 'Diameter must not be 0'))
if self.props['length'].getValue() == 0:
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.GEOMETRY, 'Length must not be 0'))
return errors
def getGrainBoundingVolume(self):
"""Returns the volume of the bounding cylinder around the grain"""
return geometry.cylinderVolume(self.props['diameter'].getValue(), self.props['length'].getValue())
def getFreeVolume(self, regDist):
"""Returns the amount of empty (non-propellant) volume in bounding cylinder of the grain for a given regression
depth."""
return float(self.getGrainBoundingVolume() - self.getVolumeAtRegression(regDist))
class PerforatedGrain(Grain):
"""A grain with a hole of some shape through the center. Adds abstract methods related to the core to the
basic grain class """
geomName = 'perfGrain'
def __init__(self):
super().__init__()
self.props['inhibitedEnds'] = EnumProperty('Inhibited ends', ['Neither', 'Top', 'Bottom', 'Both'])
self.wallWeb = 0 # Max distance from the core to the wall
def getEndPositions(self, regDist):
if self.props['inhibitedEnds'].getValue() == 'Neither': # Neither
return (regDist, self.props['length'].getValue() - regDist)
if self.props['inhibitedEnds'].getValue() == 'Top': # Top
return (0, self.props['length'].getValue() - regDist)
if self.props['inhibitedEnds'].getValue() == 'Bottom': # Bottom
return (regDist, self.props['length'].getValue())
if self.props['inhibitedEnds'].getValue() == 'Both':
return (0, self.props['length'].getValue())
# The enum should prevent this from even being raised, but to cover the case where it somehow gets set wrong
raise ValueError('Invalid number of faces inhibited')
@abstractmethod
def getCorePerimeter(self, regDist):
"""Returns the perimeter of the core after the grain has regressed a distance of 'regDist'."""
@abstractmethod
def getFaceArea(self, regDist):
"""Returns the area of the grain face after it has regressed a distance of 'regDist'. This is the
same as the area of an equal-diameter endburning grain minus the grain's port area."""
def getCoreSurfaceArea(self, regDist):
"""Returns the surface area of the grain's core after it has regressed a distance of 'regDist'"""
corePerimeter = self.getCorePerimeter(regDist)
coreArea = corePerimeter * self.getRegressedLength(regDist)
return coreArea
def getWebLeft(self, regDist):
wallLeft = self.wallWeb - regDist
if self.props['inhibitedEnds'].getValue() == 'Both':
return wallLeft
lengthLeft = self.getRegressedLength(regDist)
return min(lengthLeft, wallLeft)
def getSurfaceAreaAtRegression(self, regDist):
faceArea = self.getFaceArea(regDist)
coreArea = self.getCoreSurfaceArea(regDist)
exposedFaces = 2
if self.props['inhibitedEnds'].getValue() == 'Top' or self.props['inhibitedEnds'].getValue() == 'Bottom':
exposedFaces = 1
if self.props['inhibitedEnds'].getValue() == 'Both':
exposedFaces = 0
return coreArea + (exposedFaces * faceArea)
def getVolumeAtRegression(self, regDist):
faceArea = self.getFaceArea(regDist)
return faceArea * self.getRegressedLength(regDist)
def getPortArea(self, regDist):
faceArea = self.getFaceArea(regDist)
uncored = geometry.circleArea(self.props['diameter'].getValue())
return uncored - faceArea
def getMassFlux(self, massIn, dTime, regDist, dRegDist, position, density):
diameter = self.props['diameter'].getValue()
endPos = self.getEndPositions(regDist)
# If a position above the top face is queried, the mass flow is just the input mass and the
# diameter is the casting tube
if position < endPos[0]:
return massIn / geometry.circleArea(diameter)
# If a position in the grain is queried, the mass flow is the input mass, from the top face,
# and from the tube up to the point. The diameter is the core.
if position <= endPos[1]:
if self.props['inhibitedEnds'].getValue() in ('Top', 'Both'):
top = 0
countedCoreLength = position
else:
top = self.getFaceArea(regDist + dRegDist) * dRegDist * density
countedCoreLength = position - (endPos[0] + dRegDist)
# This block gets the mass of propellant the core burns in the step.
core = ((self.getPortArea(regDist + dRegDist) * countedCoreLength)
- (self.getPortArea(regDist) * countedCoreLength))
core *= density
massFlow = massIn + ((top + core) / dTime)
return massFlow / self.getPortArea(regDist + dRegDist)
# A position past the grain end was specified, so the mass flow includes the input mass flow
# and all mass produced by the grain. Diameter is the casting tube.
massFlow = massIn + (self.getVolumeSlice(regDist, dRegDist) * density / dTime)
return massFlow / geometry.circleArea(diameter)
@abstractmethod
def getFaceImage(self, mapDim):
"""Returns an image of the grain's cross section, with resolution (mapDim, mapDim)."""
@abstractmethod
def getRegressionData(self, mapDim, numContours=15, coreBlack=True):
"""Returns a tuple that includes a grain face image as described in 'getFaceImage', a regression map
where color maps to regression depth, a list of contours (lists of (x,y) points in image space) of
equal regression depth, and a list of corresponding contour lengths. The contours are equally spaced
between 0 regression and burnout."""
class FmmGrain(PerforatedGrain):
"""A grain that uses the fast marching method to calculate its regression. All a subclass has to do is
provide an implementation of generateCoreMap that makes an image of a cross section of the grain."""
geomName = 'fmmGrain'
def __init__(self):
super().__init__()
self.mapDim = 1001
self.mapX, self.mapY = None, None
self.mask = None
self.coreMap = None
self.regressionMap = None
self.faceArea = None
def normalize(self, value):
"""Transforms real unit quantities into self.mapX, self.mapY coordinates. For use in indexing into the
coremap."""
return value / (0.5 * self.props['diameter'].getValue())
def unNormalize(self, value):
"""Transforms self.mapX, self.mapY coordinates to real unit quantities. Used to determine real lengths in
coremap."""
return (value / 2) * self.props['diameter'].getValue()
def lengthToMap(self, value):
"""Converts meters to pixels. Used to compare real distances to pixel distances in the regression map."""
return self.mapDim * (value / self.props['diameter'].getValue())
def mapToLength(self, value):
"""Converts pixels to meters. Used to extract real distances from pixel distances such as contour lengths"""
return self.props['diameter'].getValue() * (value / self.mapDim)
def areaToMap(self, value):
"""Used to convert sqm to sq pixels, like on the regression map."""
return (self.mapDim ** 2) * (value / (self.props['diameter'].getValue() ** 2))
def mapToArea(self, value):
"""Used to convert sq pixels to sqm. For extracting real areas from the regression map."""
return (self.props['diameter'].getValue() ** 2) * (value / (self.mapDim ** 2))
def initGeometry(self, mapDim):
"""Set up an empty core map and reset the regression map. Takes in the dimension of both maps."""
if mapDim < 64:
raise ValueError('Map dimension must be 64 or larger to get good results')
self.mapDim = mapDim
self.mapX, self.mapY = np.meshgrid(np.linspace(-1, 1, self.mapDim), np.linspace(-1, 1, self.mapDim))
self.mask = self.mapX**2 + self.mapY**2 > 1
self.coreMap = np.ones_like(self.mapX)
self.regressionMap = None
@abstractmethod
def generateCoreMap(self):
"""Use self.mapX and self.mapY to generate an image of the grain cross section in self.coreMap. A 0 in the image
means propellant, and a 1 means no propellant."""
def simulationSetup(self, config):
mapSize = config.getProperty("mapDim")
self.initGeometry(mapSize)
self.generateCoreMap()
self.generateRegressionMap()
def generateRegressionMap(self):
"""Uses the fast marching method to generate an image of how the grain regresses from the core map. The map
is stored under self.regressionMap."""
masked = np.ma.MaskedArray(self.coreMap, self.mask)
cellSize = 1 / self.mapDim
self.regressionMap = skfmm.distance(masked, dx=cellSize) * 2
maxDist = np.amax(self.regressionMap)
self.wallWeb = self.unNormalize(maxDist)
faceArea = []
polled = []
valid = np.logical_not(self.mask)
for i in range(int(maxDist * self.mapDim) + 2):
polled.append(i / self.mapDim)
faceArea.append(self.mapToArea(np.count_nonzero(np.logical_and(self.regressionMap > (i / self.mapDim), valid))))
self.faceArea = savgol_filter(faceArea, 31, 5)
self.faceAreaFunc = interpolate.interp1d(polled, self.faceArea)
def getCorePerimeter(self, regDist):
mapDist = self.normalize(regDist)
corePerimeter = 0
contours = measure.find_contours(self.regressionMap, mapDist, fully_connected='low')
for contour in contours:
corePerimeter += self.mapToLength(geometry.length(contour, self.mapDim))
return corePerimeter
def getFaceArea(self, regDist):
mapDist = self.normalize(regDist)
index = int(mapDist * self.mapDim)
if index >= len(self.faceArea) - 1:
return 0 # Past burnout
return self.faceAreaFunc(mapDist)
def getFaceImage(self, mapDim):
self.initGeometry(mapDim)
self.generateCoreMap()
masked = np.ma.MaskedArray(self.coreMap, self.mask)
return masked
def getRegressionData(self, mapDim, numContours=15, coreBlack=True):
self.initGeometry(mapDim)
self.generateCoreMap()
masked = np.ma.MaskedArray(self.coreMap, self.mask)
regressionMap = None
contours = []
contourLengths = {}
try:
self.generateRegressionMap()
regmax = np.amax(self.regressionMap)
regressionMap = self.regressionMap[:, :].copy()
if coreBlack:
regressionMap[np.where(self.coreMap == 0)] = regmax # Make the core black
regressionMap = np.ma.MaskedArray(regressionMap, self.mask)
for dist in np.linspace(0, regmax, numContours):
contours.append([])
contourLengths[dist] = 0
layerContours = measure.find_contours(self.regressionMap, dist, fully_connected='low')
for contour in layerContours:
contours[-1].append(geometry.clean(contour, self.mapDim, 3))
contourLengths[dist] += geometry.length(contour, self.mapDim)
except ValueError as exc: # If there aren't any contours, do nothing
print(exc)
return (masked, regressionMap, contours, contourLengths)
openmotor-0.6.0/motorlib/grains/ 0000775 0000000 0000000 00000000000 15005301746 0016652 5 ustar 00root root 0000000 0000000 openmotor-0.6.0/motorlib/grains/__init__.py 0000664 0000000 0000000 00000001057 15005301746 0020766 0 ustar 00root root 0000000 0000000 from .endBurner import *
from .bates import *
from .finocyl import *
from .moonBurner import *
from .star import *
from .xCore import *
from .cGrain import *
from .dGrain import *
from .rodTube import *
from .conical import *
from .custom import *
# Generate grain geometry name -> constructor lookup table
grainTypes = {}
grainClasses = [BatesGrain, EndBurningGrain, Finocyl, MoonBurner, StarGrain, XCore, CGrain, DGrain, RodTubeGrain,
ConicalGrain, CustomGrain]
for grainType in grainClasses:
grainTypes[grainType.geomName] = grainType
openmotor-0.6.0/motorlib/grains/bates.py 0000664 0000000 0000000 00000007023 15005301746 0020324 0 ustar 00root root 0000000 0000000 """BATES submodule"""
import numpy as np
import skfmm
from skimage import measure
from ..grain import PerforatedGrain
from .. import geometry
from ..simResult import SimAlert, SimAlertLevel, SimAlertType
from ..properties import FloatProperty
class BatesGrain(PerforatedGrain):
"""The BATES grain has a simple cylindrical core. This type is not an FMM grain for performance reasons, as the
calculations are easy enough to do manually."""
geomName = "BATES"
def __init__(self):
super().__init__()
self.props['coreDiameter'] = FloatProperty('Core Diameter', 'm', 0, 1)
def simulationSetup(self, config):
self.wallWeb = (self.props['diameter'].getValue() - self.props['coreDiameter'].getValue()) / 2
def getCorePerimeter(self, regDist):
return geometry.circlePerimeter(self.props['coreDiameter'].getValue() + (2 * regDist))
def getFaceArea(self, regDist):
outer = geometry.circleArea(self.props['diameter'].getValue())
inner = geometry.circleArea(self.props['coreDiameter'].getValue() + (2 * regDist))
return outer - inner
def getDetailsString(self, lengthUnit='m'):
return 'Length: {}, Core: {}'.format(self.props['length'].dispFormat(lengthUnit),
self.props['coreDiameter'].dispFormat(lengthUnit))
def getGeometryErrors(self):
errors = super().getGeometryErrors()
if self.props['coreDiameter'].getValue() == 0:
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.GEOMETRY, 'Core diameter must not be 0'))
if self.props['coreDiameter'].getValue() >= self.props['diameter'].getValue():
aText = 'Core diameter must be less than grain diameter'
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.GEOMETRY, aText))
return errors
# These two functions have a lot of code reuse, but it is worth it because making BATES an fmmGrain would make it
# signficantly way slower
def getFaceImage(self, mapDim):
mapX, mapY = np.meshgrid(np.linspace(-1, 1, mapDim), np.linspace(-1, 1, mapDim))
mask = mapX**2 + mapY**2 > 1
coreMap = np.ones_like(mapX)
# Normalize core diameter
coreRadius = (self.props['coreDiameter'].getValue() / (0.5 * self.props['diameter'].getValue())) / 2
# Open up core
coreMap[mapX**2 + mapY**2 < coreRadius**2] = 0
maskedMap = np.ma.MaskedArray(coreMap, mask)
return maskedMap
def getRegressionData(self, mapDim, numContours=15, coreBlack=True):
masked = self.getFaceImage(mapDim)
regressionMap = None
contours = []
contourLengths = {}
try:
cellSize = 1 / mapDim
regressionMap = skfmm.distance(masked, dx=cellSize) * 2
regmax = np.amax(regressionMap)
regressionMap = regressionMap[:, :].copy()
if coreBlack:
regressionMap[np.where(masked == 0)] = regmax # Make the core black
for dist in np.linspace(0, regmax, numContours):
contours.append([])
contourLengths[dist] = 0
layerContours = measure.find_contours(regressionMap, dist, fully_connected='high')
for contour in layerContours:
contours[-1].append(contour)
contourLengths[dist] += geometry.length(contour, mapDim)
except ValueError as exc: # If there aren't any contours, do nothing
print(exc)
return (masked, regressionMap, contours, contourLengths)
openmotor-0.6.0/motorlib/grains/cGrain.py 0000664 0000000 0000000 00000004153 15005301746 0020432 0 ustar 00root root 0000000 0000000 """C Grain submodule"""
import numpy as np
from ..grain import FmmGrain
from ..properties import FloatProperty
from ..simResult import SimAlert, SimAlertLevel, SimAlertType
class CGrain(FmmGrain):
"""Defines a C grain, which is a cylindrical grain with a single slot taken out. The slot is a rectangular section
with a certain width that starts at the casting tube and protrudes towards the center of the grain, stopping a
specified offset away."""
geomName = 'C Grain'
def __init__(self):
super().__init__()
self.props['slotWidth'] = FloatProperty('Slot width', 'm', 0, 1)
self.props['slotOffset'] = FloatProperty('Slot offset', 'm', -1, 1)
self.props['slotOffset'].setValue(0)
def generateCoreMap(self):
slotWidth = self.normalize(self.props['slotWidth'].getValue())
slotOffset = self.normalize(self.props['slotOffset'].getValue())
self.coreMap[np.logical_and(np.abs(self.mapY) < slotWidth / 2, self.mapX > slotOffset)] = 0
def getDetailsString(self, lengthUnit='m'):
return 'Length: {}'.format(self.props['length'].dispFormat(lengthUnit))
def getGeometryErrors(self):
errors = super().getGeometryErrors()
if self.props['slotOffset'].getValue() > self.props['diameter'].getValue() / 2:
aText = 'Slot offset should be less than grain radius'
errors.append(SimAlert(SimAlertLevel.WARNING, SimAlertType.GEOMETRY, aText))
if self.props['slotOffset'].getValue() < -self.props['diameter'].getValue() / 2:
aText = 'Slot offset should be greater than negative grain radius'
errors.append(SimAlert(SimAlertLevel.WARNING, SimAlertType.GEOMETRY, aText))
if self.props['slotWidth'].getValue() == 0:
errors.append(SimAlert(SimAlertLevel.WARNING, SimAlertType.GEOMETRY, 'Slot width must not be 0'))
if self.props['slotWidth'].getValue() > self.props['diameter'].getValue():
aText = 'Slot width should not be greater than grain diameter'
errors.append(SimAlert(SimAlertLevel.WARNING, SimAlertType.GEOMETRY, aText))
return errors
openmotor-0.6.0/motorlib/grains/conical.py 0000664 0000000 0000000 00000026203 15005301746 0020637 0 ustar 00root root 0000000 0000000 """BATES submodule"""
import numpy as np
import skfmm
from skimage import measure
from math import atan, cos, sin
from ..grain import Grain
from .. import geometry
from ..simResult import SimAlert, SimAlertLevel, SimAlertType
from ..properties import FloatProperty, EnumProperty
class ConicalGrain(Grain):
"""A conical grain is similar to a BATES grain except it has different core diameters at each end."""
geomName = "Conical"
def __init__(self):
super().__init__()
self.props['forwardCoreDiameter'] = FloatProperty('Forward Core Diameter', 'm', 0, 1)
self.props['aftCoreDiameter'] = FloatProperty('Aft Core Diameter', 'm', 0, 1)
self.props['inhibitedEnds'] = EnumProperty('Inhibited ends', ['Both'])
def isCoreInverted(self):
"""A simple helper that returns 'true' if the core's foward diameter is larger than its aft diameter"""
return self.props['forwardCoreDiameter'].getValue() > self.props['aftCoreDiameter'].getValue()
def getFrustumInfo(self, regDist):
"""Returns the dimensions of the grain's core at a given regression depth. The core is always a frustum and is
returned as the aft diameter, forward diameter, and length"""
grainDiameter = self.props['diameter'].getValue()
aftDiameter = self.props['aftCoreDiameter'].getValue()
forwardDiameter = self.props['forwardCoreDiameter'].getValue()
grainLength = self.props['length'].getValue()
exposedFaces = 0
inhibitedEnds = self.props['inhibitedEnds'].getValue()
if inhibitedEnds == 'Neither':
exposedFaces = 2
elif inhibitedEnds in ['Top', 'Bottom']:
exposedFaces = 1
# These calculations are easiest if we work in terms of the core's "large end" and "small end"
if self.isCoreInverted():
coreMajorDiameter, coreMinorDiameter = forwardDiameter, aftDiameter
else:
coreMajorDiameter, coreMinorDiameter = aftDiameter, forwardDiameter
# Calculate the half angle of the core. This is done with without accounting for regression because it doesn't
# change with regression
angle = atan((coreMajorDiameter - coreMinorDiameter) / (2 * grainLength))
# Expand both core diameters by the radial component of the core's regression vector. This is allowed to expand
# beyond the casting tube as that condition is checked in a later step
regCoreMajorDiameter = coreMajorDiameter + (regDist * 2 * cos(angle))
regCoreMinorDiameter = coreMinorDiameter + (regDist * 2 * cos(angle))
# This is case where the larger core diameter has grown beyond the casting tube diameter. Once this happens,
# the diameter of the large end of the core is clamped at the grain diameter and the length is changed to keep
# the angle constant, which accounts for the regression of the grain at the major end.
if regCoreMajorDiameter >= grainDiameter:
majorFrustumDiameter = grainDiameter
minorFrustumDiameter = regCoreMinorDiameter
# How far past the grain diameter the major end has grown
effectiveReg = (regCoreMajorDiameter - grainDiameter) / 2
# Reduce the length of the frustum by the axial component of the regression vector
grainLength -= (effectiveReg / sin(angle))
# Account for the change in length due to face regression before the major end hit the casting tube
grainLength -= exposedFaces * (grainDiameter - coreMajorDiameter) / 2
# Don't double count face regression
grainLength += exposedFaces * effectiveReg
# If the large end of the core hasn't reached the casting tube, we know that the small end hasn't either. In
# this case we just return the current core diameters, and a length calculated from the inhibitor configuration
else:
majorFrustumDiameter = regCoreMajorDiameter
minorFrustumDiameter = regCoreMinorDiameter
grainLength -= exposedFaces * regDist
if self.isCoreInverted():
return minorFrustumDiameter, majorFrustumDiameter, grainLength
return majorFrustumDiameter, minorFrustumDiameter, grainLength
def getSurfaceAreaAtRegression(self, regDist):
"""Returns the surface area of the grain after it has regressed a linear distance of 'regDist'"""
aftDiameter, forwardDiameter, length = self.getFrustumInfo(regDist)
surfaceArea = geometry.frustumLateralSurfaceArea(aftDiameter, forwardDiameter, length)
fullFaceArea = geometry.circleArea(self.props['diameter'].getValue())
if self.props['inhibitedEnds'].getValue() in ['Neither', 'Bottom']:
surfaceArea += fullFaceArea - geometry.circleArea(forwardDiameter)
if self.props['inhibitedEnds'].getValue() in ['Neither', 'Top']:
surfaceArea += fullFaceArea - geometry.circleArea(aftDiameter)
return surfaceArea
def getVolumeAtRegression(self, regDist):
"""Returns the volume of propellant in the grain after it has regressed a linear distance 'regDist'"""
aftDiameter, forwardDiameter, length = self.getFrustumInfo(regDist)
frustumVolume = geometry.frustumVolume(aftDiameter, forwardDiameter, length)
outerVolume = geometry.cylinderVolume(self.props['diameter'].getValue(), length)
return outerVolume - frustumVolume
def getWebLeft(self, regDist):
"""Returns the shortest distance the grain has to regress to burn out"""
aftDiameter, forwardDiameter, length = self.getFrustumInfo(regDist)
return (self.props['diameter'].getValue() - min(aftDiameter, forwardDiameter)) / 2
def getMassFlow(self, massIn, dTime, regDist, dRegDist, position, density):
"""Returns the mass flow at a point along the grain. Takes in the mass flow into the grain, a timestep, the
distance the grain has regressed so far, the additional distance it will regress during the timestep, a
position along the grain measured from the head end, and the density of the propellant."""
# For now these grains are only allowed with inhibited faces, so we can ignore a lot of messy logic
unsteppedFrustum = self.getFrustumInfo(regDist)
steppedFrustum = self.getFrustumInfo(regDist + dRegDist)
"""These have to be reordered, because getFrustumInfo returns (aft, forward, length), but splitFrustum wants
the position from the forward face"""
unsteppedFrustum = (unsteppedFrustum[1], unsteppedFrustum[0], unsteppedFrustum[2])
steppedFrustum = (steppedFrustum[1], steppedFrustum[0], steppedFrustum[2])
# Note that this assumes the forward end of the grain is still at postition 0 - inhibited
unsteppedPartialFrustum, _ = geometry.splitFrustum(*unsteppedFrustum, position)
steppedPartialFrustum, _ = geometry.splitFrustum(*steppedFrustum, position)
unsteppedVolume = geometry.frustumVolume(*unsteppedPartialFrustum)
steppedVolume = geometry.frustumVolume(*steppedPartialFrustum)
massFlow = (steppedVolume - unsteppedVolume) * density / dTime
massFlow += massIn
return massFlow, steppedPartialFrustum[1]
def getMassFlux(self, massIn, dTime, regDist, dRegDist, position, density):
"""Returns the mass flux at a point along the grain. Takes in the mass flow into the grain, a timestep, the
distance the grain has regressed so far, the additional distance it will regress during the timestep, a
position along the grain measured from the head end, and the density of the propellant."""
massFlow, portDiameter = self.getMassFlow(massIn, dTime, regDist, dRegDist, position, density)
return massFlow / geometry.circleArea(portDiameter) # Index 1 is port diameter OR IS IT
def getPeakMassFlux(self, massIn, dTime, regDist, dRegDist, density):
"""Uses the grain's mass flux method to return the max. Need to define this here because I'm not sure what
it will look like"""
forwardMassFlux = self.getMassFlux(massIn, dTime, regDist, dRegDist, self.getEndPositions(regDist)[0], density)
aftMassFlux = self.getMassFlux(massIn, dTime, regDist, dRegDist, self.getEndPositions(regDist)[1], density)
return max(forwardMassFlux, aftMassFlux)
def getEndPositions(self, regDist):
"""Returns the positions of the grain ends relative to the original (unburned) grain top. Returns a tuple like
(forward, aft)"""
originalLength = self.props['length'].getValue()
aftCoreDiameter, forwardCoreDiameter, currentLength = self.getFrustumInfo(regDist)
inhibitedEnds = self.props['inhibitedEnds'].getValue()
if self.isCoreInverted():
if inhibitedEnds == 'Bottom' or inhibitedEnds == 'Both':
# Because all of the change in length is due to the forward end moving, the forward end's position is
# just the amount the the grain has regressed by, The aft end stays where it started
return (originalLength - currentLength, originalLength)
# Neither or Top. In this case, the forward end moving accounts for almost all of the change in total grain
# length, except for the aft face having moved up by `regDist`, so that quantity is subtracted from the
# total change in grain length to get the forward end position
return (originalLength - currentLength - regDist, originalLength - regDist)
if inhibitedEnds == 'Top' or inhibitedEnds == 'Both':
# All of the change in grain length is due to the aft face moving, so the forward face stays at 0 and the
# aft face is at the regressed grain length
return (0, currentLength)
# Neither or Bottom
return (regDist, regDist + currentLength)
def getPortArea(self, regDist):
"""Returns the area of the grain's port when it has regressed a distance of 'regDist'"""
aftCoreDiameter, _, _ = self.getFrustumInfo(regDist)
return geometry.circleArea(aftCoreDiameter)
def getDetailsString(self, lengthUnit='m'):
"""Returns a short string describing the grain, formatted using the units that is passed in"""
return 'Length: {}'.format(self.props['length'].dispFormat(lengthUnit))
def simulationSetup(self, config):
"""Do anything needed to prepare this grain for simulation"""
return None
def getGeometryErrors(self):
errors = super().getGeometryErrors()
if self.props['aftCoreDiameter'].getValue() == self.props['forwardCoreDiameter'].getValue():
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.GEOMETRY, 'Core diameters cannot be the same, use a BATES for this case.'))
if self.props['aftCoreDiameter'].getValue() > self.props['diameter'].getValue():
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.GEOMETRY, 'Aft core diameter cannot be larger than grain diameter.'))
if self.props['forwardCoreDiameter'].getValue() > self.props['diameter'].getValue():
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.GEOMETRY, 'Forward core diameter cannot be larger than grain diameter.'))
return errors
openmotor-0.6.0/motorlib/grains/custom.py 0000664 0000000 0000000 00000003107 15005301746 0020537 0 ustar 00root root 0000000 0000000 """Custom Grain submodule"""
import skimage.draw as draw
from ..grain import FmmGrain
from ..properties import PolygonProperty, EnumProperty
from ..simResult import SimAlert, SimAlertLevel, SimAlertType
from ..units import getAllConversions, convert
class CustomGrain(FmmGrain):
"""Custom grains can have any core shape. They define their geometry using a polygon property, which tracks a list
of polygons that each consist of a number of points. The polygons are scaled according to user specified units and
drawn onto the core map."""
geomName = 'Custom Grain'
def __init__(self):
super().__init__()
self.props['points'] = PolygonProperty('Core geometry')
self.props['dxfUnit'] = EnumProperty('DXF Unit', getAllConversions('m'))
def generateCoreMap(self):
inUnit = self.props['dxfUnit'].getValue()
for polygon in self.props['points'].getValue():
row = [(self.mapDim/2) + (-self.normalize(convert(p[1], inUnit, 'm')) * (self.mapDim/2)) for p in polygon]
col = [(self.mapDim/2) + (self.normalize(convert(p[0], inUnit, 'm')) * (self.mapDim/2)) for p in polygon]
imageRow, imageCol = draw.polygon(row, col, self.coreMap.shape)
self.coreMap[imageRow, imageCol] = 0
def getGeometryErrors(self):
errors = super().getGeometryErrors()
if len(self.props['points'].getValue()) > 1:
aText = 'Support for custom grains with multiple cores is experimental'
errors.append(SimAlert(SimAlertLevel.WARNING, SimAlertType.GEOMETRY, aText))
return errors
openmotor-0.6.0/motorlib/grains/dGrain.py 0000664 0000000 0000000 00000002762 15005301746 0020437 0 ustar 00root root 0000000 0000000 """D Grain submodule"""
from ..grain import FmmGrain
from ..properties import FloatProperty
from ..simResult import SimAlert, SimAlertLevel, SimAlertType
class DGrain(FmmGrain):
"""Defines a D grain, which is a grain that has no propellant past a chord that is a user-specified distance from
the diameter."""
geomName = 'D Grain'
def __init__(self):
super().__init__()
self.props['slotOffset'] = FloatProperty('Slot offset', 'm', -1, 1)
self.props['slotOffset'].setValue(0)
def generateCoreMap(self):
slotOffset = self.normalize(self.props['slotOffset'].getValue())
self.coreMap[self.mapX > slotOffset] = 0
def getDetailsString(self, lengthUnit='m'):
return 'Length: {}, Slot offset: {}'.format(self.props['length'].dispFormat(lengthUnit),
self.props['slotOffset'].dispFormat(lengthUnit))
def getGeometryErrors(self):
errors = super().getGeometryErrors()
if self.props['slotOffset'].getValue() > self.props['diameter'].getValue() / 2:
aText = 'Core offset must not be greater than grain radius'
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.GEOMETRY, aText))
if self.props['slotOffset'].getValue() < -self.props['diameter'].getValue() / 2:
aText = 'Core offset must be greater than negative grain radius'
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.GEOMETRY, aText))
return errors
openmotor-0.6.0/motorlib/grains/endBurner.py 0000664 0000000 0000000 00000001724 15005301746 0021154 0 ustar 00root root 0000000 0000000 """End Burner submodule"""
from ..grain import Grain
from ..import geometry
class EndBurningGrain(Grain):
"""Defines an end-burning grain, which is a simple cylinder that burns on one end."""
geomName = 'End Burner'
def getSurfaceAreaAtRegression(self, regDist):
diameter = self.props['diameter'].getValue()
return geometry.circleArea(diameter)
def getVolumeAtRegression(self, regDist):
bLength = self.getRegressedLength(regDist)
diameter = self.props['diameter'].getValue()
return geometry.cylinderVolume(diameter, bLength)
def simulationSetup(self, config):
pass
def getWebLeft(self, regDist):
return self.getRegressedLength(regDist)
def getMassFlux(self, massIn, dTime, regDist, dRegDist, position, density):
return 0
def getPortArea(self, regDist):
return None
def getEndPositions(self, regDist):
return (0, self.props['length'].getValue() - regDist)
openmotor-0.6.0/motorlib/grains/finocyl.py 0000664 0000000 0000000 00000012631 15005301746 0020672 0 ustar 00root root 0000000 0000000 """Finocyl grain submodule"""
import numpy as np
from ..grain import FmmGrain
from ..properties import FloatProperty, IntProperty, BooleanProperty
from ..simResult import SimAlert, SimAlertLevel, SimAlertType
class Finocyl(FmmGrain):
"""A finocyl (fins on cylinder) grain has a circular core with a number of rectangular extensions that start at the
circle's edge and protude along its normals."""
geomName = 'Finocyl'
def __init__(self):
super().__init__()
self.props['numFins'] = IntProperty('Number of fins', '', 0, 64)
self.props['finWidth'] = FloatProperty('Fin width', 'm', 0, 1)
self.props['finLength'] = FloatProperty('Fin length', 'm', 0, 1)
self.props['coreDiameter'] = FloatProperty('Core diameter', 'm', 0, 1)
self.props['invertedFins'] = BooleanProperty('Inverted fins')
def generateCoreMap(self):
coreRadius = self.normalize(self.props['coreDiameter'].getValue()) / 2
numFins = self.props['numFins'].getValue()
finWidth = self.normalize(self.props['finWidth'].getValue())
finLength = self.normalize(self.props['finLength'].getValue())
invertedFins = self.props['invertedFins'].getValue()
finStart = coreRadius - finLength if invertedFins else 0
finEnd = coreRadius if invertedFins else finLength + coreRadius
# Open up core
self.coreMap[self.mapX**2 + self.mapY**2 < coreRadius**2] = 0
# Add fins
for i in range(0, numFins):
theta = 2 * np.pi / numFins * i
# Initialize a vector pointing along the fin
vect0 = np.cos(theta)
vect1 = np.sin(theta)
# Select all points within half the width of the vector
vect = abs(vect0*self.mapX + vect1*self.mapY) < finWidth / 2
# Set up two perpendicular vectors to cap off the ends
near = (vect1 * self.mapX) - (vect0 * self.mapY) > finStart
far = (vect1 * self.mapX) - (vect0 * self.mapY) < finEnd
ends = np.logical_and(far, near)
# For inverted fins, we are filling propellant back in. For regular fins, we are removing it.
self.coreMap[np.logical_and(vect, ends)] = invertedFins
def getDetailsString(self, lengthUnit='m'):
return 'Length: {}, Core: {}, Fins: {}'.format(self.props['length'].dispFormat(lengthUnit),
self.props['coreDiameter'].dispFormat(lengthUnit),
self.props['numFins'].getValue())
def getGeometryErrors(self):
errors = super().getGeometryErrors()
if self.props['coreDiameter'].getValue() == 0:
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.GEOMETRY, 'Core diameter must not be 0'))
if self.props['coreDiameter'].getValue() >= self.props['diameter'].getValue():
aText = 'Core diameter must be less than or equal to grain diameter'
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.GEOMETRY, aText))
if self.props['finLength'].getValue() == 0:
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.GEOMETRY, 'Fin length must not be 0'))
if self.props['finLength'].getValue() * 2 > self.props['diameter'].getValue():
aText = 'Fin length should be less than or equal to grain radius'
errors.append(SimAlert(SimAlertLevel.WARNING, SimAlertType.GEOMETRY, aText))
if self.props['invertedFins'].getValue():
coreRadius = self.props['coreDiameter'].getValue() / 2
# In the weird case of one fin that extends beyond the core, we need to make sure it doesn't
# intersect the core again on the other side as that would divide the port
if self.props['finLength'].getValue() > coreRadius:
lengthPastCenter = self.props['finLength'].getValue() - coreRadius
halfWidth = self.props['finWidth'].getValue() / 2
tipRadius = (lengthPastCenter ** 2 + halfWidth ** 2) ** 0.5
if tipRadius > coreRadius and self.props['numFins'].getValue() > 0:
aText = 'Fin tips outside of core'
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.GEOMETRY, aText))
else:
coreWidth = self.props['coreDiameter'].getValue() + (2 * self.props['finLength'].getValue())
if coreWidth > self.props['diameter'].getValue():
aText = 'Core radius plus fin length should be less than or equal to grain radius'
errors.append(SimAlert(SimAlertLevel.WARNING, SimAlertType.GEOMETRY, aText))
if self.props['finWidth'].getValue() == 0:
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.GEOMETRY, 'Fin width must not be 0'))
if self.props['numFins'].getValue() > 1:
radius = self.props['coreDiameter'].getValue() / 2
finLength = self.props['finLength'].getValue()
invertedFins = self.props['invertedFins'].getValue()
level = SimAlertLevel.ERROR if invertedFins else SimAlertLevel.WARNING
apothem = radius - finLength if invertedFins else radius + finLength
sideLength = 2 * apothem * np.tan(np.pi / self.props['numFins'].getValue())
if sideLength < self.props['finWidth'].getValue():
errors.append(SimAlert(level, SimAlertType.GEOMETRY, 'Fin tips intersect'))
return errors
openmotor-0.6.0/motorlib/grains/moonBurner.py 0000664 0000000 0000000 00000003470 15005301746 0021356 0 ustar 00root root 0000000 0000000 """Moon burning grain submodule"""
from ..grain import FmmGrain
from ..properties import FloatProperty
from ..simResult import SimAlert, SimAlertLevel, SimAlertType
class MoonBurner(FmmGrain):
"""A moonburner is very similar to a BATES grain except the core is off center by a specified distance."""
geomName = 'Moon Burner'
def __init__(self):
super().__init__()
self.props['coreOffset'] = FloatProperty('Core offset', 'm', 0, 1)
self.props['coreDiameter'] = FloatProperty('Core diameter', 'm', 0, 1)
def generateCoreMap(self):
coreRadius = self.normalize(self.props['coreDiameter'].getValue()) / 2
coreOffset = self.normalize(self.props['coreOffset'].getValue())
# Open up core
self.coreMap[(self.mapX - coreOffset)**2 + self.mapY**2 < coreRadius**2] = 0
def getDetailsString(self, lengthUnit='m'):
return 'Length: {}, Core: {}'.format(self.props['length'].dispFormat(lengthUnit),
self.props['coreDiameter'].dispFormat(lengthUnit))
def getGeometryErrors(self):
errors = super().getGeometryErrors()
if self.props['coreDiameter'].getValue() == 0:
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.GEOMETRY, 'Core diameter must not be 0'))
if self.props['coreDiameter'].getValue() >= self.props['diameter'].getValue():
aText = 'Core diameter must be less than or equal to grain diameter'
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.GEOMETRY, aText))
if self.props['coreOffset'].getValue() * 2 > self.props['diameter'].getValue():
aText = 'Core offset should be less than or equal to grain radius'
errors.append(SimAlert(SimAlertLevel.WARNING, SimAlertType.GEOMETRY, aText))
return errors
openmotor-0.6.0/motorlib/grains/rodTube.py 0000664 0000000 0000000 00000012561 15005301746 0020635 0 ustar 00root root 0000000 0000000 """Rod and Tube submodule"""
import numpy as np
import skfmm
from skimage import measure
from ..grain import PerforatedGrain
from .. import geometry
from ..simResult import SimAlert, SimAlertLevel, SimAlertType
from ..properties import FloatProperty
class RodTubeGrain(PerforatedGrain):
"""Tbe rod and tube grain resembles a BATES grain except that it features a fully-uninhibited rod of propellant in
the center of the core."""
geomName = "Rod and Tube"
def __init__(self):
super().__init__()
self.props['coreDiameter'] = FloatProperty('Core Diameter', 'm', 0, 1)
self.props['rodDiameter'] = FloatProperty('Rod Diameter', 'm', 0, 1)
self.props['supportDiameter'] = FloatProperty('Support Diameter', 'm', 0, 1)
self.tubeWeb = None
self.rodWeb = None
def simulationSetup(self, config):
self.tubeWeb = (self.props['diameter'].getValue() - self.props['coreDiameter'].getValue()) / 2
self.rodWeb = (self.props['rodDiameter'].getValue() - self.props['supportDiameter'].getValue()) / 2
self.wallWeb = max(self.tubeWeb, self.rodWeb)
def getCorePerimeter(self, regDist):
if regDist < self.tubeWeb:
tubePerimeter = geometry.circlePerimeter(self.props['coreDiameter'].getValue() + (2 * regDist))
else:
tubePerimeter = 0
if regDist < self.rodWeb:
rodPerimeter = geometry.circlePerimeter(self.props['rodDiameter'].getValue() - (2 * regDist))
else:
rodPerimeter = 0
return tubePerimeter + rodPerimeter
def getFaceArea(self, regDist):
if regDist < self.tubeWeb:
outer = geometry.circleArea(self.props['diameter'].getValue())
inner = geometry.circleArea(self.props['coreDiameter'].getValue() + (2 * regDist))
tubeArea = outer - inner
else:
tubeArea = 0
if regDist < self.rodWeb:
outer = geometry.circleArea(self.props['rodDiameter'].getValue() - (2 * regDist))
inner = geometry.circleArea(self.props['supportDiameter'].getValue())
rodArea = outer - inner
else:
rodArea = 0
return tubeArea + rodArea
def getDetailsString(self, lengthUnit='m'):
return 'Length: {}, Core: {}, Rod: {}'.format(self.props['length'].dispFormat(lengthUnit),
self.props['coreDiameter'].dispFormat(lengthUnit),
self.props['rodDiameter'].dispFormat(lengthUnit))
def getGeometryErrors(self):
errors = super().getGeometryErrors()
if self.props['coreDiameter'].getValue() == 0:
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.GEOMETRY, 'Core diameter must not be 0'))
if self.props['coreDiameter'].getValue() >= self.props['diameter'].getValue():
aText = 'Core diameter must be less than grain diameter'
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.GEOMETRY, aText))
if self.props['rodDiameter'].getValue() >= self.props['coreDiameter'].getValue():
aText = 'Rod diameter must be less than core diameter'
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.GEOMETRY, aText))
return errors
# These two functions have a lot of code reuse, but it is worth it because making this an fmmGrain would make it
# signficantly way slower
def getFaceImage(self, mapDim):
# Normalize core and rod diameters
coreRadius = (self.props['coreDiameter'].getValue() / (0.5 * self.props['diameter'].getValue())) / 2
rodRadius = (self.props['rodDiameter'].getValue() / (0.5 * self.props['diameter'].getValue())) / 2
supportRadius = (self.props['supportDiameter'].getValue() / (0.5 * self.props['diameter'].getValue())) / 2
mapX, mapY = np.meshgrid(np.linspace(-1, 1, mapDim), np.linspace(-1, 1, mapDim))
mask = np.logical_or(mapX**2 + mapY**2 > 1, mapX**2 + mapY**2 < supportRadius ** 2)
coreMap = np.ones_like(mapX)
# Open up core
coreMap[mapX ** 2 + mapY ** 2 < coreRadius ** 2] = 0
coreMap[mapX ** 2 + mapY ** 2 < rodRadius ** 2] = 1
coreMap[mapX ** 2 + mapY ** 2 < supportRadius ** 2] = 0
maskedMap = np.ma.MaskedArray(coreMap, mask)
return maskedMap
def getRegressionData(self, mapDim, numContours=15, coreBlack=True):
masked = self.getFaceImage(mapDim)
regressionMap = None
contours = []
contourLengths = {}
try:
cellSize = 1 / mapDim
regressionMap = skfmm.distance(masked, dx=cellSize) * 2
regmax = np.amax(regressionMap)
regressionMap = regressionMap[:, :].copy()
if coreBlack:
regressionMap[np.where(masked == 0)] = regmax # Make the core black
for dist in np.linspace(0, regmax, numContours):
contours.append([])
contourLengths[dist] = 0
layerContours = measure.find_contours(regressionMap, dist, fully_connected='high')
for contour in layerContours:
contours[-1].append(contour)
contourLengths[dist] += geometry.length(contour, mapDim)
except ValueError as exc: # If there aren't any contours, do nothing
print(exc)
return (masked, regressionMap, contours, contourLengths)
openmotor-0.6.0/motorlib/grains/star.py 0000664 0000000 0000000 00000004471 15005301746 0020203 0 ustar 00root root 0000000 0000000 """Star grain submodule"""
import numpy as np
from ..grain import FmmGrain
from ..properties import IntProperty, FloatProperty
from ..simResult import SimAlert, SimAlertLevel, SimAlertType
class StarGrain(FmmGrain):
"""A star grain has a core shaped like a star."""
geomName = 'Star Grain'
def __init__(self):
super().__init__()
self.props['numPoints'] = IntProperty('Number of points', '', 0, 64)
self.props['pointLength'] = FloatProperty('Point length', 'm', 0, 1)
self.props['pointWidth'] = FloatProperty('Point base width', 'm', 0, 1)
def generateCoreMap(self):
numPoints = self.props['numPoints'].getValue()
pointWidth = self.normalize(self.props['pointWidth'].getValue())
pointLength = self.normalize(self.props['pointLength'].getValue())
for i in range(0, numPoints):
theta = 2 * np.pi / numPoints * i
comp0 = np.cos(theta)
comp1 = np.sin(theta)
rect = abs(comp0 * self.mapX + comp1 * self.mapY)
width = pointWidth / 2 * (1 - (((self.mapX ** 2 + self.mapY ** 2) ** 0.5) / pointLength))
vect = rect < width
near = comp1*self.mapX - comp0*self.mapY > -0.025
self.coreMap[np.logical_and(vect, near)] = 0
def getDetailsString(self, lengthUnit='m'):
return 'Length: {}, Points: {}'.format(self.props['length'].dispFormat(lengthUnit),
self.props['numPoints'].getValue())
def getGeometryErrors(self):
errors = super().getGeometryErrors()
if self.props['numPoints'].getValue() == 0:
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.GEOMETRY, 'Star grain has 0 points'))
if self.props['pointLength'].getValue() == 0:
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.GEOMETRY, 'Point length must not be 0'))
if self.props['pointLength'].getValue() * 2 > self.props['diameter'].getValue():
aText = 'Point length should be less than or equal to grain radius'
errors.append(SimAlert(SimAlertLevel.WARNING, SimAlertType.GEOMETRY, aText))
if self.props['pointWidth'].getValue() == 0:
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.GEOMETRY, 'Point width must not be 0'))
return errors
openmotor-0.6.0/motorlib/grains/xCore.py 0000664 0000000 0000000 00000004166 15005301746 0020313 0 ustar 00root root 0000000 0000000 """X Core grain submodule"""
import numpy as np
from ..grain import FmmGrain
from ..properties import FloatProperty
from ..simResult import SimAlert, SimAlertLevel, SimAlertType
class XCore(FmmGrain):
"""An X Core grain has a core shaped like a plus sign or an X."""
geomName = 'X Core'
def __init__(self):
super().__init__()
self.props['slotWidth'] = FloatProperty('Slot width', 'm', 0, 1)
self.props['slotLength'] = FloatProperty('Slot length', 'm', 0, 1)
def generateCoreMap(self):
slotWidth = self.normalize(self.props['slotWidth'].getValue())
slotLength = self.normalize(self.props['slotLength'].getValue())
self.coreMap[np.logical_and(np.abs(self.mapY) < slotWidth/2, np.abs(self.mapX) < slotLength)] = 0
self.coreMap[np.logical_and(np.abs(self.mapX) < slotWidth/2, np.abs(self.mapY) < slotLength)] = 0
def getDetailsString(self, lengthUnit='m'):
return 'Length: {}, Slots: {} by {}'.format(self.props['length'].dispFormat(lengthUnit),
self.props['slotWidth'].dispFormat(lengthUnit),
self.props['slotLength'].dispFormat(lengthUnit))
def getGeometryErrors(self):
errors = super().getGeometryErrors()
if self.props['slotWidth'].getValue() == 0:
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.GEOMETRY, 'Slot width must not be 0'))
if self.props['slotWidth'].getValue() > self.props['diameter'].getValue():
aText = 'Slot width should be less than or equal to grain diameter'
errors.append(SimAlert(SimAlertLevel.WARNING, SimAlertType.GEOMETRY, aText))
if self.props['slotLength'].getValue() == 0:
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.GEOMETRY, 'Slot length must not be 0'))
if self.props['slotLength'].getValue() * 2 > self.props['diameter'].getValue():
aText = 'Slot length should be less than or equal to grain radius'
errors.append(SimAlert(SimAlertLevel.WARNING, SimAlertType.GEOMETRY, aText))
return errors
openmotor-0.6.0/motorlib/motor.py 0000664 0000000 0000000 00000041042 15005301746 0017102 0 ustar 00root root 0000000 0000000 """Conains the motor class and a supporting configuration property collection."""
from .grains import grainTypes
from .nozzle import Nozzle
from .propellant import Propellant
from . import geometry
from .simResult import SimulationResult, SimAlert, SimAlertLevel, SimAlertType
from .grains import EndBurningGrain
from .properties import PropertyCollection, FloatProperty, IntProperty
from .constants import gasConstant
class MotorConfig(PropertyCollection):
"""Contains the settings required for simulation, including environmental conditions and details about
how to run the simulation."""
def __init__(self):
super().__init__()
# Limits
self.props['maxPressure'] = FloatProperty('Maximum Allowed Pressure', 'Pa', 0, 7e7)
self.props['maxMassFlux'] = FloatProperty('Maximum Allowed Mass Flux', 'kg/(m^2*s)', 0, 1e4)
self.props['minPortThroat'] = FloatProperty('Minimum Allowed Port/Throat Ratio', '', 1, 4)
self.props['flowSeparationWarnPercent'] = FloatProperty('Flow Separation Warning Threshold', '', 0.00, 1)
# Simulation
self.props['burnoutWebThres'] = FloatProperty('Web Burnout Threshold', 'm', 2.54e-5, 3.175e-3)
self.props['burnoutThrustThres'] = FloatProperty('Thrust Burnout Threshold', '%', 0.01, 10)
self.props['timestep'] = FloatProperty('Simulation Timestep', 's', 0.0001, 0.1)
self.props['ambPressure'] = FloatProperty('Ambient Pressure', 'Pa', 0.0001, 102000)
self.props['mapDim'] = IntProperty('Grain Map Dimension', '', 250, 2000)
self.props['sepPressureRatio'] = FloatProperty('Separation Pressure Ratio', '', 0.001, 1)
class Motor():
"""The motor class stores a number of grains, a nozzle instance, a propellant, and a configuration that it uses
to run simulations. Simulations return a simRes object that includes any warnings or errors associated with the
simulation and the data. The propellant field may be None if the motor has no propellant set, and the grains list
is allowed to be empty. The nozzle field and config must be filled, even if they are empty property collections."""
def __init__(self, propDict=None):
self.grains = []
self.propellant = None
self.nozzle = Nozzle()
self.config = MotorConfig()
if propDict is not None:
self.applyDict(propDict)
def getDict(self):
"""Returns a serializable representation of the motor. The dictionary has keys 'nozzle', 'propellant',
'grains', and 'config', which hold to the properties of their corresponding fields. Grains is a list
of dicts, each containing a type and properties. Propellant may be None if the motor has no propellant
set."""
motorData = {}
motorData['nozzle'] = self.nozzle.getProperties()
if self.propellant is not None:
motorData['propellant'] = self.propellant.getProperties()
else:
motorData['propellant'] = None
motorData['grains'] = [{'type': grain.geomName, 'properties': grain.getProperties()} for grain in self.grains]
motorData['config'] = self.config.getProperties()
return motorData
def applyDict(self, dictionary):
"""Makes the motor copy properties from the dictionary that is passed in, which must be formatted like
the result passed out by 'getDict'"""
self.nozzle.setProperties(dictionary['nozzle'])
if dictionary['propellant'] is not None:
self.propellant = Propellant(dictionary['propellant'])
else:
self.propellant = None
self.grains = []
for entry in dictionary['grains']:
self.grains.append(grainTypes[entry['type']]())
self.grains[-1].setProperties(entry['properties'])
self.config.setProperties(dictionary['config'])
def calcBurningSurfaceArea(self, regDepth):
burnoutThres = self.config.getProperty('burnoutWebThres')
gWithReg = zip(self.grains, regDepth)
perGrain = [gr.getSurfaceAreaAtRegression(reg) * int(gr.isWebLeft(reg, burnoutThres)) for gr, reg in gWithReg]
return sum(perGrain)
def calcKN(self, regDepth, dThroat):
"""Returns the motor's Kn when it has each grain has regressed by its value in regDepth, which should be a list
with the same number of elements as there are grains in the motor."""
burningSurfaceArea = self.calcBurningSurfaceArea(regDepth)
nozzleArea = self.nozzle.getThroatArea(dThroat)
return burningSurfaceArea / nozzleArea
def calcIdealPressure(self, regDepth, dThroat, kn=None):
"""Returns the steady-state pressure of the motor at a given reg. Kn is calculated automatically, but it can
optionally be passed in to save time on motors where calculating surface area is expensive."""
if kn is None:
kn = self.calcKN(regDepth, dThroat)
return self.propellant.getPressureFromKn(kn)
def calcForce(self, chamberPres, dThroat, exitPres=None):
"""Calculates the force of the motor at a given regression depth per grain. Calculates exit pressure by
default, but can also use a value passed in."""
_, _, gamma, _, _ = self.propellant.getCombustionProperties(chamberPres)
ambPressure = self.config.getProperty('ambPressure')
thrustCoeff = self.nozzle.getAdjustedThrustCoeff(chamberPres, ambPressure, gamma, dThroat, exitPres)
thrust = thrustCoeff * self.nozzle.getThroatArea(dThroat) * chamberPres
return max(thrust, 0)
def calcFreeVolume(self, regDepth):
"""Calculates the volume inside of the motor not occupied by proppellant for a set of regression depths."""
return sum([grain.getFreeVolume(reg) for grain, reg in zip(self.grains, regDepth)])
def calcTotalVolume(self):
"""Calculates the bounding-cylinder volume of the combustion chamber."""
return sum([grain.getGrainBoundingVolume() for grain in self.grains])
def runSimulation(self, callback=None):
"""Runs a simulation of the motor and returns a simRes instance with the results. Constraints are checked,
including the number of grains, if the motor has a propellant set, and if the grains have geometry errors. If
all of these tests are passed, the motor's operation is simulated by calculating Kn, using this value to get
pressure, and using pressure to determine thrust and other statistics. The next timestep is then prepared by
using the pressure to determine how the motor will regress in the given timestep at the current pressure.
This process is repeated and regression tracked until all grains have burned out, when the results and any
warnings are returned."""
burnoutWebThres = self.config.getProperty('burnoutWebThres')
burnoutThrustThres = self.config.getProperty('burnoutThrustThres')
dTime = self.config.getProperty('timestep')
simRes = SimulationResult(self)
# Check for geometry errors
if len(self.grains) == 0:
aText = 'Motor must have at least one propellant grain'
simRes.addAlert(SimAlert(SimAlertLevel.ERROR, SimAlertType.CONSTRAINT, aText, 'Motor'))
for gid, grain in enumerate(self.grains):
if isinstance(grain, EndBurningGrain) and gid != 0: # Endburners have to be at the foward end
aText = 'End burning grains must be the forward-most grain in the motor'
simRes.addAlert(SimAlert(SimAlertLevel.ERROR, SimAlertType.CONSTRAINT, aText, 'Grain {}'.format(gid + 1)))
for alert in grain.getGeometryErrors():
alert.location = 'Grain {}'.format(gid + 1)
simRes.addAlert(alert)
for alert in self.nozzle.getGeometryErrors():
simRes.addAlert(alert)
# Make sure the motor has a propellant set
if self.propellant is None:
alert = SimAlert(SimAlertLevel.ERROR, SimAlertType.CONSTRAINT, 'Motor must have a propellant set', 'Motor')
simRes.addAlert(alert)
else:
for alert in self.propellant.getErrors():
simRes.addAlert(alert)
# If any errors occurred, stop simulation and return an empty sim with errors
if len(simRes.getAlertsByLevel(SimAlertLevel.ERROR)) > 0:
return simRes
# Pull the required numbers from the propellant
density = self.propellant.getProperty('density')
# Precalculate these are they don't change
motorVolume = self.calcTotalVolume()
# Generate coremaps for perforated grains
for grain in self.grains:
grain.simulationSetup(self.config)
# Setup initial values
perGrainReg = [0 for grain in self.grains]
# At t = 0, the motor has ignited
simRes.channels['time'].addData(0)
simRes.channels['kn'].addData(self.calcKN(perGrainReg, 0))
simRes.channels['pressure'].addData(self.calcIdealPressure(perGrainReg, 0, None))
simRes.channels['force'].addData(0)
simRes.channels['mass'].addData([grain.getVolumeAtRegression(0) * density for grain in self.grains])
simRes.channels['volumeLoading'].addData(100 * (1 - (self.calcFreeVolume(perGrainReg) / motorVolume)))
simRes.channels['massFlow'].addData([0 for grain in self.grains])
simRes.channels['massFlux'].addData([0 for grain in self.grains])
simRes.channels['regression'].addData([0 for grains in self.grains])
simRes.channels['web'].addData([grain.getWebLeft(0) for grain in self.grains])
simRes.channels['exitPressure'].addData(0)
simRes.channels['dThroat'].addData(0)
# Check port/throat ratio and add a warning if it is not large enough
aftPort = self.grains[-1].getPortArea(0)
if aftPort is not None:
minAllowed = self.config.getProperty('minPortThroat')
ratio = aftPort / geometry.circleArea(self.nozzle.props['throat'].getValue())
if ratio < minAllowed:
description = 'Initial port/throat ratio of {:.3f} was less than {:.3f}'.format(ratio, minAllowed)
simRes.addAlert(SimAlert(SimAlertLevel.WARNING, SimAlertType.CONSTRAINT, description, 'N/A'))
# Perform timesteps
while simRes.shouldContinueSim(burnoutThrustThres):
# Calculate regression
massFlow = 0
perGrainMass = [0 for grain in self.grains]
perGrainMassFlow = [0 for grain in self.grains]
perGrainMassFlux = [0 for grain in self.grains]
perGrainWeb = [0 for grain in self.grains]
for gid, grain in enumerate(self.grains):
if grain.getWebLeft(perGrainReg[gid]) > burnoutWebThres:
# Calculate regression at the current pressure
reg = dTime * self.propellant.getBurnRate(simRes.channels['pressure'].getLast())
# Find the mass flux through the grain based on the mass flow fed into from grains above it
perGrainMassFlux[gid] = grain.getPeakMassFlux(massFlow, dTime, perGrainReg[gid], reg, density)
# Find the mass of the grain after regression
perGrainMass[gid] = grain.getVolumeAtRegression(perGrainReg[gid]) * density
# Add the change in grain mass to the mass flow
massFlow += (simRes.channels['mass'].getLast()[gid] - perGrainMass[gid]) / dTime
# Apply the regression
perGrainReg[gid] += reg
perGrainWeb[gid] = grain.getWebLeft(perGrainReg[gid])
perGrainMassFlow[gid] = massFlow
simRes.channels['regression'].addData(perGrainReg[:])
simRes.channels['web'].addData(perGrainWeb)
simRes.channels['volumeLoading'].addData(100 * (1 - (self.calcFreeVolume(perGrainReg) / motorVolume)))
simRes.channels['mass'].addData(perGrainMass)
simRes.channels['massFlow'].addData(perGrainMassFlow)
simRes.channels['massFlux'].addData(perGrainMassFlux)
# Calculate KN
dThroat = simRes.channels['dThroat'].getLast()
simRes.channels['kn'].addData(self.calcKN(perGrainReg, dThroat))
# Calculate Pressure
lastKn = simRes.channels['kn'].getLast()
pressure = self.calcIdealPressure(perGrainReg, dThroat, lastKn)
simRes.channels['pressure'].addData(pressure)
# Calculate Exit Pressure
_, _, gamma, _, _ = self.propellant.getCombustionProperties(pressure)
exitPressure = self.nozzle.getExitPressure(gamma, pressure)
simRes.channels['exitPressure'].addData(exitPressure)
# Calculate force
force = self.calcForce(simRes.channels['pressure'].getLast(), dThroat, exitPressure)
simRes.channels['force'].addData(force)
simRes.channels['time'].addData(simRes.channels['time'].getLast() + dTime)
# Calculate any slag deposition or erosion of the throat
if pressure == 0:
slagRate = 0
else:
slagRate = (1 / pressure) * self.nozzle.getProperty('slagCoeff')
erosionRate = pressure * self.nozzle.getProperty('erosionCoeff')
change = dTime * ((-2 * slagRate) + (2 * erosionRate))
simRes.channels['dThroat'].addData(dThroat + change)
if callback is not None:
# Uses the grain with the largest percentage of its web left
progress = max([g.getWebLeft(r) / g.getWebLeft(0) for g, r in zip(self.grains, perGrainReg)])
if callback(1 - progress): # If the callback returns true, it is time to cancel
return simRes
simRes.success = True
if simRes.getPeakMassFlux() > self.config.getProperty('maxMassFlux'):
desc = 'Peak mass flux exceeded configured limit'
alert = SimAlert(SimAlertLevel.WARNING, SimAlertType.CONSTRAINT, desc, 'Motor')
simRes.addAlert(alert)
if simRes.getMaxPressure() > self.config.getProperty('maxPressure'):
desc = 'Max pressure exceeded configured limit'
alert = SimAlert(SimAlertLevel.WARNING, SimAlertType.CONSTRAINT, desc, 'Motor')
simRes.addAlert(alert)
if (simRes.getPercentBelowThreshold('exitPressure', self.config.getProperty('ambPressure') * self.config.getProperty('sepPressureRatio')) > self.config.getProperty('flowSeparationWarnPercent')):
desc = 'Low exit pressure, nozzle flow may separate'
alert = SimAlert(SimAlertLevel.WARNING, SimAlertType.VALUE, desc, 'Nozzle')
simRes.addAlert(alert)
if simRes.getAverageForce() < burnoutThrustThres:
desc = 'Motor did not generate thrust. Check chamber pressure and expansion ratio.'
alert = SimAlert(SimAlertLevel.ERROR, SimAlertType.VALUE, desc, 'Motor')
simRes.addAlert(alert)
# Note that this only adds all errors found on the first datapoint where there were errors to avoid repeating
# errors. It should be revisited if getPressureErrors ever returns multiple types of errors
for pressure in simRes.channels['pressure'].getData():
if pressure > 0:
err = self.propellant.getPressureErrors(pressure)
if len(err) > 0:
simRes.addAlert(err[0])
break
return simRes
def getQuickResults(self):
results = {
'volumeLoading': 0,
'initialKn': 0,
'propellantMass': 0,
'portRatio': 0,
'length': 0
}
simRes = SimulationResult(self)
density = self.propellant.getProperty('density') if self.propellant is not None else None
throatArea = self.nozzle.getThroatArea()
motorVolume = self.calcTotalVolume()
if motorVolume == 0:
return results
# Generate coremaps for perforated grains
for grain in self.grains:
for alert in grain.getGeometryErrors():
if alert.level == SimAlertLevel.ERROR:
return results
grain.simulationSetup(self.config)
perGrainReg = [0 for grain in self.grains]
results['volumeLoading'] = 100 * (1 - (self.calcFreeVolume(perGrainReg) / motorVolume))
if throatArea != 0:
results['initialKn'] = self.calcKN(perGrainReg, 0)
results['portRatio'] = simRes.getPortRatio()
if density is not None:
results['propellantMass'] = sum([grain.getVolumeAtRegression(0) * density for grain in self.grains])
results['length'] = simRes.getPropellantLength()
return results
openmotor-0.6.0/motorlib/nozzle.py 0000664 0000000 0000000 00000014123 15005301746 0017263 0 ustar 00root root 0000000 0000000 """This submodule houses the nozzle object and functions related to isentropic flow"""
import math
from scipy.optimize import fsolve
from .properties import FloatProperty, PropertyCollection
from . import geometry
from .simResult import SimAlert, SimAlertLevel, SimAlertType
def eRatioFromPRatio(k, pRatio):
"""Returns the expansion ratio of a nozzle given the pressure ratio it causes."""
return (((k+1)/2)**(1/(k-1))) * (pRatio ** (1/k)) * ((((k+1)/(k-1))*(1-(pRatio**((k-1)/k))))**0.5)
class Nozzle(PropertyCollection):
"""An object that contains the details about a motor's nozzle."""
def __init__(self):
super().__init__()
self.props['throat'] = FloatProperty('Throat Diameter', 'm', 0, 0.5)
self.props['exit'] = FloatProperty('Exit Diameter', 'm', 0, 1)
self.props['efficiency'] = FloatProperty('Efficiency', '', 0, 2)
self.props['divAngle'] = FloatProperty('Divergence Half Angle', 'deg', 0, 90)
self.props['convAngle'] = FloatProperty('Convergence Half Angle', 'deg', 0, 90)
self.props['throatLength'] = FloatProperty('Throat Length', 'm', 0, 0.5)
self.props['slagCoeff'] = FloatProperty('Slag Buildup Coefficient', '(m*Pa)/s', 0, 1e6)
self.props['erosionCoeff'] = FloatProperty('Throat Erosion Coefficient', 'm/(s*Pa)', 0, 1e6)
def getDetailsString(self, lengthUnit='m'):
"""Returns a human-readable string containing some details about the nozzle."""
return 'Throat: {}'.format(self.props['throat'].dispFormat(lengthUnit))
def calcExpansion(self):
"""Returns the nozzle's expansion ratio."""
return (self.props['exit'].getValue() / self.props['throat'].getValue()) ** 2
def getThroatArea(self, dThroat=0):
"""Returns the area of the nozzle's throat. The optional parameter is added on to the nozzle throat diameter
allow erosion or slag buildup during a burn."""
return geometry.circleArea(self.props['throat'].getValue() + dThroat)
def getExitArea(self):
"""Return the area of the nozzle's exit."""
return geometry.circleArea(self.props['exit'].getValue())
def getExitPressure(self, k, inputPressure):
"""Solves for the nozzle's exit pressure, given an input pressure and the gas's specific heat ratio."""
return fsolve(lambda x: (1/self.calcExpansion()) - eRatioFromPRatio(k, x / inputPressure), 0)[0]
def getDivergenceLosses(self):
"""Returns nozzle efficiency losses due to divergence angle"""
divAngleRad = math.radians(self.props["divAngle"].getValue())
return (1 + math.cos(divAngleRad)) / 2
def getThroatLosses(self, dThroat=0):
"""Returns the losses caused by the throat aspect ratio as described in this document:
http://rasaero.com/dloads/Departures%20from%20Ideal%20Performance.pdf"""
throatAspect = self.props['throatLength'].getValue() / (self.props['throat'].getValue() + dThroat)
if throatAspect > 0.45:
return 0.95
return 0.99 - (0.0333 * throatAspect)
def getSkinLosses(self):
"""Returns the losses due to drag on the nozzle surface as described here:
https://apps.dtic.mil/dtic/tr/fulltext/u2/a099791.pdf. This is a constant for now, as people likely don't have
a way to measure this themselves."""
return 0.99
def getIdealThrustCoeff(self, chamberPres, ambPres, gamma, dThroat, exitPres=None):
"""Calculates C_f, the ideal thrust coefficient for the nozzle, given the propellant's specific heat ratio, the
ambient and chamber pressures. If nozzle exit presure isn't provided, it will be calculated. dThroat is the
change in throat diameter due to erosion or slag accumulation."""
if chamberPres == 0:
return 0
if exitPres is None:
exitPres = self.getExitPressure(gamma, chamberPres)
exitArea = self.getExitArea()
throatArea = self.getThroatArea(dThroat)
term1 = (2 * (gamma ** 2)) / (gamma - 1)
term2 = (2 / (gamma + 1)) ** ((gamma + 1) / (gamma - 1))
term3 = 1 - ((exitPres / chamberPres) ** ((gamma - 1) / gamma))
momentumThrust = (term1 * term2 * term3) ** 0.5
pressureThrust = ((exitPres - ambPres) * exitArea) / (throatArea * chamberPres)
return momentumThrust + pressureThrust
def getAdjustedThrustCoeff(self, chamberPres, ambPres, gamma, dThroat, exitPres=None):
"""Calculates adjusted thrust coefficient for the nozzle, given the propellant's specific heat ratio, the
ambient and chamber pressures. If nozzle exit presure isn't provided, it will be calculated. dThroat is the
change in throat diameter due to erosion or slag accumulation. This method uses a combination of the techniques
described in these resources to adjust the thrust coefficient:
https://apps.dtic.mil/dtic/tr/fulltext/u2/a099791.pdf
http://rasaero.com/dloads/Departures%20from%20Ideal%20Performance.pdf"""
thrustCoeffIdeal = self.getIdealThrustCoeff(chamberPres, ambPres, gamma, dThroat, exitPres)
divLoss = self.getDivergenceLosses()
throatLoss = self.getThroatLosses(dThroat)
skinLoss = self.getSkinLosses()
efficiency = self.getProperty('efficiency')
return divLoss * throatLoss * efficiency * (skinLoss * thrustCoeffIdeal + (1 - skinLoss))
def getGeometryErrors(self):
"""Returns a list containing any errors with the nozzle's properties."""
errors = []
if self.props['throat'].getValue() == 0:
aText = 'Throat diameter must not be 0'
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.GEOMETRY, aText, 'Nozzle'))
if self.props['exit'].getValue() < self.props['throat'].getValue():
aText = 'Exit diameter must not be smaller than throat diameter'
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.GEOMETRY, aText, 'Nozzle'))
if self.props['efficiency'].getValue() == 0:
aText = 'Efficiency must not be 0'
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.CONSTRAINT, aText, 'Nozzle'))
return errors
openmotor-0.6.0/motorlib/propellant.py 0000664 0000000 0000000 00000015517 15005301746 0020132 0 ustar 00root root 0000000 0000000 """Propellant submodule that contains the propellant class."""
from scipy.optimize import fsolve
from .properties import PropertyCollection, FloatProperty, StringProperty, TabularProperty
from .simResult import SimAlert, SimAlertLevel, SimAlertType
from .constants import gasConstant
class PropellantTab(PropertyCollection):
"""Contains the combustion properties of a propellant over a specified pressure range."""
def __init__(self, tabDict=None):
super().__init__()
self.props['minPressure'] = FloatProperty('Minimum Pressure', 'Pa', 0, 7e7)
self.props['maxPressure'] = FloatProperty('Maximum Pressure', 'Pa', 0, 7e7)
self.props['a'] = FloatProperty('Burn rate Coefficient', 'm/(s*Pa^n)', 1E-8, 2)
self.props['n'] = FloatProperty('Burn rate Exponent', '', -0.99, 0.99)
self.props['k'] = FloatProperty('Specific Heat Ratio', '', 1+1e-6, 10)
self.props['t'] = FloatProperty('Combustion Temperature', 'K', 1, 10000)
self.props['m'] = FloatProperty('Exhaust Molar Mass', 'g/mol', 1e-6, 100)
if tabDict is not None:
self.setProperties(tabDict)
class Propellant(PropertyCollection):
"""Contains the physical and thermodynamic properties of a propellant formula."""
def __init__(self, propDict=None):
super().__init__()
self.props['name'] = StringProperty('Name')
self.props['density'] = FloatProperty('Density', 'kg/m^3', 1, 10000)
self.props['tabs'] = TabularProperty('Properties', PropellantTab)
if propDict is not None:
self.setProperties(propDict)
def getCStar(self, pressure):
"""Returns the propellant's characteristic velocity."""
_, _, gamma, temp, molarMass = self.getCombustionProperties(pressure)
num = (gamma * gasConstant / molarMass * temp)**0.5
denom = gamma * ((2 / (gamma + 1))**((gamma + 1) / (gamma - 1)))**0.5
return num / denom
def getBurnRate(self, pressure):
"""Returns the propellant's burn rate for the given pressure"""
ballA, ballN, _, _, _ = self.getCombustionProperties(pressure)
return ballA * (pressure ** ballN)
def getPressureFromKn(self, kn):
density = self.getProperty('density')
tabPressures = []
for tab in self.getProperty('tabs'):
ballA, ballN, gamma, temp, molarMass = tab['a'], tab['n'], tab['k'], tab['t'], tab['m']
num = kn * density * ballA
exponent = 1 / (1 - ballN)
denom = ((gamma / ((gasConstant / molarMass) * temp)) * ((2 / (gamma + 1)) ** ((gamma + 1) / (gamma - 1)))) ** 0.5
tabPressure = (num / denom) ** exponent
# If the pressure that a burnrate produces falls into its range, we know it is the proper burnrate
# Due to floating point error, we sometimes get a situation in which no burnrate produces the proper pressure
# For this scenario, we go by whichever produces the least error
minTabPressure = tab['minPressure']
maxTabPressure = tab['maxPressure']
if minTabPressure == self.getMinimumValidPressure() and tabPressure < maxTabPressure:
return tabPressure
if maxTabPressure == self.getMaximumValidPressure() and minTabPressure < tabPressure:
return tabPressure
if minTabPressure < tabPressure < maxTabPressure:
return tabPressure
tabPressures.append([min(abs(minTabPressure - tabPressure), abs(tabPressure - maxTabPressure)), tabPressure])
tabPressures.sort(key=lambda x: x[0]) # Sort by the pressure error
return tabPressures[0][1] # Return the pressure
def getKnFromPressure(self, pressure):
func = lambda kn: self.getPressureFromKn(kn) - pressure
return fsolve(func, [250], maxfev=1000)
def getCombustionProperties(self, pressure):
"""Returns the propellant's a, n, gamma, combustion temp and molar mass for a given pressure"""
closest = {}
closestPressure = 1e100
for tab in self.getProperty('tabs'):
if tab['minPressure'] < pressure < tab['maxPressure']:
return tab['a'], tab['n'], tab['k'], tab['t'], tab['m']
if abs(pressure - tab['minPressure']) < closestPressure:
closest = tab
closestPressure = abs(pressure - tab['minPressure'])
if abs(pressure - tab['maxPressure']) < closestPressure:
closest = tab
closestPressure = abs(pressure - tab['maxPressure'])
return closest['a'], closest['n'], closest['k'], closest['t'], closest['m']
def getMinimumValidPressure(self):
"""Returns the lowest pressure value with associated combustion properties"""
return min([tab['minPressure'] for tab in self.getProperty('tabs')])
def getMaximumValidPressure(self):
"""Returns the highest pressure value with associated combustion properties"""
return max([tab['maxPressure'] for tab in self.getProperty('tabs')])
def getErrors(self):
"""Checks that all tabs have smaller start pressures than their end pressures, and verifies that no ranges
overlap."""
errors = []
for tabId, tab in enumerate(self.getProperty('tabs')):
if tab['maxPressure'] == tab['minPressure']:
errText = 'Tab #{} has the same minimum and maximum pressures.'.format(tabId + 1)
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.VALUE, errText, 'Propellant'))
if tab['maxPressure'] < tab['minPressure']:
errText = 'Tab #{} has reversed pressure limits.'.format(tabId + 1)
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.VALUE, errText, 'Propellant'))
for otherTabId, otherTab in enumerate(self.getProperty('tabs')):
if tabId != otherTabId:
if otherTab['minPressure'] < tab['maxPressure'] < otherTab['maxPressure']:
err = 'Tabs #{} and #{} have overlapping ranges.'.format(tabId + 1, otherTabId + 1)
errors.append(SimAlert(SimAlertLevel.ERROR, SimAlertType.VALUE, err, 'Propellant'))
return errors
def getPressureErrors(self, pressure):
"""Returns if the propellant has any errors associated with the supplied pressure such as not having set
combustion properties"""
errors = []
for tab in self.getProperty('tabs'):
if tab['minPressure'] < pressure < tab['maxPressure']:
return errors
aText = "Chamber pressure deviated from propellant's entered ranges. Results may not be accurate."
errors.append(SimAlert(SimAlertLevel.WARNING, SimAlertType.VALUE, aText, 'Propellant'))
return errors
def addTab(self, tab):
"""Adds a set of combustion properties to the propellant"""
self.props['tabs'].addTab(tab)
openmotor-0.6.0/motorlib/properties.py 0000664 0000000 0000000 00000011375 15005301746 0020144 0 ustar 00root root 0000000 0000000 """This module includes a properties, which are objects that contain different datatypes and enforce conditions on
them, such as allowed ranges. They also can optionally associate a unit with the value, which aids with display and
conversion of the value."""
from . import units
class Property():
"""The base class that properties inherit from. It associates a human-readable display name with the data, as well
as a unit and value type that it casts all inputs to."""
def __init__(self, dispName, unit, valueType):
self.dispName = dispName
self.unit = unit
self.valueType = valueType
self.value = None
def setValue(self, value):
"""Set the value of the property, casting if necessary"""
self.value = self.valueType(value)
def getValue(self):
"""Returns the value of the property"""
return self.value
def dispFormat(self, unit):
"""Returns a human-readable version of the property's current value, including the unit."""
return '{} {}'.format(self.value, unit)
class FloatProperty(Property):
"""A property that handles floats. It forces the value to be in a certain range."""
def __init__(self, dispName, unit, minValue, maxValue):
super().__init__(dispName, unit, float)
self.min = minValue
self.max = maxValue
self.value = minValue
def setValue(self, value):
if self.min <= value <= self.max:
super().setValue(value)
def dispFormat(self, unit):
return '{:.6g} {}'.format(units.convert(self.value, self.unit, unit), unit)
class EnumProperty(Property):
"""This property operates on strings, but only allows values from a list that is set when the property is
defined"""
def __init__(self, dispName, values):
super().__init__(dispName, '', object)
self.values = values
self.value = self.values[0]
def contains(self, value):
"""Checks if a value is in the allowed list"""
return value in self.values
def setValue(self, value):
if self.contains(value):
self.value = value
class IntProperty(Property):
"""A property with an integer as the value that is clamped to a certain range."""
def __init__(self, dispName, unit, minValue, maxValue):
super().__init__(dispName, unit, int)
self.min = minValue
self.max = maxValue
self.value = minValue
def setValue(self, value):
if self.min <= value <= self.max:
super().setValue(value)
class StringProperty(Property):
"""A property that works on the set of all strings"""
def __init__(self, dispName):
super().__init__(dispName, '', str)
class BooleanProperty(Property):
"""A property with a single boolean as the value"""
def __init__(self, dispName):
super().__init__(dispName, '', bool)
class PolygonProperty(Property):
"""A property that contains a list of polygons, each a list of points"""
def __init__(self, dispName):
super().__init__(dispName, '', list)
self.value = []
class TabularProperty(Property):
"""A property that is composed of a number of 'tabs', each of which is a property collection of its own."""
def __init__(self, dispName, collection):
super().__init__(dispName, '', list)
self.collection = collection
self.tabs = []
def addTab(self, tab):
"""Add a tab to the property's list of tabs."""
self.tabs.append(tab)
def getValue(self):
return [tab.getProperties() for tab in self.tabs]
def setValue(self, value):
self.tabs = [self.collection(data) for data in value]
class PropertyCollection():
"""Holds a set of properties and allows batch operations on them through dictionaries"""
def __init__(self):
self.props = {}
def setProperties(self, props):
"""Sets the value(s) of one of more properties at a time by passing in a dictionary of property names and
values"""
for prop in props.keys():
if prop in self.props: # This allows loading settings when the name of a field has changed
self.props[prop].setValue(props[prop])
def getProperties(self, props=None):
"""Get a dictionary of property names and values. The optional argument is a list of which properties are
being requested. It defaults to None, which returns all properties."""
if props is None:
props = self.props.keys()
return {k:self.props[k].getValue() for k in props}
def getProperty(self, prop):
"""Returns the value of a specific property."""
return self.props[prop].getValue()
def setProperty(self, prop, value):
"""Set the value of a specific property"""
self.props[prop].setValue(value)
openmotor-0.6.0/motorlib/simResult.py 0000664 0000000 0000000 00000034554 15005301746 0017743 0 ustar 00root root 0000000 0000000 """This module contains the classes that are returned from a simulation, including the main results class and
the channels and components that it is comprised of."""
import math
from enum import Enum
from . import geometry
from . import units
from . import constants
class SimAlertLevel(Enum):
"""Levels of severity for sim alerts"""
ERROR = 1
WARNING = 2
MESSAGE = 3
class SimAlertType(Enum):
"""Types of sim alerts"""
GEOMETRY = 1
CONSTRAINT = 2
VALUE = 3
alertLevelNames = {
SimAlertLevel.ERROR: 'Error',
SimAlertLevel.WARNING: 'Warning',
SimAlertLevel.MESSAGE: 'Message'
}
alertTypeNames = {
SimAlertType.GEOMETRY: 'Geometry',
SimAlertType.CONSTRAINT: 'Constraint',
SimAlertType.VALUE: 'Value'
}
class SimAlert():
"""A sim alert signifies a possible problem with a motor. It has levels of severity including 'error' (simulation
should not continue or has failed), 'warning' (values entered appear incorrect but can be simulated), and 'message'
(other information). The type describes the variety of issue the alert is associated with, and the description is
a human-readable version string with more details about the problem. The location can either be None or a string to
help the user find the problem."""
def __init__(self, level, alertType, description, location=None):
self.level = level
self.type = alertType
self.description = description
self.location = location
class LogChannel():
"""A log channel accepts data from a single source throughout a simulation. It has a human-readable name such as
'Pressure' to help the user interpret the result, a value type that data passed in will be cast to, and a unit to
aid in conversion and display. The data type can either be a scalar (float or int) or a list (list or tuple)."""
def __init__(self, name, valueType, unit):
if valueType not in (int, float, list, tuple):
raise TypeError('Value type not in allowed set')
self.name = name
self.unit = unit
self.valueType = valueType
self.data = []
def getData(self, unit=None):
"""Return all of the data in the channel, converting it if a type is specified."""
if unit is None: # No conversion needed
return self.data
if self.valueType in (list, tuple):
return [[units.convert(d, self.unit, unit) for d in p] for p in self.data]
# If the data type isn't a list, it should be a scalar
return [units.convert(p, self.unit, unit) for p in self.data]
def getPoint(self, i):
"""Returns a specific datapoint by index."""
return self.data[i]
def getLast(self):
"""Returns the last datapoint."""
return self.data[-1]
def addData(self, data):
"""Adds a new datapoint to the end."""
self.data.append(data)
def getAverage(self):
"""Returns the average of the datapoints."""
if self.valueType in (list, tuple):
raise NotImplementedError('Average not supported for list types')
return sum(self.data) / len(self.data)
def getMax(self):
"""Returns the maximum value of all datapoints. For list datatypes, this operation finds the largest single
value in any list."""
if self.valueType in (list, tuple):
return max([max(l) for l in self.data])
return max(self.data)
def getMin(self):
"""Returns the minimum value of all datapoints. For list datatypes, this operation finds the smallest single
value in any list."""
if self.valueType in (list, tuple):
return min([min(l) for l in self.data])
return min(self.data)
singleValueChannels = ['time', 'kn', 'pressure', 'force', 'volumeLoading', 'exitPressure', 'dThroat']
multiValueChannels = ['mass', 'massFlow', 'massFlux', 'regression', 'web']
class SimulationResult():
"""A SimulationResult instance contains all results from a single simulation. It has a number of LogChannels, each
capturing a single stream of outputs from the simulation. It also includes a flag of whether the simulation was
considered a sucess, along with a list of alerts that the simulation produced while it was running."""
def __init__(self, motor):
self.motor = motor
self.alerts = []
self.success = False
self.channels = {
'time': LogChannel('Time', float, 's'),
'kn': LogChannel('Kn', float, ''),
'pressure': LogChannel('Chamber Pressure', float, 'Pa'),
'force': LogChannel('Thrust', float, 'N'),
'mass': LogChannel('Propellant Mass', tuple, 'kg'),
'volumeLoading': LogChannel('Volume Loading', float, '%'),
'massFlow': LogChannel('Mass Flow', tuple, 'kg/s'),
'massFlux': LogChannel('Mass Flux', tuple, 'kg/(m^2*s)'),
'regression': LogChannel('Regression Depth', tuple, 'm'),
'web': LogChannel('Web', tuple, 'm'),
'exitPressure': LogChannel('Nozzle Exit Pressure', float, 'Pa'),
'dThroat': LogChannel('Change in Throat Diameter', float, 'm')
}
def addAlert(self, alert):
"""Add an entry to the list of alerts for the simulation."""
self.alerts.append(alert)
def getBurnTime(self):
"""Returns the burntime of the simulated motor, which is the time from the start when it was last producing
thrust above the user's defined threshold."""
return self.channels['time'].getLast()
def getInitialKN(self):
"""Returns the motor's Kn before it started firing."""
return self.channels['kn'].getPoint(0)
def getPeakKN(self):
"""Returns the highest Kn that was observed during the motor's burn."""
return self.channels['kn'].getMax()
def getAveragePressure(self):
"""Returns the average chamber pressure observed during the simulation."""
return self.channels['pressure'].getAverage()
def getMaxPressure(self):
"""Returns the highest chamber pressure that was observed during the motor's burn."""
return self.channels['pressure'].getMax()
def getMinExitPressure(self):
"""Returns the lowest exit pressure that was observed during the motor's burn, ignoring startup and shutdown transients"""
exit_pressures = self.channels['exitPressure'].getData()
return min(exit_pressures)
def getPercentBelowThreshold(self, channel, threshold):
"""Returns the total number of seconds spent below a given threshold value"""
count = 0
data = self.channels[channel].getData()
for point in data:
if point < threshold:
count += 1
return count/len(data)
def getImpulse(self, stop=None):
"""Returns the impulse the simulated motor produced. If 'stop' is set to a value other than None, only the
impulse to that point in the data is returned."""
impulse = 0
lastTime = 0
for time, force in zip(self.channels['time'].data[:stop], self.channels['force'].data[:stop]):
impulse += force * (time - lastTime)
lastTime = time
return impulse
def getAverageForce(self):
"""Returns the average force the motor produced during its burn."""
return self.channels['force'].getAverage()
def getDesignation(self):
"""Returns the standard amateur rocketry designation (H128, M1297) for the motor."""
imp = self.getImpulse()
if imp < 1.25: # This is to avoid a domain error finding log(0)
return 'N/A'
return chr(int(math.log(imp / 1.25, 2)) + 65) + str(int(self.getAverageForce()))
def getFullDesignation(self):
"""Returns the full motor designation, which also includes the total impulse prepended on"""
return '{:.0f}{}'.format(self.getImpulse(), self.getDesignation())
def getImpulseClassPercentage(self):
"""Returns the percentage of the way between the minimum and maximum impulse for the impulse class that the
motor is"""
impulse = self.getImpulse()
if impulse < 1.25: # This is to avoid a domain error finding log(0)
return 0
minClassImpulse = 1.25 * 2 ** int(math.log(impulse / 1.25, 2))
return (impulse - minClassImpulse) / minClassImpulse
def getPeakMassFlux(self):
"""Returns the maximum mass flux observed at any grain end."""
return self.channels['massFlux'].getMax()
def getPeakMassFluxLocation(self):
"""Returns the grain number at which the peak mass flux was observed."""
value = self.getPeakMassFlux()
# Find the value to get the location
for frame in self.channels['massFlux'].getData():
if value in frame:
return frame.index(value)
return None
def getISP(self, index=None):
"""Returns the specific impulse that the simulated motor delivered."""
if index is None:
propMass = self.getPropellantMass()
else:
propMass = self.getPropellantMass() - self.getPropellantMass(index)
if propMass == 0:
return 0
return self.getImpulse(index) / (propMass * constants.standardGravity)
def getPortRatio(self):
"""Returns the port/throat ratio of the motor, or None if it doesn't have a port."""
aftPort = self.motor.grains[-1].getPortArea(0)
if aftPort is not None:
return aftPort / geometry.circleArea(self.motor.nozzle.props['throat'].getValue())
return None
def getPropellantLength(self):
"""Returns the total length of all propellant before the simulated burn."""
return sum([g.props['length'].getValue() for g in self.motor.grains])
def getPropellantMass(self, index=0):
"""Returns the total mass of all propellant before the simulated burn. Optionally accepts a index that the mass
will be sampled at."""
return sum(self.channels['mass'].getPoint(index))
def getVolumeLoading(self, index=0):
"""Returns the percentage of the motor's volume occupied by propellant. Optionally accepts a index that the
value will be sampled at."""
return self.channels['volumeLoading'].getPoint(index)
def getIdealThrustCoefficient(self):
"""Returns the motor's thrust coefficient for the average pressure during the burn and no throat diameter
changes or performance losses."""
chamberPres = self.getAveragePressure()
_, _, gamma, _, _ = self.motor.propellant.getCombustionProperties(chamberPres)
ambPressure = self.motor.config.getProperty('ambPressure')
return self.motor.nozzle.getIdealThrustCoeff(chamberPres, ambPressure, gamma, 0)
def getAdjustedThrustCoefficient(self):
"""Returns the motor's thrust coefficient for the average pressure during the burn and no throat diameter
changes, but including performance losses."""
chamberPres = self.getAveragePressure()
_, _, gamma, _, _ = self.motor.propellant.getCombustionProperties(chamberPres)
ambPressure = self.motor.config.getProperty('ambPressure')
return self.motor.nozzle.getAdjustedThrustCoeff(chamberPres, ambPressure, gamma, 0)
def getAlertsByLevel(self, level):
"""Returns all simulation alerts of the specified level."""
out = []
for alert in self.alerts:
if alert.level == level:
out.append(alert)
return out
def shouldContinueSim(self, thrustThres):
"""Returns if the simulation should continue based on the thrust from the last timestep."""
# With only one data point, there is nothing to compare
if len(self.channels['time'].getData()) == 1:
return True
# Otherwise perform the comparison. 0.01 converts the threshold to a %
return self.channels['force'].getLast() > thrustThres * 0.01 * self.channels['force'].getMax()
def getCSV(self, pref=None, exclude=[], excludeGrains=[]):
"""Returns a string that contains a CSV of the simulated data. Preferences can be passed in to set units that
the values will be converted to. All log channels are included unless their names are in the include
argument. """
out = ''
outUnits = {}
for chan in self.channels:
if chan in exclude:
continue
# Get unit from preferences
if pref is not None:
outUnits[chan] = pref.getUnit(self.channels[chan].unit)
else:
outUnits[chan] = self.channels[chan].unit
# Add title for column
if self.channels[chan].valueType in (float, int):
out += self.channels[chan].name
if outUnits[chan] != '':
out += '({})'.format(outUnits[chan])
out += ','
elif self.channels[chan].valueType in (list, tuple):
for grain in range(1, len(self.channels[chan].getLast()) + 1):
if grain - 1 not in excludeGrains:
out += self.channels[chan].name + '('
out += 'G{}'.format(grain)
if outUnits[chan] != '':
out += ';{}'.format(outUnits[chan])
out += '),'
out = out[:-1] # Remove the last comma
out += '\n'
places = 5
for ind, time in enumerate(self.channels['time'].getData()):
out += str(round(time, places)) + ','
for chan in self.channels:
if chan in exclude:
continue
if chan != 'time':
if self.channels[chan].valueType in (float, int):
orig = self.channels[chan].getPoint(ind)
conv = units.convert(orig, self.channels[chan].unit, outUnits[chan])
rounded = round(conv, places)
out += str(rounded) + ','
elif self.channels[chan].valueType in (list, tuple):
for gid, grainVal in enumerate(self.channels[chan].getPoint(ind)):
if gid not in excludeGrains:
conv = round(units.convert(grainVal, self.channels[chan].unit, outUnits[chan]), places)
out += str(conv) + ','
out = out[:-1] # Remove the last comma
out += '\n'
return out
openmotor-0.6.0/motorlib/units.py 0000664 0000000 0000000 00000007244 15005301746 0017112 0 ustar 00root root 0000000 0000000 """This module contains tables of units and their long form names, their conversion rates with other units, and
functions for performing conversion."""
# The keys in this dictionary specify the units that all calculations are done in internally
unitLabels = {
'm': 'Length',
'm^3': 'Volume',
'm/s': 'Velocity',
'N': 'Force',
'Ns': 'Impulse',
'Pa': 'Pressure',
'kg': 'Mass',
'kg/m^3': 'Density',
'kg/s': 'Mass Flow',
'kg/(m^2*s)': 'Mass Flux',
'm/(s*Pa^n)': 'Burn Rate Coefficient',
'(m*Pa)/s': 'Nozzle Slag Coefficient',
'm/(s*Pa)': 'Nozzle Erosion Coefficient'
}
unitTable = [
('m', 'cm', 100),
('m', 'mm', 1000),
('m', 'in', 39.37),
('m', 'ft', 3.28),
('m^3', 'cm^3', 100**3),
('m^3', 'mm^3', 1000**3),
('m^3', 'in^3', 39.37**3),
('m^3', 'ft^3', 3.28**3),
('m/s', 'cm/s', 100),
('m/s', 'mm/s', 1000),
('m/s', 'ft/s', 3.28),
('m/s', 'in/s', 39.37),
('N', 'lbf', 0.2248),
('Ns', 'lbfs', 0.2248),
('Pa', 'MPa', 1/1000000),
('Pa', 'psi', 1/6895),
('kg', 'g', 1000),
('kg', 'lb', 2.205),
('kg', 'oz', 2.205 * 16),
('kg/m^3', 'lb/in^3', 3.61273e-5),
('kg/m^3', 'g/cm^3', 0.001),
('kg/s', 'lb/s', 2.205),
('kg/s', 'g/s', 1000),
('kg/(m^2*s)', 'lb/(in^2*s)', 0.001422),
('(m*Pa)/s', '(m*MPa)/s', 1000000),
('(m*Pa)/s', '(in*psi)/s', 0.00571014715),
('m/(s*Pa)', 'thou/(s*psi)', 271447138),
('m/(s*Pa)', 'um/(s*mPa)', 1E9),
('m/(s*Pa^n)', 'in/(s*psi^n)', 39.37), # Ratio converts m/s to in/s. The pressure conversion must be done separately
('m/(s*Pa^n)', 'mm/(s*Pa^n)', 1000)
]
# Some base units are... not well chosen because any reasonable value in them will have too many/few digits to edit,
# leading to them getting truncated. They all have conversions that work much better, so just don't show them in the UI
internalOnlyUnits = ['m/(s*Pa^n)', 'm/(s*Pa)']
def getAllConversions(unit):
"""Returns a list of all units that the passed unit can be converted to."""
allConversions = [unit]
for conversion in unitTable:
if conversion[0] == unit:
allConversions.append(conversion[1])
elif conversion[1] == unit:
allConversions.append(conversion[0])
for internalOnlyUnit in internalOnlyUnits:
if internalOnlyUnit in allConversions:
allConversions.remove(internalOnlyUnit)
return allConversions
def getConversion(originUnit, destUnit):
"""Returns the ratio to convert between the two units. If the conversion does not exist, an exception is raised."""
if originUnit == destUnit:
return 1
for conversion in unitTable:
if conversion[0] == originUnit and conversion[1] == destUnit:
return conversion[2]
if conversion[1] == originUnit and conversion[0] == destUnit:
return 1/conversion[2]
raise KeyError("Cannot find conversion from <" + originUnit + "> to <" + destUnit + ">")
def convert(quantity, originUnit, destUnit):
"""Returns the value of 'quantity' when it is converted from 'originUnit' to 'destUnit'."""
return quantity * getConversion(originUnit, destUnit)
def convertAll(quantities, originUnit, destUnit):
"""Converts a list of values from 'originUnit' to 'destUnit'."""
convRate = getConversion(originUnit, destUnit)
return [q * convRate for q in quantities]
def convFormat(quantity, originUnit, destUnit, places=3):
"""Takes in a quantity in originUnit, converts it to destUnit and outputs a rounded and formatted string that
includes the unit appended to the end."""
rounded = round(convert(quantity, originUnit, destUnit), places)
return '{} {}'.format(rounded, destUnit)
openmotor-0.6.0/pyinstaller/ 0000775 0000000 0000000 00000000000 15005301746 0016106 5 ustar 00root root 0000000 0000000 openmotor-0.6.0/pyinstaller/macOneFile.spec 0000664 0000000 0000000 00000002522 15005301746 0020765 0 ustar 00root root 0000000 0000000 # -*- mode: python -*-
# Run with `pyinstaller --windowed --onedir`
from uilib.fileIO import appVersionStr
block_cipher = None
a = Analysis(['../main.py'],
pathex=['../'],
binaries=[],
datas=[],
hiddenimports=['pywt._extensions._cwt'],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False,
target_arch=['x86_64', 'arm64'])
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
[],
exclude_binaries=True,
name='openMotor',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
runtime_tmpdir=None,
console=False)
coll = COLLECT(exe,
a.binaries,
a.zipfiles,
a.datas,
strip=False,
upx=True,
name='openMotor')
app = BUNDLE(coll,
name='openMotor.app',
icon='../resources/oMIconCycles.icns',
version=appVersionStr,
info_plist={
'NSHighResolutionCapable': True,
},
bundle_identifier=None)
openmotor-0.6.0/pyinstaller/winMultiFile.spec 0000664 0000000 0000000 00000001767 15005301746 0021405 0 ustar 00root root 0000000 0000000 # -*- mode: python -*-
block_cipher = None
a = Analysis(['../main.py'],
pathex=['../'],
binaries=[],
datas=[('../resources', 'resources')],
hiddenimports=['pywt._extensions._cwt'],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
[],
exclude_binaries=True,
name='openMotor',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
console=False,
icon='../resources/oMIconCycles.ico')
coll = COLLECT(exe,
a.binaries,
a.zipfiles,
a.datas,
strip=False,
upx=True,
name='openMotor')
openmotor-0.6.0/pyinstaller/winOneFile.spec 0000664 0000000 0000000 00000001540 15005301746 0021021 0 ustar 00root root 0000000 0000000 # -*- mode: python -*-
block_cipher = None
a = Analysis(['../main.py'],
pathex=['../'],
binaries=[],
datas=[],
hiddenimports=['pywt._extensions._cwt'],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
[],
name='openMotor',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
runtime_tmpdir=None,
console=False,
icon='../resources/oMIconCycles.ico' )
openmotor-0.6.0/pyuic.json 0000664 0000000 0000000 00000000234 15005301746 0015563 0 ustar 00root root 0000000 0000000 {
"files": [
[
"uilib/views/forms/*.ui",
"uilib/views"
]
],
"pyuic": "pyuic6",
"pyuic_options": ""
} openmotor-0.6.0/qt.conf 0000664 0000000 0000000 00000000055 15005301746 0015033 0 ustar 00root root 0000000 0000000 [Platforms]
WindowsArguments = dpiawareness=0 openmotor-0.6.0/requirements.txt 0000664 0000000 0000000 00000000526 15005301746 0017027 0 ustar 00root root 0000000 0000000 cycler==0.11.0
decorator==5.1.1
docopt==0.6.2
ezdxf==1.0.3
imageio==2.31.0
matplotlib==3.7.1
networkx==3.1
numpy==1.24.3
Pillow==9.5.0
platformdirs==4.2.2
pyparsing==3.0.9
pyqt-distutils==0.7.3
PyQt6==6.7.1
PyQt6-sip==13.8.0
python-dateutil==2.8.2
PyYAML==6.0
scikit-fmm==2023.4.2
scikit-image==0.18.3
scipy==1.10.1
six==1.16.0
sphinx==7.0.1
openmotor-0.6.0/resources/ 0000775 0000000 0000000 00000000000 15005301746 0015552 5 ustar 00root root 0000000 0000000 openmotor-0.6.0/resources/oMIconCycles.icns 0000664 0000000 0000000 00000177027 15005301746 0020775 0 ustar 00root root 0000000 0000000 icns þic08 þ jP
‡
ftypjp2 jp2 Ojp2h ihdr colr "cdef jp2cÿOÿQ 2 ÿd # Creator: JasPer Version 1.900.1ÿR ÿ\ @@HHPHHPHHPHHPHHPÿ] @@HHPHHPHHPHHPHHPÿ] @@HHPHHPHHPHHPHHPÿ] @@HHPHHPHHPHHPHHPÿ
üÎ ÿ“ß‚8|îî,ø†¸97jÂsU]/'hôUϨAïqÑ[Ms̺ڰY}FÝ[-íY\ºókT.¤³pqH¼ÙMÉOàGß‚0|îî,ø†¸97jÂt3J’ðÑE£H_—?PÝø®>Š5:ÛH1øk1zS£ŒJ¡Æú¦Çä,±)Š#7rO÷@¶ß‚0|îî,öî
DW}ቚ/’ÊÏÌñt¿¤@d—–‚ÈLí¬¸8£Ýi£(~½½Œ¾È[ãh:e>í»À.Ðß‚H}k¼²žõ?©¾8fe\̃ØßÕx÷Dsþé,¸Ij
J»Ï¨ùÏÑó‚›;dsÏËÁìp÷Žw<¢Lc(¹êB_7ÏÀö~ñø €;å— ž„?ó|€¦®ÐÝ|ÌQ¨Qæ{§"ý™ûA6¸úÖŸÝ. q±ãÓp²K£ûˆ‰÷7†ã‘›ÙÒÇ&øi¬ûjK‡ÿ4¸‹
$…‘ŠR,Ò(dï®Jiœ`ÙŒ)0@émŸj²rþ)ò\p4‰¬Ü*È2Cº?£gÙvd¨7…¯sQ€*‘ÉõSp¬
$@5gBÛ"Bt£‹—M¨§R‰ô¬Ò|¯{K$Ù”0vÄŒa-ã t*`euÏÀî~ñø! ;å— 3÷°;N=ê/§Ã™”–ë%L\·# ëÅÛá<·~Ç 2Ug%ÞWJìKϯ‡ƒöÂNP¥¿&øiXâ^ƒ5Ø÷E;±Zù‘s´ú÷hÛ—ßV\|xÝG´¡—»êøïÿh‚LJÁÞTe+ÖŒ 1þêq…Ÿ£gó9C-â–Æ[0âò.S–? ìðWÏñW¼êäUë–¿¡¬XO‘105ѯLh1¢M4تW _ÇÚq?ØüÀQR¶1Ovò]ü ÷Ch4|ïÖf:SZÄþAümX³ém‡ìxæ·î„˵c¬¨“˜£ìBÕhM‹¯dA3¯IÂ'z8•õ¶3¡l)ÿm'E""?:Šª+<‘©éã»Ö€h“Ö·e/¢|A.±¹7 ï=;‚Û¦¥<:2›Gȶ6‡3ÐnÜì·e©®ôçOá½½øªf’½ýç¤Jr˜Ãå‰yôÝü,÷TÀv?´?ÏÀÖüÏ'æxQR¶0ÎXe7¯F>–ÃL;ù êvm'ªiÁðñv§æ6qùƒçÜ®4Ñõй–Mæˆõ3l&
Ff]¬?š¨³€îÑi‘(Ì)¢s‰Ð0ÖkSA‰Ž²û©¶_4ž˜*–K3©"‘†ÿ7 ï™<Ö÷¥û·4]_®Lç p~+…CÔ@Ü,!=V)LÙܺ/h ¿^€ß¡Ì~M…¦0?ϾŸ…o?:üh¼2¹'ííQTµº°Ê½ïêµY_“BÉh;8Ø\/] t†3/1î)ÉRݵåà['à{øRŸMcµ©S¥6àY<‰×͵Þã®Ï!½ÓÌLÝíòÏĵ|Ïf(Iz¡ËA3O©#kÉß`Røj¸%N©˜_U ½n‡f;{à\ëÜCGåfŸ˜º0p1ñ¾¬¬?)òNšnn¿yúe>%lá¦)>®zèý'ÞïåŸO/•³®Ë0x›õ,8º
¿Ú[ê4m]ë@A¤ëí´=Z™· †ðÛ³ÔÜmÊ'ÄJdéØ,nŒFÇûÓ8T¡Ý¡º7ˆeågî^ÌëZÆ7fgLŠJÀˆ*¿´Ã^1â«°Ê¥™ ]+9){ßÓr^ PÔ³| Pø;í˜ZóZ€6Œ¨[M]¹¹°w[æggËQÃa׊Gs{‚G¿šûaùè;›ÿtTÈo“_ܸÞÚ—ÿŸ°ŸÂ¾ØÔiúÕ=F É'|dÌùõZÖÝ0Ÿ2c°DŽÅí
¨Ñq8
ÛßBü+áë ä‡av-wõÒ™ŸYˆ¥6÷›Y€†>,…_r±