index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
722,034 |
apprise.plugins.base
|
image_path
|
Returns the path of the image if it can
|
def image_path(self, notify_type, extension=None):
"""
Returns the path of the image if it can
"""
if not self.image_size:
return None
if notify_type not in NOTIFY_TYPES:
return None
return self.asset.image_path(
notify_type=notify_type,
image_size=self.image_size,
extension=extension,
)
|
(self, notify_type, extension=None)
|
722,035 |
apprise.plugins.base
|
image_raw
|
Returns the raw image if it can
|
def image_raw(self, notify_type, extension=None):
"""
Returns the raw image if it can
"""
if not self.image_size:
return None
if notify_type not in NOTIFY_TYPES:
return None
return self.asset.image_raw(
notify_type=notify_type,
image_size=self.image_size,
extension=extension,
)
|
(self, notify_type, extension=None)
|
722,036 |
apprise.plugins.base
|
image_url
|
Returns Image URL if possible
|
def image_url(self, notify_type, logo=False, extension=None,
image_size=None):
"""
Returns Image URL if possible
"""
if not self.image_size:
return None
if notify_type not in NOTIFY_TYPES:
return None
return self.asset.image_url(
notify_type=notify_type,
image_size=self.image_size if image_size is None else image_size,
logo=logo,
extension=extension,
)
|
(self, notify_type, logo=False, extension=None, image_size=None)
|
722,037 |
apprise.plugins.base
|
notify
|
Performs notification
|
def notify(self, *args, **kwargs):
"""
Performs notification
"""
try:
# Build a list of dictionaries that can be used to call send().
send_calls = list(self._build_send_calls(*args, **kwargs))
except TypeError:
# Internal error
return False
else:
# Loop through each call, one at a time. (Use a list rather than a
# generator to call all the partials, even in case of a failure.)
the_calls = [self.send(**kwargs2) for kwargs2 in send_calls]
return all(the_calls)
|
(self, *args, **kwargs)
|
722,039 |
apprise.plugins.base
|
parse_native_url
|
This is a base class that can be optionally over-ridden by child
classes who can build their Apprise URL based on the one provided
by the notification service they choose to use.
The intent of this is to make Apprise a little more userfriendly
to people who aren't familiar with constructing URLs and wish to
use the ones that were just provied by their notification serivice
that they're using.
This function will return None if the passed in URL can't be matched
as belonging to the notification service. Otherwise this function
should return the same set of results that parse_url() does.
|
@staticmethod
def parse_native_url(url):
"""
This is a base class that can be optionally over-ridden by child
classes who can build their Apprise URL based on the one provided
by the notification service they choose to use.
The intent of this is to make Apprise a little more userfriendly
to people who aren't familiar with constructing URLs and wish to
use the ones that were just provied by their notification serivice
that they're using.
This function will return None if the passed in URL can't be matched
as belonging to the notification service. Otherwise this function
should return the same set of results that parse_url() does.
"""
return None
|
(url)
|
722,041 |
apprise.plugins.base
|
parse_url
|
Parses the URL and returns it broken apart into a dictionary.
This is very specific and customized for Apprise.
Args:
url (str): The URL you want to fully parse.
verify_host (:obj:`bool`, optional): a flag kept with the parsed
URL which some child classes will later use to verify SSL
keys (if SSL transactions take place). Unless under very
specific circumstances, it is strongly recomended that
you leave this default value set to True.
Returns:
A dictionary is returned containing the URL fully parsed if
successful, otherwise None is returned.
|
@staticmethod
def parse_url(url, verify_host=True, plus_to_space=False):
"""Parses the URL and returns it broken apart into a dictionary.
This is very specific and customized for Apprise.
Args:
url (str): The URL you want to fully parse.
verify_host (:obj:`bool`, optional): a flag kept with the parsed
URL which some child classes will later use to verify SSL
keys (if SSL transactions take place). Unless under very
specific circumstances, it is strongly recomended that
you leave this default value set to True.
Returns:
A dictionary is returned containing the URL fully parsed if
successful, otherwise None is returned.
"""
results = URLBase.parse_url(
url, verify_host=verify_host, plus_to_space=plus_to_space)
if not results:
# We're done; we failed to parse our url
return results
# Allow overriding the default format
if 'format' in results['qsd']:
results['format'] = results['qsd'].get('format')
if results['format'] not in NOTIFY_FORMATS:
URLBase.logger.warning(
'Unsupported format specified {}'.format(
results['format']))
del results['format']
# Allow overriding the default overflow
if 'overflow' in results['qsd']:
results['overflow'] = results['qsd'].get('overflow')
if results['overflow'] not in OVERFLOW_MODES:
URLBase.logger.warning(
'Unsupported overflow specified {}'.format(
results['overflow']))
del results['overflow']
# Allow emoji's override
if 'emojis' in results['qsd']:
results['emojis'] = parse_bool(results['qsd'].get('emojis'))
return results
|
(url, verify_host=True, plus_to_space=False)
|
722,046 |
apprise.plugins.base
|
send
|
Should preform the actual notification itself.
|
def send(self, body, title='', notify_type=NotifyType.INFO, **kwargs):
"""
Should preform the actual notification itself.
"""
raise NotImplementedError(
"send() is not implimented by the child class.")
|
(self, body, title='', notify_type='info', **kwargs)
|
722,051 |
apprise.plugins.base
|
url_parameters
|
Provides a default set of parameters to work with. This can greatly
simplify URL construction in the acommpanied url() function in all
defined plugin services.
|
def url_parameters(self, *args, **kwargs):
"""
Provides a default set of parameters to work with. This can greatly
simplify URL construction in the acommpanied url() function in all
defined plugin services.
"""
params = {
'format': self.notify_format,
'overflow': self.overflow_mode,
}
params.update(super().url_parameters(*args, **kwargs))
# return default parameters
return params
|
(self, *args, **kwargs)
|
722,053 |
apprise.common
|
NotifyFormat
|
A list of pre-defined text message formats that can be passed via the
apprise library.
|
class NotifyFormat:
"""
A list of pre-defined text message formats that can be passed via the
apprise library.
"""
TEXT = 'text'
HTML = 'html'
MARKDOWN = 'markdown'
|
()
|
722,054 |
apprise.common
|
NotifyImageSize
|
A list of pre-defined image sizes to make it easier to work with defined
plugins.
|
class NotifyImageSize:
"""
A list of pre-defined image sizes to make it easier to work with defined
plugins.
"""
XY_32 = '32x32'
XY_72 = '72x72'
XY_128 = '128x128'
XY_256 = '256x256'
|
()
|
722,055 |
apprise.common
|
NotifyType
|
A simple mapping of notification types most commonly used with
all types of logging and notification services.
|
class NotifyType:
"""
A simple mapping of notification types most commonly used with
all types of logging and notification services.
"""
INFO = 'info'
SUCCESS = 'success'
WARNING = 'warning'
FAILURE = 'failure'
|
()
|
722,056 |
apprise.common
|
OverflowMode
|
A list of pre-defined modes of how to handle the text when it exceeds the
defined maximum message size.
|
class OverflowMode:
"""
A list of pre-defined modes of how to handle the text when it exceeds the
defined maximum message size.
"""
# Send the data as is; untouched. Let the upstream server decide how the
# content is handled. Some upstream services might gracefully handle this
# with expected intentions; others might not.
UPSTREAM = 'upstream'
# Always truncate the text when it exceeds the maximum message size and
# send it anyway
TRUNCATE = 'truncate'
# Split the message into multiple smaller messages that fit within the
# limits of what is expected. The smaller messages are sent
SPLIT = 'split'
|
()
|
722,057 |
apprise.url
|
PrivacyMode
| null |
class PrivacyMode:
# Defines different privacy modes strings can be printed as
# Astrisk sets 4 of them: e.g. ****
# This is used for passwords
Secret = '*'
# Outer takes the first and last character displaying them with
# 3 dots between. Hence, 'i-am-a-token' would become 'i...n'
Outer = 'o'
# Displays the last four characters
Tail = 't'
|
()
|
722,058 |
apprise.url
|
URLBase
|
This is the base class for all URL Manipulation
|
class URLBase:
"""
This is the base class for all URL Manipulation
"""
# The default descriptive name associated with the URL
service_name = None
# The default simple (insecure) protocol
# all inheriting entries must provide their protocol lookup
# protocol:// (in this example they would specify 'protocol')
protocol = None
# The default secure protocol
# all inheriting entries must provide their protocol lookup
# protocols:// (in this example they would specify 'protocols')
# This value can be the same as the defined protocol.
secure_protocol = None
# Throttle
request_rate_per_sec = 0
# The connect timeout is the number of seconds Requests will wait for your
# client to establish a connection to a remote machine (corresponding to
# the connect()) call on the socket.
socket_connect_timeout = 4.0
# The read timeout is the number of seconds the client will wait for the
# server to send a response.
socket_read_timeout = 4.0
# Handle
# Maintain a set of tags to associate with this specific notification
tags = set()
# Secure sites should be verified against a Certificate Authority
verify_certificate = True
# Logging to our global logger
logger = logger
# Define a default set of template arguments used for dynamically building
# details about our individual plugins for developers.
# Define object templates
templates = ()
# Provides a mapping of tokens, certain entries are fixed and automatically
# configured if found (such as schema, host, user, pass, and port)
template_tokens = {}
# Here is where we define all of the arguments we accept on the url
# such as: schema://whatever/?cto=5.0&rto=15
# These act the same way as tokens except they are optional and/or
# have default values set if mandatory. This rule must be followed
template_args = {
'verify': {
'name': _('Verify SSL'),
# SSL Certificate Authority Verification
'type': 'bool',
# Provide a default
'default': verify_certificate,
# look up default using the following parent class value at
# runtime.
'_lookup_default': 'verify_certificate',
},
'rto': {
'name': _('Socket Read Timeout'),
'type': 'float',
# Provide a default
'default': socket_read_timeout,
# look up default using the following parent class value at
# runtime. The variable name identified here (in this case
# socket_read_timeout) is checked and it's result is placed
# over-top of the 'default'. This is done because once a parent
# class inherits this one, the overflow_mode already set as a
# default 'could' be potentially over-ridden and changed to a
# different value.
'_lookup_default': 'socket_read_timeout',
},
'cto': {
'name': _('Socket Connect Timeout'),
'type': 'float',
# Provide a default
'default': socket_connect_timeout,
# look up default using the following parent class value at
# runtime. The variable name identified here (in this case
# socket_connect_timeout) is checked and it's result is placed
# over-top of the 'default'. This is done because once a parent
# class inherits this one, the overflow_mode already set as a
# default 'could' be potentially over-ridden and changed to a
# different value.
'_lookup_default': 'socket_connect_timeout',
},
}
# kwargs are dynamically built because a prefix causes us to parse the
# content slightly differently. The prefix is required and can be either
# a (+ or -). Below would handle the +key=value:
# {
# 'headers': {
# 'name': _('HTTP Header'),
# 'prefix': '+',
# 'type': 'string',
# },
# },
#
# In a kwarg situation, the 'key' is always presumed to be treated as
# a string. When the 'type' is defined, it is being defined to respect
# the 'value'.
template_kwargs = {}
def __init__(self, asset=None, **kwargs):
"""
Initialize some general logging and common server arguments that will
keep things consistent when working with the children that
inherit this class.
"""
# Prepare our Asset Object
self.asset = \
asset if isinstance(asset, AppriseAsset) else AppriseAsset()
# Certificate Verification (for SSL calls); default to being enabled
self.verify_certificate = parse_bool(kwargs.get('verify', True))
# Secure Mode
self.secure = kwargs.get('secure', None)
try:
if not isinstance(self.secure, bool):
# Attempt to detect
self.secure = kwargs.get('schema', '')[-1].lower() == 's'
except (TypeError, IndexError):
self.secure = False
self.host = URLBase.unquote(kwargs.get('host'))
self.port = kwargs.get('port')
if self.port:
try:
self.port = int(self.port)
except (TypeError, ValueError):
self.logger.warning(
'Invalid port number specified {}'
.format(self.port))
self.port = None
self.user = kwargs.get('user')
if self.user:
# Always unquote user if it exists
self.user = URLBase.unquote(self.user)
self.password = kwargs.get('password')
if self.password:
# Always unquote the password if it exists
self.password = URLBase.unquote(self.password)
# Store our full path consistently ensuring it ends with a `/'
self.fullpath = URLBase.unquote(kwargs.get('fullpath'))
if not isinstance(self.fullpath, str) or not self.fullpath:
self.fullpath = '/'
# Store our Timeout Variables
if 'rto' in kwargs:
try:
self.socket_read_timeout = float(kwargs.get('rto'))
except (TypeError, ValueError):
self.logger.warning(
'Invalid socket read timeout (rto) was specified {}'
.format(kwargs.get('rto')))
if 'cto' in kwargs:
try:
self.socket_connect_timeout = float(kwargs.get('cto'))
except (TypeError, ValueError):
self.logger.warning(
'Invalid socket connect timeout (cto) was specified {}'
.format(kwargs.get('cto')))
if 'tag' in kwargs:
# We want to associate some tags with our notification service.
# the code below gets the 'tag' argument if defined, otherwise
# it just falls back to whatever was already defined globally
self.tags = set(parse_list(kwargs.get('tag'), self.tags))
# Tracks the time any i/o was made to the remote server. This value
# is automatically set and controlled through the throttle() call.
self._last_io_datetime = None
def throttle(self, last_io=None, wait=None):
"""
A common throttle control
if a wait is specified, then it will force a sleep of the
specified time if it is larger then the calculated throttle
time.
"""
if last_io is not None:
# Assume specified last_io
self._last_io_datetime = last_io
# Get ourselves a reference time of 'now'
reference = datetime.now()
if self._last_io_datetime is None:
# Set time to 'now' and no need to throttle
self._last_io_datetime = reference
return
if self.request_rate_per_sec <= 0.0 and not wait:
# We're done if there is no throttle limit set
return
# If we reach here, we need to do additional logic.
# If the difference between the reference time and 'now' is less than
# the defined request_rate_per_sec then we need to throttle for the
# remaining balance of this time.
elapsed = (reference - self._last_io_datetime).total_seconds()
if wait is not None:
self.logger.debug('Throttling forced for {}s...'.format(wait))
time.sleep(wait)
elif elapsed < self.request_rate_per_sec:
self.logger.debug('Throttling for {}s...'.format(
self.request_rate_per_sec - elapsed))
time.sleep(self.request_rate_per_sec - elapsed)
# Update our timestamp before we leave
self._last_io_datetime = datetime.now()
return
def url(self, privacy=False, *args, **kwargs):
"""
Assembles the URL associated with the notification based on the
arguments provied.
"""
# Our default parameters
params = self.url_parameters(privacy=privacy, *args, **kwargs)
# Determine Authentication
auth = ''
if self.user and self.password:
auth = '{user}:{password}@'.format(
user=URLBase.quote(self.user, safe=''),
password=self.pprint(
self.password, privacy, mode=PrivacyMode.Secret, safe=''),
)
elif self.user:
auth = '{user}@'.format(
user=URLBase.quote(self.user, safe=''),
)
default_port = 443 if self.secure else 80
return '{schema}://{auth}{hostname}{port}{fullpath}?{params}'.format(
schema='https' if self.secure else 'http',
auth=auth,
# never encode hostname since we're expecting it to be a valid one
hostname=self.host,
port='' if self.port is None or self.port == default_port
else ':{}'.format(self.port),
fullpath=URLBase.quote(self.fullpath, safe='/')
if self.fullpath else '/',
params=URLBase.urlencode(params),
)
def __contains__(self, tags):
"""
Returns true if the tag specified is associated with this notification.
tag can also be a tuple, set, and/or list
"""
if isinstance(tags, (tuple, set, list)):
return bool(set(tags) & self.tags)
# return any match
return tags in self.tags
def __str__(self):
"""
Returns the url path
"""
return self.url(privacy=True)
@staticmethod
def escape_html(html, convert_new_lines=False, whitespace=True):
"""
Takes html text as input and escapes it so that it won't
conflict with any xml/html wrapping characters.
Args:
html (str): The HTML code to escape
convert_new_lines (:obj:`bool`, optional): escape new lines (\n)
whitespace (:obj:`bool`, optional): escape whitespace
Returns:
str: The escaped html
"""
if not isinstance(html, str) or not html:
return ''
# Escape HTML
escaped = sax_escape(html, {"'": "'", "\"": """})
if whitespace:
# Tidy up whitespace too
escaped = escaped\
.replace(u'\t', u' ')\
.replace(u' ', u' ')
if convert_new_lines:
return escaped.replace(u'\n', u'<br/>')
return escaped
@staticmethod
def unquote(content, encoding='utf-8', errors='replace'):
"""
Replace %xx escapes by their single-character equivalent. The optional
encoding and errors parameters specify how to decode percent-encoded
sequences.
Wrapper to Python's `unquote` while remaining compatible with both
Python 2 & 3 since the reference to this function changed between
versions.
Note: errors set to 'replace' means that invalid sequences are
replaced by a placeholder character.
Args:
content (str): The quoted URI string you wish to unquote
encoding (:obj:`str`, optional): encoding type
errors (:obj:`str`, errors): how to handle invalid character found
in encoded string (defined by encoding)
Returns:
str: The unquoted URI string
"""
if not content:
return ''
return _unquote(content, encoding=encoding, errors=errors)
@staticmethod
def quote(content, safe='/', encoding=None, errors=None):
""" Replaces single character non-ascii characters and URI specific
ones by their %xx code.
Wrapper to Python's `quote` while remaining compatible with both
Python 2 & 3 since the reference to this function changed between
versions.
Args:
content (str): The URI string you wish to quote
safe (str): non-ascii characters and URI specific ones that you
do not wish to escape (if detected). Setting this
string to an empty one causes everything to be
escaped.
encoding (:obj:`str`, optional): encoding type
errors (:obj:`str`, errors): how to handle invalid character found
in encoded string (defined by encoding)
Returns:
str: The quoted URI string
"""
if not content:
return ''
return _quote(content, safe=safe, encoding=encoding, errors=errors)
@staticmethod
def pprint(content, privacy=True, mode=PrivacyMode.Outer,
# privacy print; quoting is ignored when privacy is set to True
quote=True, safe='/', encoding=None, errors=None):
"""
Privacy Print is used to mainpulate the string before passing it into
part of the URL. It is used to mask/hide private details such as
tokens, passwords, apikeys, etc from on-lookers. If the privacy=False
is set, then the quote variable is the next flag checked.
Quoting is never done if the privacy flag is set to true to avoid
skewing the expected output.
"""
if not privacy:
if quote:
# Return quoted string if specified to do so
return URLBase.quote(
content, safe=safe, encoding=encoding, errors=errors)
# Return content 'as-is'
return content
if mode is PrivacyMode.Secret:
# Return 4 Asterisks
return '****'
if not isinstance(content, str) or not content:
# Nothing more to do
return ''
if mode is PrivacyMode.Tail:
# Return the trailing 4 characters
return '...{}'.format(content[-4:])
# Default mode is Outer Mode
return '{}...{}'.format(content[0:1], content[-1:])
@staticmethod
def urlencode(query, doseq=False, safe='', encoding=None, errors=None):
"""Convert a mapping object or a sequence of two-element tuples
Wrapper to Python's `urlencode` while remaining compatible with both
Python 2 & 3 since the reference to this function changed between
versions.
The resulting string is a series of key=value pairs separated by '&'
characters, where both key and value are quoted using the quote()
function.
Note: If the dictionary entry contains an entry that is set to None
it is not included in the final result set. If you want to
pass in an empty variable, set it to an empty string.
Args:
query (str): The dictionary to encode
doseq (:obj:`bool`, optional): Handle sequences
safe (:obj:`str`): non-ascii characters and URI specific ones that
you do not wish to escape (if detected). Setting this string
to an empty one causes everything to be escaped.
encoding (:obj:`str`, optional): encoding type
errors (:obj:`str`, errors): how to handle invalid character found
in encoded string (defined by encoding)
Returns:
str: The escaped parameters returned as a string
"""
return urlencode(
query, doseq=doseq, safe=safe, encoding=encoding, errors=errors)
@staticmethod
def split_path(path, unquote=True):
"""Splits a URL up into a list object.
Parses a specified URL and breaks it into a list.
Args:
path (str): The path to split up into a list.
unquote (:obj:`bool`, optional): call unquote on each element
added to the returned list.
Returns:
list: A list containing all of the elements in the path
"""
try:
paths = PATHSPLIT_LIST_DELIM.split(path.lstrip('/'))
if unquote:
paths = \
[URLBase.unquote(x) for x in filter(bool, paths)]
except AttributeError:
# path is not useable, we still want to gracefully return an
# empty list
paths = []
return paths
@staticmethod
def parse_list(content, allow_whitespace=True, unquote=True):
"""A wrapper to utils.parse_list() with unquoting support
Parses a specified set of data and breaks it into a list.
Args:
content (str): The path to split up into a list. If a list is
provided, then it's individual entries are processed.
allow_whitespace (:obj:`bool`, optional): whitespace is to be
treated as a delimiter
unquote (:obj:`bool`, optional): call unquote on each element
added to the returned list.
Returns:
list: A unique list containing all of the elements in the path
"""
content = parse_list(content, allow_whitespace=allow_whitespace)
if unquote:
content = \
[URLBase.unquote(x) for x in filter(bool, content)]
return content
@staticmethod
def parse_phone_no(content, unquote=True):
"""A wrapper to utils.parse_phone_no() with unquoting support
Parses a specified set of data and breaks it into a list.
Args:
content (str): The path to split up into a list. If a list is
provided, then it's individual entries are processed.
unquote (:obj:`bool`, optional): call unquote on each element
added to the returned list.
Returns:
list: A unique list containing all of the elements in the path
"""
if unquote:
try:
content = URLBase.unquote(content)
except TypeError:
# Nothing further to do
return []
content = parse_phone_no(content)
return content
@property
def app_id(self):
return self.asset.app_id if self.asset.app_id else ''
@property
def app_desc(self):
return self.asset.app_desc if self.asset.app_desc else ''
@property
def app_url(self):
return self.asset.app_url if self.asset.app_url else ''
@property
def request_timeout(self):
"""This is primarily used to fullfill the `timeout` keyword argument
that is used by requests.get() and requests.put() calls.
"""
return (self.socket_connect_timeout, self.socket_read_timeout)
@property
def request_auth(self):
"""This is primarily used to fullfill the `auth` keyword argument
that is used by requests.get() and requests.put() calls.
"""
return (self.user, self.password) if self.user else None
@property
def request_url(self):
"""
Assemble a simple URL that can be used by the requests library
"""
# Acquire our schema
schema = 'https' if self.secure else 'http'
# Prepare our URL
url = '%s://%s' % (schema, self.host)
# Apply Port information if present
if isinstance(self.port, int):
url += ':%d' % self.port
# Append our full path
return url + self.fullpath
def url_parameters(self, *args, **kwargs):
"""
Provides a default set of args to work with. This can greatly
simplify URL construction in the acommpanied url() function.
The following property returns a dictionary (of strings) containing
all of the parameters that can be set on a URL and managed through
this class.
"""
return {
# The socket read timeout
'rto': str(self.socket_read_timeout),
# The request/socket connect timeout
'cto': str(self.socket_connect_timeout),
# Certificate verification
'verify': 'yes' if self.verify_certificate else 'no',
}
@staticmethod
def post_process_parse_url_results(results):
"""
After parsing the URL, this function applies a bit of extra logic to
support extra entries like `pass` becoming `password`, etc
This function assumes that parse_url() was called previously setting
up the basics to be checked
"""
# if our URL ends with an 's', then assume our secure flag is set.
results['secure'] = (results['schema'][-1] == 's')
# QSD Checking (over-rides all)
qsd_exists = True if isinstance(results.get('qsd'), dict) else False
if qsd_exists and 'verify' in results['qsd']:
# Pulled from URL String
results['verify'] = parse_bool(
results['qsd'].get('verify', True))
elif 'verify' in results:
# Pulled from YAML Configuratoin
results['verify'] = parse_bool(results.get('verify', True))
else:
# Support SSL Certificate 'verify' keyword. Default to being
# enabled
results['verify'] = True
# Password overrides
if 'pass' in results:
results['password'] = results['pass']
del results['pass']
if qsd_exists:
if 'password' in results['qsd']:
results['password'] = results['qsd']['password']
if 'pass' in results['qsd']:
results['password'] = results['qsd']['pass']
# User overrides
if 'user' in results['qsd']:
results['user'] = results['qsd']['user']
# parse_url() always creates a 'password' and 'user' entry in the
# results returned. Entries are set to None if they weren't
# specified
if results['password'] is None and 'user' in results['qsd']:
# Handle cases where the user= provided in 2 locations, we want
# the original to fall back as a being a password (if one
# wasn't otherwise defined) e.g.
# mailtos://PASSWORD@hostname?user=admin@mail-domain.com
# - in the above, the PASSWORD gets lost in the parse url()
# since a user= over-ride is specified.
presults = parse_url(results['url'])
if presults:
# Store our Password
results['password'] = presults['user']
# Store our socket read timeout if specified
if 'rto' in results['qsd']:
results['rto'] = results['qsd']['rto']
# Store our socket connect timeout if specified
if 'cto' in results['qsd']:
results['cto'] = results['qsd']['cto']
if 'port' in results['qsd']:
results['port'] = results['qsd']['port']
return results
@staticmethod
def parse_url(url, verify_host=True, plus_to_space=False,
strict_port=False, sanitize=True):
"""Parses the URL and returns it broken apart into a dictionary.
This is very specific and customized for Apprise.
Args:
url (str): The URL you want to fully parse.
verify_host (:obj:`bool`, optional): a flag kept with the parsed
URL which some child classes will later use to verify SSL
keys (if SSL transactions take place). Unless under very
specific circumstances, it is strongly recomended that
you leave this default value set to True.
Returns:
A dictionary is returned containing the URL fully parsed if
successful, otherwise None is returned.
"""
results = parse_url(
url, default_schema='unknown', verify_host=verify_host,
plus_to_space=plus_to_space, strict_port=strict_port,
sanitize=sanitize)
if not results:
# We're done; we failed to parse our url
return results
return URLBase.post_process_parse_url_results(results)
@staticmethod
def http_response_code_lookup(code, response_mask=None):
"""Parses the interger response code returned by a remote call from
a web request into it's human readable string version.
You can over-ride codes or add new ones by providing your own
response_mask that contains a dictionary of integer -> string mapped
variables
"""
if isinstance(response_mask, dict):
# Apply any/all header over-rides defined
HTML_LOOKUP.update(response_mask)
# Look up our response
try:
response = HTML_LOOKUP[code]
except KeyError:
response = ''
return response
def __len__(self):
"""
Should be over-ridden and allows the tracking of how many targets
are associated with each URLBase object.
Default is always 1
"""
return 1
def schemas(self):
"""A simple function that returns a set of all schemas associated
with this object based on the object.protocol and
object.secure_protocol
"""
schemas = set([])
for key in ('protocol', 'secure_protocol'):
schema = getattr(self, key, None)
if isinstance(schema, str):
schemas.add(schema)
elif isinstance(schema, (set, list, tuple)):
# Support iterables list types
for s in schema:
if isinstance(s, str):
schemas.add(s)
return schemas
|
(asset=None, **kwargs)
|
722,060 |
apprise.url
|
__init__
|
Initialize some general logging and common server arguments that will
keep things consistent when working with the children that
inherit this class.
|
def __init__(self, asset=None, **kwargs):
"""
Initialize some general logging and common server arguments that will
keep things consistent when working with the children that
inherit this class.
"""
# Prepare our Asset Object
self.asset = \
asset if isinstance(asset, AppriseAsset) else AppriseAsset()
# Certificate Verification (for SSL calls); default to being enabled
self.verify_certificate = parse_bool(kwargs.get('verify', True))
# Secure Mode
self.secure = kwargs.get('secure', None)
try:
if not isinstance(self.secure, bool):
# Attempt to detect
self.secure = kwargs.get('schema', '')[-1].lower() == 's'
except (TypeError, IndexError):
self.secure = False
self.host = URLBase.unquote(kwargs.get('host'))
self.port = kwargs.get('port')
if self.port:
try:
self.port = int(self.port)
except (TypeError, ValueError):
self.logger.warning(
'Invalid port number specified {}'
.format(self.port))
self.port = None
self.user = kwargs.get('user')
if self.user:
# Always unquote user if it exists
self.user = URLBase.unquote(self.user)
self.password = kwargs.get('password')
if self.password:
# Always unquote the password if it exists
self.password = URLBase.unquote(self.password)
# Store our full path consistently ensuring it ends with a `/'
self.fullpath = URLBase.unquote(kwargs.get('fullpath'))
if not isinstance(self.fullpath, str) or not self.fullpath:
self.fullpath = '/'
# Store our Timeout Variables
if 'rto' in kwargs:
try:
self.socket_read_timeout = float(kwargs.get('rto'))
except (TypeError, ValueError):
self.logger.warning(
'Invalid socket read timeout (rto) was specified {}'
.format(kwargs.get('rto')))
if 'cto' in kwargs:
try:
self.socket_connect_timeout = float(kwargs.get('cto'))
except (TypeError, ValueError):
self.logger.warning(
'Invalid socket connect timeout (cto) was specified {}'
.format(kwargs.get('cto')))
if 'tag' in kwargs:
# We want to associate some tags with our notification service.
# the code below gets the 'tag' argument if defined, otherwise
# it just falls back to whatever was already defined globally
self.tags = set(parse_list(kwargs.get('tag'), self.tags))
# Tracks the time any i/o was made to the remote server. This value
# is automatically set and controlled through the throttle() call.
self._last_io_datetime = None
|
(self, asset=None, **kwargs)
|
722,067 |
apprise.url
|
parse_url
|
Parses the URL and returns it broken apart into a dictionary.
This is very specific and customized for Apprise.
Args:
url (str): The URL you want to fully parse.
verify_host (:obj:`bool`, optional): a flag kept with the parsed
URL which some child classes will later use to verify SSL
keys (if SSL transactions take place). Unless under very
specific circumstances, it is strongly recomended that
you leave this default value set to True.
Returns:
A dictionary is returned containing the URL fully parsed if
successful, otherwise None is returned.
|
@staticmethod
def parse_url(url, verify_host=True, plus_to_space=False,
strict_port=False, sanitize=True):
"""Parses the URL and returns it broken apart into a dictionary.
This is very specific and customized for Apprise.
Args:
url (str): The URL you want to fully parse.
verify_host (:obj:`bool`, optional): a flag kept with the parsed
URL which some child classes will later use to verify SSL
keys (if SSL transactions take place). Unless under very
specific circumstances, it is strongly recomended that
you leave this default value set to True.
Returns:
A dictionary is returned containing the URL fully parsed if
successful, otherwise None is returned.
"""
results = parse_url(
url, default_schema='unknown', verify_host=verify_host,
plus_to_space=plus_to_space, strict_port=strict_port,
sanitize=sanitize)
if not results:
# We're done; we failed to parse our url
return results
return URLBase.post_process_parse_url_results(results)
|
(url, verify_host=True, plus_to_space=False, strict_port=False, sanitize=True)
|
722,097 |
pytest_socket
|
SocketBlockedError
| null |
class SocketBlockedError(RuntimeError):
def __init__(self, *_args, **_kwargs):
super().__init__("A test tried to use socket.socket.")
|
(*_args, **_kwargs)
|
722,098 |
pytest_socket
|
__init__
| null |
def __init__(self, *_args, **_kwargs):
super().__init__("A test tried to use socket.socket.")
|
(self, *_args, **_kwargs)
|
722,099 |
pytest_socket
|
SocketConnectBlockedError
| null |
class SocketConnectBlockedError(RuntimeError):
def __init__(self, allowed, host, *_args, **_kwargs):
if allowed:
allowed = ",".join(allowed)
super().__init__(
"A test tried to use socket.socket.connect() "
f'with host "{host}" (allowed: "{allowed}").'
)
|
(allowed, host, *_args, **_kwargs)
|
722,100 |
pytest_socket
|
__init__
| null |
def __init__(self, allowed, host, *_args, **_kwargs):
if allowed:
allowed = ",".join(allowed)
super().__init__(
"A test tried to use socket.socket.connect() "
f'with host "{host}" (allowed: "{allowed}").'
)
|
(self, allowed, host, *_args, **_kwargs)
|
722,101 |
pytest_socket
|
_is_unix_socket
| null |
def _is_unix_socket(family) -> bool:
try:
is_unix_socket = family == socket.AF_UNIX
except AttributeError:
# AF_UNIX not supported on Windows https://bugs.python.org/issue33408
is_unix_socket = False
return is_unix_socket
|
(family) -> bool
|
722,102 |
pytest_socket
|
_remove_restrictions
|
restore socket.socket.* to allow access to the Internet. useful in testing.
|
def _remove_restrictions():
"""restore socket.socket.* to allow access to the Internet. useful in testing."""
socket.socket = _true_socket
socket.socket.connect = _true_connect
|
()
|
722,103 |
pytest_socket
|
_resolve_allow_hosts
|
Resolve `allow_hosts` behaviors.
|
def _resolve_allow_hosts(item):
"""Resolve `allow_hosts` behaviors."""
mark_restrictions = item.get_closest_marker("allow_hosts")
cli_restrictions = item.config.__socket_allow_hosts
hosts = None
if mark_restrictions:
hosts = mark_restrictions.args[0]
elif cli_restrictions:
hosts = cli_restrictions
socket_allow_hosts(hosts, allow_unix_socket=item.config.__socket_allow_unix_socket)
return hosts
|
(item)
|
722,124 |
pytest_socket
|
disable_socket
|
disable socket.socket to disable the Internet. useful in testing.
|
def disable_socket(allow_unix_socket=False):
"""disable socket.socket to disable the Internet. useful in testing."""
class GuardedSocket(socket.socket):
"""socket guard to disable socket creation (from pytest-socket)"""
def __new__(cls, family=-1, type=-1, proto=-1, fileno=None):
if _is_unix_socket(family) and allow_unix_socket:
return super().__new__(cls, family, type, proto, fileno)
raise SocketBlockedError()
socket.socket = GuardedSocket
|
(allow_unix_socket=False)
|
722,125 |
pytest_socket
|
enable_socket
|
re-enable socket.socket to enable the Internet. useful in testing.
|
def enable_socket():
"""re-enable socket.socket to enable the Internet. useful in testing."""
socket.socket = _true_socket
|
()
|
722,126 |
pytest_socket
|
host_from_address
| null |
def host_from_address(address):
host = address[0]
if isinstance(host, str):
return host
|
(address)
|
722,127 |
pytest_socket
|
host_from_connect_args
| null |
def host_from_connect_args(args):
address = args[0]
if isinstance(address, tuple):
return host_from_address(address)
|
(args)
|
722,129 |
pytest_socket
|
is_ipaddress
|
Determine if the address is a valid IPv4 or IPv6 address.
|
def is_ipaddress(address: str) -> bool:
"""
Determine if the address is a valid IPv4 or IPv6 address.
"""
try:
ipaddress.ip_address(address)
return True
except ValueError:
return False
|
(address: str) -> bool
|
722,131 |
pytest_socket
|
normalize_allowed_hosts
|
Map all items in `allowed_hosts` to IP addresses.
|
def normalize_allowed_hosts(
allowed_hosts: typing.List[str],
) -> typing.Dict[str, typing.Set[str]]:
"""Map all items in `allowed_hosts` to IP addresses."""
ip_hosts = defaultdict(set)
for host in allowed_hosts:
host = host.strip()
if is_ipaddress(host):
ip_hosts[host].add(host)
else:
ip_hosts[host].update(resolve_hostnames(host))
return ip_hosts
|
(allowed_hosts: List[str]) -> Dict[str, Set[str]]
|
722,133 |
pytest_socket
|
pytest_addoption
| null |
def pytest_addoption(parser):
group = parser.getgroup("socket")
group.addoption(
"--disable-socket",
action="store_true",
dest="disable_socket",
help="Disable socket.socket by default to block network calls.",
)
group.addoption(
"--force-enable-socket",
action="store_true",
dest="force_enable_socket",
help="Force enable socket.socket network calls (override --disable-socket).",
)
group.addoption(
"--allow-hosts",
dest="allow_hosts",
metavar="ALLOWED_HOSTS_CSV",
help="Only allow specified hosts through socket.socket.connect((host, port)).",
)
group.addoption(
"--allow-unix-socket",
action="store_true",
dest="allow_unix_socket",
help="Allow calls if they are to Unix domain sockets",
)
|
(parser)
|
722,134 |
pytest_socket
|
pytest_configure
| null |
def pytest_configure(config):
config.addinivalue_line(
"markers", "disable_socket(): Disable socket connections for a specific test"
)
config.addinivalue_line(
"markers", "enable_socket(): Enable socket connections for a specific test"
)
config.addinivalue_line(
"markers",
"allow_hosts([hosts]): Restrict socket connection to defined list of hosts",
)
# Store the global configs in the `pytest.Config` object.
config.__socket_force_enabled = config.getoption("--force-enable-socket")
config.__socket_disabled = config.getoption("--disable-socket")
config.__socket_allow_unix_socket = config.getoption("--allow-unix-socket")
config.__socket_allow_hosts = config.getoption("--allow-hosts")
|
(config)
|
722,135 |
pytest_socket
|
pytest_runtest_setup
|
During each test item's setup phase,
choose the behavior based on the configurations supplied.
This is the bulk of the logic for the plugin.
As the logic can be extensive, this method is allowed complexity.
It may be refactored in the future to be more readable.
If the given item is not a function test (i.e a DoctestItem)
or otherwise has no support for fixtures, skip it.
|
def pytest_runtest_setup(item) -> None:
"""During each test item's setup phase,
choose the behavior based on the configurations supplied.
This is the bulk of the logic for the plugin.
As the logic can be extensive, this method is allowed complexity.
It may be refactored in the future to be more readable.
If the given item is not a function test (i.e a DoctestItem)
or otherwise has no support for fixtures, skip it.
"""
if not hasattr(item, "fixturenames"):
return
# If test has the `enable_socket` marker, fixture or
# it's forced from the CLI, we accept this as most explicit.
if (
"socket_enabled" in item.fixturenames
or item.get_closest_marker("enable_socket")
or item.config.__socket_force_enabled
):
enable_socket()
return
# If the test has the `disable_socket` marker, it's explicitly disabled.
if "socket_disabled" in item.fixturenames or item.get_closest_marker(
"disable_socket"
):
disable_socket(item.config.__socket_allow_unix_socket)
return
# Resolve `allow_hosts` behaviors.
hosts = _resolve_allow_hosts(item)
# Finally, check the global config and disable socket if needed.
if item.config.__socket_disabled and not hosts:
disable_socket(item.config.__socket_allow_unix_socket)
|
(item) -> NoneType
|
722,136 |
pytest_socket
|
pytest_runtest_teardown
| null |
def pytest_runtest_teardown():
_remove_restrictions()
|
()
|
722,137 |
pytest_socket
|
resolve_hostnames
| null |
def resolve_hostnames(hostname: str) -> typing.Set[str]:
try:
return {
addr_struct[0] for *_, addr_struct in socket.getaddrinfo(hostname, None)
}
except socket.gaierror:
return set()
|
(hostname: str) -> Set[str]
|
722,139 |
pytest_socket
|
socket_allow_hosts
|
disable socket.socket.connect() to disable the Internet. useful in testing.
|
def socket_allow_hosts(allowed=None, allow_unix_socket=False):
"""disable socket.socket.connect() to disable the Internet. useful in testing."""
if isinstance(allowed, str):
allowed = allowed.split(",")
if not isinstance(allowed, list):
return
allowed_ip_hosts_by_host = normalize_allowed_hosts(allowed)
allowed_ip_hosts_and_hostnames = set(
itertools.chain(*allowed_ip_hosts_by_host.values())
) | set(allowed_ip_hosts_by_host.keys())
allowed_list = sorted(
[
(
host
if len(normalized) == 1 and next(iter(normalized)) == host
else f"{host} ({','.join(sorted(normalized))})"
)
for host, normalized in allowed_ip_hosts_by_host.items()
]
)
def guarded_connect(inst, *args):
host = host_from_connect_args(args)
if host in allowed_ip_hosts_and_hostnames or (
_is_unix_socket(inst.family) and allow_unix_socket
):
return _true_connect(inst, *args)
raise SocketConnectBlockedError(allowed_list, host)
socket.socket.connect = guarded_connect
|
(allowed=None, allow_unix_socket=False)
|
722,140 |
pytest_socket
|
socket_disabled
|
disable socket.socket for duration of this test function
| null |
(pytestconfig)
|
722,141 |
pytest_socket
|
socket_enabled
|
enable socket.socket for duration of this test function
| null |
(pytestconfig)
|
722,143 |
itables.javascript
|
JavascriptCode
|
A class that explicitly states that a string is a Javascript code
|
class JavascriptCode(str):
"""A class that explicitly states that a string is a Javascript code"""
pass
| null |
722,144 |
itables.javascript
|
JavascriptFunction
|
A class that explicitly states that a string is a Javascript function
|
class JavascriptFunction(str):
"""A class that explicitly states that a string is a Javascript function"""
def __init__(self, value):
assert value.lstrip().startswith(
"function"
), "A Javascript function is expected to start with 'function'"
|
(value)
|
722,145 |
itables.javascript
|
__init__
| null |
def __init__(self, value):
assert value.lstrip().startswith(
"function"
), "A Javascript function is expected to start with 'function'"
|
(self, value)
|
722,148 |
itables.javascript
|
init_notebook_mode
|
Load the DataTables library and the corresponding css (if connected=False),
and (if all_interactive=True), activate the DataTables representation for all the Pandas DataFrames and Series.
Warning: make sure you keep the output of this cell when 'connected=False',
otherwise the interactive tables will stop working.
|
def init_notebook_mode(
all_interactive=False,
connected=GOOGLE_COLAB,
dt_bundle=None,
):
"""Load the DataTables library and the corresponding css (if connected=False),
and (if all_interactive=True), activate the DataTables representation for all the Pandas DataFrames and Series.
Warning: make sure you keep the output of this cell when 'connected=False',
otherwise the interactive tables will stop working.
"""
if dt_bundle is None:
dt_bundle = opt.dt_bundle
global _CONNECTED
if GOOGLE_COLAB and not connected:
warnings.warn(
"The offline mode for itables is not supposed to work in Google Colab. "
"This is because HTML outputs in Google Colab are encapsulated in iframes."
)
_CONNECTED = connected
if all_interactive:
pd.DataFrame._repr_html_ = _datatables_repr_
pd.Series._repr_html_ = _datatables_repr_
if pd_style is not None:
pd_style.Styler._repr_html_ = _datatables_repr_
pl.DataFrame._repr_html_ = _datatables_repr_
pl.Series._repr_html_ = _datatables_repr_
else:
pd.DataFrame._repr_html_ = _ORIGINAL_DATAFRAME_REPR_HTML
if pd_style is not None:
pd_style.Styler._repr_html_ = _ORIGINAL_DATAFRAME_STYLE_REPR_HTML
pl.DataFrame._repr_html_ = _ORIGINAL_POLARS_DATAFRAME_REPR_HTML
if hasattr(pd.Series, "_repr_html_"):
del pd.Series._repr_html_
if hasattr(pl.Series, "_repr_html_"):
del pl.Series._repr_html_
display(HTML(read_package_file("html/init_datatables.html")))
if not connected:
display(HTML(generate_init_offline_itables_html(dt_bundle)))
|
(all_interactive=False, connected=False, dt_bundle=None)
|
722,151 |
itables.javascript
|
show
|
Show a dataframe
|
def show(df=None, caption=None, **kwargs):
"""Show a dataframe"""
connected = kwargs.pop("connected", ("dt_url" in kwargs) or _CONNECTED)
html = to_html_datatable(df, caption=caption, connected=connected, **kwargs)
display(HTML(html))
|
(df=None, caption=None, **kwargs)
|
722,152 |
itables.javascript
|
to_html_datatable
| null |
def to_html_datatable(
df=None,
caption=None,
tableId=None,
connected=True,
use_to_html=False,
**kwargs,
):
check_table_id(tableId)
if "import_jquery" in kwargs:
raise TypeError(
"The argument 'import_jquery' was removed in ITables v2.0. "
"Please pass a custom 'dt_url' instead."
)
if use_to_html or (pd_style is not None and isinstance(df, pd_style.Styler)):
return to_html_datatable_using_to_html(
df=df,
caption=caption,
tableId=tableId,
connected=connected,
**kwargs,
)
"""Return the HTML representation of the given dataframe as an interactive datatable"""
set_default_options(kwargs, use_to_html=False)
# These options are used here, not in DataTable
classes = kwargs.pop("classes")
style = kwargs.pop("style")
tags = kwargs.pop("tags")
if caption is not None:
tags = '{}<caption style="white-space: nowrap; overflow: hidden">{}</caption>'.format(
tags, caption
)
showIndex = kwargs.pop("showIndex")
if isinstance(df, (np.ndarray, np.generic)):
df = pd.DataFrame(df)
if isinstance(df, (pd.Series, pl.Series)):
df = df.to_frame()
if showIndex == "auto":
try:
showIndex = df.index.name is not None or not isinstance(
df.index, pd.RangeIndex
)
except AttributeError:
# Polars DataFrame
showIndex = False
maxBytes = kwargs.pop("maxBytes", 0)
maxRows = kwargs.pop("maxRows", 0)
maxColumns = kwargs.pop("maxColumns", pd.get_option("display.max_columns") or 0)
warn_on_unexpected_types = kwargs.pop("warn_on_unexpected_types", False)
df, downsampling_warning = downsample(
df, max_rows=maxRows, max_columns=maxColumns, max_bytes=maxBytes
)
if downsampling_warning and "fnInfoCallback" not in kwargs:
kwargs["fnInfoCallback"] = JavascriptFunction(
"function (oSettings, iStart, iEnd, iMax, iTotal, sPre) {{ return sPre + ' ({warning})'; }}".format(
warning=downsampling_warning
)
)
_adjust_layout(df, kwargs, downsampling_warning)
footer = kwargs.pop("footer")
column_filters = kwargs.pop("column_filters")
if column_filters == "header":
pass
elif column_filters == "footer":
footer = True
elif column_filters is not False:
raise ValueError(
"column_filters should be either "
"'header', 'footer' or False, not {}".format(column_filters)
)
tableId = tableId or "itables_" + str(uuid.uuid4()).replace("-", "_")
if isinstance(classes, list):
classes = " ".join(classes)
if not showIndex:
try:
df = df.set_index(pd.RangeIndex(len(df.index)))
except AttributeError:
# Polars DataFrames
pass
table_header = _table_header(
df, tableId, showIndex, classes, style, tags, footer, column_filters, connected
)
# Export the table data to JSON and include this in the HTML
if showIndex:
df = safe_reset_index(df)
# When the header has an extra column, we add
# an extra empty column in the table data #141
column_count = _column_count_in_header(table_header)
dt_data = datatables_rows(
df,
column_count,
warn_on_unexpected_types=warn_on_unexpected_types,
)
return html_table_from_template(
table_header,
table_id=tableId,
data=dt_data,
kwargs=kwargs,
connected=connected,
column_filters=column_filters,
)
|
(df=None, caption=None, tableId=None, connected=True, use_to_html=False, **kwargs)
|
722,155 |
openap.drag
|
Drag
|
Compute the drag of aircraft.
|
class Drag(object):
"""Compute the drag of aircraft."""
def __init__(self, ac, wave_drag=False, **kwargs):
"""Initialize Drag object.
Args:
ac (string): ICAO aircraft type (for example: A320).
wave_drag (bool): enable wave_drag model (experimental).
"""
if not hasattr(self, "np"):
self.np = importlib.import_module("numpy")
if not hasattr(self, "aero"):
self.aero = importlib.import_module("openap").aero
self.use_synonym = kwargs.get("use_synonym", False)
self.ac = ac.lower()
self.aircraft = prop.aircraft(ac, **kwargs)
self.polar = self.dragpolar()
self.wave_drag = wave_drag
if self.wave_drag:
warnings.warn("Performance warning: Wave drag model is experimental.")
def dragpolar(self):
"""Find and construct the drag polar model.
Returns:
dict: drag polar model parameters.
"""
polar_files = glob.glob(dir_dragpolar + "*.yml")
ac_polar_available = [s[-8:-4].lower() for s in polar_files]
if self.ac in ac_polar_available:
ac = self.ac
else:
syno = polar_synonym.query("orig==@self.ac")
if self.use_synonym and syno.shape[0] > 0:
ac = syno.new.iloc[0]
else:
raise RuntimeError(f"Drag polar for {self.ac} not avaiable in OpenAP.")
f = dir_dragpolar + ac + ".yml"
with open(f, "r") as file:
dragpolar = yaml.safe_load(file.read())
return dragpolar
@ndarrayconvert
def _cl(self, mass, tas, alt):
v = tas * self.aero.kts
h = alt * self.aero.ft
S = self.aircraft["wing"]["area"]
rho = self.aero.density(h)
qS = 0.5 * rho * v**2 * S
L = mass * self.aero.g0
qS = self.np.where(qS < 1e-3, 1e-3, qS)
cl = L / qS
return cl
@ndarrayconvert
def _calc_drag(self, mass, tas, alt, cd0, k, path_angle):
v = tas * self.aero.kts
h = alt * self.aero.ft
gamma = path_angle * self.np.pi / 180
S = self.aircraft["wing"]["area"]
rho = self.aero.density(h)
qS = 0.5 * rho * v**2 * S
L = mass * self.aero.g0 * self.np.cos(gamma)
qS = self.np.where(qS < 1e-3, 1e-3, qS)
cl = L / qS
cd = cd0 + k * cl**2
D = cd * qS
return D
@ndarrayconvert
def clean(self, mass, tas, alt, path_angle=0):
"""Compute drag at clean configuration (considering compressibility).
Args:
mass (int or ndarray): Mass of the aircraft (unit: kg).
tas (int or ndarray): True airspeed (unit: kt).
alt (int or ndarray): Altitude (unit: ft).
path_angle (float or ndarray): Path angle (unit: degree). Defaults to 0.
Returns:
int: Total drag (unit: N).
"""
cd0 = self.polar["clean"]["cd0"]
k = self.polar["clean"]["k"]
if self.wave_drag:
mach = self.aero.tas2mach(tas * self.aero.kts, alt * self.aero.ft)
cl = self._cl(mass, tas, alt)
sweep = self.np.radians(self.aircraft["wing"]["sweep"])
tc = self.aircraft["wing"]["t/c"]
if tc is None:
tc = 0.12
cos_sweep = self.np.cos(sweep)
kappa = 0.95 # assume supercritical airfoils
mach_crit = (
kappa / cos_sweep - tc / cos_sweep**2 - 0.1 * cl / cos_sweep**3 - 0.108
)
dmach = mach - mach_crit
dCdw = self.np.where(dmach > 0, 20 * dmach**4, 0)
else:
dCdw = 0
cd0 = cd0 + dCdw
D = self._calc_drag(mass, tas, alt, cd0, k, path_angle)
return D
@ndarrayconvert
def nonclean(self, mass, tas, alt, flap_angle, path_angle=0, landing_gear=False):
"""Compute drag at at non-clean configuration.
Args:
mass (int or ndarray): Mass of the aircraft (unit: kg).
tas (int or ndarray): True airspeed (unit: kt).
alt (int or ndarray): Altitude (unit: ft).
flap_angle (int or ndarray): flap deflection angle (unit: degree).
path_angle (float or ndarray): Path angle (unit: degree). Defaults to 0.
landing_gear (bool): Is landing gear extended? Defaults to False.
Returns:
int or ndarray: Total drag (unit: N).
"""
cd0 = self.polar["clean"]["cd0"]
k = self.polar["clean"]["k"]
# --- calc new CD0 ---
lambda_f = self.polar["flaps"]["lambda_f"]
cfc = self.polar["flaps"]["cf/c"]
SfS = self.polar["flaps"]["Sf/S"]
delta_cd_flap = (
lambda_f
* (cfc) ** 1.38
* (SfS)
* self.np.sin(flap_angle * self.np.pi / 180) ** 2
)
if landing_gear:
delta_cd_gear = (
self.aircraft["limits"]["MTOW"]
* 9.8065
/ self.aircraft["wing"]["area"]
* 3.16e-5
* self.aircraft["limits"]["MTOW"] ** (-0.215)
)
else:
delta_cd_gear = 0
cd0_total = cd0 + delta_cd_flap + delta_cd_gear
# --- calc new k ---
if self.aircraft["engine"]["mount"] == "rear":
delta_e_flap = 0.0046 * flap_angle
else:
delta_e_flap = 0.0026 * flap_angle
ar = self.aircraft["wing"]["span"] ** 2 / self.aircraft["wing"]["area"]
k_total = 1 / (1 / k + self.np.pi * ar * delta_e_flap)
D = self._calc_drag(mass, tas, alt, cd0_total, k_total, path_angle)
return D
|
(ac, wave_drag=False, **kwargs)
|
722,156 |
openap.drag
|
__init__
|
Initialize Drag object.
Args:
ac (string): ICAO aircraft type (for example: A320).
wave_drag (bool): enable wave_drag model (experimental).
|
def __init__(self, ac, wave_drag=False, **kwargs):
"""Initialize Drag object.
Args:
ac (string): ICAO aircraft type (for example: A320).
wave_drag (bool): enable wave_drag model (experimental).
"""
if not hasattr(self, "np"):
self.np = importlib.import_module("numpy")
if not hasattr(self, "aero"):
self.aero = importlib.import_module("openap").aero
self.use_synonym = kwargs.get("use_synonym", False)
self.ac = ac.lower()
self.aircraft = prop.aircraft(ac, **kwargs)
self.polar = self.dragpolar()
self.wave_drag = wave_drag
if self.wave_drag:
warnings.warn("Performance warning: Wave drag model is experimental.")
|
(self, ac, wave_drag=False, **kwargs)
|
722,157 |
openap.drag
|
_calc_drag
| null |
"""OpenAP drag model."""
import glob
import importlib
import os
import warnings
import pandas as pd
import yaml
from . import prop
from .extra import ndarrayconvert
curr_path = os.path.dirname(os.path.realpath(__file__))
dir_dragpolar = curr_path + "/data/dragpolar/"
file_synonym = curr_path + "/data/dragpolar/_synonym.csv"
polar_synonym = pd.read_csv(file_synonym)
class Drag(object):
"""Compute the drag of aircraft."""
def __init__(self, ac, wave_drag=False, **kwargs):
"""Initialize Drag object.
Args:
ac (string): ICAO aircraft type (for example: A320).
wave_drag (bool): enable wave_drag model (experimental).
"""
if not hasattr(self, "np"):
self.np = importlib.import_module("numpy")
if not hasattr(self, "aero"):
self.aero = importlib.import_module("openap").aero
self.use_synonym = kwargs.get("use_synonym", False)
self.ac = ac.lower()
self.aircraft = prop.aircraft(ac, **kwargs)
self.polar = self.dragpolar()
self.wave_drag = wave_drag
if self.wave_drag:
warnings.warn("Performance warning: Wave drag model is experimental.")
def dragpolar(self):
"""Find and construct the drag polar model.
Returns:
dict: drag polar model parameters.
"""
polar_files = glob.glob(dir_dragpolar + "*.yml")
ac_polar_available = [s[-8:-4].lower() for s in polar_files]
if self.ac in ac_polar_available:
ac = self.ac
else:
syno = polar_synonym.query("orig==@self.ac")
if self.use_synonym and syno.shape[0] > 0:
ac = syno.new.iloc[0]
else:
raise RuntimeError(f"Drag polar for {self.ac} not avaiable in OpenAP.")
f = dir_dragpolar + ac + ".yml"
with open(f, "r") as file:
dragpolar = yaml.safe_load(file.read())
return dragpolar
@ndarrayconvert
def _cl(self, mass, tas, alt):
v = tas * self.aero.kts
h = alt * self.aero.ft
S = self.aircraft["wing"]["area"]
rho = self.aero.density(h)
qS = 0.5 * rho * v**2 * S
L = mass * self.aero.g0
qS = self.np.where(qS < 1e-3, 1e-3, qS)
cl = L / qS
return cl
@ndarrayconvert
def _calc_drag(self, mass, tas, alt, cd0, k, path_angle):
v = tas * self.aero.kts
h = alt * self.aero.ft
gamma = path_angle * self.np.pi / 180
S = self.aircraft["wing"]["area"]
rho = self.aero.density(h)
qS = 0.5 * rho * v**2 * S
L = mass * self.aero.g0 * self.np.cos(gamma)
qS = self.np.where(qS < 1e-3, 1e-3, qS)
cl = L / qS
cd = cd0 + k * cl**2
D = cd * qS
return D
@ndarrayconvert
def clean(self, mass, tas, alt, path_angle=0):
"""Compute drag at clean configuration (considering compressibility).
Args:
mass (int or ndarray): Mass of the aircraft (unit: kg).
tas (int or ndarray): True airspeed (unit: kt).
alt (int or ndarray): Altitude (unit: ft).
path_angle (float or ndarray): Path angle (unit: degree). Defaults to 0.
Returns:
int: Total drag (unit: N).
"""
cd0 = self.polar["clean"]["cd0"]
k = self.polar["clean"]["k"]
if self.wave_drag:
mach = self.aero.tas2mach(tas * self.aero.kts, alt * self.aero.ft)
cl = self._cl(mass, tas, alt)
sweep = self.np.radians(self.aircraft["wing"]["sweep"])
tc = self.aircraft["wing"]["t/c"]
if tc is None:
tc = 0.12
cos_sweep = self.np.cos(sweep)
kappa = 0.95 # assume supercritical airfoils
mach_crit = (
kappa / cos_sweep - tc / cos_sweep**2 - 0.1 * cl / cos_sweep**3 - 0.108
)
dmach = mach - mach_crit
dCdw = self.np.where(dmach > 0, 20 * dmach**4, 0)
else:
dCdw = 0
cd0 = cd0 + dCdw
D = self._calc_drag(mass, tas, alt, cd0, k, path_angle)
return D
@ndarrayconvert
def nonclean(self, mass, tas, alt, flap_angle, path_angle=0, landing_gear=False):
"""Compute drag at at non-clean configuration.
Args:
mass (int or ndarray): Mass of the aircraft (unit: kg).
tas (int or ndarray): True airspeed (unit: kt).
alt (int or ndarray): Altitude (unit: ft).
flap_angle (int or ndarray): flap deflection angle (unit: degree).
path_angle (float or ndarray): Path angle (unit: degree). Defaults to 0.
landing_gear (bool): Is landing gear extended? Defaults to False.
Returns:
int or ndarray: Total drag (unit: N).
"""
cd0 = self.polar["clean"]["cd0"]
k = self.polar["clean"]["k"]
# --- calc new CD0 ---
lambda_f = self.polar["flaps"]["lambda_f"]
cfc = self.polar["flaps"]["cf/c"]
SfS = self.polar["flaps"]["Sf/S"]
delta_cd_flap = (
lambda_f
* (cfc) ** 1.38
* (SfS)
* self.np.sin(flap_angle * self.np.pi / 180) ** 2
)
if landing_gear:
delta_cd_gear = (
self.aircraft["limits"]["MTOW"]
* 9.8065
/ self.aircraft["wing"]["area"]
* 3.16e-5
* self.aircraft["limits"]["MTOW"] ** (-0.215)
)
else:
delta_cd_gear = 0
cd0_total = cd0 + delta_cd_flap + delta_cd_gear
# --- calc new k ---
if self.aircraft["engine"]["mount"] == "rear":
delta_e_flap = 0.0046 * flap_angle
else:
delta_e_flap = 0.0026 * flap_angle
ar = self.aircraft["wing"]["span"] ** 2 / self.aircraft["wing"]["area"]
k_total = 1 / (1 / k + self.np.pi * ar * delta_e_flap)
D = self._calc_drag(mass, tas, alt, cd0_total, k_total, path_angle)
return D
|
(self, mass, tas, alt, cd0, k, path_angle)
|
722,159 |
openap.drag
|
clean
|
Compute drag at clean configuration (considering compressibility).
Args:
mass (int or ndarray): Mass of the aircraft (unit: kg).
tas (int or ndarray): True airspeed (unit: kt).
alt (int or ndarray): Altitude (unit: ft).
path_angle (float or ndarray): Path angle (unit: degree). Defaults to 0.
Returns:
int: Total drag (unit: N).
|
"""OpenAP drag model."""
import glob
import importlib
import os
import warnings
import pandas as pd
import yaml
from . import prop
from .extra import ndarrayconvert
curr_path = os.path.dirname(os.path.realpath(__file__))
dir_dragpolar = curr_path + "/data/dragpolar/"
file_synonym = curr_path + "/data/dragpolar/_synonym.csv"
polar_synonym = pd.read_csv(file_synonym)
class Drag(object):
"""Compute the drag of aircraft."""
def __init__(self, ac, wave_drag=False, **kwargs):
"""Initialize Drag object.
Args:
ac (string): ICAO aircraft type (for example: A320).
wave_drag (bool): enable wave_drag model (experimental).
"""
if not hasattr(self, "np"):
self.np = importlib.import_module("numpy")
if not hasattr(self, "aero"):
self.aero = importlib.import_module("openap").aero
self.use_synonym = kwargs.get("use_synonym", False)
self.ac = ac.lower()
self.aircraft = prop.aircraft(ac, **kwargs)
self.polar = self.dragpolar()
self.wave_drag = wave_drag
if self.wave_drag:
warnings.warn("Performance warning: Wave drag model is experimental.")
def dragpolar(self):
"""Find and construct the drag polar model.
Returns:
dict: drag polar model parameters.
"""
polar_files = glob.glob(dir_dragpolar + "*.yml")
ac_polar_available = [s[-8:-4].lower() for s in polar_files]
if self.ac in ac_polar_available:
ac = self.ac
else:
syno = polar_synonym.query("orig==@self.ac")
if self.use_synonym and syno.shape[0] > 0:
ac = syno.new.iloc[0]
else:
raise RuntimeError(f"Drag polar for {self.ac} not avaiable in OpenAP.")
f = dir_dragpolar + ac + ".yml"
with open(f, "r") as file:
dragpolar = yaml.safe_load(file.read())
return dragpolar
@ndarrayconvert
def _cl(self, mass, tas, alt):
v = tas * self.aero.kts
h = alt * self.aero.ft
S = self.aircraft["wing"]["area"]
rho = self.aero.density(h)
qS = 0.5 * rho * v**2 * S
L = mass * self.aero.g0
qS = self.np.where(qS < 1e-3, 1e-3, qS)
cl = L / qS
return cl
@ndarrayconvert
def _calc_drag(self, mass, tas, alt, cd0, k, path_angle):
v = tas * self.aero.kts
h = alt * self.aero.ft
gamma = path_angle * self.np.pi / 180
S = self.aircraft["wing"]["area"]
rho = self.aero.density(h)
qS = 0.5 * rho * v**2 * S
L = mass * self.aero.g0 * self.np.cos(gamma)
qS = self.np.where(qS < 1e-3, 1e-3, qS)
cl = L / qS
cd = cd0 + k * cl**2
D = cd * qS
return D
@ndarrayconvert
def clean(self, mass, tas, alt, path_angle=0):
"""Compute drag at clean configuration (considering compressibility).
Args:
mass (int or ndarray): Mass of the aircraft (unit: kg).
tas (int or ndarray): True airspeed (unit: kt).
alt (int or ndarray): Altitude (unit: ft).
path_angle (float or ndarray): Path angle (unit: degree). Defaults to 0.
Returns:
int: Total drag (unit: N).
"""
cd0 = self.polar["clean"]["cd0"]
k = self.polar["clean"]["k"]
if self.wave_drag:
mach = self.aero.tas2mach(tas * self.aero.kts, alt * self.aero.ft)
cl = self._cl(mass, tas, alt)
sweep = self.np.radians(self.aircraft["wing"]["sweep"])
tc = self.aircraft["wing"]["t/c"]
if tc is None:
tc = 0.12
cos_sweep = self.np.cos(sweep)
kappa = 0.95 # assume supercritical airfoils
mach_crit = (
kappa / cos_sweep - tc / cos_sweep**2 - 0.1 * cl / cos_sweep**3 - 0.108
)
dmach = mach - mach_crit
dCdw = self.np.where(dmach > 0, 20 * dmach**4, 0)
else:
dCdw = 0
cd0 = cd0 + dCdw
D = self._calc_drag(mass, tas, alt, cd0, k, path_angle)
return D
@ndarrayconvert
def nonclean(self, mass, tas, alt, flap_angle, path_angle=0, landing_gear=False):
"""Compute drag at at non-clean configuration.
Args:
mass (int or ndarray): Mass of the aircraft (unit: kg).
tas (int or ndarray): True airspeed (unit: kt).
alt (int or ndarray): Altitude (unit: ft).
flap_angle (int or ndarray): flap deflection angle (unit: degree).
path_angle (float or ndarray): Path angle (unit: degree). Defaults to 0.
landing_gear (bool): Is landing gear extended? Defaults to False.
Returns:
int or ndarray: Total drag (unit: N).
"""
cd0 = self.polar["clean"]["cd0"]
k = self.polar["clean"]["k"]
# --- calc new CD0 ---
lambda_f = self.polar["flaps"]["lambda_f"]
cfc = self.polar["flaps"]["cf/c"]
SfS = self.polar["flaps"]["Sf/S"]
delta_cd_flap = (
lambda_f
* (cfc) ** 1.38
* (SfS)
* self.np.sin(flap_angle * self.np.pi / 180) ** 2
)
if landing_gear:
delta_cd_gear = (
self.aircraft["limits"]["MTOW"]
* 9.8065
/ self.aircraft["wing"]["area"]
* 3.16e-5
* self.aircraft["limits"]["MTOW"] ** (-0.215)
)
else:
delta_cd_gear = 0
cd0_total = cd0 + delta_cd_flap + delta_cd_gear
# --- calc new k ---
if self.aircraft["engine"]["mount"] == "rear":
delta_e_flap = 0.0046 * flap_angle
else:
delta_e_flap = 0.0026 * flap_angle
ar = self.aircraft["wing"]["span"] ** 2 / self.aircraft["wing"]["area"]
k_total = 1 / (1 / k + self.np.pi * ar * delta_e_flap)
D = self._calc_drag(mass, tas, alt, cd0_total, k_total, path_angle)
return D
|
(self, mass, tas, alt, path_angle=0)
|
722,160 |
openap.drag
|
dragpolar
|
Find and construct the drag polar model.
Returns:
dict: drag polar model parameters.
|
def dragpolar(self):
"""Find and construct the drag polar model.
Returns:
dict: drag polar model parameters.
"""
polar_files = glob.glob(dir_dragpolar + "*.yml")
ac_polar_available = [s[-8:-4].lower() for s in polar_files]
if self.ac in ac_polar_available:
ac = self.ac
else:
syno = polar_synonym.query("orig==@self.ac")
if self.use_synonym and syno.shape[0] > 0:
ac = syno.new.iloc[0]
else:
raise RuntimeError(f"Drag polar for {self.ac} not avaiable in OpenAP.")
f = dir_dragpolar + ac + ".yml"
with open(f, "r") as file:
dragpolar = yaml.safe_load(file.read())
return dragpolar
|
(self)
|
722,161 |
openap.drag
|
nonclean
|
Compute drag at at non-clean configuration.
Args:
mass (int or ndarray): Mass of the aircraft (unit: kg).
tas (int or ndarray): True airspeed (unit: kt).
alt (int or ndarray): Altitude (unit: ft).
flap_angle (int or ndarray): flap deflection angle (unit: degree).
path_angle (float or ndarray): Path angle (unit: degree). Defaults to 0.
landing_gear (bool): Is landing gear extended? Defaults to False.
Returns:
int or ndarray: Total drag (unit: N).
|
"""OpenAP drag model."""
import glob
import importlib
import os
import warnings
import pandas as pd
import yaml
from . import prop
from .extra import ndarrayconvert
curr_path = os.path.dirname(os.path.realpath(__file__))
dir_dragpolar = curr_path + "/data/dragpolar/"
file_synonym = curr_path + "/data/dragpolar/_synonym.csv"
polar_synonym = pd.read_csv(file_synonym)
class Drag(object):
"""Compute the drag of aircraft."""
def __init__(self, ac, wave_drag=False, **kwargs):
"""Initialize Drag object.
Args:
ac (string): ICAO aircraft type (for example: A320).
wave_drag (bool): enable wave_drag model (experimental).
"""
if not hasattr(self, "np"):
self.np = importlib.import_module("numpy")
if not hasattr(self, "aero"):
self.aero = importlib.import_module("openap").aero
self.use_synonym = kwargs.get("use_synonym", False)
self.ac = ac.lower()
self.aircraft = prop.aircraft(ac, **kwargs)
self.polar = self.dragpolar()
self.wave_drag = wave_drag
if self.wave_drag:
warnings.warn("Performance warning: Wave drag model is experimental.")
def dragpolar(self):
"""Find and construct the drag polar model.
Returns:
dict: drag polar model parameters.
"""
polar_files = glob.glob(dir_dragpolar + "*.yml")
ac_polar_available = [s[-8:-4].lower() for s in polar_files]
if self.ac in ac_polar_available:
ac = self.ac
else:
syno = polar_synonym.query("orig==@self.ac")
if self.use_synonym and syno.shape[0] > 0:
ac = syno.new.iloc[0]
else:
raise RuntimeError(f"Drag polar for {self.ac} not avaiable in OpenAP.")
f = dir_dragpolar + ac + ".yml"
with open(f, "r") as file:
dragpolar = yaml.safe_load(file.read())
return dragpolar
@ndarrayconvert
def _cl(self, mass, tas, alt):
v = tas * self.aero.kts
h = alt * self.aero.ft
S = self.aircraft["wing"]["area"]
rho = self.aero.density(h)
qS = 0.5 * rho * v**2 * S
L = mass * self.aero.g0
qS = self.np.where(qS < 1e-3, 1e-3, qS)
cl = L / qS
return cl
@ndarrayconvert
def _calc_drag(self, mass, tas, alt, cd0, k, path_angle):
v = tas * self.aero.kts
h = alt * self.aero.ft
gamma = path_angle * self.np.pi / 180
S = self.aircraft["wing"]["area"]
rho = self.aero.density(h)
qS = 0.5 * rho * v**2 * S
L = mass * self.aero.g0 * self.np.cos(gamma)
qS = self.np.where(qS < 1e-3, 1e-3, qS)
cl = L / qS
cd = cd0 + k * cl**2
D = cd * qS
return D
@ndarrayconvert
def clean(self, mass, tas, alt, path_angle=0):
"""Compute drag at clean configuration (considering compressibility).
Args:
mass (int or ndarray): Mass of the aircraft (unit: kg).
tas (int or ndarray): True airspeed (unit: kt).
alt (int or ndarray): Altitude (unit: ft).
path_angle (float or ndarray): Path angle (unit: degree). Defaults to 0.
Returns:
int: Total drag (unit: N).
"""
cd0 = self.polar["clean"]["cd0"]
k = self.polar["clean"]["k"]
if self.wave_drag:
mach = self.aero.tas2mach(tas * self.aero.kts, alt * self.aero.ft)
cl = self._cl(mass, tas, alt)
sweep = self.np.radians(self.aircraft["wing"]["sweep"])
tc = self.aircraft["wing"]["t/c"]
if tc is None:
tc = 0.12
cos_sweep = self.np.cos(sweep)
kappa = 0.95 # assume supercritical airfoils
mach_crit = (
kappa / cos_sweep - tc / cos_sweep**2 - 0.1 * cl / cos_sweep**3 - 0.108
)
dmach = mach - mach_crit
dCdw = self.np.where(dmach > 0, 20 * dmach**4, 0)
else:
dCdw = 0
cd0 = cd0 + dCdw
D = self._calc_drag(mass, tas, alt, cd0, k, path_angle)
return D
@ndarrayconvert
def nonclean(self, mass, tas, alt, flap_angle, path_angle=0, landing_gear=False):
"""Compute drag at at non-clean configuration.
Args:
mass (int or ndarray): Mass of the aircraft (unit: kg).
tas (int or ndarray): True airspeed (unit: kt).
alt (int or ndarray): Altitude (unit: ft).
flap_angle (int or ndarray): flap deflection angle (unit: degree).
path_angle (float or ndarray): Path angle (unit: degree). Defaults to 0.
landing_gear (bool): Is landing gear extended? Defaults to False.
Returns:
int or ndarray: Total drag (unit: N).
"""
cd0 = self.polar["clean"]["cd0"]
k = self.polar["clean"]["k"]
# --- calc new CD0 ---
lambda_f = self.polar["flaps"]["lambda_f"]
cfc = self.polar["flaps"]["cf/c"]
SfS = self.polar["flaps"]["Sf/S"]
delta_cd_flap = (
lambda_f
* (cfc) ** 1.38
* (SfS)
* self.np.sin(flap_angle * self.np.pi / 180) ** 2
)
if landing_gear:
delta_cd_gear = (
self.aircraft["limits"]["MTOW"]
* 9.8065
/ self.aircraft["wing"]["area"]
* 3.16e-5
* self.aircraft["limits"]["MTOW"] ** (-0.215)
)
else:
delta_cd_gear = 0
cd0_total = cd0 + delta_cd_flap + delta_cd_gear
# --- calc new k ---
if self.aircraft["engine"]["mount"] == "rear":
delta_e_flap = 0.0046 * flap_angle
else:
delta_e_flap = 0.0026 * flap_angle
ar = self.aircraft["wing"]["span"] ** 2 / self.aircraft["wing"]["area"]
k_total = 1 / (1 / k + self.np.pi * ar * delta_e_flap)
D = self._calc_drag(mass, tas, alt, cd0_total, k_total, path_angle)
return D
|
(self, mass, tas, alt, flap_angle, path_angle=0, landing_gear=False)
|
722,162 |
openap.emission
|
Emission
|
Emission model based on ICAO emmision databank.
|
class Emission(object):
"""Emission model based on ICAO emmision databank."""
def __init__(self, ac, eng=None, **kwargs):
"""Initialize Emission object.
Args:
ac (string): ICAO aircraft type (for example: A320).
eng (string): Engine type (for example: CFM56-5A3).
Leave empty to use the default engine specified
by in the aircraft database.
"""
if not hasattr(self, "np"):
self.np = importlib.import_module("numpy")
if not hasattr(self, "aero"):
self.aero = importlib.import_module("openap").aero
self.ac = prop.aircraft(ac, **kwargs)
self.n_eng = self.ac["engine"]["number"]
if eng is None:
eng = self.ac["engine"]["default"]
self.engine = prop.engine(eng)
def _fl2sl(self, ffac, tas, alt):
"""Convert to sea-level equivalent"""
M = self.aero.tas2mach(tas * self.aero.kts, alt * self.aero.ft)
beta = self.np.exp(0.2 * (M ** 2))
theta = (self.aero.temperature(alt * self.aero.ft) / 288.15) / beta
delta = (1 - 0.0019812 * alt / 288.15) ** 5.255876 / self.np.power(beta, 3.5)
ratio = (theta ** 3.3) / (delta ** 1.02)
ff_sl = (ffac / self.n_eng) * theta ** 3.8 / delta * beta
return ff_sl, ratio
@ndarrayconvert
def co2(self, ffac):
"""Compute CO2 emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: CO2 emission from all engines (unit: g/s).
"""
return ffac * 3149
@ndarrayconvert
def h2o(self, ffac):
"""Compute H2O emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: H2O emission from all engines (unit: g/s).
"""
return ffac * 1230
@ndarrayconvert
def soot(self, ffac):
"""Compute soot emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: Soot emission from all engines (unit: g/s).
"""
return ffac * 0.03
@ndarrayconvert
def sox(self, ffac):
"""Compute SOx emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: SOx emission from all engines (unit: g/s).
"""
return ffac * 0.84
@ndarrayconvert
def nox(self, ffac, tas, alt=0):
"""Compute NOx emission with given fuel flow, speed, and altitude.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
tas (float or ndarray): Speed (unit: kt).
alt (int or ndarray): Aircraft altitude (unit: ft).
Returns:
float: NOx emission from all engines (unit: g/s).
"""
ff_sl, ratio = self._fl2sl(ffac, tas, alt)
nox_sl = self.np.interp(
ff_sl,
[
self.engine["ff_idl"],
self.engine["ff_app"],
self.engine["ff_co"],
self.engine["ff_to"],
],
[
self.engine["ei_nox_idl"],
self.engine["ei_nox_app"],
self.engine["ei_nox_co"],
self.engine["ei_nox_to"],
],
)
# convert back to actual flight level
omega = 10 ** (-3) * self.np.exp(-0.0001426 * (alt - 12900))
nox_fl = nox_sl * self.np.sqrt(1 / ratio) * self.np.exp(-19 * (omega - 0.00634))
# convert g/(kg fuel) to g/s for all engines
nox_rate = nox_fl * ffac
return nox_rate
@ndarrayconvert
def co(self, ffac, tas, alt=0):
"""Compute CO emission with given fuel flow, speed, and altitude.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
tas (float or ndarray): Speed (unit: kt).
alt (int or ndarray): Aircraft altitude (unit: ft).
Returns:
float: CO emission from all engines (unit: g/s).
"""
ff_sl, ratio = self._fl2sl(ffac, tas, alt)
co_sl = self.np.interp(
ff_sl,
[
self.engine["ff_idl"],
self.engine["ff_app"],
self.engine["ff_co"],
self.engine["ff_to"],
],
[
self.engine["ei_co_idl"],
self.engine["ei_co_app"],
self.engine["ei_co_co"],
self.engine["ei_co_to"],
],
)
# convert back to actual flight level
co_fl = co_sl * ratio
# convert g/(kg fuel) to g/s for all engines
co_rate = co_fl * ffac
return co_rate
@ndarrayconvert
def hc(self, ffac, tas, alt=0):
"""Compute HC emission with given fuel flow, speed, and altitude.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
tas (float or ndarray): Speed (unit: kt).
alt (int or ndarray): Aircraft altitude (unit: ft).
Returns:
float: HC emission from all engines (unit: g/s).
"""
ff_sl, ratio = self._fl2sl(ffac, tas, alt)
hc_sl = self.np.interp(
ff_sl,
[
self.engine["ff_idl"],
self.engine["ff_app"],
self.engine["ff_co"],
self.engine["ff_to"],
],
[
self.engine["ei_hc_idl"],
self.engine["ei_hc_app"],
self.engine["ei_hc_co"],
self.engine["ei_hc_to"],
],
)
# convert back to actual flight level
hc_fl = hc_sl * ratio
# convert g/(kg fuel) to g/s for all engines
hc_rate = hc_fl * ffac
return hc_rate
|
(ac, eng=None, **kwargs)
|
722,163 |
openap.emission
|
__init__
|
Initialize Emission object.
Args:
ac (string): ICAO aircraft type (for example: A320).
eng (string): Engine type (for example: CFM56-5A3).
Leave empty to use the default engine specified
by in the aircraft database.
|
def __init__(self, ac, eng=None, **kwargs):
"""Initialize Emission object.
Args:
ac (string): ICAO aircraft type (for example: A320).
eng (string): Engine type (for example: CFM56-5A3).
Leave empty to use the default engine specified
by in the aircraft database.
"""
if not hasattr(self, "np"):
self.np = importlib.import_module("numpy")
if not hasattr(self, "aero"):
self.aero = importlib.import_module("openap").aero
self.ac = prop.aircraft(ac, **kwargs)
self.n_eng = self.ac["engine"]["number"]
if eng is None:
eng = self.ac["engine"]["default"]
self.engine = prop.engine(eng)
|
(self, ac, eng=None, **kwargs)
|
722,164 |
openap.emission
|
_fl2sl
|
Convert to sea-level equivalent
|
def _fl2sl(self, ffac, tas, alt):
"""Convert to sea-level equivalent"""
M = self.aero.tas2mach(tas * self.aero.kts, alt * self.aero.ft)
beta = self.np.exp(0.2 * (M ** 2))
theta = (self.aero.temperature(alt * self.aero.ft) / 288.15) / beta
delta = (1 - 0.0019812 * alt / 288.15) ** 5.255876 / self.np.power(beta, 3.5)
ratio = (theta ** 3.3) / (delta ** 1.02)
ff_sl = (ffac / self.n_eng) * theta ** 3.8 / delta * beta
return ff_sl, ratio
|
(self, ffac, tas, alt)
|
722,165 |
openap.emission
|
co
|
Compute CO emission with given fuel flow, speed, and altitude.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
tas (float or ndarray): Speed (unit: kt).
alt (int or ndarray): Aircraft altitude (unit: ft).
Returns:
float: CO emission from all engines (unit: g/s).
|
"""OpenAP FuelFlow model."""
import importlib
from openap import prop
from openap.extra import ndarrayconvert
class Emission(object):
"""Emission model based on ICAO emmision databank."""
def __init__(self, ac, eng=None, **kwargs):
"""Initialize Emission object.
Args:
ac (string): ICAO aircraft type (for example: A320).
eng (string): Engine type (for example: CFM56-5A3).
Leave empty to use the default engine specified
by in the aircraft database.
"""
if not hasattr(self, "np"):
self.np = importlib.import_module("numpy")
if not hasattr(self, "aero"):
self.aero = importlib.import_module("openap").aero
self.ac = prop.aircraft(ac, **kwargs)
self.n_eng = self.ac["engine"]["number"]
if eng is None:
eng = self.ac["engine"]["default"]
self.engine = prop.engine(eng)
def _fl2sl(self, ffac, tas, alt):
"""Convert to sea-level equivalent"""
M = self.aero.tas2mach(tas * self.aero.kts, alt * self.aero.ft)
beta = self.np.exp(0.2 * (M ** 2))
theta = (self.aero.temperature(alt * self.aero.ft) / 288.15) / beta
delta = (1 - 0.0019812 * alt / 288.15) ** 5.255876 / self.np.power(beta, 3.5)
ratio = (theta ** 3.3) / (delta ** 1.02)
ff_sl = (ffac / self.n_eng) * theta ** 3.8 / delta * beta
return ff_sl, ratio
@ndarrayconvert
def co2(self, ffac):
"""Compute CO2 emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: CO2 emission from all engines (unit: g/s).
"""
return ffac * 3149
@ndarrayconvert
def h2o(self, ffac):
"""Compute H2O emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: H2O emission from all engines (unit: g/s).
"""
return ffac * 1230
@ndarrayconvert
def soot(self, ffac):
"""Compute soot emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: Soot emission from all engines (unit: g/s).
"""
return ffac * 0.03
@ndarrayconvert
def sox(self, ffac):
"""Compute SOx emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: SOx emission from all engines (unit: g/s).
"""
return ffac * 0.84
@ndarrayconvert
def nox(self, ffac, tas, alt=0):
"""Compute NOx emission with given fuel flow, speed, and altitude.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
tas (float or ndarray): Speed (unit: kt).
alt (int or ndarray): Aircraft altitude (unit: ft).
Returns:
float: NOx emission from all engines (unit: g/s).
"""
ff_sl, ratio = self._fl2sl(ffac, tas, alt)
nox_sl = self.np.interp(
ff_sl,
[
self.engine["ff_idl"],
self.engine["ff_app"],
self.engine["ff_co"],
self.engine["ff_to"],
],
[
self.engine["ei_nox_idl"],
self.engine["ei_nox_app"],
self.engine["ei_nox_co"],
self.engine["ei_nox_to"],
],
)
# convert back to actual flight level
omega = 10 ** (-3) * self.np.exp(-0.0001426 * (alt - 12900))
nox_fl = nox_sl * self.np.sqrt(1 / ratio) * self.np.exp(-19 * (omega - 0.00634))
# convert g/(kg fuel) to g/s for all engines
nox_rate = nox_fl * ffac
return nox_rate
@ndarrayconvert
def co(self, ffac, tas, alt=0):
"""Compute CO emission with given fuel flow, speed, and altitude.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
tas (float or ndarray): Speed (unit: kt).
alt (int or ndarray): Aircraft altitude (unit: ft).
Returns:
float: CO emission from all engines (unit: g/s).
"""
ff_sl, ratio = self._fl2sl(ffac, tas, alt)
co_sl = self.np.interp(
ff_sl,
[
self.engine["ff_idl"],
self.engine["ff_app"],
self.engine["ff_co"],
self.engine["ff_to"],
],
[
self.engine["ei_co_idl"],
self.engine["ei_co_app"],
self.engine["ei_co_co"],
self.engine["ei_co_to"],
],
)
# convert back to actual flight level
co_fl = co_sl * ratio
# convert g/(kg fuel) to g/s for all engines
co_rate = co_fl * ffac
return co_rate
@ndarrayconvert
def hc(self, ffac, tas, alt=0):
"""Compute HC emission with given fuel flow, speed, and altitude.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
tas (float or ndarray): Speed (unit: kt).
alt (int or ndarray): Aircraft altitude (unit: ft).
Returns:
float: HC emission from all engines (unit: g/s).
"""
ff_sl, ratio = self._fl2sl(ffac, tas, alt)
hc_sl = self.np.interp(
ff_sl,
[
self.engine["ff_idl"],
self.engine["ff_app"],
self.engine["ff_co"],
self.engine["ff_to"],
],
[
self.engine["ei_hc_idl"],
self.engine["ei_hc_app"],
self.engine["ei_hc_co"],
self.engine["ei_hc_to"],
],
)
# convert back to actual flight level
hc_fl = hc_sl * ratio
# convert g/(kg fuel) to g/s for all engines
hc_rate = hc_fl * ffac
return hc_rate
|
(self, ffac, tas, alt=0)
|
722,166 |
openap.emission
|
co2
|
Compute CO2 emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: CO2 emission from all engines (unit: g/s).
|
"""OpenAP FuelFlow model."""
import importlib
from openap import prop
from openap.extra import ndarrayconvert
class Emission(object):
"""Emission model based on ICAO emmision databank."""
def __init__(self, ac, eng=None, **kwargs):
"""Initialize Emission object.
Args:
ac (string): ICAO aircraft type (for example: A320).
eng (string): Engine type (for example: CFM56-5A3).
Leave empty to use the default engine specified
by in the aircraft database.
"""
if not hasattr(self, "np"):
self.np = importlib.import_module("numpy")
if not hasattr(self, "aero"):
self.aero = importlib.import_module("openap").aero
self.ac = prop.aircraft(ac, **kwargs)
self.n_eng = self.ac["engine"]["number"]
if eng is None:
eng = self.ac["engine"]["default"]
self.engine = prop.engine(eng)
def _fl2sl(self, ffac, tas, alt):
"""Convert to sea-level equivalent"""
M = self.aero.tas2mach(tas * self.aero.kts, alt * self.aero.ft)
beta = self.np.exp(0.2 * (M ** 2))
theta = (self.aero.temperature(alt * self.aero.ft) / 288.15) / beta
delta = (1 - 0.0019812 * alt / 288.15) ** 5.255876 / self.np.power(beta, 3.5)
ratio = (theta ** 3.3) / (delta ** 1.02)
ff_sl = (ffac / self.n_eng) * theta ** 3.8 / delta * beta
return ff_sl, ratio
@ndarrayconvert
def co2(self, ffac):
"""Compute CO2 emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: CO2 emission from all engines (unit: g/s).
"""
return ffac * 3149
@ndarrayconvert
def h2o(self, ffac):
"""Compute H2O emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: H2O emission from all engines (unit: g/s).
"""
return ffac * 1230
@ndarrayconvert
def soot(self, ffac):
"""Compute soot emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: Soot emission from all engines (unit: g/s).
"""
return ffac * 0.03
@ndarrayconvert
def sox(self, ffac):
"""Compute SOx emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: SOx emission from all engines (unit: g/s).
"""
return ffac * 0.84
@ndarrayconvert
def nox(self, ffac, tas, alt=0):
"""Compute NOx emission with given fuel flow, speed, and altitude.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
tas (float or ndarray): Speed (unit: kt).
alt (int or ndarray): Aircraft altitude (unit: ft).
Returns:
float: NOx emission from all engines (unit: g/s).
"""
ff_sl, ratio = self._fl2sl(ffac, tas, alt)
nox_sl = self.np.interp(
ff_sl,
[
self.engine["ff_idl"],
self.engine["ff_app"],
self.engine["ff_co"],
self.engine["ff_to"],
],
[
self.engine["ei_nox_idl"],
self.engine["ei_nox_app"],
self.engine["ei_nox_co"],
self.engine["ei_nox_to"],
],
)
# convert back to actual flight level
omega = 10 ** (-3) * self.np.exp(-0.0001426 * (alt - 12900))
nox_fl = nox_sl * self.np.sqrt(1 / ratio) * self.np.exp(-19 * (omega - 0.00634))
# convert g/(kg fuel) to g/s for all engines
nox_rate = nox_fl * ffac
return nox_rate
@ndarrayconvert
def co(self, ffac, tas, alt=0):
"""Compute CO emission with given fuel flow, speed, and altitude.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
tas (float or ndarray): Speed (unit: kt).
alt (int or ndarray): Aircraft altitude (unit: ft).
Returns:
float: CO emission from all engines (unit: g/s).
"""
ff_sl, ratio = self._fl2sl(ffac, tas, alt)
co_sl = self.np.interp(
ff_sl,
[
self.engine["ff_idl"],
self.engine["ff_app"],
self.engine["ff_co"],
self.engine["ff_to"],
],
[
self.engine["ei_co_idl"],
self.engine["ei_co_app"],
self.engine["ei_co_co"],
self.engine["ei_co_to"],
],
)
# convert back to actual flight level
co_fl = co_sl * ratio
# convert g/(kg fuel) to g/s for all engines
co_rate = co_fl * ffac
return co_rate
@ndarrayconvert
def hc(self, ffac, tas, alt=0):
"""Compute HC emission with given fuel flow, speed, and altitude.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
tas (float or ndarray): Speed (unit: kt).
alt (int or ndarray): Aircraft altitude (unit: ft).
Returns:
float: HC emission from all engines (unit: g/s).
"""
ff_sl, ratio = self._fl2sl(ffac, tas, alt)
hc_sl = self.np.interp(
ff_sl,
[
self.engine["ff_idl"],
self.engine["ff_app"],
self.engine["ff_co"],
self.engine["ff_to"],
],
[
self.engine["ei_hc_idl"],
self.engine["ei_hc_app"],
self.engine["ei_hc_co"],
self.engine["ei_hc_to"],
],
)
# convert back to actual flight level
hc_fl = hc_sl * ratio
# convert g/(kg fuel) to g/s for all engines
hc_rate = hc_fl * ffac
return hc_rate
|
(self, ffac)
|
722,167 |
openap.emission
|
h2o
|
Compute H2O emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: H2O emission from all engines (unit: g/s).
|
"""OpenAP FuelFlow model."""
import importlib
from openap import prop
from openap.extra import ndarrayconvert
class Emission(object):
"""Emission model based on ICAO emmision databank."""
def __init__(self, ac, eng=None, **kwargs):
"""Initialize Emission object.
Args:
ac (string): ICAO aircraft type (for example: A320).
eng (string): Engine type (for example: CFM56-5A3).
Leave empty to use the default engine specified
by in the aircraft database.
"""
if not hasattr(self, "np"):
self.np = importlib.import_module("numpy")
if not hasattr(self, "aero"):
self.aero = importlib.import_module("openap").aero
self.ac = prop.aircraft(ac, **kwargs)
self.n_eng = self.ac["engine"]["number"]
if eng is None:
eng = self.ac["engine"]["default"]
self.engine = prop.engine(eng)
def _fl2sl(self, ffac, tas, alt):
"""Convert to sea-level equivalent"""
M = self.aero.tas2mach(tas * self.aero.kts, alt * self.aero.ft)
beta = self.np.exp(0.2 * (M ** 2))
theta = (self.aero.temperature(alt * self.aero.ft) / 288.15) / beta
delta = (1 - 0.0019812 * alt / 288.15) ** 5.255876 / self.np.power(beta, 3.5)
ratio = (theta ** 3.3) / (delta ** 1.02)
ff_sl = (ffac / self.n_eng) * theta ** 3.8 / delta * beta
return ff_sl, ratio
@ndarrayconvert
def co2(self, ffac):
"""Compute CO2 emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: CO2 emission from all engines (unit: g/s).
"""
return ffac * 3149
@ndarrayconvert
def h2o(self, ffac):
"""Compute H2O emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: H2O emission from all engines (unit: g/s).
"""
return ffac * 1230
@ndarrayconvert
def soot(self, ffac):
"""Compute soot emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: Soot emission from all engines (unit: g/s).
"""
return ffac * 0.03
@ndarrayconvert
def sox(self, ffac):
"""Compute SOx emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: SOx emission from all engines (unit: g/s).
"""
return ffac * 0.84
@ndarrayconvert
def nox(self, ffac, tas, alt=0):
"""Compute NOx emission with given fuel flow, speed, and altitude.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
tas (float or ndarray): Speed (unit: kt).
alt (int or ndarray): Aircraft altitude (unit: ft).
Returns:
float: NOx emission from all engines (unit: g/s).
"""
ff_sl, ratio = self._fl2sl(ffac, tas, alt)
nox_sl = self.np.interp(
ff_sl,
[
self.engine["ff_idl"],
self.engine["ff_app"],
self.engine["ff_co"],
self.engine["ff_to"],
],
[
self.engine["ei_nox_idl"],
self.engine["ei_nox_app"],
self.engine["ei_nox_co"],
self.engine["ei_nox_to"],
],
)
# convert back to actual flight level
omega = 10 ** (-3) * self.np.exp(-0.0001426 * (alt - 12900))
nox_fl = nox_sl * self.np.sqrt(1 / ratio) * self.np.exp(-19 * (omega - 0.00634))
# convert g/(kg fuel) to g/s for all engines
nox_rate = nox_fl * ffac
return nox_rate
@ndarrayconvert
def co(self, ffac, tas, alt=0):
"""Compute CO emission with given fuel flow, speed, and altitude.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
tas (float or ndarray): Speed (unit: kt).
alt (int or ndarray): Aircraft altitude (unit: ft).
Returns:
float: CO emission from all engines (unit: g/s).
"""
ff_sl, ratio = self._fl2sl(ffac, tas, alt)
co_sl = self.np.interp(
ff_sl,
[
self.engine["ff_idl"],
self.engine["ff_app"],
self.engine["ff_co"],
self.engine["ff_to"],
],
[
self.engine["ei_co_idl"],
self.engine["ei_co_app"],
self.engine["ei_co_co"],
self.engine["ei_co_to"],
],
)
# convert back to actual flight level
co_fl = co_sl * ratio
# convert g/(kg fuel) to g/s for all engines
co_rate = co_fl * ffac
return co_rate
@ndarrayconvert
def hc(self, ffac, tas, alt=0):
"""Compute HC emission with given fuel flow, speed, and altitude.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
tas (float or ndarray): Speed (unit: kt).
alt (int or ndarray): Aircraft altitude (unit: ft).
Returns:
float: HC emission from all engines (unit: g/s).
"""
ff_sl, ratio = self._fl2sl(ffac, tas, alt)
hc_sl = self.np.interp(
ff_sl,
[
self.engine["ff_idl"],
self.engine["ff_app"],
self.engine["ff_co"],
self.engine["ff_to"],
],
[
self.engine["ei_hc_idl"],
self.engine["ei_hc_app"],
self.engine["ei_hc_co"],
self.engine["ei_hc_to"],
],
)
# convert back to actual flight level
hc_fl = hc_sl * ratio
# convert g/(kg fuel) to g/s for all engines
hc_rate = hc_fl * ffac
return hc_rate
|
(self, ffac)
|
722,168 |
openap.emission
|
hc
|
Compute HC emission with given fuel flow, speed, and altitude.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
tas (float or ndarray): Speed (unit: kt).
alt (int or ndarray): Aircraft altitude (unit: ft).
Returns:
float: HC emission from all engines (unit: g/s).
|
"""OpenAP FuelFlow model."""
import importlib
from openap import prop
from openap.extra import ndarrayconvert
class Emission(object):
"""Emission model based on ICAO emmision databank."""
def __init__(self, ac, eng=None, **kwargs):
"""Initialize Emission object.
Args:
ac (string): ICAO aircraft type (for example: A320).
eng (string): Engine type (for example: CFM56-5A3).
Leave empty to use the default engine specified
by in the aircraft database.
"""
if not hasattr(self, "np"):
self.np = importlib.import_module("numpy")
if not hasattr(self, "aero"):
self.aero = importlib.import_module("openap").aero
self.ac = prop.aircraft(ac, **kwargs)
self.n_eng = self.ac["engine"]["number"]
if eng is None:
eng = self.ac["engine"]["default"]
self.engine = prop.engine(eng)
def _fl2sl(self, ffac, tas, alt):
"""Convert to sea-level equivalent"""
M = self.aero.tas2mach(tas * self.aero.kts, alt * self.aero.ft)
beta = self.np.exp(0.2 * (M ** 2))
theta = (self.aero.temperature(alt * self.aero.ft) / 288.15) / beta
delta = (1 - 0.0019812 * alt / 288.15) ** 5.255876 / self.np.power(beta, 3.5)
ratio = (theta ** 3.3) / (delta ** 1.02)
ff_sl = (ffac / self.n_eng) * theta ** 3.8 / delta * beta
return ff_sl, ratio
@ndarrayconvert
def co2(self, ffac):
"""Compute CO2 emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: CO2 emission from all engines (unit: g/s).
"""
return ffac * 3149
@ndarrayconvert
def h2o(self, ffac):
"""Compute H2O emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: H2O emission from all engines (unit: g/s).
"""
return ffac * 1230
@ndarrayconvert
def soot(self, ffac):
"""Compute soot emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: Soot emission from all engines (unit: g/s).
"""
return ffac * 0.03
@ndarrayconvert
def sox(self, ffac):
"""Compute SOx emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: SOx emission from all engines (unit: g/s).
"""
return ffac * 0.84
@ndarrayconvert
def nox(self, ffac, tas, alt=0):
"""Compute NOx emission with given fuel flow, speed, and altitude.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
tas (float or ndarray): Speed (unit: kt).
alt (int or ndarray): Aircraft altitude (unit: ft).
Returns:
float: NOx emission from all engines (unit: g/s).
"""
ff_sl, ratio = self._fl2sl(ffac, tas, alt)
nox_sl = self.np.interp(
ff_sl,
[
self.engine["ff_idl"],
self.engine["ff_app"],
self.engine["ff_co"],
self.engine["ff_to"],
],
[
self.engine["ei_nox_idl"],
self.engine["ei_nox_app"],
self.engine["ei_nox_co"],
self.engine["ei_nox_to"],
],
)
# convert back to actual flight level
omega = 10 ** (-3) * self.np.exp(-0.0001426 * (alt - 12900))
nox_fl = nox_sl * self.np.sqrt(1 / ratio) * self.np.exp(-19 * (omega - 0.00634))
# convert g/(kg fuel) to g/s for all engines
nox_rate = nox_fl * ffac
return nox_rate
@ndarrayconvert
def co(self, ffac, tas, alt=0):
"""Compute CO emission with given fuel flow, speed, and altitude.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
tas (float or ndarray): Speed (unit: kt).
alt (int or ndarray): Aircraft altitude (unit: ft).
Returns:
float: CO emission from all engines (unit: g/s).
"""
ff_sl, ratio = self._fl2sl(ffac, tas, alt)
co_sl = self.np.interp(
ff_sl,
[
self.engine["ff_idl"],
self.engine["ff_app"],
self.engine["ff_co"],
self.engine["ff_to"],
],
[
self.engine["ei_co_idl"],
self.engine["ei_co_app"],
self.engine["ei_co_co"],
self.engine["ei_co_to"],
],
)
# convert back to actual flight level
co_fl = co_sl * ratio
# convert g/(kg fuel) to g/s for all engines
co_rate = co_fl * ffac
return co_rate
@ndarrayconvert
def hc(self, ffac, tas, alt=0):
"""Compute HC emission with given fuel flow, speed, and altitude.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
tas (float or ndarray): Speed (unit: kt).
alt (int or ndarray): Aircraft altitude (unit: ft).
Returns:
float: HC emission from all engines (unit: g/s).
"""
ff_sl, ratio = self._fl2sl(ffac, tas, alt)
hc_sl = self.np.interp(
ff_sl,
[
self.engine["ff_idl"],
self.engine["ff_app"],
self.engine["ff_co"],
self.engine["ff_to"],
],
[
self.engine["ei_hc_idl"],
self.engine["ei_hc_app"],
self.engine["ei_hc_co"],
self.engine["ei_hc_to"],
],
)
# convert back to actual flight level
hc_fl = hc_sl * ratio
# convert g/(kg fuel) to g/s for all engines
hc_rate = hc_fl * ffac
return hc_rate
|
(self, ffac, tas, alt=0)
|
722,169 |
openap.emission
|
nox
|
Compute NOx emission with given fuel flow, speed, and altitude.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
tas (float or ndarray): Speed (unit: kt).
alt (int or ndarray): Aircraft altitude (unit: ft).
Returns:
float: NOx emission from all engines (unit: g/s).
|
"""OpenAP FuelFlow model."""
import importlib
from openap import prop
from openap.extra import ndarrayconvert
class Emission(object):
"""Emission model based on ICAO emmision databank."""
def __init__(self, ac, eng=None, **kwargs):
"""Initialize Emission object.
Args:
ac (string): ICAO aircraft type (for example: A320).
eng (string): Engine type (for example: CFM56-5A3).
Leave empty to use the default engine specified
by in the aircraft database.
"""
if not hasattr(self, "np"):
self.np = importlib.import_module("numpy")
if not hasattr(self, "aero"):
self.aero = importlib.import_module("openap").aero
self.ac = prop.aircraft(ac, **kwargs)
self.n_eng = self.ac["engine"]["number"]
if eng is None:
eng = self.ac["engine"]["default"]
self.engine = prop.engine(eng)
def _fl2sl(self, ffac, tas, alt):
"""Convert to sea-level equivalent"""
M = self.aero.tas2mach(tas * self.aero.kts, alt * self.aero.ft)
beta = self.np.exp(0.2 * (M ** 2))
theta = (self.aero.temperature(alt * self.aero.ft) / 288.15) / beta
delta = (1 - 0.0019812 * alt / 288.15) ** 5.255876 / self.np.power(beta, 3.5)
ratio = (theta ** 3.3) / (delta ** 1.02)
ff_sl = (ffac / self.n_eng) * theta ** 3.8 / delta * beta
return ff_sl, ratio
@ndarrayconvert
def co2(self, ffac):
"""Compute CO2 emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: CO2 emission from all engines (unit: g/s).
"""
return ffac * 3149
@ndarrayconvert
def h2o(self, ffac):
"""Compute H2O emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: H2O emission from all engines (unit: g/s).
"""
return ffac * 1230
@ndarrayconvert
def soot(self, ffac):
"""Compute soot emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: Soot emission from all engines (unit: g/s).
"""
return ffac * 0.03
@ndarrayconvert
def sox(self, ffac):
"""Compute SOx emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: SOx emission from all engines (unit: g/s).
"""
return ffac * 0.84
@ndarrayconvert
def nox(self, ffac, tas, alt=0):
"""Compute NOx emission with given fuel flow, speed, and altitude.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
tas (float or ndarray): Speed (unit: kt).
alt (int or ndarray): Aircraft altitude (unit: ft).
Returns:
float: NOx emission from all engines (unit: g/s).
"""
ff_sl, ratio = self._fl2sl(ffac, tas, alt)
nox_sl = self.np.interp(
ff_sl,
[
self.engine["ff_idl"],
self.engine["ff_app"],
self.engine["ff_co"],
self.engine["ff_to"],
],
[
self.engine["ei_nox_idl"],
self.engine["ei_nox_app"],
self.engine["ei_nox_co"],
self.engine["ei_nox_to"],
],
)
# convert back to actual flight level
omega = 10 ** (-3) * self.np.exp(-0.0001426 * (alt - 12900))
nox_fl = nox_sl * self.np.sqrt(1 / ratio) * self.np.exp(-19 * (omega - 0.00634))
# convert g/(kg fuel) to g/s for all engines
nox_rate = nox_fl * ffac
return nox_rate
@ndarrayconvert
def co(self, ffac, tas, alt=0):
"""Compute CO emission with given fuel flow, speed, and altitude.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
tas (float or ndarray): Speed (unit: kt).
alt (int or ndarray): Aircraft altitude (unit: ft).
Returns:
float: CO emission from all engines (unit: g/s).
"""
ff_sl, ratio = self._fl2sl(ffac, tas, alt)
co_sl = self.np.interp(
ff_sl,
[
self.engine["ff_idl"],
self.engine["ff_app"],
self.engine["ff_co"],
self.engine["ff_to"],
],
[
self.engine["ei_co_idl"],
self.engine["ei_co_app"],
self.engine["ei_co_co"],
self.engine["ei_co_to"],
],
)
# convert back to actual flight level
co_fl = co_sl * ratio
# convert g/(kg fuel) to g/s for all engines
co_rate = co_fl * ffac
return co_rate
@ndarrayconvert
def hc(self, ffac, tas, alt=0):
"""Compute HC emission with given fuel flow, speed, and altitude.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
tas (float or ndarray): Speed (unit: kt).
alt (int or ndarray): Aircraft altitude (unit: ft).
Returns:
float: HC emission from all engines (unit: g/s).
"""
ff_sl, ratio = self._fl2sl(ffac, tas, alt)
hc_sl = self.np.interp(
ff_sl,
[
self.engine["ff_idl"],
self.engine["ff_app"],
self.engine["ff_co"],
self.engine["ff_to"],
],
[
self.engine["ei_hc_idl"],
self.engine["ei_hc_app"],
self.engine["ei_hc_co"],
self.engine["ei_hc_to"],
],
)
# convert back to actual flight level
hc_fl = hc_sl * ratio
# convert g/(kg fuel) to g/s for all engines
hc_rate = hc_fl * ffac
return hc_rate
|
(self, ffac, tas, alt=0)
|
722,170 |
openap.emission
|
soot
|
Compute soot emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: Soot emission from all engines (unit: g/s).
|
"""OpenAP FuelFlow model."""
import importlib
from openap import prop
from openap.extra import ndarrayconvert
class Emission(object):
"""Emission model based on ICAO emmision databank."""
def __init__(self, ac, eng=None, **kwargs):
"""Initialize Emission object.
Args:
ac (string): ICAO aircraft type (for example: A320).
eng (string): Engine type (for example: CFM56-5A3).
Leave empty to use the default engine specified
by in the aircraft database.
"""
if not hasattr(self, "np"):
self.np = importlib.import_module("numpy")
if not hasattr(self, "aero"):
self.aero = importlib.import_module("openap").aero
self.ac = prop.aircraft(ac, **kwargs)
self.n_eng = self.ac["engine"]["number"]
if eng is None:
eng = self.ac["engine"]["default"]
self.engine = prop.engine(eng)
def _fl2sl(self, ffac, tas, alt):
"""Convert to sea-level equivalent"""
M = self.aero.tas2mach(tas * self.aero.kts, alt * self.aero.ft)
beta = self.np.exp(0.2 * (M ** 2))
theta = (self.aero.temperature(alt * self.aero.ft) / 288.15) / beta
delta = (1 - 0.0019812 * alt / 288.15) ** 5.255876 / self.np.power(beta, 3.5)
ratio = (theta ** 3.3) / (delta ** 1.02)
ff_sl = (ffac / self.n_eng) * theta ** 3.8 / delta * beta
return ff_sl, ratio
@ndarrayconvert
def co2(self, ffac):
"""Compute CO2 emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: CO2 emission from all engines (unit: g/s).
"""
return ffac * 3149
@ndarrayconvert
def h2o(self, ffac):
"""Compute H2O emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: H2O emission from all engines (unit: g/s).
"""
return ffac * 1230
@ndarrayconvert
def soot(self, ffac):
"""Compute soot emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: Soot emission from all engines (unit: g/s).
"""
return ffac * 0.03
@ndarrayconvert
def sox(self, ffac):
"""Compute SOx emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: SOx emission from all engines (unit: g/s).
"""
return ffac * 0.84
@ndarrayconvert
def nox(self, ffac, tas, alt=0):
"""Compute NOx emission with given fuel flow, speed, and altitude.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
tas (float or ndarray): Speed (unit: kt).
alt (int or ndarray): Aircraft altitude (unit: ft).
Returns:
float: NOx emission from all engines (unit: g/s).
"""
ff_sl, ratio = self._fl2sl(ffac, tas, alt)
nox_sl = self.np.interp(
ff_sl,
[
self.engine["ff_idl"],
self.engine["ff_app"],
self.engine["ff_co"],
self.engine["ff_to"],
],
[
self.engine["ei_nox_idl"],
self.engine["ei_nox_app"],
self.engine["ei_nox_co"],
self.engine["ei_nox_to"],
],
)
# convert back to actual flight level
omega = 10 ** (-3) * self.np.exp(-0.0001426 * (alt - 12900))
nox_fl = nox_sl * self.np.sqrt(1 / ratio) * self.np.exp(-19 * (omega - 0.00634))
# convert g/(kg fuel) to g/s for all engines
nox_rate = nox_fl * ffac
return nox_rate
@ndarrayconvert
def co(self, ffac, tas, alt=0):
"""Compute CO emission with given fuel flow, speed, and altitude.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
tas (float or ndarray): Speed (unit: kt).
alt (int or ndarray): Aircraft altitude (unit: ft).
Returns:
float: CO emission from all engines (unit: g/s).
"""
ff_sl, ratio = self._fl2sl(ffac, tas, alt)
co_sl = self.np.interp(
ff_sl,
[
self.engine["ff_idl"],
self.engine["ff_app"],
self.engine["ff_co"],
self.engine["ff_to"],
],
[
self.engine["ei_co_idl"],
self.engine["ei_co_app"],
self.engine["ei_co_co"],
self.engine["ei_co_to"],
],
)
# convert back to actual flight level
co_fl = co_sl * ratio
# convert g/(kg fuel) to g/s for all engines
co_rate = co_fl * ffac
return co_rate
@ndarrayconvert
def hc(self, ffac, tas, alt=0):
"""Compute HC emission with given fuel flow, speed, and altitude.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
tas (float or ndarray): Speed (unit: kt).
alt (int or ndarray): Aircraft altitude (unit: ft).
Returns:
float: HC emission from all engines (unit: g/s).
"""
ff_sl, ratio = self._fl2sl(ffac, tas, alt)
hc_sl = self.np.interp(
ff_sl,
[
self.engine["ff_idl"],
self.engine["ff_app"],
self.engine["ff_co"],
self.engine["ff_to"],
],
[
self.engine["ei_hc_idl"],
self.engine["ei_hc_app"],
self.engine["ei_hc_co"],
self.engine["ei_hc_to"],
],
)
# convert back to actual flight level
hc_fl = hc_sl * ratio
# convert g/(kg fuel) to g/s for all engines
hc_rate = hc_fl * ffac
return hc_rate
|
(self, ffac)
|
722,171 |
openap.emission
|
sox
|
Compute SOx emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: SOx emission from all engines (unit: g/s).
|
"""OpenAP FuelFlow model."""
import importlib
from openap import prop
from openap.extra import ndarrayconvert
class Emission(object):
"""Emission model based on ICAO emmision databank."""
def __init__(self, ac, eng=None, **kwargs):
"""Initialize Emission object.
Args:
ac (string): ICAO aircraft type (for example: A320).
eng (string): Engine type (for example: CFM56-5A3).
Leave empty to use the default engine specified
by in the aircraft database.
"""
if not hasattr(self, "np"):
self.np = importlib.import_module("numpy")
if not hasattr(self, "aero"):
self.aero = importlib.import_module("openap").aero
self.ac = prop.aircraft(ac, **kwargs)
self.n_eng = self.ac["engine"]["number"]
if eng is None:
eng = self.ac["engine"]["default"]
self.engine = prop.engine(eng)
def _fl2sl(self, ffac, tas, alt):
"""Convert to sea-level equivalent"""
M = self.aero.tas2mach(tas * self.aero.kts, alt * self.aero.ft)
beta = self.np.exp(0.2 * (M ** 2))
theta = (self.aero.temperature(alt * self.aero.ft) / 288.15) / beta
delta = (1 - 0.0019812 * alt / 288.15) ** 5.255876 / self.np.power(beta, 3.5)
ratio = (theta ** 3.3) / (delta ** 1.02)
ff_sl = (ffac / self.n_eng) * theta ** 3.8 / delta * beta
return ff_sl, ratio
@ndarrayconvert
def co2(self, ffac):
"""Compute CO2 emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: CO2 emission from all engines (unit: g/s).
"""
return ffac * 3149
@ndarrayconvert
def h2o(self, ffac):
"""Compute H2O emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: H2O emission from all engines (unit: g/s).
"""
return ffac * 1230
@ndarrayconvert
def soot(self, ffac):
"""Compute soot emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: Soot emission from all engines (unit: g/s).
"""
return ffac * 0.03
@ndarrayconvert
def sox(self, ffac):
"""Compute SOx emission with given fuel flow.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
Returns:
float: SOx emission from all engines (unit: g/s).
"""
return ffac * 0.84
@ndarrayconvert
def nox(self, ffac, tas, alt=0):
"""Compute NOx emission with given fuel flow, speed, and altitude.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
tas (float or ndarray): Speed (unit: kt).
alt (int or ndarray): Aircraft altitude (unit: ft).
Returns:
float: NOx emission from all engines (unit: g/s).
"""
ff_sl, ratio = self._fl2sl(ffac, tas, alt)
nox_sl = self.np.interp(
ff_sl,
[
self.engine["ff_idl"],
self.engine["ff_app"],
self.engine["ff_co"],
self.engine["ff_to"],
],
[
self.engine["ei_nox_idl"],
self.engine["ei_nox_app"],
self.engine["ei_nox_co"],
self.engine["ei_nox_to"],
],
)
# convert back to actual flight level
omega = 10 ** (-3) * self.np.exp(-0.0001426 * (alt - 12900))
nox_fl = nox_sl * self.np.sqrt(1 / ratio) * self.np.exp(-19 * (omega - 0.00634))
# convert g/(kg fuel) to g/s for all engines
nox_rate = nox_fl * ffac
return nox_rate
@ndarrayconvert
def co(self, ffac, tas, alt=0):
"""Compute CO emission with given fuel flow, speed, and altitude.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
tas (float or ndarray): Speed (unit: kt).
alt (int or ndarray): Aircraft altitude (unit: ft).
Returns:
float: CO emission from all engines (unit: g/s).
"""
ff_sl, ratio = self._fl2sl(ffac, tas, alt)
co_sl = self.np.interp(
ff_sl,
[
self.engine["ff_idl"],
self.engine["ff_app"],
self.engine["ff_co"],
self.engine["ff_to"],
],
[
self.engine["ei_co_idl"],
self.engine["ei_co_app"],
self.engine["ei_co_co"],
self.engine["ei_co_to"],
],
)
# convert back to actual flight level
co_fl = co_sl * ratio
# convert g/(kg fuel) to g/s for all engines
co_rate = co_fl * ffac
return co_rate
@ndarrayconvert
def hc(self, ffac, tas, alt=0):
"""Compute HC emission with given fuel flow, speed, and altitude.
Args:
ffac (float or ndarray): Fuel flow for all engines (unit: kg/s).
tas (float or ndarray): Speed (unit: kt).
alt (int or ndarray): Aircraft altitude (unit: ft).
Returns:
float: HC emission from all engines (unit: g/s).
"""
ff_sl, ratio = self._fl2sl(ffac, tas, alt)
hc_sl = self.np.interp(
ff_sl,
[
self.engine["ff_idl"],
self.engine["ff_app"],
self.engine["ff_co"],
self.engine["ff_to"],
],
[
self.engine["ei_hc_idl"],
self.engine["ei_hc_app"],
self.engine["ei_hc_co"],
self.engine["ei_hc_to"],
],
)
# convert back to actual flight level
hc_fl = hc_sl * ratio
# convert g/(kg fuel) to g/s for all engines
hc_rate = hc_fl * ffac
return hc_rate
|
(self, ffac)
|
722,172 |
openap.phase
|
FlightPhase
|
Fuzzy logic flight phase identification.
|
class FlightPhase(object):
"""Fuzzy logic flight phase identification."""
def __init__(self):
"""Initialize of the FlightPhase object."""
super(FlightPhase, self).__init__()
# logic states
self.alt_range = np.arange(0, 40000, 1)
self.roc_range = np.arange(-4000, 4000, 0.1)
self.spd_range = np.arange(0, 600, 1)
self.states = np.arange(0, 6, 0.01)
self.alt_gnd = fuzzy.zmf(self.alt_range, 0, 200)
self.alt_lo = fuzzy.gaussmf(self.alt_range, 10000, 10000)
self.alt_hi = fuzzy.gaussmf(self.alt_range, 35000, 20000)
self.roc_zero = fuzzy.gaussmf(self.roc_range, 0, 100)
self.roc_plus = fuzzy.smf(self.roc_range, 10, 1000)
self.roc_minus = fuzzy.zmf(self.roc_range, -1000, -10)
self.spd_hi = fuzzy.gaussmf(self.spd_range, 600, 100)
self.spd_md = fuzzy.gaussmf(self.spd_range, 300, 100)
self.spd_lo = fuzzy.gaussmf(self.spd_range, 0, 50)
self.state_ground = fuzzy.gaussmf(self.states, 1, 0.1)
self.state_climb = fuzzy.gaussmf(self.states, 2, 0.1)
self.state_descent = fuzzy.gaussmf(self.states, 3, 0.1)
self.state_cruise = fuzzy.gaussmf(self.states, 4, 0.1)
self.state_level = fuzzy.gaussmf(self.states, 5, 0.1)
self.state_lable_map = {1: "GND", 2: "CL", 3: "DE", 4: "CR", 5: "LVL"}
self.ts = None
self.alt = None
self.spd = None
self.roc = None
def set_trajectory(self, ts, alt, spd, roc):
"""Set trajectory data.
Args:
ts (list): Time (unit: second).
alt (list): Altitude (unit: ft).
spd (list): True airspeed (unit: kt).
roc (list): Rate of climb (unit: ft/min). Negative for descent.
"""
self.ts = ts - ts[0]
self.alt = alt
self.spd = spd
self.roc = roc
if len(set([len(self.ts), len(self.alt), len(self.spd), len(self.roc)])) > 1:
raise RuntimeError("Input lists must have same length.")
self.ndata = len(self.ts)
return
def phaselabel(self, twindow=60):
"""Fuzzy logic for determining phase label.
Args:
twindow (int): Time window in number of seconds. Default to 60.
Returns:
list: Labels could be: ground [GND], climb [CL], descent [DE],
cruise [CR], leveling [LVL].
"""
if self.ts is None:
raise RuntimeError(
"Trajectory data not set, run set_trajectory(ts, alt, spd, roc) first"
)
idxs = np.arange(0, self.ndata)
labels = ["NA"] * self.ndata
twindows = self.ts // twindow
for tw in range(0, int(max(twindows))):
if tw not in twindows:
continue
mask = twindows == tw
idxchk = idxs[mask]
altchk = self.alt[mask]
spdchk = self.spd[mask]
rocchk = self.roc[mask]
# mean value or extream value as range
alt = max(min(np.mean(altchk), self.alt_range[-1]), self.alt_range[0])
spd = max(min(np.mean(spdchk), self.spd_range[-1]), self.spd_range[0])
roc = max(min(np.mean(rocchk), self.roc_range[-1]), self.roc_range[0])
# make sure values are within the boundaries
alt = max(min(alt, self.alt_range[-1]), self.alt_range[0])
spd = max(min(spd, self.spd_range[-1]), self.spd_range[0])
roc = max(min(roc, self.roc_range[-1]), self.roc_range[0])
alt_level_gnd = fuzzy.interp_membership(self.alt_range, self.alt_gnd, alt)
alt_level_lo = fuzzy.interp_membership(self.alt_range, self.alt_lo, alt)
alt_level_hi = fuzzy.interp_membership(self.alt_range, self.alt_hi, alt)
spd_level_hi = fuzzy.interp_membership(self.spd_range, self.spd_hi, spd)
spd_level_md = fuzzy.interp_membership(self.spd_range, self.spd_md, spd)
spd_level_lo = fuzzy.interp_membership(self.spd_range, self.spd_lo, spd)
roc_level_zero = fuzzy.interp_membership(self.roc_range, self.roc_zero, roc)
roc_level_plus = fuzzy.interp_membership(self.roc_range, self.roc_plus, roc)
roc_level_minus = fuzzy.interp_membership(
self.roc_range, self.roc_minus, roc
)
# print alt_level_gnd, alt_level_lo, alt_level_hi
# print roc_level_zero, roc_level_plus, roc_level_minus
# print spd_level_hi, spd_level_md, spd_level_lo
rule_ground = min(alt_level_gnd, roc_level_zero, spd_level_lo)
state_activate_ground = np.fmin(rule_ground, self.state_ground)
rule_climb = min(alt_level_lo, roc_level_plus, spd_level_md)
state_activate_climb = np.fmin(rule_climb, self.state_climb)
rule_descent = min(alt_level_lo, roc_level_minus, spd_level_md)
state_activate_descent = np.fmin(rule_descent, self.state_descent)
rule_cruise = min(alt_level_hi, roc_level_zero, spd_level_hi)
state_activate_cruise = np.fmin(rule_cruise, self.state_cruise)
rule_level = min(alt_level_lo, roc_level_zero, spd_level_md)
state_activate_level = np.fmin(rule_level, self.state_level)
aggregated = np.max(
np.vstack(
[
state_activate_ground,
state_activate_climb,
state_activate_descent,
state_activate_cruise,
state_activate_level,
]
),
axis=0,
)
state_raw = fuzzy.defuzz(self.states, aggregated, "lom")
state = int(round(state_raw))
if state > 6:
state = 6
if state < 1:
state = 1
if len(idxchk) > 0:
label = self.state_lable_map[state]
labels[idxchk[0] : (idxchk[-1] + 1)] = [label] * len(idxchk)
return labels
def plot_logics(self):
"""Visualize fuzzy logic membership functions."""
plt.figure(figsize=(10, 8))
plt.subplot(411)
plt.plot(self.alt_range, self.alt_gnd, lw=2, label="Ground")
plt.plot(self.alt_range, self.alt_lo, lw=2, label="Low")
plt.plot(self.alt_range, self.alt_hi, lw=2, label="High")
plt.ylim([-0.05, 1.05])
plt.ylabel("Altitude (ft)")
plt.yticks([0, 1])
plt.legend()
plt.subplot(412)
plt.plot(self.roc_range, self.roc_zero, lw=2, label="Zero")
plt.plot(self.roc_range, self.roc_plus, lw=2, label="Positive")
plt.plot(self.roc_range, self.roc_minus, lw=2, label="Negative")
plt.ylim([-0.05, 1.05])
plt.ylabel("RoC (ft/m)")
plt.yticks([0, 1])
plt.legend()
plt.subplot(413)
plt.plot(self.spd_range, self.spd_hi, lw=2, label="High")
plt.plot(self.spd_range, self.spd_md, lw=2, label="Midium")
plt.plot(self.spd_range, self.spd_lo, lw=2, label="Low")
plt.ylim([-0.05, 1.05])
plt.ylabel("Speed (kt)")
plt.yticks([0, 1])
plt.legend()
plt.subplot(414)
plt.plot(self.states, self.state_ground, lw=2, label="ground")
plt.plot(self.states, self.state_climb, lw=2, label="climb")
plt.plot(self.states, self.state_descent, lw=2, label="descent")
plt.plot(self.states, self.state_cruise, lw=2, label="cruise")
plt.plot(self.states, self.state_level, lw=2, label="level flight")
plt.ylim([-0.05, 1.05])
plt.ylabel("Flight Phases")
plt.yticks([0, 1])
plt.legend(prop={"size": 7})
plt.show()
def _get_to_ic(self):
# get the data chunk up to certain ft
istart = 0
iend = 0
for i in range(0, self.ndata):
if self.alt[i] < 1500: # ft
iend = i
continue
else:
break
# keep only the chunk in taking-off states, break at starting point
spdtmp = self.spd[iend]
for i in reversed(list(range(0, iend))):
if self.spd[i] < 30 and self.spd[i] > spdtmp:
break
elif self.spd[i] < 5:
break
else:
istart = i
spdtmp = self.spd[i]
# ignore too long take-off
if self.ts[iend] - self.ts[istart] > 300:
return None
# ignore insufficient chunk size
if iend - istart < 10:
return None
# ignore no in air data
if self.alt[iend] < 200:
return None
# find the liftoff moment
ilof = istart
for i in range(istart + 1, iend):
if abs(self.alt[i] - self.alt[i - 1]) > 10:
ilof = i
break
# not sufficient data
if ilof - istart < 5:
return None
return (istart, ilof, iend + 1)
def _get_fa_ld(self):
# get the approach + landing data chunk (h=0)
istart = 0
iend = 0
for i in reversed(list(range(0, self.ndata))):
if self.alt[i] < 1500: # ft
istart = i
else:
break
# keep only the chunk in landing deceleration states, break at taxing point
spdtmp = self.spd[istart]
for i in range(istart, self.ndata):
if self.spd[i] <= 50 and self.spd[i] >= spdtmp: # kts
break
elif self.spd[i] < 30:
break
else:
iend = i
spdtmp = self.spd[i]
# ignore insufficient chunk size
# if iend - istart < 20:
# return None
# ignore QNH altitude, or no in-air data
if self.alt[istart] < 100:
return None
# # ignore where the end speed too high, ie. not breaked
# if spd[iend] > 60: # kts
# return None
# find the landing moment
ild = iend
for i in reversed(list(range(istart, iend - 1))):
if abs(self.alt[i] - self.alt[i + 1]) > 10:
ild = i
break
# ignore ground or air data sample less than 4
if ild - istart < 5 or iend - ild < 5:
return None
return (istart, ild, iend + 1)
def _get_cl(self):
labels = np.array(self.phaselabel())
if "CL" not in labels:
return None
idx = np.where(np.array(labels) == "CL")[0]
istart = idx[0]
iend = idx[-1]
return istart, iend
def _get_de(self):
labels = np.array(self.phaselabel())
if "DE" not in labels:
return None
idx = np.where(np.array(labels) == "DE")[0]
istart = idx[0]
iend = idx[-1]
if "LVL" in labels[istart:iend]:
isCDA = False
else:
isCDA = True
return istart, iend, isCDA
def _get_cr(self):
# CR start = CL end, CR end = DE start
ttCL = self._get_cl()
if not ttCL:
return None
ttDE = self._get_de()
if not ttDE:
return None
ttDE = ttDE[0:2]
istart = ttCL[-1]
iend = ttDE[0]
if iend - istart < 200:
# too few samples
return None
return istart, iend
def flight_phase_indices(self):
"""Get the indices of data, of which different flight phase start.
Returns:
dict: Indices for takeoff (TO), initial climb (IC), climb (CL),
cruise (CR), descent (DE), final approach (FA), landing (LD).
"""
# Process the data and get the phase index
ii_toic = self._get_to_ic()
ii_cl = self._get_cl()
ii_de = self._get_de()
ii_fald = self._get_fa_ld()
ito = ii_toic[0] if ii_toic is not None else None
iic = ii_toic[1] if ii_toic is not None else None
if ii_toic is not None:
icl = ii_toic[2]
else:
if ii_cl is not None:
icl = ii_cl[0]
else:
icl = None
icr = ii_cl[1] if ii_cl is not None else None
ide = ii_de[0] if ii_de is not None else None
if ii_fald is not None:
ifa = ii_fald[0]
ild = ii_fald[1]
iend = ii_fald[2]
elif ii_de is not None:
ifa = ii_de[1]
ild = None
iend = len(self.ts)
else:
ifa = None
ild = None
iend = len(self.ts)
idx = {
"TO": ito,
"IC": iic,
"CL": icl,
"CR": icr,
"DE": ide,
"FA": ifa,
"LD": ild,
"END": iend,
}
return idx
|
()
|
722,173 |
openap.phase
|
__init__
|
Initialize of the FlightPhase object.
|
def __init__(self):
"""Initialize of the FlightPhase object."""
super(FlightPhase, self).__init__()
# logic states
self.alt_range = np.arange(0, 40000, 1)
self.roc_range = np.arange(-4000, 4000, 0.1)
self.spd_range = np.arange(0, 600, 1)
self.states = np.arange(0, 6, 0.01)
self.alt_gnd = fuzzy.zmf(self.alt_range, 0, 200)
self.alt_lo = fuzzy.gaussmf(self.alt_range, 10000, 10000)
self.alt_hi = fuzzy.gaussmf(self.alt_range, 35000, 20000)
self.roc_zero = fuzzy.gaussmf(self.roc_range, 0, 100)
self.roc_plus = fuzzy.smf(self.roc_range, 10, 1000)
self.roc_minus = fuzzy.zmf(self.roc_range, -1000, -10)
self.spd_hi = fuzzy.gaussmf(self.spd_range, 600, 100)
self.spd_md = fuzzy.gaussmf(self.spd_range, 300, 100)
self.spd_lo = fuzzy.gaussmf(self.spd_range, 0, 50)
self.state_ground = fuzzy.gaussmf(self.states, 1, 0.1)
self.state_climb = fuzzy.gaussmf(self.states, 2, 0.1)
self.state_descent = fuzzy.gaussmf(self.states, 3, 0.1)
self.state_cruise = fuzzy.gaussmf(self.states, 4, 0.1)
self.state_level = fuzzy.gaussmf(self.states, 5, 0.1)
self.state_lable_map = {1: "GND", 2: "CL", 3: "DE", 4: "CR", 5: "LVL"}
self.ts = None
self.alt = None
self.spd = None
self.roc = None
|
(self)
|
722,174 |
openap.phase
|
_get_cl
| null |
def _get_cl(self):
labels = np.array(self.phaselabel())
if "CL" not in labels:
return None
idx = np.where(np.array(labels) == "CL")[0]
istart = idx[0]
iend = idx[-1]
return istart, iend
|
(self)
|
722,175 |
openap.phase
|
_get_cr
| null |
def _get_cr(self):
# CR start = CL end, CR end = DE start
ttCL = self._get_cl()
if not ttCL:
return None
ttDE = self._get_de()
if not ttDE:
return None
ttDE = ttDE[0:2]
istart = ttCL[-1]
iend = ttDE[0]
if iend - istart < 200:
# too few samples
return None
return istart, iend
|
(self)
|
722,176 |
openap.phase
|
_get_de
| null |
def _get_de(self):
labels = np.array(self.phaselabel())
if "DE" not in labels:
return None
idx = np.where(np.array(labels) == "DE")[0]
istart = idx[0]
iend = idx[-1]
if "LVL" in labels[istart:iend]:
isCDA = False
else:
isCDA = True
return istart, iend, isCDA
|
(self)
|
722,177 |
openap.phase
|
_get_fa_ld
| null |
def _get_fa_ld(self):
# get the approach + landing data chunk (h=0)
istart = 0
iend = 0
for i in reversed(list(range(0, self.ndata))):
if self.alt[i] < 1500: # ft
istart = i
else:
break
# keep only the chunk in landing deceleration states, break at taxing point
spdtmp = self.spd[istart]
for i in range(istart, self.ndata):
if self.spd[i] <= 50 and self.spd[i] >= spdtmp: # kts
break
elif self.spd[i] < 30:
break
else:
iend = i
spdtmp = self.spd[i]
# ignore insufficient chunk size
# if iend - istart < 20:
# return None
# ignore QNH altitude, or no in-air data
if self.alt[istart] < 100:
return None
# # ignore where the end speed too high, ie. not breaked
# if spd[iend] > 60: # kts
# return None
# find the landing moment
ild = iend
for i in reversed(list(range(istart, iend - 1))):
if abs(self.alt[i] - self.alt[i + 1]) > 10:
ild = i
break
# ignore ground or air data sample less than 4
if ild - istart < 5 or iend - ild < 5:
return None
return (istart, ild, iend + 1)
|
(self)
|
722,178 |
openap.phase
|
_get_to_ic
| null |
def _get_to_ic(self):
# get the data chunk up to certain ft
istart = 0
iend = 0
for i in range(0, self.ndata):
if self.alt[i] < 1500: # ft
iend = i
continue
else:
break
# keep only the chunk in taking-off states, break at starting point
spdtmp = self.spd[iend]
for i in reversed(list(range(0, iend))):
if self.spd[i] < 30 and self.spd[i] > spdtmp:
break
elif self.spd[i] < 5:
break
else:
istart = i
spdtmp = self.spd[i]
# ignore too long take-off
if self.ts[iend] - self.ts[istart] > 300:
return None
# ignore insufficient chunk size
if iend - istart < 10:
return None
# ignore no in air data
if self.alt[iend] < 200:
return None
# find the liftoff moment
ilof = istart
for i in range(istart + 1, iend):
if abs(self.alt[i] - self.alt[i - 1]) > 10:
ilof = i
break
# not sufficient data
if ilof - istart < 5:
return None
return (istart, ilof, iend + 1)
|
(self)
|
722,179 |
openap.phase
|
flight_phase_indices
|
Get the indices of data, of which different flight phase start.
Returns:
dict: Indices for takeoff (TO), initial climb (IC), climb (CL),
cruise (CR), descent (DE), final approach (FA), landing (LD).
|
def flight_phase_indices(self):
"""Get the indices of data, of which different flight phase start.
Returns:
dict: Indices for takeoff (TO), initial climb (IC), climb (CL),
cruise (CR), descent (DE), final approach (FA), landing (LD).
"""
# Process the data and get the phase index
ii_toic = self._get_to_ic()
ii_cl = self._get_cl()
ii_de = self._get_de()
ii_fald = self._get_fa_ld()
ito = ii_toic[0] if ii_toic is not None else None
iic = ii_toic[1] if ii_toic is not None else None
if ii_toic is not None:
icl = ii_toic[2]
else:
if ii_cl is not None:
icl = ii_cl[0]
else:
icl = None
icr = ii_cl[1] if ii_cl is not None else None
ide = ii_de[0] if ii_de is not None else None
if ii_fald is not None:
ifa = ii_fald[0]
ild = ii_fald[1]
iend = ii_fald[2]
elif ii_de is not None:
ifa = ii_de[1]
ild = None
iend = len(self.ts)
else:
ifa = None
ild = None
iend = len(self.ts)
idx = {
"TO": ito,
"IC": iic,
"CL": icl,
"CR": icr,
"DE": ide,
"FA": ifa,
"LD": ild,
"END": iend,
}
return idx
|
(self)
|
722,180 |
openap.phase
|
phaselabel
|
Fuzzy logic for determining phase label.
Args:
twindow (int): Time window in number of seconds. Default to 60.
Returns:
list: Labels could be: ground [GND], climb [CL], descent [DE],
cruise [CR], leveling [LVL].
|
def phaselabel(self, twindow=60):
"""Fuzzy logic for determining phase label.
Args:
twindow (int): Time window in number of seconds. Default to 60.
Returns:
list: Labels could be: ground [GND], climb [CL], descent [DE],
cruise [CR], leveling [LVL].
"""
if self.ts is None:
raise RuntimeError(
"Trajectory data not set, run set_trajectory(ts, alt, spd, roc) first"
)
idxs = np.arange(0, self.ndata)
labels = ["NA"] * self.ndata
twindows = self.ts // twindow
for tw in range(0, int(max(twindows))):
if tw not in twindows:
continue
mask = twindows == tw
idxchk = idxs[mask]
altchk = self.alt[mask]
spdchk = self.spd[mask]
rocchk = self.roc[mask]
# mean value or extream value as range
alt = max(min(np.mean(altchk), self.alt_range[-1]), self.alt_range[0])
spd = max(min(np.mean(spdchk), self.spd_range[-1]), self.spd_range[0])
roc = max(min(np.mean(rocchk), self.roc_range[-1]), self.roc_range[0])
# make sure values are within the boundaries
alt = max(min(alt, self.alt_range[-1]), self.alt_range[0])
spd = max(min(spd, self.spd_range[-1]), self.spd_range[0])
roc = max(min(roc, self.roc_range[-1]), self.roc_range[0])
alt_level_gnd = fuzzy.interp_membership(self.alt_range, self.alt_gnd, alt)
alt_level_lo = fuzzy.interp_membership(self.alt_range, self.alt_lo, alt)
alt_level_hi = fuzzy.interp_membership(self.alt_range, self.alt_hi, alt)
spd_level_hi = fuzzy.interp_membership(self.spd_range, self.spd_hi, spd)
spd_level_md = fuzzy.interp_membership(self.spd_range, self.spd_md, spd)
spd_level_lo = fuzzy.interp_membership(self.spd_range, self.spd_lo, spd)
roc_level_zero = fuzzy.interp_membership(self.roc_range, self.roc_zero, roc)
roc_level_plus = fuzzy.interp_membership(self.roc_range, self.roc_plus, roc)
roc_level_minus = fuzzy.interp_membership(
self.roc_range, self.roc_minus, roc
)
# print alt_level_gnd, alt_level_lo, alt_level_hi
# print roc_level_zero, roc_level_plus, roc_level_minus
# print spd_level_hi, spd_level_md, spd_level_lo
rule_ground = min(alt_level_gnd, roc_level_zero, spd_level_lo)
state_activate_ground = np.fmin(rule_ground, self.state_ground)
rule_climb = min(alt_level_lo, roc_level_plus, spd_level_md)
state_activate_climb = np.fmin(rule_climb, self.state_climb)
rule_descent = min(alt_level_lo, roc_level_minus, spd_level_md)
state_activate_descent = np.fmin(rule_descent, self.state_descent)
rule_cruise = min(alt_level_hi, roc_level_zero, spd_level_hi)
state_activate_cruise = np.fmin(rule_cruise, self.state_cruise)
rule_level = min(alt_level_lo, roc_level_zero, spd_level_md)
state_activate_level = np.fmin(rule_level, self.state_level)
aggregated = np.max(
np.vstack(
[
state_activate_ground,
state_activate_climb,
state_activate_descent,
state_activate_cruise,
state_activate_level,
]
),
axis=0,
)
state_raw = fuzzy.defuzz(self.states, aggregated, "lom")
state = int(round(state_raw))
if state > 6:
state = 6
if state < 1:
state = 1
if len(idxchk) > 0:
label = self.state_lable_map[state]
labels[idxchk[0] : (idxchk[-1] + 1)] = [label] * len(idxchk)
return labels
|
(self, twindow=60)
|
722,181 |
openap.phase
|
plot_logics
|
Visualize fuzzy logic membership functions.
|
def plot_logics(self):
"""Visualize fuzzy logic membership functions."""
plt.figure(figsize=(10, 8))
plt.subplot(411)
plt.plot(self.alt_range, self.alt_gnd, lw=2, label="Ground")
plt.plot(self.alt_range, self.alt_lo, lw=2, label="Low")
plt.plot(self.alt_range, self.alt_hi, lw=2, label="High")
plt.ylim([-0.05, 1.05])
plt.ylabel("Altitude (ft)")
plt.yticks([0, 1])
plt.legend()
plt.subplot(412)
plt.plot(self.roc_range, self.roc_zero, lw=2, label="Zero")
plt.plot(self.roc_range, self.roc_plus, lw=2, label="Positive")
plt.plot(self.roc_range, self.roc_minus, lw=2, label="Negative")
plt.ylim([-0.05, 1.05])
plt.ylabel("RoC (ft/m)")
plt.yticks([0, 1])
plt.legend()
plt.subplot(413)
plt.plot(self.spd_range, self.spd_hi, lw=2, label="High")
plt.plot(self.spd_range, self.spd_md, lw=2, label="Midium")
plt.plot(self.spd_range, self.spd_lo, lw=2, label="Low")
plt.ylim([-0.05, 1.05])
plt.ylabel("Speed (kt)")
plt.yticks([0, 1])
plt.legend()
plt.subplot(414)
plt.plot(self.states, self.state_ground, lw=2, label="ground")
plt.plot(self.states, self.state_climb, lw=2, label="climb")
plt.plot(self.states, self.state_descent, lw=2, label="descent")
plt.plot(self.states, self.state_cruise, lw=2, label="cruise")
plt.plot(self.states, self.state_level, lw=2, label="level flight")
plt.ylim([-0.05, 1.05])
plt.ylabel("Flight Phases")
plt.yticks([0, 1])
plt.legend(prop={"size": 7})
plt.show()
|
(self)
|
722,182 |
openap.phase
|
set_trajectory
|
Set trajectory data.
Args:
ts (list): Time (unit: second).
alt (list): Altitude (unit: ft).
spd (list): True airspeed (unit: kt).
roc (list): Rate of climb (unit: ft/min). Negative for descent.
|
def set_trajectory(self, ts, alt, spd, roc):
"""Set trajectory data.
Args:
ts (list): Time (unit: second).
alt (list): Altitude (unit: ft).
spd (list): True airspeed (unit: kt).
roc (list): Rate of climb (unit: ft/min). Negative for descent.
"""
self.ts = ts - ts[0]
self.alt = alt
self.spd = spd
self.roc = roc
if len(set([len(self.ts), len(self.alt), len(self.spd), len(self.roc)])) > 1:
raise RuntimeError("Input lists must have same length.")
self.ndata = len(self.ts)
return
|
(self, ts, alt, spd, roc)
|
722,183 |
openap.fuel
|
FuelFlow
|
Fuel flow model based on ICAO emission databank.
|
class FuelFlow(object):
"""Fuel flow model based on ICAO emission databank."""
def __init__(self, ac, eng=None, **kwargs):
"""Initialize FuelFlow object.
Args:
ac (string): ICAO aircraft type (for example: A320).
eng (string): Engine type (for example: CFM56-5A3).
Leave empty to use the default engine specified
by in the aircraft database.
polydeg (int): Order of the polynomials for fuel flow model (2 or 3), defaults to 2.
"""
if not hasattr(self, "np"):
self.np = importlib.import_module("numpy")
if not hasattr(self, "Thrust"):
self.Thrust = importlib.import_module("openap.thrust").Thrust
if not hasattr(self, "Drag"):
self.Drag = importlib.import_module("openap.drag").Drag
if not hasattr(self, "WRAP"):
self.WRAP = importlib.import_module("openap.kinematic").WRAP
self.aircraft = prop.aircraft(ac, **kwargs)
if eng is None:
eng = self.aircraft["engine"]["default"]
self.engine = prop.engine(eng)
self.thrust = self.Thrust(ac, eng, **kwargs)
self.drag = self.Drag(ac, **kwargs)
self.wrap = self.WRAP(ac, **kwargs)
polydeg = kwargs.get("polydeg", 2)
if polydeg == 2:
a, b = self.engine["fuel_a"], self.engine["fuel_b"]
self.polyfuel = func_fuel2(a, b)
elif polydeg == 3:
c3, c2, c1 = (
self.engine["fuel_c3"],
self.engine["fuel_c2"],
self.engine["fuel_c1"],
)
self.polyfuel = func_fuel3(c3, c2, c1)
else:
raise RuntimeError(f"polydeg must be 2 or 3")
@ndarrayconvert
def at_thrust(self, acthr, alt=0, limit=True):
"""Compute the fuel flow at a given total thrust.
Args:
acthr (int or ndarray): The total net thrust of the aircraft (unit: N).
alt (int or ndarray): Aircraft altitude (unit: ft).
Returns:
float: Fuel flow (unit: kg/s).
"""
n_eng = self.aircraft["engine"]["number"]
engthr = acthr / n_eng
maxthr = self.thrust.takeoff(tas=0, alt=0)
ratio = acthr / maxthr
if limit:
ratio = self.np.where(ratio < 0.07, 0.07, ratio)
ratio = self.np.where(ratio > 1, 1, ratio)
ff_sl = self.polyfuel(ratio)
ff_corr_alt = self.engine["fuel_ch"] * (engthr / 1000) * (alt * 0.3048)
ff_eng = ff_sl + ff_corr_alt
fuelflow = ff_eng * n_eng
return fuelflow
@ndarrayconvert
def takeoff(self, tas, alt=None, throttle=1):
"""Compute the fuel flow at takeoff.
The net thrust is first estimated based on the maximum thrust model
and throttle setting. Then FuelFlow.at_thrust() is called to compted
the thrust.
Args:
tas (int or ndarray): Aircraft true airspeed (unit: kt).
alt (int or ndarray): Altitude of airport (unit: ft). Defaults to sea-level.
throttle (float or ndarray): The throttle setting, between 0 and 1.
Defaults to 1, which is at full thrust.
Returns:
float: Fuel flow (unit: kg/s).
"""
Tmax = self.thrust.takeoff(tas=tas, alt=alt)
fuelflow = throttle * self.at_thrust(Tmax)
return fuelflow
@ndarrayconvert
def enroute(self, mass, tas, alt, path_angle=0, limit=True):
"""Compute the fuel flow during climb, cruise, or descent.
The net thrust is first estimated based on the dynamic equation.
Then FuelFlow.at_thrust() is called to compted the thrust. Assuming
no flap deflection and no landing gear extended.
Args:
mass (int or ndarray): Aircraft mass (unit: kg).
tas (int or ndarray): Aircraft true airspeed (unit: kt).
alt (int or ndarray): Aircraft altitude (unit: ft).
path_angle (float or ndarray): Flight path angle (unit: degrees).
Returns:
float: Fuel flow (unit: kg/s).
"""
D = self.drag.clean(mass=mass, tas=tas, alt=alt, path_angle=path_angle)
# Convert angles from degrees to radians.
gamma = path_angle * 3.142 / 180
T = D + mass * 9.81 * self.np.sin(gamma)
if limit:
T_max = self.thrust.climb(tas=tas, alt=alt, roc=0)
T_idle = self.thrust.descent_idle(tas=tas, alt=alt)
# below idle thrust
T = self.np.where(T < T_idle, T_idle, T)
# outside performance boundary (with margin of 20%)
T = self.np.where(T > 1.2 * T_max, 1.2 * T_max, T)
fuelflow = self.at_thrust(T, alt, limit=limit)
return fuelflow
def plot_model(self, plot=True):
"""Plot the engine fuel model, or return the pyplot object.
Args:
plot (bool): Display the plot or return an object.
Returns:
None or pyplot object.
"""
import matplotlib.pyplot as plt
x = [0.07, 0.3, 0.85, 1.0]
y = [
self.engine["ff_idl"],
self.engine["ff_app"],
self.engine["ff_co"],
self.engine["ff_to"],
]
plt.scatter(x, y, color="k")
xx = self.np.linspace(0, 1, 50)
yy = self.polyfuel(xx)
plt.plot(xx, yy, "--", color="gray")
if plot:
plt.show()
else:
return plt
|
(ac, eng=None, **kwargs)
|
722,184 |
openap.fuel
|
__init__
|
Initialize FuelFlow object.
Args:
ac (string): ICAO aircraft type (for example: A320).
eng (string): Engine type (for example: CFM56-5A3).
Leave empty to use the default engine specified
by in the aircraft database.
polydeg (int): Order of the polynomials for fuel flow model (2 or 3), defaults to 2.
|
def __init__(self, ac, eng=None, **kwargs):
"""Initialize FuelFlow object.
Args:
ac (string): ICAO aircraft type (for example: A320).
eng (string): Engine type (for example: CFM56-5A3).
Leave empty to use the default engine specified
by in the aircraft database.
polydeg (int): Order of the polynomials for fuel flow model (2 or 3), defaults to 2.
"""
if not hasattr(self, "np"):
self.np = importlib.import_module("numpy")
if not hasattr(self, "Thrust"):
self.Thrust = importlib.import_module("openap.thrust").Thrust
if not hasattr(self, "Drag"):
self.Drag = importlib.import_module("openap.drag").Drag
if not hasattr(self, "WRAP"):
self.WRAP = importlib.import_module("openap.kinematic").WRAP
self.aircraft = prop.aircraft(ac, **kwargs)
if eng is None:
eng = self.aircraft["engine"]["default"]
self.engine = prop.engine(eng)
self.thrust = self.Thrust(ac, eng, **kwargs)
self.drag = self.Drag(ac, **kwargs)
self.wrap = self.WRAP(ac, **kwargs)
polydeg = kwargs.get("polydeg", 2)
if polydeg == 2:
a, b = self.engine["fuel_a"], self.engine["fuel_b"]
self.polyfuel = func_fuel2(a, b)
elif polydeg == 3:
c3, c2, c1 = (
self.engine["fuel_c3"],
self.engine["fuel_c2"],
self.engine["fuel_c1"],
)
self.polyfuel = func_fuel3(c3, c2, c1)
else:
raise RuntimeError(f"polydeg must be 2 or 3")
|
(self, ac, eng=None, **kwargs)
|
722,185 |
openap.fuel
|
at_thrust
|
Compute the fuel flow at a given total thrust.
Args:
acthr (int or ndarray): The total net thrust of the aircraft (unit: N).
alt (int or ndarray): Aircraft altitude (unit: ft).
Returns:
float: Fuel flow (unit: kg/s).
|
"""OpenAP FuelFlow model."""
import importlib
from openap import prop
from openap.extra import ndarrayconvert
def func_fuel2(a, b):
return lambda x: a * (x + b) ** 2
|
(self, acthr, alt=0, limit=True)
|
722,186 |
openap.fuel
|
enroute
|
Compute the fuel flow during climb, cruise, or descent.
The net thrust is first estimated based on the dynamic equation.
Then FuelFlow.at_thrust() is called to compted the thrust. Assuming
no flap deflection and no landing gear extended.
Args:
mass (int or ndarray): Aircraft mass (unit: kg).
tas (int or ndarray): Aircraft true airspeed (unit: kt).
alt (int or ndarray): Aircraft altitude (unit: ft).
path_angle (float or ndarray): Flight path angle (unit: degrees).
Returns:
float: Fuel flow (unit: kg/s).
|
"""OpenAP FuelFlow model."""
import importlib
from openap import prop
from openap.extra import ndarrayconvert
def func_fuel2(a, b):
return lambda x: a * (x + b) ** 2
|
(self, mass, tas, alt, path_angle=0, limit=True)
|
722,187 |
openap.fuel
|
plot_model
|
Plot the engine fuel model, or return the pyplot object.
Args:
plot (bool): Display the plot or return an object.
Returns:
None or pyplot object.
|
def plot_model(self, plot=True):
"""Plot the engine fuel model, or return the pyplot object.
Args:
plot (bool): Display the plot or return an object.
Returns:
None or pyplot object.
"""
import matplotlib.pyplot as plt
x = [0.07, 0.3, 0.85, 1.0]
y = [
self.engine["ff_idl"],
self.engine["ff_app"],
self.engine["ff_co"],
self.engine["ff_to"],
]
plt.scatter(x, y, color="k")
xx = self.np.linspace(0, 1, 50)
yy = self.polyfuel(xx)
plt.plot(xx, yy, "--", color="gray")
if plot:
plt.show()
else:
return plt
|
(self, plot=True)
|
722,188 |
openap.fuel
|
takeoff
|
Compute the fuel flow at takeoff.
The net thrust is first estimated based on the maximum thrust model
and throttle setting. Then FuelFlow.at_thrust() is called to compted
the thrust.
Args:
tas (int or ndarray): Aircraft true airspeed (unit: kt).
alt (int or ndarray): Altitude of airport (unit: ft). Defaults to sea-level.
throttle (float or ndarray): The throttle setting, between 0 and 1.
Defaults to 1, which is at full thrust.
Returns:
float: Fuel flow (unit: kg/s).
|
"""OpenAP FuelFlow model."""
import importlib
from openap import prop
from openap.extra import ndarrayconvert
def func_fuel2(a, b):
return lambda x: a * (x + b) ** 2
|
(self, tas, alt=None, throttle=1)
|
722,189 |
openap.thrust
|
Thrust
|
Simplified two-shaft turbonfan model.
|
class Thrust(object):
"""Simplified two-shaft turbonfan model."""
def __init__(self, ac, eng=None, **kwargs):
"""Initialize Thrust object.
Args:
ac (string): ICAO aircraft type (for example: A320).
eng (string): Engine type (for example: CFM56-5A3).
"""
if not hasattr(self, "np"):
self.np = importlib.import_module("numpy")
if not hasattr(self, "aero"):
self.aero = importlib.import_module("openap").aero
aircraft = prop.aircraft(ac, **kwargs)
force_engine = kwargs.get("force_engine", False)
if eng is None:
eng = aircraft["engine"]["default"]
engine = prop.engine(eng)
eng_options = aircraft["engine"]["options"]
if isinstance(eng_options, dict):
eng_options = list(aircraft["engine"]["options"].values())
if (not force_engine) and (engine["name"] not in eng_options):
raise RuntimeError(
f"Engine {eng} and aircraft {ac} mismatch. Available engines for {ac} are {eng_options}"
)
self.cruise_alt = aircraft["cruise"]["height"] / self.aero.ft
# self.cruise_alt = 30000
self.eng_bpr = engine["bpr"]
self.eng_max_thrust = engine["max_thrust"]
self.eng_number = aircraft["engine"]["number"]
if engine["cruise_mach"] > 0:
self.cruise_mach = engine["cruise_mach"]
self.eng_cruise_thrust = engine["cruise_thrust"]
else:
self.cruise_mach = aircraft["cruise"]["mach"]
self.eng_cruise_thrust = 0.2 * self.eng_max_thrust + 890
def _dfunc(self, mratio):
d = -0.4204 * mratio + 1.0824
return d
def _nfunc(self, roc):
# n = self.np.where(roc<1500, 0.89, self.np.where(roc<2500, 0.93, 0.97))
n = 2.667e-05 * roc + 0.8633
return n
def _mfunc(self, vratio, roc):
m = -1.2043e-1 * vratio - 8.8889e-9 * roc**2 + 2.4444e-5 * roc + 4.7379e-1
return m
@ndarrayconvert
def takeoff(self, tas, alt=None):
"""Calculate thrust at takeoff condition.
Args:
tas (float or ndarray): True airspeed (kt).
alt (float or ndarray): Altitude of the runway (ft). Defaults to 0.
Returns:
float or ndarray: Total thrust (unit: N).
"""
mach = self.aero.tas2mach(tas * self.aero.kts, 0)
eng_bpr = self.eng_bpr
G0 = 0.0606 * self.eng_bpr + 0.6337
if alt is None:
# at sea level
ratio = (
1
- 0.377 * (1 + eng_bpr) / self.np.sqrt((1 + 0.82 * eng_bpr) * G0) * mach
+ (0.23 + 0.19 * self.np.sqrt(eng_bpr)) * mach**2
)
else:
# at certain altitude
P = self.aero.pressure(alt * self.aero.ft)
dP = P / self.aero.p0
A = -0.4327 * dP**2 + 1.3855 * dP + 0.0472
Z = 0.9106 * dP**3 - 1.7736 * dP**2 + 1.8697 * dP
X = 0.1377 * dP**3 - 0.4374 * dP**2 + 1.3003 * dP
ratio = (
A
- 0.377
* (1 + eng_bpr)
/ self.np.sqrt((1 + 0.82 * eng_bpr) * G0)
* Z
* mach
+ (0.23 + 0.19 * self.np.sqrt(eng_bpr)) * X * mach**2
)
F = ratio * self.eng_max_thrust * self.eng_number
return F
@ndarrayconvert
def cruise(self, tas, alt):
"""Calculate thrust at the cruise.
Args:
tas (float or ndarray): True airspeed (kt).
alt (float or ndarray): Altitude (ft).
Returns:
float or ndarray: Total thrust (unit: N).
"""
return self.climb(tas, alt, roc=0)
@ndarrayconvert
def climb(self, tas, alt, roc):
"""Calculate thrust during the climb.
Args:
tas (float or ndarray): True airspeed (kt).
alt (float or ndarray): Altitude(ft)
roc (float or ndarray): Vertical rate (ft/min).
Returns:
float or ndarray: Total thrust (unit: N).
"""
roc = self.np.abs(roc)
h = alt * self.aero.ft
tas = self.np.where(tas < 10, 10, tas)
mach = self.aero.tas2mach(tas * self.aero.kts, h)
vcas = self.aero.tas2cas(tas * self.aero.kts, h)
P = self.aero.pressure(h)
P10 = self.aero.pressure(10000 * self.aero.ft)
Pcr = self.aero.pressure(self.cruise_alt * self.aero.ft)
# approximate thrust at top of climb (REF 2)
Fcr = self.eng_cruise_thrust * self.eng_number
vcas_ref = self.aero.mach2cas(self.cruise_mach, self.cruise_alt * self.aero.ft)
# segment 3: alt > 30000:
d = self._dfunc(mach / self.cruise_mach)
b = (mach / self.cruise_mach) ** (-0.11)
ratio_seg3 = d * self.np.log(P / Pcr) + b
# segment 2: 10000 < alt <= 30000:
a = (vcas / vcas_ref) ** (-0.1)
n = self._nfunc(roc)
ratio_seg2 = a * (P / Pcr) ** (-0.355 * (vcas / vcas_ref) + n)
# segment 1: alt <= 10000:
F10 = Fcr * a * (P10 / Pcr) ** (-0.355 * (vcas / vcas_ref) + n)
m = self._mfunc(vcas / vcas_ref, roc)
ratio_seg1 = m * (P / Pcr) + (F10 / Fcr - m * (P10 / Pcr))
ratio = self.np.where(
alt > 30000, ratio_seg3, self.np.where(alt > 10000, ratio_seg2, ratio_seg1)
)
F = ratio * Fcr
return F
def descent_idle(self, tas, alt):
"""Idle thrust during the descent.
Note: The idle thrust at the descent is taken as 7% of the maximum
avaiable thrust. This may (likely) differ from actual idle thrust.
Args:
tas (float or ndarray): True airspeed (kt).
alt (float or ndarray): Altitude(ft)
Returns:
float or ndarray: Total thrust (unit: N).
"""
F = 0.07 * self.climb(tas, alt, roc=0)
return F
|
(ac, eng=None, **kwargs)
|
722,190 |
openap.thrust
|
__init__
|
Initialize Thrust object.
Args:
ac (string): ICAO aircraft type (for example: A320).
eng (string): Engine type (for example: CFM56-5A3).
|
def __init__(self, ac, eng=None, **kwargs):
"""Initialize Thrust object.
Args:
ac (string): ICAO aircraft type (for example: A320).
eng (string): Engine type (for example: CFM56-5A3).
"""
if not hasattr(self, "np"):
self.np = importlib.import_module("numpy")
if not hasattr(self, "aero"):
self.aero = importlib.import_module("openap").aero
aircraft = prop.aircraft(ac, **kwargs)
force_engine = kwargs.get("force_engine", False)
if eng is None:
eng = aircraft["engine"]["default"]
engine = prop.engine(eng)
eng_options = aircraft["engine"]["options"]
if isinstance(eng_options, dict):
eng_options = list(aircraft["engine"]["options"].values())
if (not force_engine) and (engine["name"] not in eng_options):
raise RuntimeError(
f"Engine {eng} and aircraft {ac} mismatch. Available engines for {ac} are {eng_options}"
)
self.cruise_alt = aircraft["cruise"]["height"] / self.aero.ft
# self.cruise_alt = 30000
self.eng_bpr = engine["bpr"]
self.eng_max_thrust = engine["max_thrust"]
self.eng_number = aircraft["engine"]["number"]
if engine["cruise_mach"] > 0:
self.cruise_mach = engine["cruise_mach"]
self.eng_cruise_thrust = engine["cruise_thrust"]
else:
self.cruise_mach = aircraft["cruise"]["mach"]
self.eng_cruise_thrust = 0.2 * self.eng_max_thrust + 890
|
(self, ac, eng=None, **kwargs)
|
722,191 |
openap.thrust
|
_dfunc
| null |
def _dfunc(self, mratio):
d = -0.4204 * mratio + 1.0824
return d
|
(self, mratio)
|
722,192 |
openap.thrust
|
_mfunc
| null |
def _mfunc(self, vratio, roc):
m = -1.2043e-1 * vratio - 8.8889e-9 * roc**2 + 2.4444e-5 * roc + 4.7379e-1
return m
|
(self, vratio, roc)
|
722,193 |
openap.thrust
|
_nfunc
| null |
def _nfunc(self, roc):
# n = self.np.where(roc<1500, 0.89, self.np.where(roc<2500, 0.93, 0.97))
n = 2.667e-05 * roc + 0.8633
return n
|
(self, roc)
|
722,194 |
openap.thrust
|
climb
|
Calculate thrust during the climb.
Args:
tas (float or ndarray): True airspeed (kt).
alt (float or ndarray): Altitude(ft)
roc (float or ndarray): Vertical rate (ft/min).
Returns:
float or ndarray: Total thrust (unit: N).
|
"""OpenAP thrust model.
Simplified two-shaft turbonfan model base on:
- M. Bartel, T. M. Young, Simplified Thrust and Fuel Consumption
Models for Modern Two-Shaft Turbonfan Engines
- C. Svoboda, Turbofan engine database as a preliminary desgin (cruise thrust)
"""
import importlib
from openap import prop
from openap.extra import ndarrayconvert
class Thrust(object):
"""Simplified two-shaft turbonfan model."""
def __init__(self, ac, eng=None, **kwargs):
"""Initialize Thrust object.
Args:
ac (string): ICAO aircraft type (for example: A320).
eng (string): Engine type (for example: CFM56-5A3).
"""
if not hasattr(self, "np"):
self.np = importlib.import_module("numpy")
if not hasattr(self, "aero"):
self.aero = importlib.import_module("openap").aero
aircraft = prop.aircraft(ac, **kwargs)
force_engine = kwargs.get("force_engine", False)
if eng is None:
eng = aircraft["engine"]["default"]
engine = prop.engine(eng)
eng_options = aircraft["engine"]["options"]
if isinstance(eng_options, dict):
eng_options = list(aircraft["engine"]["options"].values())
if (not force_engine) and (engine["name"] not in eng_options):
raise RuntimeError(
f"Engine {eng} and aircraft {ac} mismatch. Available engines for {ac} are {eng_options}"
)
self.cruise_alt = aircraft["cruise"]["height"] / self.aero.ft
# self.cruise_alt = 30000
self.eng_bpr = engine["bpr"]
self.eng_max_thrust = engine["max_thrust"]
self.eng_number = aircraft["engine"]["number"]
if engine["cruise_mach"] > 0:
self.cruise_mach = engine["cruise_mach"]
self.eng_cruise_thrust = engine["cruise_thrust"]
else:
self.cruise_mach = aircraft["cruise"]["mach"]
self.eng_cruise_thrust = 0.2 * self.eng_max_thrust + 890
def _dfunc(self, mratio):
d = -0.4204 * mratio + 1.0824
return d
def _nfunc(self, roc):
# n = self.np.where(roc<1500, 0.89, self.np.where(roc<2500, 0.93, 0.97))
n = 2.667e-05 * roc + 0.8633
return n
def _mfunc(self, vratio, roc):
m = -1.2043e-1 * vratio - 8.8889e-9 * roc**2 + 2.4444e-5 * roc + 4.7379e-1
return m
@ndarrayconvert
def takeoff(self, tas, alt=None):
"""Calculate thrust at takeoff condition.
Args:
tas (float or ndarray): True airspeed (kt).
alt (float or ndarray): Altitude of the runway (ft). Defaults to 0.
Returns:
float or ndarray: Total thrust (unit: N).
"""
mach = self.aero.tas2mach(tas * self.aero.kts, 0)
eng_bpr = self.eng_bpr
G0 = 0.0606 * self.eng_bpr + 0.6337
if alt is None:
# at sea level
ratio = (
1
- 0.377 * (1 + eng_bpr) / self.np.sqrt((1 + 0.82 * eng_bpr) * G0) * mach
+ (0.23 + 0.19 * self.np.sqrt(eng_bpr)) * mach**2
)
else:
# at certain altitude
P = self.aero.pressure(alt * self.aero.ft)
dP = P / self.aero.p0
A = -0.4327 * dP**2 + 1.3855 * dP + 0.0472
Z = 0.9106 * dP**3 - 1.7736 * dP**2 + 1.8697 * dP
X = 0.1377 * dP**3 - 0.4374 * dP**2 + 1.3003 * dP
ratio = (
A
- 0.377
* (1 + eng_bpr)
/ self.np.sqrt((1 + 0.82 * eng_bpr) * G0)
* Z
* mach
+ (0.23 + 0.19 * self.np.sqrt(eng_bpr)) * X * mach**2
)
F = ratio * self.eng_max_thrust * self.eng_number
return F
@ndarrayconvert
def cruise(self, tas, alt):
"""Calculate thrust at the cruise.
Args:
tas (float or ndarray): True airspeed (kt).
alt (float or ndarray): Altitude (ft).
Returns:
float or ndarray: Total thrust (unit: N).
"""
return self.climb(tas, alt, roc=0)
@ndarrayconvert
def climb(self, tas, alt, roc):
"""Calculate thrust during the climb.
Args:
tas (float or ndarray): True airspeed (kt).
alt (float or ndarray): Altitude(ft)
roc (float or ndarray): Vertical rate (ft/min).
Returns:
float or ndarray: Total thrust (unit: N).
"""
roc = self.np.abs(roc)
h = alt * self.aero.ft
tas = self.np.where(tas < 10, 10, tas)
mach = self.aero.tas2mach(tas * self.aero.kts, h)
vcas = self.aero.tas2cas(tas * self.aero.kts, h)
P = self.aero.pressure(h)
P10 = self.aero.pressure(10000 * self.aero.ft)
Pcr = self.aero.pressure(self.cruise_alt * self.aero.ft)
# approximate thrust at top of climb (REF 2)
Fcr = self.eng_cruise_thrust * self.eng_number
vcas_ref = self.aero.mach2cas(self.cruise_mach, self.cruise_alt * self.aero.ft)
# segment 3: alt > 30000:
d = self._dfunc(mach / self.cruise_mach)
b = (mach / self.cruise_mach) ** (-0.11)
ratio_seg3 = d * self.np.log(P / Pcr) + b
# segment 2: 10000 < alt <= 30000:
a = (vcas / vcas_ref) ** (-0.1)
n = self._nfunc(roc)
ratio_seg2 = a * (P / Pcr) ** (-0.355 * (vcas / vcas_ref) + n)
# segment 1: alt <= 10000:
F10 = Fcr * a * (P10 / Pcr) ** (-0.355 * (vcas / vcas_ref) + n)
m = self._mfunc(vcas / vcas_ref, roc)
ratio_seg1 = m * (P / Pcr) + (F10 / Fcr - m * (P10 / Pcr))
ratio = self.np.where(
alt > 30000, ratio_seg3, self.np.where(alt > 10000, ratio_seg2, ratio_seg1)
)
F = ratio * Fcr
return F
def descent_idle(self, tas, alt):
"""Idle thrust during the descent.
Note: The idle thrust at the descent is taken as 7% of the maximum
avaiable thrust. This may (likely) differ from actual idle thrust.
Args:
tas (float or ndarray): True airspeed (kt).
alt (float or ndarray): Altitude(ft)
Returns:
float or ndarray: Total thrust (unit: N).
"""
F = 0.07 * self.climb(tas, alt, roc=0)
return F
|
(self, tas, alt, roc)
|
722,195 |
openap.thrust
|
cruise
|
Calculate thrust at the cruise.
Args:
tas (float or ndarray): True airspeed (kt).
alt (float or ndarray): Altitude (ft).
Returns:
float or ndarray: Total thrust (unit: N).
|
"""OpenAP thrust model.
Simplified two-shaft turbonfan model base on:
- M. Bartel, T. M. Young, Simplified Thrust and Fuel Consumption
Models for Modern Two-Shaft Turbonfan Engines
- C. Svoboda, Turbofan engine database as a preliminary desgin (cruise thrust)
"""
import importlib
from openap import prop
from openap.extra import ndarrayconvert
class Thrust(object):
"""Simplified two-shaft turbonfan model."""
def __init__(self, ac, eng=None, **kwargs):
"""Initialize Thrust object.
Args:
ac (string): ICAO aircraft type (for example: A320).
eng (string): Engine type (for example: CFM56-5A3).
"""
if not hasattr(self, "np"):
self.np = importlib.import_module("numpy")
if not hasattr(self, "aero"):
self.aero = importlib.import_module("openap").aero
aircraft = prop.aircraft(ac, **kwargs)
force_engine = kwargs.get("force_engine", False)
if eng is None:
eng = aircraft["engine"]["default"]
engine = prop.engine(eng)
eng_options = aircraft["engine"]["options"]
if isinstance(eng_options, dict):
eng_options = list(aircraft["engine"]["options"].values())
if (not force_engine) and (engine["name"] not in eng_options):
raise RuntimeError(
f"Engine {eng} and aircraft {ac} mismatch. Available engines for {ac} are {eng_options}"
)
self.cruise_alt = aircraft["cruise"]["height"] / self.aero.ft
# self.cruise_alt = 30000
self.eng_bpr = engine["bpr"]
self.eng_max_thrust = engine["max_thrust"]
self.eng_number = aircraft["engine"]["number"]
if engine["cruise_mach"] > 0:
self.cruise_mach = engine["cruise_mach"]
self.eng_cruise_thrust = engine["cruise_thrust"]
else:
self.cruise_mach = aircraft["cruise"]["mach"]
self.eng_cruise_thrust = 0.2 * self.eng_max_thrust + 890
def _dfunc(self, mratio):
d = -0.4204 * mratio + 1.0824
return d
def _nfunc(self, roc):
# n = self.np.where(roc<1500, 0.89, self.np.where(roc<2500, 0.93, 0.97))
n = 2.667e-05 * roc + 0.8633
return n
def _mfunc(self, vratio, roc):
m = -1.2043e-1 * vratio - 8.8889e-9 * roc**2 + 2.4444e-5 * roc + 4.7379e-1
return m
@ndarrayconvert
def takeoff(self, tas, alt=None):
"""Calculate thrust at takeoff condition.
Args:
tas (float or ndarray): True airspeed (kt).
alt (float or ndarray): Altitude of the runway (ft). Defaults to 0.
Returns:
float or ndarray: Total thrust (unit: N).
"""
mach = self.aero.tas2mach(tas * self.aero.kts, 0)
eng_bpr = self.eng_bpr
G0 = 0.0606 * self.eng_bpr + 0.6337
if alt is None:
# at sea level
ratio = (
1
- 0.377 * (1 + eng_bpr) / self.np.sqrt((1 + 0.82 * eng_bpr) * G0) * mach
+ (0.23 + 0.19 * self.np.sqrt(eng_bpr)) * mach**2
)
else:
# at certain altitude
P = self.aero.pressure(alt * self.aero.ft)
dP = P / self.aero.p0
A = -0.4327 * dP**2 + 1.3855 * dP + 0.0472
Z = 0.9106 * dP**3 - 1.7736 * dP**2 + 1.8697 * dP
X = 0.1377 * dP**3 - 0.4374 * dP**2 + 1.3003 * dP
ratio = (
A
- 0.377
* (1 + eng_bpr)
/ self.np.sqrt((1 + 0.82 * eng_bpr) * G0)
* Z
* mach
+ (0.23 + 0.19 * self.np.sqrt(eng_bpr)) * X * mach**2
)
F = ratio * self.eng_max_thrust * self.eng_number
return F
@ndarrayconvert
def cruise(self, tas, alt):
"""Calculate thrust at the cruise.
Args:
tas (float or ndarray): True airspeed (kt).
alt (float or ndarray): Altitude (ft).
Returns:
float or ndarray: Total thrust (unit: N).
"""
return self.climb(tas, alt, roc=0)
@ndarrayconvert
def climb(self, tas, alt, roc):
"""Calculate thrust during the climb.
Args:
tas (float or ndarray): True airspeed (kt).
alt (float or ndarray): Altitude(ft)
roc (float or ndarray): Vertical rate (ft/min).
Returns:
float or ndarray: Total thrust (unit: N).
"""
roc = self.np.abs(roc)
h = alt * self.aero.ft
tas = self.np.where(tas < 10, 10, tas)
mach = self.aero.tas2mach(tas * self.aero.kts, h)
vcas = self.aero.tas2cas(tas * self.aero.kts, h)
P = self.aero.pressure(h)
P10 = self.aero.pressure(10000 * self.aero.ft)
Pcr = self.aero.pressure(self.cruise_alt * self.aero.ft)
# approximate thrust at top of climb (REF 2)
Fcr = self.eng_cruise_thrust * self.eng_number
vcas_ref = self.aero.mach2cas(self.cruise_mach, self.cruise_alt * self.aero.ft)
# segment 3: alt > 30000:
d = self._dfunc(mach / self.cruise_mach)
b = (mach / self.cruise_mach) ** (-0.11)
ratio_seg3 = d * self.np.log(P / Pcr) + b
# segment 2: 10000 < alt <= 30000:
a = (vcas / vcas_ref) ** (-0.1)
n = self._nfunc(roc)
ratio_seg2 = a * (P / Pcr) ** (-0.355 * (vcas / vcas_ref) + n)
# segment 1: alt <= 10000:
F10 = Fcr * a * (P10 / Pcr) ** (-0.355 * (vcas / vcas_ref) + n)
m = self._mfunc(vcas / vcas_ref, roc)
ratio_seg1 = m * (P / Pcr) + (F10 / Fcr - m * (P10 / Pcr))
ratio = self.np.where(
alt > 30000, ratio_seg3, self.np.where(alt > 10000, ratio_seg2, ratio_seg1)
)
F = ratio * Fcr
return F
def descent_idle(self, tas, alt):
"""Idle thrust during the descent.
Note: The idle thrust at the descent is taken as 7% of the maximum
avaiable thrust. This may (likely) differ from actual idle thrust.
Args:
tas (float or ndarray): True airspeed (kt).
alt (float or ndarray): Altitude(ft)
Returns:
float or ndarray: Total thrust (unit: N).
"""
F = 0.07 * self.climb(tas, alt, roc=0)
return F
|
(self, tas, alt)
|
722,196 |
openap.thrust
|
descent_idle
|
Idle thrust during the descent.
Note: The idle thrust at the descent is taken as 7% of the maximum
avaiable thrust. This may (likely) differ from actual idle thrust.
Args:
tas (float or ndarray): True airspeed (kt).
alt (float or ndarray): Altitude(ft)
Returns:
float or ndarray: Total thrust (unit: N).
|
def descent_idle(self, tas, alt):
"""Idle thrust during the descent.
Note: The idle thrust at the descent is taken as 7% of the maximum
avaiable thrust. This may (likely) differ from actual idle thrust.
Args:
tas (float or ndarray): True airspeed (kt).
alt (float or ndarray): Altitude(ft)
Returns:
float or ndarray: Total thrust (unit: N).
"""
F = 0.07 * self.climb(tas, alt, roc=0)
return F
|
(self, tas, alt)
|
722,197 |
openap.thrust
|
takeoff
|
Calculate thrust at takeoff condition.
Args:
tas (float or ndarray): True airspeed (kt).
alt (float or ndarray): Altitude of the runway (ft). Defaults to 0.
Returns:
float or ndarray: Total thrust (unit: N).
|
"""OpenAP thrust model.
Simplified two-shaft turbonfan model base on:
- M. Bartel, T. M. Young, Simplified Thrust and Fuel Consumption
Models for Modern Two-Shaft Turbonfan Engines
- C. Svoboda, Turbofan engine database as a preliminary desgin (cruise thrust)
"""
import importlib
from openap import prop
from openap.extra import ndarrayconvert
class Thrust(object):
"""Simplified two-shaft turbonfan model."""
def __init__(self, ac, eng=None, **kwargs):
"""Initialize Thrust object.
Args:
ac (string): ICAO aircraft type (for example: A320).
eng (string): Engine type (for example: CFM56-5A3).
"""
if not hasattr(self, "np"):
self.np = importlib.import_module("numpy")
if not hasattr(self, "aero"):
self.aero = importlib.import_module("openap").aero
aircraft = prop.aircraft(ac, **kwargs)
force_engine = kwargs.get("force_engine", False)
if eng is None:
eng = aircraft["engine"]["default"]
engine = prop.engine(eng)
eng_options = aircraft["engine"]["options"]
if isinstance(eng_options, dict):
eng_options = list(aircraft["engine"]["options"].values())
if (not force_engine) and (engine["name"] not in eng_options):
raise RuntimeError(
f"Engine {eng} and aircraft {ac} mismatch. Available engines for {ac} are {eng_options}"
)
self.cruise_alt = aircraft["cruise"]["height"] / self.aero.ft
# self.cruise_alt = 30000
self.eng_bpr = engine["bpr"]
self.eng_max_thrust = engine["max_thrust"]
self.eng_number = aircraft["engine"]["number"]
if engine["cruise_mach"] > 0:
self.cruise_mach = engine["cruise_mach"]
self.eng_cruise_thrust = engine["cruise_thrust"]
else:
self.cruise_mach = aircraft["cruise"]["mach"]
self.eng_cruise_thrust = 0.2 * self.eng_max_thrust + 890
def _dfunc(self, mratio):
d = -0.4204 * mratio + 1.0824
return d
def _nfunc(self, roc):
# n = self.np.where(roc<1500, 0.89, self.np.where(roc<2500, 0.93, 0.97))
n = 2.667e-05 * roc + 0.8633
return n
def _mfunc(self, vratio, roc):
m = -1.2043e-1 * vratio - 8.8889e-9 * roc**2 + 2.4444e-5 * roc + 4.7379e-1
return m
@ndarrayconvert
def takeoff(self, tas, alt=None):
"""Calculate thrust at takeoff condition.
Args:
tas (float or ndarray): True airspeed (kt).
alt (float or ndarray): Altitude of the runway (ft). Defaults to 0.
Returns:
float or ndarray: Total thrust (unit: N).
"""
mach = self.aero.tas2mach(tas * self.aero.kts, 0)
eng_bpr = self.eng_bpr
G0 = 0.0606 * self.eng_bpr + 0.6337
if alt is None:
# at sea level
ratio = (
1
- 0.377 * (1 + eng_bpr) / self.np.sqrt((1 + 0.82 * eng_bpr) * G0) * mach
+ (0.23 + 0.19 * self.np.sqrt(eng_bpr)) * mach**2
)
else:
# at certain altitude
P = self.aero.pressure(alt * self.aero.ft)
dP = P / self.aero.p0
A = -0.4327 * dP**2 + 1.3855 * dP + 0.0472
Z = 0.9106 * dP**3 - 1.7736 * dP**2 + 1.8697 * dP
X = 0.1377 * dP**3 - 0.4374 * dP**2 + 1.3003 * dP
ratio = (
A
- 0.377
* (1 + eng_bpr)
/ self.np.sqrt((1 + 0.82 * eng_bpr) * G0)
* Z
* mach
+ (0.23 + 0.19 * self.np.sqrt(eng_bpr)) * X * mach**2
)
F = ratio * self.eng_max_thrust * self.eng_number
return F
@ndarrayconvert
def cruise(self, tas, alt):
"""Calculate thrust at the cruise.
Args:
tas (float or ndarray): True airspeed (kt).
alt (float or ndarray): Altitude (ft).
Returns:
float or ndarray: Total thrust (unit: N).
"""
return self.climb(tas, alt, roc=0)
@ndarrayconvert
def climb(self, tas, alt, roc):
"""Calculate thrust during the climb.
Args:
tas (float or ndarray): True airspeed (kt).
alt (float or ndarray): Altitude(ft)
roc (float or ndarray): Vertical rate (ft/min).
Returns:
float or ndarray: Total thrust (unit: N).
"""
roc = self.np.abs(roc)
h = alt * self.aero.ft
tas = self.np.where(tas < 10, 10, tas)
mach = self.aero.tas2mach(tas * self.aero.kts, h)
vcas = self.aero.tas2cas(tas * self.aero.kts, h)
P = self.aero.pressure(h)
P10 = self.aero.pressure(10000 * self.aero.ft)
Pcr = self.aero.pressure(self.cruise_alt * self.aero.ft)
# approximate thrust at top of climb (REF 2)
Fcr = self.eng_cruise_thrust * self.eng_number
vcas_ref = self.aero.mach2cas(self.cruise_mach, self.cruise_alt * self.aero.ft)
# segment 3: alt > 30000:
d = self._dfunc(mach / self.cruise_mach)
b = (mach / self.cruise_mach) ** (-0.11)
ratio_seg3 = d * self.np.log(P / Pcr) + b
# segment 2: 10000 < alt <= 30000:
a = (vcas / vcas_ref) ** (-0.1)
n = self._nfunc(roc)
ratio_seg2 = a * (P / Pcr) ** (-0.355 * (vcas / vcas_ref) + n)
# segment 1: alt <= 10000:
F10 = Fcr * a * (P10 / Pcr) ** (-0.355 * (vcas / vcas_ref) + n)
m = self._mfunc(vcas / vcas_ref, roc)
ratio_seg1 = m * (P / Pcr) + (F10 / Fcr - m * (P10 / Pcr))
ratio = self.np.where(
alt > 30000, ratio_seg3, self.np.where(alt > 10000, ratio_seg2, ratio_seg1)
)
F = ratio * Fcr
return F
def descent_idle(self, tas, alt):
"""Idle thrust during the descent.
Note: The idle thrust at the descent is taken as 7% of the maximum
avaiable thrust. This may (likely) differ from actual idle thrust.
Args:
tas (float or ndarray): True airspeed (kt).
alt (float or ndarray): Altitude(ft)
Returns:
float or ndarray: Total thrust (unit: N).
"""
F = 0.07 * self.climb(tas, alt, roc=0)
return F
|
(self, tas, alt=None)
|
722,198 |
openap.kinematic
|
WRAP
|
Construct the kinematic model of the aicraft.
|
class WRAP(object):
"""Construct the kinematic model of the aicraft."""
def __init__(self, ac, **kwargs):
"""Initialize WRAP object.
Args:
ac (string): ICAO aircraft type (for example: A320).
"""
super(WRAP, self).__init__()
self.ac = ac.lower()
self.use_synonym = kwargs.get("use_synonym", False)
wrap_files = glob.glob(dir_wrap + "*.txt")
ac_wrap_available = [s[-8:-4].lower() for s in wrap_files]
if self.ac not in ac_wrap_available and not self.use_synonym:
raise RuntimeError(f"Kinematic model for {self.ac} not avaiable in OpenAP.")
if self.ac not in ac_wrap_available and self.use_synonym:
syno = wrap_synonym.query("orig==@self.ac")
if syno.shape[0] > 0:
self.ac = syno.new.iloc[0]
else:
raise RuntimeError(
f"Kinematic model for {self.ac} not avaiable in OpenAP."
)
self.df = pd.read_fwf(dir_wrap + self.ac + ".txt")
def _get_var(self, var):
r = self.df[self.df["variable"] == var]
if r.shape[0] == 0:
raise RuntimeError("variable not found")
v = r.values[0]
res = {
"default": v[3],
"minimum": v[4],
"maximum": v[5],
"statmodel": v[6],
"statmodel_params": [float(i) for i in v[7].split("|")],
}
return res
def takeoff_speed(self):
"""Get takeoff speed."""
return self._get_var("to_v_lof")
def takeoff_distance(self):
"""Get takeoff takeoff distance."""
return self._get_var("to_d_tof")
def takeoff_acceleration(self):
"""Get takeoff takeoff acceleration."""
return self._get_var("to_acc_tof")
def initclimb_vcas(self):
"""Get initial climb CAS."""
return self._get_var("ic_va_avg")
def initclimb_vs(self):
"""Get initial climb vertical rate."""
return self._get_var("ic_vs_avg")
def climb_range(self):
"""Get climb range distance (in km)."""
return self._get_var("cl_d_range")
def climb_const_vcas(self):
"""Get speed for constant CAS climb."""
return self._get_var("cl_v_cas_const")
def climb_const_mach(self):
"""Get speed during constant Mach climb."""
return self._get_var("cl_v_mach_const")
def climb_cross_alt_concas(self):
"""Get cross over altitude when constant CAS climb starts."""
return self._get_var("cl_h_cas_const")
def climb_cross_alt_conmach(self):
"""Get cross over altitude from constant CAS to Mach climb."""
return self._get_var("cl_h_mach_const")
def climb_vs_pre_concas(self):
"""Get vertical rate before constant CAS climb."""
return self._get_var("cl_vs_avg_pre_cas")
def climb_vs_concas(self):
"""Get vertical rate during constant CAS climb."""
return self._get_var("cl_vs_avg_cas_const")
def climb_vs_conmach(self):
"""Get vertical rate during constant Mach climb."""
return self._get_var("cl_vs_avg_mach_const")
def cruise_range(self):
"""Get crusie range."""
return self._get_var("cr_d_range")
def cruise_alt(self):
"""Get average cruise altitude."""
return self._get_var("cr_h_mean")
def cruise_init_alt(self):
"""Get initial crusie altitude."""
return self._get_var("cr_h_init")
def cruise_mach(self):
"""Get average crusie Mach number."""
return self._get_var("cr_v_mach_mean")
def descent_range(self):
"""Get descent range."""
return self._get_var("de_d_range")
def descent_const_mach(self):
"""Get speed during the constant Mach descent."""
return self._get_var("de_v_mach_const")
def descent_const_vcas(self):
"""Get speed during the constant CAS descent."""
return self._get_var("de_v_cas_const")
def descent_cross_alt_conmach(self):
"""Get crossover altitude from constant Mach to CAS descent."""
return self._get_var("de_h_mach_const")
def descent_cross_alt_concas(self):
"""Get crossover altitude from constant Mach to CAS descent."""
return self._get_var("de_h_cas_const")
def descent_vs_conmach(self):
"""Get vertical rate during constant Mach descent."""
return self._get_var("de_vs_avg_mach_const")
def descent_vs_concas(self):
"""Get vertical rate during constant CAS descent."""
return self._get_var("de_vs_avg_cas_const")
def descent_vs_post_concas(self):
"""Get vertical rate after constant CAS descent."""
return self._get_var("de_vs_avg_after_cas")
def finalapp_vcas(self):
"""Get CAS for final approach."""
return self._get_var("fa_va_avg")
def finalapp_vs(self):
"""Get vertical speed for final approach."""
return self._get_var("fa_vs_avg")
def landing_speed(self):
"""Get landing speed."""
return self._get_var("ld_v_app")
def landing_distance(self):
"""Get breaking distance for landing."""
return self._get_var("ld_d_brk")
def landing_acceleration(self):
"""Get landing deceleration."""
return self._get_var("ld_acc_brk")
|
(ac, **kwargs)
|
722,199 |
openap.kinematic
|
__init__
|
Initialize WRAP object.
Args:
ac (string): ICAO aircraft type (for example: A320).
|
def __init__(self, ac, **kwargs):
"""Initialize WRAP object.
Args:
ac (string): ICAO aircraft type (for example: A320).
"""
super(WRAP, self).__init__()
self.ac = ac.lower()
self.use_synonym = kwargs.get("use_synonym", False)
wrap_files = glob.glob(dir_wrap + "*.txt")
ac_wrap_available = [s[-8:-4].lower() for s in wrap_files]
if self.ac not in ac_wrap_available and not self.use_synonym:
raise RuntimeError(f"Kinematic model for {self.ac} not avaiable in OpenAP.")
if self.ac not in ac_wrap_available and self.use_synonym:
syno = wrap_synonym.query("orig==@self.ac")
if syno.shape[0] > 0:
self.ac = syno.new.iloc[0]
else:
raise RuntimeError(
f"Kinematic model for {self.ac} not avaiable in OpenAP."
)
self.df = pd.read_fwf(dir_wrap + self.ac + ".txt")
|
(self, ac, **kwargs)
|
722,200 |
openap.kinematic
|
_get_var
| null |
def _get_var(self, var):
r = self.df[self.df["variable"] == var]
if r.shape[0] == 0:
raise RuntimeError("variable not found")
v = r.values[0]
res = {
"default": v[3],
"minimum": v[4],
"maximum": v[5],
"statmodel": v[6],
"statmodel_params": [float(i) for i in v[7].split("|")],
}
return res
|
(self, var)
|
722,201 |
openap.kinematic
|
climb_const_mach
|
Get speed during constant Mach climb.
|
def climb_const_mach(self):
"""Get speed during constant Mach climb."""
return self._get_var("cl_v_mach_const")
|
(self)
|
722,202 |
openap.kinematic
|
climb_const_vcas
|
Get speed for constant CAS climb.
|
def climb_const_vcas(self):
"""Get speed for constant CAS climb."""
return self._get_var("cl_v_cas_const")
|
(self)
|
722,203 |
openap.kinematic
|
climb_cross_alt_concas
|
Get cross over altitude when constant CAS climb starts.
|
def climb_cross_alt_concas(self):
"""Get cross over altitude when constant CAS climb starts."""
return self._get_var("cl_h_cas_const")
|
(self)
|
722,204 |
openap.kinematic
|
climb_cross_alt_conmach
|
Get cross over altitude from constant CAS to Mach climb.
|
def climb_cross_alt_conmach(self):
"""Get cross over altitude from constant CAS to Mach climb."""
return self._get_var("cl_h_mach_const")
|
(self)
|
722,205 |
openap.kinematic
|
climb_range
|
Get climb range distance (in km).
|
def climb_range(self):
"""Get climb range distance (in km)."""
return self._get_var("cl_d_range")
|
(self)
|
722,206 |
openap.kinematic
|
climb_vs_concas
|
Get vertical rate during constant CAS climb.
|
def climb_vs_concas(self):
"""Get vertical rate during constant CAS climb."""
return self._get_var("cl_vs_avg_cas_const")
|
(self)
|
722,207 |
openap.kinematic
|
climb_vs_conmach
|
Get vertical rate during constant Mach climb.
|
def climb_vs_conmach(self):
"""Get vertical rate during constant Mach climb."""
return self._get_var("cl_vs_avg_mach_const")
|
(self)
|
722,208 |
openap.kinematic
|
climb_vs_pre_concas
|
Get vertical rate before constant CAS climb.
|
def climb_vs_pre_concas(self):
"""Get vertical rate before constant CAS climb."""
return self._get_var("cl_vs_avg_pre_cas")
|
(self)
|
722,209 |
openap.kinematic
|
cruise_alt
|
Get average cruise altitude.
|
def cruise_alt(self):
"""Get average cruise altitude."""
return self._get_var("cr_h_mean")
|
(self)
|
722,210 |
openap.kinematic
|
cruise_init_alt
|
Get initial crusie altitude.
|
def cruise_init_alt(self):
"""Get initial crusie altitude."""
return self._get_var("cr_h_init")
|
(self)
|
722,211 |
openap.kinematic
|
cruise_mach
|
Get average crusie Mach number.
|
def cruise_mach(self):
"""Get average crusie Mach number."""
return self._get_var("cr_v_mach_mean")
|
(self)
|
722,212 |
openap.kinematic
|
cruise_range
|
Get crusie range.
|
def cruise_range(self):
"""Get crusie range."""
return self._get_var("cr_d_range")
|
(self)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.