code stringlengths 114 1.05M | path stringlengths 3 312 | quality_prob float64 0.5 0.99 | learning_prob float64 0.2 1 | filename stringlengths 3 168 | kind stringclasses 1
value |
|---|---|---|---|---|---|
from poppy.core.configuration import Configuration
from poppy.core.db.dry_runner import DryRunner
from poppy.core.generic.cache import CachedProperty
from poppy.pop.db_connector import POPPy as POPPyConnector
from roc.idb.models.idb import IdbRelease
from roc.idb.manager import IDBManager
from sqlalchemy.orm.exc import NoResultFound
__all__ = ['IdbConnector']
class IdbDatabaseError(Exception):
"""
Errors for the connector of the POPPy database.
"""
class IdbConnector(POPPyConnector):
"""
A class for querying the POPPy database with the IDB schema.
"""
@CachedProperty
def idb_manager(self):
"""
Create the IDB manager and store it.
"""
return IDBManager(self.session)
@DryRunner.dry_run
def get_idb(self):
"""
Return the database_descr object of the selected version of the IDB.
"""
if self._idb is None:
raise ValueError('Must specify a version for the IDB')
# construct the query
query = self.session.query(IdbRelease)
query = query.filter_by(idb_version=self._idb)
try:
return query.one()
except NoResultFound:
raise IdbDatabaseError(
(
'The IDB version {0} was not found on the database. '
+ 'Have you loaded the IDB inside the database with '
+ 'help of the -> pop rpl load command?'
).format(self._idb)
)
@property
def configuration(self):
return self._configuration
@configuration.setter
def configuration(self, configuration):
self._configuration = configuration
# get the descriptor file
descriptor = Configuration.manager['descriptor']
self._pipeline = descriptor['pipeline.release.version']
self._pipeline_name = descriptor['pipeline.identifier']
if 'idb_version' in self._configuration:
self._idb = self._configuration.idb_version | /roc_idb-1.4.3-py3-none-any.whl/roc/idb/connector.py | 0.616936 | 0.168173 | connector.py | pypi |
# Reference documentation
# ROC-GEN-SYS-NTT-00038-LES_Iss01_Rev02(Mission_Database_Description_Document)
from poppy.core.db.base import Base
from poppy.core.db.non_null_column import NonNullColumn
from sqlalchemy import String, ForeignKey, UniqueConstraint
from sqlalchemy.dialects.postgresql import (
BIGINT,
BOOLEAN,
DOUBLE_PRECISION,
ENUM,
INTEGER,
SMALLINT,
TIMESTAMP,
)
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.orm import relationship, validates, backref
__all__ = [
'ItemInfo',
'PacketMapInfo',
'IdbRelease',
'PacketMetadata',
'ParamInfo',
'PacketHeader',
'TransferFunction',
]
idb_source_enum = ['PALISADE', 'MIB', 'SRDB']
class IdbRelease(Base):
"""
The “idb_release” table provides information about the IDB releases stored
in the database.
"""
id_idb_release = NonNullColumn(INTEGER(), primary_key=True)
idb_version = NonNullColumn(String(128), descr='Version of the RPW IDB')
idb_source = NonNullColumn(
ENUM(*idb_source_enum, name='idb_source_type', schema='idb'),
descr='Sources of the IDB. Possible values '
f'are : {idb_source_enum}',
)
mib_version = NonNullColumn(
String(),
nullable=True,
descr='First row of the vdf.dat table including tabs',
)
current = NonNullColumn(
BOOLEAN(),
descr='"True" = current IDB to be used'
' by default, "False" otherwise',
)
validity_min = NonNullColumn(
TIMESTAMP(),
nullable=True,
descr='Minimal date/time of the IDB validity',
)
validity_max = NonNullColumn(
TIMESTAMP(),
nullable=True,
descr='Maximal date/time of the IDB validity',
)
__tablename__ = 'idb_release'
__table_args__ = (
UniqueConstraint('idb_version', 'idb_source'),
{'schema': 'idb',},
)
class ItemInfo(Base):
"""
The “item_info” table provides general information about RPW TM/TC packets
and packet parameters defined in the IDB.
"""
id_item_info = NonNullColumn(INTEGER(), primary_key=True)
idb_release_id = NonNullColumn(
INTEGER(), ForeignKey('idb.idb_release.id_idb_release')
)
srdb_id = NonNullColumn(
String(10), nullable=True, descr='SRDB ID of the packet or parameter'
)
palisade_id = NonNullColumn(
String(128),
nullable=True,
descr='PALISADE ID of the packet or parameter',
)
item_descr = NonNullColumn(
String(), nullable=True, descr='Description of the packet or parameter'
)
idb = relationship(
'IdbRelease',
backref=backref('item_info_idb_release', cascade='all,delete-orphan'),
)
__tablename__ = 'item_info'
__table_args__ = (
UniqueConstraint('srdb_id', 'idb_release_id'),
{'schema': 'idb',},
)
@validates('srdb_id')
def validate_srdbid(self, key, srdb_id):
if srdb_id is None:
pass
elif srdb_id.startswith('CIW'):
assert len(srdb_id) == 10
else:
assert len(srdb_id) == 8
return srdb_id
class PacketMetadata(Base):
"""
The “packet_metadata” table provides information about the SCOS-2000 packet
description.
"""
id_packet_metadata = NonNullColumn(INTEGER(), primary_key=True)
idb_release_id = NonNullColumn(
INTEGER(), ForeignKey('idb.idb_release.id_idb_release')
)
packet_category = NonNullColumn(
String(256), nullable=True, descr='Packet category'
)
idb = relationship(
'IdbRelease',
backref=backref(
'packet_metadata_idb_release', cascade='all,delete-orphan'
),
)
__tablename__ = 'packet_metadata'
__table_args__ = {
'schema': 'idb',
}
class TransferFunction(Base):
"""
The "transfer_function" table provides information about the transfer functions.
"""
id_transfer_function = NonNullColumn(INTEGER(), primary_key=True)
item_info_id = NonNullColumn(
INTEGER(), ForeignKey('idb.item_info.id_item_info')
)
raw = NonNullColumn(BIGINT(), descr='Raw value of the parameter')
eng = NonNullColumn(
String(),
descr='Engineering value of the parameter after transfer function applies',
)
item_info = relationship(
'ItemInfo',
backref=backref(
'transfer_function_item_info', cascade='all,delete-orphan'
),
)
__tablename__ = 'transfer_function'
__table_args__ = {
'schema': 'idb',
}
class PacketHeader(Base):
"""
The “packet_header” table provides information about the CCSDS packet
header description.
"""
id_packet_header = NonNullColumn(INTEGER(), primary_key=True)
item_info_id = NonNullColumn(
INTEGER(), ForeignKey('idb.item_info.id_item_info')
)
packet_metadata_id = NonNullColumn(
INTEGER(),
ForeignKey('idb.packet_metadata.id_packet_metadata'),
nullable=True,
)
cat_eng = NonNullColumn(
String(128), descr='Packet category in engineering value'
)
cat = NonNullColumn(BIGINT(), descr='Packet category in raw value')
packet_type = NonNullColumn(
String(16), descr='Packet type in engineering value'
)
byte_size = NonNullColumn(INTEGER(), descr='Packet byte size')
pid_eng = NonNullColumn(
String(128), nullable=True, descr='Packet PID in engineering value'
)
pid = NonNullColumn(
BIGINT(), nullable=True, descr='Packet PID in raw value'
)
spid = NonNullColumn(BIGINT(), nullable=True, descr='Packet SPID')
sid_eng = NonNullColumn(
String(128), nullable=True, descr='Packet SID in engineering value'
)
sid = NonNullColumn(
BIGINT(), nullable=True, descr='Packet SID in raw value'
)
service_type_eng = NonNullColumn(
String(128),
nullable=True,
descr='Packet service type in engineering' ' value',
)
service_type = NonNullColumn(
BIGINT(), descr='Packet service type in raw value'
)
service_subtype_eng = NonNullColumn(
String(128),
nullable=True,
descr='Packet service subtype in ' 'engineering value',
)
service_subtype = NonNullColumn(
BIGINT(), descr='Packet service subtype in raw value'
)
item_info = relationship(
'ItemInfo',
backref=backref(
'packet_header_item_info', cascade='all,delete-orphan'
),
)
packet_metadata = relationship(
'PacketMetadata',
backref=backref(
'packet_header_packet_metadata', cascade='all,delete-orphan'
),
)
__tablename__ = 'packet_header'
__table_args__ = {
'schema': 'idb',
}
class ParamInfo(Base):
"""
The “param_info” table provides information about the CCSDS packet
parameter description.
"""
id_param_info = NonNullColumn(INTEGER(), primary_key=True)
item_info_id = NonNullColumn(
INTEGER(), ForeignKey('idb.item_info.id_item_info')
)
par_bit_length = NonNullColumn(
SMALLINT(), descr='Bit length of the parameter'
)
par_type = NonNullColumn(String(16), descr='Type of parameter')
par_max = NonNullColumn(
DOUBLE_PRECISION(), nullable=True, descr='Parameter maximum value'
)
par_min = NonNullColumn(
DOUBLE_PRECISION(), nullable=True, descr='Parameter minimum value'
)
par_def = NonNullColumn(
String(64), nullable=True, descr='Parameter default value'
)
cal_num = NonNullColumn(
String(16), nullable=True, descr='raw-eng. cal. num.'
)
cal_val = NonNullColumn(
BIGINT(), nullable=True, descr='raw-eng. cal. val.'
)
par_unit = NonNullColumn(String(8), nullable=True, descr='Parameter unit')
par_is_editable = NonNullColumn(
BOOLEAN, nullable=True, descr='Parameter edition possibility'
)
transfer_function_id = NonNullColumn(
INTEGER(), ForeignKey('idb.item_info.id_item_info'), nullable=True
)
__tablename__ = 'param_info'
__table_args__ = {
'schema': 'idb',
}
info = relationship(
ItemInfo,
foreign_keys=[item_info_id],
backref=backref('param_info_item_info', cascade='all,delete-orphan'),
)
transfer_function = relationship(
ItemInfo,
foreign_keys=[transfer_function_id],
backref=backref(
'param_info_transfer_function', cascade='all,delete-orphan'
),
)
name = association_proxy('info', 'palisade_id')
description = association_proxy('info', 'item_descr')
class PacketMapInfo(Base):
"""
The “packet_map_info” table provides mapping information between the packet
and parameter description.
"""
id_packet_map_info = NonNullColumn(INTEGER(), primary_key=True)
packet_header_id = NonNullColumn(
INTEGER(), ForeignKey('idb.packet_header.id_packet_header')
)
param_info_id = NonNullColumn(
INTEGER(), ForeignKey('idb.param_info.id_param_info')
)
block_size = NonNullColumn(INTEGER(), descr='Size of the block')
group_size = NonNullColumn(INTEGER(), descr='Group size')
loop_value = NonNullColumn(INTEGER(), descr='Number of loop over blocks')
byte_position = NonNullColumn(INTEGER(), descr='Byte position')
bit_position = NonNullColumn(INTEGER(), descr='Bit position')
__tablename__ = 'packet_map_info'
__table_args__ = {
'schema': 'idb',
}
packet = relationship(
'PacketHeader',
backref=backref('packet_parameters', cascade='all,delete-orphan'),
)
parameter = relationship(
'ParamInfo',
backref=backref(
'packet_map_info_param_info', cascade='all,delete-orphan'
),
)
def __init__(
self,
parameter,
packet,
byte_position=0,
bit_position=0,
group_size=0,
block_size=0,
loop_value=0,
):
self.parameter = parameter
self.packet = packet
self.byte_position = byte_position
self.bit_position = bit_position
self.group_size = group_size
self.block_size = block_size
self.loop_value = loop_value | /roc_idb-1.4.3-py3-none-any.whl/roc/idb/models/idb.py | 0.717507 | 0.234226 | idb.py | pypi |
import csv
import glob
import os
from poppy.core.conf import settings
from poppy.core.db.connector import Connector
from poppy.core.target import FileTarget, PyObjectTarget
from poppy.core.task import Task
from roc.idb.parsers import MIBParser
__all__ = [
'ParseSequencesTask',
]
def parse_tc_duration_table(file_target):
# open the duration table and load the data
with file_target.open() as csv_file:
csv_reader = csv.reader(csv_file, delimiter=';')
# skip the headers
for _ in range(6):
next(csv_reader)
table = {}
for row in csv_reader:
# get the srdb id of the TC
srdb_id, palisade_id, duration, comment = row
table[srdb_id] = {
'palisade_id': palisade_id,
'duration': int(duration),
'comment': comment,
}
return table
def parse_sequence_description_table(file_target):
# open the sequence description table and load the data
with file_target.open() as csv_file:
csv_reader = csv.reader(csv_file, delimiter=';')
# skip the headers
for _ in range(1):
next(csv_reader)
table = {}
for row in csv_reader:
# get the srdb id of the TC
sequence_name, long_description, short_description = row
table[sequence_name] = {
'long_description': long_description,
'description': short_description,
}
return table
def load_rpw_states(rpw_state_description_directory_path):
state_description = {}
for json_filepath in glob.glob(
os.path.join(rpw_state_description_directory_path, '*.json')
):
key = os.path.splitext(os.path.basename(json_filepath))[0]
with open(json_filepath) as json_file:
state_description[key] = json_file.read()
return state_description
class ParseSequencesTask(Task):
plugin_name = 'roc.idb'
name = 'idb_parse_sequences'
def get_tc_duration_table_filepath(self, pipeline):
return os.path.join(pipeline.args.mib_dir_path, 'tc_duration.csv')
def get_sequence_description_table_filepath(self, pipeline):
return os.path.join(
pipeline.args.mib_dir_path, 'sequence_description_table.csv'
)
def add_targets(self):
self.add_input(
target_class=FileTarget,
identifier='tc_duration_table_filepath',
filepath=self.get_tc_duration_table_filepath,
)
self.add_input(
target_class=FileTarget,
identifier='sequence_description_table_filepath',
filepath=self.get_sequence_description_table_filepath,
)
self.add_output(target_class=PyObjectTarget, identifier='sequences')
self.add_output(
target_class=PyObjectTarget, identifier='tc_duration_table'
)
self.add_output(
target_class=PyObjectTarget,
identifier='sequence_description_table',
)
self.add_output(target_class=PyObjectTarget, identifier='rpw_states')
self.add_output(target_class=PyObjectTarget, identifier='idb_version')
@Connector.if_connected(settings.PIPELINE_DATABASE)
def run(self):
"""
Load MIB sequences into the ROC database
"""
# get the database session
self.session = self.pipeline.db.session
# instantiate the MIB parser
self.parser = MIBParser(
os.path.join(self.pipeline.args.mib_dir_path, 'data'),
None, # no mapping file needed to load sequences
)
# parse the sequences
sequences_data = self.parser.parse_sequences()
# read the TC duration table
self.outputs['tc_duration_table'].value = parse_tc_duration_table(
self.inputs['tc_duration_table_filepath']
)
# read the sequence duration table
self.outputs[
'sequence_description_table'
].value = parse_sequence_description_table(
self.inputs['sequence_description_table_filepath']
)
self.outputs['rpw_states'].value = load_rpw_states(
os.path.join(self.pipeline.args.mib_dir_path, 'rpw_states')
)
self.outputs['sequences'].value = sequences_data
self.outputs['idb_version'].value = self.parser.version() | /roc_idb-1.4.3-py3-none-any.whl/roc/idb/tasks/parse_sequences.py | 0.540924 | 0.180107 | parse_sequences.py | pypi |
import csv
import datetime
import os
import xlwt
from poppy.core.target import PyObjectTarget
from poppy.core.task import Task
from roc.idb.parsers.mib_parser.procedure import Procedure
__all__ = ['ExportSequencesTask']
def create_csv_from_dict(filepath, data):
# create directories if needed
os.makedirs(os.path.dirname(filepath), exist_ok=True)
# create the csv file
with open(filepath, 'w') as csv_file:
csv_writer = csv.DictWriter(csv_file, data['header'])
csv_writer.writeheader()
for row in data['rows']:
csv_writer.writerow(row)
def create_sequence_csv(filepath, data):
# loop over the sheets
for key in ['STMT', 'CMD Params', 'TLM Values', 'PKT Params', 'Info']:
create_csv_from_dict(os.path.join(filepath, key + '.csv'), data[key])
def create_xls_sheet(workbook, sheet_name, data):
header = data['header']
# create the sheet
sheet = workbook.add_sheet(sheet_name)
# populate the header
for index, entry in enumerate(header):
sheet.write(0, index, entry)
# populate the rest of the sheet with the given data
for row_idx, row in enumerate(data['rows']):
for col_index, col_name in enumerate(header):
entry = row.get(col_name)
# handle case where style is bundled with the value
if isinstance(entry, tuple):
value, style = entry
sheet.write(row_idx + 1, col_index, value, style)
else:
sheet.write(row_idx + 1, col_index, entry)
def create_sequence_xls(filepath, data):
workbook = xlwt.Workbook()
# loop over the sheets
for key in ['STMT', 'CMD Params', 'TLM Values', 'PKT Params', 'Info']:
create_xls_sheet(workbook, key, data[key])
workbook.save(filepath)
def render_xls_time(time_str, format='h:mm:ss'):
h, m, s = map(int, time_str.split(':'))
time_format = xlwt.XFStyle()
time_format.num_format_str = format
return (datetime.time(h, m, s), time_format)
@PyObjectTarget.input('sequences')
@PyObjectTarget.input('tc_duration_table')
@Task.as_task(plugin_name='roc.idb', name='idb_export_sequences')
def ExportSequencesTask(self):
args = self.pipeline.args
if args.seq_dir_path is None:
output_path = os.path.join(self.pipeline.output, 'mib_sequences')
else:
output_path = args.seq_dir_path
sequences_data = self.inputs['sequences'].value
tc_duration_table = self.inputs['tc_duration_table'].value
# create the csv files
for procedure_name in sequences_data:
for sequence_name in sequences_data[procedure_name]:
xls_data = Procedure.as_xls_data(
sequences_data[procedure_name][sequence_name],
tc_duration_table,
)
create_sequence_csv(
os.path.join(output_path, procedure_name, sequence_name),
xls_data,
)
# update the total duration value to be compatible with the xls renderer
xls_data['Info']['rows'][0][
'Procedure Duration'
] = render_xls_time(
xls_data['Info']['rows'][0]['Procedure Duration']
)
create_sequence_xls(
os.path.join(
output_path, procedure_name, sequence_name + '.xls'
),
xls_data,
) | /roc_idb-1.4.3-py3-none-any.whl/roc/idb/tasks/export_sequences.py | 0.424889 | 0.232277 | export_sequences.py | pypi |
from poppy.core.generic.metaclasses import Singleton
from poppy.core.logger import logger
__all__ = ['CDFToFill', 'fill_records', 'fill_dict']
def fill_records(records):
_filler(records, records.dtype.names)
def fill_dict(records):
_filler(records, records.keys())
def _filler(records, names):
# the converter
converter = CDFToFill()
# loop over fields
for name in names:
# dtype of the record
dtype = records[name].dtype.name
# the to fill with
value = converter(dtype)
logger.debug(
'Fill {0} record with {1} for type {2}'.format(name, value, dtype,)
)
# fill with value
records[name].fill(value)
class CDFToFill(object, metaclass=Singleton):
"""
To create a mapping between the CDF units and their fill values.
"""
def __init__(self):
self.mapping = {
'CDF_BYTE': -128,
'CDF_INT1': -128,
'int8': -128,
'CDF_UINT1': 255,
'uint8': 255,
'CDF_INT2': -32768,
'int16': -32768,
'CDF_UINT2': 65535,
'uint16': 65535,
'CDF_INT4': -2147483648,
'int32': -2147483648,
'CDF_UINT4': 4294967295,
'uint32': 4294967295,
'CDF_INT8': -9223372036854775808,
'int64': -9223372036854775808,
'uint64': 18446744073709551615,
'float': -1e31,
'float16': -1e31,
'CDF_REAL4': -1e31,
'CDF_FLOAT': -1e31,
'float32': -1e31,
'CDF_REAL8': -1e31,
'CDF_DOUBLE': -1e31,
'float64': -1e31,
'CDF_EPOCH': 0.0,
'CDF_TIME_TT2000': -9223372036854775808,
'CDF_CHAR': ' ',
'CDF_UCHAR': ' ',
}
self.validmin_mapping = {
'CDF_BYTE': -127,
'CDF_INT1': -127,
'CDF_UINT1': 0,
'CDF_INT2': -32767,
'CDF_UINT2': 0,
'CDF_INT4': -2147483647,
'CDF_UINT4': 0,
'CDF_INT8': -9223372036854775807,
'CDF_REAL4': -1e30,
'CDF_FLOAT': -1e30,
'CDF_REAL8': -1e30,
'CDF_DOUBLE': -1e30,
'CDF_TIME_TT2000': -9223372036854775807,
}
self.validmax_mapping = {
'CDF_BYTE': 127,
'CDF_INT1': 127,
'CDF_UINT1': 254,
'CDF_INT2': 32767,
'CDF_UINT2': 65534,
'CDF_INT4': 2147483647,
'CDF_UINT4': 4294967294,
'CDF_INT8': 9223372036854775807,
'CDF_REAL4': 3.4028235e38,
'CDF_FLOAT': 3.4028235e38,
'CDF_REAL8': 1.7976931348623157e308,
'CDF_DOUBLE': 1.7976931348623157e308,
'CDF_TIME_TT2000': 9223372036854775807,
}
def __call__(self, value):
if value not in self.mapping:
logger.error('{0} fill type not mapped'.format(value))
return
return self.mapping[value]
def validmin(self, value):
if value not in self.validmin_mapping:
logger.error('{0} validmin type not mapped'.format(value))
return
return self.validmin_mapping[value]
def validmax(self, value):
if value not in self.validmax_mapping:
logger.error('{0} validmax type not mapped'.format(value))
return
return self.validmax_mapping[value]
# vim: set tw=79 : | /roc_idb-1.4.3-py3-none-any.whl/roc/idb/converters/cdf_fill.py | 0.715424 | 0.255112 | cdf_fill.py | pypi |
from poppy.core.command import Command
from roc.idb.tasks import (
LoadTask,
LoadSequencesTask,
LoadPalisadeMetadataTask,
ParseSequencesTask,
)
__all__ = ['Load', 'LoadIdb', 'LoadSequences']
class Load(Command):
"""
Command to set a given idb version as current
"""
__command__ = 'idb_load'
__command_name__ = 'load'
__parent__ = 'idb'
__parent_arguments__ = ['base']
__help__ = 'Load the IDB from files'
class LoadIdb(Command):
"""
Command to load the information of the IDB into the ROC database.
"""
__command__ = 'idb_load_idb'
__command_name__ = 'idb'
__parent__ = 'idb_load'
__parent_arguments__ = ['base']
__help__ = (
'Load the IDB packets, parameters and transfer functions from files'
)
def add_arguments(self, parser):
# path to XML file of the IDB
parser.add_argument(
'-i',
'--idb-path',
help="""
Path to the IDB directory (e.g. 'V4.3.3/IDB/').
""",
type=str,
required=True,
)
# idb source
parser.add_argument(
'-t',
'--idb-source',
help="""
IDB type: SRDB or PALISADE or MIB (default: %(default)s).
""",
type=str,
default='MIB',
required=True,
)
# path to the mapping of parameters and packets to the SRDB
parser.add_argument(
'-m',
'--mapping',
help="""
Path to the XML file containing the mapping of parameters and
packets to the SRDB.
""",
type=str,
required=True,
)
def setup_tasks(self, pipeline):
"""
Load the information from the IDB in the given XML files and set them
into the ROC database.
"""
load_task = LoadTask()
# set the pipeline for this situation
pipeline | load_task
pipeline.start = load_task
class LoadPalisadeMetadata(Command):
"""
Command to load the PALISADE metadata into the ROC database.
"""
__command__ = 'idb_load_palisade_metadata'
__command_name__ = 'palisade_metadata'
__parent__ = 'idb_load'
__parent_arguments__ = ['base']
__help__ = 'Load the PALISADE metadata from XML files'
def add_arguments(self, parser):
# path to XML file of the IDB
parser.add_argument(
'idb_path',
help="""
Path to the PALISADE IDB directory (e.g. 'V4.3.3/IDB/').
""",
type=str,
)
def setup_tasks(self, pipeline):
"""
Load the information from the IDB in the given XML files and set them
into the ROC database.
"""
load_metadata_task = LoadPalisadeMetadataTask()
# set the pipeline for this situation
pipeline | load_metadata_task
pipeline.start = load_metadata_task
class LoadSequences(Command):
"""
Command to load MIB sequences into the ROC database.
"""
__command__ = 'idb_load_sequences'
__command_name__ = 'sequences'
__parent__ = 'idb_load'
__parent_arguments__ = ['base']
__help__ = 'Command to load MIB sequences into the MUSIC database'
def add_arguments(self, parser):
# path to MIB files directory
parser.add_argument(
'mib_dir_path',
help="""
Path to MIB files directory.
""",
type=str,
)
def setup_tasks(self, pipeline):
"""
Load MIB sequences into the MUSIC database
"""
# instantiate the task
parse_sequences = ParseSequencesTask()
load_sequences = LoadSequencesTask()
# set the pipeline topology
pipeline | (parse_sequences | load_sequences)
pipeline.start = parse_sequences | /roc_idb-1.4.3-py3-none-any.whl/roc/idb/commands/load.py | 0.755186 | 0.210726 | load.py | pypi |
import os
import numpy
from .procedure import Procedure
class ParseSequenceMixin(object):
def parse_sequences(self):
"""
Parse MIB sequences
"""
# the CSF table describes the top level of the sequence hierarchy, i.e. it defines the sequence itself
csf_dtype = numpy.dtype(
[
('SQNAME', 'U8'),
('DESC', 'U24'),
('DESC2', 'U64'),
(
'IFTT',
'U1',
), # Flag identifying whether or not the sequence contains execution
# time-tagged commands
(
'NFPARS',
'U64',
), # Number of formal parameters of this sequence
('ELEMS', 'U64'), # Number of elements in this sequence
(
'CRITICAL',
'U1',
), # Flag identifying the sequence 'criticality'
(
'PLAN',
'U1',
), # Flag identifying the sources which are allowed to reference
# directly this sequence and use it in a planning file
(
'EXEC',
'U1',
), # Flag controlling whether this sequence can be loaded onto
# SCOS-2000 manual stacks stand-alone
(
'SUBSYS',
'U64',
), # Identifier of the subsystem which the sequence belongs to
('TIME', 'U17'), # Time when sequence was generated
(
'DOCNAME',
'U32',
), # Document name from which it was generated (Procedure name)
('ISSUE', 'U10'), # Issue number of document described above
('DATE', 'U17'), # Issue date of document described above
(
'DEFSET',
'U8',
), # Name of the default parameter value set for the sequence
(
'SUBSCHEDID',
'U64',
), # Identifier of the default on-board sub-schedule to be used when
# loading this sequence as execution time-tagged
]
)
csf_table = self.from_table(
os.path.join(self.dir_path, 'csf.dat'),
dtype=csf_dtype,
regex_dict={'SQNAME': '^(ANEF|AIW[CFV])[0-9]{3}[A-Z]$'},
)
# the CSS table contains an entry for each element in the sequence
# an element can either be a sequence or command, or it can be a formal parameter of the current sequence
css_dtype = numpy.dtype(
[
(
'SQNAME',
'U8',
), # Name of the sequence which the element belongs to
(
'COMM',
'U32',
), # Additional comment to be associated with the sequence element
('ENTRY', int), # Entry number for the sequence element
(
'TYPE',
'U1',
), # Flag identifying the element type (C: Command, T: Textual comment)
(
'ELEMID',
'U8',
), # Element (identifier) for the current entry within the sequence
(
'NPARS',
int,
), # Number of editable parameters this element has
(
'MANDISP',
'U1',
), # Flag controlling whether the command requires explicit manual
# dispatch in a manual stack
(
'RELTYPE',
'U1',
), # Flag controlling how the field CSS_RELTIME has to be used to
# calculate the command release time-tag or the nested sequence
# release start time
(
'RELTIME',
'U8',
), # This field contains the delta release time-tag for the sequence
# element
(
'EXTIME',
'U17',
), # This field contains the delta execution time-tag for the sequence
# element
(
'PREVREL',
'U1',
), # Flag controlling how the field CSS_EXTIME has to be used to
# calculate the command execution time-tag or the nested sequence
# execution start time
(
'GROUP',
'U1',
), # This field defines the grouping condition for the sequence element
(
'BLOCK',
'U1',
), # This field defines the blocking condition for the sequence element
('ILSCOPE', 'U1'),
# Flag identifying the type of the interlock associated to this sequence element
('ILSTAGE', 'U1'),
# The type of verification stage to which an interlock associated to this
# sequence element waits on
('DYNPTV', 'U1'),
# Flag controlling whether the dynamic PTV checks shall be overridden for this sequence element
('STAPTV', 'U1'),
# Flag controlling whether the static (TM based) PTV check shall be overridden for this sequence element
('CEV', 'U1'),
# Flag controlling whether the CEV checks shall be disabled for this sequence element
]
)
css_table = self.from_table(
os.path.join(self.dir_path, 'css.dat'),
dtype=css_dtype,
regex_dict={'SQNAME': '^(ANEF|AIW[CFV])[0-9]{3}[A-Z]$'},
)
# the SDF table defines the values of the editable element parameters.
sdf_dtype = numpy.dtype(
[
(
'SQNAME',
'U8',
), # Name of the sequence which the parameter belongs to
(
'ENTRY',
int,
), # Entry number of the sequence element to which this parameter belongs
(
'ELEMID',
'U8',
), # Name of the sequence element to which this parameter belongs
('POS', int),
# If the sequence element is a command, then this field specifies the bit offset of the parameter in the command
(
'PNAME',
'U8',
), # Element parameter name i.e. name of the editable command parameter
('FTYPE', 'U1'),
# Flag controlling whether the parameter value can be modified after loading the sequence on the stack or if it should be considered as fixed
('VTYPE', 'U1'),
# Flag identifying the source of the element parameter value and how to interpret the SDF_VALUE field
(
'VALUE',
'U17',
), # This field contains the value for the element parameter
('VALSET', 'U8'),
# Name of the parameter value set (PSV_PVSID) which will be used to provide the value
('REPPOS', 'int'), # Command parameter repeated position
]
)
sdf_table = self.from_table(
os.path.join(self.dir_path, 'sdf.dat'),
dtype=sdf_dtype,
regex_dict={'SQNAME': '^(ANEF|AIW[CFV])[0-9]{3}[A-Z]$'},
)
# the CSP defines the formal parameters associated with the current sequence
csp_dtype = numpy.dtype(
[
(
'SQNAME',
'U8',
), # Name of the sequence which formal parameter belongs to
('FPNAME', 'U8'), # Name of this formal parameter
(
'FPNUM',
int,
), # Unique number of the formal parameter within the sequence
(
'DESCR',
'U24',
), # Textual description of the formal parameter
('PTC', int), # Parameter Type Code
('PFC', int), # Parameter Format Code
('DISPFMT', 'U1'),
# Flag controlling the input and display format of the engineering values for calibrated parameters and for time parameters
('RADIX', 'U1'),
# This is the default radix that the raw representation of the parameter if it is unsigned integer
(
'TYPE',
'U1',
), # Flag identifying the type of the formal parameter
('VTYPE', 'U1'),
# Flag identifying the representation used to express the formal parameter default value
(
'DEFVAL',
'U17',
), # This field contains the default value for this formal parameter
('CATEG', 'U1'),
# Flag identifying the type of calibration or special processing associated to the parameter
('PRFREF', 'U10'),
# This field contains the name of an existing parameter range set to which the parameter will be associated
('CCAREF', 'U10'),
# This field contains the name of an existing numeric calibration curve to which the parameter will be associated
('PAFREF', 'U10'),
# This field contains the name of an existing textual calibration definition to which the parameter will be associated
('UNIT', 'U4'), # Engineering unit mnemonic
]
)
csp_table = self.from_table(
os.path.join(self.dir_path, 'csp.dat'), dtype=csp_dtype,
)
# filter tables to keep only RPW sequences and return tables
# filter tables to keep only RPW sequences and create the procedure list
return Procedure.create_from_MIB(
csf_table, css_table, sdf_table, csp_table,
) | /roc_idb-1.4.3-py3-none-any.whl/roc/idb/parsers/mib_parser/parse_sequence_mixin.py | 0.482673 | 0.18665 | parse_sequence_mixin.py | pypi |
import os.path as osp
import xml.etree.ElementInclude as EI
import xml.etree.ElementTree as ET
from poppy.core.logger import logger
from roc.idb.parsers.idb_parser import IDBParser
__all__ = ['BasePALISADEParser', 'PALISADEException']
class PALISADEException(Exception):
"""
Exception for PALISADE.
"""
class BasePALISADEParser(IDBParser):
"""
Base class used for the parsing of the XML of the PALISADE IDB
"""
def __init__(self, idb, mapping_file_path):
"""
Store the file names of the XML files containing the IDB and the
mapping to the SRDB.
"""
super().__init__(mapping_file_path)
self._source = 'PALISADE'
self.idb = osp.join(idb, 'xml', 'RPW_IDB.xml')
self.enumerations = None
# create the tree of the IDB
self.store_tree()
# store the palisade metadata as a map indexed by SRDB IDs
self.palisade_metadata_map = {}
def store_tree(self):
"""
Create the tree from the file given in argument.
"""
# check that the file exist
if self.idb is None or not osp.isfile(self.idb):
message = "IDB {0} doesn't exist".format(self.idb)
logger.error(message)
raise FileNotFoundError(message)
# get the tree and namespace
self.tree, self.namespace = self.parse_and_get_ns(self.idb)
# get the root element
self.root = self.tree.getroot()
# get the directory path
self._path = self.get_path()
# include other files from root : First level
EI.include(self.root, loader=self._loader)
# include other files from child of root (second level)
# FIXME : Implement the general case with several level of "include"
EI.include(self.root, loader=self._loader)
# compute the parent map after includes
self.parent_map = {
child: parent for parent in self.tree.iter() for child in parent
}
def get_path(self):
"""
Return the directory path of the IDB to be used as root for the
included files in the XML.
"""
# get the absolute path of the directory
return osp.abspath(osp.dirname(self.idb))
def _loader(self, href, parse, encoding=None):
"""
The loader of included files in XML. In our case, the parse attribute
is always XML so do not do anything else.
"""
# open the included file and parse it to be returned
with open(osp.join(self._path, href), 'rb') as f:
return ET.parse(f).getroot()
def _find(self, node, path, *args):
"""
To find a node with the namespace passed as argument.
"""
return node.find(
path.format(*[self._ns[x] if x in self._ns else x for x in args])
)
def _findall(self, node, path, *args):
"""
To findall a node with the namespace passed as argument.
"""
return node.findall(
path.format(*[self._ns[x] if x in self._ns else x for x in args])
)
def get_structures(self):
"""
Get a dictionary of all structures defined in the XML IDB.
"""
# get all structures
structures = self._findall(self.root, './/{0}StructDefinition', '',)
# keep a dictionary of the structure name and the corresponding node
self.structures = {
struct.attrib['ID']: struct for struct in structures
}
def generate_srdb_ids_from_palisade_id(self, palisade_id):
"""
Given a PALISADE ID, generate the corresponding SRDB ID(s)
"""
for packet_type in ['TM', 'TC']:
if palisade_id in self.palisade_to_srdb_id[packet_type]:
if isinstance(
self.palisade_to_srdb_id[packet_type][palisade_id], list
):
for srdb_id in self.palisade_to_srdb_id[packet_type][
palisade_id
]:
yield srdb_id
else:
yield self.palisade_to_srdb_id[packet_type][palisade_id]
def get_palisade_category(self, node):
"""
Get the palisade category of a given node using the parent map of the xml tree
:param node: the node we want the category
:return: the palisade category
"""
current_node = node
node_tag_list = []
while 'parent is a node of the xml tree':
# get the parent node
parent = self.parent_map.get(current_node, None)
if parent is None:
break
if parent.tag.endswith('Category'):
# prepend the category to the list
node_tag_list.insert(0, parent.attrib['Name'])
current_node = parent
return '/' + '/'.join(node_tag_list)
def is_enumeration(self, parameter):
"""
Return True if a parameter is an enumeration.
"""
return parameter.is_enumeration()
@property
def namespace(self):
return self._ns
@namespace.setter
def namespace(self, namespace):
self._ns = namespace
# store some information from the namespace
self.struct_tag = '{0}Struct'.format(self._ns[''])
self.param_tag = '{0}Parameter'.format(self._ns[''])
self.spare_tag = '{0}Spare'.format(self._ns[''])
self.loop_tag = '{0}Loop'.format(self._ns[''])
def version(self):
"""
Return the version of the IDB defined in the XML file.
"""
if 'Version' not in self.root.attrib:
message = 'No version for the IDB from the specified XML file.'
logger.error(message)
raise PALISADEException(message)
return self.root.attrib['Version'].replace(' ', '_').upper() | /roc_idb-1.4.3-py3-none-any.whl/roc/idb/parsers/palisade_parser/base_palisade_parser.py | 0.505859 | 0.259281 | base_palisade_parser.py | pypi |
from poppy.core.logger import logger
from .base_palisade_parser import BasePALISADEParser
__all__ = [
'PALISADEMetadataParser',
]
class PALISADEMetadataParser(BasePALISADEParser):
"""
Class used for the parsing of the XML of the IDB (PALISADE) to get only the PALISADE metadata
"""
def parse(self):
"""
Call the load palisade method
"""
self.load_palisade_metadata()
def load_palisade_metadata(self):
"""
Load the palisade metadata map
:return:
"""
# search for packets in the given node
for packet_node in self._findall(
self.root, './/{0}PacketDefinition', '',
):
# get the name of the packet
palisade_id = packet_node.attrib['Name']
# search for the SRDB id of the packet
if palisade_id[:2] not in ['TM', 'TC']:
logger.warning('Skipping packet %s' % palisade_id)
continue
elif palisade_id in self.palisade_to_srdb_id[palisade_id[:2]]:
# keep reference to mapping
info = self.packets_mapping[palisade_id]
else:
logger.error(
(
'Packet {0} not found in PALISADE. Maybe an internal DPU'
+ ' command ?'
).format(palisade_id)
)
continue
# get the type of the packet
packet_type_node = self._find(
packet_node,
".//{0}Param[@StructParamIDRef='PACKET_TYPE']",
'',
)
if packet_type_node is None:
# the packet doesn't have a type, so don't analyze it
logger.warning(
(
"Packet {0} doesn't have a type. Surely an internal "
+ 'command of the DPU.'
).format(palisade_id)
)
continue
else:
packet_type = packet_type_node.attrib['Value'][:2]
# get the palisade category
palisade_category = self.get_palisade_category(packet_node)
# compute the long srdb id
srdb_id = self.compute_packet_srdbid(packet_type, info['SRDBID'])
# store the palisade id and the palisade category indexed by the srdb id
self.palisade_metadata_map[srdb_id] = {
'palisade_id': palisade_id,
'palisade_category': palisade_category,
} | /roc_idb-1.4.3-py3-none-any.whl/roc/idb/parsers/palisade_parser/palisade_metadata_parser.py | 0.592077 | 0.151749 | palisade_metadata_parser.py | pypi |
import os
from poppy.core.tools.poppy_argparse import argparse
from poppy.core.command import Command
from roc.punk.tasks.descriptor_report import DescriptorReport
from roc.punk.tasks.sbm_report import SBMReport
from roc.punk.tasks.sbm_query import SBMQuery
__all__ = []
def valid_data_path_type(arg):
""" Type function for argparse - an accessible path not empty """
# check is accessible
ret = os.access(arg, os.R_OK)
if not ret:
raise argparse.ArgumentTypeError(
'Argument must be a valid and readable data path')
# check if not empty
listdir = os.listdir(arg)
if len(listdir) == 0:
raise argparse.ArgumentTypeError(
'Argument data path must contain data. Directory is empty.')
return arg
class PunkCommand(Command):
"""
Command to manage the commands for the calibration softwares.
"""
__command__ = 'punk'
__command_name__ = 'punk'
__parent__ = 'master'
__help__ = """Command relative to the PUNK module, responsible for making
reports about the ROC pipeline and database."""
class PunkSoftwaresReport(Command):
"""
A command to run a calibration mode for a given software.
"""
__command__ = 'punk_sw_report'
__command_name__ = 'softwares'
__parent__ = 'punk'
__parent_arguments__ = ['base']
__help__ = """Command for generating a report in HTML or PDF format about
softwares and datasets in the ROC database"""
def add_arguments(self, parser):
parser.add_argument(
'-o', '--output',
help="""
The output directory
""",
default='/tmp/',
type=valid_data_path_type,
)
def setup_tasks(self, pipeline):
# Set start task
start = DescriptorReport()
end = DescriptorReport()
# Build workflow of tasks
pipeline | start
# define the start/end task of the pipeline
pipeline.start = start
pipeline.end = end
class PunkSBMReport(Command):
"""
A command to run a calibration mode for a given software.
"""
__command__ = 'punk_sbm_report'
__command_name__ = 'sbm'
__parent__ = 'punk'
__parent_arguments__ = ['base']
__help__ = """Command for generating a weekly report
with SBM1 detection of the week"""
def add_arguments(self, parser):
parser.add_argument(
'--token',
help="""
The Gitlab access token
""",
type=str,
required=True
)
parser.add_argument(
'-t', '--type',
help="""
The SBM type
Possible values: 1, 2
""",
type=int,
default=1,
choices=[1, 2],
)
parser.add_argument(
'-d', '--days',
help="""
The nb of days to take into account
""",
type=int,
default=8,
)
def setup_tasks(self, pipeline):
# Set start task
query = SBMQuery()
report = SBMReport()
# Build workflow of tasks
pipeline | query | report
# define the start/end task of the pipeline
pipeline.start = query
pipeline.end = report
# vim: set tw=79 : | /roc-punk-0.2.7.tar.gz/roc-punk-0.2.7/roc/punk/commands.py | 0.650134 | 0.231484 | commands.py | pypi |
import os.path as osp
import datetime
from jinja2 import PackageLoader
from jinja2 import Environment
from weasyprint import HTML
from poppy.core.db.connector import Connector
from poppy.core.task import Task
from poppy.core.plugin import Plugin
from roc.punk.constants import PIPELINE_DATABASE
__all__ = ['DescriptorReport']
class DescriptorReport(Task):
"""
Class for managing reports from the ROC database.
"""
plugin_name = 'roc.punk'
name = 'descriptor_report'
def setup_inputs(self):
"""
Init sessions, etc.
"""
# Get the output directory
self.output = self.pipeline.get('output', args=True)
"""
Init the Jinja2 environment for loading templates with inheritance.
"""
# get the environment
self.environment = Environment(
loader=PackageLoader('roc.punk', 'templates')
)
def get_softwares(self):
"""
Get the list of softwares in the database for the specified version of
the pipeline.
"""
# get the pipeline
# pipeline = self.roc.get_pipeline()
# query for softwares
query = self.session.query(Plugin)
# query = query.filter_by(pipeline=pipeline)
return query.all()
def run(self):
"""
Make a report about softwares and their datasets.
"""
# Get roc connector
if not hasattr(self, 'roc'):
self.roc = Connector.manager[PIPELINE_DATABASE]
# Get the database connection if needed
if not hasattr(self, 'session'):
self.session = self.roc.session
# Initialize inputs
self.setup_inputs()
# get softwares inside the ROC database for the specified version of
# the pipeline
softwares = self.get_softwares()
# create a list of datasets from the softwares
datasets = set()
for software in softwares:
for dataset in software.datasets:
datasets.add(dataset)
# get the template for the report about softwares
template = self.environment.get_template('software_report.html')
# render the template
html = template.render(softwares=softwares, datasets=datasets)
# get current datetime
now = datetime.datetime.now()
# the filename prefix
filename = osp.join(
self.output,
'_'.join(
[
self.roc.get_pipeline().release.release_version,
now.strftime('%Y-%m-%d-%H-%M-%S')
]
)
)
# store into a file
with open('.'.join([filename, 'html']), 'w') as f:
f.write(html)
# write the PDF
HTML(string=html).write_pdf('.'.join([filename, 'pdf']))
# vim: set tw=79 : | /roc-punk-0.2.7.tar.gz/roc-punk-0.2.7/roc/punk/tasks/descriptor_report.py | 0.610337 | 0.179638 | descriptor_report.py | pypi |
import numpy as np
from poppy.core.logger import logger
from roc.rpl.time import Time
from roc.idb.converters.cdf_fill import fill_records
# Numpy array dtype for BIAS sweep data
# Name convention is lower case
from roc.rap.tasks.utils import sort_data
SWEEP_DTYPE = [
('epoch', 'uint64'),
('scet', 'float64'),
('acquisition_time', 'uint32', 2),
('synchro_flag', 'uint8'),
('quality_flag', 'uint8'),
('quality_bitmask', 'uint8'),
('bias_mode_mux_set', 'uint8'),
('bias_mode_hv_enabled', 'uint8'),
('bias_mode_bias1_enabled', 'uint8'),
('bias_mode_bias2_enabled', 'uint8'),
('bias_mode_bias3_enabled', 'uint8'),
('bias_mode_bypass_probe1', 'uint8'),
('bias_mode_bypass_probe2', 'uint8'),
('bias_mode_bypass_probe3', 'uint8'),
('bias_on_off', 'uint8'),
('ant_flag', 'uint8'),
('bw', 'uint8'),
('sp0', 'uint8'),
('sp1', 'uint8'),
('r0', 'uint8'),
('r1', 'uint8'),
('r2', 'uint8'),
('sampling_rate', 'float32'),
('v', 'float32', 3),
('bias_sweep_current', 'float32', 3),
]
# Factor to convert LFR Bias sweep data voltage into volts, i.e., V_TM ~ V_Volt * 8000 * 1/17
# Provided by Yuri
BIA_SWEEP_TM2V_FACTOR = 1.0 / (8000 * 1.0 / 17.0)
# F3 = 16Hz
CWF_SAMPLING_RATE = 16.0
def set_sweep(l0, task, freq):
# Get/create time instance
time_instance = Time()
# Get the number of packets
size = l0['PA_LFR_ACQUISITION_TIME'].shape[0]
if freq == 'F3':
blk_nr = l0['PA_LFR_CWF3_BLK_NR'][:]
elif freq == 'LONG_F3':
blk_nr = l0['PA_LFR_CWFL3_BLK_NR'][:]
freq = freq[-2:]
else:
logger.warning(f'Unknown frequency label {freq}')
return np.empty(size, dtype=SWEEP_DTYPE)
# Sort input packets by ascending acquisition times
l0, __ = sort_data(l0, (
l0['PA_LFR_ACQUISITION_TIME'][:, 1],
l0['PA_LFR_ACQUISITION_TIME'][:, 0],
))
# Total number of samples
nsamps = np.sum(blk_nr)
# Sampling rate
samp_rate = CWF_SAMPLING_RATE
# Cadence in nanosec
delta_t = 1.0e9 / samp_rate
# create a record array with the good dtype and good length
data = np.empty(nsamps, dtype=SWEEP_DTYPE)
fill_records(data)
# Loop over packets
i = 0
for packet in range(size):
# Get the number of samples for the current packet
nsamp = blk_nr[packet]
# get the acquisition time and time synch. flag
data['acquisition_time'][i:i + nsamp, :] = \
l0['PA_LFR_ACQUISITION_TIME'][packet, :2]
data['synchro_flag'][i:i + nsamp] = \
l0['PA_LFR_ACQUISITION_TIME'][packet, 2]
# Compute corresponding Epoch time
epoch0 = time_instance.obt_to_utc(
l0['PA_LFR_ACQUISITION_TIME'][packet, :2].reshape([1, 2]),
to_tt2000=True)
data['epoch'][i:i + nsamp] = epoch0 + np.uint64(delta_t * np.arange(0, nsamp, 1))
data['scet'][i:i + nsamp] = Time.cuc_to_scet(data['acquisition_time'][i:i + nsamp, :])
data['bias_mode_mux_set'][i:i + nsamp] = \
l0['PA_BIA_MODE_MUX_SET'][packet]
data['bias_mode_hv_enabled'][i:i + nsamp] = \
l0['PA_BIA_MODE_HV_ENABLED'][packet]
data['bias_mode_bias1_enabled'][i:i + nsamp] = \
l0['PA_BIA_MODE_BIAS1_ENABLED'][packet]
data['bias_mode_bias2_enabled'][i:i + nsamp] = \
l0['PA_BIA_MODE_BIAS2_ENABLED'][packet]
data['bias_mode_bias3_enabled'][i:i + nsamp] = \
l0['PA_BIA_MODE_BIAS3_ENABLED'][packet]
data['bias_on_off'][i:i + nsamp] = l0['PA_BIA_ON_OFF'][packet]
data['bw'][i:i + nsamp] = l0['SY_LFR_BW'][packet]
data['sp0'][i:i + nsamp] = l0['SY_LFR_SP0'][packet]
data['sp1'][i:i + nsamp] = l0['SY_LFR_SP1'][packet]
data['r0'][i:i + nsamp] = l0['SY_LFR_R0'][packet]
data['r1'][i:i + nsamp] = l0['SY_LFR_R1'][packet]
data['r2'][i:i + nsamp] = l0['SY_LFR_R2'][packet]
# Fill sampling rate
data['sampling_rate'][i:i + nsamp] = CWF_SAMPLING_RATE
# Electrical potential on each antenna 1, 2 and 3 (just need to be reshaped)
data['v'][i:i + nsamp, 0] = raw_to_volts(l0['PA_LFR_SC_V_' + freq][packet, :])
data['v'][i:i + nsamp, 1] = raw_to_volts(l0['PA_LFR_SC_E1_' + freq][packet, :])
data['v'][i:i + nsamp, 2] = raw_to_volts(l0['PA_LFR_SC_E2_' + freq][packet, :])
i += nsamp
return data
def raw_to_volts(raw_value):
"""
Convert LFR V raw value to Volts units.
Comment from Bias team:
'for DC single(which we have for mux=4, BIAS_1-3), and BIAS+LFR,
the conversion should be _approximately_ V_TM = V_Volt * 8000 * 1/17'
:param raw_value: LFR F3 V value in count. Can be a scalar or a numpy array
:return: value in Volts
"""
return raw_value * BIA_SWEEP_TM2V_FACTOR | /roc_rap-1.4.5.tar.gz/roc_rap-1.4.5/roc/rap/tasks/bia/sweep.py | 0.561696 | 0.274424 | sweep.py | pypi |
from datetime import timedelta
from copy import deepcopy
import numpy as np
import pandas as pd
from sqlalchemy import asc, and_
from sqlalchemy.orm.exc import NoResultFound
from poppy.core.db.connector import Connector
from poppy.core.logger import logger
from roc.rpl.time import Time
from roc.dingo.models.data import HfrTimeLog
from roc.dingo.tools import actual_sql
from roc.rap.constants import PIPELINE_DATABASE, UINT32_MAX_ENCODING
__all__ = ['get_hfr_time_log', 'get_hfr_delta_times',
'merge_coarse_fine']
@Connector.if_connected(PIPELINE_DATABASE)
def get_hfr_time_log(mode, start_time, end_time,
model=HfrTimeLog):
"""
Query pipeline.hfr_time_log table in database
:param mode: Mode of HFR receiver (0=NORMAL, 1=BURST)
:param start_time: minimal acquisition time to query (datetime object)
:param end_time: maximal acquisition time to query (datetime object)
:param model: database table class
:return:
"""
# get a database session
session = Connector.manager[PIPELINE_DATABASE].session
# Set filters
logger.debug(f'Connecting {PIPELINE_DATABASE} database to retrieve entries from pipeline.hfr_time_log table ...')
filters = []
filters.append(model.mode == mode) # Get data for current mode
filters.append(model.acq_time >= str(start_time))
filters.append(model.acq_time <= str(end_time))
# Join query conditions with AND
filters = and_(*filters)
# Query database (returns results as a pandas.DataFrame object)
try:
query = session.query(model).filter(
filters).order_by(asc(HfrTimeLog.acq_time))
results = pd.read_sql(query.statement, session.bind)
except NoResultFound:
logger.exception(f'No result for {actual_sql(query)}')
results = pd.DataFrame()
return results
def get_hfr_delta_times(mode, acq_time_min,
duration=48):
"""
Retrieve delta_times values in the pipeline.hfr_time_log table
:param mode: HFR receiver mode (0=NORMAL, 1=BURST)
:param acq_time_min: Minimal acquisition time to query (tuple with coarse and fine parts)
:param duration: Time range to query will be [acq_start_time, acq_start_time + duration] with duration in hours. default is 24.
:return: pandas.DataFrame with database query results
"""
delta_times = [[], []]
# Convert input acquisition time (coarse, fine) into
# datetime object
start_time = Time.cuc_to_datetime(acq_time_min)[0] - timedelta(minutes=1)
end_time = start_time + timedelta(hours=duration)
# Query database
try:
results = get_hfr_time_log(mode, start_time, end_time)
except Exception as e:
logger.exception('Cannot query pipeline.hfr_time_log table')
raise e
if results.shape[0] > 0:
# If no empty dataframe, then make sure to have valid
# delta times values
results['delta_time1'] = results['delta_time1'].apply(valid_delta_time)
results['delta_time2'] = results['delta_time2'].apply(valid_delta_time)
# Add a variable containing merged coarse/fine parts of
# acquisition time
results['coarse_fine'] = results.apply(
lambda row: merge_coarse_fine(
row['coarse_time'], row['fine_time']),
axis=1)
return results
def valid_delta_time(delta_times):
"""
Check if delta times values are valid for the input hfr_time_log row
(i.e., first delta_time1 values for each record should be 0
# and delta_times values should increase monotonically)
:param delta_times1: hfr_time_log.delta_time 1 or 2 values to check
:return: row with updates (if needed)
"""
# Initialize output
new_delta_times = deepcopy(delta_times)
# Initialize byte offset
offset = np.uint64(0)
# Initialize previous value to compare
prev_val = 0
# Loop over packets
for key, val in delta_times.items():
# Loop over delta time values for current packet
for j in range(0, len(val)):
# Define index of value to compare
if j > 0:
prev_val = val[j - 1]
# If previous delta time value is upper or equal than current value
# then the increase is not monotone,
# which indicates the max encoding value is reached
if val[j] + offset < prev_val + offset:
# In this case, increase offset
offset += np.uint64(UINT32_MAX_ENCODING)
logger.warning(f'Maximal encoding value reached for 32-bits delta time (offset={offset})')
# Save delta time value with correct offset
new_delta_times[key][j] = np.uint64(val[j]) + offset
prev_val = val[j]
return new_delta_times
def merge_coarse_fine(coarse, fine):
"""
return input coarse and fine parts of CCSDS CUC time
as an unique integer
:param coarse: coarse part of CUC time
:param fine: fine part of CUC time
:return: resulting unique integer
"""
return int(coarse * 100000 + fine)
def found_delta_time(group, delta_times, packet_times, i, message):
"""
Get HF1 / HF2 delta times values for current HFR science packet
:param group: h5.group containing HFR science packet source_data
:param delta_times: pandas.DataFrame storing hfr_time_log table data
:param packet_times: list of packet (creation) times (coarse, fine, sync)
:param i: index of the current HFR science packet in the L0 file
:param message: string containing HFR receiver mode ('normal' or 'burst')
:return: delta_time1 and delta_time2 values found in delta_times for current packet
"""
# Get row index where condition is fulfilled
where_packet = (merge_coarse_fine(group['PA_THR_ACQUISITION_TIME'][i][0], group['PA_THR_ACQUISITION_TIME'][i][1]) ==
delta_times['coarse_fine'])
# Must be only one row
if delta_times[where_packet].shape[0] > 1:
raise ValueError(f'Wrong number of hfr_time_log entries found for HFR {message} packet at {packet_times[i][:2]}: '
f'1 expected but {delta_times[where_packet].shape[0]} found! '
f'(acq. time is {group["PA_THR_ACQUISITION_TIME"][i][:2]})')
# Must be at least one row
elif delta_times[where_packet].shape[0] == 0:
raise ValueError(f'No hfr_time_log entry found for HFR {message} packet #{i} at {packet_times[i][:2]} '
f'(acq. time is {group["PA_THR_ACQUISITION_TIME"][i][:2]})')
else:
# Else extract delta_time1 and delta_time2 values found
delta_time1 = delta_times['delta_time1'][where_packet].reset_index(drop=True)[0][
str(merge_coarse_fine(packet_times[i][0], packet_times[i][1]))]
delta_time2 = delta_times['delta_time2'][where_packet].reset_index(drop=True)[0][
str(merge_coarse_fine(packet_times[i][0], packet_times[i][1]))]
return delta_time1, delta_time2 | /roc_rap-1.4.5.tar.gz/roc_rap-1.4.5/roc/rap/tasks/thr/hfr_time_log.py | 0.739422 | 0.346845 | hfr_time_log.py | pypi |
import pandas as pd
from poppy.core.generic.metaclasses import Singleton
from poppy.core.db.connector import Connector
from poppy.core.logger import logger
from roc.rap.constants import PIPELINE_DATABASE, TC_HFR_LIST_PAR
__all__ = ['HfrListMode']
class HfrListMode(object, metaclass=Singleton):
def __init__(self):
self._hfr_list_data = None
@property
def hfr_list_data(self):
if self._hfr_list_data is None:
self._hfr_list_data = self.load_hfr_list_data()
return self._hfr_list_data
@hfr_list_data.setter
def hfr_list_data(self, value):
self._hfr_list_data = value
@Connector.if_connected(PIPELINE_DATABASE)
def load_hfr_list_data(self):
"""
Query ROC database to get the data from hfr_freq_list table.
:return: query result
"""
from sqlalchemy import asc, or_
from roc.dingo.models.packet import TcLog
# get a database session
session = Connector.manager[PIPELINE_DATABASE].session
# Set filters
logger.debug(f'Connecting {PIPELINE_DATABASE} database to retrieve entries from pipeline.tc_log table ...')
filters = [TcLog.palisade_id == current_tc
for current_tc in TC_HFR_LIST_PAR]
filters = or_(*filters)
# Query database (returns results as a pandas.DataFrame object)
results = pd.read_sql(session.query(TcLog).filter(
filters).order_by(asc(TcLog.utc_time)).statement, session.bind)
return results
def get_freq(self, utc_time, band, mode, get_index=False):
"""
Get the list of frequencies (kHz) in HFR LIST mode for a given band (HF1 or HF2)
:param utc_time: datetime object containing the UTC time for which the frequency list must be returned
:param band: string giving the name of the HFR band (HF1 or HFR2)
:param mode: string giving the mode (0=NORMAL, 1=BURST)
:param get_index: If True return the index of the frequencies instead of value
:return:
"""
# Get lists of frequencies in HFR LIST mode stored in database
hfr_list_data = self.hfr_list_data
# Expected TC name
band_index = int(band[-1])
if mode == 1:
tc_name = f'TC_THR_LOAD_BURST_PAR_{band_index + 1}'
param_name = f'SY_THR_B_SET_HLS_FREQ_HF{band_index}'
else:
tc_name = f'TC_THR_LOAD_NORMAL_PAR_{band_index + 1}'
param_name = f'SY_THR_N_SET_HLS_FREQ_HF{band_index}'
# Get list of frequencies from the last TC executed on board
try:
latest_hfr_list_data = hfr_list_data[(
hfr_list_data.palisade_id == tc_name) & (hfr_list_data.utc_time <= utc_time)].iloc[-1]
except:
logger.warning(f'No valid frequency list found for {tc_name} at {utc_time}!')
frequency_list = []
else:
# Get indices of frequencies for current utc_time, mode and band
frequency_list = latest_hfr_list_data.data[param_name].copy()
logger.debug(f'Frequency values found for {tc_name} on {latest_hfr_list_data.utc_time}: {frequency_list}')
if not get_index:
# Compute frequency values in kHz
frequency_list = [compute_hfr_list_freq(current_freq)
for current_freq in frequency_list]
return frequency_list
def compute_hfr_list_freq(freq_index):
"""
In HFR LIST mode, return frequency value in kHz giving its
index
:param freq_index: index of the frequency
:return: Value of the frequency in kHz
"""
return 375 + 50 * (int(freq_index) - 436) | /roc_rap-1.4.5.tar.gz/roc_rap-1.4.5/roc/rap/tasks/thr/hfr_list.py | 0.846673 | 0.201322 | hfr_list.py | pypi |
import numpy as np
import datetime as dt
from roc.rap.tasks.thr.hfr_time_log import get_hfr_delta_times
from roc.rap.tasks.thr.normal_burst_tnr import decommute_normal as tnr_normal_decom
from roc.rap.tasks.thr.normal_burst_tnr import decommute_burst as tnr_burst_decom
from roc.rap.tasks.thr.normal_burst_hfr import decommute_normal as hfr_normal_decom
from roc.rap.tasks.thr.normal_burst_hfr import decommute_burst as hfr_burst_decom
from roc.rap.tasks.thr.calibration_tnr import decommute as tnr_calibration_decom
from roc.rap.tasks.thr.calibration_hfr import decommute as hfr_calibration_decom
from roc.rap.tasks.thr.science_spectral_power import decommute as spectral_power_decom
__all__ = [
'extract_tnr_data',
'extract_hfr_data',
'extract_spectral_power_data',
]
# nanoseconds since POSIX epoch to J2000
POSIX_TO_J2000 = 946728000000000000
@np.vectorize
def convert_ns_to_datetime(value):
return dt.datetime.utcfromtimestamp((value + POSIX_TO_J2000) / 1000000000)
def extract_tnr_data(l0, task):
"""
Get the TNR data in a record array that can be easily exported into
the CDF format.
:param l0: h5py.h5 object containing RPW L0 packet data
:param task: POPPy Task instance
:return: TNR data array
"""
# Extract source_data from the L0 file
modes = tnr_decommutation(l0, task)
# filter from None
modes = [x for x in modes if x is not None]
# check not empty
if len(modes) == 0:
return None
return np.concatenate(modes)
def extract_hfr_data(l0, task):
"""
Get the HFR data in a record array that can be easily exported into
the CDF format.
:param l0: h5py.h5 object containing RPW L0 packet data
:param task: POPPy Task instance
:return: HFR data array
"""
# Extract source_data from the L0 file
modes = hfr_decommutation(l0, task)
# filter from None
modes = [x for x in modes if x is not None]
# check not empty
if len(modes) == 0:
return None
return np.concatenate(modes)
def tnr_decommutation(l0, task):
"""
Extract source_data from TNR SCIENCE TM packets.
:param l0: h5py.h5 object containing RPW L0 packet data
:param task: POPPy task
:return: tuple of normal, burst and calibration TNR data
"""
normal = None
burst = None
calibration = None
# normal mode
if 'TM_THR_SCIENCE_NORMAL_TNR' in l0['TM']:
normal = tnr_normal_decom(
l0['TM']['TM_THR_SCIENCE_NORMAL_TNR']['source_data'],
task,
)
# burst mode
if 'TM_THR_SCIENCE_BURST_TNR' in l0['TM']:
burst = tnr_burst_decom(
l0['TM']['TM_THR_SCIENCE_BURST_TNR']['source_data'],
task,
)
# calibration mode
if 'TM_THR_SCIENCE_CALIBRATION_TNR' in l0['TM']:
calibration = tnr_calibration_decom(
l0['TM']['TM_THR_SCIENCE_CALIBRATION_TNR']['source_data'],
task,
)
return normal, burst, calibration
def hfr_decommutation(f, task):
"""
Extract source_data from HFR SCIENCE TM packets.
"""
normal = None
burst = None
calibration = None
# normal mode
packet_name = 'TM_THR_SCIENCE_NORMAL_HFR'
if packet_name in f['TM']:
# First get actual delta times values from pipeline.hfr_time_log table
acq_time_min = f['TM'][packet_name]['source_data']['PA_THR_ACQUISITION_TIME'][0][:2]
mode = 0
delta_times = get_hfr_delta_times(mode, acq_time_min)
# Then get measurements in packets
normal = hfr_normal_decom(
f['TM'][packet_name]['source_data'],
task,
f['TM'][packet_name]['data_field_header']['time'],
delta_times,
mode,
)
# burst mode
packet_name = 'TM_THR_SCIENCE_BURST_HFR'
if packet_name in f['TM']:
# First get actual delta times values from pipeline.hfr_time_log table
acq_time_min = f['TM'][packet_name]['source_data']['PA_THR_ACQUISITION_TIME'][0][:2]
mode = 1
delta_times = get_hfr_delta_times(mode, acq_time_min)
# Then get measurements in packets
burst = hfr_burst_decom(
f['TM'][packet_name]['source_data'],
task,
f['TM'][packet_name]['data_field_header']['time'],
delta_times,
mode,
)
# calibration mode
packet_name = 'TM_THR_SCIENCE_CALIBRATION_HFR'
if packet_name in f['TM']:
calibration = hfr_calibration_decom(
f['TM'][packet_name]['source_data'],
task,
)
return normal, burst, calibration
def extract_spectral_power_data(f, task):
"""
Extract source_data from TM_THR_SCIENCE_SPECTRAL_POWER TM packets.
"""
if 'TM_THR_SCIENCE_SPECTRAL_POWER' in f['TM']:
return spectral_power_decom(
f['TM']['TM_THR_SCIENCE_SPECTRAL_POWER']['source_data'],
task,
)
return None | /roc_rap-1.4.5.tar.gz/roc_rap-1.4.5/roc/rap/tasks/thr/thr.py | 0.77535 | 0.5119 | thr.py | pypi |
from collections import namedtuple
import numpy as np
from poppy.core.logger import logger
from roc.rpl.time import Time
from roc.idb.converters.cdf_fill import fill_records
from roc.rap.tasks.utils import sort_data
from roc.rap.tasks.lfr.utils import set_cwf
from roc.rap.tasks.lfr.bp import convert_BP as bp_lib
__all__ = ['bp1', 'bp2', 'cwf']
class L1LFRSBM2Error(Exception):
"""
Errors for L1 SBM2 LFR.
"""
# Numpy array dtype for LFR BP1 L1 SBM2 data
# Name convention is lower case
BP1 = [
('epoch', 'uint64'),
('scet', 'float64'),
('acquisition_time', 'uint32', 2),
('synchro_flag', 'uint8'),
('quality_flag', 'uint8'),
('quality_bitmask', 'uint8'),
('bias_mode_mux_set', 'uint8'),
('bias_mode_hv_enabled', 'uint8'),
('bias_mode_bias1_enabled', 'uint8'),
('bias_mode_bias2_enabled', 'uint8'),
('bias_mode_bias3_enabled', 'uint8'),
('bias_on_off', 'uint8'),
('bw', 'uint8'),
('sp0', 'uint8'),
('sp1', 'uint8'),
('r0', 'uint8'),
('r1', 'uint8'),
('r2', 'uint8'),
('pe', 'float64', 26),
('pb', 'float64', 26),
('nvec_v0', 'float32', 26),
('nvec_v1', 'float32', 26),
('nvec_v2', 'uint8', 26),
('ellip', 'float32', 26),
('dop', 'float32', 26),
('sx_rea', 'float64', 26),
('sx_arg', 'uint8', 26),
('vphi_rea', 'float64', 26),
('vphi_arg', 'uint8', 26),
('freq', 'uint8'),
]
def set_bp1(fdata, freq):
# Sort input packets by ascending acquisition times
fdata, __ = sort_data(fdata, (
fdata['PA_LFR_ACQUISITION_TIME'][:, 1],
fdata['PA_LFR_ACQUISITION_TIME'][:, 0],
))
# create a record array with the good dtype and good length
result = np.empty(
fdata['PA_LFR_ACQUISITION_TIME'].shape[0],
dtype=BP1,
)
fill_records(result)
# get the shape of the data
shape = fdata['PA_LFR_SC_BP1_PE_' + freq].shape
# Get number of packets and blocks
n = shape[1]
# get the acquisition time and other data
result['acquisition_time'] = fdata['PA_LFR_ACQUISITION_TIME'][:, :2]
result['synchro_flag'] = fdata['PA_LFR_ACQUISITION_TIME'][:, 2]
result['bias_mode_mux_set'] = fdata['PA_BIA_MODE_MUX_SET']
result['bias_mode_hv_enabled'] = fdata['PA_BIA_MODE_HV_ENABLED']
result['bias_mode_bias1_enabled'] = fdata[
'PA_BIA_MODE_BIAS1_ENABLED'
]
result['bias_mode_bias2_enabled'] = fdata[
'PA_BIA_MODE_BIAS2_ENABLED'
]
result['bias_mode_bias3_enabled'] = fdata[
'PA_BIA_MODE_BIAS3_ENABLED'
]
result['bias_on_off'] = fdata['PA_BIA_ON_OFF']
result['bw'] = fdata['SY_LFR_BW']
result['sp0'] = fdata['SY_LFR_SP0']
result['sp1'] = fdata['SY_LFR_SP1']
result['r0'] = fdata['SY_LFR_R0']
result['r1'] = fdata['SY_LFR_R1']
result['r2'] = fdata['SY_LFR_R2']
# Convert BP1 values (see convert_BP.py)
struct = namedtuple('struct', ['nbitexp', 'nbitsig', 'rangesig_16',
'rangesig_14', 'expmax', 'expmin'])
bp_lib.init_struct(struct)
result['pe'][:, :n] = bp_lib.convToFloat16(struct,
fdata['PA_LFR_SC_BP1_PE_' + freq][:, :n])
result['pb'][:, :n] = bp_lib.convToFloat16(struct,
fdata['PA_LFR_SC_BP1_PB_' + freq][:, :n])
# Compute n1 component of k-vector (normalized)
result['nvec_v0'][:, :n] = bp_lib.convToFloat8(
fdata['PA_LFR_SC_BP1_NVEC_V0_' + freq][:, :n])
# Compute n2 component of k-vector (normalized)
result['nvec_v1'][:, :n] = bp_lib.convToFloat8(
fdata['PA_LFR_SC_BP1_NVEC_V1_' + freq][:, :n])
# Store the 1b bit of the sign of n3 components k-vector in nvec_v2
result['nvec_v2'][:, :n] = bp_lib.convToUint8(
fdata['PA_LFR_SC_BP1_NVEC_' + freq][:, :n])
result['ellip'][:, :n] = bp_lib.convToFloat4(
fdata['PA_LFR_SC_BP1_ELLIP_' + freq][:, :n])
result['dop'][:, :n] = bp_lib.convToFloat3(
fdata['PA_LFR_SC_BP1_DOP_' + freq][:, :n])
# Extract x-component of normalized Poynting flux...
# sign (1 bit)...
sx_sign = 1 - \
(2 * bp_lib.Uint16ToUint8(fdata['PA_LFR_SC_BP1_SX_' +
freq][:, :n], 15, 0x1).astype(float))
# real value (14 bits)
result['sx_rea'][:, :n] = sx_sign * bp_lib.convToFloat14(struct,
fdata['PA_LFR_SC_BP1_SX_' + freq][:, :n])
# and arg (1 bit)
result['sx_arg'][:, :n] = bp_lib.Uint16ToUint8(
fdata['PA_LFR_SC_BP1_SX_' + freq][:, :n], 14, 0x1)
# Extract velocity phase...
# sign (1 bit)...
vphi_sign = 1 - (2 * bp_lib.Uint16ToUint8(
fdata['PA_LFR_SC_BP1_VPHI_' + freq][:, :n], 15, 0x1).astype(float))
# real value (14 bits)
result['vphi_rea'][:, :n] = vphi_sign * bp_lib.convToFloat14(struct,
fdata['PA_LFR_SC_BP1_VPHI_' + freq][:, :n])
# and arg (1 bit)
result['vphi_arg'][:, :n] = bp_lib.Uint16ToUint8(
fdata['PA_LFR_SC_BP1_VPHI_' + freq][:, :n], 14, 0x1)
# Get TT2000 Epoch time
result['epoch'] = Time().obt_to_utc(
result['acquisition_time'], to_tt2000=True)
# Get scet
result['scet'] = Time.cuc_to_scet(result['acquisition_time'])
return result
def bp1(f, task):
def get_data(freq):
# get name of the packet
name = 'TM_LFR_SCIENCE_SBM2_BP1_F' + freq
logger.debug('Get data for ' + name)
# get the sbm2 bp1 data
if name in f['TM']:
# get data from the file
fdata = f['TM'][name]['source_data']
# get data
data = set_bp1(fdata, 'F' + freq)
data['freq'][:] = int(freq)
else:
data = np.empty(0, dtype=BP1)
return data
# get the data of all packets
data = [get_data(x) for x in '01']
# concatenate both arrays
return np.concatenate(tuple(data))
# Numpy array dtype for LFR BP2 L1 SBM2 data
# Name convention is lower case
BP2 = [
('epoch', 'uint64'),
('scet', 'float64'),
('acquisition_time', 'uint32', 2),
('synchro_flag', 'uint8'),
('quality_flag', 'uint8'),
('quality_bitmask', 'uint8'),
('bias_mode_mux_set', 'uint8'),
('bias_mode_hv_enabled', 'uint8'),
('bias_mode_bias1_enabled', 'uint8'),
('bias_mode_bias2_enabled', 'uint8'),
('bias_mode_bias3_enabled', 'uint8'),
('bias_on_off', 'uint8'),
('bw', 'uint8'),
('sp0', 'uint8'),
('sp1', 'uint8'),
('r0', 'uint8'),
('r1', 'uint8'),
('r2', 'uint8'),
('auto', 'float64', (26, 5)),
('cross_re', 'float32', (26, 10)),
('cross_im', 'float32', (26, 10)),
('freq', 'uint8'),
]
def set_bp2(fdata, freq):
# Sort input packets by ascending acquisition times
fdata, __ = sort_data(fdata, (
fdata['PA_LFR_ACQUISITION_TIME'][:, 1],
fdata['PA_LFR_ACQUISITION_TIME'][:, 0],
))
# create a record array with the good dtype and good length
result = np.empty(
fdata['PA_LFR_ACQUISITION_TIME'].shape[0],
dtype=BP2,
)
fill_records(result)
# get shape of data
shape = fdata['PA_LFR_SC_BP2_AUTO_A0_' + freq].shape
# get the acquisition time and other data
result['acquisition_time'] = fdata['PA_LFR_ACQUISITION_TIME'][:, :2]
result['synchro_flag'] = fdata['PA_LFR_ACQUISITION_TIME'][:, 2]
result['bias_mode_mux_set'] = fdata['PA_BIA_MODE_MUX_SET']
result['bias_mode_hv_enabled'] = fdata['PA_BIA_MODE_HV_ENABLED']
result['bias_mode_bias1_enabled'] = fdata[
'PA_BIA_MODE_BIAS1_ENABLED'
]
result['bias_mode_bias2_enabled'] = fdata[
'PA_BIA_MODE_BIAS2_ENABLED'
]
result['bias_mode_bias3_enabled'] = fdata[
'PA_BIA_MODE_BIAS3_ENABLED'
]
result['bias_on_off'] = fdata['PA_BIA_ON_OFF']
result['bw'] = fdata['SY_LFR_BW']
result['sp0'] = fdata['SY_LFR_SP0']
result['sp1'] = fdata['SY_LFR_SP1']
result['r0'] = fdata['SY_LFR_R0']
result['r1'] = fdata['SY_LFR_R1']
result['r2'] = fdata['SY_LFR_R2']
auto = np.dstack(
list(
fdata['PA_LFR_SC_BP2_AUTO_A{0}_{1}'.format(x, freq)]
for x in range(5)
)
)
cross_re = np.dstack(
list(
fdata['PA_LFR_SC_BP2_CROSS_RE_{0}_{1}'.format(x, freq)]
for x in range(10)
)
)
cross_im = np.dstack(
list(
fdata['PA_LFR_SC_BP2_CROSS_IM_{0}_{1}'.format(x, freq)]
for x in range(10)
)
)
# Get number of blocks
n = shape[1]
# Convert AUTO, CROSS_RE an CROSS_IM (see convert_BP.py)
struct = namedtuple('struct', ['nbitexp', 'nbitsig', 'rangesig_16', 'rangesig_14',
'expmax', 'expmin'])
bp_lib.init_struct(struct)
result['auto'][:, :n, :] = bp_lib.convToAutoFloat(struct, auto)
result['cross_re'][:, :n, :] = bp_lib.convToCrossFloat(cross_re)
result['cross_im'][:, :n, :] = bp_lib.convToCrossFloat(cross_im)
# WARNING, IF NAN or INF, put FILLVAL
# TODO - Optimize this part
result['auto'][np.isinf(result['auto'])] = -1e31
result['auto'][np.isnan(result['auto'])] = -1e31
result['cross_re'][np.isinf(result['cross_re'])] = -1e31
result['cross_re'][np.isnan(result['cross_re'])] = -1e31
result['cross_im'][np.isinf(result['cross_im'])] = -1e31
result['cross_im'][np.isnan(result['cross_im'])] = -1e31
# Get TT2000 Epoch times
result['epoch'] = Time().obt_to_utc(
result['acquisition_time'], to_tt2000=True)
# Get scet
result['scet'] = Time.cuc_to_scet(result['acquisition_time'])
return result
def bp2(f, task):
def get_data(freq):
# get name of the packet
name = 'TM_LFR_SCIENCE_SBM2_BP2_F' + freq
logger.debug('Get data for ' + name)
# get the sbm2 bp1 data
if name in f['TM']:
# get data from the file
fdata = f['TM'][name]['source_data']
# get the data
data = set_bp2(fdata, 'F' + freq)
data['freq'][:] = int(freq)
else:
data = np.empty(0, dtype=BP2)
return data
# get data for all packets
data = [get_data(x) for x in '01']
# concatenate both arrays
return np.concatenate(tuple(data))
# Numpy array dtype for LFR CWF L1 SBM2 data
# Name convention is lower case
CWF = [
('epoch', 'uint64'),
('scet', 'float64'),
('acquisition_time', 'uint32', 2),
('synchro_flag', 'uint8'),
('quality_flag', 'uint8'),
('quality_bitmask', 'uint8'),
('bias_mode_mux_set', 'uint8'),
('bias_mode_hv_enabled', 'uint8'),
('bias_mode_bias1_enabled', 'uint8'),
('bias_mode_bias2_enabled', 'uint8'),
('bias_mode_bias3_enabled', 'uint8'),
('bias_on_off', 'uint8'),
('bw', 'uint8'),
('sp0', 'uint8'),
('sp1', 'uint8'),
('r0', 'uint8'),
('r1', 'uint8'),
('r2', 'uint8'),
('sampling_rate', 'float32'),
('v', 'int16'),
('e', 'int16', 2),
('b', 'int16', 3),
]
def cwf(f, task):
# get name of the packet
name = 'TM_LFR_SCIENCE_SBM2_CWF_F2'
logger.debug('Get data for ' + name)
# get the sbm1 bp1 data
if name in f['TM']:
fdata = f['TM'][name]['source_data']
else:
return np.empty(
0,
dtype=CWF,
)
ddata = {
name: fdata[name][...] for name in fdata.keys()
}
# get the data for cwf
return set_cwf(ddata, 'F2', CWF, True, task) | /roc_rap-1.4.5.tar.gz/roc_rap-1.4.5/roc/rap/tasks/lfr/sbm2.py | 0.665084 | 0.216529 | sbm2.py | pypi |
from collections import namedtuple
import numpy as np
from poppy.core.logger import logger
from roc.rpl.time import Time
from roc.idb.converters.cdf_fill import fill_records
from roc.rap.tasks.utils import sort_data
from roc.rap.tasks.lfr.utils import fill_asm, set_cwf, set_swf
from roc.rap.tasks.lfr.bp import convert_BP as bp_lib
__all__ = ['asm', 'bp1', 'bp2', 'cwf', 'swf']
class L1LFRNormalBurstError(Exception):
"""
Errors for the L1 LFR ASM data
"""
# Numpy array dtype for LFR ASM L1 survey data
# Name convention is lower case
ASM = [
('epoch', 'uint64'),
('scet', 'float64'),
('acquisition_time', 'uint32', 2),
('synchro_flag', 'uint8'),
('quality_flag', 'uint8'),
('survey_mode', 'uint8'),
('quality_bitmask', 'uint8'),
('bias_mode_mux_set', 'uint8'),
('bias_mode_hv_enabled', 'uint8'),
('bias_mode_bias1_enabled', 'uint8'),
('bias_mode_bias2_enabled', 'uint8'),
('bias_mode_bias3_enabled', 'uint8'),
('bias_on_off', 'uint8'),
('bw', 'uint8'),
('sp0', 'uint8'),
('sp1', 'uint8'),
('r0', 'uint8'),
('r1', 'uint8'),
('r2', 'uint8'),
('asm_cnt', 'uint8'),
('asm', 'float32', (128, 25)),
('freq', 'uint8'),
]
def set_asm(fdata, freq):
"""
Fill LFR ASM values
:param fdata:
:param freq:
:return:
"""
# number of blocks in the packets for the current freq
nblk = fdata['PA_LFR_ASM_{0}_BLK_NR'.format(freq)]
asm_blks = np.zeros([nblk.shape[0], np.max(nblk), 25], dtype=np.float32)
asm_blks[:] = -1.0e31
asm_blks[:] = np.dstack(
list(fdata['PA_LFR_SC_ASM_{2}_{0}{1}'.format(i, j, freq)]
for i in range(1, 6) for j in range(1, 6))
).reshape((nblk.shape[0], np.max(nblk), 25)).view('float32')
data = fill_asm(fdata, freq, ASM, asm_blks)
return data
def asm(f, task):
# closure to compute the data
def get_data(freq):
# get the asm
if ('TM_LFR_SCIENCE_NORMAL_ASM_F' + freq) in f['TM']:
logger.info(
'Getting data for TM_LFR_SCIENCE_NORMAL_ASM_F' + freq
)
# get data from the file
fdata = f['TM']['TM_LFR_SCIENCE_NORMAL_ASM_F' + freq]['source_data']
ddata = {
name: fdata[name][...] for name in fdata.keys()
}
# set the data correctly
data = set_asm(ddata, 'F' + freq)
# set specific properties
data['freq'][:] = int(freq)
# set SURVEY_MODE
data['survey_mode'][:] = 0
else:
data = np.empty(0, dtype=ASM)
return data
# get data
data = [get_data(x) for x in '012']
# concatenate both arrays
return np.concatenate(tuple(data))
# Numpy array dtype for LFR BP1 L1 survey data
# Name convention is lower case
BP1 = [
('epoch', 'uint64'),
('scet', 'float64'),
('acquisition_time', 'uint32', 2),
('synchro_flag', 'uint8'),
('quality_flag', 'uint8'),
('quality_bitmask', 'uint8'),
('bias_mode_mux_set', 'uint8'),
('bias_mode_hv_enabled', 'uint8'),
('bias_mode_bias1_enabled', 'uint8'),
('bias_mode_bias2_enabled', 'uint8'),
('bias_mode_bias3_enabled', 'uint8'),
('bias_on_off', 'uint8'),
('bw', 'uint8'),
('sp0', 'uint8'),
('sp1', 'uint8'),
('r0', 'uint8'),
('r1', 'uint8'),
('r2', 'uint8'),
('pe', 'float64', 26),
('pb', 'float64', 26),
('nvec_v0', 'float32', 26),
('nvec_v1', 'float32', 26),
('nvec_v2', 'uint8', 26),
('ellip', 'float32', 26),
('dop', 'float32', 26),
('sx_rea', 'float64', 26),
('sx_arg', 'uint8', 26),
('vphi_rea', 'float64', 26),
('vphi_arg', 'uint8', 26),
('freq', 'uint8'),
('survey_mode', 'uint8'),
]
NB_MAP = {
'NORMAL': 0,
'BURST': 1,
}
BP_LIST = [
('NORMAL', '0'),
('NORMAL', '1'),
('NORMAL', '2'),
('BURST', '0'),
('BURST', '1'),
]
def set_bp1(fdata, freq, task):
"""
Fill LFR BP1 values
:param fdata:
:param freq:
:param task:
:return:
"""
# Sort input packets by ascending acquisition times
fdata, __ = sort_data(fdata, (
fdata['PA_LFR_ACQUISITION_TIME'][:,1],
fdata['PA_LFR_ACQUISITION_TIME'][:,0],
))
# create a record array with the good dtype and good length
result = np.zeros(
fdata['PA_LFR_ACQUISITION_TIME'].shape[0],
dtype=BP1,
)
fill_records(result)
# add common properties
result['acquisition_time'] = fdata['PA_LFR_ACQUISITION_TIME'][:, :2]
result['synchro_flag'] = fdata['PA_LFR_ACQUISITION_TIME'][:, 2]
result['bias_mode_mux_set'] = fdata['PA_BIA_MODE_MUX_SET']
result['bias_mode_hv_enabled'] = fdata['PA_BIA_MODE_HV_ENABLED']
result['bias_mode_bias1_enabled'] = fdata[
'PA_BIA_MODE_BIAS1_ENABLED'
]
result['bias_mode_bias2_enabled'] = fdata[
'PA_BIA_MODE_BIAS2_ENABLED'
]
result['bias_mode_bias3_enabled'] = fdata[
'PA_BIA_MODE_BIAS3_ENABLED'
]
result['bias_on_off'] = fdata['PA_BIA_ON_OFF']
result['bw'] = fdata['SY_LFR_BW']
result['sp0'] = fdata['SY_LFR_SP0']
result['sp1'] = fdata['SY_LFR_SP1']
result['r0'] = fdata['SY_LFR_R0']
result['r1'] = fdata['SY_LFR_R1']
result['r2'] = fdata['SY_LFR_R2']
# get the shape of the data
# (required since number of blocks are not the same in the normal/burst F0/F1/F2 packets)
shape = fdata['PA_LFR_SC_BP1_PE_' + freq].shape
n = shape[1]
# Convert BP1 values (see convert_BP.py)
struct = namedtuple('struct', ['nbitexp', 'nbitsig', 'rangesig_16',\
'rangesig_14', 'expmax', 'expmin'])
bp_lib.init_struct(struct)
result['pe'][:, :n] = bp_lib.convToFloat16(struct,
fdata['PA_LFR_SC_BP1_PE_' + freq][:, :n])
result['pb'][:, :n] = bp_lib.convToFloat16(struct,
fdata['PA_LFR_SC_BP1_PB_' + freq][:, :n])
# Compute n1 component of k-vector (normalized)
result['nvec_v0'][:, :n] = bp_lib.convToFloat8(
fdata['PA_LFR_SC_BP1_NVEC_V0_' + freq][:, :n])
# Compute n2 component of k-vector (normalized)
result['nvec_v1'][:, :n] = bp_lib.convToFloat8(
fdata['PA_LFR_SC_BP1_NVEC_V1_' + freq][:, :n])
# Store the 1b bit of the sign of n3 components k-vector in nvec_v2
result['nvec_v2'][:, :n] = bp_lib.convToUint8(fdata['PA_LFR_SC_BP1_NVEC_' + freq][:, :n])
result['ellip'][:, :n] = bp_lib.convToFloat4(
fdata['PA_LFR_SC_BP1_ELLIP_' + freq][:, :n])
result['dop'][:, :n] = bp_lib.convToFloat3(
fdata['PA_LFR_SC_BP1_DOP_' + freq][:, :n])
# Extract x-component of normalized Poynting flux...
# sign (1 bit)...
sx_sign = 1 - (2 * bp_lib.Uint16ToUint8(fdata['PA_LFR_SC_BP1_SX_' + freq][:, :n], 15, 0x1).astype(float))
# real value (14 bits)
result['sx_rea'][:, :n] = sx_sign * bp_lib.convToFloat14(struct,
fdata['PA_LFR_SC_BP1_SX_' + freq][:, :n])
# and arg (1 bit)
result['sx_arg'][:, :n] = bp_lib.Uint16ToUint8(fdata['PA_LFR_SC_BP1_SX_' + freq][:, :n], 14, 0x1)
# Extract velocity phase...
# sign (1 bit)...
vphi_sign = 1 - (2 * bp_lib.Uint16ToUint8(fdata['PA_LFR_SC_BP1_VPHI_' + freq][:, :n], 15, 0x1).astype(float))
# real value (14 bits)
result['vphi_rea'][:, :n] = vphi_sign * bp_lib.convToFloat14(struct,
fdata['PA_LFR_SC_BP1_VPHI_' + freq][:, :n])
# and arg (1 bit)
result['vphi_arg'][:, :n] = bp_lib.Uint16ToUint8(fdata['PA_LFR_SC_BP1_VPHI_' + freq][:, :n], 14, 0x1)
# Get TT2000 Epoch time
result['epoch'] = Time().obt_to_utc(result['acquisition_time'], to_tt2000=True)
# Get scet
result['scet'] = Time.cuc_to_scet(result['acquisition_time'])
return result
def bp1(f, task):
# define the function to get the data
def get_data(mode, freq):
# get the packet name
name = 'TM_LFR_SCIENCE_{0}_BP1_F{1}'.format(mode, freq)
logger.debug('Get data for ' + name)
# get the sbm2 bp1 data
if name in f['TM']:
# get data from the file
fdata = f['TM'][name]['source_data']
# set common parameters with other frequencies
data = set_bp1(fdata, 'F' + freq, task)
# set some specific properties
data['freq'][:] = int(freq)
data['survey_mode'] = NB_MAP[mode]
else:
data = np.empty(0, dtype=BP1)
return data
# get the data
data = [get_data(mode, freq) for mode, freq in BP_LIST]
# concatenate both arrays
return np.concatenate(data)
# Numpy array dtype for LFR BP2 L1 survey data
# Name convention is lower case
BP2 = [
('epoch', 'uint64'),
('scet', 'float64'),
('acquisition_time', 'uint32', 2),
('synchro_flag', 'uint8'),
('quality_flag', 'uint8'),
('quality_bitmask', 'uint8'),
('bias_mode_mux_set', 'uint8'),
('bias_mode_hv_enabled', 'uint8'),
('bias_mode_bias1_enabled', 'uint8'),
('bias_mode_bias2_enabled', 'uint8'),
('bias_mode_bias3_enabled', 'uint8'),
('bias_on_off', 'uint8'),
('bw', 'uint8'),
('sp0', 'uint8'),
('sp1', 'uint8'),
('r0', 'uint8'),
('r1', 'uint8'),
('r2', 'uint8'),
('auto', 'float64', (26, 5)),
('cross_re', 'float32', (26, 10)),
('cross_im', 'float32', (26, 10)),
('freq', 'uint8'),
('survey_mode', 'uint8'),
]
def set_bp2(fdata, freq, task):
# Sort input packets by ascending acquisition times
fdata, __ = sort_data(fdata, (
fdata['PA_LFR_ACQUISITION_TIME'][:,1],
fdata['PA_LFR_ACQUISITION_TIME'][:,0],
))
# create a record array with the good dtype and good length
data = np.zeros(
fdata['PA_LFR_ACQUISITION_TIME'].shape[0],
dtype=BP2,
)
fill_records(data)
# get the acquisition time and other data common
data['acquisition_time'] = fdata['PA_LFR_ACQUISITION_TIME'][:, :2]
data['synchro_flag'] = fdata['PA_LFR_ACQUISITION_TIME'][:, 2]
data['bias_mode_mux_set'] = fdata['PA_BIA_MODE_MUX_SET']
data['bias_mode_hv_enabled'] = fdata['PA_BIA_MODE_HV_ENABLED']
data['bias_mode_bias1_enabled'] = fdata[
'PA_BIA_MODE_BIAS1_ENABLED'
]
data['bias_mode_bias2_enabled'] = fdata[
'PA_BIA_MODE_BIAS2_ENABLED'
]
data['bias_mode_bias3_enabled'] = fdata[
'PA_BIA_MODE_BIAS3_ENABLED'
]
data['bias_on_off'] = fdata['PA_BIA_ON_OFF']
data['bw'] = fdata['SY_LFR_BW']
data['sp0'] = fdata['SY_LFR_SP0']
data['sp1'] = fdata['SY_LFR_SP1']
data['r0'] = fdata['SY_LFR_R0']
data['r1'] = fdata['SY_LFR_R1']
data['r2'] = fdata['SY_LFR_R2']
# get the shape of the data
shape = fdata['PA_LFR_SC_BP2_AUTO_A0_' + freq].shape
n = shape[1]
# more specific parameters
auto = np.dstack(
list(
fdata['PA_LFR_SC_BP2_AUTO_A{0}_{1}'.format(x, freq)]
for x in range(5)
)
)[:, :, :]
cross_re = np.dstack(
list(
fdata['PA_LFR_SC_BP2_CROSS_RE_{0}_{1}'.format(x, freq)]
for x in range(10)
)
)[:, :, :]
cross_im = np.dstack(
list(
fdata['PA_LFR_SC_BP2_CROSS_IM_{0}_{1}'.format(x, freq)]
for x in range(10)
)
)[:, :, :]
# Convert AUTO, CROSS_RE an CROSS_IM (see convert_BP.py)
struct = namedtuple('struct', ['nbitexp', 'nbitsig', 'rangesig_16', 'rangesig_14', \
'expmax', 'expmin'])
bp_lib.init_struct(struct)
data['auto'][:, :n, :] = bp_lib.convToAutoFloat(struct, auto)
data['cross_re'][:, :n, :] = bp_lib.convToCrossFloat(cross_re)
data['cross_im'][:, :n, :] = bp_lib.convToCrossFloat(cross_im)
# WARNING, IF NAN or INF, put FILLVAL
# TODO - Optimize this part
data['auto'][np.isinf(data['auto'])] = -1e31
data['auto'][np.isnan(data['auto'])] = -1e31
data['cross_re'][np.isinf(data['cross_re'])] = -1e31
data['cross_re'][np.isnan(data['cross_re'])] = -1e31
data['cross_im'][np.isinf(data['cross_im'])] = -1e31
data['cross_im'][np.isnan(data['cross_im'])] = -1e31
# Get TT2000 Epoch time
data['epoch'] = Time().obt_to_utc(data['acquisition_time'], to_tt2000=True)
# Get scet
data['scet'] = Time.cuc_to_scet(data['acquisition_time'])
return data
def bp2(f, task):
# define the function to get the data
def get_data(mode, freq):
# get the packet name
name = 'TM_LFR_SCIENCE_{0}_BP2_F{1}'.format(mode, freq)
logger.info('Get data for ' + name)
# get the sbm2 bp1 data
if name in f['TM']:
# get data from the file
fdata = f['TM'][name]['source_data']
# set common parameters with other frequencies
data = set_bp2(fdata, 'F' + freq, task)
# set some specific properties
data['freq'][:] = int(freq)
data['survey_mode'] = NB_MAP[mode]
else:
data = np.empty(0, dtype=BP2)
return data
# get the data
data = [get_data(mode, freq) for mode, freq in BP_LIST]
# concatenate both arrays
return np.concatenate(data)
# Numpy array dtype for LFR CWF L1 survey data
# Name convention is lower case
CWF = [
('epoch', 'uint64'),
('scet', 'float64'),
('acquisition_time', 'uint32', 2),
('synchro_flag', 'uint8'),
('quality_flag', 'uint8'),
('quality_bitmask', 'uint8'),
('bias_mode_mux_set', 'uint8'),
('bias_mode_hv_enabled', 'uint8'),
('bias_mode_bias1_enabled', 'uint8'),
('bias_mode_bias2_enabled', 'uint8'),
('bias_mode_bias3_enabled', 'uint8'),
('bias_on_off', 'uint8'),
('bw', 'uint8'),
('sp0', 'uint8'),
('sp1', 'uint8'),
('r0', 'uint8'),
('r1', 'uint8'),
('r2', 'uint8'),
('v', 'int16'),
('e', 'int16', 2),
('b', 'int16', 3),
('freq', 'uint8'),
('sampling_rate', 'float32'),
('survey_mode', 'uint8'),
('type', 'uint8'),
]
def cwf(f, task):
"""LFR CWF packet data."""
if 'TM_LFR_SCIENCE_NORMAL_CWF_F3' in f['TM']:
# get data from the file
logger.info('Get data for TM_LFR_SCIENCE_NORMAL_CWF_F3')
fdata = f['TM']['TM_LFR_SCIENCE_NORMAL_CWF_F3']['source_data']
ddata = {
name: fdata[name][...] for name in fdata.keys()
}
# create data with common
data = set_cwf(ddata, 'F3', CWF, False, task)
# specific parameters
data['freq'][:] = 3
data['type'][:] = 0
data['survey_mode'][:] = 0
else:
data = np.empty(0, dtype=CWF)
if 'TM_LFR_SCIENCE_NORMAL_CWF_LONG_F3' in f['TM']:
# get data from the file
logger.info('Get data for TM_LFR_SCIENCE_NORMAL_CWF_LONG_F3')
fdata = f['TM']['TM_LFR_SCIENCE_NORMAL_CWF_LONG_F3']['source_data']
ddata = {
name: fdata[name][...] for name in fdata.keys()
}
# create data with common
data1 = set_cwf(ddata, 'LONG_F3', CWF, True, task)
# specific parameters
data1['freq'][:] = 3
data1['type'][:] = 1
data1['survey_mode'][:] = 0
else:
data1 = np.empty(0, dtype=CWF)
if 'TM_LFR_SCIENCE_BURST_CWF_F2' in f['TM']:
# get data from the file
logger.info('Get data for TM_LFR_SCIENCE_BURST_CWF_F2')
fdata = f['TM']['TM_LFR_SCIENCE_BURST_CWF_F2']['source_data']
ddata = {
name: fdata[name][...] for name in fdata.keys()
}
# create data with common
data2 = set_cwf(ddata, 'F2', CWF, True, task)
# specific parameters
data2['freq'][:] = 2
data2['type'][:] = 0
data2['survey_mode'][:] = 1
else:
data2 = np.empty(0, dtype=CWF)
# concatenate both arrays
return np.concatenate((data, data1, data2))
# Numpy array dtype for LFR SWF L1 survey data
# Name convention is lower case
SWF = [
('epoch', 'uint64'),
('scet', 'float64'),
('acquisition_time', 'uint32', 2),
('synchro_flag', 'uint8'),
('quality_flag', 'uint8'),
('quality_bitmask', 'uint8'),
('bias_mode_mux_set', 'uint8'),
('bias_mode_hv_enabled', 'uint8'),
('bias_mode_bias1_enabled', 'uint8'),
('bias_mode_bias2_enabled', 'uint8'),
('bias_mode_bias3_enabled', 'uint8'),
('bias_on_off', 'uint8'),
('bw', 'uint8'),
('sp0', 'uint8'),
('sp1', 'uint8'),
('r0', 'uint8'),
('r1', 'uint8'),
('r2', 'uint8'),
('v', 'int16', 2048),
('e', 'int16', (2, 2048)),
('b', 'int16', (3, 2048)),
('freq', 'uint8'),
('sampling_rate', 'float32'),
('survey_mode', 'uint8'),
]
def swf(f, task):
# closure for getting the data for several packets
def get_data(freq):
if 'TM_LFR_SCIENCE_NORMAL_SWF_F' + freq in f['TM']:
# get data from the file
logger.info('Get data for TM_LFR_SCIENCE_NORMAL_SWF_F' + freq)
fdata = f['TM']['TM_LFR_SCIENCE_NORMAL_SWF_F' + freq]['source_data']
# copy data from file to numpy
ddata = {
name: fdata[name][...] for name in fdata.keys()
}
# create data with common
data = set_swf(ddata, 'F' + freq, SWF, task)
# specific parameters
data['freq'][:] = int(freq)
data['survey_mode'][:] = 0
else:
data = np.empty(0, dtype=SWF)
return data
# get the data
data = [get_data(x) for x in '012']
x = np.concatenate(tuple(data))
# concatenate both arrays
return np.concatenate(tuple(data)) | /roc_rap-1.4.5.tar.gz/roc_rap-1.4.5/roc/rap/tasks/lfr/normal_burst.py | 0.58818 | 0.218586 | normal_burst.py | pypi |
from collections import namedtuple
import numpy as np
from poppy.core.logger import logger
from roc.rpl.time import Time
from roc.idb.converters.cdf_fill import fill_records
from roc.rap.tasks.utils import sort_data
from roc.rap.tasks.lfr.utils import set_cwf
from roc.rap.tasks.lfr.bp import convert_BP as bp_lib
__all__ = ['bp1', 'bp2', 'cwf']
class L1LFRSBM1Error(Exception):
"""
Errors for L1 SBM1 LFR.
"""
# Numpy array dtype for LFR BP1 L1 SBM1 data
# Name convention is lower case
BP1 = [
('epoch', 'uint64'),
('scet', 'float64'),
('acquisition_time', 'uint32', 2),
('synchro_flag', 'uint8'),
('quality_flag', 'uint8'),
('quality_bitmask', 'uint8'),
('bias_mode_mux_set', 'uint8'),
('bias_mode_hv_enabled', 'uint8'),
('bias_mode_bias1_enabled', 'uint8'),
('bias_mode_bias2_enabled', 'uint8'),
('bias_mode_bias3_enabled', 'uint8'),
('bias_on_off', 'uint8'),
('bw', 'uint8'),
('sp0', 'uint8'),
('sp1', 'uint8'),
('r0', 'uint8'),
('r1', 'uint8'),
('r2', 'uint8'),
('pe', 'float64', 22),
('pb', 'float64', 22),
('nvec_v0', 'float32', 22),
('nvec_v1', 'float32', 22),
('nvec_v2', 'uint8', 22),
('ellip', 'float32', 22),
('dop', 'float32', 22),
('sx_rea', 'float64', 22),
('sx_arg', 'uint8', 22),
('vphi_rea', 'float64', 22),
('vphi_arg', 'uint8', 22),
]
def bp1(f, task):
# name of the packet
freq = 'F0'
name = 'TM_LFR_SCIENCE_SBM1_BP1_' + freq
logger.debug('Get data for ' + name)
# get the sbm1 bp1 data
if name in f['TM']:
fdata = f['TM'][name]['source_data']
else:
# rest of the code inside the with statement will not be called
return np.empty(
0,
dtype=BP1,
)
# Sort input packets by ascending acquisition times
fdata, __ = sort_data(fdata, (
fdata['PA_LFR_ACQUISITION_TIME'][:, 1],
fdata['PA_LFR_ACQUISITION_TIME'][:, 0],
))
# create an array for the data
result = np.empty(
fdata['PA_LFR_ACQUISITION_TIME'].shape[0],
dtype=BP1,
)
fill_records(result)
# Get number of packets and blocks
shape = fdata['PA_LFR_SC_BP1_PE_' + freq].shape
n = shape[1]
# get the acquisition time and other data
result['acquisition_time'] = fdata['PA_LFR_ACQUISITION_TIME'][:, :2]
result['synchro_flag'] = fdata['PA_LFR_ACQUISITION_TIME'][:, 2]
result['bias_mode_mux_set'] = fdata['PA_BIA_MODE_MUX_SET']
result['bias_mode_hv_enabled'] = fdata['PA_BIA_MODE_HV_ENABLED']
result['bias_mode_bias1_enabled'] = fdata['PA_BIA_MODE_BIAS1_ENABLED']
result['bias_mode_bias2_enabled'] = fdata['PA_BIA_MODE_BIAS2_ENABLED']
result['bias_mode_bias3_enabled'] = fdata['PA_BIA_MODE_BIAS3_ENABLED']
result['bias_on_off'] = fdata['PA_BIA_ON_OFF']
result['bw'] = fdata['SY_LFR_BW']
result['sp0'] = fdata['SY_LFR_SP0']
result['sp1'] = fdata['SY_LFR_SP1']
result['r0'] = fdata['SY_LFR_R0']
result['r1'] = fdata['SY_LFR_R1']
result['r2'] = fdata['SY_LFR_R2']
# Convert BP1 values (see convert_BP.py)
struct = namedtuple('struct', ['nbitexp', 'nbitsig', 'rangesig_16',
'rangesig_14', 'expmax', 'expmin'])
bp_lib.init_struct(struct)
result['pe'][:, :n] = bp_lib.convToFloat16(struct,
fdata['PA_LFR_SC_BP1_PE_' + freq][:, :n])
result['pb'][:, :n] = bp_lib.convToFloat16(struct,
fdata['PA_LFR_SC_BP1_PB_' + freq][:, :n])
# Compute n1 component of k-vector (normalized)
result['nvec_v0'][:, :n] = bp_lib.convToFloat8(
fdata['PA_LFR_SC_BP1_NVEC_V0_' + freq][:, :n])
# Compute n2 component of k-vector (normalized)
result['nvec_v1'][:, :n] = bp_lib.convToFloat8(
fdata['PA_LFR_SC_BP1_NVEC_V1_' + freq][:, :n])
# Store the 1b bit of the sign of n3 components k-vector in nvec_v2
result['nvec_v2'][:, :n] = bp_lib.convToUint8(
fdata['PA_LFR_SC_BP1_NVEC_' + freq][:, :n])
result['ellip'][:, :n] = bp_lib.convToFloat4(
fdata['PA_LFR_SC_BP1_ELLIP_' + freq][:, :n])
result['dop'][:, :n] = bp_lib.convToFloat3(
fdata['PA_LFR_SC_BP1_DOP_' + freq][:, :n])
# Extract x-component of normalized Poynting flux...
# sign (1 bit)...
sx_sign = 1 - \
(2 * bp_lib.Uint16ToUint8(fdata['PA_LFR_SC_BP1_SX_' +
freq][:, :n], 15, 0x1).astype(float))
# real value (14 bits)
result['sx_rea'][:, :n] = sx_sign * bp_lib.convToFloat14(struct,
fdata['PA_LFR_SC_BP1_SX_' + freq][:, :n])
# and arg (1 bit)
result['sx_arg'][:, :n] = bp_lib.Uint16ToUint8(
fdata['PA_LFR_SC_BP1_SX_' + freq][:, :n], 14, 0x1)
# Extract velocity phase...
# sign (1 bit)...
vphi_sign = 1 - (2 * bp_lib.Uint16ToUint8(
fdata['PA_LFR_SC_BP1_VPHI_' + freq][:, :n], 15, 0x1).astype(float))
# real value (14 bits)
result['vphi_rea'][:, :n] = vphi_sign * bp_lib.convToFloat14(struct,
fdata['PA_LFR_SC_BP1_VPHI_' + freq][:, :n])
# and arg (1 bit)
result['vphi_arg'][:, :n] = bp_lib.Uint16ToUint8(
fdata['PA_LFR_SC_BP1_VPHI_' + freq][:, :n], 14, 0x1)
# Get TT2000 Epoch time
result['epoch'] = Time().obt_to_utc(
result['acquisition_time'], to_tt2000=True)
# Get scet
result['scet'] = Time.cuc_to_scet(result['acquisition_time'])
return result
# Numpy array dtype for LFR BP2 L1 SBM1 data
# Name convention is lower case
BP2 = [
('epoch', 'uint64'),
('scet', 'float64'),
('acquisition_time', 'uint32', 2),
('synchro_flag', 'uint8'),
('quality_flag', 'uint8'),
('quality_bitmask', 'uint8'),
('bias_mode_mux_set', 'uint8'),
('bias_mode_hv_enabled', 'uint8'),
('bias_mode_bias1_enabled', 'uint8'),
('bias_mode_bias2_enabled', 'uint8'),
('bias_mode_bias3_enabled', 'uint8'),
('bias_on_off', 'uint8'),
('bw', 'uint8'),
('sp0', 'uint8'),
('sp1', 'uint8'),
('r0', 'uint8'),
('r1', 'uint8'),
('r2', 'uint8'),
('auto', 'float64', (22, 5)),
('cross_re', 'float32', (22, 10)),
('cross_im', 'float32', (22, 10)),
]
def bp2(f, task):
# name of the packet
name = 'TM_LFR_SCIENCE_SBM1_BP2_F0'
logger.debug('Get data for ' + name)
# get the sbm1 bp2 data
if name in f['TM']:
data = f['TM'][name]['source_data']
else:
return np.empty(
0,
dtype=BP2,
)
# Sort input packets by ascending acquisition times
data, __ = sort_data(data, (
data['PA_LFR_ACQUISITION_TIME'][:, 1],
data['PA_LFR_ACQUISITION_TIME'][:, 0],
))
# create an array for the data
result = np.empty(
data['PA_LFR_ACQUISITION_TIME'].shape[0],
dtype=BP2,
)
fill_records(result)
# get the acquisition time and other data
result['acquisition_time'] = data['PA_LFR_ACQUISITION_TIME'][:, :2]
result['synchro_flag'] = data['PA_LFR_ACQUISITION_TIME'][:, 2]
result['bias_mode_mux_set'] = data['PA_BIA_MODE_MUX_SET']
result['bias_mode_hv_enabled'] = data['PA_BIA_MODE_HV_ENABLED']
result['bias_mode_bias1_enabled'] = data['PA_BIA_MODE_BIAS1_ENABLED']
result['bias_mode_bias2_enabled'] = data['PA_BIA_MODE_BIAS2_ENABLED']
result['bias_mode_bias3_enabled'] = data['PA_BIA_MODE_BIAS3_ENABLED']
result['bias_on_off'] = data['PA_BIA_ON_OFF']
result['bw'] = data['SY_LFR_BW']
result['sp0'] = data['SY_LFR_SP0']
result['sp1'] = data['SY_LFR_SP1']
result['r0'] = data['SY_LFR_R0']
result['r1'] = data['SY_LFR_R1']
result['r2'] = data['SY_LFR_R2']
auto = np.dstack(
list(
data['PA_LFR_SC_BP2_AUTO_A{0}_F0'.format(x)]
for x in range(5)
)
)
cross_re = np.dstack(
list(
data['PA_LFR_SC_BP2_CROSS_RE_{0}_F0'.format(x)]
for x in range(10)
)
)
cross_im = np.dstack(
list(
data['PA_LFR_SC_BP2_CROSS_IM_{0}_F0'.format(x)]
for x in range(10)
)
)
# Get number of packets and blocks
shape = data['PA_LFR_SC_BP2_AUTO_A0_F0'].shape
n = shape[1]
# Convert AUTO, CROSS_RE an CROSS_IM (see convert_BP.py)
struct = namedtuple('struct', ['nbitexp', 'nbitsig', 'rangesig_16', 'rangesig_14',
'expmax', 'expmin'])
bp_lib.init_struct(struct)
result['auto'][:, :n, :] = bp_lib.convToAutoFloat(struct, auto)
result['cross_re'][:, :n, :] = bp_lib.convToCrossFloat(cross_re)
result['cross_im'][:, :n, :] = bp_lib.convToCrossFloat(cross_im)
# WARNING, IF NAN or INF, put FILLVAL
# TODO - Optimize this part
result['auto'][np.isinf(result['auto'])] = -1e31
result['auto'][np.isnan(result['auto'])] = -1e31
result['cross_re'][np.isinf(result['cross_re'])] = -1e31
result['cross_re'][np.isnan(result['cross_re'])] = -1e31
result['cross_im'][np.isinf(result['cross_im'])] = -1e31
result['cross_im'][np.isnan(result['cross_im'])] = -1e31
# Get Epoch in nanoseconds
result['epoch'] = Time().obt_to_utc(
result['acquisition_time'], to_tt2000=True)
# Get scet
result['scet'] = Time.cuc_to_scet(result['acquisition_time'])
return result
# Numpy array dtype for LFR CWF L1 SBM1 data
# Name convention is lower case
CWF = [
('epoch', 'uint64'),
('scet', 'float64'),
('acquisition_time', 'uint32', 2),
('synchro_flag', 'uint8'),
('quality_flag', 'uint8'),
('quality_bitmask', 'uint8'),
('bias_mode_mux_set', 'uint8'),
('bias_mode_hv_enabled', 'uint8'),
('bias_mode_bias1_enabled', 'uint8'),
('bias_mode_bias2_enabled', 'uint8'),
('bias_mode_bias3_enabled', 'uint8'),
('bias_on_off', 'uint8'),
('bw', 'uint8'),
('sp0', 'uint8'),
('sp1', 'uint8'),
('r0', 'uint8'),
('r1', 'uint8'),
('r2', 'uint8'),
('freq', 'uint8'),
('sampling_rate', 'float32'),
('v', 'int16'),
('e', 'int16', 2),
('b', 'int16', 3),
]
def cwf(f, task):
# name of the packet
name = 'TM_LFR_SCIENCE_SBM1_CWF_F1'
logger.debug('Get data for ' + name)
# get the sbm1 bp1 data
if name in f['TM']:
fdata = f['TM'][name]['source_data']
else:
return np.empty(
0,
dtype=CWF,
)
in_data = {
name: fdata[name][...] for name in fdata.keys()
}
# get the data for cwf
out_data = set_cwf(in_data, 'F1', CWF, True, task)
# specific parameters
out_data['freq'][:] = 1
return out_data | /roc_rap-1.4.5.tar.gz/roc_rap-1.4.5/roc/rap/tasks/lfr/sbm1.py | 0.667148 | 0.256198 | sbm1.py | pypi |
import numpy as np
from poppy.core.logger import logger
from roc.rpl.time import Time
from roc.idb.converters.cdf_fill import fill_records
from roc.rap.tasks.utils import sort_data
__all__ = ['HIST1D', 'set_hist1d']
# Numpy array dtype for TDS histo1D L1 survey data
# Name convention is lower case
HIST1D = [
('epoch', 'uint64'),
('scet', 'float64'),
('acquisition_time', ('uint32', 2)),
('synchro_flag', 'uint8'),
('quality_flag', 'uint8'),
('quality_bitmask', 'uint8'),
('survey_mode', 'uint8'),
('bia_status_info', ('uint8', 6)),
('sampling_rate', 'float32'),
('rpw_status_info', ('uint8', 8)),
('channel_status_info', ('uint8', 4)),
('input_config', 'uint32'),
('snapshot_len', 'uint8'),
('hist1d_id', 'uint8'),
('hist1d_param', 'uint8'),
('hist1d_axis', 'uint8'),
('hist1d_col_time', 'uint16'),
('hist1d_out', 'uint16'),
('hist1d_bins', 'uint16'),
('hist1d_counts', ('uint16', 256)),
]
# TDS HIST1D sampling rate in Hz
SAMPLING_RATE_HZ = [65534.375, 131068.75, 262137.5, 524275., 2097100.]
def set_hist1d(l0, task):
# name of the packet
name = 'TM_TDS_SCIENCE_NORMAL_HIST1D'
logger.debug('Get data for ' + name)
# get the HIST1D packet data
if name in l0['TM']:
tm = l0['TM'][name]['source_data']
else:
# rest of the code inside the with statement will not be called
return np.empty(
0,
dtype=HIST1D,
)
# Sort input packets by ascending acquisition times
tm, __ = sort_data(tm, (
tm['PA_TDS_ACQUISITION_TIME'][:,1],
tm['PA_TDS_ACQUISITION_TIME'][:,0],
))
# get the number of packets
size = tm['PA_TDS_ACQUISITION_TIME'].shape[0]
# create the data array with good size
data = np.zeros(size, dtype=HIST1D)
fill_records(data)
# set the data for stat, directly a copy of the content of parameters
data['epoch'][:] = Time().obt_to_utc(tm['PA_TDS_ACQUISITION_TIME'][:, :2], to_tt2000=True)
data['acquisition_time'][:, :] = tm['PA_TDS_ACQUISITION_TIME'][:, :2]
data['synchro_flag'][:] = tm['PA_TDS_ACQUISITION_TIME'][:, 2]
data['scet'][:] = Time.cuc_to_scet(data['acquisition_time'])
data['survey_mode'][:] = 3
# bias info
data['bia_status_info'][:, :] = np.vstack(
(
tm['PA_BIA_ON_OFF'],
tm['PA_BIA_MODE_BIAS3_ENABLED'],
tm['PA_BIA_MODE_BIAS2_ENABLED'],
tm['PA_BIA_MODE_BIAS1_ENABLED'],
tm['PA_BIA_MODE_HV_ENABLED'],
tm['PA_BIA_MODE_MUX_SET'],
)
).T
data['channel_status_info'][:, :] = np.vstack(
(
tm['PA_TDS_STAT_ADC_CH1'],
tm['PA_TDS_STAT_ADC_CH2'],
tm['PA_TDS_STAT_ADC_CH3'],
tm['PA_TDS_STAT_ADC_CH4'],
)
).T
# rpw status
data['rpw_status_info'][:, :] = np.vstack(
(
tm['PA_TDS_THR_OFF'],
tm['PA_TDS_LFR_OFF'],
tm['PA_TDS_ANT1_OFF'],
tm['PA_TDS_ANT2_OFF'],
tm['PA_TDS_ANT3_OFF'],
tm['PA_TDS_SCM_OFF'],
tm['PA_TDS_HF_ART_MAG_HEATER'],
tm['PA_TDS_HF_ART_SCM_CALIB'],
)
).T
# input config
data['input_config'] = tm['PA_TDS_SWF_HF_CH_CONF']
# hist parameters
data['snapshot_len'] = tm['PA_TDS_SNAPSHOT_LEN']
data['hist1d_id'] = tm['PA_TDS_SC_HIST1D_ID']
data['hist1d_param'] = tm['PA_TDS_SC_HIST1D_PARAM']
data['hist1d_axis'] = tm['PA_TDS_SC_HIST1D_BINS']
data['hist1d_col_time'] = tm['PA_TDS_SC_HIST1D_COLL_TIME']
data['hist1d_out'] = tm['PA_TDS_SC_HIST1D_OUT']
data['hist1d_bins'] = tm['PA_TDS_SC_HIST1D_NUM_BINS']
for i in range(size):
# sampling rate
data['sampling_rate'][i] = SAMPLING_RATE_HZ[tm['PA_TDS_STAT_SAMP_RATE'][i]]
# HIST1D count
ncount = len(tm['PA_TDS_SC_HIST1D_COUNTS'][i, :])
data['hist1d_counts'][i, 0:ncount] = tm['PA_TDS_SC_HIST1D_COUNTS'][i, :]
return data | /roc_rap-1.4.5.tar.gz/roc_rap-1.4.5/roc/rap/tasks/tds/normal_hist1d.py | 0.419529 | 0.253457 | normal_hist1d.py | pypi |
from roc.idb.constants import IDB_SOURCE
from roc.rpl import SCOS_HEADER_BYTES
from roc.rpl.tasks import IdentifyPackets, ParsePackets
from roc.rpl.tasks.packets_to_json import PacketsToJson
try:
from poppy.core.command import Command
from poppy.core.logger import logger
except:
print('POPPy framework is not installed!')
__all__ = ['RPL']
class RPL(Command):
"""
A command to do the decommutation of a test log file in the XML format.
"""
__command__ = 'rpl'
__command_name__ = 'rpl'
__parent__ = 'master'
__parent_arguments__ = ['base']
__help__ = (
'Commands relative to the decommutation of packets with help ' +
'of PacketParser library'
)
def add_arguments(self, parser):
"""
Add input arguments common to all the RPL plugin.
:param parser: high-level pipeline parser
:return:
"""
# specify the IDB version to use
parser.add_argument(
'--idb-version',
help='IDB version to use.',
default=[None],
nargs=1,
)
# specify the IDB source to use
parser.add_argument(
'--idb-source',
help='IDB source to use: SRDB, PALISADE or MIB.',
default=[IDB_SOURCE],
nargs=1,
)
# Remove SCOS2000 header in the binary packet
parser.add_argument(
'--scos-header',
nargs=1,
type=int,
default=[SCOS_HEADER_BYTES],
help='Length (in bytes) of SCOS2000 header to be removed'
' from the TM packet in the DDS file.'
f' (Default value is {SCOS_HEADER_BYTES} bytes.)',
)
class PacketsToJsonCommand(Command):
"""
Command to parse and write RPW packets data into a JSON format file.
input binary data must be passed as hexadecimal strings.
IDB must be available in the database.
"""
__command__ = 'rpl_pkt_to_json'
__command_name__ = 'pkt_to_json'
__parent__ = 'rpl'
__parent_arguments__ = ['base']
__help__ = """
Command to parse and save RPW packets data into a JSON format file.
"""
def add_arguments(self, parser):
# packet binary data
parser.add_argument(
'-b', '--binary',
help="""
Packet binary data (hexadecimal).
""",
type=str,
nargs='+',
required=True,
)
# Output file path
parser.add_argument(
'-j', '--output-json-file',
help=f'If passed, save packet data in a output JSON file.',
type=str,
nargs=1,
default=[None],
)
# Header only
parser.add_argument(
'-H', '--header-only',
action='store_true',
default=False,
help='Return packet header information only'
)
# Only return valid packets
parser.add_argument(
'-V', '--valid-only',
action='store_true',
default=False,
help='Return valid packets only'
)
# Only return valid packets
parser.add_argument(
'-P', '--print',
action='store_true',
default=False,
help='Return results in stdin'
)
# Overwrite existing file
parser.add_argument(
'-O', '--overwrite',
action='store_true',
default=False,
help='Overwrite existing JSON file'
)
def setup_tasks(self, pipeline):
"""
Execute the command.
"""
if pipeline.args.header_only:
start = IdentifyPackets()
else:
start = ParsePackets()
pipeline | start | PacketsToJson()
# define the start points of the pipeline
pipeline.start = start | /roc_rpl-1.5.1-cp38-cp38-manylinux_2_28_x86_64.whl/roc/rpl/commands.py | 0.74826 | 0.210016 | commands.py | pypi |
from sqlalchemy import func
try:
from poppy.core.db.connector import Connector
from poppy.core.logger import logger
except:
print('POPPy framework is not installed')
try:
from roc.idb.models.idb import PacketHeader, ItemInfo
except:
print('roc.idb plugin is not installed!')
from roc.rpl.exceptions import InvalidPacketID
from roc.rpl.packet_parser.packet_cache import PacketCache
from roc.rpl.packet_structure.data import Data
from roc.rpl.packet_structure.data import header_foot_offset
__all__ = ['ExtendedData']
class ExtendedData(Data):
"""
Extended data class which allows to manage the analysis of the packet header
as well as the identification of the PALISADE ID.
"""
# Use __new__ instead of __init__ since Data parent class is supposed as immutable class
# __new__ is then required to introduce idb ExtendedData class argument
# FIXME - See why roc.rap installation fails when using settings.PIPELINE_DATABASE
#@Connector.if_connected('MAIN-DB')
def __new__(cls, data, size, idb):
instance = super(ExtendedData, cls).__new__(cls, data, size)
# Get/create PacketCache singleton instance
instance._cache = PacketCache()
# Initialize IDB
if idb in instance._cache.idb:
instance.idb = instance._cache.idb[idb][0]
instance.session = instance._cache.idb[idb][1]
else:
instance.idb = idb.get_idb()
instance.session = idb.session
instance._cache.idb[idb] = (instance.idb, instance.session)
return instance
def _get_max_sid(self, header, data_header):
"""
Get Packet max_sid value
:param header: packet_header parameters
:param data_header: packet data_field_header parameters
:return: max_sid value
"""
# Return Sid value if already in the cache
param_tuple = (self.idb,
header.packet_type,
header.process_id,
header.packet_category,
data_header.service_type,
data_header.service_subtype)
if param_tuple in self._cache.max_sid:
return self._cache.max_sid[param_tuple]
# Else, retrieve value from IDB data in the database
# The structure_id (sid) is required to fully identify TM packets
if header.packet_type == 0:
query_max_sid = self.session.query(func.max(PacketHeader.sid))
query_max_sid = query_max_sid.join(ItemInfo)
query_max_sid = query_max_sid.filter_by(idb=self.idb)
query_max_sid = query_max_sid.filter(
PacketHeader.cat == header.packet_category)
query_max_sid = query_max_sid.filter(
PacketHeader.pid == header.process_id)
if data_header is not None:
query_max_sid = query_max_sid.filter(
PacketHeader.service_type == data_header.service_type)
query_max_sid = query_max_sid.filter(
PacketHeader.service_subtype == data_header.service_subtype)
max_sid_value = query_max_sid.one()[0]
# now we can obtain the palisade name
else:
max_sid_value = None
# add max_sid_value in cache
self._cache.max_sid[param_tuple] = max_sid_value
return max_sid_value
def _get_sid(self, header, data_header, max_sid_value):
"""
Get Packet sid value
:param header: packet_header parameters
:param data_header: packet data_field_header parameters
:param max_sid_value: max sid value
:return: sid value
"""
# get header and footer offsets
header_offset, _ = header_foot_offset(header.packet_type)
# For service 1 TM packets, add 4 bytes to the offset
if data_header.service_type == 1:
header_offset += 4
# get the value from data
if max_sid_value <= 255:
value = self.u8p(header_offset, 0, 8)
# logger.warning('8 bits data')
else:
value = self.u16p(header_offset, 0, 16)
# logger.warning('16 bits data')
return value
def _get_packet_ids(self, header, data_header):
"""
Get packet IDs (SRDB_ID and PALISADE ID)
:param header: packet_header parameters
:param data_header: packet data_field_header parameters
:param max_sid_value: max SID value
:param sid_value:
:return: tuple (SRDB ID, PALISADE ID) for the current packet
"""
# Initialize outputs
srdb_id = None
palisade_id = None
# extract the Structure ID (SID) only if the packet is not empty ...
# get the max possible value for the SID
max_sid_value = self._get_max_sid(header, data_header)
# If it is a TM packet and it has a SID, then...
if max_sid_value is not None:
# SID is always positive, so if max_sid_value == 0, then ...
if max_sid_value == 0:
sid_value = 0
else:
# check the first byte of data to get the SID
sid_value = self._get_sid(header, data_header, max_sid_value)
else:
sid_value = None
# Return SRDB ID and palisade ID if already stored in the cache
param_tuple = (self.idb,
header.packet_category,
header.process_id,
data_header.service_type,
data_header.service_subtype,
max_sid_value, sid_value)
if param_tuple in self._cache.packet_ids:
return self._cache.packet_ids[param_tuple]
# Else, build query to retrieve the TM/TC packet srdb and palisade IDs
query_packet_ids = self.session.query(
ItemInfo.srdb_id, ItemInfo.palisade_id)
query_packet_ids = query_packet_ids.filter_by(idb=self.idb)
query_packet_ids = query_packet_ids.join(PacketHeader)
query_packet_ids = query_packet_ids.filter(
PacketHeader.cat == header.packet_category)
query_packet_ids = query_packet_ids.filter(
PacketHeader.pid == header.process_id)
# logger.warning('packet_category: '+str(header.packet_category))
# logger.warning('process_id: '+str(header.process_id))
if data_header is not None:
query_packet_ids = query_packet_ids.filter(
PacketHeader.service_type == data_header.service_type)
query_packet_ids = query_packet_ids.filter(
PacketHeader.service_subtype == data_header.service_subtype)
# logger.warning('max sid value: '+str(max_sid_value))
# If it is a TM packet and it has a SID, then...
if max_sid_value is not None:
# SID is always positive, so if max_sid_value == 0, then ...
if max_sid_value == 0:
sid_value = 0
else:
sid_value = self._get_sid(header, data_header, max_sid_value)
query_packet_ids = query_packet_ids.filter(
PacketHeader.sid == sid_value)
try:
srdb_id, palisade_id = query_packet_ids.all()[0]
except InvalidPacketID:
logger.warning('Unknown palisade ID')
except:
logger.exception('Querying packet IDs has failed!')
else:
# add into the cache
self._cache.packet_ids[param_tuple] = (srdb_id, palisade_id)
finally:
return (srdb_id, palisade_id)
def get_packet_summary(self,
srdb_id=None,
palisade_id=None):
"""
Get a summary (srdb_id, palisade_id, header, data_header) of the packet.
:return: srdb_id, palisade_id, header, data_header
"""
# extract the header
header = self.extract_header()
# check if there is a data header
data_header = None
if header.data_field_header_flag:
# check if the packet is a TM or a TC
packet_type = header.packet_type
if packet_type == 0:
data_header = self.extract_tm_header()
elif packet_type == 1:
data_header = self.extract_tc_header()
# get srdb and palisade ids
if srdb_id is None or palisade_id is None:
srdb_id, palisade_id = self._get_packet_ids(
header, data_header)
else:
logger.warning('No data header')
return srdb_id, palisade_id, header, data_header | /roc_rpl-1.5.1-cp38-cp38-manylinux_2_28_x86_64.whl/roc/rpl/packet_parser/extended_data.py | 0.511229 | 0.20467 | extended_data.py | pypi |
import struct
from roc.rpl.exceptions import RPLError
from roc.rpl.packet_parser.packet_parser import PacketParser
from .utils import find_index
from .utils import get_base_packet
from roc.rpl.packet_structure.data import Data
__all__ = []
def get_base_tds(Packet):
"""
Generate the base class to use for compressed packets in the case of TDS.
"""
# base class for compressed packet
Base = get_base_packet(Packet)
# base class for the compressed packets of LFR
class TDS(Base):
"""
Base class for the compressed packets of LFR. Define the special
behaviour of the treatment for those packets, that should mimic the non
compressed (NC) ones.
"""
def __init__(self, name):
# init the packet as the other
super(TDS, self).__init__(name)
# the index of the parameter with the number of blocks
self.idx_nchannels, self.nchannels = find_index(
self.parameters,
self.NCHANNEL,
)
def data_substitution(self, data, uncompressed):
"""
Create a new data bytes array in order to simulate an non
compressed packet with the data from an uncompressed packet,
allowing to decommute and store a compressed packet as an
uncompressed one. Different from the base one since we need to add
the parameter indicating the number of blocks used in the packet,
not present in the compressed packet.
"""
new_bytes = data.to_bytes()[:self.start.byte + self.header_offset]
new_bytes += struct.pack(
">H",
len(uncompressed) // self.block_size,
)
new_bytes += uncompressed
new_data = Data(new_bytes, len(new_bytes))
return new_data
def uncompressed_byte_size(self, data, values):
# check number of samples
if values[self.idx_nblocks] > self.nblocks.maximum:
raise RPLError(
"The number of samples is superior to authorized values" +
" for packet {0}: {1} with maximum {2}".format(
self.name,
values[self.idx_nblocks],
self.nblocks.maximum,
)
)
# check number of channels
if values[self.idx_nchannels] > self.nchannels.maximum:
raise RPLError(
"The number of samples is superior to authorized values" +
" for packet {0}: {1} with maximum {2}".format(
self.name,
values[self.idx_nchannels],
self.nchannels.maximum,
)
)
return (
values[self.idx_nblocks] * values[self.idx_nchannels] *
self.block_size
)
return TDS
def create_packet(Packet):
"""
Given the base class of the packets to use, add special methods into the
new class to be able to treat the compressed packet as an existing one.
"""
# get the base class for TDS packets
TDS = get_base_tds(Packet)
# TM_TDS_SCIENCE_NORMAL_RSWF
class NormalRSWF(TDS):
DATA_START = "PA_TDS_COMP_DATA_BLK"
DATA_COUNT = "PA_TDS_N_RSWF_C_BLK_NR"
START = "PA_TDS_COMPUTED_CRC"
NBLOCK = "PA_TDS_SAMPS_PER_CH"
NCHANNEL = "PA_TDS_NUM_CHANNELS"
NC_DATA_START = "PA_TDS_RSWF_DATA_BLK"
NormalRSWF("TM_TDS_SCIENCE_NORMAL_RSWF_C")
# TM_TDS_SCIENCE_SBM1_RSWF
class SBM1RSWF(NormalRSWF):
DATA_COUNT = "PA_TDS_S1_RSWF_C_BLK_NR"
SBM1RSWF("TM_TDS_SCIENCE_SBM1_RSWF_C")
# TM_TDS_SCIENCE_NORMAL_TSWF
class NormalTSWF(TDS):
DATA_START = "PA_TDS_COMP_DATA_BLK"
DATA_COUNT = "PA_TDS_N_TSWF_C_BLK_NR"
START = "PA_TDS_COMPUTED_CRC"
NBLOCK = "PA_TDS_SAMPS_PER_CH"
NCHANNEL = "PA_TDS_NUM_CHANNELS"
NC_DATA_START = "PA_TDS_TSWF_DATA_BLK"
NormalTSWF("TM_TDS_SCIENCE_NORMAL_TSWF_C")
# TM_TDS_SCIENCE_SBM2_TSWF
class SBM2TSWF(NormalTSWF):
DATA_COUNT = "PA_TDS_S2_TSWF_C_BLK_NR"
SBM2TSWF("TM_TDS_SCIENCE_SBM2_TSWF_C")
# TM_TDS_SCIENCE_NORMAL_MAMP
class NormalMAMP(TDS):
DATA_START = "PA_TDS_COMP_DATA_BLK"
DATA_COUNT = "PA_TDS_MAMP_C_DATA_BLK_NR"
START = "PA_TDS_COMPUTED_CRC"
NBLOCK = "PA_TDS_MAMP_SAMP_PER_CH"
NCHANNEL = "PA_TDS_MAMP_NUM_CH"
NC_DATA_START = "PA_TDS_MAMP_DATA_BLK"
NormalMAMP("TM_TDS_SCIENCE_NORMAL_MAMP_C")
# TM_TDS_SCIENCE_LFM_CWF
class LFMCWF(TDS):
DATA_START = "PA_TDS_COMP_DATA_BLK"
DATA_COUNT = "PA_TDS_LFM_CWF_C_BLK_NR"
START = "PA_TDS_COMPUTED_CRC"
NBLOCK = "PA_TDS_LFR_CWF_SAMPS_PER_CH"
NCHANNEL = "PA_TDS_LFM_CWF_CH_NR"
NC_DATA_START = "PA_TDS_LFM_CWF_DATA_BLK"
LFMCWF("TM_TDS_SCIENCE_LFM_CWF_C")
# TM_TDS_SCIENCE_LFM_RSWF
class LFMRSWF(TDS):
DATA_START = "PA_TDS_COMP_DATA_BLK"
DATA_COUNT = "PA_TDS_LFM_RSWF_C_BLK_NR"
START = "PA_TDS_COMPUTED_CRC"
NBLOCK = "PA_TDS_LFR_SAMPS_PER_CH"
NCHANNEL = "PA_TDS_LFM_RSWF_CH_NR"
NC_DATA_START = "PA_TDS_LFM_RSWF_DATA_BLK"
LFMRSWF("TM_TDS_SCIENCE_LFM_RSWF_C")
# connect to the signal of the PacketParser to generate handlers of compressed packets
PacketParser.reseted.connect(create_packet) | /roc_rpl-1.5.1-cp38-cp38-manylinux_2_28_x86_64.whl/roc/rpl/compressed/tds.py | 0.724286 | 0.246307 | tds.py | pypi |
from roc.rpl.exceptions import RPLError
from roc.rpl.packet_parser.packet_parser import PacketParser
from .utils import get_base_packet
__all__ = []
def get_base_lfr(Packet):
"""
Generate the base class to use for compressed packets in the case of LFR.
"""
# base class for compressed packet
Base = get_base_packet(Packet)
# base class for the compressed packets of LFR
class LFR(Base):
"""
Base class for the compressed packets of LFR. Define the special
behaviour of the treatment for those packets, that should mimic the non
compressed (NC) ones.
"""
def uncompressed_byte_size(self, data, values):
"""
To get the size in bytes of the uncompressed data.
"""
# get the number of blocks and return the size in bytes of the
# uncompressed data
if values[self.idx_nblocks] > self.nblocks.maximum:
raise RPLError(
'The number of blocks is superior to authorized values' +
' for packet {0}: {1} with maximum {2}'.format(
self.name,
values[self.idx_nblocks],
self.nblocks.maximum,
)
)
return values[self.idx_nblocks] * self.block_size
return LFR
def create_packet(Packet):
"""
Given the base class of the packets to use, add special methods into the
new class to be able to treat the compressed packet as an existing one.
"""
# get the base class for LFR
LFR = get_base_lfr(Packet)
# base class for the compressed packets of LFR
class BurstCWFF2(LFR):
DATA_START = 'PA_LFR_COMP_DATA_BLK'
DATA_COUNT = 'PA_LFR_B_CWF_F2_C_BLK_NR'
START = 'PA_LFR_COMPUTED_CRC'
NBLOCK = 'PA_LFR_CWF_BLK_NR'
NC_DATA_START = 'PA_LFR_SC_V_F2'
BurstCWFF2('TM_LFR_SCIENCE_BURST_CWF_F2_C')
class NormalCWFF3(LFR):
DATA_START = 'PA_LFR_COMP_DATA_BLK'
DATA_COUNT = 'PA_LFR_N_CWF_F3_C_BLK_NR'
START = 'PA_LFR_COMPUTED_CRC'
NBLOCK = 'PA_LFR_CWF3_BLK_NR'
NC_DATA_START = 'PA_LFR_SC_V_F3'
NormalCWFF3('TM_LFR_SCIENCE_NORMAL_CWF_F3_C')
NormalCWFF3('TM_DPU_SCIENCE_BIAS_CALIB_C')
class NormalCWFLongF3(NormalCWFF3):
NBLOCK = 'PA_LFR_CWFL3_BLK_NR'
NormalCWFLongF3('TM_LFR_SCIENCE_NORMAL_CWF_LONG_F3_C')
NormalCWFLongF3('TM_DPU_SCIENCE_BIAS_CALIB_LONG_C')
class NormalSWFF0(LFR):
DATA_START = 'PA_LFR_COMP_DATA_BLK'
DATA_COUNT = 'PA_LFR_N_SWF_F0_C_BLK_NR'
START = 'PA_LFR_COMPUTED_CRC'
NBLOCK = 'PA_LFR_SWF_BLK_NR'
NC_DATA_START = 'PA_LFR_SC_V_F0'
NormalSWFF0('TM_LFR_SCIENCE_NORMAL_SWF_F0_C')
class NormalSWFF1(LFR):
DATA_START = 'PA_LFR_COMP_DATA_BLK'
DATA_COUNT = 'PA_LFR_N_SWF_F1_C_BLK_NR'
START = 'PA_LFR_COMPUTED_CRC'
NBLOCK = 'PA_LFR_SWF_BLK_NR'
NC_DATA_START = 'PA_LFR_SC_V_F1'
NormalSWFF1('TM_LFR_SCIENCE_NORMAL_SWF_F1_C')
class NormalSWFF2(LFR):
DATA_START = 'PA_LFR_COMP_DATA_BLK'
DATA_COUNT = 'PA_LFR_N_SWF_F2_C_BLK_NR'
START = 'PA_LFR_COMPUTED_CRC'
NBLOCK = 'PA_LFR_SWF_BLK_NR'
NC_DATA_START = 'PA_LFR_SC_V_F2'
NormalSWFF2('TM_LFR_SCIENCE_NORMAL_SWF_F2_C')
class SBM1CWFF1(LFR):
DATA_START = 'PA_LFR_COMP_DATA_BLK'
DATA_COUNT = 'PA_LFR_S1_CWF_F1_C_BLK_NR'
START = 'PA_LFR_COMPUTED_CRC'
NBLOCK = 'PA_LFR_CWF_BLK_NR'
NC_DATA_START = 'PA_LFR_SC_V_F1'
SBM1CWFF1('TM_LFR_SCIENCE_SBM1_CWF_F1_C')
class SBM2CWFF2(LFR):
DATA_START = 'PA_LFR_COMP_DATA_BLK'
DATA_COUNT = 'PA_LFR_S2_CWF_F2_C_BLK_NR'
START = 'PA_LFR_COMPUTED_CRC'
NBLOCK = 'PA_LFR_CWF_BLK_NR'
NC_DATA_START = 'PA_LFR_SC_V_F2'
SBM2CWFF2('TM_LFR_SCIENCE_SBM2_CWF_F2_C')
# connect to the signal of the PacketParser to generate handlers of compressed packets
PacketParser.reseted.connect(create_packet) | /roc_rpl-1.5.1-cp38-cp38-manylinux_2_28_x86_64.whl/roc/rpl/compressed/lfr.py | 0.691706 | 0.15444 | lfr.py | pypi |
"""PacketParser time module"""
import os
import os.path as osp
from datetime import datetime
import numpy as np
from poppy.core.configuration import Configuration
from poppy.core.generic.metaclasses import Singleton
from poppy.core.logger import logger
from roc.rpl.constants import SOLAR_ORBITER_NAIF_ID
from roc.rpl.packet_structure.data import Data
from roc.rpl.time.spice import SpiceHarvester
__all__ = ['Time']
# SEC TO NANOSEC conversion factor
SEC_TO_NANOSEC = np.timedelta64(1000000000, 'ns')
# J2000 base time
J2000_BASETIME = np.datetime64('2000-01-01T12:00', 'ns')
# Number of leap nanoseconds at J2000 origin (32 sec)
J2000_LEAP_NSEC = np.timedelta64(32000000000, 'ns')
# RPW CCSDS CUC base time
RPW_BASETIME = np.datetime64('2000-01-01T00:00', 'ns')
# Delta nanosec betwen TAI and TT time bases (TAI = TT + 32.184 sec)
DELTA_NSEC_TAI_TT = np.timedelta64(32184000000, 'ns')
# Delta nanosec between RPW and J2000 epoch (J2000 = RPW + 12h)
DELTA_NSEC_RPW_J2000 = RPW_BASETIME - J2000_BASETIME
# RPW BASETIME in TT2000 (nanoseconds since J2000)
TT2000_RPW_BASETIME = DELTA_NSEC_TAI_TT + \
J2000_LEAP_NSEC + DELTA_NSEC_RPW_J2000
# TT2000 BASETIME in Julian days
TT2000_JD_BASETIME = 2451545.0
# CUC fine part max value
CUC_FINE_MAX = 65536
# NASA CDF leapsecond table filename
CDF_LEAPSECONDSTABLE = 'CDFLeapSeconds.txt'
class TimeError(Exception):
"""Errors for the time."""
class Time(object, metaclass=Singleton):
"""
PacketParser Time class.
(Singleton: only one instance can be called.)
"""
def __init__(self,
kernel_date=None,
predictive=True,
flown=True,
spice_kernel_path='',
lstable_file=None,
no_spice=False):
# Set SPICE attributes
self.kernel_date = kernel_date
self.predictive = predictive
self.flown = flown
self.kernel_path = spice_kernel_path
self.no_spice = no_spice
# Initialize cached property and unloaded kernels (if any)
self.reset()
# If no spice, need a CDF leap second table file
if no_spice and lstable_file:
self.leapsec_file = lstable_file
def reset(self, spice=True, lstable=True):
"""
Reset spice and lstable related attribute values of the Time object.
:param spice: If True, reset spice attribute
:param lstable: If True, reset lstable attribute
:return:
"""
if lstable:
self._leapsec_file = ''
self._lstable = None
if spice:
# Make sure to unload all kernels
if hasattr(self, '_spice') and self._spice:
self._spice.unload_all()
self.kernel_path = ''
self._spice = None
@property
def leapsec_file(self):
return self._leapsec_file
@leapsec_file.setter
def leapsec_file(self, lstable_file):
"""
Set input leap seconds table file (and reload table if necessary).
:param lstable_file: Path to the leap seconds table file, as provided in the NASA CDF software
:return:
"""
if lstable_file and lstable_file == self._leapsec_file:
logger.debug(f'{lstable_file} already loaded')
else:
from maser.tools.time import Lstable
if not lstable_file:
if 'pipeline.environment.CDF_LEAPSECONDSTABLE' in Configuration.manager:
lstable_file = Configuration.manager['pipeline'][
'environment.CDF_LEAPSECONDSTABLE']
elif 'CDF_LEAPSECONDSTABLE' in os.environ:
lstable_file = os.environ['CDF_LEAPSECONDSTABLE']
elif 'CDF_LIB' in os.environ:
lstable_file = osp.join(
os.environ['CDF_LIB'], '..', CDF_LEAPSECONDSTABLE)
else:
lstable_file = CDF_LEAPSECONDSTABLE
try:
lstable = Lstable(file=lstable_file)
except:
logger.error(f'New leap second table "{lstable_file}" cannot be loaded!')
else:
self._lstable = lstable
self._leapsec_file = lstable_file
@property
def lstable(self):
if not self._lstable:
# If not alread loaded,
# get lstable (Set self.leapsec_file to None will trigger loading table file from config. file or
# environment variables)
self.leapsec_file = None
return self._lstable
@property
def spice(self):
if not self._spice and not self.no_spice:
self.spice = self._load_spice()
return self._spice
@spice.setter
def spice(self, value):
self._spice = value
def _load_spice(self):
"""
Load NAIF Solar Orbiter SPICE kernels for the current session.
:return:
"""
if not self.kernel_path:
self.kernel_path = SpiceHarvester.spice_kernel_path()
# Load SPICE kernels (only meta kernels for the moment)
return SpiceHarvester.load_spice_kernels(self.kernel_path,
only_mk=True,
by_date=self.kernel_date,
predictive=self.predictive,
flown=self.flown)
def obt_to_utc(self, cuc_time,
to_datetime=False,
to_tt2000=False):
"""
Convert input RPW CCSDS CUC time(s) into UTC time(s).
:param cuc_time: RPW CCSDS CUC time(s)
:param to_datetime: If True, return UTC time as datetime object
:param to_tt2000: If True, return TT2000 epoch time (nanosec since J2000) instead of UTC (data type is int)
:param: predictive: If True, then use predictive SPICE kernels instead of as-flown
:param: kernel_date: datetime object containing the date for which SPICE kernels must be loaded (if not passed, then load the latest kernels)
:param: reset: If True, then reset Time instance harvester
:param: no_spice: If True, dot not use SPICE toolkit to compute UTC time
:return: utc time(s) as numpy.datetime64 datatype (datetime object if to_datetime is True)
"""
# Make sure that cuc_time is a numpy array
cuc_time = np.array(cuc_time)
# Check that input cuc_time has the good shape
shape = cuc_time.shape
if shape == (2,):
cuc_time = cuc_time.reshape([1, 2])
# If no_spice = True ...
if self.no_spice:
# If SPICE not available, use internal routines
# (assuming no drift of OBT or light time travel corrections
# . It should be used for on-ground test only)
utc_time = self.cuc_to_utc(cuc_time, to_tt2000=to_tt2000)
else:
spice = self.spice
nrec = len(cuc_time)
if not to_tt2000:
utc_time = np.empty(nrec, dtype='datetime64[ns]')
else:
utc_time = np.empty(nrec, dtype=int)
# Then use SpiceManager to compute utc
for i, current_time in enumerate(cuc_time):
obt = spice.cuc2obt(current_time)
et = spice.obt2et(SOLAR_ORBITER_NAIF_ID, obt)
if not to_tt2000:
utc_time[i] = spice.et2utc(et)
else:
tdt = spice.et2tdt(et)
utc_time[i] = tdt * SEC_TO_NANOSEC
# Convert to datetime object if to_datetime keyword is True
if not to_tt2000 and to_datetime:
utc_time = Time.datetime64_to_datetime(utc_time)
return utc_time
@staticmethod
def cuc_to_nanosec(cuc_time, j2000=False):
"""
Given a CCSDS CUC coarse and fine cuc_time in the numpy array format,
returns it in nanoseconds since the defined epoch.
:param cuc_time: input RPW CCSDS CUC time provided as numpy array
:return: Return time in nano seconds since RPW origin (or J2000 if j2000 keyword is True) as numpy.uint64 array
"""
# first convert cuc time into scet
scet = Time.cuc_to_scet(cuc_time)
# Then convert scet in nanosec
nanosec = scet * np.float64(SEC_TO_NANOSEC)
if j2000:
nanosec -= np.float64(DELTA_NSEC_RPW_J2000)
return nanosec.astype(np.uint64)
@staticmethod
def cuc_to_scet(cuc_time):
"""
Return input RPW CCSDS CUC time as spacecraft elapsed time since RPW origin
:param cuc_time: input RPW CCSDS CUC time as numpy array
:return: spacecraft elapsed time since RPW origin as numpy.float46 array
"""
# Make sure that input cuc_time is a numpy array
if not isinstance(cuc_time, np.ndarray):
cuc_time = np.array(cuc_time, dtype=np.float64)
# Check that input cuc_time has the good shape
shape = cuc_time.shape
if shape == (2,):
cuc_time = cuc_time.reshape([1, 2])
# convert coarse part into nanoseconds
coarse = cuc_time[:, 0].astype('float64')
# same for fine part
fine = cuc_time[:, 1].astype('float64')
fine = fine / np.float64(CUC_FINE_MAX)
return coarse + fine
def cuc_to_utc(self, cuc_time,
from_nanosec=False,
to_tt2000=False):
"""
Convert RPW CCSDS CUC time(s) into in UTC time(s)
:param cuc_time: numpy uint array of RPW CCSDS CUC time(s)
:param from_nanosec: If True, then input RPW CCSDS CUC time array is expected in nanoseconds
:param to_tt2000: Convert input CCSDS CUC time into TT2000 epoch instead of UTC
:return: numpy datetime64 array of UTC time(s)
"""
if not from_nanosec:
# Convert cuc to nanosec since RPW_BASETIME
cuc_nanosec = self.cuc_to_nanosec(cuc_time)
else:
cuc_nanosec = cuc_time.astype(np.unint64)
# Convert to TT20000 epoch time
tt2000_epoch = cuc_nanosec + TT2000_RPW_BASETIME
if to_tt2000:
return tt2000_epoch
else:
return self.tt2000_to_utc(tt2000_epoch)
def tt2000_to_utc(self, tt2000_epoch,
leap_sec=None,
to_datetime=True):
"""
Convert input TT2000 epoch time into UTC time
:param tt2000_epoch: TT2000 epoch time to convert
:param leap_sec: number of leap second to apply
:param to_datetime: return utc time as a datetime object (microsecond resolution)
:return: UTC time (datetime.datetime if to_datetime=True, format returned by spice.tdt2uct otherwise)
"""
if self.no_spice:
# TT2000 to TT time
tt_time = tt2000_epoch + J2000_BASETIME
# Get leap seconds in nanosec
if not leap_sec:
lstable = self.lstable
leap_nsec = np.array([lstable.get_leapsec(Time.datetime64_to_datetime(tt)) * SEC_TO_NANOSEC
for tt in tt_time], dtype='timedelta64[ns]')
else:
leap_nsec = leap_sec * np.uint64(SEC_TO_NANOSEC)
utc_time = tt_time - DELTA_NSEC_TAI_TT - leap_nsec
else:
spice = self.spice
# Convert input TT2000 time in seconds (float)
tdt = float(tt2000_epoch) / float(SEC_TO_NANOSEC)
utc_time = spice.tdt2utc(tdt)
if to_datetime:
utc_time = datetime.strptime(utc_time,
spice.TIME_ISOC_STRFORMAT)
return utc_time
def utc_to_tt2000(self, utc_time,
leap_sec=None):
"""
Convert an input UTC time value into a TT2000 epoch time
:param utc_time: an input UTC time value to convert (numpy.datetime64 or datetime.datetime type)
:param leap_sec: number of leap seconds at the utc_time (only used if no_spice=True)
:param no_spice: If True, do not use SPICE toolkit to compute tt2000 time.
:return: TT2000 epoch time value (integer type)
"""
# Only works with scalar value for input utc_time
if isinstance(utc_time, list):
utc_time = utc_time[0]
if isinstance(utc_time, datetime):
utc_dt64 = Time.datetime_to_datetime64(utc_time)
utc_dt = utc_time
elif isinstance(utc_time, np.datetime64):
utc_dt64 = utc_time
utc_dt = Time.datetime64_to_datetime(utc_time)
else:
logger.error('Unknown type for input utc_time!')
return None
# Compute without SPICE
if self.no_spice:
# Get leap seconds in nanosec
if not leap_sec:
lstable = self.lstable
leap_nsec = lstable.get_leapsec(utc_dt) * SEC_TO_NANOSEC
else:
leap_nsec = leap_sec * np.uint64(SEC_TO_NANOSEC)
# Get nanoseconds since J2000
# And add leap seconds + the delta time between TAI and TT
tt2000_epoch = int(utc_dt64 - J2000_BASETIME) \
+ DELTA_NSEC_TAI_TT + np.timedelta64(leap_nsec, 'ns')
else:
# Use SPICE toolkit
spice = self.spice
# Convert input utc to string
utc_string = spice.utc_datetime_to_str(utc_dt)
# Convert utc string into ephemeris time then tdt
et = spice.utc2et(utc_string)
tdt = spice.et2tdt(et)
# Get tt2000_epoch in nanoseconds
tt2000_epoch = int(tdt * SEC_TO_NANOSEC)
return tt2000_epoch
@staticmethod
def cuc_to_microsec(time):
"""
cuc_to_microsec.
Convert a RPW CUC format time into microsec.
"""
# convert coarse part into microseconds
coarse = time[:, 0].astype('uint64') * 1000000
# same for fine part
fine = np.rint((time[:, 1].astype('uint64') * 1000000) / 65536).astype(
'uint64'
)
return coarse + fine
@staticmethod
def cuc_to_numpy_datetime64(time):
"""
Given a CUC format RPW time in the numpy array format
, returns it np datetime64 format.
(For more details about RPW CUC format see RPW-SYS-SSS-00013-LES)
:param time: array of input CCSDS CUC times (coarse, fine)
:return: datetime64 object of input CUC time
"""
ns = Time.cuc_to_nanosec(time)
base_time = RPW_BASETIME
dt64 = np.array([
base_time + np.timedelta64(int(nsec), 'ns')
for nsec in ns
], dtype=np.datetime64)
#dt64 = Time.datetime64_to_datetime(dt64)
return dt64
@staticmethod
def cuc_to_datetime(time):
"""
Convert input CCSDS CUC RPW time into datetime object.
:param time: array of input CCSDS CUC times (coarse, fine)
:return: CUC time as datetime
"""
dt = Time.cuc_to_numpy_datetime64(time)
return Time.datetime64_to_datetime(dt)
@staticmethod
def numpy_datetime64_to_cuc(time, synchro_flag=False):
"""
Given a numpy.datetime64, returns CCSDS CUC format time in the numpy array format.
(For more details about RPW CUC format see RPW-SYS-SSS-00013-LES)
:param time: numpy.datetime64 to convert to CCSDS CUC
:param synchro_flag: If True, time synchro flag bit is 1 (=not sync), 0 (=sync) otherwise
:return:numpy.array with [CUC coarse, fine, sync_flag]
"""
# convert time into nanoseconds since 2000-01-01T00:00:00
base_time = RPW_BASETIME
nanoseconds = np.timedelta64(time - base_time, 'ns').item()
# compute coarse part
coarse = nanoseconds // SEC_TO_NANOSEC
# compute fine part
fine = np.rint(((nanoseconds - coarse * SEC_TO_NANOSEC) /
SEC_TO_NANOSEC) * 65536).astype('uint16')
return np.array([[coarse, fine, int(synchro_flag)]])
@staticmethod
def extract_cuc(cuc_bytes):
"""
Extract RPW CCSDS CUC time 48 bytes and return
coarse, fine and sync flag
:param cuc_bytes: 48-bytes CUC time
:return: coarse, fine and sync flag
"""
if not isinstance(cuc_bytes, bytes):
cuc_bytes = bytes(cuc_bytes)
nbytes = len(cuc_bytes)
if nbytes != 48:
logger.error(f'Expect 48 bytes, but {nbytes} found for input CUC time!')
return None, None, None
return Data(cuc_bytes, nbytes).timep(0, 0, 48)
@staticmethod
def str2datetime64(string):
"""
Convert an input string in numpy.datetime64
:param string: string of ISO8601 format 'YYYY-MM-DDThh:mm:ss.ffffffZ'
:return: numpy.datetime64 time
"""
return np.datetime64(string)
@staticmethod
def datetime64_to_datetime(datetime64_input):
"""
Convert numpy.datetime64 object into datetime.datetime object
:param datetime64_input: input numpy.datetime64 object to convert
:return: datetime.datetime object
"""
return datetime64_input.astype('M8[us]').astype('O')
@staticmethod
def datetime_to_datetime64(datetime_input):
"""
Convert datetime.datetime object into numpy.datetime64 object
:param datetime_input: datetime.datetime object to convert
:return: numpy.datetime64 object
"""
return np.datetime64(datetime_input)
@staticmethod
def tt2000_to_jd(tt2000_time):
"""
Convert input TT2000 format time into Julian days
:param tt2000_time: TT2000 format time (i.e., nanoseconds since J2000)
:return: time in julian days (double)
"""
return (float(tt2000_time) / (1000000000.0 * 3600.0 * 24.0)) + TT2000_JD_BASETIME
@staticmethod
def jd_to_tt2000(jd_time):
"""
Convert input Julian day into TT2000 time
:param jd_time: Julian day time
:return: time in TT2000 format time (i.e., nanoseconds since J2000)
"""
return (float(jd_time) - TT2000_JD_BASETIME) * (1000000000.0 * 3600.0 * 24.0)
def jd_to_datetime(self, jd_time):
"""
Convert input Julian day into datetime.datetime object
:param jd_time: Julian day time
:return: datetime.datime object
"""
# convert to UTC first
utc_time = self.tt2000_to_utc(
np.array([
Time.jd_to_tt2000(jd_time)]), to_datetime=True)
return utc_time | /roc_rpl-1.5.1-cp38-cp38-manylinux_2_28_x86_64.whl/roc/rpl/time/time.py | 0.762247 | 0.164047 | time.py | pypi |
from __future__ import division
from __future__ import print_function
__author__ = 'zf'
import sys, os, time
import bz2, gzip
import uuid
import heapq
import numpy as np
import pickle
import random
import argparse
from collections import namedtuple
from itertools import islice
from multiprocessing import Process, Pool
from matplotlib import pyplot
import pylab
os.environ["DISPLAY"] = ":0.0"
MERGE_DIR = 'merges'
SORT_DIR = 'sorts'
OUTPUT_DIR = 'results'
DATA_PICKLE = 'data.pickle'
PHRASE_GROUP = 0
PHRASE_SORT = 1
PHRASE_PROCESS = 2
PHRASE_CHART = 3
DEFAULT_SAMPLE = 1.0
DEFAULT_SHART_COUNT = 100
DEFAULT_BUFFER_SIZE = 32000
DEFAULT_PLOT_SIZE_RATE = 2
DEFAULT_TEMPDIR = '/tmp/'
DEFAULT_DELIMTER = '\x01'
def openFile(file):
"""
Handles opening different types of files (only normal files and bz2 supported)
"""
file = file.lower()
if file.endswith('.bz2'):
return bz2.BZ2File(file)
elif file.endswith('.gz'):
return gzip.open(file)
return open(file)
def ensure_dir(dirName):
"""
Create directory if necessary.
"""
if not os.path.exists(dirName):
os.makedirs(dirName)
def batchSort(input, output, key, buffer_size, tempdir):
"""
External sort on file using merge sort.
See http://code.activestate.com/recipes/576755-sorting-big-files-the-python-26-way/
"""
def merge(key=None, *iterables):
if key is None:
keyed_iterables = iterables
else:
Keyed = namedtuple("Keyed", ["key", "obj"])
keyed_iterables = [(Keyed(key(obj), obj) for obj in iterable)
for iterable in iterables]
for element in heapq.merge(*keyed_iterables):
yield element.obj
tempdir = os.path.join(tempdir, str(uuid.uuid4()))
os.makedirs(tempdir)
chunks = []
try:
with open(input, 'rb', 64 * 1024) as inputFile:
inputIter = iter(inputFile)
while True:
current_chunk = list(islice(inputIter, buffer_size))
if not current_chunk:
break
current_chunk.sort(key=key)
output_chunk = open(
os.path.join(tempdir, '%06i' % len(chunks)), 'w+b',
64 * 1024)
chunks.append(output_chunk)
output_chunk.writelines(current_chunk)
output_chunk.flush()
output_chunk.seek(0)
with open(output, 'wb', 64 * 1024) as output_file:
output_file.writelines(merge(key, *chunks))
finally:
for chunk in chunks:
try:
chunk.close()
os.remove(chunk.name)
except Exception:
pass
print("sorted file %s ready" % (output))
def computeMetrics(model, input, shard_count, delimiter, print_cutoff=False):
"""
Process data. Bin data into shard_count bins. Accumulate data for each bin and populate necessary metrics.
"""
print('compute metrics for %s' % model)
data = np.loadtxt(input,
delimiter=delimiter,
dtype={
'names': ('model', 'weight', 'score', 'label'),
'formats': ('S16', 'f4', 'f4', 'i1')
})
dataSize = len(data)
shardSize = int(dataSize / shard_count)
rocPoints = [(0, 0)]
prPoints = []
corrPoints = []
cutoff = []
totalConditionPositive = 0.0
totalConditionNegative = 0.0
for record in data:
modelId = record[0]
weight = record[1]
score = record[2]
label = record[3]
if label == 1:
totalConditionPositive += weight
elif label == 0:
totalConditionNegative += weight
else:
assert False, 'label invalid: %d' % label
truePositive = 0.0
falsePositive = 0.0
binTotalScore = 0.0
binWeight = 0.0
binPositive = 0.0
overallTatalScore = 0.0
partitionSize = 0
for record in data:
modelId = record[0]
weight = record[1]
score = record[2]
label = record[3]
partitionSize += 1
binWeight += weight
overallTatalScore += weight * score
if label == 1:
truePositive += weight
binPositive += weight
binTotalScore += score * weight
elif label == 0:
falsePositive += weight
if partitionSize % shardSize == 0 or partitionSize == dataSize:
recall = (truePositive / totalConditionPositive) if totalConditionPositive > 0 else 0.0
fallout = (falsePositive / totalConditionNegative) if totalConditionPositive > 0 else 0.0
precision = truePositive / (truePositive + falsePositive)
meanPctr = binTotalScore / binWeight
eCtr = binPositive / binWeight
rocPoints += [(fallout, recall)]
prPoints += [(recall, precision)]
corrPoints += [(eCtr, meanPctr)]
cutoff += [(score, recall, precision, fallout)]
binWeight = 0.0
binTotalScore = 0.0
binPositive = 0.0
rocPoints = sorted(rocPoints, key=lambda x: x[0])
prPoints = sorted(prPoints, key=lambda x: x[0])
corrPoints = sorted(corrPoints, key=lambda x: x[0])
cutoff = sorted(cutoff, key=lambda x: x[0])
def calculateAUC(rocPoints):
AUC = 0.0
lastPoint = (0, 0)
for point in rocPoints:
AUC += (point[1] + lastPoint[1]) * (point[0] - lastPoint[0]) / 2.0
lastPoint = point
return AUC
AUC = calculateAUC(rocPoints)
OER = truePositive / overallTatalScore #Observed Expected Ratio
F1 = 2 * truePositive / (truePositive + falsePositive + totalConditionPositive)
print('%s AUC: %f' % (model, AUC))
print('%s F1: %f' % (model, F1))
print('%s Observed/Expected Ratio: %f' % (model, OER))
if print_cutoff:
print('%s cutoff:' % model, cutoff)
return model, {
'ROC': rocPoints,
'PR': prPoints,
'CORR': corrPoints,
'AUC': AUC,
'OER': OER,
'F1': F1,
'cutoff': cutoff
}
def walktree(input):
"""
Returns a list of file paths to traverse given input (a file or directory name)
"""
if os.path.isfile(input):
return [input]
else:
fileNames = []
for root, dirs, files in os.walk(input):
fileNames += [os.path.join(root, f) for f in files]
return fileNames
class ROC(object):
def __init__(self,
args=None, # ArgumentParser args object, override all the below args if set
input_dirs = '',
phrase = 0,
sample = DEFAULT_SAMPLE,
shard_count = DEFAULT_SHART_COUNT,
buffer_size = DEFAULT_BUFFER_SIZE,
plot_size_rate = DEFAULT_PLOT_SIZE_RATE,
delimiter = DEFAULT_DELIMTER,
ignore_invalid = False,
use_mask = '',
tempdir = DEFAULT_TEMPDIR,
auc_select = False,
select_limit = 0,
verbose = False,
print_cutoff = False,
no_plot = False,
output_dir = OUTPUT_DIR,
cache_dir = ''
):
self.args = args
self.input_dirs = args.input_dirs if args else input_dirs
self.phrase = args.phrase if args else phrase
self.shard_count = args.shard_count if args else shard_count
self.sample = args.sample if args else sample
self.buffer_size = args.buffer_size if args else buffer_size
self.plot_size_rate = args.plot_size_rate if args else plot_size_rate
self.delimiter = args.delimiter if args else delimiter
self.ignore_invalid = args.ignore_invalid if args else ignore_invalid
self.use_mask = args.use_mask if args else use_mask
self.auc_select = args.auc_select if args else auc_select
self.select_limit = args.select_limit if args else select_limit
self.verbose = args.verbose if args else verbose
self.print_cutoff = args.print_cutoff if args else print_cutoff
self.tempdir = args.tempdir if args else tempdir
self.no_plot = args.no_plot if args else no_plot
self.cache_dir = args.cache_dir if args else cache_dir
self.merge_dir = os.path.join(self.cache_dir, MERGE_DIR)
self.sort_dir = os.path.join(self.cache_dir, SORT_DIR)
self.output_dir = args.output_dir if args else output_dir
def plotCurves(self, dataByModel):
"""
Plot ROC, PR and Correlation Curves by model.
"""
prFigure = pyplot.figure()
self.configChart()
prAx = prFigure.add_subplot(111)
prAx.set_xlabel('Recall')
prAx.set_ylabel('Precision')
prAx.set_title('PR Curve')
prAx.grid(True)
rocFigure = pyplot.figure()
self.configChart()
rocAx = rocFigure.add_subplot(111)
rocAx.set_xlabel('Fallout / FPR')
rocAx.set_ylabel('Recall')
rocAx.set_title('ROC Curve')
rocAx.grid(True)
corrFigure = pyplot.figure()
self.configChart()
corrAx = corrFigure.add_subplot(111)
corrAx.set_xlabel('predict score')
corrAx.set_ylabel('real score')
corrAx.set_title('Correlation Curve')
corrAx.grid(True)
precisionFigure = pyplot.figure()
self.configChart()
precisionAx = precisionFigure.add_subplot(111)
precisionAx.set_xlabel('score')
precisionAx.set_ylabel('Precision')
precisionAx.set_title('Threshold score vs precision')
precisionAx.grid(True)
recallFigure = pyplot.figure()
self.configChart()
recallAx = recallFigure.add_subplot(111)
recallAx.set_xlabel('score')
recallAx.set_ylabel('Recall')
recallAx.set_title('Threshold score vs recall')
recallAx.grid(True)
falloutFigure = pyplot.figure()
self.configChart()
falloutAx = falloutFigure.add_subplot(111)
falloutAx.set_xlabel('score')
falloutAx.set_ylabel('Fallout (False Positive Rate)')
falloutAx.set_title('Threshold score vs fallout')
falloutAx.grid(True)
for (model, data) in list(dataByModel.items()):
(recalls, precisions) = list(zip(*(data['PR'])))
prAx.plot(recalls, precisions, marker='o', linestyle='--', label=model)
(fallouts, recalls) = list(zip(*(data['ROC'])))
rocAx.plot(fallouts, recalls, marker='o', linestyle='--', label=model)
(pCtrs, eCtrs) = list(zip(*(data['CORR'])))
corrAx.plot(pCtrs, eCtrs, label=model)
(score, recall, precision, fallout) = list(zip(*(data['cutoff'])))
recallAx.plot(score, recall, label=model + '_recall')
precisionAx.plot(score, precision, label=model + '_precision')
falloutAx.plot(score, fallout, label=model + '_fallout')
# saving figures
ensure_dir(self.output_dir)
prAx.legend(loc='upper right', shadow=True)
prFigure.savefig('%s/pr_curve.png' % self.output_dir)
rocAx.legend(loc='lower right', shadow=True)
rocFigure.savefig('%s/roc_curve.png' % self.output_dir)
corrAx.legend(loc='upper left', shadow=True)
corrFigure.savefig('%s/corr_curve.png' % self.output_dir)
precisionAx.legend(loc='upper left', shadow=True)
precisionFigure.savefig('%s/precision.png' % self.output_dir)
recallAx.legend(loc='lower left', shadow=True)
recallFigure.savefig('%s/recall.png' % self.output_dir)
falloutAx.legend(loc='upper right', shadow=True)
falloutFigure.savefig('%s/fallout.png' % self.output_dir)
pyplot.close()
pngs = '{result}/pr_curve.png {result}/roc_curve.png {result}/corr_curve.png {result}/precision.png {result}/recall.png {result}/fallout.png'.format(result=self.output_dir)
print('png: ', pngs)
def groupDataByModel(self, input_dirs):
"""
Group data to separated file by model.
"""
t1 = time.time()
print("merging files by model to")
ensure_dir(self.merge_dir)
fileByModel = dict()
randomByModel = dict()
totalLineMerged = 0
for inputDir in input_dirs:
for file in walktree(inputDir):
for line in openFile(file):
fields = line.split(self.delimiter)
if self.ignore_invalid:
if len(fields) != 4 or fields[0] == '' or fields[
1] == '' or fields[2] == '' or fields[3] == '':
print('Ingonre Invalid line', fields)
continue
model = fields[0]
if model not in fileByModel:
fileByModel[model] = open('%s/%s.txt' % (self.merge_dir, model), 'w')
randomByModel[model] = random.Random()
if self.sample >= 1.0 or randomByModel[model].random() < self.sample:
fileByModel[model].write(line)
totalLineMerged += 1
for file in list(fileByModel.values()):
file.close()
t2 = time.time()
print('Total line proccessed {}'.format(totalLineMerged))
print("merging files take %ss" % (t2 - t1))
if self.use_mask:
fileByModel = self.removeMaskData(fileByModel)
return fileByModel
def removeMaskData(self, dataByName):
toRemoveList = []
masks = self.use_mask.split(',')
for mask in masks:
for name in dataByName.keys():
if mask.endswith('*'):
if name.startswith(mask[:-1]):
print('remove %s because of filter:%s' % (name, mask))
toRemoveList.append(name)
else:
if name == mask:
print('remove %s because of filter:%s' % (name, mask))
toRemoveList.append(name)
for removeName in toRemoveList:
del dataByName[removeName]
return dataByName
def loadFileNameByModel(self, inputDir):
"""
Load the file names from a directory. Use to restart the process from a given phrase.
"""
fileNames = walktree(inputDir)
fileByModel = {}
for file in fileNames:
modelName = file.split('/')[-1]
modelName = modelName.replace('.txt', '')
fileByModel[modelName] = file
return fileByModel
def sortDataFileByModel(self, fileByModel):
"""
Use external sort to sort data file by score column.
"""
t1 = time.time()
print("sorting files....")
ensure_dir(self.sort_dir)
processPool = []
for model in list(fileByModel.keys()):
mergedFile = '%s/%s.txt' % (self.merge_dir, model)
sortedFile = '%s/%s.txt' % (self.sort_dir, model)
if self.ignore_invalid:
key = eval('lambda l: -float(l.split("' + self.delimiter +
'")[2] or 0.0)')
else:
key = eval('lambda l: -float(l.split("' + self.delimiter +
'")[2])')
process = Process(target=batchSort, args=(mergedFile, sortedFile, key, self.buffer_size, self.tempdir))
process.start()
processPool.append(process)
for process in processPool:
process.join()
t2 = time.time()
print("sorting files take %ss" % (t2 - t1))
def processDataByModel(self, fileByModel):
"""
Process data by model. Wait all the subprocess finish then plot curves together.
"""
t1 = time.time()
print("processing data....")
pool = Pool(len(fileByModel))
dataByModel = dict()
resultList = []
for model in list(fileByModel.keys()):
sortedFile = '%s/%s.txt' % (self.sort_dir, model)
result = pool.apply_async(computeMetrics, args=(model, sortedFile, self.shard_count, self.delimiter, self.print_cutoff))
resultList.append(result)
for result in resultList:
try:
(model, data) = result.get()
dataByModel[model] = data
except Exception as e:
if not self.ignore_invalid:
raise e
t2 = time.time()
if self.auc_select:
select_limit = self.select_limit
print('Sort model by AUC and select top', select_limit)
sortedModelTuple = sorted(list(dataByModel.items()),
key=lambda item: item[1]['AUC'],
reverse=True)
dataByModel = dict(sortedModelTuple[:select_limit])
if self.verbose:
print(dataByModel)
ensure_dir(self.output_dir)
pickle.dump(dataByModel, open(os.path.join(self.output_dir, DATA_PICKLE), 'wb'))
print("processing data take %ss" % (t2 - t1))
return dataByModel
def configChart(self):
cf = pylab.gcf()
defaultSize = cf.get_size_inches()
plotSizeXRate = self.plot_size_rate
plotSizeYRate = self.plot_size_rate
cf.set_size_inches(
(defaultSize[0] * plotSizeXRate, defaultSize[1] * plotSizeYRate))
def loadProcessedDataByModel(self):
return pickle.load(open(os.path.join(self.output_dir, DATA_PICKLE), 'rb'))
def process(self):
phrase = self.phrase
if phrase == PHRASE_GROUP:
fileByModel = self.groupDataByModel(self.input_dirs)
if self.verbose:
print(fileByModel)
phrase = PHRASE_GROUP + 1
else:
fileByModel = self.loadFileNameByModel(self.merge_dir)
if phrase == PHRASE_SORT:
self.sortDataFileByModel(fileByModel)
phrase = PHRASE_SORT + 1
else:
fileByModel = self.loadFileNameByModel(self.sort_dir)
if phrase == PHRASE_PROCESS:
dataByModel = self.processDataByModel(fileByModel)
phrase = PHRASE_PROCESS + 1
else:
dataByModel = self.loadProcessedDataByModel()
if not self.no_plot:
self.plotCurves(dataByModel)
return dataByModel
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'input_dirs',
nargs='+',
help=
'Input format: CSV by --delimiter: len(rocord)==4. Ex: modelId, weight, score, label'
)
parser.add_argument('-p',
'--phrase',
dest='phrase',
default=0,
type=int,
help='Start phrase. 0 : Group, 1 : Sort, 2 : Process, 3 : Chart')
parser.add_argument('-d',
'--delimiter',
dest='delimiter',
default=DEFAULT_DELIMTER,
help='CSV field delimiter. Default is \\x01')
parser.add_argument(
'-s',
'--shard',
dest='shard_count',
default=DEFAULT_SHART_COUNT,
type=int,
help=
'Shard count. Specify how many data point to generate for plotting. default is 100'
)
parser.add_argument(
'--sample',
dest='sample',
default=DEFAULT_SAMPLE,
type=float,
help=
'Record sample rate. Specify how much percentage of records to keep per model.'
)
parser.add_argument('-b',
'--buffer',
dest='buffer_size',
default=DEFAULT_BUFFER_SIZE,
type=int,
help='buffer_size to use for sorting, default is 32000')
parser.add_argument('-i',
'--ignore_invalid',
action='store_true',
help='Ignore invalid in thread')
parser.add_argument('-r',
'--rate',
type=float,
dest='plot_size_rate',
default=DEFAULT_PLOT_SIZE_RATE,
help='Chart size rate. default 2')
parser.add_argument(
'--mask',
dest='use_mask',
default='',
help=
'mask certain data. Ex \'metric_nus*,metric_supply*\'. Will remove data collection label start with \'metric_nus and metric_supply\''
)
parser.add_argument(
'--tmp',
dest='tempdir',
default=DEFAULT_TEMPDIR,
help= 'Tmp dir path'
)
parser.add_argument('--auc_select',
dest='auc_select',
action='store_true',
help='Select top n=select_limit roc curve by roc AUC')
parser.add_argument('--select_limit',
dest='select_limit',
default=0,
type=int,
help='Select top n model')
parser.add_argument('-v',
'--verbose',
action='store_true',
help='Be verbose')
parser.add_argument('--print-cutoff',
dest='print_cutoff',
action='store_true',
help='print cutoff')
parser.add_argument('--no-plot',
dest='no_plot',
action='store_true',
help='do not plot')
parser.add_argument('--output-dir',
dest='output_dir',
default=OUTPUT_DIR,
help='output data dir')
parser.add_argument('--cache-dir',
dest='cache_dir',
default='',
help='cache data dir')
args = parser.parse_args()
print('Args:', args)
roc = ROC(args)
roc.process()
if __name__ == '__main__':
main() | /roc-tools-0.3.0.tar.gz/roc-tools-0.3.0/roc_tools/roc.py | 0.431584 | 0.159414 | roc.py | pypi |
import numpy as np
def resample_data(*arrays, **kwargs):
"""
Similar to sklearn's resample function, with a few more extras.
arrays: Arrays with consistent first dimension.
kwargs:
replace: Sample with replacement. Default: True
n_samples: Number of samples. Default: len(arrays[0])
frac: Compute the number of samples as a fraction of the
array length: n_samples=frac*len(arrays[0])
Overrides the value for n_samples if provided.
random_state: Determines the random number generation. Can be None,
an int or np.random.RandomState. Default: None
stratify: An iterable containing the class labels by which the
the arrays should be stratified. Default: None
axis: Sampling axis. Note: axis!=0 is slow! Also, stratify
is currently not supported if axis!=0. Default: axis=0
squeeze: Flatten the output array if only one array is provided.
Default: Trues
"""
def _resample(*arrays, replace, n_samples, stratify, rng, axis=0):
lens = [x.shape[axis] for x in arrays]
equal_length = (lens.count(lens[0]) == len(lens))
if not equal_length:
msg = "Input arrays don't have equal length: %s"
raise ValueError(msg % lens)
if stratify is not None:
msg = "Stratification is not supported yet."
raise ValueError(msg)
if not isinstance(rng, np.random.RandomState):
rng = np.random.RandomState(rng)
n = lens[0]
if replace:
indices = rng.randint(0, n, n_samples)
else:
indices = rng.choice(np.arange(0, n), n_samples)
# Sampling along an axis!=0 is not very clever.
arrays = [x.take(indices, axis=axis) for x in arrays]
# Flatten the output if only one input array was provided.
return arrays if len(arrays) > 1 else arrays[0]
try:
from sklearn.utils import resample
has_sklearn = True
except ModuleNotFoundError:
has_sklearn = False
replace = kwargs.pop("replace", True)
n_samples = kwargs.pop("n_samples", None)
frac = kwargs.pop("frac", None)
rng = kwargs.pop("random_state", None)
stratify = kwargs.pop("stratify", None)
squeeze = kwargs.pop("squeeze", True)
axis = kwargs.pop("axis", 0)
if kwargs:
msg = "Received unexpected argument(s): %s" % kwargs
raise ValueError(msg)
arrays = [np.asarray(x) if not hasattr(x, "shape") else x for x in arrays]
lens = [x.shape[axis] for x in arrays]
if frac:
n_samples = int(np.round(frac * lens[0]))
if n_samples is None:
n_samples = lens[0]
if axis > 0 or not has_sklearn:
ret = _resample(*arrays, replace=replace, n_samples=n_samples,
stratify=stratify, rng=rng, axis=axis)
else:
ret = resample(*arrays,
replace=replace,
n_samples=n_samples,
stratify=stratify,
random_state=rng,)
# Undo the squeezing, which is done by resample (and _resample).
if not squeeze and len(arrays) == 1:
ret = [ret]
return ret | /roc_utils-0.2.2-py3-none-any.whl/roc_utils/_sampling.py | 0.600071 | 0.703537 | _sampling.py | pypi |
import numpy as np
from ._roc import (compute_roc,
compute_mean_roc,
compute_roc_bootstrap,
_DEFAULT_OBJECTIVE)
def plot_roc(roc,
color="red",
label=None,
show_opt=False,
show_details=False,
format_axes=True,
ax=None,
**kwargs):
"""
Plot the ROC curve given the output of compute_roc.
Arguments:
roc: Output of compute_roc() with the following keys:
- fpr: false positive rates fpr(thr)
- tpr: true positive rates tpr(thr)
- opd: optimal point(s).
- inv: true if predictor is inverted (predicts ~y)
label: Label used for legend.
show_opt: Show optimal point.
show_details: Show additional information.
format_axes: Apply axes settings, show legend, etc.
kwargs: A dictionary with detail settings not exposed
explicitly in the function signature. The following
options are available:
- zorder:
- legend_out: Place legend outside (default: False)
- legend_label_inv: Use 1-AUC if roc.inv=True (True)
Additional kwargs are forwarded to ax.plot().
"""
import matplotlib.pyplot as plt
import matplotlib.colors as mplc
def _format_axes(loc, margin):
ax.axis("square")
ax.set_xlim([0 - margin, 1. + margin])
ax.set_ylim([0 - margin, 1. + margin])
ax.set_xlabel("FPR (false positive rate)")
ax.set_ylabel("TPR (true positive rate)")
ax.grid(True)
if legend_out:
ax.legend(loc=loc,
bbox_to_anchor=(1.05, 1),
borderaxespad=0.)
else:
ax.legend(loc=loc)
def _plot_opt_point(key, opt, color, marker, zorder, label, ax):
# Some objectives can be visualized.
# Plot these optional things first.
if key == "minopt":
ax.plot([0, opt.opp[0]], [1, opt.opp[1]], ":ok",
alpha=0.3,
zorder=zorder + 1)
if key == "minoptsym":
d2_ul = (opt.opp[0]-0)**2+(opt.opp[1]-1)**2
d2_ll = (opt.opp[0]-1)**2+(opt.opp[1]-0)**2
ref = (0, 1) if (d2_ul < d2_ll) else (1, 0)
ax.plot([ref[0], opt.opp[0]], [ref[1], opt.opp[1]], ":ok",
alpha=0.3,
zorder=zorder + 1)
if key == "youden":
# Vertical line between optimal point and diagonal.
ax.plot([opt.opp[0], opt.opp[0]],
[opt.opp[0], opt.opp[1]],
color=color,
zorder=zorder + 1)
if key == "cost":
# Line parallel to diagonal (shrunk by m if m≠1).
ax.plot(opt.opq[0], opt.opq[1], ":k",
alpha=0.3,
zorder=zorder + 1)
if key == "concordance":
# Rectangle illustrating the area tpr*(1-fpr)
from matplotlib import patches
ll = [opt.opp[0], 0]
w = 1 - opt.opp[0]
h = opt.opp[1]
rect = patches.Rectangle(ll, w, h,
facecolor=color,
alpha=0.2,
zorder=zorder + 1)
ax.add_patch(rect)
face_color = mplc.to_rgba(color, alpha=0.3)
ax.plot(opt.opp[0], opt.opp[1],
linestyle="None",
marker=marker,
markerfacecolor=face_color,
markeredgecolor=color,
label=label,
zorder=zorder + 3)
if ax is None:
ax = plt.gca()
# Copy the kwargs (a shallow copy should be sufficient).
# Set some defaults.
label = label if label else "Feature"
zorder = kwargs.pop("zorder", 1)
legend_out = kwargs.pop("legend_out", False)
legend_label_inv = kwargs.pop("legend_label_inv", True)
if legend_label_inv:
auc_disp, auc_val = "1-AUC" if roc.inv else "AUC", roc.auc
else:
auc_disp, auc_val = "AUC", roc.auc
label = "%s (%s=%.3f)" % (label, auc_disp, auc_val)
# Plot the ROC curve.
ax.plot(
roc.fpr,
roc.tpr,
color=color,
zorder=zorder + 2,
label=label,
**kwargs)
# Plot the no-discrimination line.
label_diag = "No discrimination" if show_details else None
ax.plot([0, 1], [0, 1], ":k", label=label_diag,
zorder=zorder, linewidth=1)
# Visualize the optimal point.
if show_opt:
from itertools import cycle
markers = cycle(["o", "*", "^", "s", "P", "D"])
for key, opt in roc.opd.items():
pa_str = (", PA=%.3f" % opt.opa) if opt.opa else ""
if show_details:
legend_entry_opt = ("Optimal point (%s, thr=%.3g%s)"
% (key, opt.opt, pa_str))
else:
legend_entry_opt = "Optimal point (thr=%.3g)" % opt.opt
_plot_opt_point(key=key, opt=opt, color=color,
marker=next(markers), zorder=zorder,
label=legend_entry_opt, ax=ax)
if format_axes:
margin = 0.02
loc = "upper left" if (roc.inv or legend_out) else "lower right"
_format_axes(loc=loc, margin=margin)
def plot_mean_roc(rocs, auto_flip=True, show_all=False, ax=None, **kwargs):
"""
Compute and plot the mean ROC curve for a sequence of ROC containers.
rocs: List of ROC containers created by compute_roc().
auto_flip: See compute_roc(), applies only to mean ROC curve.
show_all: If True, show the single ROC curves.
If an integer, show the rocs[:show_all] roc curves.
show_ci: Show confidence interval
show_ti: Show tolerance interval
kwargs: Forwarded to plot_roc(), applies only to mean ROC curve.
Optional kwargs argument show_opt can be either False, True or a string
specifying the particular objective function to be used to plot the
optimal point. See get_objective() for details. Default choice is the
"minopt" objective.
"""
import matplotlib.pyplot as plt
if ax is None:
ax = plt.gca()
n_samples = len(rocs)
# Some default values.
zorder = kwargs.get("zorder", 1)
label = kwargs.pop("label", "Mean ROC curve")
# kwargs for plot_roc()...
show_details = kwargs.get("show_details", False)
show_opt = kwargs.pop("show_opt", False)
show_ti = kwargs.pop("show_ti", True)
show_ci = kwargs.pop("show_ci", True)
color = kwargs.pop("color", "red")
is_opt_str = isinstance(show_opt, (str, list, tuple))
# Defaults for mean-ROC.
resolution = kwargs.pop("resolution", 101)
objective = show_opt if is_opt_str else _DEFAULT_OBJECTIVE
# Compute average ROC.
ret_mean = compute_mean_roc(rocs=rocs,
resolution=resolution,
auto_flip=auto_flip,
objective=objective)
# Plot ROC curve for single bootstrap samples.
if show_all:
def isint(x):
return isinstance(x, int) and not isinstance(x, bool)
n_loops = show_all if isint(show_all) else np.inf
n_loops = min(n_loops, len(rocs))
for ret in rocs[:n_loops]:
ax.plot(ret.fpr, ret.tpr,
color="gray",
alpha=0.2,
zorder=zorder + 2)
if show_ti:
# 95% interval
tpr_sort = np.sort(ret_mean.tpr_all, axis=0)
tpr_lower = tpr_sort[int(0.025 * n_samples), :]
tpr_upper = tpr_sort[int(0.975 * n_samples), :]
label_int = "95% of all samples" if show_details else None
ax.fill_between(ret_mean.fpr, tpr_lower, tpr_upper,
color="gray", alpha=.2,
label=label_int,
zorder=zorder + 1)
if show_ci:
# 95% confidence interval
tpr_std = np.std(ret_mean.tpr_all, axis=0, ddof=1)
tpr_lower = ret_mean.tpr - 1.96 * tpr_std / np.sqrt(n_samples)
tpr_upper = ret_mean.tpr + 1.96 * tpr_std / np.sqrt(n_samples)
label_ci = "95% CI of mean curve" if show_details else None
ax.fill_between(ret_mean.fpr, tpr_lower, tpr_upper,
color=color, alpha=.3,
label=label_ci,
zorder=zorder)
# Last but not least, plot the average ROC curve on top of everything.
plot_roc(roc=ret_mean, label=label, show_opt=show_opt,
color=color, ax=ax, zorder=zorder + 3, **kwargs)
return ret_mean
def plot_roc_simple(X, y, pos_label, auto_flip=True,
title=None, ax=None, **kwargs):
"""
Compute and plot the receiver-operator characteristic curve for X and y.
kwargs are forwarded to plot_roc(), see there for details.
Optional kwargs argument show_opt can be either False, True or a string
specifying the particular objective function to be used to plot the
optimal point. See get_objective() for details. Default choice is the
"minopt" objective.
"""
import matplotlib.pyplot as plt
if ax is None:
ax = plt.gca()
show_opt = kwargs.pop("show_opt", False)
is_opt_str = isinstance(show_opt, (str, list, tuple))
objective = show_opt if is_opt_str else _DEFAULT_OBJECTIVE
ret = compute_roc(X=X, y=y, pos_label=pos_label,
objective=objective,
auto_flip=auto_flip)
plot_roc(roc=ret, show_opt=show_opt, ax=ax, **kwargs)
title = "ROC curve" if title is None else title
ax.get_figure().suptitle(title)
return ret
def plot_roc_bootstrap(X, y, pos_label,
objective=_DEFAULT_OBJECTIVE,
auto_flip=True,
n_bootstrap=100,
random_state=None,
stratified=False,
show_boots=False,
title=None,
ax=None,
**kwargs):
"""
Similar as plot_roc_simple(), but estimate an average ROC curve from
multiple bootstrap samples.
See compute_roc_bootstrap() for the meaning of the arguments.
Optional kwargs argument show_opt can be either False, True or a string
specifying the particular objective function to be used to plot the
optimal point. See get_objective() for details. Default choice is the
"minopt" objective.
"""
import matplotlib.pyplot as plt
if ax is None:
ax = plt.gca()
# 1) Collect the data.
rocs = compute_roc_bootstrap(X=X, y=y,
pos_label=pos_label,
objective=objective,
auto_flip=auto_flip,
n_bootstrap=n_bootstrap,
random_state=random_state,
stratified=stratified,
return_mean=False)
# 2) Plot the average ROC curve.
ret_mean = plot_mean_roc(rocs=rocs, auto_flip=auto_flip,
show_all=show_boots, ax=ax, **kwargs)
title = "ROC curve" if title is None else title
ax.get_figure().suptitle(title)
ax.set_title("Bootstrap reps: %d, sample size: %d" %
(n_bootstrap, len(y)), fontsize=10)
return ret_mean | /roc_utils-0.2.2-py3-none-any.whl/roc_utils/_plot.py | 0.856302 | 0.521106 | _plot.py | pypi |
import warnings
import numpy as np
import pandas as pd
from scipy import interp
from ._stats import mean_intervals
from ._types import StructContainer
from ._sampling import resample_data
_DEFAULT_OBJECTIVE = "minoptsym"
def get_objective(objective=_DEFAULT_OBJECTIVE, **kwargs):
"""
The function returns a callable computing a cost f(fpr(c), tpr(c))
as a function of a cut-off/threshold c. The cost function is used to
identify an optimal cut-off c* which maximizes this cost function.
Explanations:
fpr: false positive rate == 1 - specificity
tpr: true positive rate (recall, sensitivity)
The diagonal fpr(c)=tpr(c) corresponds to a (diagnostic) test that
gives the same proportion of positive results for groups with and
without the condition being true. A perfect test is characterized
by fpr(c*)=0 and tpr(c*)=1 at the optimal cut-off c*, where there
are no false negatives (tpr=1) and no false positives (fpr=0).
The prevalence is the ratio between the cases for which the condition
is true and the total population:
prevalence = (tp+fn)/(tp+tn+fp+fn)
Available objectives:
minopt: Computes the distance from the optimal point (0,1).
J = sqrt((1-specitivity)^2 + (1-sensitivity)^2)
J = sqrt(fpr^2 + (1-tpr)^2)
minoptsym: Similar as "minopt", but takes the smaller of the distances
from points (0,1) and (1,0). This makes sense for a
"inverted" predictor whose ROC curve is mainly under the
diagonal.
youden: Computes Youden's J statistic (also called Youden's index).
J = sensitivity + specitivity - 1
= tpr - fpr
Youden's index summarizes the performance of a diagnostic
test that is 1 for a perfect test (fpr=0, tpr=1) and 0 for
a perfectly useless test (where fpr=tpr). See also the
explanations above.
Youden's index can be visualized as the distance from the
diagonal in vertical direction.
cost: Maximizes the distance from the diagonal fpr==tpr.
Principally, it is possible to apply particular costs
for the four possible outcomes of a diagnostic tests (tp,
tn, fp, fn). With C0 being the fixed costs, the C_tp the
cost associated with a true positive and P(tp) the
proportion of TP's in the population, and so on:
C = (C0 + C_tp*P(tp) + C_tn*P(tn)
+ C_fp*P(fp) + C_fn*P(fn))
It can be shown (Metz 1978) that the slope of the ROC curve
at the optimal cutoff value is
m = (1-prevalence)/prevalence * (C_fp-C_tn)/(C_fn-C_tp)
Zweig and Campbell (1993) showed that the point along the
ROC curve where the average cost is minimum corresponds to
the cutoff value where fm is maximized:
J = fm = tpr - m*fpr
For m=1, the cost reduces to Youden's index.
concordance: Another objective that summarizes the diagnostic
performance of a test.
J = sensitivity * specitivity
J = tpr * (1-fpr)
The objective is 0 (minimal) if either (1-fpr) or tpr
are 0, and it is 1 (maximal) if tpr=1 and fpr=0.
The concordance can be visualized as the rectangular
formed by tpr and (1-fpr).
lr+, plr: Positive likelihood ratio (LR+):
J = tpr / fpr
lr-, nlr: Negative likelihood ratio (LR-):
J = fnr / tnr
J = (1-tpr) / (1-fpr)
dor: Diagnostic odds ratio:
J = LR+/LR-
J = (tpr / fpr) * ((1-fpr) / (1-tpr))
J = tpr*(1-fpr) / (fpr*(1-tpr))
chi2: An objective proposed by Miller and Siegmund in 1982.
The optimal cut-off c* maximizes the standard chi-square
statistic with one degree of freedom.
J = (tpr-fpr)^2 /
( (P*tpr+N*fpr) / (P+N) *
(1 - (P*tpr+N*fpr) / (P+N)) *
(1/P+1/N)
)
where P and N are the number of positive and negative
observations respectively.
acc: Prediction accuracy:
J = (TP+TN)/(P+N)
= (P*tpr+N*tnr)/(P+N)
= (P*tpr+N*(1-fpr))/(P+N)
cohen: Cohen kappa ("agreement") between x and y.
The goal is to find a threshold thr that binarizes the
predictor x such that it maximizes the agreement between
observed rater y and that binarized predictor.
This function evaluates rather slowly.
contingency = [ [TP, FP], [FN, TN]]
contingency = [[tpr*P, fpr*N], [(1-tpr)*P, (1-fpr)*N]]
J = cohens_kappa(contingency)
"cost" with m=1, "youden" and "minopt" likely are equivalent in most of
the cases.
More about cost functions:
NCSS Statistical Software: One ROC Curve and Cutoff Analysis:
https://www.ncss.com/software/ncss/ncss-documentation/#ROCCurves
Wikipedia: Sensitivity and specificity
https://en.wikipedia.org/wiki/Sensitivity_and_specificity
Youden's J statistic
https://en.wikipedia.org/wiki/Youden%27s_J_statistic
Rota, Antolini (2014). Finding the optimal cut-point for Gaussian
and Gamma distributed biomarkers.
http://doi.org/10.1016/j.csda.2013.07.015
Unal (2017). Defining an Optimal Cut-Point Value in ROC
Analysis: An Alternative Approach.
http://doi.org/10.1155/2017/3762651
Miller, Siegmund (1982). Maximally Selected Chi Square Statistics.
http://doi.org/10.2307/2529881
"""
objective = objective.lower()
if objective == "minopt":
# Take negative distance for maximization.
def J(fpr, tpr):
return -np.sqrt(fpr**2 + (1 - tpr)**2)
elif objective == "minoptsym":
# Same as minopt, except that it takes the smaller of
# the distances from points (0,1) or (1,0).
def J(fpr, tpr):
return -min(np.sqrt(fpr**2 + (1 - tpr)**2),
np.sqrt((1 - fpr)**2 + tpr**2))
elif objective == "youden":
def J(fpr, tpr):
return tpr - fpr
elif objective == "cost":
# Assignment cost ratio, see reference below.
# It is possible to pass a value for m. Default choice: 1.
m = kwargs.get("m", 1.)
def J(fpr, tpr):
return tpr - m * fpr
elif objective == "hesse":
# This function is roughly redundant to "cost".
# Distance function from diagonal (Hesse normal form)
# See also: https://ch.mathworks.com/help/stats/perfcurve.html
m = 1 # Assignment cost ratio, see reference below.
def J(fpr, tpr):
return np.abs(m * fpr - tpr) / np.sqrt(m * m + 1)
elif objective in ("plr", "lr+", "positivelikelihoodratio"):
def J(fpr, tpr):
return tpr / fpr if fpr > 0 else -1
elif objective in ("nlr", "lr-", "negativelikelihoodratio"):
def J(fpr, tpr):
return -(1 - tpr) / (1 - fpr) if fpr < 1 else -1
elif objective == "dor":
def J(fpr, tpr):
return ((tpr * (1 - fpr) / (fpr * (1 - tpr)))
if fpr > 0 and tpr < 1 else -1)
elif objective == "concordance":
def J(fpr, tpr):
return tpr * (1 - fpr)
elif objective == "chi2":
# N: number of negative observations.
# P: number of positive observations.
assert("N" in kwargs)
assert("P" in kwargs)
N = kwargs["N"]
P = kwargs["P"]
assert(N > 0 and P > 0)
def fun(fpr, tpr):
if (P * tpr + N * fpr) == 0:
return -1
if (1 - (P * tpr + N * fpr) / (P + N)) == 0:
return -1
return ((tpr - fpr)**2 /
(P * tpr + N * fpr) / (P + N) *
(1 - (P * tpr + N * fpr) / (P + N)) *
(1 / P + 1 / N))
J = fun
elif objective == "acc":
# N: number of negative observations.
# P: number of positive observations.
assert("N" in kwargs)
assert("P" in kwargs)
N = kwargs["N"]
P = kwargs["P"]
def J(fpr, tpr):
return (P * tpr + N * (1 - fpr)) / (P + N)
elif objective == "cohen":
# N: number of negative observations.
# P: number of positive observations.
assert("N" in kwargs)
assert("P" in kwargs)
N = kwargs["N"]
P = kwargs["P"]
def fun(fpr, tpr):
from statsmodels.stats.inter_rater import cohens_kappa
contingency = [[(1 - fpr) * N, (1 - tpr) * P],
[fpr * N, tpr * P]]
with warnings.catch_warnings():
warnings.filterwarnings("ignore",
message="invalid value encountered",
category=RuntimeWarning)
# Degenerate cases are not nicely handled by statsmodels.
# https://github.com/statsmodels/statsmodels/issues/5530
return cohens_kappa(contingency)["kappa"]
J = fun
else:
assert(False)
return J
def compute_roc(X, y, pos_label=True,
objective=_DEFAULT_OBJECTIVE,
auto_flip=False):
"""
Compute receiver-operator characteristics for a 1D dataset.
The ROC curve compares the false positive rate (FPR) with true positive
rate (TPR) for different classifier thresholds. It is a parametrized curve,
with the classification threshold being the parameter.
One can draw the ROC curve with the output of the ROC analysis.
roc: x=fpr(thr), y=ypr(thr), where thr is the curve parameter
Parameter thr varies from min(data) to max(data).
In the context of machine learning, data often represents classification
probabilities, but it can also be used for any metric data to discriminate
between two classes.
Note: The discrimination operation for binary classification is x>thr.
In case the operation is rather x<thr, the ROC curve is simply
mirrored along the diagonal fpr=tpr. The computation of the area
under curve (AUC) takes this into account and returns the maximum
auc = max(area(fpr,tpr), area(tpr,fpr))
Arguments:
X: The data, pd.Series, a np.ndarray (1D) or a list
y: The true labels of the data
pos_label: The value of the positive label
objective: Identifier for the cost function (see get_objective()),
can also be a list of identifiers
auto_flip: Set True if an inverted predictor should be flipped
automatically upon detection, which will set the
roc.inv flag to True. Better approach: switch the
pos_label explicitly.
Returns:
roc: A struct consisting of the following elements:
- fpr: false positive rate (the "x-vals")
- tpr: true positive rate (the "y-vals")
- thr: thresholds
- auc: area under curve
- opd: optimal point(s)
- inv: True if inverted predictor was detected (auto_flip)
For every specified objective, the opd dictionary
contains a struct with the following fields:
- ind: index of optimal threshold
- opt: the optimal threshold: thr[ind]
- opp: the optimal point: (fpr[ind], tpr[ind])
- opa: the optimal pred. accuracy (tp+tn)/(len(X))
- opq: cost line through optimal point
"""
if isinstance(X, (pd.DataFrame, pd.Series)):
X = X.values # ndarray-like numpy array
else:
# Assuming an np.ndarray or anything that naturally can be converted
# into an np.ndarray
X = np.array(X)
if isinstance(y, (pd.DataFrame, pd.Series)):
y = y.values
else:
y = np.array(y)
# Ensure objective to be a list of strings.
objectives = [objective] if isinstance(objective, str) else objective
# Assert X and y are 1d.
assert(len(X.shape) == 1 or min(X.shape) == 1)
assert(len(y.shape) == 1 or min(y.shape) == 1)
X = X.flatten()
y = y.flatten()
# The number of labels must match the dimensions (axis is either 0 or 1).
assert(len(X) == len(y))
if pd.isna(X).any():
# msg = "NaNs found in data. Better remove with X[~np.isnan(X)]."
# warnings.warn(msg)
isnan = pd.isna(X)
X = X[~isnan]
y = y[~isnan]
if pd.isna(y).any():
raise RuntimeError("NaNs found in labels.")
# Convert y into boolean array.
y = (y == pos_label)
# Prepare the cost functions.
p = np.sum(y)
n = len(y) - p
costs = {o: get_objective(o, N=n, P=p) for o in objectives}
# Sort X, and organize the y with the same ordering.
i_sorted = X.argsort() # If y_pred = x>thr
# In case the discriminator is x<thr instead of x>thr, one could
# simply reverse the sorted values.
# Note: AUC compensates for this (it simply takes the maximum)
# i_sorted = X.argsort()[::-1] # If y_pred = x<thr
X_sorted = X[i_sorted]
y_sorted = y[i_sorted]
# Now the thresholds are simply the values d.
# Because the data has been sorted and it holds that...
# fp(thr) = sum(y(d>=thr)==0)
# tp(thr) = sum(y(d>=thr)==1)
# ...one can calculate fp and tp effectively using cumulative sums.
fp = n - np.cumsum(~y_sorted)
tp = p - np.cumsum(y_sorted)
fpr = fp[::-1] / float(n)
tpr = tp[::-1] / float(p)
thr = X_sorted[::-1]
# Remove duplicated thresholds!
# This fixes the rare case where X[i]-X[i+1]≈tol. np.unique(thr) will
# keep both X[i] and X[i+1], even though they are almost equal. If
# some subsequent rounding / cancellation happens, X[i] and X[i+1] might
# fall together, which will issue a warning compute_roc_aucopt()...
# We usually don't need this precision anyways, though the fix is hacky.
thr = thr.round(8)
# This fixes the issue described in compute_roc_aucopt.
thr, i_unique = np.unique(thr, return_index=True)
thr, i_unique = thr[::-1], i_unique[::-1]
fpr = fpr[i_unique]
tpr = tpr[i_unique]
# Finalize (closure).
thr = np.r_[np.inf, thr, -np.inf]
fpr = np.r_[0, fpr, 1]
tpr = np.r_[0, tpr, 1]
ret = compute_roc_aucopt(fpr=fpr,
tpr=tpr,
thr=thr,
X=X,
y=y,
costs=costs,
auto_flip=auto_flip)
return ret
def compute_roc_aucopt(fpr, tpr, thr, costs,
X=None, y=None, auto_flip=False):
"""
Given the false positive rates fpr(thr) and true positive rates tpr(thr)
evaluated for different thresholds thr, the AUC is computed by simple
integration.
Besides AUC, the optimal threshold is computed that maximizes some cost
criteria. Argument costs is expected to be a dictionary with the cost
type as key and a functor f(fpr, tpr) as value.
If X and y are provided (optional), the resulting prediction
accuracy is also computed for the optimal point.
The function returns a struct as described in compute_roc().
"""
# It's possible that the last element [-1] occurs more than once sometimes.
thr_no_last = np.delete(thr, np.argwhere(thr == thr[-1]))
if len(np.unique(thr_no_last)) != len(thr_no_last):
warnings.warn("thr should contain only unique values.")
# Assignment cost ratio, see reference below and get_objective().
m = 1
auc = np.trapz(x=fpr, y=tpr)
flipped = False
if auto_flip:
if auc < 0.5:
auc, flipped = 1 - auc, True # Mark as flipped.
fpr, tpr = tpr, fpr # Flip the data!
opd = {}
for cost_id, cost in costs.items():
# NOTE: The following evaluation is optimistic if x contains duplicated
# values! This is best seen in an example. Let's try to optimize
# the prediction accuracy acc=(TP+TN)/(T+P). Let x and y be
# x = 3 3 3 4 5 6
# y = F T T T T T.
# The optimal threshold is 3. It binarizes the data as follows,
# b = F F F T T T = x > 3
# y = F T T T T T => acc = 4/6
# However, the brute-force optimization permits to find a split
# in-between the duplicated values of x.
# o = F T T T T T
# y = F T T T T T => acc = 1.0
# NOTE: The effect of this optimism is negligible if the ordering of
# the outcome y for duplicated values in x is randomized. This
# is typically the case for natural data.
# If the "parametrization" thr does not contain equal points,
# the problem is not apparent.
costs = list(map(cost, fpr, tpr))
ind = np.argmax(costs)
opt = thr[ind]
if X is not None and y is not None:
# Prediction accuracy (if X available).
opa = sum((X > opt) == y) / float(len(X))
opa = (1 - opa) if flipped else opa
else:
opa = None
# Now that we got the index, flip back to extract the data.
if flipped:
fpr, tpr = tpr, fpr
# Characterize optimal point.
opo = costs[ind]
opp = (fpr[ind], tpr[ind])
q = tpr[ind] - m * fpr[ind]
opq = ((0, 1), (q, m + q))
opd[cost_id] = StructContainer(ind=ind, # index of optimal point
opt=opt, # optimal threshold
opp=opp, # optimal point (fpr*, tpr*)
opa=opa, # prediction accuracy
opo=opo, # objective value
opq=opq) # line through opt point
struct = StructContainer(fpr=fpr,
tpr=tpr,
thr=thr,
auc=auc,
opd=opd,
inv=flipped)
return struct
def compute_mean_roc(rocs,
resolution=101,
auto_flip=True,
objective=_DEFAULT_OBJECTIVE):
objectives = [objective] if isinstance(objective, str) else objective
# Initialize
fpr_mean = np.linspace(0, 1, resolution)
fpr_mean = np.insert(fpr_mean, 0, 0) # Insert a leading 0 (closure)
n_samples = len(rocs)
thr_all = np.zeros([n_samples, resolution + 1])
tpr_all = np.zeros([n_samples, resolution + 1])
auc_all = np.zeros(n_samples)
# Interpolate the curves to measure at fixed fpr.
# This is required to compute the mean ROC curve.
# Note: Although I'm optimistic, I'm not entirely
# sure if it is okay to interpolate thr too.
for i, ret in enumerate(rocs):
tpr_all[i, :] = interp(fpr_mean, ret.fpr, ret.tpr)
thr_all[i, :] = interp(fpr_mean, ret.fpr, ret.thr)
auc_all[i] = ret.auc
# Closure
tpr_all[i, [0, -1]] = ret.tpr[[0, -1]]
thr_all[i, [0, -1]] = ret.thr[[0, -1]]
thr_mean = np.mean(thr_all, axis=0)
tpr_mean = np.mean(tpr_all, axis=0)
# Compute performance/discriminability measures.
costs = {o: get_objective(o) for o in objectives}
ret_mean = compute_roc_aucopt(fpr=fpr_mean,
tpr=tpr_mean,
thr=thr_mean,
X=None,
y=None,
costs=costs,
auto_flip=auto_flip)
# Invert predictor only if enough evidence was found (-> mean).
if ret_mean.inv:
auc_all = 1 - auc_all
if n_samples > 1:
auc_mean, auc95_ci, auc95_ti = mean_intervals(auc_all, 0.95)
auc_std = np.std(auc_all)
else:
auc_mean = auc_all[0]
auc95_ci = auc_mean.copy()
auc95_ti = auc_mean.copy()
auc_std = np.zeros_like(auc_mean)
ret_mean["auc_mean"] = auc_mean
ret_mean["auc95_ci"] = auc95_ci
ret_mean["auc95_ti"] = auc95_ti
ret_mean["auc_std"] = auc_std
ret_mean["tpr_all"] = tpr_all
return ret_mean
def compute_roc_bootstrap(X, y, pos_label,
objective=_DEFAULT_OBJECTIVE,
auto_flip=False,
n_bootstrap=100,
random_state=None,
stratified=False,
return_mean=True):
"""
Estimate an average ROC using bootstrap sampling.
Arguments:
X: The data, pd.Series, a np.ndarray (1D) or a list
y: The true labels of the data
pos_label: See compute_roc()
objective: See compute_roc()
auto_flip: See compute_roc()
n_bootstrap: Number of bootstrap samples to generate.
random_state: None, integer or np.random.RandomState
stratified: Perform stratified sampling, which takes into account
the relative frequency of the labels. This ensures that
the samples always will have the same number of
positive and negative samples. Enable stratification
if the dataset is very imbalanced or small, such that
degenerate samples (with only positives or negatives)
will become more likely. Disabling this flag results
in a mean ROC curve that will appear smoother: the
single ROC curves per bootstrap sample show more
variation if the total number of positive and negative
samples varies, reducing the "jaggedness" of the
average curve. Default: False.
return_mean: Return only the aggregate ROC-curve instead of a list
of n_bootstrap ROC items.
Returns:
A list of roc objects (see compute_roc()) or
a roc object if return_mean=True.
"""
# n: number of samples
# k: number of classes
X = np.asarray(X)
y = np.asarray(y)
# n = len(X)
k = len(np.unique(y))
if not isinstance(random_state, np.random.RandomState):
random_state = np.random.RandomState(random_state)
results = []
# Collect the data. About bootstrapping:
# https://datascience.stackexchange.com/questions/14369/
for _ in range(n_bootstrap):
x_boot, y_boot = resample_data(X, y,
replace=True,
stratify=y if stratified else None,
random_state=random_state)
if len(np.unique(y_boot)) < k:
# Test for a (hopefully) rare enough situation.
msg = ("Not all classes are represented in current bootstrap "
"sample. Skipping it. If this problem occurs too often, "
"try stratified=True or operate with larger samples.")
warnings.warn(msg)
continue
ret = compute_roc(X=x_boot,
y=y_boot,
pos_label=pos_label,
objective=objective,
auto_flip=False)
results.append(ret)
if return_mean:
mean_roc = compute_mean_roc(rocs=results,
auto_flip=auto_flip,
objective=objective)
return mean_roc
return results | /roc_utils-0.2.2-py3-none-any.whl/roc_utils/_roc.py | 0.784897 | 0.503357 | _roc.py | pypi |
class StructContainer():
"""
Build a type that behaves similar to a struct.
Usage:
# Construction from named arguments.
settings = StructContainer(option1 = False,
option2 = True)
# Construction from dictionary.
settings = StructContainer({"option1": False,
"option2": True})
print(settings.option1)
settings.option2 = False
for k,v in settings.items():
print(k,v)
"""
def __init__(self, dictionary=None, **kwargs):
if dictionary is not None:
assert(isinstance(dictionary, (dict, StructContainer)))
self.__dict__.update(dictionary)
self.__dict__.update(kwargs)
def __iter__(self):
for i in self.__dict__:
yield i
def __getitem__(self, key):
return self.__dict__[key]
def __setitem__(self, key, value):
self.__dict__[key] = value
def __len__(self):
return sum(1 for k in self.keys())
def __repr__(self):
return "struct(**%s)" % str(self.__dict__)
def __str__(self):
return str(self.__dict__)
def items(self):
for k, v in self.__dict__.items():
if not k.startswith("_"):
yield (k, v)
def keys(self):
for k in self.__dict__:
if not k.startswith("_"):
yield k
def values(self):
for k, v in self.__dict__.items():
if not k.startswith("_"):
yield v
def update(self, data):
self.__dict__.update(data)
def asdict(self):
return dict(self.items())
def first(self):
# Assumption: __dict__ is ordered (python>=3.6).
key, value = next(self.items())
return key, value
def last(self):
# Assumption: __dict__ is ordered (python>=3.6).
# See also: https://stackoverflow.com/questions/58413076
key = list(self.keys())[-1]
return key, self[key]
def get(self, key, default=None):
return self.__dict__.get(key, default)
def setdefault(self, key, default=None):
return self.__dict__.setdefault(key, default) | /roc_utils-0.2.2-py3-none-any.whl/roc_utils/_types.py | 0.679072 | 0.33012 | _types.py | pypi |
# ROCC Client Library for Python
[](https://github.com/Sage-Bionetworks/rocc-client/releases)
[](https://github.com/Sage-Bionetworks/rocc-client)
[](https://github.com/Sage-Bionetworks/rocc-client)
[](https://pypi.org/project/rocc-client)
# Introduction
TBA
This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project:
- API version: 0.1.3
- Package version: 1.0.0
- Build package: org.openapitools.codegen.languages.PythonClientCodegen
For more information, please visit [https://Sage-Bionetworks.github.io/rocc-schemas](https://Sage-Bionetworks.github.io/rocc-schemas)
## Requirements.
Python 2.7 and 3.4+
## Installation & Usage
### pip install
If the python package is hosted on a repository, you can install directly using:
```sh
pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git
```
(you may need to run `pip` with root permission: `sudo pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git`)
Then import the package:
```python
import roccclient
```
### Setuptools
Install via [Setuptools](http://pypi.python.org/pypi/setuptools).
```sh
python setup.py install --user
```
(or `sudo python setup.py install` to install the package for all users)
Then import the package:
```python
import roccclient
```
## Getting Started
Please follow the [installation procedure](#installation--usage) and then run the following:
```python
from __future__ import print_function
import time
import roccclient
from roccclient.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to https://rocc.org/api/v1
# See configuration.py for a list of all supported configuration parameters.
configuration = roccclient.Configuration(
host = "https://rocc.org/api/v1"
)
# Enter a context with an instance of the API client
with roccclient.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = roccclient.ChallengeApi(api_client)
challenge = roccclient.Challenge() # Challenge |
try:
# Add a challenge
api_response = api_instance.create_challenge(challenge)
pprint(api_response)
except ApiException as e:
print("Exception when calling ChallengeApi->create_challenge: %s\n" % e)
```
## Documentation for API Endpoints
All URIs are relative to *https://rocc.org/api/v1*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*ChallengeApi* | [**create_challenge**](docs/ChallengeApi.md#create_challenge) | **POST** /challenges | Add a challenge
*ChallengeApi* | [**delete_challenge**](docs/ChallengeApi.md#delete_challenge) | **DELETE** /challenges/{challengeId} | Delete a challenge
*ChallengeApi* | [**get_challenge**](docs/ChallengeApi.md#get_challenge) | **GET** /challenges/{challengeId} | Get a challenge
*ChallengeApi* | [**list_challenges**](docs/ChallengeApi.md#list_challenges) | **GET** /challenges | List all the challenges
*GrantApi* | [**create_grant**](docs/GrantApi.md#create_grant) | **POST** /grants | Create a grant
*GrantApi* | [**delete_grant**](docs/GrantApi.md#delete_grant) | **DELETE** /grants/{grantId} | Delete a grant
*GrantApi* | [**get_grant**](docs/GrantApi.md#get_grant) | **GET** /grants/{grantId} | Get a grant
*GrantApi* | [**list_grants**](docs/GrantApi.md#list_grants) | **GET** /grants | Get all grants
*OrganizationApi* | [**create_organization**](docs/OrganizationApi.md#create_organization) | **POST** /organizations | Create an organization
*OrganizationApi* | [**delete_organization**](docs/OrganizationApi.md#delete_organization) | **DELETE** /organizations/{organizationId} | Delete an organization
*OrganizationApi* | [**get_organization**](docs/OrganizationApi.md#get_organization) | **GET** /organizations/{organizationId} | Get an organization
*OrganizationApi* | [**list_organizations**](docs/OrganizationApi.md#list_organizations) | **GET** /organizations | Get all organizations
*PersonApi* | [**create_person**](docs/PersonApi.md#create_person) | **POST** /persons | Create a person
*PersonApi* | [**delete_person**](docs/PersonApi.md#delete_person) | **DELETE** /persons/{personId} | Delete a person
*PersonApi* | [**get_person**](docs/PersonApi.md#get_person) | **GET** /persons/{personId} | Get a person
*PersonApi* | [**list_persons**](docs/PersonApi.md#list_persons) | **GET** /persons | Get all persons
*TagApi* | [**create_tag**](docs/TagApi.md#create_tag) | **POST** /tags | Create a tag
*TagApi* | [**delete_tag**](docs/TagApi.md#delete_tag) | **DELETE** /tags/{tagId} | Delete a tag
*TagApi* | [**get_tag**](docs/TagApi.md#get_tag) | **GET** /tags/{tagId} | Get a tag
*TagApi* | [**list_tags**](docs/TagApi.md#list_tags) | **GET** /tags | Get all tags
## Documentation For Models
- [Challenge](docs/Challenge.md)
- [ChallengeFilter](docs/ChallengeFilter.md)
- [ChallengeResults](docs/ChallengeResults.md)
- [ChallengeStatus](docs/ChallengeStatus.md)
- [Error](docs/Error.md)
- [Grant](docs/Grant.md)
- [Organization](docs/Organization.md)
- [PageOfChallenges](docs/PageOfChallenges.md)
- [PageOfChallengesAllOf](docs/PageOfChallengesAllOf.md)
- [PageOfGrants](docs/PageOfGrants.md)
- [PageOfGrantsAllOf](docs/PageOfGrantsAllOf.md)
- [PageOfOrganizations](docs/PageOfOrganizations.md)
- [PageOfOrganizationsAllOf](docs/PageOfOrganizationsAllOf.md)
- [PageOfPersons](docs/PageOfPersons.md)
- [PageOfPersonsAllOf](docs/PageOfPersonsAllOf.md)
- [PageOfTags](docs/PageOfTags.md)
- [PageOfTagsAllOf](docs/PageOfTagsAllOf.md)
- [Person](docs/Person.md)
- [PersonFilter](docs/PersonFilter.md)
- [ResponsePageMetadata](docs/ResponsePageMetadata.md)
- [ResponsePageMetadataLinks](docs/ResponsePageMetadataLinks.md)
- [Tag](docs/Tag.md)
- [TagFilter](docs/TagFilter.md)
## Documentation For Authorization
All endpoints do not require authorization.
## Author
thomas.schaffter@sagebionetworks.org
| /rocc-client-0.1.3.tar.gz/rocc-client-0.1.3/README.md | 0.442396 | 0.79999 | README.md | pypi |
import six
class OpenApiException(Exception):
"""The base exception class for all OpenAPIExceptions"""
class ApiTypeError(OpenApiException, TypeError):
def __init__(self, msg, path_to_item=None, valid_classes=None,
key_type=None):
""" Raises an exception for TypeErrors
Args:
msg (str): the exception message
Keyword Args:
path_to_item (list): a list of keys an indices to get to the
current_item
None if unset
valid_classes (tuple): the primitive classes that current item
should be an instance of
None if unset
key_type (bool): False if our value is a value in a dict
True if it is a key in a dict
False if our item is an item in a list
None if unset
"""
self.path_to_item = path_to_item
self.valid_classes = valid_classes
self.key_type = key_type
full_msg = msg
if path_to_item:
full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
super(ApiTypeError, self).__init__(full_msg)
class ApiValueError(OpenApiException, ValueError):
def __init__(self, msg, path_to_item=None):
"""
Args:
msg (str): the exception message
Keyword Args:
path_to_item (list) the path to the exception in the
received_data dict. None if unset
"""
self.path_to_item = path_to_item
full_msg = msg
if path_to_item:
full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
super(ApiValueError, self).__init__(full_msg)
class ApiAttributeError(OpenApiException, AttributeError):
def __init__(self, msg, path_to_item=None):
"""
Raised when an attribute reference or assignment fails.
Args:
msg (str): the exception message
Keyword Args:
path_to_item (None/list) the path to the exception in the
received_data dict
"""
self.path_to_item = path_to_item
full_msg = msg
if path_to_item:
full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
super(ApiAttributeError, self).__init__(full_msg)
class ApiKeyError(OpenApiException, KeyError):
def __init__(self, msg, path_to_item=None):
"""
Args:
msg (str): the exception message
Keyword Args:
path_to_item (None/list) the path to the exception in the
received_data dict
"""
self.path_to_item = path_to_item
full_msg = msg
if path_to_item:
full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
super(ApiKeyError, self).__init__(full_msg)
class ApiException(OpenApiException):
def __init__(self, status=None, reason=None, http_resp=None):
if http_resp:
self.status = http_resp.status
self.reason = http_resp.reason
self.body = http_resp.data
self.headers = http_resp.getheaders()
else:
self.status = status
self.reason = reason
self.body = None
self.headers = None
def __str__(self):
"""Custom error messages for exception"""
error_message = "({0})\n"\
"Reason: {1}\n".format(self.status, self.reason)
if self.headers:
error_message += "HTTP response headers: {0}\n".format(
self.headers)
if self.body:
error_message += "HTTP response body: {0}\n".format(self.body)
return error_message
def render_path(path_to_item):
"""Returns a string representation of a path"""
result = ""
for pth in path_to_item:
if isinstance(pth, six.integer_types):
result += "[{0}]".format(pth)
else:
result += "['{0}']".format(pth)
return result | /rocc-client-0.1.3.tar.gz/rocc-client-0.1.3/roccclient/exceptions.py | 0.706899 | 0.286147 | exceptions.py | pypi |
import json
import os
from io import BytesIO
class AvatarInstance:
def __init__(self, series, unit_list, output_path="./output", oss_bucket=None):
self._series = series
self._unit_list = unit_list
self._output_path = output_path
self._oss_bucket = oss_bucket
self._result_image = None
self._result_info = None
@property
def series(self):
return self._series
@property
def unit_list(self):
return self._unit_list
@property
def output_path(self):
return self._output_path
@property
def avatar_name(self):
sum_score = sum([unit.unit_score for unit in self.unit_list])
new_unit_list = [unit for unit in self.unit_list]
new_unit_list.sort(key=lambda x: x.unit_type)
new_unit_list = [unit for unit in new_unit_list if unit.unit_name != "blank"]
return ",".join([str(sum_score)] + [unit.unit_name for unit in new_unit_list])
@property
def valid(self):
color_list = [unit for unit in self.unit_list if unit.unit_color]
return not color_list or len(set(color_list)) > 1
@property
def avatar_image_name(self):
return self.avatar_name + ".png"
@property
def avatar_info_name(self):
return self.avatar_name + ".json"
@property
def avatar_image_path(self):
return os.path.join(self.output_path, self.avatar_image_name)
@property
def avatar_info_path(self):
return os.path.join(self.output_path, self.avatar_info_name)
@property
def oss_bucket(self):
return self._oss_bucket
def blend_info(self):
info = {
unit.unit_type: unit.unit_name for unit in self.unit_list
}
info["image_name"] = self.avatar_name,
info["image_url"] = self.avatar_image_name,
self._result_info = info
return info
@staticmethod
def blend_two(background, overlay):
_, _, _, alpha = overlay.split()
background.paste(overlay, (0, 0), mask=alpha)
return background
@property
def result_info(self):
return self._result_info
@property
def result_image(self):
return self._result_image
def blend_image(self):
result = self.unit_list[0].image()
for i in range(1, len(self.unit_list)):
result = AvatarInstance.blend_two(result, self.unit_list[i].image())
self._result_image = result
return result
def blend_and_save_info_local(self):
if os.path.isfile(self.avatar_info_path):
return
self.blend_info()
if not os.path.isdir(self.output_path):
os.mkdir(self.output_path)
with open(self.avatar_info_path, "w") as f:
json.dump(self.result_info, f)
def blend_and_save_image_local(self):
if os.path.isfile(self.avatar_image_path):
return
self.blend_image()
if not os.path.isdir(self.output_path):
os.mkdir(self.output_path)
self.result_image.save(self.avatar_image_path, "PNG")
def blend_and_save_info_oss(self):
oss_path = os.path.join(self.series, self.avatar_info_name)
if self.oss_bucket.exist(oss_path):
return
self.oss_bucket.put(oss_path, json.dumps(self.blend_info()))
def blend_and_save_image_oss(self):
oss_path = os.path.join(self.series, self.avatar_image_name)
if self.oss_bucket.exist(oss_path):
return
self.blend_image()
with BytesIO() as output:
self.result_image.save(output, format="PNG")
self.oss_bucket.put(oss_path, output.getvalue())
def save(self):
if self.oss_bucket:
self.blend_and_save_info_oss()
self.blend_and_save_image_oss()
else:
self.blend_and_save_info_local()
self.blend_and_save_image_local() | /rock_avatars-0.0.2.tar.gz/rock_avatars-0.0.2/rock_avatars/avatar_instance.py | 0.574156 | 0.227899 | avatar_instance.py | pypi |
import os
from io import BytesIO
from pathlib import Path
from psd_tools import PSDImage
class PSDCompose:
def __init__(self, psd_file, output_base, oss_bucket=None) -> None:
self._series = Path(psd_file).stem
self._oss_bucket = oss_bucket
if self.oss_bucket:
stream = BytesIO(self.oss_bucket.get(psd_file))
self._psd = PSDImage.open(stream)[0]
else:
# 跳过第一层ArtBoard
self._psd = PSDImage.open(psd_file)[0]
self._view_box = self._psd.bbox
self._output_base = output_base
self._component_depth = 2
@property
def series(self):
return self._series
@property
def psd(self):
return self._psd
@property
def view_box(self):
return self._view_box
@property
def output_base(self):
return self._output_base
@property
def component_depth(self):
return self._component_depth
@property
def oss_bucket(self):
return self._oss_bucket
def unit_list(self):
unit_list = []
for child in self.psd:
if child.kind == 'group':
unit_list.append(child.name)
return unit_list
def compose(self):
self.recur(
0,
"",
self.psd,
)
if self.oss_bucket:
path_base = ""
else:
path_base = self.output_base
return [
self.series,
PSDCompose.path_join(path_base, self.psd),
self.unit_list(),
]
@staticmethod
def path_join(path, layer):
return os.path.join(path, layer.name)
@staticmethod
def png_file(path, layer):
return '%s.png' % PSDCompose.path_join(path, layer)
def save_to_oss(self, layer, relative_path):
image_path = PSDCompose.png_file(relative_path, layer)
with BytesIO() as output:
layer.composite(viewport=self.view_box).save(output, format="PNG")
self.oss_bucket.put(image_path, output.getvalue())
def save_to_local(self, layer, relative_path):
absolute_path = os.path.join(self.output_base, relative_path)
if not os.path.isdir(absolute_path):
os.makedirs(absolute_path)
layer.composite(viewport=self.view_box).save(PSDCompose.png_file(absolute_path, layer), format="PNG")
def save(self, layer, relative_path):
if self.oss_bucket:
return self.save_to_oss(layer, relative_path)
else:
return self.save_to_local(layer, relative_path)
def recur(self, depth, relative_path, layer):
if not layer.is_visible():
return
if layer.is_group() and depth == self.component_depth:
self.save(layer, relative_path)
elif layer.is_group():
for child in layer:
self.recur(
depth + 1,
PSDCompose.path_join(relative_path, layer),
child,
)
else:
self.save(layer, relative_path) | /rock_avatars-0.0.2.tar.gz/rock_avatars-0.0.2/rock_avatars/psd_compose.py | 0.481698 | 0.197715 | psd_compose.py | pypi |
import itertools
import random
from rockart_examples import (
RockartExamplesException,
RockartExamplesIndexError,
RockartExamplesValueError
)
class Game:
__INITIAL_LIFE_PROBABILITY = 0.1
__NEIGHBOUR_LIFE_PROBABILITY = 0.3
def __init__(self, rows, columns, *args, seed=None, **kwargs):
super().__init__(*args, **kwargs)
if rows < 0:
raise RockartExamplesValueError("`rows` must be positive")
if columns < 0:
raise RockartExamplesValueError("`columns` must be positive")
self.__is_initialized = False
self.__epoch = None
self.__rows = rows
self.__columns = columns
self.__field = [
[False]*self.__columns for _ in range(self.__rows)
]
self.__hidden_field = [
[False]*self.__columns for _ in range(self.__rows)
]
self.__random = random.Random(seed)
@property
def rows(self):
return self.__rows
@property
def columns(self):
return self.__columns
@property
def is_initialized(self):
return self.__is_initialized
@property
def epoch(self):
if not self.__is_initialized:
raise RockartExamplesException("Initialize game first")
return self.__epoch
def is_cell_alive(self, row, column):
if not self.__is_initialized:
raise RockartExamplesException("Initialize game first")
if not 0 <= row < self.__rows:
raise RockartExamplesIndexError(
f"`row` must belong to a range [0; {self.__rows - 1}])"
)
if not 0 <= column < self.__columns:
raise RockartExamplesIndexError(
f"`column` must belong to a range [0; {self.__columns - 1}])"
)
return self.__field[row][column]
def initialize(self):
if self.__is_initialized:
raise RockartExamplesException("Game is initialized already")
for row, column in itertools.product(range(self.__rows), range(self.__columns)):
self.__field[row][column] = self.__random.random() < Game.__INITIAL_LIFE_PROBABILITY
self.__epoch = 0
self.__is_initialized = True
def move(self):
if not self.__is_initialized:
raise RockartExamplesException("Initialize game first")
for row, column in itertools.product(range(self.__rows), range(self.__columns)):
alive_neighbours_number = 0
for row_offset, column_offset in itertools.product([-1, 0, 1], repeat=2):
if row_offset == column_offset == 0:
continue
neighbour_row = row + row_offset
neighbour_column = column + column_offset
is_neighbour_internal = \
0 <= neighbour_row < self.__rows \
and 0 <= neighbour_column < self.__columns
if is_neighbour_internal:
is_neighbour_alive = self.__field[neighbour_row][neighbour_column]
else:
is_neighbour_alive = self.__random.random() < Game.__NEIGHBOUR_LIFE_PROBABILITY
if is_neighbour_alive:
alive_neighbours_number += 1
is_alive = self.__field[row][column]
if is_alive:
will_live = alive_neighbours_number in {2, 3}
else:
will_live = alive_neighbours_number == 3
self.__hidden_field[row][column] = will_live
self.__field, self.__hidden_field = self.__hidden_field, self.__field
self.__epoch += 1 | /rockart_examples-0.2.1-py3-none-any.whl/rockart_examples/life/game.py | 0.519765 | 0.262233 | game.py | pypi |
from enum import IntEnum
class directions(IntEnum):
Ahead = 0
Left = 1
Right = 2
Stop = 3
Backward = 4
ArmUp = 5
ArmDown = 6
TiltUp = 7
TiltDown = 8
Lights = 9
Camera = 10
Sound = 11
Parked = 12
LR = 13
def directionToInt(direction):
switcher = {
"Ahead" : directions.Ahead,
"Left" : directions.Left,
"Right" : directions.Right,
"Stop" : directions.Stop,
"Backward" : directions.Backward,
"ArmUp" : directions.ArmUp,
"ArmDown" : directions.ArmDown,
"TiltUp" : directions.TiltUp,
"TiltDown" : directions.TiltDown,
"Lights" : directions.Lights,
"Camera" : directions.Camera,
"Sound" : directions.Sound,
"Parked" : directions.Parked,
"LR" : directions.LR
}
return switcher.get(direction)
def directionToArray(direction):
switcher = {
"Ahead" : [0x0,0xA,0x0,0x0,0xA,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xD],
"Left" : [0x1,0xA,0x0,0x0,0x8,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xD],
"Right" : [0x0,0xA,0x0,0x1,0x3,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xD],
"Stop" : [0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xD],
"Backward" : [0x1,0xA,0x0,0x1,0xA,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xD],
"ArmUp" : [0x0,0x0,0x0,0x0,0x0,0x0,0xB,0x6,0x6,0x0,0x0,0x0,0x0,0x0,0xD],
"ArmDown" : [0x0,0x0,0x0,0x0,0x0,0x0,0x4,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xD],
"TiltUp" : [0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x5,0x6,0x6,0x0,0x0,0xD],
"TiltDown" : [0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xA,0xC,0xC,0x0,0x0,0xD],
"Lights" : [0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xC,0xC,0xF,0xF,0xD],
"Camera" : [0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xF,0xF,0xD],
"Sound" : [0x0,0x0,0x0,0x0,0x0,0x6,0x0,0x6,0x0,0x0,0xC,0x0,0xC,0xC,0xD],
"Parked" : [0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3,0x0,0x0,0x0,0x0,0xD],
"DI" : [0x0,0x0,0x0,0x0,0x0,0x0,0x5,0x6,0x6,0xA,0xC,0xC,0x0,0x0,0x0],
"GG" : [0x0,0x0,0x0,0x0,0x0,0x0,0x5,0x6,0x6,0xA,0xC,0xC,0x0,0x0,0x0],
"ER" : [0x0,0x0,0x0,0x0,0xE,0x0,0xA,0x0,0x0,0xC,0x0,0x0,0x0,0x0,0xD]
}
#high, low = byte >> 4, byte & 0x0F
print ("Command:----------------- ", direction, " ------------------------")
sequence = ("".join(hex(byte & 0x0F) for byte in switcher.get(direction)))
sequence = sequence.replace("0x", "")
sequence = sequence.upper()
print (sequence)
print ("-----------------------------------------------------------")
return (sequence)
def directionToJoystick(direction, L : int, R : int):
L = int(L)
R = int(R)
switcher = {
"LR" : [0x0,L,0x0,0x0,R,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xD],
}
#high, low = byte >> 4, byte & 0x0F
print ("Command:----------------- ", direction, " ------------------------")
sequence = ("".join(hex(byte & 0x0F) for byte in switcher.get(direction)))
sequence = sequence.replace("0x", "")
sequence = sequence.upper()
print (sequence)
print ("-----------------------------------------------------------")
return (sequence)
def intToDirection(i):
switcher = {
directions.Ahead : "Ahead",
directions.Left : "Left",
directions.Right : "Right",
directions.Stop : "Stop",
directions.Backward : "Backward",
directions.ArmUp : "ArmUp",
directions.ArmDown : "ArmDown",
directions.TiltUp : "TiltUp",
directions.TiltDown : "TiltDown",
directions.Lights : "Lights",
directions.Camera : "Camera",
directions.Sound : "Sound",
directions.Parked : "Parked",
directions.LR : "LR"
}
return switcher.get(i) | /rocket-daisy-1.0a2.tar.gz/rocket-daisy-1.0a2/rocket/modules/RC_car_direction_converter.py | 0.434941 | 0.191328 | RC_car_direction_converter.py | pypi |
import time
from rocket.daisy.utils.types import signInteger
from rocket.daisy.devices.i2c import I2C
from rocket.daisy.devices.sensor import Temperature, Pressure
class BMP085(I2C, Temperature, Pressure):
def __init__(self, altitude=0, external=None):
I2C.__init__(self, 0x77)
Pressure.__init__(self, altitude, external)
self.ac1 = self.readSignedInteger(0xAA)
self.ac2 = self.readSignedInteger(0xAC)
self.ac3 = self.readSignedInteger(0xAE)
self.ac4 = self.readUnsignedInteger(0xB0)
self.ac5 = self.readUnsignedInteger(0xB2)
self.ac6 = self.readUnsignedInteger(0xB4)
self.b1 = self.readSignedInteger(0xB6)
self.b2 = self.readSignedInteger(0xB8)
self.mb = self.readSignedInteger(0xBA)
self.mc = self.readSignedInteger(0xBC)
self.md = self.readSignedInteger(0xBE)
def __str__(self):
return "BMP085"
def __family__(self):
return [Temperature.__family__(self), Pressure.__family__(self)]
def readUnsignedInteger(self, address):
d = self.readRegisters(address, 2)
return d[0] << 8 | d[1]
def readSignedInteger(self, address):
d = self.readUnsignedInteger(address)
return signInteger(d, 16)
def readUT(self):
self.writeRegister(0xF4, 0x2E)
time.sleep(0.01)
return self.readUnsignedInteger(0xF6)
def readUP(self):
self.writeRegister(0xF4, 0x34)
time.sleep(0.01)
return self.readUnsignedInteger(0xF6)
def getB5(self):
ut = self.readUT()
x1 = ((ut - self.ac6) * self.ac5) / 2**15
x2 = (self.mc * 2**11) / (x1 + self.md)
return x1 + x2
def __getKelvin__(self):
return self.Celsius2Kelvin()
def __getCelsius__(self):
t = (self.getB5() + 8) / 2**4
return float(t) / 10.0
def __getFahrenheit__(self):
return self.Celsius2Fahrenheit()
def __getPascal__(self):
b5 = self.getB5()
up = self.readUP()
b6 = b5 - 4000
x1 = (self.b2 * (b6 * b6 / 2**12)) / 2**11
x2 = self.ac2 * b6 / 2**11
x3 = x1 + x2
b3 = (self.ac1*4 + x3 + 2) / 4
x1 = self.ac3 * b6 / 2**13
x2 = (self.b1 * (b6 * b6 / 2**12)) / 2**16
x3 = (x1 + x2 + 2) / 2**2
b4 = self.ac4 * (x3 + 32768) / 2**15
b7 = (up-b3) * 50000
if b7 < 0x80000000:
p = (b7 * 2) / b4
else:
p = (b7 / b4) * 2
x1 = (p / 2**8) * (p / 2**8)
x1 = (x1 * 3038) / 2**16
x2 = (-7357*p) / 2**16
p = p + (x1 + x2 + 3791) / 2**4
return int(p)
class BMP180(BMP085):
def __init__(self, altitude=0, external=None):
BMP085.__init__(self, altitude, external)
def __str__(self):
return "BMP180" | /rocket-daisy-1.0a2.tar.gz/rocket-daisy-1.0a2/rocket/daisy/devices/sensor/bmp085.py | 0.620162 | 0.257459 | bmp085.py | pypi |
from rocket.daisy.utils.types import toint
from rocket.daisy.utils.types import M_JSON
from rocket.daisy.devices.instance import deviceInstance
from rocket.daisy.decorators.rest import request, response
class Pressure():
def __init__(self, altitude=0, external=None):
self.altitude = toint(altitude)
if isinstance(external, str):
self.external = deviceInstance(external)
else:
self.external = external
if self.external != None and not isinstance(self.external, Temperature):
raise Exception("external must be a Temperature sensor")
def __family__(self):
return "Pressure"
def __getPascal__(self):
raise NotImplementedError
def __getPascalAtSea__(self):
raise NotImplementedError
@request("GET", "sensor/pressure/pa")
@response("%d")
def getPascal(self):
return self.__getPascal__()
@request("GET", "sensor/pressure/hpa")
@response("%.2f")
def getHectoPascal(self):
return float(self.__getPascal__()) / 100.0
@request("GET", "sensor/pressure/sea/pa")
@response("%d")
def getPascalAtSea(self):
pressure = self.__getPascal__()
if self.external != None:
k = self.external.getKelvin()
if k != 0:
return float(pressure) / (1.0 / (1.0 + 0.0065 / k * self.altitude)**5.255)
return float(pressure) / (1.0 - self.altitude / 44330.0)**5.255
@request("GET", "sensor/pressure/sea/hpa")
@response("%.2f")
def getHectoPascalAtSea(self):
return self.getPascalAtSea() / 100.0
class Temperature():
def __family__(self):
return "Temperature"
def __getKelvin__(self):
raise NotImplementedError
def __getCelsius__(self):
raise NotImplementedError
def __getFahrenheit__(self):
raise NotImplementedError
def Kelvin2Celsius(self, value=None):
if value == None:
value = self.getKelvin()
return value - 273.15
def Kelvin2Fahrenheit(self, value=None):
if value == None:
value = self.getKelvin()
return value * 1.8 - 459.67
def Celsius2Kelvin(self, value=None):
if value == None:
value = self.getCelsius()
return value + 273.15
def Celsius2Fahrenheit(self, value=None):
if value == None:
value = self.getCelsius()
return value * 1.8 + 32
def Fahrenheit2Kelvin(self, value=None):
if value == None:
value = self.getFahrenheit()
return (value - 459.67) / 1.8
def Fahrenheit2Celsius(self, value=None):
if value == None:
value = self.getFahrenheit()
return (value - 32) / 1.8
@request("GET", "sensor/temperature/k")
@response("%.02f")
def getKelvin(self):
return self.__getKelvin__()
@request("GET", "sensor/temperature/c")
@response("%.02f")
def getCelsius(self):
return self.__getCelsius__()
@request("GET", "sensor/temperature/f")
@response("%.02f")
def getFahrenheit(self):
return self.__getFahrenheit__()
class Luminosity():
def __family__(self):
return "Luminosity"
def __getLux__(self):
raise NotImplementedError
@request("GET", "sensor/luminosity/lux")
@response("%.02f")
def getLux(self):
return self.__getLux__()
class Distance():
def __family__(self):
return "Distance"
def __getMillimeter__(self):
raise NotImplementedError
@request("GET", "sensor/distance/mm")
@response("%.02f")
def getMillimeter(self):
return self.__getMillimeter__()
@request("GET", "sensor/distance/cm")
@response("%.02f")
def getCentimeter(self):
return self.getMillimeter() / 10
@request("GET", "sensor/distance/m")
@response("%.02f")
def getMeter(self):
return self.getMillimeter() / 1000
@request("GET", "sensor/distance/in")
@response("%.02f")
def getInch(self):
return self.getMillimeter() / 0.254
@request("GET", "sensor/distance/ft")
@response("%.02f")
def getFoot(self):
return self.getInch() / 12
@request("GET", "sensor/distance/yd")
@response("%.02f")
def getYard(self):
return self.getInch() / 36
class Humidity():
def __family__(self):
return "Humidity"
def __getHumidity__(self):
raise NotImplementedError
@request("GET", "sensor/humidity/float")
@response("%f")
def getHumidity(self):
return self.__getHumidity__()
@request("GET", "sensor/humidity/percent")
@response("%d")
def getHumidityPercent(self):
return self.__getHumidity__() * 100
DRIVERS = {}
DRIVERS["bmp085"] = ["BMP085", "BMP180"]
DRIVERS["onewiretemp"] = ["DS1822", "DS1825", "DS18B20", "DS18S20", "DS28EA00"]
DRIVERS["tmpXXX"] = ["TMP75", "TMP102", "TMP275"]
DRIVERS["tslXXXX"] = ["TSL2561", "TSL2561CS", "TSL2561T", "TSL4531", "TSL45311", "TSL45313", "TSL45315", "TSL45317"]
DRIVERS["vcnl4000"] = ["VCNL4000"]
DRIVERS["hytXXX"] = ["HYT221"] | /rocket-daisy-1.0a2.tar.gz/rocket-daisy-1.0a2/rocket/daisy/devices/sensor/__init__.py | 0.756627 | 0.156749 | __init__.py | pypi |
from rocket.daisy.utils.types import toint
from rocket.daisy.devices.i2c import I2C
from rocket.daisy.devices.spi import SPI
from rocket.daisy.devices.digital import GPIOPort
class MCP23XXX(GPIOPort):
IODIR = 0x00
IPOL = 0x01
GPINTEN = 0x02
DEFVAL = 0x03
INTCON = 0x04
IOCON = 0x05
GPPU = 0x06
INTF = 0x07
INTCAP = 0x08
GPIO = 0x09
OLAT = 0x0A
def __init__(self, channelCount):
GPIOPort.__init__(self, channelCount)
self.banks = int(channelCount / 8)
def getAddress(self, register, channel=0):
return register * self.banks + int(channel / 8)
def getChannel(self, register, channel):
self.checkDigitalChannel(channel)
addr = self.getAddress(register, channel)
mask = 1 << (channel % 8)
return (addr, mask)
def __digitalRead__(self, channel):
(addr, mask) = self.getChannel(self.GPIO, channel)
d = self.readRegister(addr)
return (d & mask) == mask
def __digitalWrite__(self, channel, value):
(addr, mask) = self.getChannel(self.GPIO, channel)
d = self.readRegister(addr)
if value:
d |= mask
else:
d &= ~mask
self.writeRegister(addr, d)
def __getFunction__(self, channel):
(addr, mask) = self.getChannel(self.IODIR, channel)
d = self.readRegister(addr)
return self.IN if (d & mask) == mask else self.OUT
def __setFunction__(self, channel, value):
if not value in [self.IN, self.OUT]:
raise ValueError("Requested function not supported")
(addr, mask) = self.getChannel(self.IODIR, channel)
d = self.readRegister(addr)
if value == self.IN:
d |= mask
else:
d &= ~mask
self.writeRegister(addr, d)
def __portRead__(self):
value = 0
for i in range(self.banks):
value |= self.readRegister(self.banks*self.GPIO+i) << 8*i
return value
def __portWrite__(self, value):
for i in range(self.banks):
self.writeRegister(self.banks*self.GPIO+i, (value >> 8*i) & 0xFF)
class MCP230XX(MCP23XXX, I2C):
def __init__(self, slave, channelCount, name):
I2C.__init__(self, toint(slave))
MCP23XXX.__init__(self, channelCount)
self.name = name
def __str__(self):
return "%s(slave=0x%02X)" % (self.name, self.slave)
class MCP23008(MCP230XX):
def __init__(self, slave=0x20):
MCP230XX.__init__(self, slave, 8, "MCP23008")
class MCP23009(MCP230XX):
def __init__(self, slave=0x20):
MCP230XX.__init__(self, slave, 8, "MCP23009")
class MCP23017(MCP230XX):
def __init__(self, slave=0x20):
MCP230XX.__init__(self, slave, 16, "MCP23017")
class MCP23018(MCP230XX):
def __init__(self, slave=0x20):
MCP230XX.__init__(self, slave, 16, "MCP23018")
class MCP23SXX(MCP23XXX, SPI):
SLAVE = 0x20
WRITE = 0x00
READ = 0x01
def __init__(self, chip, slave, channelCount, name):
SPI.__init__(self, toint(chip), 0, 8, 10000000)
MCP23XXX.__init__(self, channelCount)
self.slave = self.SLAVE
iocon_value = 0x08 # Hardware Address Enable
iocon_addr = self.getAddress(self.IOCON)
self.writeRegister(iocon_addr, iocon_value)
self.slave = toint(slave)
self.name = name
def __str__(self):
return "%s(chip=%d, slave=0x%02X)" % (self.name, self.chip, self.slave)
def readRegister(self, addr):
d = self.xfer([(self.slave << 1) | self.READ, addr, 0x00])
return d[2]
def writeRegister(self, addr, value):
self.writeBytes([(self.slave << 1) | self.WRITE, addr, value])
class MCP23S08(MCP23SXX):
def __init__(self, chip=0, slave=0x20):
MCP23SXX.__init__(self, chip, slave, 8, "MCP23S08")
class MCP23S09(MCP23SXX):
def __init__(self, chip=0, slave=0x20):
MCP23SXX.__init__(self, chip, slave, 8, "MCP23S09")
class MCP23S17(MCP23SXX):
def __init__(self, chip=0, slave=0x20):
MCP23SXX.__init__(self, chip, slave, 16, "MCP23S17")
class MCP23S18(MCP23SXX):
def __init__(self, chip=0, slave=0x20):
MCP23SXX.__init__(self, chip, slave, 16, "MCP23S18") | /rocket-daisy-1.0a2.tar.gz/rocket-daisy-1.0a2/rocket/daisy/devices/digital/mcp23XXX.py | 0.550366 | 0.159315 | mcp23XXX.py | pypi |
from time import sleep
from rocket.daisy.utils.types import toint, signInteger
from rocket.daisy.devices.i2c import I2C
from rocket.daisy.devices.analog import ADC
class ADS1X1X(ADC, I2C):
VALUE = 0x00
CONFIG = 0x01
LO_THRESH = 0x02
HI_THRESH = 0x03
CONFIG_STATUS_MASK = 0x80
CONFIG_CHANNEL_MASK = 0x70
CONFIG_GAIN_MASK = 0x0E
CONFIG_MODE_MASK = 0x01
def __init__(self, slave, channelCount, resolution, name):
I2C.__init__(self, toint(slave))
ADC.__init__(self, channelCount, resolution, 4.096)
self._analogMax = 2**(resolution-1)
self.name = name
config = self.readRegisters(self.CONFIG, 2)
mode = 0 # continuous
config[0] &= ~self.CONFIG_MODE_MASK
config[0] |= mode
gain = 0x1 # FS = +/- 4.096V
config[0] &= ~self.CONFIG_GAIN_MASK
config[0] |= gain << 1
self.writeRegisters(self.CONFIG, config)
def __str__(self):
return "%s(slave=0x%02X)" % (self.name, self.slave)
def __analogRead__(self, channel, diff=False):
config = self.readRegisters(self.CONFIG, 2)
config[0] &= ~self.CONFIG_CHANNEL_MASK
if diff:
config[0] |= channel << 4
else:
config[0] |= (channel + 4) << 4
self.writeRegisters(self.CONFIG, config)
sleep(0.001)
d = self.readRegisters(self.VALUE, 2)
value = (d[0] << 8 | d[1]) >> (16-self._analogResolution)
return signInteger(value, self._analogResolution)
class ADS1014(ADS1X1X):
def __init__(self, slave=0x48):
ADS1X1X.__init__(self, slave, 1, 12, "ADS1014")
class ADS1015(ADS1X1X):
def __init__(self, slave=0x48):
ADS1X1X.__init__(self, slave, 4, 12, "ADS1015")
class ADS1114(ADS1X1X):
def __init__(self, slave=0x48):
ADS1X1X.__init__(self, slave, 1, 16, "ADS1114")
class ADS1115(ADS1X1X):
def __init__(self, slave=0x48):
ADS1X1X.__init__(self, slave, 4, 16, "ADS1115") | /rocket-daisy-1.0a2.tar.gz/rocket-daisy-1.0a2/rocket/daisy/devices/analog/ads1x1x.py | 0.454714 | 0.152095 | ads1x1x.py | pypi |
from rocket.daisy.utils.types import toint
from rocket.daisy.devices.spi import SPI
from rocket.daisy.devices.analog import DAC
class MCP48XX(SPI, DAC):
def __init__(self, chip, channelCount, resolution, name):
SPI.__init__(self, toint(chip), 0, 8, 10000000)
DAC.__init__(self, channelCount, resolution, 2.048)
self.name = name
self.buffered=False
self.gain=False
self.shutdown=True
self.values = [0 for i in range(channelCount)]
def __str__(self):
return "%s(chip=%d)" % (self.name, self.chip)
def int2bin(self,n,count):
return "".join([str((n >> y) & 1 ) for y in range(count-1,-1,-1)])
def __analogRead__(self, channel, diff=False):
return self.values[channel]
def __analogWriteShut__(self, channel):
self.shutdown = True
d = [0x00, 0x00]
d[0] |= (channel & 0x01) << 7 # bit 15 = channel
d[0] |= 0x00 << 6 # bit 14 = ignored
d[0] |= 0x00 << 5 # bit 13 = gain
d[0] |= (self.shutdown & 0x01) << 4 # bit 12 = shutdown
d[0] |= 0x00 # bits 8-11 = msb data
d[1] |= 0x00 # bits 0 - 7 = lsb data
self.writeBytes(d)
self.values[channel] = 0
def __analogWrite__(self, channel, value):
self.shutdown=False
d = [0x00, 0x00]
d[0] |= (channel & 0x01) << 7 # bit 15 = channel
d[0] |= (self.buffered & 0x01) << 6 # bit 14 = ignored
d[0] |= (not self.gain & 0x01) << 5 # bit 13 = gain
d[0] |= (not self.shutdown & 0x01) << 4 # bit 12 = shutdown
d[0] |= value >> (self._analogResolution - 4) # bits 8-11 = msb data
d[1] |= ((value << (12-self._analogResolution)) & 0xFF) # bits 4 - 7 = lsb data (4802) bits 2-7 (4812) bits 0-7 (4822) # bits 0 - 3 = ignored
self.writeBytes(d)
self.values[channel] = value
class MCP4802(MCP48XX):
def __init__(self, chip=0):
MCP48XX.__init__(self, chip, 2, 8, "MCP4802")
class MCP4812(MCP48XX):
def __init__(self, chip=0):
MCP48XX.__init__(self, chip, 2, 10, "MCP4812")
class MCP4822(MCP48XX):
def __init__(self, chip=0):
MCP48XX.__init__(self, chip, 2, 12, "MCP4822") | /rocket-daisy-1.0a2.tar.gz/rocket-daisy-1.0a2/rocket/daisy/devices/analog/mcp48XX.py | 0.619241 | 0.265007 | mcp48XX.py | pypi |
from rocket.daisy.utils.types import toint
from rocket.daisy.devices.spi import SPI
from rocket.daisy.devices.analog import ADC
class MCP3X0X(SPI, ADC):
def __init__(self, chip, channelCount, resolution, vref, name):
SPI.__init__(self, toint(chip), 0, 8, 10000)
ADC.__init__(self, channelCount, resolution, float(vref))
self.name = name
self.MSB_MASK = 2**(resolution-8) - 1
def __str__(self):
return "%s(chip=%d)" % (self.name, self.chip)
def __analogRead__(self, channel, diff):
data = self.__command__(channel, diff)
r = self.xfer(data)
return ((r[1] & self.MSB_MASK) << 8) | r[2]
class MCP300X(MCP3X0X):
def __init__(self, chip, channelCount, vref, name):
MCP3X0X.__init__(self, chip, channelCount, 10, vref, name)
def __command__(self, channel, diff):
d = [0x00, 0x00, 0x00]
d[0] |= 1
d[1] |= (not diff) << 7
d[1] |= ((channel >> 2) & 0x01) << 6
d[1] |= ((channel >> 1) & 0x01) << 5
d[1] |= ((channel >> 0) & 0x01) << 4
return d
class MCP3002(MCP300X):
def __init__(self, chip=0, vref=3.3):
MCP300X.__init__(self, chip, 2, vref, "MCP3002")
def __analogRead__(self, channel, diff):
data = self.__command__(channel, diff)
r = self.xfer(data)
# Format of return is
# 1 empty bit
# 1 null bit
# 10 ADC bits
return (r[0]<<14 | r[1]<<6 | r[2]>>2) & ((2**self._analogResolution)-1)
def __command__(self, channel, diff):
d = [0x00, 0x00, 0x00]
d[0] |= 1 #start bit
d[1] |= (not diff) << 7 #single/differntial input
d[1] |= channel << 6 #channel select
return d
class MCP3004(MCP300X):
def __init__(self, chip=0, vref=3.3):
MCP300X.__init__(self, chip, 4, vref, "MCP3004")
class MCP3008(MCP300X):
def __init__(self, chip=0, vref=3.3):
MCP300X.__init__(self, chip, 8, vref, "MCP3008")
class MCP320X(MCP3X0X):
def __init__(self, chip, channelCount, vref, name):
MCP3X0X.__init__(self, chip, channelCount, 12, vref, name)
def __command__(self, channel, diff):
d = [0x00, 0x00, 0x00]
d[0] |= 1 << 2
d[0] |= (not diff) << 1
d[0] |= (channel >> 2) & 0x01
d[1] |= ((channel >> 1) & 0x01) << 7
d[1] |= ((channel >> 0) & 0x01) << 6
return d
class MCP3204(MCP320X):
def __init__(self, chip=0, vref=3.3):
MCP320X.__init__(self, chip, 4, vref, "MCP3204")
class MCP3208(MCP320X):
def __init__(self, chip=0, vref=3.3):
MCP320X.__init__(self, chip, 8, vref, "MCP3208") | /rocket-daisy-1.0a2.tar.gz/rocket-daisy-1.0a2/rocket/daisy/devices/analog/mcp3x0x.py | 0.649023 | 0.308959 | mcp3x0x.py | pypi |
from rocket.daisy.decorators.rest import request, response
from rocket.daisy.utils.types import M_JSON
class ADC():
def __init__(self, channelCount, resolution, vref):
self._analogCount = channelCount
self._analogResolution = resolution
self._analogMax = 2**resolution - 1
self._analogRef = vref
def __family__(self):
return "ADC"
def checkAnalogChannel(self, channel):
if not 0 <= channel < self._analogCount:
raise ValueError("Channel %d out of range [%d..%d]" % (channel, 0, self._analogCount-1))
def checkAnalogValue(self, value):
if not 0 <= value <= self._analogMax:
raise ValueError("Value %d out of range [%d..%d]" % (value, 0, self._analogMax))
@request("GET", "analog/count")
@response("%d")
def analogCount(self):
return self._analogCount
@request("GET", "analog/resolution")
@response("%d")
def analogResolution(self):
return self._analogResolution
@request("GET", "analog/max")
@response("%d")
def analogMaximum(self):
return int(self._analogMax)
@request("GET", "analog/vref")
@response("%.2f")
def analogReference(self):
return self._analogRef
def __analogRead__(self, channel, diff):
raise NotImplementedError
@request("GET", "analog/%(channel)d/integer")
@response("%d")
def analogRead(self, channel, diff=False):
self.checkAnalogChannel(channel)
return self.__analogRead__(channel, diff)
@request("GET", "analog/%(channel)d/float")
@response("%.2f")
def analogReadFloat(self, channel, diff=False):
return self.analogRead(channel, diff) / float(self._analogMax)
@request("GET", "analog/%(channel)d/volt")
@response("%.2f")
def analogReadVolt(self, channel, diff=False):
if self._analogRef == 0:
raise NotImplementedError
return self.analogReadFloat(channel, diff) * self._analogRef
@request("GET", "analog/*/integer")
@response(contentType=M_JSON)
def analogReadAll(self):
values = {}
for i in range(self._analogCount):
values[i] = self.analogRead(i)
return values
@request("GET", "analog/*/float")
@response(contentType=M_JSON)
def analogReadAllFloat(self):
values = {}
for i in range(self._analogCount):
values[i] = float("%.2f" % self.analogReadFloat(i))
return values
@request("GET", "analog/*/volt")
@response(contentType=M_JSON)
def analogReadAllVolt(self):
values = {}
for i in range(self._analogCount):
values[i] = float("%.2f" % self.analogReadVolt(i))
return values
class DAC(ADC):
def __init__(self, channelCount, resolution, vref):
ADC.__init__(self, channelCount, resolution, vref)
def __family__(self):
return "DAC"
def __analogWrite__(self, channel, value):
raise NotImplementedError
@request("POST", "analog/%(channel)d/integer/%(value)d")
@response("%d")
def analogWrite(self, channel, value):
self.checkAnalogChannel(channel)
self.checkAnalogValue(value)
self.__analogWrite__(channel, value)
return self.analogRead(channel)
@request("POST", "analog/%(channel)d/float/%(value)f")
@response("%.2f")
def analogWriteFloat(self, channel, value):
self.analogWrite(channel, int(value * self._analogMax))
return self.analogReadFloat(channel)
@request("POST", "analog/%(channel)d/volt/%(value)f")
@response("%.2f")
def analogWriteVolt(self, channel, value):
self.analogWriteFloat(channel, value /self._analogRef)
return self.analogReadVolt(channel)
class PWM():
def __init__(self, channelCount, resolution, frequency):
self._pwmCount = channelCount
self._pwmResolution = resolution
self._pwmMax = 2**resolution - 1
self.frequency = frequency
self.period = 1.0/frequency
# Futaba servos standard
self.servo_neutral = 0.00152
self.servo_travel_time = 0.0004
self.servo_travel_angle = 45.0
self.reverse = [False for i in range(channelCount)]
def __family__(self):
return "PWM"
def checkPWMChannel(self, channel):
if not 0 <= channel < self._pwmCount:
raise ValueError("Channel %d out of range [%d..%d]" % (channel, 0, self._pwmCount-1))
def checkPWMValue(self, value):
if not 0 <= value <= self._pwmMax:
raise ValueError("Value %d out of range [%d..%d]" % (value, 0, self._pwmMax))
def __pwmRead__(self, channel):
raise NotImplementedError
def __pwmWrite__(self, channel, value):
raise NotImplementedError
@request("GET", "pwm/count")
@response("%d")
def pwmCount(self):
return self._pwmCount
@request("GET", "pwm/resolution")
@response("%d")
def pwmResolution(self):
return self._pwmResolution
@request("GET", "pwm/max")
@response("%d")
def pwmMaximum(self):
return int(self._pwmMax)
@request("GET", "pwm/%(channel)d/integer")
@response("%d")
def pwmRead(self, channel):
self.checkPWMChannel(channel)
return self.__pwmRead__(channel)
@request("GET", "pwm/%(channel)d/float")
@response("%.2f")
def pwmReadFloat(self, channel):
return self.pwmRead(channel) / float(self._pwmMax)
@request("POST", "pwm/%(channel)d/integer/%(value)d")
@response("%d")
def pwmWrite(self, channel, value):
self.checkPWMChannel(channel)
self.checkPWMValue(value)
self.__pwmWrite__(channel, value)
return self.pwmRead(channel)
@request("POST", "pwm/%(channel)d/float/%(value)f")
@response("%.2f")
def pwmWriteFloat(self, channel, value):
self.pwmWrite(channel, int(value * self._pwmMax))
return self.pwmReadFloat(channel)
def getReverse(self, channel):
self.checkChannel(channel)
return self.reverse[channel]
def setReverse(self, channel, value):
self.checkChannel(channel)
self.reverse[channel] = value
return value
def RatioToAngle(self, value):
f = value
f *= self.period
f -= self.servo_neutral
f *= self.servo_travel_angle
f /= self.servo_travel_time
return f
def AngleToRatio(self, value):
f = value
f *= self.servo_travel_time
f /= self.servo_travel_angle
f += self.servo_neutral
f /= self.period
return f
@request("GET", "pwm/%(channel)d/angle")
@response("%.2f")
def pwmReadAngle(self, channel):
f = self.pwmReadFloat(channel)
f = self.RatioToAngle(f)
if self.reverse[channel]:
f = -f
else:
f = f
return f
@request("POST", "pwm/%(channel)d/angle/%(value)f")
@response("%.2f")
def pwmWriteAngle(self, channel, value):
if self.reverse[channel]:
f = -value
else:
f = value
f = self.AngleToRatio(f)
self.pwmWriteFloat(channel, f)
return self.pwmReadAngle(channel)
@request("GET", "pwm/*")
@response(contentType=M_JSON)
def pwmWildcard(self):
values = {}
for i in range(self._pwmCount):
val = self.pwmReadFloat(i)
values[i] = {}
values[i]["float"] = float("%.2f" % val)
values[i]["angle"] = float("%.2f" % self.RatioToAngle(val))
return values
DRIVERS = {}
DRIVERS["ads1x1x"] = ["ADS1014", "ADS1015", "ADS1114", "ADS1115"]
DRIVERS["mcp3x0x"] = ["MCP3002", "MCP3004", "MCP3008", "MCP3204", "MCP3208"]
DRIVERS["mcp4725"] = ["MCP4725"]
DRIVERS["mcp48XX"] = ["MCP4802", "MCP4812", "MCP4822"]
DRIVERS["mcp492X"] = ["MCP4921", "MCP4922"]
DRIVERS["pca9685"] = ["PCA9685"]
DRIVERS["pcf8591"] = ["PCF8591"] | /rocket-daisy-1.0a2.tar.gz/rocket-daisy-1.0a2/rocket/daisy/devices/analog/__init__.py | 0.803906 | 0.20456 | __init__.py | pypi |
import numba as nb
from numba import TypingError
from numba.core import types
from numba.np.numpy_support import is_nonelike
def is_sequence_like(arg):
seq_like = (types.Tuple, types.ListType,
types.Array, types.Sequence)
return isinstance(arg, seq_like)
def is_integer(arg):
return isinstance(arg, (types.Integer, types.Boolean))
def is_scalar(arg):
return isinstance(arg, (types.Number, types.Boolean))
def is_integer_2tuple(arg):
return (isinstance(arg, types.UniTuple)
and (arg.count == 2)
and is_integer(arg.dtype))
def is_literal_integer(val):
def impl(arg):
if not isinstance(arg, types.IntegerLiteral):
return False
return arg.literal_value == val
return impl
def is_literal_bool(val):
def impl(arg):
if not isinstance(arg, types.BooleanLiteral):
return False
return arg.literal_value == val
return impl
def is_contiguous_array(layout):
def impl(arg):
if not isinstance(arg, types.Array):
return False
return arg.layout == layout
return impl
def is_not_nonelike(arg):
return not is_nonelike(arg)
class Check:
__slots__ = ("ty", "as_one", "as_seq", "allow_none", "msg")
def __init__(self, ty, as_one=True, as_seq=False, allow_none=False, msg=None):
self.ty = ty
self.as_one = as_one
self.as_seq = as_seq
self.allow_none = allow_none
self.msg = msg
def __call__(self, arg, fmt=None):
if not isinstance(arg, types.Type):
arg = nb.typeof(arg)
if self.allow_none and is_nonelike(arg):
return True
if self.as_one and isinstance(arg, self.ty):
return True
if self.as_seq and is_sequence_like(arg):
if isinstance(arg.dtype, self.ty):
return True
if self.msg is None:
return False
if fmt is None:
raise TypingError(self.msg)
raise TypingError(self.msg.format(*fmt))
def typing_check(ty, as_one=True, as_seq=False, allow_none=False):
def impl(arg, msg):
check = Check(ty, as_one, as_seq, allow_none, msg)
return check(arg)
return impl
class TypingChecker:
__slots__ = ("checks")
def __init__(self, **checks):
self.checks = checks
def __call__(self, **kwargs):
items = kwargs.items()
for i, (argname, argval) in enumerate(items, start=1):
check = self.checks.get(argname)
if check is not None:
ordinal = self.get_ordinal(i)
check(argval, fmt=(ordinal, argname))
return self
def register(self, **kwargs):
self.checks.update(kwargs)
return self
@staticmethod
def get_ordinal(n):
ordinals = ("th", "st", "nd", "rd", "th",
"th", "th", "th", "th", "th")
return str(n) + ordinals[n % 10] | /rocket_fft-0.2.1-cp310-cp310-macosx_11_0_arm64.whl/rocket_fft/typutils.py | 0.663342 | 0.279847 | typutils.py | pypi |
import ctypes
from llvmlite import ir
from numba import TypingError, types, vectorize
from numba.core.cgutils import get_or_insert_function
from numba.extending import intrinsic, overload
from .extutils import get_extension_path, load_extension_library_permanently
special_helpers_module = "_special_helpers"
load_extension_library_permanently(special_helpers_module)
lib_path = get_extension_path(special_helpers_module)
dll = ctypes.PyDLL(lib_path)
init_special_functions = dll.init_special_functions
init_special_functions()
ll_void = ir.VoidType()
ll_int32 = ir.IntType(32)
ll_longlong = ir.IntType(64)
ll_double = ir.DoubleType()
ll_double_ptr = ll_double.as_pointer()
ll_complex128 = ir.LiteralStructType([ll_double, ll_double])
def _call_complex_loggamma(builder, real, imag, real_out, imag_out):
fname = "numba_complex_loggamma"
arg_types = (ll_double, ll_double, ll_double_ptr, ll_double_ptr)
fnty = ir.FunctionType(ll_void, arg_types)
fn = get_or_insert_function(builder.module, fnty, fname)
real = builder.fpext(real, ll_double)
imag = builder.fpext(imag, ll_double)
real_out = builder.bitcast(real_out, ll_double_ptr)
imag_out = builder.bitcast(imag_out, ll_double_ptr)
builder.call(fn, [real, imag, real_out, imag_out])
@intrinsic
def _complex_loggamma(typingctx, z):
if not isinstance(z, types.Complex):
raise TypingError("Argument 'z' must be a complex")
def codegen(context, builder, sig, args):
real = builder.extract_value(args[0], 0)
imag = builder.extract_value(args[0], 1)
real_out = builder.alloca(ll_double)
imag_out = builder.alloca(ll_double)
_call_complex_loggamma(builder, real, imag, real_out, imag_out)
zout = builder.alloca(ll_complex128)
zout_real = builder.gep(zout, [ll_int32(0), ll_int32(0)])
zout_imag = builder.gep(zout, [ll_int32(0), ll_int32(1)])
builder.store(builder.load(real_out), zout_real)
builder.store(builder.load(imag_out), zout_imag)
return builder.load(zout)
sig = types.complex128(z)
return sig, codegen
@intrinsic
def _real_loggamma(typingctx, z):
if not isinstance(z, types.Float):
raise TypingError("Argument 'z' must be a float")
def codegen(context, builder, sig, args):
fname = "numba_real_loggamma"
fnty = ir.FunctionType(ll_double, (ll_double,))
fn = get_or_insert_function(builder.module, fnty, fname)
z = builder.fpext(args[0], ll_double)
return builder.call(fn, [z])
sig = types.double(z)
return sig, codegen
def _loggamma(z):
pass
@overload(_loggamma)
def _loggamma_impl(z):
if isinstance(z, types.Complex):
return lambda z: _complex_loggamma(z)
if isinstance(z, types.Float):
return lambda z: _real_loggamma(z)
raise TypingError("Argument 'z' must be a float or complex")
@intrinsic
def _poch(typingctx, z, m):
if not isinstance(z, types.Float):
raise TypingError("First argument 'z' must be a float")
if not isinstance(m, types.Float):
raise TypingError("Second argument 'm' must be a float")
def codegen(context, builder, sig, args):
fname = "numba_poch"
fnty = ir.FunctionType(ll_double, (ll_double, ll_double))
fn = get_or_insert_function(builder.module, fnty, fname)
z = builder.fpext(args[0], ll_double)
m = builder.fpext(args[1], ll_double)
return builder.call(fn, [z, m])
sig = types.double(z, m)
return sig, codegen
_loggamma_sigs = (
"float64(float32)",
"float64(float64)",
"complex128(complex64)",
"complex128(complex128)",
)
@vectorize
def loggamma(z):
return _loggamma(z)
_poch_sigs = (
"float64(float32, float32)",
"float64(float64, float32)",
"float64(float32, float64)",
"float64(float64, float64)",
)
@vectorize
def poch(z, m):
return _poch(z, m)
def add_signatures(loggamma_sigs=None, poch_sigs=None):
list(map(loggamma.add, loggamma_sigs or _loggamma_sigs))
list(map(poch.add, poch_sigs or _poch_sigs)) | /rocket_fft-0.2.1-cp310-cp310-macosx_11_0_arm64.whl/rocket_fft/special.py | 0.566378 | 0.206114 | special.py | pypi |
from __future__ import print_function
import numpy as np
def fact(n):
"""
Factorial of n
"""
if n < 0:
print("Error, n must be positive")
return None
if n == 0 or n == 1:
return 1
result = 1
for i in range(1, n+1):
result *= i
return result
def get_limit(m_objs, H):
"""
Return the number of solutions for Eq (1) [see list_sol()]
"""
n = H + m_objs - 1
k = H
# numerator
num = 1
for i in range(k):
num *= (n-i)
# denominator
den = fact(k)
limit = num / den
return int(limit)
def next_sol(sol, m_objs, H):
"""
Create a new solution (sol) by incrementing the value of
sol[m_objs-2] += 1
and adjusting the last position of sol
sol[m_objs-1] = H - sum(new_sol)
The resulting solution (new_sol) can be invalid.
Input
sol list, solution with m_objs integers
m_objs int, number of objectives
H int, granularity >= 2
Output
new_sol list, a (possibly) valid solution
"""
new_sol = [0]*m_objs
for i in range(m_objs-1):
new_sol[i] = sol[i]
new_sol[m_objs-2] += 1
new_sol[m_objs-1] = H - sum(new_sol)
return new_sol
def check_sol(sol, m_objs, H, verbose=False):
"""
Determine whether a solution (sol) is valid.
Input
sol list, solution with m_objs integers
m_objs int, number of objectives
H int, granularity >= 2
verbose bool, flag to show messages
Output
ok bool, if ok is False, sol is invalid
error_pos int, position of the first invalid value found in sol (if any)
"""
ok = True
error_pos = None
for pos in range(m_objs-2, -1, -1): # sequence [m_objs-2, ..., 0]
lb = 0
ub = H - sum(sol[:pos]) # sum(sol[0], ..., sol[pos-1])
if sol[pos] >= lb and sol[pos] <= ub:
continue
else:
ok = False
error_pos = pos
if verbose:
print(" * %s, pos %d" % (sol, pos))
return ok, error_pos
def repair_sol(sol, m_objs, H, pos):
"""
Given a solution (sol), a new solution is created (new_sol).
This function copies the first pos-1 values of sol into new_sol.
Then, the value before pos (new_sol[pos-1]) is incremented.
Finally, the last position (new_sol[m_objs-1] == new_sol[-1])
is adjusted to sum H.
Input
sol list, solution with m_objs integers
m_objs int, number of objectives
H int, granularity >= 2
pos int, position of the first invalid value found in sol
Output
new_sol list, a (possibly) valid solution
"""
new_sol = [0]*m_objs
for i in range(pos):
new_sol[i] = sol[i]
new_sol[pos-1] += 1
# adjust the last position to sum H
new_sol[m_objs-1] = H - sum(new_sol[:m_objs]) # it sums everything except the last position
return new_sol
def full_repair_sol(sol, m_objs, H, verbose=False):
"""
Given a solution (sol), this function determines if sol is a valid solution.
If so, it is returned. Otherwise, a new attempt is made and the process
is repeated until a valid solution is created.
Input
sol list, solution with m_objs integers
m_objs int, number of objectives
H int, granularity >= 2
verbose bool, flag to show messages
Output
new_sol list, a valid solution
"""
sol_is_ok = False # we assume that sol is invalid
new_sol = list(sol) # returned solution
while not sol_is_ok:
# determine whether new_sol is valid
ok, pos = check_sol(new_sol, m_objs, H, verbose)
if ok:
sol_is_ok = True
return list(new_sol)
else:
# create a new solution and repeat the process
new_sol = repair_sol(new_sol, m_objs, H, pos)
def list_sol(m_objs, H, verbose=False):
"""
Create a matrix (W) with the integer solutions to this equation:
x_1 + x_2 + ... + x_{m_objs} = H (1)
The number of solutions is limit:
limit = binom{H+m-1}{H}
= binom{H+m-1}{m-1}
Input
m_objs int, number of objectives
H int, granularity >= 2
verbose bool, flag to show messages
Output
W (limit, m_objs) int np.array with solutions to Eq. (1)
"""
limit = get_limit(m_objs, H)
# output matrix
W = np.zeros((limit, m_objs), dtype=int)
# initial solution
sol_a = [0]*m_objs
sol_a[-1] = H
if verbose:
print("%2s %s" % (0, sol_a))
# add to W
W[0, :] = np.array(sol_a)
# main loop
for i in range(limit-1):
# get next solution
sol_b = next_sol(sol_a, m_objs, H)
# repair it, if needed
sol_c = full_repair_sol(sol_b, m_objs, H, verbose)
# update reference
sol_a = list(sol_c)
if verbose:
print("%2d %s" % (i+1, sol_a))
# add to W
W[i+1, :] = np.array(sol_a)
return W.copy()
def check_vectors(W, H, verbose):
"""
Check if the sum of each row of W equals H
Input
W (n_rows, m_objs) np.array with n_rows solutions
H granularity
verbose bool, flag to show messages
Output
to_keep (n_rows, ) bool np.array, if to_keep[i] == True, then
the i-th row of W is invalid
indices (l, ) int np.array, if W has invalid rows, indices
contains the indices of those invalid rows
"""
by_row = 1
suma = W.sum(axis=by_row)
indices = None
to_keep = suma != H
if to_keep.any():
print("Error, W has invalid rows")
indices = np.arange(len(to_keep), dtype=int)[to_keep]
else:
if verbose:
print("W is OK")
return None, None
return to_keep.copy(), indices.copy()
def get_reference_vectors(m_objs, H, verbose=False):
"""
Return a matrix of reference vectors
Input
m_objs int, number of objectives
H int, granularity >= 2
verbose bool, flag to show messages
Output
Wp (n_rows, m_objs) float np.array, reference vectors
"""
W = list_sol(m_objs, H, verbose)
# check
check_vectors(W, H, verbose)
# normalize
Wp = W/H
return Wp.copy() | /rocket_moea-0.1-py3-none-any.whl/rocket_moea/helpers/reference_vectors.py | 0.701815 | 0.486636 | reference_vectors.py | pypi |
from __future__ import print_function
import numpy as np
from numpy.linalg import norm
import os, sys
from rocket_moea.helpers import get_reference_vectors
def simplex_lattice(m_objs):
"""
Create a uniform set of reference vectors.
[Deb14] An Evolutionary Many-Objective Optimization Algorithm Using
Reference-Point-Based Nondominated Sorting Approach,
Part I: Solving Problems With Box Constrains
Input
m_objs int, number of objectives
Output
w (n_points, m_objs) float np.array, reference vectors
"""
# spacing H1, H2
spacing = {
2: (99, 0),
3: (12, 0),
5: (6, 0),
8: (3, 0),
10: (3, 0),
}
dims = m_objs
h1, h2 = spacing[m_objs]
# create first layer
w = get_reference_vectors(dims, h1)
# create second layer (optional)
if h2:
sf = 0.5 # this scaling factor is employed in [Deb14], Fig 4.
v = get_reference_vectors(dims, h2) * sf
merged = np.vstack((w, v))
w = merged.copy()
return w.copy()
def create_linear_front(m_objs, scale=None):
"""
Create the linear Pareto front of DTLZ1 according to
[Li15] An Evolutionary Many-Objective Optimization Algorithm Based on Dominance and Decomposition
Input
m_objs int, number of objectives
scale (m_objs, ) scale[i] is the scaling factor for the i-th objective (ie, fronts[:, i]).
If scale is None, the objectives are not scaled.
Output
front (n_points, m_objs) float np.array, sample front
"""
# uniform set of vectors
vectors = simplex_lattice(m_objs)
# number of vectors
n_points = vectors.shape[0]
by_row = 1
div = vectors.sum(axis=by_row).reshape((n_points, 1))
# linear pareto front
front = 0.5 * (vectors / div) # Eq. (14) [Li15]
# scale each dimension (optional)
if scale is not None:
for m in range(m_objs):
front[:, m] = front[:, m] * scale[m]
return front.copy()
def create_spherical_front(m_objs, scale=None):
"""
Create the spherical Pareto front of DTLZ2-4 according to
[Li15] An Evolutionary Many-Objective Optimization Algorithm Based on Dominance and Decomposition
Input
m_objs int, number of objectives
scale (m_objs, ) scale[i] is the scaling factor for the i-th objective (ie, fronts[:, i]).
If scale is None, the objectives are not scaled.
Output
front (n_points, m_objs) float np.array, sample front
"""
# uniform set of vectors
vectors = simplex_lattice(m_objs)
# number of vectors
n_points = vectors.shape[0]
by_row = 1
div = norm(vectors, axis=by_row).reshape((n_points, 1))
# spherical pareto front
front = vectors / div # Eq. (17) [Li15]
# scale each dimension (optional)
if scale is not None:
for m in range(m_objs):
front[:, m] = front[:, m] * scale[m]
return front.copy()
def create_inverted_linear_front(m_objs, scale=None):
"""
Create the inverted linear Pareto front of inv-DTLZ1 according to
[Tian17] PlatEMO: A MATLAB Platform for Evolutionary Multi-Objective Optimization
Input
m_objs int, number of objectives
scale (m_objs, ) scale[i] is the scaling factor for the i-th objective (ie, fronts[:, i]).
If scale is None, the objectives are not scaled.
Output
front (n_points, m_objs) float np.array, sample front
"""
# uniform set of vectors
vectors = simplex_lattice(m_objs)
# inverted front as defined in IDTLZ1.m
front = (1 - vectors) / 2
# scale each dimension (optional)
if scale is not None:
for m in range(m_objs):
front[:, m] = front[:, m] * scale[m]
return front.copy()
def get_front(mop_name, m_objs):
"""
Return the Pareto front of a given problem.
Input
mop_name str, name of problem
m_objs int, number of objectives
Output
front (pop_size, m_objs) np.array, Pareto front
"""
if mop_name == "dtlz1":
return create_linear_front(m_objs)
elif mop_name == "inv-dtlz1":
return create_inverted_linear_front(m_objs)
elif mop_name in ("dtlz2", "dtlz3"):
return create_spherical_front(m_objs)
else:
print("Problem not found (mop_name: %s)" % mop_name) | /rocket_moea-0.1-py3-none-any.whl/rocket_moea/fronts/fronts.py | 0.668015 | 0.499695 | fronts.py | pypi |
from enum import IntEnum
class directions(IntEnum):
Ahead = 0
Left = 1
Right = 2
Stop = 3
Backward = 4
ArmUp = 5
ArmDown = 6
TiltUp = 7
TiltDown = 8
Lights = 9
Camera = 10
Sound = 11
Parked = 12
LR = 13
def directionToInt(direction):
switcher = {
"Ahead" : directions.Ahead,
"Left" : directions.Left,
"Right" : directions.Right,
"Stop" : directions.Stop,
"Backward" : directions.Backward,
"ArmUp" : directions.ArmUp,
"ArmDown" : directions.ArmDown,
"TiltUp" : directions.TiltUp,
"TiltDown" : directions.TiltDown,
"Lights" : directions.Lights,
"Camera" : directions.Camera,
"Sound" : directions.Sound,
"Parked" : directions.Parked,
"LR" : directions.LR
}
return switcher.get(direction)
def directionToArray(direction):
switcher = {
"Ahead" : [0x0,0xA,0x0,0x0,0xA,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xD],
"Left" : [0x1,0xA,0x0,0x0,0x8,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xD],
"Right" : [0x0,0xA,0x0,0x1,0x3,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xD],
"Stop" : [0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xD],
"Backward" : [0x1,0xA,0x0,0x1,0xA,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xD],
"ArmUp" : [0x0,0x0,0x0,0x0,0x0,0x0,0xB,0x6,0x6,0x0,0x0,0x0,0x0,0x0,0xD],
"ArmDown" : [0x0,0x0,0x0,0x0,0x0,0x0,0x4,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xD],
"TiltUp" : [0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x5,0x6,0x6,0x0,0x0,0xD],
"TiltDown" : [0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xA,0xC,0xC,0x0,0x0,0xD],
"Lights" : [0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xC,0xC,0xF,0xF,0xD],
"Camera" : [0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xF,0xF,0xD],
"Sound" : [0x0,0x0,0x0,0x0,0x0,0x6,0x0,0x6,0x0,0x0,0xC,0x0,0xC,0xC,0xD],
"Parked" : [0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3,0x0,0x0,0x0,0x0,0xD],
"DI" : [0x0,0x0,0x0,0x0,0x0,0x0,0x5,0x6,0x6,0xA,0xC,0xC,0x0,0x0,0x0],
"GG" : [0x0,0x0,0x0,0x0,0x0,0x0,0x5,0x6,0x6,0xA,0xC,0xC,0x0,0x0,0x0],
"ER" : [0x0,0x0,0x0,0x0,0xE,0x0,0xA,0x0,0x0,0xC,0x0,0x0,0x0,0x0,0xD]
}
#high, low = byte >> 4, byte & 0x0F
print ("Command:----------------- ", direction, " ------------------------")
sequence = ("".join(hex(byte & 0x0F) for byte in switcher.get(direction)))
sequence = sequence.replace("0x", "")
sequence = sequence.upper()
print (sequence)
print ("-----------------------------------------------------------")
return (sequence)
def directionToJoystick(direction, L : int, R : int):
L = int(L)
R = int(R)
switcher = {
"LR" : [0x0,L,0x0,0x0,R,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xD],
}
#high, low = byte >> 4, byte & 0x0F
print ("Command:----------------- ", direction, " ------------------------")
sequence = ("".join(hex(byte & 0x0F) for byte in switcher.get(direction)))
sequence = sequence.replace("0x", "")
sequence = sequence.upper()
print (sequence)
print ("-----------------------------------------------------------")
return (sequence)
def intToDirection(i):
switcher = {
directions.Ahead : "Ahead",
directions.Left : "Left",
directions.Right : "Right",
directions.Stop : "Stop",
directions.Backward : "Backward",
directions.ArmUp : "ArmUp",
directions.ArmDown : "ArmDown",
directions.TiltUp : "TiltUp",
directions.TiltDown : "TiltDown",
directions.Lights : "Lights",
directions.Camera : "Camera",
directions.Sound : "Sound",
directions.Parked : "Parked",
directions.LR : "LR"
}
return switcher.get(i) | /rocket-pi-1.1.tar.gz/rocket-pi-1.1/rocket/modules/direction_converter.py | 0.434941 | 0.191328 | direction_converter.py | pypi |
import asyncio
from . import basic_requests, custom_exceptions, data_classes
from .constants import *
class RLS_Client(object):
"""
Represents the client, does everything. Initialize with api key and some other settings if you want to.
:param api_key: The key for the https://rocketleaguestats.com api.
If not supplied, an InvalidArgumentException will be thrown.
:param auto_rate_limit: If the api should automatically delay execution of request to satisfy the default ratelimiting.
When this is True automatic ratelimiting is enabled.
:param event_loop: The asyncio event loop that should be used.
If not supplied, the default one returned by ``asyncio.get_event_loop()`` is used.
:param _api_version: What version endpoint to use.
Do not change if you don't know what you're doing.
:type api_key: :class:`str`
:type auto_rate_limit: :class:`bool`, default is ``True``.
:type event_loop: :class:`asyncio.AbstractEventLoop`
:param _api_version: :class:`int`, default is ``1``.
"""
def __init__(self, api_key: str = None, auto_rate_limit: bool = True,
event_loop: asyncio.AbstractEventLoop = None, _api_version: int = 1):
if api_key is None:
raise custom_exceptions.NoAPIKeyError("No api key was supplied to client initialization.")
else:
self._api_key = api_key
self.auto_ratelimit = auto_rate_limit
if event_loop is None:
self._event_loop = asyncio.get_event_loop()
else:
self._event_loop = event_loop
self._api_version = _api_version
async def get_platforms(self):
"""
Gets the supported platforms for the api.
:return The platforms.
:rtype :class:`list` of :class:`str`.
"""
raw_playlist_data = await basic_requests.get_platforms(api_key=self._api_key, api_version=self._api_version,
loop=self._event_loop,
handle_ratelimiting=self.auto_ratelimit)
return [ID_PLATFORM_LUT.get(plat_id, None) for plat_id in [entry["id"] for entry in raw_playlist_data] if
ID_PLATFORM_LUT.get(plat_id, None) is not None]
async def get_playlists(self):
"""
Gets the supported playlists for the api.
:return The supported playlists (basically gamemodes, separate per platform) for the api.
:rtype A :class:`list` of :class:`data_classes.Playlists`.
"""
raw_playlist_data = await basic_requests.get_playlists(api_key=self._api_key, api_version=self._api_version,
loop=self._event_loop,
handle_ratelimiting=self.auto_ratelimit)
playlists = []
for raw_playlist in raw_playlist_data:
playlists.append(data_classes.Playlist(
raw_playlist["id"], raw_playlist["name"], ID_PLATFORM_LUT[raw_playlist["platformId"]],
raw_playlist["population"]["players"], raw_playlist["population"]["updatedAt"]
))
return playlists
async def get_seasons(self):
"""
Gets the supported seasons for the api.
:return The supported seasons for the api. One of them has ``Season.time_ended == None``, and ``Season.is_current == True``
which means it's the current season.
:rtype A :class:`list` of :class:`data_classes.Seasons`.
"""
raw_seasons_data = await basic_requests.get_seasons(api_key=self._api_key, api_version=self._api_version,
loop=self._event_loop,
handle_ratelimiting=self.auto_ratelimit)
seasons = []
for raw_season in raw_seasons_data:
seasons.append(data_classes.Season(
raw_season["seasonId"], raw_season["endedOn"] is None, raw_season["startedOn"],
raw_season["endedOn"]
))
return seasons
async def get_tiers(self):
"""
Gets the supported tiers for the api.
:return The supported tiers for the api.
:rtype A :class:`list` of :class:`data_classes.Tiers`.
"""
raw_tiers_data = await basic_requests.get_tiers(api_key=self._api_key, api_version=self._api_version,
loop=self._event_loop,
handle_ratelimiting=self.auto_ratelimit)
tiers = []
for raw_tier in raw_tiers_data:
tiers.append(data_classes.Tier(raw_tier["tierId"], raw_tier["tierName"]))
return tiers
async def get_player(self, unique_id: str, platform: str):
"""
Gets a single player from the api for a single player.
:param unique_id: The string to search for. Depending on the platform parameter,
this can represent Xbox Gamertag, Xbox user ID, steam 64 ID, or PSN username.
:param platform: The platform to search on. This should be one of the platforms defined in rocket_snake/constants.py.
:type platform: One of the platform constants in :mod:`rocket_snake.constants`, they are all :class:`str`.
:type unique_id: :class:`str`.
:return A :class:`data_classes.Player` object.
:rtype A :class:`data_classes.Player`, which is the player that was requested.
:raise: :class:`exceptions.APINotFoundError` if the player could be found.
"""
# If the player couldn't be found, the server returns a 404
raw_player_data = await basic_requests.get_player(unique_id, PLATFORM_ID_LUT[platform],
api_key=self._api_key, api_version=self._api_version,
loop=self._event_loop,
handle_ratelimiting=self.auto_ratelimit)
# We have some valid player data
player = data_classes.Player(raw_player_data["uniqueId"], raw_player_data["displayName"], platform,
avatar_url=raw_player_data["avatar"], profile_url=raw_player_data["profileUrl"],
signature_url=raw_player_data["signatureUrl"], stats=raw_player_data["stats"],
ranked_seasons=data_classes.RankedSeasons(raw_player_data["rankedSeasons"]))
return player
async def get_players(self, unique_id_platform_pairs: list):
"""
Does what :func:`RLS_Client.get_player` does but for up to 10 players at once.
.. warning::
This function can take really long to execute, sometimes up to 15 seconds or more.
This is because the API automatically updates the users' data from Rocket League itself, and sometimes doesn't.
There is currently no way of finding out how long using this function will take, as the API sometimes doesn't
update the users' data, and therefore returns the data quickly.
:param unique_id_platform_pairs: The users you want to search for. These are specified by unique id and platform.
:type unique_id_platform_pairs: A :class:`list` of :tuples:`tuple`s of unique ids and platform,
where both the unique ids and platforms are strings. The platform strings can be found in :mod:`rocket_snake.constants`,
and the unique ids are of the same type as what :func:`RLS_Client.get_player` uses.
Example: ``[("ExampleUniqueID1", constants.STEAM), ("ExampleUniqueID1OnXBOX", constants.XBOX1)]``
:return The players that could be found.
:rtype A :class:`list` of :class:`data_classes.Player` objects.
If a player could not be found, the corresponding index (the index in the ``unique_id_platform_pairs`` :class:`list`)
in the returned :class:`list` will be None.
"""
# We can only request 10 or less players at a time
if not (10 >= len(unique_id_platform_pairs) >= 1):
raise ValueError("The list of unique ids and platforms was not between 1 and 10 inclusive. Length was: {0}"
.format(len(unique_id_platform_pairs)))
# We convert the platforms to platform ids
unique_id_platform_pairs = [(entry[0], PLATFORM_ID_LUT[entry[1]]) for entry in unique_id_platform_pairs]
# If no player could be found, the server returns a 404
raw_players_data = await basic_requests.get_player_batch(tuple(unique_id_platform_pairs),
api_key=self._api_key, api_version=self._api_version,
loop=self._event_loop,
handle_ratelimiting=self.auto_ratelimit)
players = {
raw_player_data["uniqueId"]: data_classes.Player(raw_player_data["uniqueId"],
raw_player_data["displayName"],
ID_PLATFORM_LUT[req_pair[1]],
avatar_url=raw_player_data["avatar"],
profile_url=raw_player_data["profileUrl"],
signature_url=raw_player_data["signatureUrl"],
stats=raw_player_data["stats"],
ranked_seasons=data_classes.RankedSeasons(
raw_player_data["rankedSeasons"]))
for raw_player_data, req_pair in
list(zip(raw_players_data, unique_id_platform_pairs))}
ordered_players = []
for unique_id, platform in unique_id_platform_pairs:
ordered_players.append(players.get(unique_id, None))
return ordered_players
async def get_ranked_leaderboard(self, playlist):
"""
Gets the leaderboard for ranked playlists from RLS.
:param playlist: The playlist you want to get a leaderboard for.
:type playlist: A :class:`data_classes.Playlist` or :class:`int` if you pass a playlist id.
:return The leaderboard, that is, the top players in the requested ranked playlist.
The list is usually around 100 players long.
:rtype A :class:`list` of :class:`data_classes.Player` objects,
where the first one is the one with the highest rank in the requested playlist and current season, and the list is descending.
"""
raw_leaderboard_data = await basic_requests.get_ranked_leaderboard(
playlist if isinstance(playlist, int) else playlist.id, api_key=self._api_key,
api_version=self._api_version, loop=self._event_loop, handle_ratelimiting=self.auto_ratelimit)
leaderboard_players = [data_classes.Player(raw_player_data["uniqueId"], raw_player_data["displayName"],
raw_player_data["platform"]["name"],
avatar_url=raw_player_data["avatar"],
profile_url=raw_player_data["profileUrl"],
signature_url=raw_player_data["signatureUrl"],
stats=raw_player_data["stats"],
ranked_seasons=data_classes.RankedSeasons(
raw_player_data["rankedSeasons"]))
for raw_player_data in raw_leaderboard_data]
return leaderboard_players
async def get_stats_leaderboard(self, stat_type: str):
"""
Gets a list of the top 100 rocket league players according to a specified stat.
:param stat_type: What statistic you want to get a leaderboard for.
:type stat_type: One of the ``LEADERBOARD_*`` constants in :mod:`rocket_snake.constants`.
:return A ordered list of Player objects, where the first one is the one with the highest stat (descending).
:rtype A :class:`list` of :class:`data_classes.Player` objects,
where the first one is the one with the highest amount of the requested stat, and the list is descending.
"""
raw_leaderboard_data = await basic_requests.get_stats_leaderboard(
stat_type, api_key=self._api_key, api_version=self._api_version, loop=self._event_loop,
handle_ratelimiting=self.auto_ratelimit)
leaderboard_players = [data_classes.Player(raw_player_data["uniqueId"], raw_player_data["displayName"],
raw_player_data["platform"]["name"],
avatar_url=raw_player_data["avatar"],
profile_url=raw_player_data["profileUrl"],
signature_url=raw_player_data["signatureUrl"],
stats=raw_player_data["stats"],
ranked_seasons=data_classes.RankedSeasons(
raw_player_data["rankedSeasons"]))
for raw_player_data in raw_leaderboard_data]
return leaderboard_players
async def search_player(self, display_name: str, get_all: bool=False):
"""
Searches for a displayname and returns the results, this does not search all of Rocket League, but only the https://rocketleaguestats.com database.
:param display_name: The displayname you want to search for.
:param get_all: Whether to get all search results or not.
If this is True, the function may take many seconds to return,
since it will get all the search results from the API one page at a time.
If this is False, the function will only return with the first (called "page" in the http api) 20 results or less.
:type display_name: :class:`str`
:type :class:`bool`, default is ``False``.
:return The search results.
:rtype A :class:`list` of :class:`data_classes.Player` objects, where the first one is the top result.
If the search didn't return any players, this :class:`list` is empty (``[]``).
"""
raw_leader_board_data = [await basic_requests.search_players(display_name, 0, api_key=self._api_key,
api_version=self._api_version, loop=self._event_loop,
handle_ratelimiting=self.auto_ratelimit)]
if get_all:
# We calculate the number of pages to get
num_pages = raw_leader_board_data[0]["totalResults"] / raw_leader_board_data[0]["maxResultsPerPage"]
num_pages = int(num_pages) if int(num_pages) >= num_pages else int(num_pages) + 1
# We get all the other pages
for i in range(1, num_pages):
raw_leader_board_data.append(await basic_requests.search_players(display_name, i, api_key=self._api_key,
api_version=self._api_version, loop=self._event_loop,
handle_ratelimiting=self.auto_ratelimit))
# We transform the pages into Player objects
sorted_results = []
for page in raw_leader_board_data:
sorted_results.extend(page["data"])
return [data_classes.Player(raw_player_data["uniqueId"], raw_player_data["displayName"],
raw_player_data["platform"]["name"], avatar_url=raw_player_data["avatar"],
profile_url=raw_player_data["profileUrl"], signature_url=raw_player_data["signatureUrl"],
stats=raw_player_data["stats"],
ranked_seasons=data_classes.RankedSeasons(raw_player_data["rankedSeasons"]))
for raw_player_data in sorted_results] | /rocket_snake-0.1.5.tar.gz/rocket_snake-0.1.5/rocket_snake/client.py | 0.777427 | 0.227148 | client.py | pypi |
These are all the pure data classes that are used by the api client.
In general, these should not be instantiated, but created by the api client itself.
"""
from collections import namedtuple
from . import constants
class Tier(namedtuple("Tier", ("id", "name"))):
"""
Represents a tier. Unless otherwise specified, this will be created with data from the last season.
Fields:
id: int; The id for this Tier.
name: str; The name of this Tier.
"""
pass
class Season(namedtuple("Season", ("id", "is_current", "time_started", "time_ended"))):
"""
Represents a season. Each season is time-bounded, and if a season hasn't ended yet, the time_ended field will be None
Fields:
id: int; The id for this season. Unique for each season.
is_current: bool; True if the season is currently active (hasn't ended). False otherwise.
time_started: int; A timestamp of when the season started (seconds since unix epoch, see output of time.time()).
time_ended: int; A timestamp of when the season ended (see time_started).
If the season hasn't ended (is_current is True), this field is None.
"""
pass
class Playlist(namedtuple("Playlist", ("id", "name", "platform", "population", "last_updated"))):
"""
Represents a playlist. There is a playlist for each unique combination of platform and gamemode.
:var id: The id for this playlist. Unique for each gamemode, not for each platform.
:var name: "Gamemode", such as "Ranked Duels" or "Hoops".
:var platform: The platform this playlist is on.
Corresponds to the platforms in the module constants.
:var population: The number of people currently (see last_updated) playing this playlist.
Note that this only count people on this playlist's platform.
:var last_updated: A timestamp (seconds since unix epoch, see output of time.time()) of when the population field was updated.
"""
pass
class SeasonPlaylistRank(namedtuple("SeasonPlaylistRank", ("rankPoints", "division", "matchesPlayed", "tier"))):
pass
class RankedSeason(dict):
"""Represents a single ranked season for a single user."""
def __getitem__(self, item):
if isinstance(item, Playlist):
return self[item.id]
else:
return super().__getitem__(item)
def __str__(self):
return "".join(["\n\tRanked season on playlist {0}: {1}".format(playlist_id, str(rank)) for playlist_id, rank in
self.items()])
class RankedSeasons(object):
"""
Represents the ranked data of a user. These can be indexed by season id or Season object to get data for a
specific season (a RankedSeason object). This object defines some method to be more similar to a dictionary.
Do not create these yourself.
:var data: The raw dict to convert into this object.
"""
def __init__(self, data: dict):
self.ranked_seasons = {}
for season_id, ranked_data in data.items():
self.ranked_seasons[season_id] = RankedSeason({key: SeasonPlaylistRank(val.get("rankPoints", None),
val.get("division", None),
val.get("matchesPlayed", None),
val.get("tier", None)) for key, val
in ranked_data.items()})
def __getitem__(self, item):
if isinstance(item, Season):
return self.ranked_seasons[item.id]
else:
return self.ranked_seasons[item]
def __contains__(self, item):
if isinstance(item, Season):
return item.id in self.ranked_seasons
else:
return item in self.ranked_seasons
def __len__(self):
return len(self.ranked_seasons)
def __iter__(self):
return iter(self.ranked_seasons)
def __getattr__(self, item):
regular_functions = {
"__init__": self.__init__,
"__getitem__": self.__getitem__,
"__contains__": self.__contains__,
"__len__": self.__len__,
"__iter__": self.__iter__,
}
return regular_functions.get(item, getattr(self.ranked_seasons, item))
def __str__(self):
return "\n".join(["Season {0}: {1}".format(season_id, str(ranked_season)) for season_id, ranked_season in
self.ranked_seasons.items()])
class Player(object):
"""
Represents a player. Some ways of getting player object might not populate all fields. If a field isn't populated, it will be None.
"""
def __init__(self, uid: str, display_name: str, platform: str, avatar_url: str = None, profile_url: str = None,
signature_url: str = None,
stats: dict = None, ranked_seasons: RankedSeasons = None):
# Our parameters
self.uid = uid
self.display_name = display_name
self.platform = platform
self.platform_id = constants.PLATFORM_ID_LUT.get(platform, None)
self.avatar_url = avatar_url
self.profile_url = profile_url
self.signature_url = signature_url
self.stats = stats
self.ranked_seasons = ranked_seasons
def __str__(self):
return ("Rocket League player \'{0}\' with unique id {1}:\n\t"
"Platform: {2}, id {3}\n\t"
"Avatar url: {4}\n\t"
"Profile url: {5}\n\t"
"Signature url: {6}\n\t"
"Stats: {7}\n\t"
"Ranked data: \n\t{8}".format(self.display_name, self.uid, self.platform, self.platform_id,
self.avatar_url,
self.profile_url, self.signature_url, self.stats,
"\n\t".join(str(self.ranked_seasons).split("\n"))))
def __repr__(self):
return str(self) | /rocket_snake-0.1.5.tar.gz/rocket_snake-0.1.5/rocket_snake/data_classes.py | 0.929848 | 0.412767 | data_classes.py | pypi |
# Rocket Space Stuff
Rocket Space Stuff is a Python library that allows you to interact with various space-related API endpoints. With this library, you can retrieve information about astronauts, launches, and launchers.
## Links and Creators:
* Creator: Miro Rava [Linkedin profile](https://www.linkedin.com/in/miro-rava/)
* Tester: Oleg Lastocichin [Linkedin profile](https://www.linkedin.com/in/oleg-lastocichin-845733252/)
* [Github page for the entire project](https://github.com/MiroRavaProj/Web-service-and-API-for-Space-Data)
## Installation
```shell
python -m pip install rocket-space-stuff
```
## Usage and methods for Astronaut Objects
### Initialize Astronaut Object
* From Database:
```python
# Initialize the SpaceAPI client
api = SpaceApi()
# Find astronaut by name
astro = api.find_astro_by('name', 'John Smith')
```
* Manually
```python
from space_py import Astronaut
astro = Astronaut({"name": name, "date_of_birth": birth, "date_of_death": death, "nationality": nationality,
"bio": description,
"twitter": twitter, "instagram": insta, "wiki": wiki,
"profile_image": profile_img,
"profile_image_thumbnail": profile_img_thmb,
"flights_count": flights, "landings_count": landings, "last_flight": last_fl,
"first_flight": first_fl, "status_name": status, "type_name": enroll,
"agency_name": agency, "agency_type": agency_type,
"agency_country_code": agency_countries, "agency_abbrev": agency_acr,
"agency_logo_url": agency_logo})
```
### Getters and Setters
`age`
Retrieves the astronaut's age.
```python
# Get astronaut's age
age = astro.age
```
`age_of_death`
Retrieves the astronaut's age of death.
```python
# Get astronaut's age_of_death
age_of_death = astro.age_of_death
```
`agency_abbrev`
Retrieves and Set the astronaut's agency abbreviation.
```python
# Get astronaut's agency abbreviation
agency_abbrev = astro.agency_abbrev
# Set astronaut's agency abbreviation
astro.agency_abbrev = "NASA"
```
`agency_country_code`
Retrieves and Set the astronaut's agency country code.
```python
# Get astronaut's agency country code
agency_country_code = astro.agency_country_code
# Set astronaut's agency country code
astro.agency_country_code = "US"
```
`agency_logo_url`
Retrieves and Set the astronaut's agency logo url.
```python
# Get astronaut's agency logo url
agency_logo_url = astro.agency_logo_url
# Set astronaut's agency logo url
astro.agency_logo_url = "https://www.nasa.gov/sites/default/files/images/nasa-logo.png"
```
`agency_name`
Retrieves and Set the astronaut's agency name.
```python
# Get astronaut's agency name
agency_name = astro.agency_name
# Set astronaut's agency name
astro.agency_name = "National Aeronautics and Space Administration"
```
`agency_type`
Retrieves and Set the astronaut's agency type.
```python
# Get astronaut's agency type
agency_type = astro.agency_type
# Set astronaut's agency type
astro.agency_type = "Governmental"
```
`bio`
Retrieves and Set the astronaut's bio.
```python
# Get astronaut's bio
bio = astro.bio
# Set astronaut's bio
astro.bio = "John Smith is an astronaut with NASA. He has flown on 3 space missions."
```
`birth_date`
Retrieves and Set the astronaut's birth date.
```python
# Get astronaut's birth date
birth_date = astro.birth_date
# Set astronaut's birth date
astro.birth_date = "1970-01-01"
```
`death_date`
Retrieves and Set the astronaut's death date.
```python
# Get astronaut's death date
death_date = astro.death_date
# Set astronaut's death date
astro.death_date = "2050-01-01"
```
`first_flight`
Retrieves and Set the astronaut's first flight.
```python
# Get astronaut's first flight
first_flight = astro.first_flight
# Set astronaut's first flight
astro.first_flight = "2000-01-01"
```
`flights_count`
Retrieves and Set the astronaut's flights count.
```python
# Get astronaut's flights count
flights_count = astro.flights_count
# Set astronaut's flights count
astro.flights_count = "3"
```
`instagram`
Retrieves and Set the astronaut's Instagram page url.
```python
# Get astronaut's Instagram page url
instagram = astro.instagram
# Set astronaut's Instagram handle
astro.instagram = "https://www.instagram.com/j_smith_astro"
```
`jsonify`
Retrieves the astronaut's information in JSON format.
```python
# Get astronaut's information in JSON format
json_data = astro.jsonify
```
`landings_count`
Retrieves and Set the astronaut's landings count.
```python
# Get astronaut's landings count
landings_count = astro.landings_count
# Set astronaut's landings count
astro.landings_count = "2"
```
`last_flight`
Retrieves and Set the astronaut's last flight.
```python
# Get astronaut's last flight
last_flight = astro.last_flight
# Set astronaut's last flight
astro.last_flight = "2022-01-01"
```
`name`
Retrieves and Set the astronaut's name.
```python
# Get astronaut's name
name = astro.name
# Set astronaut's name
astro.name = "John Smith"
```
`nationality`
Retrieves and Set the astronaut's nationality.
```python
# Get astronaut's nationality
nationality = astro.nationality
# Set astronaut's nationality
astro.nationality = "USA"
```
`profile_image`
Retrieves and Set the astronaut's profile image url.
```python
# Get astronaut's profile image url
profile_image = astro.profile_image
# Set astronaut's profile image url
astro.profile_image = "https://www.example.com/images/j_smith_astro.jpg"
```
`profile_image_thumbnail`
Retrieves and Set the astronaut's profile image thumbnail url.
```python
# Get astronaut's profile image thumbnail url
profile_image_thumbnail = astro.profile_image_thumbnail
# Set astronaut's profile image thumbnail url
astro.profile_image_thumbnail = "https://www.example.com/images/j_smith_astro_thumbnail.jpg"
```
`show_basic_info`
Retrieves the astronaut's basic information.
```python
# Get astronaut's basic information
basic_info = astro.show_basic_info
```
`status_name`
Retrieves and Set the astronaut's status name.
```python
# Get astronaut's status name
status_name = astro.status_name
# Set astronaut's status name
astro.status_name = "Active"
```
`twitter`
Retrieves and Set the astronaut's twitter url.
```python
# Get astronaut's twitter url
twitter = astro.twitter
# Set astronaut's twitter handle
astro.twitter = "https://twitter.com/j_smith_astro"
```
`type_name`
Retrieves and Set the astronaut's type name.
```python
# Get astronaut's type name
type_name = astro.type_name
# Set astronaut's type name
astro.type_name = "Government"
```
`wiki`
Retrieves and Set the astronaut's wiki page url.
```python
# Get astronaut's wiki page url
wiki = astro.wiki
# Set astronaut's wiki page url
astro.wiki = "https://en.wikipedia.org/wiki/John_Smith_(astronaut)"
```
## Usage and methods for Launcher Objects
### Initialize Launcher Object
* From Database:
```python
# Initialize the SpaceAPI client
api = SpaceApi()
# Find astronaut by name
launcher = api.find_launcher_by('full_name', 'Atlas V')
```
* Manually
```python
from space_py import Launcher
launcher = Launcher({"flight_proven": flight_proven, "serial_number": serial_number, "status": status,
"details": details, "image_url": image_url, "flights": flights,
"last_launch_date": last_launch_date, "first_launch_date": first_launch_date,
"launcher_config_full_name": launcher_config_full_name})
```
* The methods `jsonify` and `show_basic_info` are similar to the Astronaut's ones.
* All these following methods are both Getters and Setters similarly to the Astronaut's ones:
```python
[launcher.description, launcher.first_launch, launcher.flights_count, launcher.full_name, launcher.is_flight_proven,
launcher.last_launch, launcher.launcher_image, launcher.serial_n, launcher.status]
```
## Usage and methods for Launch Objects
### Initialize Launch Object
* From Database:
```python
# Initialize the SpaceAPI client
api = SpaceApi()
# Find astronaut by name
launch = api.find_launch_by('name', 'Atlas V')
```
* Manually
```python
from space_py import Launch
launch = Launch({"name": name, "net": net, "window_start": window_start,
"window_end": window_end, "failreason": fail_reason, "image": image,
"infographic": infographic, "orbital_launch_attempt_count": orbital_launch_attempt_count,
"orbital_launch_attempt_count_year": orbital_launch_attempt_count_year,
"location_launch_attempt_count": location_launch_attempt_count,
"location_launch_attempt_count_year": location_launch_attempt_count_year,
"pad_launch_attempt_count": pad_launch_attempt_count,
"pad_launch_attempt_count_year": pad_launch_attempt_count_year,
"agency_launch_attempt_count": agency_launch_attempt_count,
"agency_launch_attempt_count_year": agency_launch_attempt_count_year,
"status_name": status_name, "launch_service_provider_name": launch_service_provider_name,
"launch_service_provider_type": launch_service_provider_type, "rocket_id": rocket_id,
"rocket_configuration_full_name": rocket_config_full_name,
"mission_name": mission_name, "mission_description": mission_description,
"mission_type": mission_type, "mission_orbit_name": mission_orbit_name,
"pad_wiki_url": pad_wiki_url, "pad_longitude": pad_longitude,
"pad_latitude": pad_latitude, "pad_location_name": pad_location_name,
"pad_location_country_code": pad_location_country_code})
```
* The methods `jsonify` and `show_basic_info` are similar to the Astronaut's ones.
* All these methods are both Getters and Setters similarly to the Astronaut's ones:
```python
[launch.agency_launch_attempt_count, launch.agency_launch_attempt_count_year, launch.fail_reason, launch.image,
launch.infographic, launch.jsonify, launch.launch_service_provider_name, launch.launch_service_provider_type,
launch.location_launch_attempt_count, launch.location_launch_attempt_count_year, launch.mission_description,
launch.mission_name, launch.mission_orbit_name, launch.mission_type, launch.name, launch.net,
launch.orbital_launch_attempt_count, launch.orbital_launch_attempt_count_year, launch.pad_latitude,
launch.pad_launch_attempt_count, launch.pad_launch_attempt_count_year, launch.pad_location_country_code,
launch.pad_location_name, launch.pad_longitude, launch.pad_wiki_url, launch.rocket_config_full_name, launch.rocket_id,
launch.show_basic_info, launch.status_name, launch.window_end, launch.window_start]
```
## Usage and methods for SpaceApi Objects
###Populate Astronaut Launch and Launcher with SpaceApi
* Instead of Initializing manually Astronaut, Launch or Launcher Objects, we can use SpaceApi `populate` methods.
```python
from space_py import SpaceApi
api = SpaceApi()
astro = api.populate_astro(name: str, birth: str, death: str, nationality: str, description: str, flights: str,
landings: str, last_fl: str, agency_acr: str, twitter: str = "None", insta: str = "None",
wiki: str = "None", profile_img: str = "None", profile_img_thmb: str = "None",
first_fl: str = "None",
status: str = "None", enroll: str = "None", agency: str = "None", agency_type: str = "None",
agency_countries: str = "None", agency_logo: str = "None")
launch = api.populate_launch(name: str, net: str, status_name: str, launch_service_provider_name: str,
rocket_config_full_name: str,
mission_description: str, pad_location_name: str,
window_start: str = "None", window_end: str = "None", fail_reason: str = "None",
image: str = "None",
infographic: str = "None", orbital_launch_attempt_count: str = "None",
orbital_launch_attempt_count_year: str = "None",
location_launch_attempt_count: str = "None", location_launch_attempt_count_year: str = "None",
pad_launch_attempt_count: str = "None", pad_launch_attempt_count_year: str = "None",
agency_launch_attempt_count: str = "None", agency_launch_attempt_count_year: str = "None",
launch_service_provider_type: str = "None", rocket_id: str = "None",
mission_name: str = "None", mission_type: str = "None",
mission_orbit_name: str = "None", pad_wiki_url: str = "None", pad_longitude: str = "None",
pad_latitude: str = "None",
pad_location_country_code: str = "None")
launcher = api.populate_launcher(launcher_config_full_name: str, serial_number: str, status: str, details: str, flights: str,
image_url: str = "None",
last_launch_date: str = "None", first_launch_date: str = "None",
flight_proven: str = "False")
```
### Url methods
* `default_url`: Returns the default API URL.
```python
from space_py import SpaceApi
api = SpaceApi()
default_url = api.default_url
```
* `url`: Returns the current API URL and can permit you to change it.
```python
from space_py import SpaceApi
api = SpaceApi()
print(api.url)
# https://current-api-url.com
new_url = 'https://new-api-url.com'
api.url = new_url
print(api.url)
# https://new-api-url.com
```
### Add methods
* `add_astro(astro: Astronaut)`: Adds a new astronaut to the API. The `astro` parameter should be an Astronaut object containing the astronaut's information.
```python
from space_py import SpaceApi, Astronaut
api = SpaceApi()
new_astro = Astronaut({"name": name, "date_of_birth": birth, "date_of_death": death, "nationality": nationality,
"bio": description,
"twitter": twitter, "instagram": insta, "wiki": wiki,
"profile_image": profile_img,
"profile_image_thumbnail": profile_img_thmb,
"flights_count": flights, "landings_count": landings, "last_flight": last_fl,
"first_flight": first_fl, "status_name": status, "type_name": enroll,
"agency_name": agency, "agency_type": agency_type,
"agency_country_code": agency_countries, "agency_abbrev": agency_acr,
"agency_logo_url": agency_logo})
api.add_astro(new_astro)
```
* `add_launch(launch: Launch)`: Adds a new launch to the API. The `launch` parameter should be a Launch Object containing the launch's information.
```python
from space_py import SpaceApi, Launch
api = SpaceApi()
new_astro = Launch({"name": name, "net": net, "window_start": window_start,
"window_end": window_end, "failreason": fail_reason, "image": image,
"infographic": infographic,
"orbital_launch_attempt_count": orbital_launch_attempt_count,
"orbital_launch_attempt_count_year": orbital_launch_attempt_count_year,
"location_launch_attempt_count": location_launch_attempt_count,
"location_launch_attempt_count_year": location_launch_attempt_count_year,
"pad_launch_attempt_count": pad_launch_attempt_count,
"pad_launch_attempt_count_year": pad_launch_attempt_count_year,
"agency_launch_attempt_count": agency_launch_attempt_count,
"agency_launch_attempt_count_year": agency_launch_attempt_count_year,
"status_name": status_name,
"launch_service_provider_name": launch_service_provider_name,
"launch_service_provider_type": launch_service_provider_type, "rocket_id": rocket_id,
"rocket_configuration_full_name": rocket_config_full_name,
"mission_name": mission_name, "mission_description": mission_description,
"mission_type": mission_type, "mission_orbit_name": mission_orbit_name,
"pad_wiki_url": pad_wiki_url, "pad_longitude": pad_longitude,
"pad_latitude": pad_latitude, "pad_location_name": pad_location_name,
"pad_location_country_code": pad_location_country_code})
api.add_launch(new_astro)
```
* `add_launcher(launcher: Launcher)`: Adds a new launcher to the API. The `launcher` parameter should be a Launch Object containing the launcher's information.
```python
from space_py import SpaceApi, Launcher
api = SpaceApi()
new_astro = Launcher({"flight_proven": flight_proven, "serial_number": serial_number, "status": status,
"details": details, "image_url": image_url, "flights": flights,
"last_launch_date": last_launch_date, "first_launch_date": first_launch_date,
"launcher_config_full_name": launcher_config_full_name})
api.add_launcher(new_astro)
```
### Delete methods
* `delete_astro_by(field: str, value: str)`: Deletes an astronaut from the API based on the specified field and value.
```python
from space_py import SpaceApi
api = SpaceApi()
api.delete_astro_by('name', 'John Smith')
```
* `delete_launch_by(field: str, value: str)`: Deletes a launch from the API based on the specified field and value.
```python
from space_py import SpaceApi
api = SpaceApi()
api.delete_launch_by('name', 'Falcon 9')
```
* `delete_launcher_by(field: str, value: str)`: Deletes a launcher from the API based on the specified field and value.
```python
from space_py import SpaceApi
api = SpaceApi()
api.delete_launcher_by('full_name', 'Atlas V')
```
### Find methods
#### Used to find an entry with exact match
* `find_astro_by(field: str, value: str)`: Retrieves an astronaut from the API based on the specified field and value. If astronaut is found, `astro` is an Astronaut Object, otherwise it is a string like: `'entry non found'`
```python
from space_py import SpaceApi
api = SpaceApi()
astro = api.find_astro_by('name', 'John Smith')
```
* `find_launch_by(field: str, value: str)`: Retrieves a launch from the API based on the specified field and value. If launch is found, `launch` is a Launch Object, otherwise it is a string like: `'entry non found'`
```python
from space_py import SpaceApi
api = SpaceApi()
launch = api.find_launch_by('name', 'Falcon 9')
```
* `find_launcher_by(field: str, value: str)`: Retrieves a launcher from the API based on the specified field and value. If launcher is found, `launcher` is a Launcher Object, otherwise it is a string like: `'entry non found'`
```python
from space_py import SpaceApi
api = SpaceApi()
launcher = api.find_launcher_by('full_name', 'Atlas V')
```
### Search methods
#### Used to search for and entry that contains `value` in the `field`
* `search_astro_by(field: str, value: str)`: Retrieves an astronaut from the API based on the specified field and value. If astronaut is found, `astro` is a dictionary containing Astronaut Objects, otherwise it is a dictionary like: `{'error':'entry non found'}`
```python
from space_py import SpaceApi
api = SpaceApi()
astro = api.search_astro_by('name', 'John Smith')
```
* `search_launch_by(field: str, value: str)`: Retrieves a launch from the API based on the specified field and value. If launch is found, `launch` is a dictionary containing Launch Objects, otherwise it is a dictionary like: `{'error':'entry non found'}`
```python
from space_py import SpaceApi
api = SpaceApi()
launch = api.search_launch_by('name', 'Falcon 9')
```
* `search_launcher_by(field: str, value: str)`: Retrieves a launcher from the API based on the specified field and value. If launcher is found, `launcher` is a dictionary containing Launcher Objects, otherwise it is a dictionary like: `{'error':'entry non found'}`
```python
from space_py import SpaceApi
api = SpaceApi()
launcher = api.search_launcher_by('full_name', 'Atlas V')
```
### Update methods
#### Used to overwrite an entry that exactly mach `value` in `field`
* `update_astro_by(field: str, value: str, update: Astronaut)`: Updates an astronaut record in the API based on the specified field and value. The `astro` parameter should be an Astronaut object containing the astronaut's information.
```python
from space_py import SpaceApi, Astronaut
api = SpaceApi()
updated_astro = Astronaut({"name": name, "date_of_birth": birth, "date_of_death": death, "nationality": nationality,
"bio": description,
"twitter": twitter, "instagram": insta, "wiki": wiki,
"profile_image": profile_img,
"profile_image_thumbnail": profile_img_thmb,
"flights_count": flights, "landings_count": landings, "last_flight": last_fl,
"first_flight": first_fl, "status_name": status, "type_name": enroll,
"agency_name": agency, "agency_type": agency_type,
"agency_country_code": agency_countries, "agency_abbrev": agency_acr,
"agency_logo_url": agency_logo})
api.update_astro_by('name', 'John Smith', updated_astro)
```
* `update_launch_by(field: str, value: str, update: Launch)`: Updates a launch record in the API based on the specified field and value. The `launch` parameter should be a Launch Object containing the launch's information.
```python
from space_py import SpaceApi, Launch
api = SpaceApi()
updated_astro = Launch({"name": name, "net": net, "window_start": window_start,
"window_end": window_end, "failreason": fail_reason, "image": image,
"infographic": infographic,
"orbital_launch_attempt_count": orbital_launch_attempt_count,
"orbital_launch_attempt_count_year": orbital_launch_attempt_count_year,
"location_launch_attempt_count": location_launch_attempt_count,
"location_launch_attempt_count_year": location_launch_attempt_count_year,
"pad_launch_attempt_count": pad_launch_attempt_count,
"pad_launch_attempt_count_year": pad_launch_attempt_count_year,
"agency_launch_attempt_count": agency_launch_attempt_count,
"agency_launch_attempt_count_year": agency_launch_attempt_count_year,
"status_name": status_name,
"launch_service_provider_name": launch_service_provider_name,
"launch_service_provider_type": launch_service_provider_type, "rocket_id": rocket_id,
"rocket_configuration_full_name": rocket_config_full_name,
"mission_name": mission_name, "mission_description": mission_description,
"mission_type": mission_type, "mission_orbit_name": mission_orbit_name,
"pad_wiki_url": pad_wiki_url, "pad_longitude": pad_longitude,
"pad_latitude": pad_latitude, "pad_location_name": pad_location_name,
"pad_location_country_code": pad_location_country_code})
api.update_launch_by('name', 'Falcon 9', updated_astro)
```
* `update_launcher_by(field: str, value: str, update: Launcher)`: Updates a launcher record in the API based on the specified field and value. The `launcher` parameter should be a Launch Object containing the launcher's information.
```python
from space_py import SpaceApi, Launcher
api = SpaceApi()
updated_astro = Launcher({"flight_proven": flight_proven, "serial_number": serial_number, "status": status,
"details": details, "image_url": image_url, "flights": flights,
"last_launch_date": last_launch_date, "first_launch_date": first_launch_date,
"launcher_config_full_name": launcher_config_full_name})
api.update_launcher_by('full_name', 'Atlas V', updated_astro)
```
## Contributing
If you would like to contribute to the development of SpaceApi, please feel free to submit a pull request.
| /rocket-space-stuff-0.1.0.tar.gz/rocket-space-stuff-0.1.0/README.md | 0.759404 | 0.917154 | README.md | pypi |
from __future__ import annotations
from datetime import datetime, timedelta
from enum import auto, Enum
from typing import Tuple, Union
import logging # noqa: I100
import os
import re
import json # noqa: I100
import base64 # noqa: I100
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding, rsa
from .exceptions import (
BadlyFormattedTokenException,
InvalidTokenException,
MethodMismatchException,
NoPrivateKeyException,
PathMismatchException,
TokenExpiredException,
)
# disbaled I100; in places where I think changing the import order
# would make the code less readable
LOGGER = logging.getLogger(__file__)
class HTTPMethods(Enum):
"""Class to hold the available HTTP request methods"""
GET = auto()
HEAD = auto()
POST = auto()
PUT = auto()
DELETE = auto()
CONNECT = auto()
OPTIONS = auto()
TRACE = auto()
PATCH = auto()
class RocketToken:
"""Class to represent a public key, private key pair used
for encrypting, decrypting, creating and validating tokens
"""
def __init__(
self,
public_key: Union[rsa.RSAPublicKey, None] = None,
private_key: Union[rsa.RSAPrivateKey, None] = None,
) -> None:
"""Creates an instance of the RocketToken class, optionally providing
a public and private key
Args:
public_key: The public key to use for encrypting the token.
private_key: The private key that matches the public_key and is
used for decrypting the token.
"""
if os.environ.get("ROCKET_DEVELOPER_MODE", "false") == "true":
self.public_key, self.private_key = RocketToken._load_keys_from_env()
else:
self.public_key = public_key
self.private_key = private_key
def decode_public_key(self) -> str:
"""
Returns the Public key in PEM format.
Returns (str): Public key
"""
return self.public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo,
).decode("utf-8")
@staticmethod
def _load_keys_from_env() -> Tuple[rsa.RSAPublicKey, rsa.RSAPrivateKey]:
"""Loads a public key and private key from environmental variables.
Expected names for the environmental variables are `public_key` and
`private_key` respectively. The private_key is optional.
Returns:
public_key rsa.RSAPublicKey
private_key rsa.RSAPrivateKey
"""
if os.environ.get("ROCKET_DEVELOPER_MODE", "false") == "true":
public_key = os.environ["RT_DEV_PUBLIC"]
private_key = os.environ.get("RT_DEV_PRIVATE", None)
else:
public_key = os.environ["public_key"]
private_key = os.environ.get("private_key", None)
public_key = base64.b64decode(public_key.encode('utf-8'))
public_key = serialization.load_pem_public_key(
public_key, backend=default_backend()
)
if private_key is not None:
private_key = base64.b64decode(private_key.encode('utf-8'))
private_key = serialization.load_pem_private_key(
private_key, password=None, backend=default_backend()
)
return public_key, private_key
@classmethod
def rocket_token_from_env(cls: RocketToken) -> RocketToken:
"""Loads a public key and private key from environmental variables.
Expected names for the environmental variables are public_key and
private_key respectively. The private_key is optional.
Args:
cls (RocketToken): Instance of RocketToken class
Returns: RocketToken
"""
public_key, private_key = RocketToken._load_keys_from_env()
return cls(public_key, private_key)
@classmethod
def rocket_token_from_path(
cls, public_path: str = None, private_path: Union[str, None] = None
) -> RocketToken:
"""
Creates an instance of the RocketToken class from a
public and private key stored on disk. The private key
is optional.
Args:
public_path (str): File path to the public key file.
private_path (str): File path to the private key file.
Returns (RocketToken): RocketToken
"""
public_key, private_key = None, None
with open(public_path, "rb") as public:
public_key = serialization.load_pem_public_key(
public.read(), backend=default_backend()
)
if private_path:
with open(private_path, "rb") as keyfile:
private_key = serialization.load_pem_private_key(
keyfile.read(), password=None, backend=default_backend()
)
return cls(public_key=public_key, private_key=private_key)
@staticmethod
def generate_key_pair(
path: str,
key_size: int = 4096,
public_exponent: int = 65537,
) -> Tuple[rsa.RSAPrivateKey, rsa.RSAPublicKey]:
"""
Generates and saves public and private key files in PEM format.
Args:
path (str): Directory Location to save public and private key pairs.
key_size (int): How many bits long the key should be.
public_exponent int: indicates what one mathematical property of the
key generation will be. Unless you have a
valid reason to do otherwise, always use 65537.
Returns (tuple[rsa.RSAPrivateKey, rsa.RSAPublicKey]): private_key, public_key
"""
if not os.path.isdir(path):
os.mkdir(path)
private_key = rsa.generate_private_key(
public_exponent=public_exponent,
key_size=key_size,
backend=default_backend(),
)
public_key = private_key.public_key()
pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
)
public = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo,
)
with open(f"{path}/id_rsa", "wb") as binaryfile:
binaryfile.write(pem)
with open(f"{path}/id_rsa.pub", "wb") as binaryfile:
binaryfile.write(public)
return private_key, public_key
@staticmethod
def validate_web_token(token: dict, path: str, method: str) -> Union[None, True]:
"""Verifies that the passed token has a `path` and `method`
that matches those specified in the argument. It also checks
that the token has not expired.
Args:
token (dict): User API token to validate.
Raises:
BadlyFormattedTokenException: Token is missing required keys.
TokenExpiredException: Token has expired.
PathMismatchException: Token Path != required path
MethodMismatchException: Token Method != required method
Returns: Union[None, True]
"""
expected_keys = ["path", "exp", "method"]
if not set(expected_keys).issubset(token.keys()):
raise BadlyFormattedTokenException(
f"Incorrect token keys; token must contain at least: {expected_keys}"
)
if not datetime.utcnow() < datetime.fromisoformat(token["exp"]):
raise TokenExpiredException(f"token exp: `{token['exp']}` has expired.")
if path.lower() != token["path"].lower():
raise PathMismatchException(f"token path `{token['path']}` != `{path}`")
if method.lower() != token["method"].lower():
raise MethodMismatchException(
f"token method `{token['method']}` != `{method}`"
)
return True
def _encrypt_dict(self, d: dict) -> bytes:
encrypted_token: bytes = self.public_key.encrypt(
bytes(json.dumps(d), encoding="utf-8"),
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None,
),
)
return base64.b64encode(encrypted_token)
def generate_web_token(self, path: str, exp: int, method: str, **kwargs) -> str:
"""Generates a web token for the specified `path`, `method` and expires
and after current_datetime + timedelata(minutes=exp)
Args:
path (str): The REST endpoint path that the token is valid for.
exp (int): A +ve integer of minutes until the token should expire.
method (str): The HTTP method that the token is valid for.
kwargs: The extra key-value payloads to add to the dictionary.
Raises:
ValueError: Raised when an invalid HTTP method is passed in the `method`
arguemnt.
Returns:
str: The web token.
"""
try:
HTTPMethods[method.upper()]
except KeyError:
raise ValueError(f"{method.upper()} is not a valid HTTP Method")
if exp <= 0:
raise ValueError("exp should be larger than 0.")
token = {
"path": path,
"exp": (datetime.utcnow() + timedelta(minutes=exp)).isoformat(),
"method": method.upper(),
**kwargs,
}
encrypted_token = self._encrypt_dict(token)
return f'Bearer {encrypted_token.decode("utf-8")}'
def generate_token(self, **kwargs) -> str:
"""Creates a general purpose token using the payload values in kwargs
Returns:
str: The general token
"""
encrypted_token = self._encrypt_dict(kwargs)
return f'Bearer {encrypted_token.decode("utf-8")}'
def decode_token(self, token: str) -> dict:
"""Decrypts an encrypted token.
Args:
token (str): Encrypted token to decrypt.
Returns (dict): json.loads(plaintext.decode(encoding="utf-8"))
"""
if self.private_key is None:
raise NoPrivateKeyException("No private key loaded. Cannot decode token.")
if token.count(" ") != 1:
raise InvalidTokenException("Token must have exactly 1 space character.")
_, token = token.split(" ")
token = base64.b64decode(token.encode("utf-8"))
self.private_key: rsa.RSAPrivateKey
plaintext = self.private_key.decrypt(
token,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None,
),
)
return json.loads(plaintext.decode(encoding="utf-8"))
def decode_and_validate_web_token(self, token: str, path: str, method: str) -> bool:
"""
A convenience function to bundle the logic of decoding the token and
validating it into one function.
Args:
token (str): The token to decode and validate.
path (str): The path of the requested resource.
method (str): The HTTP method used to access the requested resource.
Returns:
bool: Indicates if the token was valid or not.
NoReturn: No return when an exception is raised.
Raises:
NoPrivateKeyException: Raised when the RocketToken class is
initialised without a private key and you attempt to decrypt a token.
InvalidTokenException: Raised when token, path, exp, or method fail
during validation.
"""
token_dict = self.decode_token(token=token)
return self.validate_web_token(token=token_dict, path=path, method=method) | /rocket_token-3.0.0-py3-none-any.whl/rocket_token/token.py | 0.893585 | 0.151906 | token.py | pypi |
import os
import sys
from typing import NoReturn, Union
import click
from .token import RocketToken
@click.command()
@click.argument("directory")
def generate_keys(directory):
"""Generate public and private keys and save them to `directory`
Args:
DIRECTORY (str): The directory to save the public and private keys in.\n
"""
RocketToken.generate_key_pair(directory)
click.echo(f"Key-pair saved to `{directory}`")
@click.command()
@click.argument("public_key", type=click.Path(exists=True))
@click.argument("path")
@click.argument("method")
@click.argument("exp", type=int)
@click.option("--payload", "-p", multiple=True)
def generate_web_token(
public_key: str, path: str, method: str, exp: int, payload: list
) -> Union[NoReturn, None]:
"""Generate a web token for use within REST APIs.
Args:
PATH (str): The path/endpoint the token is valid for.\n
METHOD (str): The HTTP method the token is valid for.\n
EXP (int): The number of minutes until the token expires.\n
PAYLOAD (str): Space seperated key-value arguments of the form name=Jon\n
"""
for p in payload:
if "=" not in p:
click.echo("Payload must be a key value pair of the format i.e key=value")
sys.exit(1)
payload_values = {p.split("=")[0]: p.split("=")[1] for p in payload}
rt = RocketToken.rocket_token_from_path(public_path=public_key)
token = rt.generate_web_token(path=path, exp=exp, method=method, **payload_values)
click.echo(token)
@click.command()
@click.argument("path")
@click.argument("method")
@click.argument("exp", type=int)
@click.option("--payload", "-p", multiple=True)
def generate_developer_web_token(
path: str, method: str, exp: int, payload: list
) -> Union[NoReturn, None]:
"""Generate a developer web token for use within REST apis.
PATH (str): The path/endpoint the token is valid for.\n
METHOD (str): The HTTP method the token is valid for.\n
EXP (int): The number of minutes until the token expires.\n
PAYLOAD (str): Space seperated key-value arguments of the form name=Jon\n
"""
for p in payload:
if "=" not in p:
click.echo("Payload must be a key value pair of the format i.e key=value")
sys.exit(1)
payload_values = {p.split("=")[0]: p.split("=")[1] for p in payload}
os.environ["ROCKET_DEVELOPER_MODE"] = "true"
rt = RocketToken()
token = rt.generate_web_token(path=path, exp=exp, method=method, **payload_values)
click.echo(token) | /rocket_token-3.0.0-py3-none-any.whl/rocket_token/cli.py | 0.599954 | 0.155848 | cli.py | pypi |
[](https://rocketpyalpha.readthedocs.io/en/latest/?badge=latest)
[](https://colab.research.google.com/github/giovaniceotto/rocketpy/blob/master/docs/notebooks/getting_started_colab.ipynb)
[](https://mybinder.org/v2/gh/giovaniceotto/RocketPy/master?filepath=docs%2Fnotebooks%2Fgetting_started.ipynb)
[](https://pepy.tech/project/rocketpyalpha)
[](https://discord.gg/b6xYnNh)
# RocketPy
RocketPy is a trajectory simulation for High-Power Rocketry built by [Projeto Jupiter](https://www.facebook.com/ProjetoJupiter/). The code is written as a [Python](http://www.python.org) library and allows for a complete 6 degrees of freedom simulation of a rocket's flight trajectory, including high fidelity variable mass effects as well as descent under parachutes. Weather conditions, such as wind profile, can be imported from sophisticated datasets, allowing for realistic scenarios. Furthermore, the implementation facilitates complex simulations, such as multi-stage rockets, design and trajectory optimization and dispersion analysis.
### Main features
<details>
<summary>Nonlinear 6 degrees of freedom simulations</summary>
<ul>
<li>Rigorous treatment of mass variation effects</li>
<li>Solved using LSODA with adjustable error tolerances</li>
<li>Highly optimized to run fast</li>
</ul>
</details>
<details>
<summary>Accurate weather modeling</summary>
<ul>
<li>International Standard Atmosphere (1976)</li>
<li>Custom atmospheric profiles</li>
<li>Soundings (Wyoming, NOAARuc)</li>
<li>Weather forecasts and reanalysis</li>
<li>Weather ensembles</li>
</ul>
</details>
<details>
<summary>Aerodynamic models</summary>
<ul>
<li>Barrowman equations for lift coefficients (optional)</li>
<li>Drag coefficients can be easily imported from other sources (e.g. CFD simulations)</li>
</ul>
</details>
<details>
<summary>Parachutes with external trigger functions</summary>
<ul>
<li>Test the exact code that will fly</li>
<li>Sensor data can be augmented with noise</li>
</ul>
</details>
<details>
<summary>Solid motors models</summary>
<ul>
<li>Burn rate and mass variation properties from thrust curve</li>
<li>CSV and ENG file support</li>
</ul>
</details>
<details>
<summary>Monte Carlo simulations</summary>
<ul>
<li>Dispersion analysis</li>
<li>Global sensitivity analysis</li>
</ul>
</details>
<details>
<summary>Flexible and modular</summary>
<ul>
<li>Straightforward engineering analysis (e.g. apogee and lifting off speed as a function of mass)</li>
<li>Non-standard flights (e.g. parachute drop test from helicopter)</li>
<li>Multi-stage rockets</li>
<li>Custom continuous and discrete control laws</li>
<li>Create new classes (e.g. other types of motors)</li>
</ul>
</details>
### Documentation
Check out documentation details using the links below:
- [User Guide](https://rocketpyalpha.readthedocs.io/en/latest/user/index.html)
- [Code Documentation](https://rocketpyalpha.readthedocs.io/en/latest/reference/index.html)
- [Development Guide](https://rocketpyalpha.readthedocs.io/en/latest/development/index.html)
## Join Our Community!
RocketPy is growing fast! Many unviersity groups and rocket hobbyist have already started using it. The number of stars and forks for this repository is skyrocketing. And this is all thanks to a great community of users, engineers, developers, marketing specialists, and everyone interested in helping.
If you want to be a part of this and make RocketPy your own, join our [Discord](https://discord.gg/b6xYnNh) server today!
## Previewing
You can preview RocketPy's main functionalities by browsing through a sample notebook either in [Google Colab](https://colab.research.google.com/github/giovaniceotto/rocketpy/blob/master/docs/notebooks/getting_started_colab.ipynb) or in [MyBinder](https://mybinder.org/v2/gh/giovaniceotto/RocketPy/master?filepath=docs%2Fnotebooks%2Fgetting_started.ipynb)!
Then, you can read the *Getting Started* section to get your own copy!
## Getting Started
These instructions will get you a copy of RocketPy up and running on your local machine.
### Prerequisites
The following is needed in order to run RocketPy:
- Python >= 3.0
- Numpy >= 1.0
- Scipy >= 1.0
- Matplotlib >= 3.0
- requests
- netCDF4 >= 1.4 (optional, requires Cython)
All of these packages, with the exception of netCDF4, should be automatically
installed when RocketPy is installed using either pip or conda.
However, in case the user wants to install these packages manually, they can do
so by following the instructions bellow:
The first 4 prerequisites come with Anaconda, but Scipy might need
updating. The nedCDF4 package can be installed if there is interest in
importing weather data from netCDF files. To update Scipy and install
netCDF4 using Conda, the following code is used:
```
$ conda install "scipy>=1.0"
$ conda install -c anaconda "netcdf4>=1.4"
```
Alternatively, if you only have Python 3.X installed, the packages needed can be installed using pip:
```
$ pip install "numpy>=1.0"
$ pip install "scipy>=1.0"
$ pip install "matplotlib>=3.0"
$ pip install "netCDF4>=1.4"
$ pip install "requests"
```
Although [Jupyter Notebooks](http://jupyter.org/) are by no means required to run RocketPy, they are strongly recommend. They already come with Anaconda builds, but can also be installed separately using pip:
```
$ pip install jupyter
```
### Installation
To get a copy of RocketPy using pip, just run:
```
$ pip install rocketpy
```
Alternatively, the package can also be installed using conda:
```
$ conda install -c conda-forge rocketpy
```
If you want to downloaded it from source, you may do so either by:
- Downloading it from [RocketPy's GitHub](https://github.com/giovaniceotto/RocketPy) page
- Unzip the folder and you are ready to go
- Or cloning it to a desired directory using git:
- ```$ git clone https://github.com/giovaniceotto/RocketPy.git```
The RockeyPy library can then be installed by running:
```
$ python setup.py install
```
### Documentations
You can find RocketPy's documentation at [Read the Docs](https://rocketpyalpha.readthedocs.io/en/latest/).
### Running Your First Simulation
In order to run your first rocket trajectory simulation using RocketPy, you can start a Jupyter Notebook and navigate to the **_nbks_** folder. Open **_Getting Started - Examples.ipynb_** and you are ready to go.
Otherwise, you may want to create your own script or your own notebook using RocketPy. To do this, let's see how to use RocketPy's four main classes:
- Environment - Keeps data related to weather.
- SolidMotor - Keeps data related to solid motors. Hybrid motor support is coming in the next weeks.
- Rocket - Keeps data related to a rocket.
- Flight - Runs the simulation and keeps the results.
A typical workflow starts with importing these classes from RocketPy:
```python
from rocketpy import Environment, Rocket, SolidMotor, Flight
```
Then create an Environment object. To learn more about it, you can use:
```python
help(Environment)
```
A sample code is:
```python
Env = Environment(
railLength=5.2,
latitude=32.990254,
longitude=-106.974998,
elevation=1400,
date=(2020, 3, 4, 12) # Tomorrow's date in year, month, day, hour UTC format
)
Env.setAtmosphericModel(type='Forecast', file='GFS')
```
This can be followed up by starting a Solid Motor object. To get help on it, just use:
```python
help(SolidMotor)
```
A sample Motor object can be created by the following code:
```python
Pro75M1670 = SolidMotor(
thrustSource="../data/motors/Cesaroni_M1670.eng",
burnOut=3.9,
grainNumber=5,
grainSeparation=5/1000,
grainDensity=1815,
grainOuterRadius=33/1000,
grainInitialInnerRadius=15/1000,
grainInitialHeight=120/1000,
nozzleRadius=33/1000,
throatRadius=11/1000,
interpolationMethod='linear'
)
```
With a Solid Motor defined, you are ready to create your Rocket object. As you may have guessed, to get help on it, use:
```python
help(Rocket)
```
A sample code to create a Rocket is:
```python
Calisto = Rocket(
motor=Pro75M1670,
radius=127/2000,
mass=19.197-2.956,
inertiaI=6.60,
inertiaZ=0.0351,
distanceRocketNozzle=-1.255,
distanceRocketPropellant=-0.85704,
powerOffDrag='../data/calisto/powerOffDragCurve.csv',
powerOnDrag='../data/calisto/powerOnDragCurve.csv'
)
Calisto.setRailButtons([0.2, -0.5])
NoseCone = Calisto.addNose(length=0.55829, kind="vonKarman", distanceToCM=0.71971)
FinSet = Calisto.addFins(4, span=0.100, rootChord=0.120, tipChord=0.040, distanceToCM=-1.04956)
Tail = Calisto.addTail(topRadius=0.0635, bottomRadius=0.0435, length=0.060, distanceToCM=-1.194656)
```
You may want to add parachutes to your rocket as well:
```python
def drogueTrigger(p, y):
return True if y[5] < 0 else False
def mainTrigger(p, y):
return True if y[5] < 0 and y[2] < 800 else False
Main = Calisto.addParachute('Main',
CdS=10.0,
trigger=mainTrigger,
samplingRate=105,
lag=1.5,
noise=(0, 8.3, 0.5))
Drogue = Calisto.addParachute('Drogue',
CdS=1.0,
trigger=drogueTrigger,
samplingRate=105,
lag=1.5,
noise=(0, 8.3, 0.5))
```
Finally, you can create a Flight object to simulate your trajectory. To get help on the Flight class, use:
```python
help(Flight)
```
To actually create a Flight object, use:
```python
TestFlight = Flight(rocket=Calisto, environment=Env, inclination=85, heading=0)
```
Once the TestFlight object is created, your simulation is done! Use the following code to get a summary of the results:
```python
TestFlight.info()
```
To seel all available results, use:
```python
TestFlight.allInfo()
```
## Built With
* [Numpy](http://www.numpy.org/)
* [Scipy](https://www.scipy.org/)
* [Matplotlib](https://matplotlib.org/)
* [netCDF4](https://github.com/Unidata/netcdf4-python)
## Contributing
Please read [CONTRIBUTING.md](https://github.com/giovaniceotto/RocketPy/blob/master/CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests to us. - **_Still working on this!_**
## Authors
* Creator: **Giovani Hidalgo Ceotto**
See the list of [contributors](https://github.com/giovaniceotto/RocketPy/contributors) who are actively working on RocketPy.
## License
This project is licensed under the MIT License - see the [LICENSE.md](https://github.com/giovaniceotto/RocketPy/blob/master/LICENSE) file for details
## Release Notes
Want to know which bugs have been fixed and new features of each version? Check out the [release notes](https://github.com/giovaniceotto/RocketPy/releases).
| /rocket.py-1.0.1.tar.gz/rocket.py-1.0.1/README.md | 0.532668 | 0.966156 | README.md | pypi |
__author__ = "Giovani Hidalgo Ceotto, Franz Masatoshi Yuri"
__copyright__ = "Copyright 20XX, Projeto Jupiter"
__license__ = "MIT"
import re
import math
import bisect
import warnings
import time
from datetime import datetime, timedelta
from inspect import signature, getsourcelines
from collections import namedtuple
import numpy as np
from scipy import integrate
from scipy import linalg
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from numpy import genfromtxt
from .Function import Function
class Rocket:
"""Keeps all rocket and parachute information.
Attributes
----------
Geometrical attributes:
Rocket.radius : float
Rocket's largest radius in meters.
Rocket.area : float
Rocket's circular cross section largest frontal area in squared
meters.
Rocket.distanceRocketNozzle : float
Distance between rocket's center of mass, without propellant,
to the exit face of the nozzle, in meters. Always positive.
Rocket.distanceRocketPropellant : float
Distance between rocket's center of mass, without propellant,
to the center of mass of propellant, in meters. Always positive.
Mass and Inertia attributes:
Rocket.mass : float
Rocket's mass without propellant in kg.
Rocket.inertiaI : float
Rocket's moment of inertia, without propellant, with respect to
to an axis perpendicular to the rocket's axis of cylindrical
symmetry, in kg*m^2.
Rocket.inertiaZ : float
Rocket's moment of inertia, without propellant, with respect to
the rocket's axis of cylindrical symmetry, in kg*m^2.
Rocket.centerOfMass : Function
Distance of the rocket's center of mass, including propellant,
to rocket's center of mass without propellant, in meters.
Expressed as a function of time.
Rocket.reducedMass : Function
Function of time expressing the reduced mass of the rocket,
defined as the product of the propellant mass and the mass
of the rocket without propellant, divided by the sum of the
propellant mass and the rocket mass.
Rocket.totalMass : Function
Function of time expressing the total mass of the rocket,
defined as the sum of the propellant mass and the rocket
mass without propellant.
Rocket.thrustToWeight : Function
Function of time expressing the motor thrust force divided by rocket
weight. The gravitational acceleration is assumed as 9.80665 m/s^2.
Excentricity attributes:
Rocket.cpExcentricityX : float
Center of pressure position relative to center of mass in the x
axis, perpendicular to axis of cylindrical symmetry, in meters.
Rocket.cpExcentricityY : float
Center of pressure position relative to center of mass in the y
axis, perpendicular to axis of cylindrical symmetry, in meters.
Rocket.thrustExcentricityY : float
Thrust vector position relative to center of mass in the y
axis, perpendicular to axis of cylindrical symmetry, in meters.
Rocket.thrustExcentricityX : float
Thrust vector position relative to center of mass in the x
axis, perpendicular to axis of cylindrical symmetry, in meters.
Parachute attributes:
Rocket.parachutes : list
List of parachutes of the rocket.
Each parachute has the following attributes:
name : string
Parachute name, such as drogue and main. Has no impact in
simulation, as it is only used to display data in a more
organized matter.
CdS : float
Drag coefficient times reference area for parachute. It is
used to compute the drag force exerted on the parachute by
the equation F = ((1/2)*rho*V^2)*CdS, that is, the drag
force is the dynamic pressure computed on the parachute
times its CdS coefficient. Has units of area and must be
given in squared meters.
trigger : function
Function which defines if the parachute ejection system is
to be triggered. It must take as input the freestream
pressure in pascal and the state vector of the simulation,
which is defined by [x, y, z, vx, vy, vz, e0, e1, e2, e3, wx, wy, wz].
It will be called according to the sampling rate given next.
It should return True if the parachute ejection system is
to be triggered and False otherwise.
samplingRate : float, optional
Sampling rate in which the trigger function works. It is used to
simulate the refresh rate of onboard sensors such as barometers.
Default value is 100. Value must be given in hertz.
lag : float, optional
Time between the parachute ejection system is triggered and the
parachute is fully opened. During this time, the simulation will
consider the rocket as flying without a parachute. Default value
is 0. Must be given in seconds.
noise : tuple, list, optional
List in the format (mean, standard deviation, time-correlation).
The values are used to add noise to the pressure signal which is
passed to the trigger function. Default value is (0, 0, 0). Units
are in pascal.
noiseSignal : list
List of (t, noise signal) corresponding to signal passed to
trigger function. Completed after running a simulation.
noisyPressureSignal : list
List of (t, noisy pressure signal) that is passed to the
trigger function. Completed after running a simulation.
cleanPressureSignal : list
List of (t, clean pressure signal) corresponding to signal passed to
trigger function. Completed after running a simulation.
noiseSignalFunction : Function
Function of noiseSignal.
noisyPressureSignalFunction : Function
Function of noisyPressureSignal.
cleanPressureSignalFunction : Function
Function of cleanPressureSignal.
Aerodynamic attributes
Rocket.aerodynamicSurfaces : list
List of aerodynamic surfaces of the rocket.
Rocket.staticMargin : float
Float value corresponding to rocket static margin when
loaded with propellant in units of rocket diameter or
calibers.
Rocket.powerOffDrag : Function
Rocket's drag coefficient as a function of Mach number when the
motor is off.
Rocket.powerOnDrag : Function
Rocket's drag coefficient as a function of Mach number when the
motor is on.
Motor attributes:
Rocket.motor : Motor
Rocket's motor. See Motor class for more details.
"""
def __init__(
self,
motor,
mass,
inertiaI,
inertiaZ,
radius,
distanceRocketNozzle,
distanceRocketPropellant,
powerOffDrag,
powerOnDrag,
):
"""Initializes Rocket class, process inertial, geometrical and
aerodynamic parameters.
Parameters
----------
motor : Motor
Motor used in the rocket. See Motor class for more information.
mass : int, float
Unloaded rocket total mass (without propelant) in kg.
inertiaI : int, float
Unloaded rocket lateral (perpendicular to axis of symmetry)
moment of inertia (without propelant) in kg m^2.
inertiaZ : int, float
Unloaded rocket axial moment of inertia (without propelant)
in kg m^2.
radius : int, float
Rocket biggest outer radius in meters.
distanceRocketNozzle : int, float
Distance from rocket's unloaded center of mass to nozzle outlet,
in meters. Generally negative, meaning a negative position in the
z axis which has an origin in the rocket's center of mass (without
propellant) and points towards the nose cone.
distanceRocketPropellant : int, float
Distance from rocket's unloaded center of mass to propellant
center of mass, in meters. Generally negative, meaning a negative
position in the z axis which has an origin in the rocket's center
of mass (with out propellant) and points towards the nose cone.
powerOffDrag : int, float, callable, string, array
Rocket's drag coefficient when the motor is off. Can be given as an
entry to the Function class. See help(Function) for more
information. If int or float is given, it is assumed constant. If
callable, string or array is given, it must be a function of Mach
number only.
powerOnDrag : int, float, callable, string, array
Rocket's drag coefficient when the motor is on. Can be given as an
entry to the Function class. See help(Function) for more
information. If int or float is given, it is assumed constant. If
callable, string or array is given, it must be a function of Mach
number only.
Returns
-------
None
"""
# Define rocket inertia attributes in SI units
self.mass = mass
self.inertiaI = inertiaI
self.inertiaZ = inertiaZ
self.centerOfMass = distanceRocketPropellant * motor.mass / (mass + motor.mass)
# Define rocket geometrical parameters in SI units
self.radius = radius
self.area = np.pi * self.radius ** 2
# Center of mass distance to points of interest
self.distanceRocketNozzle = distanceRocketNozzle
self.distanceRocketPropellant = distanceRocketPropellant
# Excentricity data initialization
self.cpExcentricityX = 0
self.cpExcentricityY = 0
self.thrustExcentricityY = 0
self.thrustExcentricityX = 0
# Parachute data initialization
self.parachutes = []
# Rail button data initialization
self.railButtons = None
# Aerodynamic data initialization
self.aerodynamicSurfaces = []
self.cpPosition = 0
self.staticMargin = Function(
lambda x: 0, inputs="Time (s)", outputs="Static Margin (c)"
)
# Define aerodynamic drag coefficients
self.powerOffDrag = Function(
powerOffDrag,
"Mach Number",
"Drag Coefficient with Power Off",
"spline",
"constant",
)
self.powerOnDrag = Function(
powerOnDrag,
"Mach Number",
"Drag Coefficient with Power On",
"spline",
"constant",
)
# Define motor to be used
self.motor = motor
# Important dynamic inertial quantities
self.reducedMass = None
self.totalMass = None
# Calculate dynamic inertial quantities
self.evaluateReducedMass()
self.evaluateTotalMass()
self.thrustToWeight = self.motor.thrust / (9.80665 * self.totalMass)
self.thrustToWeight.setInputs("Time (s)")
self.thrustToWeight.setOutputs("Thrust/Weight")
# Evaluate static margin (even though no aerodynamic surfaces are present yet)
self.evaluateStaticMargin()
return None
def evaluateReducedMass(self):
"""Calculates and returns the rocket's total reduced mass. The
reduced mass is defined as the product of the propellant mass
and the mass of the rocket without propellant, divided by the
sum of the propellant mass and the rocket mass. The function
returns an object of the Function class and is defined as a
function of time.
Parameters
----------
None
Returns
-------
self.reducedMass : Function
Function of time expressing the reduced mass of the rocket,
defined as the product of the propellant mass and the mass
of the rocket without propellant, divided by the sum of the
propellant mass and the rocket mass.
"""
# Make sure there is a motor associated with the rocket
if self.motor is None:
print("Please associate this rocket with a motor!")
return False
# Retrieve propellant mass as a function of time
motorMass = self.motor.mass
# Retrieve constant rocket mass without propellant
mass = self.mass
# Calculate reduced mass
self.reducedMass = motorMass * mass / (motorMass + mass)
self.reducedMass.setOutputs("Reduced Mass (kg)")
# Return reduced mass
return self.reducedMass
def evaluateTotalMass(self):
"""Calculates and returns the rocket's total mass. The total
mass is defined as the sum of the propellant mass and the
rocket mass without propellant. The function returns an object
of the Function class and is defined as a function of time.
Parameters
----------
None
Returns
-------
self.totalMass : Function
Function of time expressing the total mass of the rocket,
defined as the sum of the propellant mass and the rocket
mass without propellant.
"""
# Make sure there is a motor associated with the rocket
if self.motor is None:
print("Please associate this rocket with a motor!")
return False
# Calculate total mass by summing up propellant and dry mass
self.totalMass = self.mass + self.motor.mass
self.totalMass.setOutputs("Total Mass (Rocket + Propellant) (kg)")
# Return total mass
return self.totalMass
def evaluateStaticMargin(self):
"""Calculates and returns the rocket's static margin when
loaded with propellant. The static margin is saved and returned
in units of rocket diameter or calibers.
Parameters
----------
None
Returns
-------
self.staticMargin : float
Float value corresponding to rocket static margin when
loaded with propellant in units of rocket diameter or
calibers.
"""
# Initialize total lift coeficient derivative and center of pressure
self.totalLiftCoeffDer = 0
self.cpPosition = 0
# Calculate total lift coeficient derivative and center of pressure
if len(self.aerodynamicSurfaces) > 0:
for aerodynamicSurface in self.aerodynamicSurfaces:
self.totalLiftCoeffDer += aerodynamicSurface[1].differentiate(
x=1e-2, dx=1e-3
)
self.cpPosition += (
aerodynamicSurface[1].differentiate(x=1e-2, dx=1e-3)
* aerodynamicSurface[0][2]
)
self.cpPosition /= self.totalLiftCoeffDer
# Calculate static margin
self.staticMargin = (self.centerOfMass - self.cpPosition) / (2 * self.radius)
self.staticMargin.setInputs("Time (s)")
self.staticMargin.setOutputs("Static Margin (c)")
self.staticMargin.setDiscrete(
lower=0, upper=self.motor.burnOutTime, samples=200
)
# Return self
return self
def addTail(self, topRadius, bottomRadius, length, distanceToCM):
"""Create a new tail or rocket diameter change, storing its
parameters as part of the aerodynamicSurfaces list. Its
parameters are the axial position along the rocket and its
derivative of the coefficient of lift in respect to angle of
attack.
Parameters
----------
topRadius : int, float
Tail top radius in meters, considering positive direction
from center of mass to nose cone.
bottomRadius : int, float
Tail bottom radius in meters, considering positive direction
from center of mass to nose cone.
length : int, float
Tail length or height in meters. Must be a positive value.
distanceToCM : int, float
Tail position relative to rocket unloaded center of mass,
considering positive direction from center of mass to nose
cone. Consider the point belonging to the tail which is
closest to the unloaded center of mass to calculate
distance.
Returns
-------
cldata : Function
Object of the Function class. Contains tail's lift data.
self : Rocket
Object of the Rocket class.
"""
# Calculate ratio between top and bottom radius
r = topRadius / bottomRadius
# Retrieve reference radius
rref = self.radius
# Calculate cp position relative to cm
if distanceToCM < 0:
cpz = distanceToCM - (length / 3) * (1 + (1 - r) / (1 - r ** 2))
else:
cpz = distanceToCM + (length / 3) * (1 + (1 - r) / (1 - r ** 2))
# Calculate clalpha
clalpha = -2 * (1 - r ** (-2)) * (topRadius / rref) ** 2
cldata = Function(
lambda x: clalpha * x, "Alpha (rad)", "Cl", interpolation="linear"
)
# Store values as new aerodynamic surface
tail = [(0, 0, cpz), cldata, "Tail"]
self.aerodynamicSurfaces.append(tail)
# Refresh static margin calculation
self.evaluateStaticMargin()
# Return self
return self.aerodynamicSurfaces[-1]
def addNose(self, length, kind, distanceToCM):
"""Creates a nose cone, storing its parameters as part of the
aerodynamicSurfaces list. Its parameters are the axial position
along the rocket and its derivative of the coefficient of lift
in respect to angle of attack.
Parameters
----------
length : int, float
Nose cone length or height in meters. Must be a postive
value.
kind : string
Nose cone type. Von Karman, conical, ogive, and lvhaack are
supported.
distanceToCM : int, float
Nose cone position relative to rocket unloaded center of
mass, considering positive direction from center of mass to
nose cone. Consider the center point belonging to the nose
cone base to calculate distance.
Returns
-------
cldata : Function
Object of the Function class. Contains nose's lift data.
self : Rocket
Object of the Rocket class.
"""
# Analyze type
if kind == "conical":
k = 1 - 1 / 3
elif kind == "ogive":
k = 1 - 0.534
elif kind == "lvhaack":
k = 1 - 0.437
else:
k = 0.5
# Calculate cp position relative to cm
if distanceToCM > 0:
cpz = distanceToCM + k * length
else:
cpz = distanceToCM - k * length
# Calculate clalpha
clalpha = 2
cldata = Function(
lambda x: clalpha * x,
"Alpha (rad)",
"Cl",
interpolation="linear",
extrapolation="natural",
)
# Store values
nose = [(0, 0, cpz), cldata, "Nose Cone"]
self.aerodynamicSurfaces.append(nose)
# Refresh static margin calculation
self.evaluateStaticMargin()
# Return self
return self.aerodynamicSurfaces[-1]
def addFins(
self, n, span, rootChord, tipChord, distanceToCM, radius=0, airfoil=None
):
"""Create a fin set, storing its parameters as part of the
aerodynamicSurfaces list. Its parameters are the axial position
along the rocket and its derivative of the coefficient of lift
in respect to angle of attack.
Parameters
----------
n : int
Number of fins, from 2 to infinity.
span : int, float
Fin span in meters.
rootChord : int, float
Fin root chord in meters.
tipChord : int, float
Fin tip chord in meters.
distanceToCM : int, float
Fin set position relative to rocket unloaded center of
mass, considering positive direction from center of mass to
nose cone. Consider the center point belonging to the top
of the fins to calculate distance.
radius : int, float, optional
Reference radius to calculate lift coefficient. If 0, which
is default, use rocket radius. Otherwise, enter the radius
of the rocket in the section of the fins, as this impacts
its lift coefficient.
airfoil : string
Fin's lift curve. It must be a .csv file. The .csv file shall
contain no headers and the first column must specify time in
seconds, while the second column specifies lift coefficient. Lift
coeffitient is adimentional.
Returns
-------
cldata : Function
Object of the Function class. Contains fin's lift data.
self : Rocket
Object of the Rocket class.
"""
# Retrieve parameters for calculations
Cr = rootChord
Ct = tipChord
Yr = rootChord + tipChord
s = span
Lf = np.sqrt((rootChord / 2 - tipChord / 2) ** 2 + span ** 2)
radius = self.radius if radius == 0 else radius
d = 2 * radius
# Save geometric parameters for later Fin Flutter Analysis
self.rootChord = Cr
self.tipChord = Ct
self.span = s
self.distanceRocketFins = distanceToCM
# Calculate cp position relative to cm
if distanceToCM < 0:
cpz = distanceToCM - (
((Cr - Ct) / 3) * ((Cr + 2 * Ct) / (Cr + Ct))
+ (1 / 6) * (Cr + Ct - Cr * Ct / (Cr + Ct))
)
else:
cpz = distanceToCM + (
((Cr - Ct) / 3) * ((Cr + 2 * Ct) / (Cr + Ct))
+ (1 / 6) * (Cr + Ct - Cr * Ct / (Cr + Ct))
)
# Calculate lift parameters for planar fins
if not airfoil:
# Calculate clalpha
clalpha = (4 * n * (s / d) ** 2) / (1 + np.sqrt(1 + (2 * Lf / Yr) ** 2))
clalpha *= 1 + radius / (s + radius)
# # Create a function of lift values by attack angle
cldata = Function(
lambda x: clalpha * x, "Alpha (rad)", "Cl", interpolation="linear"
)
# Store values
fin = [(0, 0, cpz), cldata, "Fins"]
self.aerodynamicSurfaces.append(fin)
# Refresh static margin calculation
self.evaluateStaticMargin()
# Return self
return self.aerodynamicSurfaces[-1]
else:
def cnalfa1(cn):
"""Calculates the normal force coefficient derivative of a 3D
airfoil for a given Cnalfa0
Parameters
----------
cn : int
Normal force coefficient derivative of a 2D airfoil.
Returns
-------
Cnalfa1 : int
Normal force coefficient derivative of a 3D airfoil.
"""
# Retrieve parameters for calculations
Af = (Cr + Ct) * span / 2
# fin area
AR = 2 * (span ** 2) / Af # Aspect ratio
gamac = np.arctan((Cr - Ct) / (2 * span))
# mid chord angle
FD = 2 * np.pi * AR / (cn * np.cos(gamac))
Cnalfa1 = (
cn
* FD
* (Af / self.area)
* np.cos(gamac)
/ (2 + FD * (1 + (4 / FD ** 2)) ** 0.5)
)
return Cnalfa1
# Import the lift curve as a function of lift values by attack angle
read = genfromtxt(airfoil, delimiter=",")
# Aplies number of fins to lift coefficient data
data = [[cl[0], (n / 2) * cnalfa1(cl[1])] for cl in read]
cldata = Function(
data,
"Alpha (rad)",
"Cl",
interpolation="linear",
extrapolation="natural",
)
# Takes an approximation to an angular coefficient
clalpha = cldata.differentiate(x=0, dx=1e-2)
# Store values
fin = [(0, 0, cpz), cldata, "Fins"]
self.aerodynamicSurfaces.append(fin)
# Refresh static margin calculation
self.evaluateStaticMargin()
# Return self
return self.aerodynamicSurfaces[-1]
def addParachute(
self, name, CdS, trigger, samplingRate=100, lag=0, noise=(0, 0, 0)
):
"""Creates a new parachute, storing its parameters such as
opening delay, drag coefficients and trigger function.
Parameters
----------
name : string
Parachute name, such as drogue and main. Has no impact in
simulation, as it is only used to display data in a more
organized matter.
CdS : float
Drag coefficient times reference area for parachute. It is
used to compute the drag force exerted on the parachute by
the equation F = ((1/2)*rho*V^2)*CdS, that is, the drag
force is the dynamic pressure computed on the parachute
times its CdS coefficient. Has units of area and must be
given in squared meters.
trigger : function
Function which defines if the parachute ejection system is
to be triggered. It must take as input the freestream
pressure in pascal and the state vector of the simulation,
which is defined by [x, y, z, vx, vy, vz, e0, e1, e2, e3, wx, wy, wz].
It will be called according to the sampling rate given next.
It should return True if the parachute ejection system is
to be triggered and False otherwise.
samplingRate : float, optional
Sampling rate in which the trigger function works. It is used to
simulate the refresh rate of onboard sensors such as barometers.
Default value is 100. Value must be given in hertz.
lag : float, optional
Time between the parachute ejection system is triggered and the
parachute is fully opened. During this time, the simulation will
consider the rocket as flying without a parachute. Default value
is 0. Must be given in seconds.
noise : tuple, list, optional
List in the format (mean, standard deviation, time-correlation).
The values are used to add noise to the pressure signal which is
passed to the trigger function. Default value is (0, 0, 0). Units
are in pascal.
Returns
-------
parachute : Parachute Object
Parachute object containing trigger, samplingRate, lag, CdS, noise
and name as attributes. Furthermore, it stores cleanPressureSignal,
noiseSignal and noisyPressureSignal which are filled in during
Flight simulation.
"""
# Create an object to serve as the parachute
parachute = type("", (), {})()
# Store Cds coefficient, lag, name and trigger function
parachute.trigger = trigger
parachute.samplingRate = samplingRate
parachute.lag = lag
parachute.CdS = CdS
parachute.name = name
parachute.noiseBias = noise[0]
parachute.noiseDeviation = noise[1]
parachute.noiseCorr = (noise[2], (1 - noise[2] ** 2) ** 0.5)
alpha, beta = parachute.noiseCorr
parachute.noiseSignal = [[-1e-6, np.random.normal(noise[0], noise[1])]]
parachute.noiseFunction = lambda: alpha * parachute.noiseSignal[-1][
1
] + beta * np.random.normal(noise[0], noise[1])
parachute.cleanPressureSignal = []
parachute.noisyPressureSignal = []
# Add parachute to list of parachutes
self.parachutes.append(parachute)
# Return self
return self.parachutes[-1]
def setRailButtons(self, distanceToCM, angularPosition=45):
"""Adds rail buttons to the rocket, allowing for the
calculation of forces exerted by them when the rocket is
slinding in the launch rail. Furthermore, rail buttons are
also needed for the simulation of the planar flight phase,
when the rocket experiences 3 degrees of freedom motion while
only one rail button is still in the launch rail.
Parameters
----------
distanceToCM : tuple, list, array
Two values organized in a tuple, list or array which
represent the distance of each of the two rail buttons
to the center of mass of the rocket without propellant.
If the rail button is positioned above the center of mass,
its distance should be a positive value. If it is below,
its distance should be a negative value. The order does
not matter. All values should be in meters.
angularPosition : float
Angular postion of the rail buttons in degrees measured
as the rotation around the symmetry axis of the rocket
relative to one of the other principal axis.
Default value is 45 degrees, generally used in rockets with
4 fins.
Returns
-------
None
"""
# Order distance to CM
if distanceToCM[0] < distanceToCM[1]:
distanceToCM.reverse()
# Save
self.railButtons = self.railButtonPair(distanceToCM, angularPosition)
return None
def addCMExcentricity(self, x, y):
"""Moves line of action of aerodynamic and thrust forces by
equal translation ammount to simulate an excentricity in the
position of the center of mass of the rocket relative to its
geometrical center line. Should not be used together with
addCPExentricity and addThrustExentricity.
Parameters
----------
x : float
Distance in meters by which the CM is to be translated in
the x direction relative to geometrical center line.
y : float
Distance in meters by which the CM is to be translated in
the y direction relative to geometrical center line.
Returns
-------
self : Rocket
Object of the Rocket class.
"""
# Move center of pressure to -x and -y
self.cpExcentricityX = -x
self.cpExcentricityY = -y
# Move thrust center by -x and -y
self.thrustExcentricityY = -x
self.thrustExcentricityX = -y
# Return self
return self
def addCPExentricity(self, x, y):
"""Moves line of action of aerodynamic forces to simulate an
excentricity in the position of the center of pressure relative
to the center of mass of the rocket.
Parameters
----------
x : float
Distance in meters by which the CP is to be translated in
the x direction relative to the center of mass axial line.
y : float
Distance in meters by which the CP is to be translated in
the y direction relative to the center of mass axial line.
Returns
-------
self : Rocket
Object of the Rocket class.
"""
# Move center of pressure by x and y
self.cpExcentricityX = x
self.cpExcentricityY = y
# Return self
return self
def addThrustExentricity(self, x, y):
"""Moves line of action of thrust forces to simulate a
disalignment of the thrust vector and the center of mass.
Parameters
----------
x : float
Distance in meters by which the line of action of the
thrust force is to be translated in the x direction
relative to the center of mass axial line.
y : float
Distance in meters by which the line of action of the
thrust force is to be translated in the x direction
relative to the center of mass axial line.
Returns
-------
self : Rocket
Object of the Rocket class.
"""
# Move thrust line by x and y
self.thrustExcentricityY = x
self.thrustExcentricityX = y
# Return self
return self
def info(self):
"""Prints out a summary of the data and graphs available about
the Rocket.
Parameters
----------
None
Return
------
None
"""
# Print inertia details
print("Inertia Details")
print("Rocket Dry Mass: " + str(self.mass) + " kg (No Propellant)")
print("Rocket Total Mass: " + str(self.totalMass(0)) + " kg (With Propellant)")
# Print rocket geometrical parameters
print("\nGeometrical Parameters")
print("Rocket Radius: " + str(self.radius) + " m")
# Print rocket aerodynamics quantities
print("\nAerodynamics Stability")
print("Initial Static Margin: " + "{:.3f}".format(self.staticMargin(0)) + " c")
print(
"Final Static Margin: "
+ "{:.3f}".format(self.staticMargin(self.motor.burnOutTime))
+ " c"
)
# Print parachute data
for chute in self.parachutes:
print("\n" + chute.name.title() + " Parachute")
print("CdS Coefficient: " + str(chute.CdS) + " m2")
# Show plots
print("\nAerodynamics Plots")
self.powerOnDrag()
# Return None
return None
def allInfo(self):
"""Prints out all data and graphs available about the Rocket.
Parameters
----------
None
Return
------
None
"""
# Print inertia details
print("Inertia Details")
print("Rocket Mass: {:.3f} kg (No Propellant)".format(self.mass))
print("Rocket Mass: {:.3f} kg (With Propellant)".format(self.totalMass(0)))
print("Rocket Inertia I: {:.3f} kg*m2".format(self.inertiaI))
print("Rocket Inertia Z: {:.3f} kg*m2".format(self.inertiaZ))
# Print rocket geometrical parameters
print("\nGeometrical Parameters")
print("Rocket Maximum Radius: " + str(self.radius) + " m")
print("Rocket Frontal Area: " + "{:.6f}".format(self.area) + " m2")
print("\nRocket Distances")
print(
"Rocket Center of Mass - Nozzle Exit Distance: "
+ str(self.distanceRocketNozzle)
+ " m"
)
print(
"Rocket Center of Mass - Propellant Center of Mass Distance: "
+ str(self.distanceRocketPropellant)
+ " m"
)
print(
"Rocket Center of Mass - Rocket Loaded Center of Mass: "
+ "{:.3f}".format(self.centerOfMass(0))
+ " m"
)
print("\nAerodynamic Coponents Parameters")
print("Currently not implemented.")
# Print rocket aerodynamics quantities
print("\nAerodynamics Lift Coefficient Derivatives")
for aerodynamicSurface in self.aerodynamicSurfaces:
name = aerodynamicSurface[-1]
clalpha = aerodynamicSurface[1].differentiate(x=1e-2, dx=1e-3)
print(
name + " Lift Coefficient Derivative: {:.3f}".format(clalpha) + "/rad"
)
print("\nAerodynamics Center of Pressure")
for aerodynamicSurface in self.aerodynamicSurfaces:
name = aerodynamicSurface[-1]
cpz = aerodynamicSurface[0][2]
print(name + " Center of Pressure to CM: {:.3f}".format(cpz) + " m")
print(
"Distance - Center of Pressure to CM: "
+ "{:.3f}".format(self.cpPosition)
+ " m"
)
print("Initial Static Margin: " + "{:.3f}".format(self.staticMargin(0)) + " c")
print(
"Final Static Margin: "
+ "{:.3f}".format(self.staticMargin(self.motor.burnOutTime))
+ " c"
)
# Print parachute data
for chute in self.parachutes:
print("\n" + chute.name.title() + " Parachute")
print("CdS Coefficient: " + str(chute.CdS) + " m2")
if chute.trigger.__name__ == "<lambda>":
line = getsourcelines(chute.trigger)[0][0]
print(
"Ejection signal trigger: "
+ line.split("lambda ")[1].split(",")[0].split("\n")[0]
)
else:
print("Ejection signal trigger: " + chute.trigger.__name__)
print("Ejection system refresh rate: " + str(chute.samplingRate) + " Hz.")
print(
"Time between ejection signal is triggered and the "
"parachute is fully opened: " + str(chute.lag) + " s"
)
# Show plots
print("\nMass Plots")
self.totalMass()
self.reducedMass()
print("\nAerodynamics Plots")
self.staticMargin()
self.powerOnDrag()
self.powerOffDrag()
self.thrustToWeight.plot(lower=0, upper=self.motor.burnOutTime)
# ax = plt.subplot(415)
# ax.plot( , self.rocket.motor.thrust()/(self.env.g() * self.rocket.totalMass()))
# ax.set_xlim(0, self.rocket.motor.burnOutTime)
# ax.set_xlabel("Time (s)")
# ax.set_ylabel("Thrust/Weight")
# ax.set_title("Thrust-Weight Ratio")
# Return None
return None
def addFin(
self,
numberOfFins=4,
cl=2 * np.pi,
cpr=1,
cpz=1,
gammas=[0, 0, 0, 0],
angularPositions=None,
):
"Hey! I will document this function later"
self.aerodynamicSurfaces = []
pi = np.pi
# Calculate angular postions if not given
if angularPositions is None:
angularPositions = np.array(range(numberOfFins)) * 2 * pi / numberOfFins
else:
angularPositions = np.array(angularPositions) * pi / 180
# Convert gammas to degree
if isinstance(gammas, (int, float)):
gammas = [(pi / 180) * gammas for i in range(numberOfFins)]
else:
gammas = [(pi / 180) * gamma for gamma in gammas]
for i in range(numberOfFins):
# Get angular position and inclination for current fin
angularPosition = angularPositions[i]
gamma = gammas[i]
# Calculate position vector
cpx = cpr * np.cos(angularPosition)
cpy = cpr * np.sin(angularPosition)
positionVector = np.array([cpx, cpy, cpz])
# Calculate chord vector
auxVector = np.array([cpy, -cpx, 0]) / (cpr)
chordVector = (
np.cos(gamma) * np.array([0, 0, 1]) - np.sin(gamma) * auxVector
)
self.aerodynamicSurfaces.append([positionVector, chordVector])
return None
# Variables
railButtonPair = namedtuple("railButtonPair", "distanceToCM angularPosition") | /rocket.py-1.0.1.tar.gz/rocket.py-1.0.1/rocketpy/Rocket.py | 0.844826 | 0.650863 | Rocket.py | pypi |
__author__ = "Giovani Hidalgo Ceotto, Oscar Mauricio Prada Ramirez"
__copyright__ = "Copyright 20XX, Projeto Jupiter"
__license__ = "MIT"
import re
import math
import bisect
import warnings
import time
from datetime import datetime, timedelta
from inspect import signature, getsourcelines
from collections import namedtuple
import numpy as np
from scipy import integrate
from scipy import linalg
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from .Function import Function
class SolidMotor:
"""Class to specify characteristics and useful operations for solid
motors.
Attributes
----------
Geometrical attributes:
Motor.nozzleRadius : float
Radius of motor nozzle outlet in meters.
Motor.throatRadius : float
Radius of motor nozzle throat in meters.
Motor.grainNumber : int
Number of solid grains.
Motor.grainSeparation : float
Distance between two grains in meters.
Motor.grainDensity : float
Density of each grain in kg/meters cubed.
Motor.grainOuterRadius : float
Outer radius of each grain in meters.
Motor.grainInitialInnerRadius : float
Initial inner radius of each grain in meters.
Motor.grainInitialHeight : float
Initial height of each grain in meters.
Motor.grainInitialVolume : float
Initial volume of each grain in meters cubed.
Motor.grainInnerRadius : Function
Inner radius of each grain in meters as a function of time.
Motor.grainHeight : Function
Height of each grain in meters as a function of time.
Mass and moment of inertia attributes:
Motor.grainInitialMass : float
Initial mass of each grain in kg.
Motor.propellantInitialMass : float
Total propellant initial mass in kg.
Motor.mass : Function
Propellant total mass in kg as a function of time.
Motor.massDot : Function
Time derivative of propellant total mass in kg/s as a function
of time.
Motor.inertiaI : Function
Propellant moment of inertia in kg*meter^2 with respect to axis
perpendicular to axis of cylindrical symmetry of each grain,
given as a function of time.
Motor.inertiaIDot : Function
Time derivative of inertiaI given in kg*meter^2/s as a function
of time.
Motor.inertiaZ : Function
Propellant moment of inertia in kg*meter^2 with respect to axis of
cylindrical symmetry of each grain, given as a function of time.
Motor.inertiaDot : Function
Time derivative of inertiaZ given in kg*meter^2/s as a function
of time.
Thrust and burn attributes:
Motor.thrust : Function
Motor thrust force, in Newtons, as a function of time.
Motor.totalImpulse : float
Total impulse of the thrust curve in N*s.
Motor.maxThrust : float
Maximum thrust value of the given thrust curve, in N.
Motor.maxThrustTime : float
Time, in seconds, in which the maximum thrust value is achieved.
Motor.averageThrust : float
Average thrust of the motor, given in N.
Motor.burnOutTime : float
Total motor burn out time, in seconds. Must include delay time
when the motor takes time to ignite. Also seen as time to end thrust
curve.
Motor.exhaustVelocity : float
Propulsion gases exhaust velocity, assumed constant, in m/s.
Motor.burnArea : Function
Total burn area considering all grains, made out of inner
cylindrical burn area and grain top and bottom faces. Expressed
in meters squared as a function of time.
Motor.Kn : Function
Motor Kn as a function of time. Defined as burnArea divided by
nozzle throat cross sectional area. Has no units.
Motor.burnRate : Function
Propellant burn rate in meter/second as a function of time.
Motor.interpolate : string
Method of interpolation used in case thrust curve is given
by data set in .csv or .eng, or as an array. Options are 'spline'
'akima' and 'linear'. Default is "linear".
"""
def __init__(
self,
thrustSource,
burnOut,
grainNumber,
grainDensity,
grainOuterRadius,
grainInitialInnerRadius,
grainInitialHeight,
grainSeparation=0,
nozzleRadius=0.0335,
throatRadius=0.0114,
reshapeThrustCurve=False,
interpolationMethod="linear",
):
"""Initialize Motor class, process thrust curve and geometrical
parameters and store results.
Parameters
----------
thrustSource : int, float, callable, string, array
Motor's thrust curve. Can be given as an int or float, in which
case the thrust will be considered constant in time. It can
also be given as a callable function, whose argument is time in
seconds and returns the thrust supplied by the motor in the
instant. If a string is given, it must point to a .csv or .eng file.
The .csv file shall contain no headers and the first column must
specify time in seconds, while the second column specifies thrust.
Arrays may also be specified, following rules set by the class
Function. See help(Function). Thrust units are Newtons.
burnOut : int, float
Motor burn out time in seconds.
grainNumber : int
Number of solid grains
grainDensity : int, float
Solid grain density in kg/m3.
grainOuterRadius : int, float
Solid grain outer radius in meters.
grainInitialInnerRadius : int, float
Solid grain initial inner radius in meters.
grainInitialHeight : int, float
Solid grain initial height in meters.
grainSeparation : int, float, optional
Distance between grains, in meters. Default is 0.
nozzleRadius : int, float, optional
Motor's nozzle outlet radius in meters. Used to calculate Kn curve.
Optional if the Kn curve is not interesting. Its value does not impact
trajectory simulation.
throatRadius : int, float, optional
Motor's nozzle throat radius in meters. Its value has very low
impact in trajectory simulation, only useful to analyze
dynamic instabilities, therefore it is optional.
reshapeThrustCurve : boolean, tuple, optional
If False, the original thrust curve supplied is not altered. If a
tuple is given, whose first parameter is a new burn out time and
whose second parameter is a new total impulse in Ns, the thrust
curve is reshaped to match the new specifications. May be useful
for motors whose thrust curve shape is expected to remain similar
in case the impulse and burn time varies slightly. Default is
False.
interpolationMethod : string, optional
Method of interpolation to be used in case thrust curve is given
by data set in .csv or .eng, or as an array. Options are 'spline'
'akima' and 'linear'. Default is "linear".
Returns
-------
None
"""
# Thrust parameters
self.interpolate = interpolationMethod
self.burnOutTime = burnOut
# Check if thrustSource is csv, eng, function or other
if isinstance(thrustSource, str):
# Determine if csv or eng
if thrustSource[-3:] == "eng":
# Import content
comments, desc, points = self.importEng(thrustSource)
# Process description and points
# diameter = float(desc[1])/1000
# height = float(desc[2])/1000
# mass = float(desc[4])
# nozzleRadius = diameter/4
# throatRadius = diameter/8
# grainNumber = grainnumber
# grainVolume = height*np.pi*((diameter/2)**2 -(diameter/4)**2)
# grainDensity = mass/grainVolume
# grainOuterRadius = diameter/2
# grainInitialInnerRadius = diameter/4
# grainInitialHeight = height
thrustSource = points
self.burnOutTime = points[-1][0]
# Create thrust function
self.thrust = Function(
thrustSource, "Time (s)", "Thrust (N)", self.interpolate, "zero"
)
if callable(thrustSource) or isinstance(thrustSource, (int, float)):
self.thrust.setDiscrete(0, burnOut, 50, self.interpolate, "zero")
# Reshape curve and calculate impulse
if reshapeThrustCurve:
self.reshapeThrustCurve(*reshapeThrustCurve)
else:
self.evaluateTotalImpulse()
# Define motor attributes
# Grain and nozzle parameters
self.nozzleRadius = nozzleRadius
self.throatRadius = throatRadius
self.grainNumber = grainNumber
self.grainSeparation = grainSeparation
self.grainDensity = grainDensity
self.grainOuterRadius = grainOuterRadius
self.grainInitialInnerRadius = grainInitialInnerRadius
self.grainInitialHeight = grainInitialHeight
# Other quantities that will be computed
self.exhaustVelocity = None
self.massDot = None
self.mass = None
self.grainInnerRadius = None
self.grainHeight = None
self.burnArea = None
self.Kn = None
self.burnRate = None
self.inertiaI = None
self.inertiaIDot = None
self.inertiaZ = None
self.inertiaDot = None
self.maxThrust = None
self.maxThrustTime = None
self.averageThrust = None
# Compute uncalculated quantities
# Thrust information - maximum and average
self.maxThrust = np.amax(self.thrust.source[:, 1])
maxThrustIndex = np.argmax(self.thrust.source[:, 1])
self.maxThrustTime = self.thrust.source[maxThrustIndex, 0]
self.averageThrust = self.totalImpulse / self.burnOutTime
# Grains initial geometrical parameters
self.grainInitialVolume = (
self.grainInitialHeight
* np.pi
* (self.grainOuterRadius ** 2 - self.grainInitialInnerRadius ** 2)
)
self.grainInitialMass = self.grainDensity * self.grainInitialVolume
self.propellantInitialMass = self.grainNumber * self.grainInitialMass
# Dynamic quantities
self.evaluateExhaustVelocity()
self.evaluateMassDot()
self.evaluateMass()
self.evaluateGeometry()
self.evaluateInertia()
def reshapeThrustCurve(
self, burnTime, totalImpulse, oldTotalImpulse=None, startAtZero=True
):
"""Transforms the thrust curve supplied by changing its total
burn time and/or its total impulse, without altering the
general shape of the curve. May translate the curve so that
thrust starts at time equals 0, without any delays.
Parameters
----------
burnTime : float
New desired burn out time in seconds.
totalImpulse : float
New desired total impulse.
oldTotalImpulse : float, optional
Specify the total impulse of the given thrust curve,
overriding the value calculated by numerical integration.
If left as None, the value calculated by numerical
integration will be used in order to reshape the curve.
startAtZero: bool, optional
If True, trims the initial thrust curve points which
are 0 Newtons, translating the thrust curve so that
thrust starts at time equals 0. If False, no translation
is applied.
Returns
-------
None
"""
# Retrieve current thrust curve data points
timeArray = self.thrust.source[:, 0]
thrustArray = self.thrust.source[:, 1]
# Move start to time = 0
if startAtZero and timeArray[0] != 0:
timeArray = timeArray - timeArray[0]
# Reshape time - set burn time to burnTime
self.thrust.source[:, 0] = (burnTime / timeArray[-1]) * timeArray
self.burnOutTime = burnTime
self.thrust.setInterpolation(self.interpolate)
# Reshape thrust - set total impulse
if oldTotalImpulse is None:
oldTotalImpulse = self.evaluateTotalImpulse()
self.thrust.source[:, 1] = (totalImpulse / oldTotalImpulse) * thrustArray
self.thrust.setInterpolation(self.interpolate)
# Store total impulse
self.totalImpulse = totalImpulse
# Return reshaped curve
return self.thrust
def evaluateTotalImpulse(self):
"""Calculates and returns total impulse by numerical
integration of the thrust curve in SI units. The value is
also stored in self.totalImpulse.
Parameters
----------
None
Returns
-------
self.totalImpulse : float
Motor total impulse in Ns.
"""
# Calculate total impulse
self.totalImpulse = self.thrust.integral(0, self.burnOutTime)
# Return total impulse
return self.totalImpulse
def evaluateExhaustVelocity(self):
"""Calculates and returns exhaust velocity by assuming it
as a constant. The formula used is total impulse/propellant
initial mass. The value is also stored in
self.exhaustVelocity.
Parameters
----------
None
Returns
-------
self.exhaustVelocity : float
Constant gas exhaust velocity of the motor.
"""
# Calculate total impulse if not yet done so
if self.totalImpulse is None:
self.evaluateTotalImpulse()
# Calculate exhaust velocity
self.exhaustVelocity = self.totalImpulse / self.propellantInitialMass
# Return exhaust velocity
return self.exhaustVelocity
def evaluateMassDot(self):
"""Calculates and returns the time derivative of propellant
mass by assuming constant exhaust velocity. The formula used
is the opposite of thrust divided by exhaust velocity. The
result is a function of time, object of the Function class,
which is stored in self.massDot.
Parameters
----------
None
Returns
-------
self.massDot : Function
Time derivative of total propellant mas as a function
of time.
"""
# Calculate exhaust velocity if not done so already
if self.exhaustVelocity is None:
self.evaluateExhaustVelocity()
# Create mass dot Function
self.massDot = self.thrust / (-self.exhaustVelocity)
self.massDot.setOutputs("Mass Dot (kg/s)")
self.massDot.setExtrapolation("zero")
# Return Function
return self.massDot
def evaluateMass(self):
"""Calculates and returns the total propellant mass curve by
numerically integrating the MassDot curve, calculated in
evaluateMassDot. Numerical integration is done with the
Trapezoidal Rule, given the same result as scipy.integrate.
odeint but 100x faster. The result is a function of time,
object of the class Function, which is stored in self.mass.
Parameters
----------
None
Returns
-------
self.mass : Function
Total propellant mass as a function of time.
"""
# Retrieve mass dot curve data
t = self.massDot.source[:, 0]
ydot = self.massDot.source[:, 1]
# Set initial conditions
T = [0]
y = [self.propellantInitialMass]
# Solve for each time point
for i in range(1, len(t)):
T += [t[i]]
y += [y[i - 1] + 0.5 * (t[i] - t[i - 1]) * (ydot[i] + ydot[i - 1])]
# Create Function
self.mass = Function(
np.concatenate(([T], [y])).transpose(),
"Time (s)",
"Propellant Total Mass (kg)",
self.interpolate,
"constant",
)
# Return Mass Function
return self.mass
def evaluateGeometry(self):
"""Calculates grain inner radius and grain height as a
function of time by assuming that every propellant mass
burnt is exhausted. In order to do that, a system of
differential equations is solved using scipy.integrate.
odeint. Furthermore, the function calculates burn area,
burn rate and Kn as a function of time using the previous
results. All functions are stored as objects of the class
Function in self.grainInnerRadius, self.grainHeight, self.
burnArea, self.burnRate and self.Kn.
Parameters
----------
None
Returns
-------
geometry : list of Functions
First element is the Function representing the inner
radius of a grain as a function of time. Second
argument is the Function representing the height of a
grain as a function of time.
"""
# Define initial conditions for integration
y0 = [self.grainInitialInnerRadius, self.grainInitialHeight]
# Define time mesh
t = self.massDot.source[:, 0]
# Define system of differential equations
density = self.grainDensity
rO = self.grainOuterRadius
def geometryDot(y, t):
grainMassDot = self.massDot(t) / self.grainNumber
rI, h = y
rIDot = (
-0.5 * grainMassDot / (density * np.pi * (rO ** 2 - rI ** 2 + rI * h))
)
hDot = 1.0 * grainMassDot / (density * np.pi * (rO ** 2 - rI ** 2 + rI * h))
return [rIDot, hDot]
# Solve the system of differential equations
sol = integrate.odeint(geometryDot, y0, t)
# Write down functions for innerRadius and height
self.grainInnerRadius = Function(
np.concatenate(([t], [sol[:, 0]])).transpose().tolist(),
"Time (s)",
"Grain Inner Radius (m)",
self.interpolate,
"constant",
)
self.grainHeight = Function(
np.concatenate(([t], [sol[:, 1]])).transpose().tolist(),
"Time (s)",
"Grain Height (m)",
self.interpolate,
"constant",
)
# Create functions describing burn rate, Kn and burn area
# Burn Area
self.burnArea = (
2
* np.pi
* (
self.grainOuterRadius ** 2
- self.grainInnerRadius ** 2
+ self.grainInnerRadius * self.grainHeight
)
* self.grainNumber
)
self.burnArea.setOutputs("Burn Area (m2)")
# Kn
throatArea = np.pi * (self.throatRadius) ** 2
KnSource = (
np.concatenate(
(
[self.grainInnerRadius.source[:, 1]],
[self.burnArea.source[:, 1] / throatArea],
)
).transpose()
).tolist()
self.Kn = Function(
KnSource,
"Grain Inner Radius (m)",
"Kn (m2/m2)",
self.interpolate,
"constant",
)
# Burn Rate
self.burnRate = (-1) * self.massDot / (self.burnArea * self.grainDensity)
self.burnRate.setOutputs("Burn Rate (m/s)")
return [self.grainInnerRadius, self.grainHeight]
def evaluateInertia(self):
"""Calculates propellant inertia I, relative to directions
perpendicular to the rocket body axis and its time derivative
as a function of time. Also calculates propellant inertia Z,
relative to the axial direction, and its time derivative as a
function of time. Products of inertia are assumed null due to
symmetry. The four functions are stored as an object of the
Function class.
Parameters
----------
None
Returns
-------
list of Functions
The first argument is the Function representing inertia I,
while the second argument is the Function representing
inertia Z.
"""
# Inertia I
# Calculate inertia I for each grain
grainMass = self.mass / self.grainNumber
grainMassDot = self.massDot / self.grainNumber
grainNumber = self.grainNumber
grainInertiaI = grainMass * (
(1 / 4) * (self.grainOuterRadius ** 2 + self.grainInnerRadius ** 2)
+ (1 / 12) * self.grainHeight ** 2
)
# Calculate each grain's distance d to propellant center of mass
initialValue = (grainNumber - 1) / 2
d = np.linspace(-initialValue, initialValue, self.grainNumber)
d = d * (self.grainInitialHeight + self.grainSeparation)
# Calculate inertia for all grains
self.inertiaI = grainNumber * (grainInertiaI) + grainMass * np.sum(d ** 2)
self.inertiaI.setOutputs("Propellant Inertia I (kg*m2)")
# Inertia I Dot
# Calculate each grain's inertia I dot
grainInertiaIDot = (
grainMassDot
* (
(1 / 4) * (self.grainOuterRadius ** 2 + self.grainInnerRadius ** 2)
+ (1 / 12) * self.grainHeight ** 2
)
+ grainMass
* ((1 / 2) * self.grainInnerRadius - (1 / 3) * self.grainHeight)
* self.burnRate
)
# Calculate inertia I dot for all grains
self.inertiaIDot = grainNumber * (grainInertiaIDot) + grainMassDot * np.sum(
d ** 2
)
self.inertiaIDot.setOutputs("Propellant Inertia I Dot (kg*m2/s)")
# Inertia Z
self.inertiaZ = (
(1 / 2.0)
* self.mass
* (self.grainOuterRadius ** 2 + self.grainInnerRadius ** 2)
)
self.inertiaZ.setOutputs("Propellant Inertia Z (kg*m2)")
# Inertia Z Dot
self.inertiaZDot = (
(1 / 2.0) * (self.massDot * self.grainOuterRadius ** 2)
+ (1 / 2.0) * (self.massDot * self.grainInnerRadius ** 2)
+ self.mass * self.grainInnerRadius * self.burnRate
)
self.inertiaZDot.setOutputs("Propellant Inertia Z Dot (kg*m2/s)")
return [self.inertiaI, self.inertiaZ]
def importEng(self, fileName):
"""Read content from .eng file and process it, in order to
return the comments, description and data points.
Parameters
----------
fileName : string
Name of the .eng file. E.g. 'test.eng'.
Note that the .eng file must not contain the 0 0 point.
Returns
-------
comments : list
All comments in the .eng file, separated by line in a list. Each
line is an entry of the list.
description: list
Description of the motor. All attributes are returned separated in
a list. E.g. "F32 24 124 5-10-15 .0377 .0695 RV\n" is return as
['F32', '24', '124', '5-10-15', '.0377', '.0695', 'RV\n']
dataPoints: list
List of all data points in file. Each data point is an entry in
the returned list and written as a list of two entries.
"""
# Intiailize arrays
comments = []
description = []
dataPoints = [[0, 0]]
# Open and read .eng file
with open(fileName) as file:
for line in file:
if line[0] == ";":
# Extract comment
comments.append(line)
else:
if description == []:
# Extract description
description = line.split(" ")
else:
# Extract thrust curve data points
time, thrust = re.findall(r"[-+]?\d*\.\d+|[-+]?\d+", line)
dataPoints.append([float(time), float(thrust)])
# Return all extract content
return comments, description, dataPoints
def exportEng(self, fileName, motorName):
"""Exports thrust curve data points and motor description to
.eng file format. A description of the format can be found
here: http://www.thrustcurve.org/raspformat.shtml
Parameters
----------
fileName : string
Name of the .eng file to be exported. E.g. 'test.eng'
motorName : string
Name given to motor. Will appear in the description of the
.eng file. E.g. 'Mandioca'
Returns
-------
None
"""
# Open file
file = open(fileName, "w")
# Write first line
file.write(
motorName
+ " {:3.1f} {:3.1f} 0 {:2.3} {:2.3} PJ \n".format(
2000 * self.grainOuterRadius,
1000
* self.grainNumber
* (self.grainInitialHeight + self.grainSeparation),
self.propellantInitialMass,
self.propellantInitialMass,
)
)
# Write thrust curve data points
for item in self.thrust.source[:-1, :]:
time = item[0]
thrust = item[1]
file.write("{:.4f} {:.3f}\n".format(time, thrust))
# Write last line
file.write("{:.4f} {:.3f}\n".format(self.thrust.source[-1, 0], 0))
# Close file
file.close()
return None
def info(self):
"""Prints out a summary of the data and graphs available about
the Motor.
Parameters
----------
None
Return
------
None
"""
# Print motor details
print("\nMotor Details")
print("Total Burning Time: " + str(self.burnOutTime) + " s")
print(
"Total Propellant Mass: "
+ "{:.3f}".format(self.propellantInitialMass)
+ " kg"
)
print(
"Propellant Exhaust Velocity: "
+ "{:.3f}".format(self.exhaustVelocity)
+ " m/s"
)
print("Average Thrust: " + "{:.3f}".format(self.averageThrust) + " N")
print(
"Maximum Thrust: "
+ str(self.maxThrust)
+ " N at "
+ str(self.maxThrustTime)
+ " s after ignition."
)
print("Total Impulse: " + "{:.3f}".format(self.totalImpulse) + " Ns")
# Show plots
print("\nPlots")
self.thrust()
return None
def allInfo(self):
"""Prints out all data and graphs available about the Motor.
Parameters
----------
None
Return
------
None
"""
# Print nozzle details
print("Nozzle Details")
print("Nozzle Radius: " + str(self.nozzleRadius) + " m")
print("Nozzle Throat Radius: " + str(self.throatRadius) + " m")
# Print grain details
print("\nGrain Details")
print("Number of Grains: " + str(self.grainNumber))
print("Grain Spacing: " + str(self.grainSeparation) + " m")
print("Grain Density: " + str(self.grainDensity) + " kg/m3")
print("Grain Outer Radius: " + str(self.grainOuterRadius) + " m")
print("Grain Inner Radius: " + str(self.grainInitialInnerRadius) + " m")
print("Grain Height: " + str(self.grainInitialHeight) + " m")
print("Grain Volume: " + "{:.3f}".format(self.grainInitialVolume) + " m3")
print("Grain Mass: " + "{:.3f}".format(self.grainInitialMass) + " kg")
# Print motor details
print("\nMotor Details")
print("Total Burning Time: " + str(self.burnOutTime) + " s")
print(
"Total Propellant Mass: "
+ "{:.3f}".format(self.propellantInitialMass)
+ " kg"
)
print(
"Propellant Exhaust Velocity: "
+ "{:.3f}".format(self.exhaustVelocity)
+ " m/s"
)
print("Average Thrust: " + "{:.3f}".format(self.averageThrust) + " N")
print(
"Maximum Thrust: "
+ str(self.maxThrust)
+ " N at "
+ str(self.maxThrustTime)
+ " s after ignition."
)
print("Total Impulse: " + "{:.3f}".format(self.totalImpulse) + " Ns")
# Show plots
print("\nPlots")
self.thrust()
self.mass()
self.massDot()
self.grainInnerRadius()
self.grainHeight()
self.burnRate()
self.burnArea()
self.Kn()
self.inertiaI()
self.inertiaIDot()
self.inertiaZ()
self.inertiaZDot()
return None | /rocket.py-1.0.1.tar.gz/rocket.py-1.0.1/rocketpy/SolidMotor.py | 0.877135 | 0.560914 | SolidMotor.py | pypi |
__author__ = "Giovani Hidalgo Ceotto, João Lemes Gribel Soares"
__copyright__ = "Copyright 20XX, Projeto Jupiter"
__license__ = "MIT"
import re
import math
import bisect
import warnings
import time
from datetime import datetime, timedelta
from inspect import signature, getsourcelines
from collections import namedtuple
import numpy as np
from scipy import integrate
from scipy import linalg
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from .Function import Function
class Flight:
"""Keeps all flight information and has a method to simulate flight.
Attributes
----------
Other classes:
Flight.env : Environment
Environment object describing rail length, elevation, gravity and
weather condition. See Environment class for more details.
Flight.rocket : Rocket
Rocket class describing rocket. See Rocket class for more
details.
Flight.parachutes : Parachutes
Direct link to parachutes of the Rocket. See Rocket class
for more details.
Flight.frontalSurfaceWind : float
Surface wind speed in m/s aligned with the launch rail.
Flight.lateralSurfaceWind : float
Surface wind speed in m/s perpendicular to launch rail.
Helper classes:
Flight.flightPhases : class
Helper class to organize and manage different flight phases.
Flight.timeNodes : class
Helper class to manage time discretization during simulation.
Helper functions:
Flight.timeIterator : function
Helper iterator function to generate time discretization points.
Helper parameters:
Flight.effective1RL : float
Original rail length minus the distance measured from nozzle exit
to the upper rail button. It assumes the nozzle to be aligned with
the beginning of the rail.
Flight.effective2RL : float
Original rail length minus the distance measured from nozzle exit
to the lower rail button. It assumes the nozzle to be aligned with
the beginning of the rail.
Numerical Integration settings:
Flight.maxTime : int, float
Maximum simulation time allowed. Refers to physical time
being simulated, not time taken to run simulation.
Flight.maxTimeStep : int, float
Maximum time step to use during numerical integration in seconds.
Flight.minTimeStep : int, float
Minimum time step to use during numerical integration in seconds.
Flight.rtol : int, float
Maximum relative error tolerance to be tolerated in the
numerical integration scheme.
Flight.atol : int, float
Maximum absolute error tolerance to be tolerated in the
integration scheme.
Flight.timeOvershoot : bool, optional
If True, decouples ODE time step from parachute trigger functions
sampling rate. The time steps can overshoot the necessary trigger
function evaluation points and then interpolation is used to
calculate them and feed the triggers. Can greatly improve run
time in some cases.
Flight.terminateOnApogee : bool
Whether to terminate simulation when rocket reaches apogee.
Flight.solver : scipy.integrate.LSODA
Scipy LSODA integration scheme.
State Space Vector Definition:
(Only available after Flight.postProcess has been called.)
Flight.x : Function
Rocket's X coordinate (positive east) as a function of time.
Flight.y : Function
Rocket's Y coordinate (positive north) as a function of time.
Flight.z : Function
Rocket's z coordinate (positive up) as a function of time.
Flight.vx : Function
Rocket's X velocity as a function of time.
Flight.vy : Function
Rocket's Y velocity as a function of time.
Flight.vz : Function
Rocket's Z velocity as a function of time.
Flight.e0 : Function
Rocket's Euler parameter 0 as a function of time.
Flight.e1 : Function
Rocket's Euler parameter 1 as a function of time.
Flight.e2 : Function
Rocket's Euler parameter 2 as a function of time.
Flight.e3 : Function
Rocket's Euler parameter 3 as a function of time.
Flight.w1 : Function
Rocket's angular velocity Omega 1 as a function of time.
Direction 1 is in the rocket's body axis and points perpendicular
to the rocket's axis of cylindrical symmetry.
Flight.w2 : Function
Rocket's angular velocity Omega 2 as a function of time.
Direction 2 is in the rocket's body axis and points perpendicular
to the rocket's axis of cylindrical symmetry and direction 1.
Flight.w3 : Function
Rocket's angular velocity Omega 3 as a function of time.
Direction 3 is in the rocket's body axis and points in the
direction of cylindrical symmetry.
Solution attributes:
Flight.inclination : int, float
Launch rail inclination angle relative to ground, given in degrees.
Flight.heading : int, float
Launch heading angle relative to north given in degrees.
Flight.initialSolution : list
List defines initial condition - [tInit, xInit,
yInit, zInit, vxInit, vyInit, vzInit, e0Init, e1Init,
e2Init, e3Init, w1Init, w2Init, w3Init]
Flight.tInitial : int, float
Initial simulation time in seconds. Usually 0.
Flight.solution : list
Solution array which keeps results from each numerical
integration.
Flight.t : float
Current integration time.
Flight.y : list
Current integration state vector u.
Flight.postProcessed : bool
Defines if solution data has been post processed.
Solution monitor attributes:
Flight.initialSolution : list
List defines initial condition - [tInit, xInit,
yInit, zInit, vxInit, vyInit, vzInit, e0Init, e1Init,
e2Init, e3Init, w1Init, w2Init, w3Init]
Flight.outOfRailTime : int, float
Time, in seconds, in which the rocket completely leaves the
rail.
Flight.outOfRailState : list
State vector u corresponding to state when the rocket
completely leaves the rail.
Flight.outOfRailVelocity : int, float
Velocity, in m/s, with which the rocket completely leaves the
rail.
Flight.apogeeState : array
State vector u corresponding to state when the rocket's
vertical velocity is zero in the apogee.
Flight.apogeeTime : int, float
Time, in seconds, in which the rocket's vertical velocity
reaches zero in the apogee.
Flight.apogeeX : int, float
X coordinate (positive east) of the center of mass of the
rocket when it reaches apogee.
Flight.apogeeY : int, float
Y coordinate (positive north) of the center of mass of the
rocket when it reaches apogee.
Flight.apogee : int, float
Z coordinate, or altitute, of the center of mass of the
rocket when it reaches apogee.
Flight.xImpact : int, float
X coordinate (positive east) of the center of mass of the
rocket when it impacts ground.
Flight.yImpact : int, float
Y coordinate (positive east) of the center of mass of the
rocket when it impacts ground.
Flight.impactVelocity : int, float
Velocity magnitude of the center of mass of the rocket when
it impacts ground.
Flight.impactState : array
State vector u corresponding to state when the rocket
impacts the ground.
Flight.parachuteEvents : array
List that stores parachute events triggered during flight.
Flight.functionEvaluations : array
List that stores number of derivative function evaluations
during numerical integration in cumulative manner.
Flight.functionEvaluationsPerTimeStep : array
List that stores number of derivative function evaluations
per time step during numerical integration.
Flight.timeSteps : array
List of time steps taking during numerical integration in
seconds.
Flight.flightPhases : Flight.FlightPhases
Stores and manages flight phases.
Solution Secondary Attributes:
(Only available after Flight.postProcess has been called.)
Atmospheric:
Flight.windVelocityX : Function
Wind velocity X (East) experienced by the rocket as a
function of time. Can be called or accessed as array.
Flight.windVelocityY : Function
Wind velocity Y (North) experienced by the rocket as a
function of time. Can be called or accessed as array.
Flight.density : Function
Air density experienced by the rocket as a function of
time. Can be called or accessed as array.
Flight.pressure : Function
Air pressure experienced by the rocket as a function of
time. Can be called or accessed as array.
Flight.dynamicViscosity : Function
Air dynamic viscosity experienced by the rocket as a function of
time. Can be called or accessed as array.
Flight.speedOfSound : Function
Speed of Sound in air experienced by the rocket as a
function of time. Can be called or accessed as array.
Kinematics:
Flight.ax : Function
Rocket's X (East) acceleration as a function of time, in m/s².
Can be called or accessed as array.
Flight.ay : Function
Rocket's Y (North) acceleration as a function of time, in m/s².
Can be called or accessed as array.
Flight.az : Function
Rocket's Z (Up) acceleration as a function of time, in m/s².
Can be called or accessed as array.
Flight.alpha1 : Function
Rocket's angular acceleration Alpha 1 as a function of time.
Direction 1 is in the rocket's body axis and points perpendicular
to the rocket's axis of cylindrical symmetry.
Units of rad/s². Can be called or accessed as array.
Flight.alpha2 : Function
Rocket's angular acceleration Alpha 2 as a function of time.
Direction 2 is in the rocket's body axis and points perpendicular
to the rocket's axis of cylindrical symmetry and direction 1.
Units of rad/s². Can be called or accessed as array.
Flight.alpha3 : Function
Rocket's angular acceleration Alpha 3 as a function of time.
Direction 3 is in the rocket's body axis and points in the
direction of cylindrical symmetry.
Units of rad/s². Can be called or accessed as array.
Flight.speed : Function
Rocket velocity magnitude in m/s relative to ground as a
function of time. Can be called or accessed as array.
Flight.maxSpeed : float
Maximum velocity magnitude in m/s reached by the rocket
relative to ground during flight.
Flight.maxSpeedTime : float
Time in seconds at which rocket reaches maximum velocity
magnitude relative to ground.
Flight.horizontalSpeed : Function
Rocket's velocity magnitude in the horizontal (North-East)
plane in m/s as a function of time. Can be called or
accessed as array.
Flight.Acceleration : Function
Rocket acceleration magnitude in m/s² relative to ground as a
function of time. Can be called or accessed as array.
Flight.maxAcceleration : float
Maximum acceleration magnitude in m/s² reached by the rocket
relative to ground during flight.
Flight.maxAccelerationTime : float
Time in seconds at which rocket reaches maximum acceleration
magnitude relative to ground.
Flight.pathAngle : Function
Rocket's flight path angle, or the angle that the
rocket's velocity makes with the horizontal (North-East)
plane. Measured in degrees and expressed as a function
of time. Can be called or accessed as array.
Flight.attitudeVectorX : Function
Rocket's attiude vector, or the vector that points
in the rocket's axis of symmetry, component in the X
direction (East) as a function of time.
Can be called or accessed as array.
Flight.attitudeVectorY : Function
Rocket's attiude vector, or the vector that points
in the rocket's axis of symmetry, component in the Y
direction (East) as a function of time.
Can be called or accessed as array.
Flight.attitudeVectorZ : Function
Rocket's attiude vector, or the vector that points
in the rocket's axis of symmetry, component in the Z
direction (East) as a function of time.
Can be called or accessed as array.
Flight.attitudeAngle : Function
Rocket's attiude angle, or the angle that the
rocket's axis of symmetry makes with the horizontal (North-East)
plane. Measured in degrees and expressed as a function
of time. Can be called or accessed as array.
Flight.lateralAttitudeAngle : Function
Rocket's lateral attiude angle, or the angle that the
rocket's axis of symmetry makes with plane defined by
the launch rail direction and the Z (up) axis.
Measured in degrees and expressed as a function
of time. Can be called or accessed as array.
Flight.phi : Function
Rocket's Spin Euler Angle, φ, according to the 3-2-3 rotation
system (NASA Standard Aerospace). Measured in degrees and
expressed as a function of time. Can be called or accessed as array.
Flight.theta : Function
Rocket's Nutation Euler Angle, θ, according to the 3-2-3 rotation
system (NASA Standard Aerospace). Measured in degrees and
expressed as a function of time. Can be called or accessed as array.
Flight.psi : Function
Rocket's Precession Euler Angle, ψ, according to the 3-2-3 rotation
system (NASA Standard Aerospace). Measured in degrees and
expressed as a function of time. Can be called or accessed as array.
Dynamics:
Flight.R1 : Function
Resultant force perpendicular to rockets axis due to
aerodynamic forces as a function of time. Units in N.
Expressed as a function of time. Can be called or accessed
as array.
Direction 1 is in the rocket's body axis and points perpendicular
to the rocket's axis of cylindrical symmetry.
Flight.R2 : Function
Resultant force perpendicular to rockets axis due to
aerodynamic forces as a function of time. Units in N.
Expressed as a function of time. Can be called or accessed
as array.
Direction 2 is in the rocket's body axis and points perpendicular
to the rocket's axis of cylindrical symmetry and direction 1.
Flight.R3 : Function
Resultant force in rockets axis due to aerodynamic forces
as a function of time. Units in N. Usually just drag.
Expressed as a function of time. Can be called or accessed
as array.
Direction 3 is in the rocket's body axis and points in the
direction of cylindrical symmetry.
Flight.M1 : Function
Resultant moment (torque) perpendicular to rockets axis due to
aerodynamic forces and excentricity as a function of time.
Units in N*m.
Expressed as a function of time. Can be called or accessed
as array.
Direction 1 is in the rocket's body axis and points perpendicular
to the rocket's axis of cylindrical symmetry.
Flight.M2 : Function
Resultant moment (torque) perpendicular to rockets axis due to
aerodynamic forces and excentricity as a function of time.
Units in N*m.
Expressed as a function of time. Can be called or accessed
as array.
Direction 2 is in the rocket's body axis and points perpendicular
to the rocket's axis of cylindrical symmetry and direction 1.
Flight.M3 : Function
Resultant moment (torque) in rockets axis due to aerodynamic
forces and excentricity as a function of time. Units in N*m.
Expressed as a function of time. Can be called or accessed
as array.
Direction 3 is in the rocket's body axis and points in the
direction of cylindrical symmetry.
Flight.aerodynamicLift : Function
Resultant force perpendicular to rockets axis due to
aerodynamic effects as a function of time. Units in N.
Expressed as a function of time. Can be called or accessed
as array.
Flight.aerodynamicDrag : Function
Resultant force aligned with the rockets axis due to
aerodynamic effects as a function of time. Units in N.
Expressed as a function of time. Can be called or accessed
as array.
Flight.aerodynamicBendingMoment : Function
Resultant moment perpendicular to rocket's axis due to
aerodynamic effects as a function of time. Units in N m.
Expressed as a function of time. Can be called or accessed
as array.
Flight.aerodynamicSpinMoment : Function
Resultant moment aligned with the rockets axis due to
aerodynamic effects as a function of time. Units in N m.
Expressed as a function of time. Can be called or accessed
as array.
Flight.railButton1NormalForce : Function
Upper rail button normal force in N as a function
of time. Can be called or accessed as array.
Flight.maxRailButton1NormalForce : float
Maximum upper rail button normal force experienced
during rail flight phase in N.
Flight.railButton1ShearForce : Function
Upper rail button shear force in N as a function
of time. Can be called or accessed as array.
Flight.maxRailButton1ShearForce : float
Maximum upper rail button shear force experienced
during rail flight phase in N.
Flight.railButton2NormalForce : Function
Lower rail button normal force in N as a function
of time. Can be called or accessed as array.
Flight.maxRailButton2NormalForce : float
Maximum lower rail button normal force experienced
during rail flight phase in N.
Flight.railButton2ShearForce : Function
Lower rail button shear force in N as a function
of time. Can be called or accessed as array.
Flight.maxRailButton2ShearForce : float
Maximum lower rail button shear force experienced
during rail flight phase in N.
Flight.rotationalEnergy : Function
Rocket's rotational kinetic energy as a function of time.
Units in J.
Flight.translationalEnergy : Function
Rocket's translational kinetic energy as a function of time.
Units in J.
Flight.kineticEnergy : Function
Rocket's total kinetic energy as a function of time.
Units in J.
Flight.potentialEnergy : Function
Rocket's gravitational potential energy as a function of
time. Units in J.
Flight.totalEnergy : Function
Rocket's total mechanical energy as a function of time.
Units in J.
Flight.thrustPower : Function
Rocket's engine thrust power output as a function
of time in Watts. Can be called or accessed as array.
Flight.dragPower : Function
Aerodynamic drag power output as a function
of time in Watts. Can be called or accessed as array.
Stability and Control:
Flight.attitudeFrequencyResponse : Function
Fourier Frequency Analysis of the rocket's attitude angle.
Expressed as the absolute vale of the magnitude as a function
of frequency in Hz. Can be called or accessed as array.
Flight.omega1FrequencyResponse : Function
Fourier Frequency Analysis of the rocket's angular velocity omega 1.
Expressed as the absolute vale of the magnitude as a function
of frequency in Hz. Can be called or accessed as array.
Flight.omega2FrequencyResponse : Function
Fourier Frequency Analysis of the rocket's angular velocity omega 2.
Expressed as the absolute vale of the magnitude as a function
of frequency in Hz. Can be called or accessed as array.
Flight.omega3FrequencyResponse : Function
Fourier Frequency Analysis of the rocket's angular velocity omega 3.
Expressed as the absolute vale of the magnitude as a function
of frequency in Hz. Can be called or accessed as array.
Flight.staticMargin : Function
Rocket's static margin during flight in calibers.
Fluid Mechanics:
Flight.streamVelocityX : Function
Freestream velocity x (East) component, in m/s, as a function of
time. Can be called or accessed as array.
Flight.streamVelocityY : Function
Freestream velocity y (North) component, in m/s, as a function of
time. Can be called or accessed as array.
Flight.streamVelocityZ : Function
Freestream velocity z (up) component, in m/s, as a function of
time. Can be called or accessed as array.
Flight.freestreamSpeed : Function
Freestream velocity magnitude, in m/s, as a function of time.
Can be called or accessed as array.
Flight.apogeeFreestreamSpeed : float
Freestream speed of the rocket at apogee in m/s.
Flight.MachNumber : Function
Rocket's Mach number defined as its freestream speed
devided by the speed of sound at its altitude. Expressed
as a function of time. Can be called or accessed as array.
Flight.maxMachNumber : float
Rocket's maximum Mach number experienced during flight.
Flight.maxMachNumberTime : float
Time at which the rocket experiences the maximum Mach number.
Flight.ReynoldsNumber : Function
Rocket's Reynolds number, using its diameter as reference
length and freestreamSpeed as reference velocity. Expressed
as a function of time. Can be called or accessed as array.
Flight.maxReynoldsNumber : float
Rocket's maximum Reynolds number experienced during flight.
Flight.maxReynoldsNumberTime : float
Time at which the rocket experiences the maximum Reynolds number.
Flight.dynamicPressure : Function
Dynamic pressure experienced by the rocket in Pa as a function
of time, defined by 0.5*rho*V^2, where rho is air density and V
is the freestream speed. Can be called or accessed as array.
Flight.maxDynamicPressure : float
Maximum dynamic pressure, in Pa, experienced by the rocket.
Flight.maxDynamicPressureTime : float
Time at which the rocket experiences maximum dynamic pressure.
Flight.totalPressure : Function
Total pressure experienced by the rocket in Pa as a function
of time. Can be called or accessed as array.
Flight.maxTotalPressure : float
Maximum total pressure, in Pa, experienced by the rocket.
Flight.maxTotalPressureTime : float
Time at which the rocket experiences maximum total pressure.
Flight.angleOfAttack : Function
Rocket's angle of attack in degrees as a function of time.
Defined as the minimum angle between the attitude vector and
the freestream velocity vector. Can be called or accessed as
array.
Fin Flutter Analysis:
Flight.flutterMachNumber: Function
The freestream velocity at which begins flutter phenomenon in
rocket's fins. It's expressed as a function of the air pressure
experienced for the rocket. Can be called or accessed as array.
Flight.difference: Function
Difference between flutterMachNumber and machNumber, as a function of time.
Flight.safetyFactor: Function
Ratio between the flutterMachNumber and machNumber, as a function of time.
"""
def __init__(
self,
rocket,
environment,
inclination=80,
heading=90,
initialSolution=None,
terminateOnApogee=False,
maxTime=600,
maxTimeStep=np.inf,
minTimeStep=0,
rtol=1e-6,
atol=6 * [1e-3] + 4 * [1e-6] + 3 * [1e-3],
timeOvershoot=True,
verbose=False,
):
"""Run a trajectory simulation.
Parameters
----------
rocket : Rocket
Rocket to simulate. See help(Rocket) for more information.
environment : Environment
Environment to run simulation on. See help(Environment) for
more information.
inclination : int, float, optional
Rail inclination angle relative to ground, given in degrees.
Default is 80.
heading : int, float, optional
Heading angle relative to north given in degrees.
Default is 90, which points in the x direction.
initialSolution : array, optional
Initial solution array to be used. Format is
initialSolution = [self.tInitial,
xInit, yInit, zInit,
vxInit, vyInit, vzInit,
e0Init, e1Init, e2Init, e3Init,
w1Init, w2Init, w3Init].
If None, the initial solution will start with all null values,
except for the euler parameters which will be calculated based
on given values of inclination and heading. Default is None.
terminateOnApogee : boolean, optioanal
Whether to terminate simulation when rocket reaches apogee.
Default is False.
maxTime : int, float, optional
Maximum time in which to simulate trajectory in seconds.
Using this without setting a maxTimeStep may cause unexpected
errors. Default is 600.
maxTimeStep : int, float, optional
Maximum time step to use during integration in seconds.
Default is 0.01.
minTimeStep : int, float, optional
Minimum time step to use during integration in seconds.
Default is 0.01.
rtol : float, array, optional
Maximum relative error tolerance to be tolerated in the
integration scheme. Can be given as array for each
state space variable. Default is 1e-3.
atol : float, optional
Maximum absolute error tolerance to be tolerated in the
integration scheme. Can be given as array for each
state space variable. Default is 6*[1e-3] + 4*[1e-6] + 3*[1e-3].
timeOvershoot : bool, optional
If True, decouples ODE time step from parachute trigger functions
sampling rate. The time steps can overshoot the necessary trigger
function evaluation points and then interpolation is used to
calculate them and feed the triggers. Can greatly improve run
time in some cases. Default is True.
verbose : bool, optional
If true, verbose mode is activated. Default is False.
Returns
-------
None
"""
# Fetch helper classes and functions
FlightPhases = self.FlightPhases
TimeNodes = self.TimeNodes
timeIterator = self.timeIterator
# Save rocket, parachutes, environment, maximum simulation time
# and termination events
self.env = environment
self.rocket = rocket
self.parachutes = self.rocket.parachutes[:]
self.inclination = inclination
self.heading = heading
self.maxTime = maxTime
self.maxTimeStep = maxTimeStep
self.minTimeStep = minTimeStep
self.rtol = rtol
self.atol = atol
self.initialSolution = initialSolution
self.timeOvershoot = timeOvershoot
self.terminateOnApogee = terminateOnApogee
# Modifying Rail Length for a better out of rail condition
upperRButton = max(self.rocket.railButtons[0])
lowerRButton = min(self.rocket.railButtons[0])
nozzle = self.rocket.distanceRocketNozzle
self.effective1RL = self.env.rL - abs(nozzle - upperRButton)
self.effective2RL = self.env.rL - abs(nozzle - lowerRButton)
# Flight initialization
# Initialize solution monitors
self.outOfRailTime = 0
self.outOfRailState = np.array([0])
self.outOfRailVelocity = 0
self.apogeeState = np.array([0])
self.apogeeTime = 0
self.apogeeX = 0
self.apogeeY = 0
self.apogee = 0
self.xImpact = 0
self.yImpact = 0
self.impactVelocity = 0
self.impactState = np.array([0])
self.parachuteEvents = []
self.postProcessed = False
# Intialize solver monitors
self.functionEvaluations = []
self.functionEvaluationsPerTimeStep = []
self.timeSteps = []
# Initialize solution state
self.solution = []
if self.initialSolution is None:
# Initialize time and state variables
self.tInitial = 0
xInit, yInit, zInit = 0, 0, self.env.elevation
vxInit, vyInit, vzInit = 0, 0, 0
w1Init, w2Init, w3Init = 0, 0, 0
# Initialize attitude
psiInit = -heading * (np.pi / 180) # Precession / Heading Angle
thetaInit = (inclination - 90) * (np.pi / 180) # Nutation Angle
e0Init = np.cos(psiInit / 2) * np.cos(thetaInit / 2)
e1Init = np.cos(psiInit / 2) * np.sin(thetaInit / 2)
e2Init = np.sin(psiInit / 2) * np.sin(thetaInit / 2)
e3Init = np.sin(psiInit / 2) * np.cos(thetaInit / 2)
# Store initial conditions
self.initialSolution = [
self.tInitial,
xInit,
yInit,
zInit,
vxInit,
vyInit,
vzInit,
e0Init,
e1Init,
e2Init,
e3Init,
w1Init,
w2Init,
w3Init,
]
# Set initial derivative for rail phase
self.initialDerivative = self.uDotRail1
else:
# Initial solution given, ignore rail phase
# TODO: Check if rocket is actually out of rail. Otherwise, start at rail
self.outOfRailState = self.initialSolution[1:]
self.outOfRailTime = self.initialSolution[0]
self.initialDerivative = self.uDot
self.tInitial = self.initialSolution[0]
self.solution.append(self.initialSolution)
self.t = self.solution[-1][0]
self.y = self.solution[-1][1:]
# Calculate normal and lateral surface wind
windU = self.env.windVelocityX(self.env.elevation)
windV = self.env.windVelocityY(self.env.elevation)
headingRad = heading * np.pi / 180
self.frontalSurfaceWind = windU * np.sin(headingRad) + windV * np.cos(
headingRad
)
self.lateralSurfaceWind = -windU * np.cos(headingRad) + windV * np.sin(
headingRad
)
# Create known flight phases
self.flightPhases = FlightPhases()
self.flightPhases.addPhase(self.tInitial, self.initialDerivative, clear=False)
self.flightPhases.addPhase(self.maxTime)
# Simulate flight
for phase_index, phase in timeIterator(self.flightPhases):
# print('\nCurrent Flight Phase List')
# print(self.flightPhases)
# print('\n\tCurrent Flight Phase')
# print('\tIndex: ', phase_index, ' | Phase: ', phase)
# Determine maximum time for this flight phase
phase.timeBound = self.flightPhases[phase_index + 1].t
# Evaluate callbacks
for callback in phase.callbacks:
callback(self)
# Create solver for this flight phase
self.functionEvaluations.append(0)
phase.solver = integrate.LSODA(
phase.derivative,
t0=phase.t,
y0=self.y,
t_bound=phase.timeBound,
min_step=self.minTimeStep,
max_step=self.maxTimeStep,
rtol=self.rtol,
atol=self.atol,
)
# print('\n\tSolver Initialization Details')
# print('\tInitial Time: ', phase.t)
# print('\tInitial State: ', self.y)
# print('\tTime Bound: ', phase.timeBound)
# print('\tMin Step: ', self.minTimeStep)
# print('\tMax Step: ', self.maxTimeStep)
# print('\tTolerances: ', self.rtol, self.atol)
# Initialize phase time nodes
phase.timeNodes = TimeNodes()
# Add first time node to permanent list
phase.timeNodes.addNode(phase.t, [], [])
# Add non-overshootable parachute time nodes
if self.timeOvershoot is False:
phase.timeNodes.addParachutes(self.parachutes, phase.t, phase.timeBound)
# Add lst time node to permanent list
phase.timeNodes.addNode(phase.timeBound, [], [])
# Sort time nodes
phase.timeNodes.sort()
# Merge equal time nodes
phase.timeNodes.merge()
# Clear triggers from first time node if necessary
if phase.clear:
phase.timeNodes[0].parachutes = []
phase.timeNodes[0].callbacks = []
# print('\n\tPhase Time Nodes')
# print('\tTime Nodes Length: ', str(len(phase.timeNodes)), ' | Time Nodes Preview: ', phase.timeNodes[0:3])
# Iterate through time nodes
for node_index, node in timeIterator(phase.timeNodes):
# print('\n\t\tCurrent Time Node')
# print('\t\tIndex: ', node_index, ' | Time Node: ', node)
# Determine time bound for this time node
node.timeBound = phase.timeNodes[node_index + 1].t
phase.solver.t_bound = node.timeBound
phase.solver._lsoda_solver._integrator.rwork[0] = phase.solver.t_bound
phase.solver._lsoda_solver._integrator.call_args[
4
] = phase.solver._lsoda_solver._integrator.rwork
phase.solver.status = "running"
# Feed required parachute and discrete controller triggers
for callback in node.callbacks:
callback(self)
for parachute in node.parachutes:
# Calculate and save pressure signal
pressure = self.env.pressure.getValueOpt(self.y[2])
parachute.cleanPressureSignal.append([node.t, pressure])
# Calculate and save noise
noise = parachute.noiseFunction()
parachute.noiseSignal.append([node.t, noise])
parachute.noisyPressureSignal.append([node.t, pressure + noise])
if parachute.trigger(pressure + noise, self.y):
# print('\nEVENT DETECTED')
# print('Parachute Triggered')
# print('Name: ', parachute.name, ' | Lag: ', parachute.lag)
# Remove parachute from flight parachutes
self.parachutes.remove(parachute)
# Create flight phase for time after detection and before inflation
self.flightPhases.addPhase(
node.t, phase.derivative, clear=True, index=phase_index + 1
)
# Create flight phase for time after inflation
callbacks = [
lambda self, parachuteCdS=parachute.CdS: setattr(
self, "parachuteCdS", parachuteCdS
)
]
self.flightPhases.addPhase(
node.t + parachute.lag,
self.uDotParachute,
callbacks,
clear=False,
index=phase_index + 2,
)
# Prepare to leave loops and start new flight phase
phase.timeNodes.flushAfter(node_index)
phase.timeNodes.addNode(self.t, [], [])
phase.solver.status = "finished"
# Save parachute event
self.parachuteEvents.append([self.t, parachute])
# Step through simulation
while phase.solver.status == "running":
# Step
phase.solver.step()
# Save step result
self.solution += [[phase.solver.t, *phase.solver.y]]
# Step step metrics
self.functionEvaluationsPerTimeStep.append(
phase.solver.nfev - self.functionEvaluations[-1]
)
self.functionEvaluations.append(phase.solver.nfev)
self.timeSteps.append(phase.solver.step_size)
# Update time and state
self.t = phase.solver.t
self.y = phase.solver.y
if verbose:
print(
"Current Simulation Time: {:3.4f} s".format(self.t),
end="\r",
)
# print('\n\t\t\tCurrent Step Details')
# print('\t\t\tIState: ', phase.solver._lsoda_solver._integrator.istate)
# print('\t\t\tTime: ', phase.solver.t)
# print('\t\t\tAltitude: ', phase.solver.y[2])
# print('\t\t\tEvals: ', self.functionEvaluationsPerTimeStep[-1])
# Check for first out of rail event
if len(self.outOfRailState) == 1 and (
self.y[0] ** 2
+ self.y[1] ** 2
+ (self.y[2] - self.env.elevation) ** 2
>= self.effective1RL ** 2
):
# Rocket is out of rail
# Check exactly when it went out using root finding
# States before and after
# t0 -> 0
# print('\nEVENT DETECTED')
# print('Rocket is Out of Rail!')
# Disconsider elevation
self.solution[-2][3] -= self.env.elevation
self.solution[-1][3] -= self.env.elevation
# Get points
y0 = (
sum([self.solution[-2][i] ** 2 for i in [1, 2, 3]])
- self.effective1RL ** 2
)
yp0 = 2 * sum(
[
self.solution[-2][i] * self.solution[-2][i + 3]
for i in [1, 2, 3]
]
)
t1 = self.solution[-1][0] - self.solution[-2][0]
y1 = (
sum([self.solution[-1][i] ** 2 for i in [1, 2, 3]])
- self.effective1RL ** 2
)
yp1 = 2 * sum(
[
self.solution[-1][i] * self.solution[-1][i + 3]
for i in [1, 2, 3]
]
)
# Put elevation back
self.solution[-2][3] += self.env.elevation
self.solution[-1][3] += self.env.elevation
# Cubic Hermite interpolation (ax**3 + bx**2 + cx + d)
D = float(phase.solver.step_size)
d = float(y0)
c = float(yp0)
b = float((3 * y1 - yp1 * D - 2 * c * D - 3 * d) / (D ** 2))
a = float(-(2 * y1 - yp1 * D - c * D - 2 * d) / (D ** 3)) + 1e-5
# Find roots
d0 = b ** 2 - 3 * a * c
d1 = 2 * b ** 3 - 9 * a * b * c + 27 * d * a ** 2
c1 = ((d1 + (d1 ** 2 - 4 * d0 ** 3) ** (0.5)) / 2) ** (1 / 3)
t_roots = []
for k in [0, 1, 2]:
c2 = c1 * (-1 / 2 + 1j * (3 ** 0.5) / 2) ** k
t_roots.append(-(1 / (3 * a)) * (b + c2 + d0 / c2))
# Find correct root
valid_t_root = []
for t_root in t_roots:
if 0 < t_root.real < t1 and abs(t_root.imag) < 0.001:
valid_t_root.append(t_root.real)
if len(valid_t_root) > 1:
raise ValueError(
"Multiple roots found when solving for rail exit time."
)
# Determine final state when upper button is going out of rail
self.t = valid_t_root[0] + self.solution[-2][0]
interpolator = phase.solver.dense_output()
self.y = interpolator(self.t)
self.solution[-1] = [self.t, *self.y]
self.outOfRailTime = self.t
self.outOfRailState = self.y
self.outOfRailVelocity = (
self.y[3] ** 2 + self.y[4] ** 2 + self.y[5] ** 2
) ** (0.5)
# Create new flight phase
self.flightPhases.addPhase(
self.t, self.uDot, index=phase_index + 1
)
# Prepare to leave loops and start new flight phase
phase.timeNodes.flushAfter(node_index)
phase.timeNodes.addNode(self.t, [], [])
phase.solver.status = "finished"
# Check for apogee event
if len(self.apogeeState) == 1 and self.y[5] < 0:
# print('\nPASSIVE EVENT DETECTED')
# print('Rocket Has Reached Apogee!')
# Apogee reported
# Assume linear vz(t) to detect when vz = 0
vz0 = self.solution[-2][6]
t0 = self.solution[-2][0]
vz1 = self.solution[-1][6]
t1 = self.solution[-1][0]
t_root = -(t1 - t0) * vz0 / (vz1 - vz0) + t0
# Fetch state at t_root
interpolator = phase.solver.dense_output()
self.apogeeState = interpolator(t_root)
# Store apogee data
self.apogeeTime = t_root
self.apogeeX = self.apogeeState[0]
self.apogeeY = self.apogeeState[1]
self.apogee = self.apogeeState[2]
if self.terminateOnApogee:
# print('Terminate on Apogee Activated!')
self.t = t_root
self.tFinal = self.t
self.state = self.apogeeState
# Roll back solution
self.solution[-1] = [self.t, *self.state]
# Set last flight phase
self.flightPhases.flushAfter(phase_index)
self.flightPhases.addPhase(self.t)
# Prepare to leave loops and start new flight phase
phase.timeNodes.flushAfter(node_index)
phase.timeNodes.addNode(self.t, [], [])
phase.solver.status = "finished"
# Check for impact event
if self.y[2] < self.env.elevation:
# print('\nPASSIVE EVENT DETECTED')
# print('Rocket Has Reached Ground!')
# Impact reported
# Check exactly when it went out using root finding
# States before and after
# t0 -> 0
# Disconsider elevation
self.solution[-2][3] -= self.env.elevation
self.solution[-1][3] -= self.env.elevation
# Get points
y0 = self.solution[-2][3]
yp0 = self.solution[-2][6]
t1 = self.solution[-1][0] - self.solution[-2][0]
y1 = self.solution[-1][3]
yp1 = self.solution[-1][6]
# Put elevation back
self.solution[-2][3] += self.env.elevation
self.solution[-1][3] += self.env.elevation
# Cubic Hermite interpolation (ax**3 + bx**2 + cx + d)
D = float(phase.solver.step_size)
d = float(y0)
c = float(yp0)
b = float((3 * y1 - yp1 * D - 2 * c * D - 3 * d) / (D ** 2))
a = float(-(2 * y1 - yp1 * D - c * D - 2 * d) / (D ** 3))
# Find roots
d0 = b ** 2 - 3 * a * c
d1 = 2 * b ** 3 - 9 * a * b * c + 27 * d * a ** 2
c1 = ((d1 + (d1 ** 2 - 4 * d0 ** 3) ** (0.5)) / 2) ** (1 / 3)
t_roots = []
for k in [0, 1, 2]:
c2 = c1 * (-1 / 2 + 1j * (3 ** 0.5) / 2) ** k
t_roots.append(-(1 / (3 * a)) * (b + c2 + d0 / c2))
# Find correct root
valid_t_root = []
for t_root in t_roots:
if 0 < t_root.real < t1 and abs(t_root.imag) < 0.001:
valid_t_root.append(t_root.real)
if len(valid_t_root) > 1:
raise ValueError(
"Multiple roots found when solving for impact time."
)
# Determine impact state at t_root
self.t = valid_t_root[0] + self.solution[-2][0]
interpolator = phase.solver.dense_output()
self.y = interpolator(self.t)
# Roll back solution
self.solution[-1] = [self.t, *self.y]
# Save impact state
self.impactState = self.y
self.xImpact = self.impactState[0]
self.yImpact = self.impactState[1]
self.zImpact = self.impactState[2]
self.impactVelocity = self.impactState[5]
self.tFinal = self.t
# Set last flight phase
self.flightPhases.flushAfter(phase_index)
self.flightPhases.addPhase(self.t)
# Prepare to leave loops and start new flight phase
phase.timeNodes.flushAfter(node_index)
phase.timeNodes.addNode(self.t, [], [])
phase.solver.status = "finished"
# List and feed overshootable time nodes
if self.timeOvershoot:
# Initialize phase overshootable time nodes
overshootableNodes = TimeNodes()
# Add overshootable parachute time nodes
overshootableNodes.addParachutes(
self.parachutes, self.solution[-2][0], self.t
)
# Add last time node (always skipped)
overshootableNodes.addNode(self.t, [], [])
if len(overshootableNodes) > 1:
# Sort overshootable time nodes
overshootableNodes.sort()
# Merge equal overshootable time nodes
overshootableNodes.merge()
# Clear if necessary
if overshootableNodes[0].t == phase.t and phase.clear:
overshootableNodes[0].parachutes = []
overshootableNodes[0].callbacks = []
# print('\n\t\t\t\tOvershootable Time Nodes')
# print('\t\t\t\tInterval: ', self.solution[-2][0], self.t)
# print('\t\t\t\tOvershootable Nodes Length: ', str(len(overshootableNodes)), ' | Overshootable Nodes: ', overshootableNodes)
# Feed overshootable time nodes trigger
interpolator = phase.solver.dense_output()
for overshootable_index, overshootableNode in timeIterator(
overshootableNodes
):
# print('\n\t\t\t\tCurrent Overshootable Node')
# print('\t\t\t\tIndex: ', overshootable_index, ' | Overshootable Node: ', overshootableNode)
# Calculate state at node time
overshootableNode.y = interpolator(overshootableNode.t)
# Calculate and save pressure signal
pressure = self.env.pressure.getValueOpt(
overshootableNode.y[2]
)
for parachute in overshootableNode.parachutes:
# Save pressure signal
parachute.cleanPressureSignal.append(
[overshootableNode.t, pressure]
)
# Calculate and save noise
noise = parachute.noiseFunction()
parachute.noiseSignal.append(
[overshootableNode.t, noise]
)
parachute.noisyPressureSignal.append(
[overshootableNode.t, pressure + noise]
)
if parachute.trigger(
pressure + noise, overshootableNode.y
):
# print('\nEVENT DETECTED')
# print('Parachute Triggered')
# print('Name: ', parachute.name, ' | Lag: ', parachute.lag)
# Remove parachute from flight parachutes
self.parachutes.remove(parachute)
# Create flight phase for time after detection and before inflation
self.flightPhases.addPhase(
overshootableNode.t,
phase.derivative,
clear=True,
index=phase_index + 1,
)
# Create flight phase for time after inflation
callbacks = [
lambda self, parachuteCdS=parachute.CdS: setattr(
self, "parachuteCdS", parachuteCdS
)
]
self.flightPhases.addPhase(
overshootableNode.t + parachute.lag,
self.uDotParachute,
callbacks,
clear=False,
index=phase_index + 2,
)
# Rollback history
self.t = overshootableNode.t
self.y = overshootableNode.y
self.solution[-1] = [
overshootableNode.t,
*overshootableNode.y,
]
# Prepare to leave loops and start new flight phase
overshootableNodes.flushAfter(
overshootable_index
)
phase.timeNodes.flushAfter(node_index)
phase.timeNodes.addNode(self.t, [], [])
phase.solver.status = "finished"
# Save parachute event
self.parachuteEvents.append([self.t, parachute])
self.tFinal = self.t
if verbose:
print("Simulation Completed at Time: {:3.4f} s".format(self.t))
def uDotRail1(self, t, u, postProcessing=False):
"""Calculates derivative of u state vector with respect to time
when rocket is flying in 1 DOF motion in the rail.
Parameters
----------
t : float
Time in seconds
u : list
State vector defined by u = [x, y, z, vx, vy, vz, e0, e1,
e2, e3, omega1, omega2, omega3].
postProcessing : bool, optional
If True, adds flight data information directly to self
variables such as self.attackAngle. Default is False.
Return
------
uDot : list
State vector defined by uDot = [vx, vy, vz, ax, ay, az,
e0Dot, e1Dot, e2Dot, e3Dot, alpha1, alpha2, alpha3].
"""
# Check if post processing mode is on
if postProcessing:
# Use uDot post processing code
return self.uDot(t, u, True)
# Retrieve integration data
x, y, z, vx, vy, vz, e0, e1, e2, e3, omega1, omega2, omega3 = u
# Retrieve important quantities
# Mass
M = self.rocket.totalMass.getValueOpt(t)
# Get freestrean speed
freestreamSpeed = (
(self.env.windVelocityX.getValueOpt(z) - vx) ** 2
+ (self.env.windVelocityY.getValueOpt(z) - vy) ** 2
+ (vz) ** 2
) ** 0.5
freestreamMach = freestreamSpeed / self.env.speedOfSound.getValueOpt(z)
dragCoeff = self.rocket.powerOnDrag.getValueOpt(freestreamMach)
# Calculate Forces
Thrust = self.rocket.motor.thrust.getValueOpt(t)
rho = self.env.density.getValueOpt(z)
R3 = -0.5 * rho * (freestreamSpeed ** 2) * self.rocket.area * (dragCoeff)
# Calculate Linear acceleration
a3 = (R3 + Thrust) / M - (e0 ** 2 - e1 ** 2 - e2 ** 2 + e3 ** 2) * self.env.g
if a3 > 0:
ax = 2 * (e1 * e3 + e0 * e2) * a3
ay = 2 * (e2 * e3 - e0 * e1) * a3
az = (1 - 2 * (e1 ** 2 + e2 ** 2)) * a3
else:
ax, ay, az = 0, 0, 0
return [vx, vy, vz, ax, ay, az, 0, 0, 0, 0, 0, 0, 0]
def uDotRail2(self, t, u, postProcessing=False):
"""[Still not implemented] Calculates derivative of u state vector with
respect to time when rocket is flying in 3 DOF motion in the rail.
Parameters
----------
t : float
Time in seconds
u : list
State vector defined by u = [x, y, z, vx, vy, vz, e0, e1,
e2, e3, omega1, omega2, omega3].
postProcessing : bool, optional
If True, adds flight data information directly to self
variables such as self.attackAngle, by default False
Returns
-------
uDot : list
State vector defined by uDot = [vx, vy, vz, ax, ay, az,
e0Dot, e1Dot, e2Dot, e3Dot, alpha1, alpha2, alpha3].
"""
# Hey! We will finish this function later, now we just can use uDot
return self.uDot(t, u, postProcessing=postProcessing)
def uDot(self, t, u, postProcessing=False):
"""Calculates derivative of u state vector with respect to time
when rocket is flying in 6 DOF motion during ascent out of rail
and descent without parachute.
Parameters
----------
t : float
Time in seconds
u : list
State vector defined by u = [x, y, z, vx, vy, vz, e0, e1,
e2, e3, omega1, omega2, omega3].
postProcessing : bool, optional
If True, adds flight data information directly to self
variables such as self.attackAngle, by default False
Returns
-------
uDot : list
State vector defined by uDot = [vx, vy, vz, ax, ay, az,
e0Dot, e1Dot, e2Dot, e3Dot, alpha1, alpha2, alpha3].
"""
# Retrieve integration data
x, y, z, vx, vy, vz, e0, e1, e2, e3, omega1, omega2, omega3 = u
# Determine lift force and moment
R1, R2 = 0, 0
M1, M2, M3 = 0, 0, 0
# Determine current behaviour
if t < self.rocket.motor.burnOutTime:
# Motor burning
# Retrieve important motor quantities
# Inertias
Tz = self.rocket.motor.inertiaZ.getValueOpt(t)
Ti = self.rocket.motor.inertiaI.getValueOpt(t)
TzDot = self.rocket.motor.inertiaZDot.getValueOpt(t)
TiDot = self.rocket.motor.inertiaIDot.getValueOpt(t)
# Mass
MtDot = self.rocket.motor.massDot.getValueOpt(t)
Mt = self.rocket.motor.mass.getValueOpt(t)
# Thrust
Thrust = self.rocket.motor.thrust.getValueOpt(t)
# Off center moment
M1 += self.rocket.thrustExcentricityX * Thrust
M2 -= self.rocket.thrustExcentricityY * Thrust
else:
# Motor stopped
# Retrieve important motor quantities
# Inertias
Tz, Ti, TzDot, TiDot = 0, 0, 0, 0
# Mass
MtDot, Mt = 0, 0
# Thrust
Thrust = 0
# Retrieve important quantities
# Inertias
Rz = self.rocket.inertiaZ
Ri = self.rocket.inertiaI
# Mass
Mr = self.rocket.mass
M = Mt + Mr
mu = (Mt * Mr) / (Mt + Mr)
# Geometry
b = -self.rocket.distanceRocketPropellant
c = -self.rocket.distanceRocketNozzle
a = b * Mt / M
rN = self.rocket.motor.nozzleRadius
# Prepare transformation matrix
a11 = 1 - 2 * (e2 ** 2 + e3 ** 2)
a12 = 2 * (e1 * e2 - e0 * e3)
a13 = 2 * (e1 * e3 + e0 * e2)
a21 = 2 * (e1 * e2 + e0 * e3)
a22 = 1 - 2 * (e1 ** 2 + e3 ** 2)
a23 = 2 * (e2 * e3 - e0 * e1)
a31 = 2 * (e1 * e3 - e0 * e2)
a32 = 2 * (e2 * e3 + e0 * e1)
a33 = 1 - 2 * (e1 ** 2 + e2 ** 2)
# Transformation matrix: (123) -> (XYZ)
K = [[a11, a12, a13], [a21, a22, a23], [a31, a32, a33]]
# Transformation matrix: (XYZ) -> (123) or K transpose
Kt = [[a11, a21, a31], [a12, a22, a32], [a13, a23, a33]]
# Calculate Forces and Moments
# Get freestrean speed
windVelocityX = self.env.windVelocityX.getValueOpt(z)
windVelocityY = self.env.windVelocityY.getValueOpt(z)
freestreamSpeed = (
(windVelocityX - vx) ** 2 + (windVelocityY - vy) ** 2 + (vz) ** 2
) ** 0.5
freestreamMach = freestreamSpeed / self.env.speedOfSound.getValueOpt(z)
# Determine aerodynamics forces
# Determine Drag Force
if t > self.rocket.motor.burnOutTime:
dragCoeff = self.rocket.powerOnDrag.getValueOpt(freestreamMach)
else:
dragCoeff = self.rocket.powerOffDrag.getValueOpt(freestreamMach)
rho = self.env.density.getValueOpt(z)
R3 = -0.5 * rho * (freestreamSpeed ** 2) * self.rocket.area * (dragCoeff)
# Off center moment
M1 += self.rocket.cpExcentricityY * R3
M2 -= self.rocket.cpExcentricityX * R3
# Get rocket velocity in body frame
vxB = a11 * vx + a21 * vy + a31 * vz
vyB = a12 * vx + a22 * vy + a32 * vz
vzB = a13 * vx + a23 * vy + a33 * vz
# Calculate lift and moment for each component of the rocket
for aerodynamicSurface in self.rocket.aerodynamicSurfaces:
compCp = aerodynamicSurface[0][2]
# Component absolute velocity in body frame
compVxB = vxB + compCp * omega2
compVyB = vyB - compCp * omega1
compVzB = vzB
# Wind velocity at component
compZ = z + compCp
compWindVx = self.env.windVelocityX.getValueOpt(compZ)
compWindVy = self.env.windVelocityY.getValueOpt(compZ)
# Component freestream velocity in body frame
compWindVxB = a11 * compWindVx + a21 * compWindVy
compWindVyB = a12 * compWindVx + a22 * compWindVy
compWindVzB = a13 * compWindVx + a23 * compWindVy
compStreamVxB = compWindVxB - compVxB
compStreamVyB = compWindVyB - compVyB
compStreamVzB = compWindVzB - compVzB
compStreamSpeed = (
compStreamVxB ** 2 + compStreamVyB ** 2 + compStreamVzB ** 2
) ** 0.5
# Component attack angle and lift force
compAttackAngle = 0
compLift, compLiftXB, compLiftYB = 0, 0, 0
if compStreamVxB ** 2 + compStreamVyB ** 2 != 0:
# Normalize component stream velocity in body frame
compStreamVzBn = compStreamVzB / compStreamSpeed
if -1 * compStreamVzBn < 1:
compAttackAngle = np.arccos(-compStreamVzBn)
cLift = abs(aerodynamicSurface[1](compAttackAngle))
# Component lift force magnitude
compLift = (
0.5 * rho * (compStreamSpeed ** 2) * self.rocket.area * cLift
)
# Component lift force components
liftDirNorm = (compStreamVxB ** 2 + compStreamVyB ** 2) ** 0.5
compLiftXB = compLift * (compStreamVxB / liftDirNorm)
compLiftYB = compLift * (compStreamVyB / liftDirNorm)
# Add to total lift force
R1 += compLiftXB
R2 += compLiftYB
# Add to total moment
M1 -= (compCp + a) * compLiftYB
M2 += (compCp + a) * compLiftXB
# Calculate derivatives
# Angular acceleration
alpha1 = (
M1
- (
omega2 * omega3 * (Rz + Tz - Ri - Ti - mu * b ** 2)
+ omega1
* (
(TiDot + MtDot * (Mr - 1) * (b / M) ** 2)
- MtDot * ((rN / 2) ** 2 + (c - b * mu / Mr) ** 2)
)
)
) / (Ri + Ti + mu * b ** 2)
alpha2 = (
M2
- (
omega1 * omega3 * (Ri + Ti + mu * b ** 2 - Rz - Tz)
+ omega2
* (
(TiDot + MtDot * (Mr - 1) * (b / M) ** 2)
- MtDot * ((rN / 2) ** 2 + (c - b * mu / Mr) ** 2)
)
)
) / (Ri + Ti + mu * b ** 2)
alpha3 = (M3 - omega3 * (TzDot - MtDot * (rN ** 2) / 2)) / (Rz + Tz)
# Euler parameters derivative
e0Dot = 0.5 * (-omega1 * e1 - omega2 * e2 - omega3 * e3)
e1Dot = 0.5 * (omega1 * e0 + omega3 * e2 - omega2 * e3)
e2Dot = 0.5 * (omega2 * e0 - omega3 * e1 + omega1 * e3)
e3Dot = 0.5 * (omega3 * e0 + omega2 * e1 - omega1 * e2)
# Linear acceleration
L = [
(R1 - b * Mt * (omega2 ** 2 + omega3 ** 2) - 2 * c * MtDot * omega2) / M,
(R2 + b * Mt * (alpha3 + omega1 * omega2) + 2 * c * MtDot * omega1) / M,
(R3 - b * Mt * (alpha2 - omega1 * omega3) + Thrust) / M,
]
ax, ay, az = np.dot(K, L)
az -= self.env.g # Include gravity
# Create uDot
uDot = [
vx,
vy,
vz,
ax,
ay,
az,
e0Dot,
e1Dot,
e2Dot,
e3Dot,
alpha1,
alpha2,
alpha3,
]
if postProcessing:
# Dynamics variables
self.R1.append([t, R1])
self.R2.append([t, R2])
self.R3.append([t, R3])
self.M1.append([t, M1])
self.M2.append([t, M2])
self.M3.append([t, M3])
# Atmospheric Conditions
self.windVelocityX.append([t, self.env.windVelocityX(z)])
self.windVelocityY.append([t, self.env.windVelocityY(z)])
self.density.append([t, self.env.density(z)])
self.dynamicViscosity.append([t, self.env.dynamicViscosity(z)])
self.pressure.append([t, self.env.pressure(z)])
self.speedOfSound.append([t, self.env.speedOfSound(z)])
return uDot
def uDotParachute(self, t, u, postProcessing=False):
"""Calculates derivative of u state vector with respect to time
when rocket is flying under parachute. A 3 DOF aproximation is
used.
Parameters
----------
t : float
Time in seconds
u : list
State vector defined by u = [x, y, z, vx, vy, vz, e0, e1,
e2, e3, omega1, omega2, omega3].
postProcessing : bool, optional
If True, adds flight data information directly to self
variables such as self.attackAngle. Default is False.
Return
------
uDot : list
State vector defined by uDot = [vx, vy, vz, ax, ay, az,
e0Dot, e1Dot, e2Dot, e3Dot, alpha1, alpha2, alpha3].
"""
# Parachute data
CdS = self.parachuteCdS
ka = 1
R = 1.5
rho = self.env.density.getValueOpt(u[2])
to = 1.2
ma = ka * rho * (4 / 3) * np.pi * R ** 3
mp = self.rocket.mass
eta = 1
Rdot = (6 * R * (1 - eta) / (1.2 ** 6)) * (
(1 - eta) * t ** 5 + eta * (to ** 3) * (t ** 2)
)
Rdot = 0
# Get relevant state data
x, y, z, vx, vy, vz, e0, e1, e2, e3, omega1, omega2, omega3 = u
# Get wind data
windVelocityX = self.env.windVelocityX.getValueOpt(z)
windVelocityY = self.env.windVelocityY.getValueOpt(z)
freestreamSpeed = (
(windVelocityX - vx) ** 2 + (windVelocityY - vy) ** 2 + (vz) ** 2
) ** 0.5
freestreamX = vx - windVelocityX
freestreamY = vy - windVelocityY
freestreamZ = vz
# Determine drag force
pseudoD = (
-0.5 * rho * CdS * freestreamSpeed - ka * rho * 4 * np.pi * (R ** 2) * Rdot
)
Dx = pseudoD * freestreamX
Dy = pseudoD * freestreamY
Dz = pseudoD * freestreamZ
ax = Dx / (mp + ma)
ay = Dy / (mp + ma)
az = (Dz - 9.8 * mp) / (mp + ma)
if postProcessing:
# Dynamics variables
self.R1.append([t, Dx])
self.R2.append([t, Dy])
self.R3.append([t, Dz])
self.M1.append([t, 0])
self.M2.append([t, 0])
self.M3.append([t, 0])
# Atmospheric Conditions
self.windVelocityX.append([t, self.env.windVelocityX(z)])
self.windVelocityY.append([t, self.env.windVelocityY(z)])
self.density.append([t, self.env.density(z)])
self.dynamicViscosity.append([t, self.env.dynamicViscosity(z)])
self.pressure.append([t, self.env.pressure(z)])
self.speedOfSound.append([t, self.env.speedOfSound(z)])
return [vx, vy, vz, ax, ay, az, 0, 0, 0, 0, 0, 0, 0]
def postProcess(self):
"""Post-process all Flight information produced during
simulation. Includes the calculation of maximum values,
calculation of secundary values such as energy and conversion
of lists to Function objects to facilitate plotting.
Parameters
----------
None
Return
------
None
"""
# Process first type of outputs - state vector
# Transform solution array into Functions
sol = np.array(self.solution)
self.x = Function(
sol[:, [0, 1]], "Time (s)", "X (m)", "spline", extrapolation="natural"
)
self.y = Function(
sol[:, [0, 2]], "Time (s)", "Y (m)", "spline", extrapolation="natural"
)
self.z = Function(
sol[:, [0, 3]], "Time (s)", "Z (m)", "spline", extrapolation="natural"
)
self.vx = Function(
sol[:, [0, 4]], "Time (s)", "Vx (m/s)", "spline", extrapolation="natural"
)
self.vy = Function(
sol[:, [0, 5]], "Time (s)", "Vy (m/s)", "spline", extrapolation="natural"
)
self.vz = Function(
sol[:, [0, 6]], "Time (s)", "Vz (m/s)", "spline", extrapolation="natural"
)
self.e0 = Function(
sol[:, [0, 7]], "Time (s)", "e0", "spline", extrapolation="natural"
)
self.e1 = Function(
sol[:, [0, 8]], "Time (s)", "e1", "spline", extrapolation="natural"
)
self.e2 = Function(
sol[:, [0, 9]], "Time (s)", "e2", "spline", extrapolation="natural"
)
self.e3 = Function(
sol[:, [0, 10]], "Time (s)", "e3", "spline", extrapolation="natural"
)
self.w1 = Function(
sol[:, [0, 11]], "Time (s)", "ω1 (rad/s)", "spline", extrapolation="natural"
)
self.w2 = Function(
sol[:, [0, 12]], "Time (s)", "ω2 (rad/s)", "spline", extrapolation="natural"
)
self.w3 = Function(
sol[:, [0, 13]], "Time (s)", "ω3 (rad/s)", "spline", extrapolation="natural"
)
# Process second type of outputs - accelerations
# Initialize acceleration arrays
self.ax, self.ay, self.az = [], [], []
self.alpha1, self.alpha2, self.alpha3 = [], [], []
# Go throught each time step and calculate accelerations
# Get flight phases
for phase_index, phase in self.timeIterator(self.flightPhases):
initTime = phase.t
finalTime = self.flightPhases[phase_index + 1].t
currentDerivative = phase.derivative
# Call callback functions
for callback in phase.callbacks:
callback(self)
# Loop through time steps in flight phase
for step in self.solution: # Can be optmized
if initTime < step[0] <= finalTime:
# Get derivatives
uDot = currentDerivative(step[0], step[1:])
# Get accelerations
ax, ay, az = uDot[3:6]
alpha1, alpha2, alpha3 = uDot[10:]
# Save accelerations
self.ax.append([step[0], ax])
self.ay.append([step[0], ay])
self.az.append([step[0], az])
self.alpha1.append([step[0], alpha1])
self.alpha2.append([step[0], alpha2])
self.alpha3.append([step[0], alpha3])
# Convert accelerations to functions
self.ax = Function(self.ax, "Time (s)", "Ax (m/s2)", "spline")
self.ay = Function(self.ay, "Time (s)", "Ay (m/s2)", "spline")
self.az = Function(self.az, "Time (s)", "Az (m/s2)", "spline")
self.alpha1 = Function(self.alpha1, "Time (s)", "α1 (rad/s2)", "spline")
self.alpha2 = Function(self.alpha2, "Time (s)", "α2 (rad/s2)", "spline")
self.alpha3 = Function(self.alpha3, "Time (s)", "α3 (rad/s2)", "spline")
# Process third type of outputs - temporary values calculated during integration
# Initialize force and atmospheric arrays
self.R1, self.R2, self.R3, self.M1, self.M2, self.M3 = [], [], [], [], [], []
self.pressure, self.density, self.dynamicViscosity, self.speedOfSound = (
[],
[],
[],
[],
)
self.windVelocityX, self.windVelocityY = [], []
# Go throught each time step and calculate forces and atmospheric values
# Get flight phases
for phase_index, phase in self.timeIterator(self.flightPhases):
initTime = phase.t
finalTime = self.flightPhases[phase_index + 1].t
currentDerivative = phase.derivative
# Call callback functions
for callback in phase.callbacks:
callback(self)
# Loop through time steps in flight phase
for step in self.solution: # Can be optmized
if initTime < step[0] <= finalTime or (initTime == 0 and step[0] == 0):
# Call derivatives in post processing mode
uDot = currentDerivative(step[0], step[1:], postProcessing=True)
# Convert forces and atmospheric arrays to functions
self.R1 = Function(self.R1, "Time (s)", "R1 (N)", "spline")
self.R2 = Function(self.R2, "Time (s)", "R2 (N)", "spline")
self.R3 = Function(self.R3, "Time (s)", "R3 (N)", "spline")
self.M1 = Function(self.M1, "Time (s)", "M1 (Nm)", "spline")
self.M2 = Function(self.M2, "Time (s)", "M2 (Nm)", "spline")
self.M3 = Function(self.M3, "Time (s)", "M3 (Nm)", "spline")
self.windVelocityX = Function(
self.windVelocityX, "Time (s)", "Wind Velocity X (East) (m/s)", "spline"
)
self.windVelocityY = Function(
self.windVelocityY, "Time (s)", "Wind Velocity Y (North) (m/s)", "spline"
)
self.density = Function(self.density, "Time (s)", "Density (kg/m³)", "spline")
self.pressure = Function(self.pressure, "Time (s)", "Pressure (Pa)", "spline")
self.dynamicViscosity = Function(
self.dynamicViscosity, "Time (s)", "Dynamic Viscosity (Pa s)", "spline"
)
self.speedOfSound = Function(
self.speedOfSound, "Time (s)", "Speed of Sound (m/s)", "spline"
)
# Process fourth type of output - values calculated from previous outputs
# Kinematics functions and values
# Velocity Magnitude
self.speed = (self.vx ** 2 + self.vy ** 2 + self.vz ** 2) ** 0.5
self.speed.setOutputs("Speed - Velocity Magnitude (m/s)")
maxSpeedTimeIndex = np.argmax(self.speed[:, 1])
self.maxSpeed = self.speed[maxSpeedTimeIndex, 1]
self.maxSpeedTime = self.speed[maxSpeedTimeIndex, 0]
# Acceleration
self.acceleration = (self.ax ** 2 + self.ay ** 2 + self.az ** 2) ** 0.5
self.acceleration.setOutputs("Acceleration Magnitude (m/s²)")
maxAccelerationTimeIndex = np.argmax(self.acceleration[:, 1])
self.maxAcceleration = self.acceleration[maxAccelerationTimeIndex, 1]
self.maxAccelerationTime = self.acceleration[maxAccelerationTimeIndex, 0]
# Path Angle
self.horizontalSpeed = (self.vx ** 2 + self.vy ** 2) ** 0.5
pathAngle = (180 / np.pi) * np.arctan2(
self.vz[:, 1], self.horizontalSpeed[:, 1]
)
pathAngle = np.column_stack([self.vz[:, 0], pathAngle])
self.pathAngle = Function(pathAngle, "Time (s)", "Path Angle (°)")
# Attitude Angle
self.attitudeVectorX = 2 * (self.e1 * self.e3 + self.e0 * self.e2) # a13
self.attitudeVectorY = 2 * (self.e2 * self.e3 - self.e0 * self.e1) # a23
self.attitudeVectorZ = 1 - 2 * (self.e1 ** 2 + self.e2 ** 2) # a33
horizontalAttitudeProj = (
self.attitudeVectorX ** 2 + self.attitudeVectorY ** 2
) ** 0.5
attitudeAngle = (180 / np.pi) * np.arctan2(
self.attitudeVectorZ[:, 1], horizontalAttitudeProj[:, 1]
)
attitudeAngle = np.column_stack([self.attitudeVectorZ[:, 0], attitudeAngle])
self.attitudeAngle = Function(attitudeAngle, "Time (s)", "Attitude Angle (°)")
# Lateral Attitude Angle
lateralVectorAngle = (np.pi / 180) * (self.heading - 90)
lateralVectorX = np.sin(lateralVectorAngle)
lateralVectorY = np.cos(lateralVectorAngle)
attitudeLateralProj = (
lateralVectorX * self.attitudeVectorX[:, 1]
+ lateralVectorY * self.attitudeVectorY[:, 1]
)
attitudeLateralProjX = attitudeLateralProj * lateralVectorX
attitudeLateralProjY = attitudeLateralProj * lateralVectorY
attiutdeLateralPlaneProjX = self.attitudeVectorX[:, 1] - attitudeLateralProjX
attiutdeLateralPlaneProjY = self.attitudeVectorY[:, 1] - attitudeLateralProjY
attiutdeLateralPlaneProjZ = self.attitudeVectorZ[:, 1]
attiutdeLateralPlaneProj = (
attiutdeLateralPlaneProjX ** 2
+ attiutdeLateralPlaneProjY ** 2
+ attiutdeLateralPlaneProjZ ** 2
) ** 0.5
lateralAttitudeAngle = (180 / np.pi) * np.arctan2(
attitudeLateralProj, attiutdeLateralPlaneProj
)
lateralAttitudeAngle = np.column_stack(
[self.attitudeVectorZ[:, 0], lateralAttitudeAngle]
)
self.lateralAttitudeAngle = Function(
lateralAttitudeAngle, "Time (s)", "Lateral Attitude Angle (°)"
)
# Euler Angles
psi = (180 / np.pi) * (
np.arctan2(self.e3[:, 1], self.e0[:, 1])
+ np.arctan2(-self.e2[:, 1], -self.e1[:, 1])
) # Precession angle
psi = np.column_stack([self.e1[:, 0], psi]) # Precession angle
self.psi = Function(psi, "Time (s)", "Precession Angle - ψ (°)")
phi = (180 / np.pi) * (
np.arctan2(self.e3[:, 1], self.e0[:, 1])
- np.arctan2(-self.e2[:, 1], -self.e1[:, 1])
) # Spin angle
phi = np.column_stack([self.e1[:, 0], phi]) # Spin angle
self.phi = Function(phi, "Time (s)", "Spin Angle - φ (°)")
theta = (
(180 / np.pi)
* 2
* np.arcsin(-((self.e1[:, 1] ** 2 + self.e2[:, 1] ** 2) ** 0.5))
) # Nutation angle
theta = np.column_stack([self.e1[:, 0], theta]) # Nutation angle
self.theta = Function(theta, "Time (s)", "Nutation Angle - θ (°)")
# Dynamics functions and variables
# Rail Button Forces
alpha = self.rocket.railButtons.angularPosition * (
np.pi / 180
) # Rail buttons angular position
D1 = self.rocket.railButtons.distanceToCM[
0
] # Distance from Rail Button 1 (upper) to CM
D2 = self.rocket.railButtons.distanceToCM[
1
] # Distance from Rail Button 2 (lower) to CM
F11 = (self.R1 * D2 - self.M2) / (
D1 + D2
) # Rail Button 1 force in the 1 direction
F12 = (self.R2 * D2 + self.M1) / (
D1 + D2
) # Rail Button 1 force in the 2 direction
F21 = (self.R1 * D1 + self.M2) / (
D1 + D2
) # Rail Button 2 force in the 1 direction
F22 = (self.R2 * D1 - self.M1) / (
D1 + D2
) # Rail Button 2 force in the 2 direction
outOfRailTimeIndex = np.searchsorted(
F11[:, 0], self.outOfRailTime
) # Find out of rail time index
# F11 = F11[:outOfRailTimeIndex + 1, :] # Limit force calculation to when rocket is in rail
# F12 = F12[:outOfRailTimeIndex + 1, :] # Limit force calculation to when rocket is in rail
# F21 = F21[:outOfRailTimeIndex + 1, :] # Limit force calculation to when rocket is in rail
# F22 = F22[:outOfRailTimeIndex + 1, :] # Limit force calculation to when rocket is in rail
self.railButton1NormalForce = F11 * np.cos(alpha) + F12 * np.sin(alpha)
self.railButton1NormalForce.setOutputs("Upper Rail Button Normal Force (N)")
self.railButton1ShearForce = F11 * -np.sin(alpha) + F12 * np.cos(alpha)
self.railButton1ShearForce.setOutputs("Upper Rail Button Shear Force (N)")
self.railButton2NormalForce = F21 * np.cos(alpha) + F22 * np.sin(alpha)
self.railButton2NormalForce.setOutputs("Lower Rail Button Normal Force (N)")
self.railButton2ShearForce = F21 * -np.sin(alpha) + F22 * np.cos(alpha)
self.railButton2ShearForce.setOutputs("Lower Rail Button Shear Force (N)")
# Rail Button Maximum Forces
if outOfRailTimeIndex == 0:
self.maxRailButton1NormalForce = 0
self.maxRailButton1ShearForce = 0
self.maxRailButton2NormalForce = 0
self.maxRailButton2ShearForce = 0
else:
self.maxRailButton1NormalForce = np.amax(
self.railButton1NormalForce[:outOfRailTimeIndex]
)
self.maxRailButton1ShearForce = np.amax(
self.railButton1ShearForce[:outOfRailTimeIndex]
)
self.maxRailButton2NormalForce = np.amax(
self.railButton2NormalForce[:outOfRailTimeIndex]
)
self.maxRailButton2ShearForce = np.amax(
self.railButton2ShearForce[:outOfRailTimeIndex]
)
# Aerodynamic Lift and Drag
self.aerodynamicLift = (self.R1 ** 2 + self.R2 ** 2) ** 0.5
self.aerodynamicLift.setOutputs("Aerodynamic Lift Force (N)")
self.aerodynamicDrag = -1 * self.R3
self.aerodynamicDrag.setOutputs("Aerodynamic Drag Force (N)")
self.aerodynamicBendingMoment = (self.M1 ** 2 + self.M2 ** 2) ** 0.5
self.aerodynamicBendingMoment.setOutputs("Aerodynamic Bending Moment (N m)")
self.aerodynamicSpinMoment = self.M3
self.aerodynamicSpinMoment.setOutputs("Aerodynamic Spin Moment (N m)")
# Energy
b = -self.rocket.distanceRocketPropellant
totalMass = self.rocket.totalMass
mu = self.rocket.reducedMass
Rz = self.rocket.inertiaZ
Ri = self.rocket.inertiaI
Tz = self.rocket.motor.inertiaZ
Ti = self.rocket.motor.inertiaI
I1, I2, I3 = (Ri + Ti + mu * b ** 2), (Ri + Ti + mu * b ** 2), (Rz + Tz)
# Redefine I1, I2 and I3 grid
grid = self.vx[:, 0]
I1 = Function(np.column_stack([grid, I1(grid)]), "Time (s)")
I2 = Function(np.column_stack([grid, I2(grid)]), "Time (s)")
I3 = Function(np.column_stack([grid, I3(grid)]), "Time (s)")
# Redefine total mass grid
totalMass = Function(np.column_stack([grid, totalMass(grid)]), "Time (s)")
# Redefine thrust grid
thrust = Function(
np.column_stack([grid, self.rocket.motor.thrust(grid)]), "Time (s)"
)
# Get some nicknames
vx, vy, vz = self.vx, self.vy, self.vz
w1, w2, w3 = self.w1, self.w2, self.w3
# Kinetic Energy
self.rotationalEnergy = 0.5 * (I1 * w1 ** 2 + I2 * w2 ** 2 + I3 * w3 ** 2)
self.rotationalEnergy.setOutputs("Rotational Kinetic Energy (J)")
self.translationalEnergy = 0.5 * totalMass * (vx ** 2 + vy ** 2 + vz ** 2)
self.translationalEnergy.setOutputs("Translational Kinetic Energy (J)")
self.kineticEnergy = self.rotationalEnergy + self.translationalEnergy
self.kineticEnergy.setOutputs("Kinetic Energy (J)")
# Potential Energy
self.potentialEnergy = totalMass * self.env.g * self.z
self.potentialEnergy.setInputs("Time (s)")
# Total Mechanical Energy
self.totalEnergy = self.kineticEnergy + self.potentialEnergy
self.totalEnergy.setOutputs("Total Mechanical Energy (J)")
# Thrust Power
self.thrustPower = thrust * self.speed
self.thrustPower.setOutputs("Thrust Power (W)")
# Drag Power
self.dragPower = self.R3 * self.speed
self.dragPower.setOutputs("Drag Power (W)")
# Stability and Control variables
# Angular velocities frequency response - Fourier Analysis
# Omega 1 - w1
Fs = 100.0
# sampling rate
Ts = 1.0 / Fs
# sampling interval
t = np.arange(1, self.tFinal, Ts) # time vector
y = self.w1(t)
y -= np.mean(y)
n = len(y) # length of the signal
k = np.arange(n)
T = n / Fs
frq = k / T # two sides frequency range
frq = frq[range(n // 2)] # one side frequency range
Y = np.fft.fft(y) / n # fft computing and normalization
Y = Y[range(n // 2)]
omega1FrequencyResponse = np.column_stack([frq, abs(Y)])
self.omega1FrequencyResponse = Function(
omega1FrequencyResponse, "Frequency (Hz)", "Omega 1 Angle Fourier Amplitude"
)
# Omega 2 - w2
Fs = 100.0
# sampling rate
Ts = 1.0 / Fs
# sampling interval
t = np.arange(1, self.tFinal, Ts) # time vector
y = self.w2(t)
y -= np.mean(y)
n = len(y) # length of the signal
k = np.arange(n)
T = n / Fs
frq = k / T # two sides frequency range
frq = frq[range(n // 2)] # one side frequency range
Y = np.fft.fft(y) / n # fft computing and normalization
Y = Y[range(n // 2)]
omega2FrequencyResponse = np.column_stack([frq, abs(Y)])
self.omega2FrequencyResponse = Function(
omega2FrequencyResponse, "Frequency (Hz)", "Omega 2 Angle Fourier Amplitude"
)
# Omega 3 - w3
Fs = 100.0
# sampling rate
Ts = 1.0 / Fs
# sampling interval
t = np.arange(1, self.tFinal, Ts) # time vector
y = self.w3(t)
y -= np.mean(y)
n = len(y) # length of the signal
k = np.arange(n)
T = n / Fs
frq = k / T # two sides frequency range
frq = frq[range(n // 2)] # one side frequency range
Y = np.fft.fft(y) / n # fft computing and normalization
Y = Y[range(n // 2)]
omega3FrequencyResponse = np.column_stack([frq, abs(Y)])
self.omega3FrequencyResponse = Function(
omega3FrequencyResponse, "Frequency (Hz)", "Omega 3 Angle Fourier Amplitude"
)
# Attitude Frequency Response
Fs = 100.0
# sampling rate
Ts = 1.0 / Fs
# sampling interval
t = np.arange(1, self.tFinal, Ts) # time vector
y = self.attitudeAngle(t)
y -= np.mean(y)
n = len(y) # length of the signal
k = np.arange(n)
T = n / Fs
frq = k / T # two sides frequency range
frq = frq[range(n // 2)] # one side frequency range
Y = np.fft.fft(y) / n # fft computing and normalization
Y = Y[range(n // 2)]
attitudeFrequencyResponse = np.column_stack([frq, abs(Y)])
self.attitudeFrequencyResponse = Function(
attitudeFrequencyResponse,
"Frequency (Hz)",
"Attitude Angle Fourier Amplitude",
)
# Static Margin
self.staticMargin = self.rocket.staticMargin
# Fluid Mechanics variables
# Freestream Velocity
self.streamVelocityX = self.windVelocityX - self.vx
self.streamVelocityX.setOutputs("Freestream Velocity X (m/s)")
self.streamVelocityY = self.windVelocityY - self.vy
self.streamVelocityY.setOutputs("Freestream Velocity Y (m/s)")
self.streamVelocityZ = -1 * self.vz
self.streamVelocityZ.setOutputs("Freestream Velocity Z (m/s)")
self.freestreamSpeed = (
self.streamVelocityX ** 2
+ self.streamVelocityY ** 2
+ self.streamVelocityZ ** 2
) ** 0.5
self.freestreamSpeed.setOutputs("Freestream Speed (m/s)")
# Apogee Freestream speed
self.apogeeFreestreamSpeed = self.freestreamSpeed(self.apogeeTime)
# Mach Number
self.MachNumber = self.freestreamSpeed / self.speedOfSound
self.MachNumber.setOutputs("Mach Number")
maxMachNumberTimeIndex = np.argmax(self.MachNumber[:, 1])
self.maxMachNumberTime = self.MachNumber[maxMachNumberTimeIndex, 0]
self.maxMachNumber = self.MachNumber[maxMachNumberTimeIndex, 1]
# Reynolds Number
self.ReynoldsNumber = (
self.density * self.freestreamSpeed / self.dynamicViscosity
) * (2 * self.rocket.radius)
self.ReynoldsNumber.setOutputs("Reynolds Number")
maxReynoldsNumberTimeIndex = np.argmax(self.ReynoldsNumber[:, 1])
self.maxReynoldsNumberTime = self.ReynoldsNumber[maxReynoldsNumberTimeIndex, 0]
self.maxReynoldsNumber = self.ReynoldsNumber[maxReynoldsNumberTimeIndex, 1]
# Dynamic Pressure
self.dynamicPressure = 0.5 * self.density * self.freestreamSpeed ** 2
self.dynamicPressure.setOutputs("Dynamic Pressure (Pa)")
maxDynamicPressureTimeIndex = np.argmax(self.dynamicPressure[:, 1])
self.maxDynamicPressureTime = self.dynamicPressure[
maxDynamicPressureTimeIndex, 0
]
self.maxDynamicPressure = self.dynamicPressure[maxDynamicPressureTimeIndex, 1]
# Total Pressure
self.totalPressure = self.pressure * (1 + 0.2 * self.MachNumber ** 2) ** (3.5)
self.totalPressure.setOutputs("Total Pressure (Pa)")
maxtotalPressureTimeIndex = np.argmax(self.totalPressure[:, 1])
self.maxtotalPressureTime = self.totalPressure[maxtotalPressureTimeIndex, 0]
self.maxtotalPressure = self.totalPressure[maxDynamicPressureTimeIndex, 1]
# Angle of Attack
angleOfAttack = []
for i in range(len(self.attitudeVectorX[:, 1])):
dotProduct = -(
self.attitudeVectorX[i, 1] * self.streamVelocityX[i, 1]
+ self.attitudeVectorY[i, 1] * self.streamVelocityY[i, 1]
+ self.attitudeVectorZ[i, 1] * self.streamVelocityZ[i, 1]
)
if self.freestreamSpeed[i, 1] < 1e-6:
angleOfAttack.append([self.freestreamSpeed[i, 0], 0])
else:
dotProductNormalized = dotProduct / self.freestreamSpeed[i, 1]
dotProductNormalized = (
1 if dotProductNormalized > 1 else dotProductNormalized
)
dotProductNormalized = (
-1 if dotProductNormalized < -1 else dotProductNormalized
)
angleOfAttack.append(
[
self.freestreamSpeed[i, 0],
(180 / np.pi) * np.arccos(dotProductNormalized),
]
)
self.angleOfAttack = Function(
angleOfAttack, "Time (s)", "Angle Of Attack (°)", "linear"
)
# Post process other quantities
# Transform parachute sensor feed into functions
for parachute in self.rocket.parachutes:
parachute.cleanPressureSignalFunction = Function(
parachute.cleanPressureSignal,
"Time (s)",
"Pressure - Without Noise (Pa)",
"linear",
)
parachute.noisyPressureSignalFunction = Function(
parachute.noisyPressureSignal,
"Time (s)",
"Pressure - With Noise (Pa)",
"linear",
)
parachute.noiseSignalFunction = Function(
parachute.noiseSignal, "Time (s)", "Pressure Noise (Pa)", "linear"
)
# Register post processing
self.postProcessed = True
return None
def info(self):
"""Prints out a summary of the data available about the Flight.
Parameters
----------
None
Return
------
None
"""
# Post-process results
if self.postProcessed is False:
self.postProcess()
# Get index of out of rail time
outOfRailTimeIndexs = np.nonzero(self.x[:, 0] == self.outOfRailTime)
outOfRailTimeIndex = (
-1 if len(outOfRailTimeIndexs) == 0 else outOfRailTimeIndexs[0][0]
)
# Get index of time before parachute event
if len(self.parachuteEvents) > 0:
eventTime = self.parachuteEvents[0][0] + self.parachuteEvents[0][1].lag
eventTimeIndex = np.nonzero(self.x[:, 0] == eventTime)[0][0]
else:
eventTime = self.tFinal
eventTimeIndex = -1
# Print surface wind conditions
print("Surface Wind Conditions\n")
print("Frontal Surface Wind Speed: {:.2f} m/s".format(self.frontalSurfaceWind))
print("Lateral Surface Wind Speed: {:.2f} m/s".format(self.lateralSurfaceWind))
# Print out of rail conditions
print("\n\n Rail Departure State\n")
print("Rail Departure Time: {:.3f} s".format(self.outOfRailTime))
print("Rail Departure Velocity: {:.3f} m/s".format(self.outOfRailVelocity))
print(
"Rail Departure Static Margin: {:.3f} c".format(
self.staticMargin(self.outOfRailTime)
)
)
print(
"Rail Departure Angle of Attack: {:.3f}°".format(
self.angleOfAttack(self.outOfRailTime)
)
)
print(
"Rail Departure Thrust-Weight Ratio: {:.3f}".format(
self.rocket.thrustToWeight(self.outOfRailTime)
)
)
print(
"Rail Departure Reynolds Number: {:.3e}".format(
self.ReynoldsNumber(self.outOfRailTime)
)
)
# Print burnOut conditions
print("\n\nBurnOut State\n")
print("BurnOut time: {:.3f} s".format(self.rocket.motor.burnOutTime))
print(
"Altitude at burnOut: {:.3f} m (AGL)".format(
self.z(self.rocket.motor.burnOutTime) - self.env.elevation
)
)
print(
"Rocket velocity at burnOut: {:.3f} m/s".format(
self.speed(self.rocket.motor.burnOutTime)
)
)
print(
"Freestream velocity at burnOut: {:.3f} m/s".format(
(
self.streamVelocityX(self.rocket.motor.burnOutTime) ** 2
+ self.streamVelocityY(self.rocket.motor.burnOutTime) ** 2
+ self.streamVelocityZ(self.rocket.motor.burnOutTime) ** 2
)
** 0.5
)
)
print(
"Mach Number at burnOut: {:.3f}".format(
self.MachNumber(self.rocket.motor.burnOutTime)
)
)
print(
"Kinetic energy at burnOut: {:.3e} J".format(
self.kineticEnergy(self.rocket.motor.burnOutTime)
)
)
# Print apogee conditions
print("\n\nApogee\n")
print(
"Apogee Altitude: {:.3f} m (ASL) | {:.3f} m (AGL)".format(
self.apogee, self.apogee - self.env.elevation
)
)
print("Apogee Time: {:.3f} s".format(self.apogeeTime))
print("Apogee Freestream Speed: {:.3f} m/s".format(self.apogeeFreestreamSpeed))
# Print events registered
print("\n\nEvents\n")
if len(self.parachuteEvents) == 0:
print("No Parachute Events Were Triggered.")
for event in self.parachuteEvents:
triggerTime = event[0]
parachute = event[1]
openTime = triggerTime + parachute.lag
velocity = self.freestreamSpeed(openTime)
altitude = self.z(openTime)
name = parachute.name.title()
print(name + " Ejection Triggered at: {:.3f} s".format(triggerTime))
print(name + " Parachute Inflated at: {:.3f} s".format(openTime))
print(
name
+ " Parachute Inflated with Freestream Speed of: {:.3f} m/s".format(
velocity
)
)
print(
name
+ " Parachute Inflated at Height of: {:.3f} m (AGL)".format(
altitude - self.env.elevation
)
)
# Print impact conditions
if len(self.impactState) != 0:
print("\n\nImpact\n")
print("X Impact: {:.3f} m".format(self.xImpact))
print("Y Impact: {:.3f} m".format(self.yImpact))
print("Time of Impact: {:.3f} s".format(self.tFinal))
print("Velocity at Impact: {:.3f} m/s".format(self.impactVelocity))
elif self.terminateOnApogee is False:
print("\n\nEnd of Simulation\n")
print("Time: {:.3f} s".format(self.solution[-1][0]))
print("Altitude: {:.3f} m".format(self.solution[-1][3]))
# Print maximum values
print("\n\nMaximum Values\n")
print(
"Maximum Speed: {:.3f} m/s at {:.2f} s".format(
self.maxSpeed, self.maxSpeedTime
)
)
print(
"Maximum Mach Number: {:.3f} Mach at {:.2f} s".format(
self.maxMachNumber, self.maxMachNumberTime
)
)
print(
"Maximum Reynolds Number: {:.3e} at {:.2f} s".format(
self.maxReynoldsNumber, self.maxReynoldsNumberTime
)
)
print(
"Maximum Dynamic Pressure: {:.3e} Pa at {:.2f} s".format(
self.maxDynamicPressure, self.maxDynamicPressureTime
)
)
print(
"Maximum Acceleration: {:.3f} m/s² at {:.2f} s".format(
self.maxAcceleration, self.maxAccelerationTime
)
)
print(
"Maximum Gs: {:.3f} g at {:.2f} s".format(
self.maxAcceleration / self.env.g, self.maxAccelerationTime
)
)
print(
"Maximum Upper Rail Button Normal Force: {:.3f} N".format(
self.maxRailButton1NormalForce
)
)
print(
"Maximum Upper Rail Button Shear Force: {:.3f} N".format(
self.maxRailButton1ShearForce
)
)
print(
"Maximum Lower Rail Button Normal Force: {:.3f} N".format(
self.maxRailButton2NormalForce
)
)
print(
"Maximum Lower Rail Button Shear Force: {:.3f} N".format(
self.maxRailButton2ShearForce
)
)
return None
def printInitialConditionsData(self):
"""Prints all initial conditions data available about the flight
Parameters
----------
None
Return
------
None
"""
# Post-process results
if self.postProcessed is False:
self.postProcess()
print(
"Position - x: {:.2f} m | y: {:.2f} m | z: {:.2f} m".format(
self.x(0), self.y(0), self.z(0)
)
)
print(
"Velocity - Vx: {:.2f} m/s | Vy: {:.2f} m/s | Vz: {:.2f} m/s".format(
self.vx(0), self.vy(0), self.vz(0)
)
)
print(
"Attitude - e0: {:.3f} | e1: {:.3f} | e2: {:.3f} | e3: {:.3f}".format(
self.e0(0), self.e1(0), self.e2(0), self.e3(0)
)
)
print(
"Euler Angles - Spin φ : {:.2f}° | Nutation θ: {:.2f}° | Precession ψ: {:.2f}°".format(
self.phi(0), self.theta(0), self.psi(0)
)
)
print(
"Angular Velocity - ω1: {:.2f} rad/s | ω2: {:.2f} rad/s| ω3: {:.2f} rad/s".format(
self.w1(0), self.w2(0), self.w3(0)
)
)
return None
def printNumericalIntegrationSettings(self):
"""Prints out the Numerical Integration settings
Parameters
----------
None
Return
------
None
"""
print("Maximum Allowed Flight Time: {:f} s".format(self.maxTime))
print("Maximum Allowed Time Step: {:f} s".format(self.maxTimeStep))
print("Minimum Allowed Time Step: {:e} s".format(self.minTimeStep))
print("Relative Error Tolerance: ", self.rtol)
print("Absolute Error Tolerance: ", self.atol)
print("Allow Event Overshoot: ", self.timeOvershoot)
print("Terminate Simulation on Apogee: ", self.terminateOnApogee)
print("Number of Time Steps Used: ", len(self.timeSteps))
print(
"Number of Derivative Functions Evaluation: ",
sum(self.functionEvaluationsPerTimeStep),
)
print(
"Average Function Evaluations per Time Step: {:3f}".format(
sum(self.functionEvaluationsPerTimeStep) / len(self.timeSteps)
)
)
return None
def calculateStallWindVelocity(self, stallAngle):
"""Function to calculate the maximum wind velocity before the angle of
attack exceeds a desired angle, at the instant of departing rail launch.
Can be helpful if you know the exact stall angle of all aerodynamics
surfaces.
Parameters
----------
stallAngle : float
Angle, in degrees, for which you would like to know the maximum wind
speed before the angle of attack exceeds it
Return
------
None
"""
vF = self.outOfRailVelocity
# Convert angle to radians
tetha = self.inclination * np.pi / 180
stallAngle = stallAngle * np.pi / 180
c = (math.cos(stallAngle) ** 2 - math.cos(tetha) ** 2) / math.sin(
stallAngle
) ** 2
wV = (
2 * vF * math.cos(tetha) / c
+ (
4 * vF * vF * math.cos(tetha) * math.cos(tetha) / (c ** 2)
+ 4 * 1 * vF * vF / c
)
** 0.5
) / 2
# Convert stallAngle to degrees
stallAngle = stallAngle * 180 / np.pi
print(
"Maximum wind velocity at Rail Departure time before angle of attack exceeds {:.3f}°: {:.3f} m/s".format(
stallAngle, wV
)
)
return None
def plot3dTrajectory(self):
"""Plot a 3D graph of the trajectory
Parameters
----------
None
Return
------
None
"""
# Post-process results
if self.postProcessed is False:
self.postProcess()
# Get max and min x and y
maxZ = max(self.z[:, 1] - self.env.elevation)
maxX = max(self.x[:, 1])
minX = min(self.x[:, 1])
maxY = max(self.y[:, 1])
minY = min(self.y[:, 1])
maxXY = max(maxX, maxY)
minXY = min(minX, minY)
# Create figure
fig1 = plt.figure(figsize=(9, 9))
ax1 = plt.subplot(111, projection="3d")
ax1.plot(self.x[:, 1], self.y[:, 1], zs=0, zdir="z", linestyle="--")
ax1.plot(
self.x[:, 1],
self.z[:, 1] - self.env.elevation,
zs=minXY,
zdir="y",
linestyle="--",
)
ax1.plot(
self.y[:, 1],
self.z[:, 1] - self.env.elevation,
zs=minXY,
zdir="x",
linestyle="--",
)
ax1.plot(
self.x[:, 1], self.y[:, 1], self.z[:, 1] - self.env.elevation, linewidth="2"
)
ax1.scatter(0, 0, 0)
ax1.set_xlabel("X - East (m)")
ax1.set_ylabel("Y - North (m)")
ax1.set_zlabel("Z - Altitude Above Ground Level (m)")
ax1.set_title("Flight Trajectory")
ax1.set_zlim3d([0, maxZ])
ax1.set_ylim3d([minXY, maxXY])
ax1.set_xlim3d([minXY, maxXY])
ax1.view_init(15, 45)
plt.show()
return None
def plotLinearKinematicsData(self):
"""Prints out all Kinematics graphs available about the Flight
Parameters
----------
None
Return
------
None
"""
# Post-process results
if self.postProcessed is False:
self.postProcess()
# Velocity and acceleration plots
fig2 = plt.figure(figsize=(9, 12))
ax1 = plt.subplot(414)
ax1.plot(self.vx[:, 0], self.vx[:, 1], color="#ff7f0e")
ax1.set_xlim(0, self.tFinal)
ax1.set_title("Velocity X | Acceleration X")
ax1.set_xlabel("Time (s)")
ax1.set_ylabel("Velocity X (m/s)", color="#ff7f0e")
ax1.tick_params("y", colors="#ff7f0e")
ax1.grid(True)
ax1up = ax1.twinx()
ax1up.plot(self.ax[:, 0], self.ax[:, 1], color="#1f77b4")
ax1up.set_ylabel("Acceleration X (m/s²)", color="#1f77b4")
ax1up.tick_params("y", colors="#1f77b4")
ax2 = plt.subplot(413)
ax2.plot(self.vy[:, 0], self.vy[:, 1], color="#ff7f0e")
ax2.set_xlim(0, self.tFinal)
ax2.set_title("Velocity Y | Acceleration Y")
ax2.set_xlabel("Time (s)")
ax2.set_ylabel("Velocity Y (m/s)", color="#ff7f0e")
ax2.tick_params("y", colors="#ff7f0e")
ax2.grid(True)
ax2up = ax2.twinx()
ax2up.plot(self.ay[:, 0], self.ay[:, 1], color="#1f77b4")
ax2up.set_ylabel("Acceleration Y (m/s²)", color="#1f77b4")
ax2up.tick_params("y", colors="#1f77b4")
ax3 = plt.subplot(412)
ax3.plot(self.vz[:, 0], self.vz[:, 1], color="#ff7f0e")
ax3.set_xlim(0, self.tFinal)
ax3.set_title("Velocity Z | Acceleration Z")
ax3.set_xlabel("Time (s)")
ax3.set_ylabel("Velocity Z (m/s)", color="#ff7f0e")
ax3.tick_params("y", colors="#ff7f0e")
ax3.grid(True)
ax3up = ax3.twinx()
ax3up.plot(self.az[:, 0], self.az[:, 1], color="#1f77b4")
ax3up.set_ylabel("Acceleration Z (m/s²)", color="#1f77b4")
ax3up.tick_params("y", colors="#1f77b4")
ax4 = plt.subplot(411)
ax4.plot(self.speed[:, 0], self.speed[:, 1], color="#ff7f0e")
ax4.set_xlim(0, self.tFinal)
ax4.set_title("Velocity Magnitude | Acceleration Magnitude")
ax4.set_xlabel("Time (s)")
ax4.set_ylabel("Velocity (m/s)", color="#ff7f0e")
ax4.tick_params("y", colors="#ff7f0e")
ax4.grid(True)
ax4up = ax4.twinx()
ax4up.plot(self.acceleration[:, 0], self.acceleration[:, 1], color="#1f77b4")
ax4up.set_ylabel("Acceleration (m/s²)", color="#1f77b4")
ax4up.tick_params("y", colors="#1f77b4")
plt.subplots_adjust(hspace=0.5)
plt.show()
return None
def plotAttitudeData(self):
"""Prints out all Angular position graphs available about the Flight
Parameters
----------
None
Return
------
None
"""
# Post-process results
if self.postProcessed is False:
self.postProcess()
# Get index of time before parachute event
if len(self.parachuteEvents) > 0:
eventTime = self.parachuteEvents[0][0] + self.parachuteEvents[0][1].lag
eventTimeIndex = np.nonzero(self.x[:, 0] == eventTime)[0][0]
else:
eventTime = self.tFinal
eventTimeIndex = -1
# Angular position plots
fig3 = plt.figure(figsize=(9, 12))
ax1 = plt.subplot(411)
ax1.plot(self.e0[:, 0], self.e0[:, 1], label="$e_0$")
ax1.plot(self.e1[:, 0], self.e1[:, 1], label="$e_1$")
ax1.plot(self.e2[:, 0], self.e2[:, 1], label="$e_2$")
ax1.plot(self.e3[:, 0], self.e3[:, 1], label="$e_3$")
ax1.set_xlim(0, eventTime)
ax1.set_xlabel("Time (s)")
ax1.set_ylabel("Euler Parameters")
ax1.set_title("Euler Parameters")
ax1.legend()
ax1.grid(True)
ax2 = plt.subplot(412)
ax2.plot(self.psi[:, 0], self.psi[:, 1])
ax2.set_xlim(0, eventTime)
ax2.set_xlabel("Time (s)")
ax2.set_ylabel("ψ (°)")
ax2.set_title("Euler Precession Angle")
ax2.grid(True)
ax3 = plt.subplot(413)
ax3.plot(self.theta[:, 0], self.theta[:, 1], label="θ - Nutation")
ax3.set_xlim(0, eventTime)
ax3.set_xlabel("Time (s)")
ax3.set_ylabel("θ (°)")
ax3.set_title("Euler Nutation Angle")
ax3.grid(True)
ax4 = plt.subplot(414)
ax4.plot(self.phi[:, 0], self.phi[:, 1], label="φ - Spin")
ax4.set_xlim(0, eventTime)
ax4.set_xlabel("Time (s)")
ax4.set_ylabel("φ (°)")
ax4.set_title("Euler Spin Angle")
ax4.grid(True)
plt.subplots_adjust(hspace=0.5)
plt.show()
return None
def plotFlightPathAngleData(self):
"""Prints out Flight path and Rocket Attitude angle graphs available
about the Flight
Parameters
----------
None
Return
------
None
"""
# Post-process results
if self.postProcessed is False:
self.postProcess()
# Get index of time before parachute event
if len(self.parachuteEvents) > 0:
eventTime = self.parachuteEvents[0][0] + self.parachuteEvents[0][1].lag
eventTimeIndex = np.nonzero(self.x[:, 0] == eventTime)[0][0]
else:
eventTime = self.tFinal
eventTimeIndex = -1
# Path, Attitude and Lateral Attitude Angle
# Angular position plots
fig5 = plt.figure(figsize=(9, 6))
ax1 = plt.subplot(211)
ax1.plot(self.pathAngle[:, 0], self.pathAngle[:, 1], label="Flight Path Angle")
ax1.plot(
self.attitudeAngle[:, 0],
self.attitudeAngle[:, 1],
label="Rocket Attitude Angle",
)
ax1.set_xlim(0, eventTime)
ax1.legend()
ax1.grid(True)
ax1.set_xlabel("Time (s)")
ax1.set_ylabel("Angle (°)")
ax1.set_title("Flight Path and Attitude Angle")
ax2 = plt.subplot(212)
ax2.plot(self.lateralAttitudeAngle[:, 0], self.lateralAttitudeAngle[:, 1])
ax2.set_xlim(0, eventTime)
ax2.set_xlabel("Time (s)")
ax2.set_ylabel("Lateral Attitude Angle (°)")
ax2.set_title("Lateral Attitude Angle")
ax2.grid(True)
plt.subplots_adjust(hspace=0.5)
plt.show()
return None
def plotAngularKinematicsData(self):
"""Prints out all Angular velocity and acceleration graphs available
about the Flight
Parameters
----------
None
Return
------
None
"""
# Post-process results
if self.postProcessed is False:
self.postProcess()
# Get index of time before parachute event
if len(self.parachuteEvents) > 0:
eventTime = self.parachuteEvents[0][0] + self.parachuteEvents[0][1].lag
eventTimeIndex = np.nonzero(self.x[:, 0] == eventTime)[0][0]
else:
eventTime = self.tFinal
eventTimeIndex = -1
# Angular velocity and acceleration plots
fig4 = plt.figure(figsize=(9, 9))
ax1 = plt.subplot(311)
ax1.plot(self.w1[:, 0], self.w1[:, 1], color="#ff7f0e")
ax1.set_xlim(0, eventTime)
ax1.set_xlabel("Time (s)")
ax1.set_ylabel("Angular Velocity - ${\omega_1}$ (rad/s)", color="#ff7f0e")
ax1.set_title(
"Angular Velocity ${\omega_1}$ | Angular Acceleration ${\\alpha_1}$"
)
ax1.tick_params("y", colors="#ff7f0e")
ax1.grid(True)
ax1up = ax1.twinx()
ax1up.plot(self.alpha1[:, 0], self.alpha1[:, 1], color="#1f77b4")
ax1up.set_ylabel(
"Angular Acceleration - ${\\alpha_1}$ (rad/s²)", color="#1f77b4"
)
ax1up.tick_params("y", colors="#1f77b4")
ax2 = plt.subplot(312)
ax2.plot(self.w2[:, 0], self.w2[:, 1], color="#ff7f0e")
ax2.set_xlim(0, eventTime)
ax2.set_xlabel("Time (s)")
ax2.set_ylabel("Angular Velocity - ${\omega_2}$ (rad/s)", color="#ff7f0e")
ax2.set_title(
"Angular Velocity ${\omega_2}$ | Angular Acceleration ${\\alpha_2}$"
)
ax2.tick_params("y", colors="#ff7f0e")
ax2.grid(True)
ax2up = ax2.twinx()
ax2up.plot(self.alpha2[:, 0], self.alpha2[:, 1], color="#1f77b4")
ax2up.set_ylabel(
"Angular Acceleration - ${\\alpha_2}$ (rad/s²)", color="#1f77b4"
)
ax2up.tick_params("y", colors="#1f77b4")
ax3 = plt.subplot(313)
ax3.plot(self.w3[:, 0], self.w3[:, 1], color="#ff7f0e")
ax3.set_xlim(0, eventTime)
ax3.set_xlabel("Time (s)")
ax3.set_ylabel("Angular Velocity - ${\omega_3}$ (rad/s)", color="#ff7f0e")
ax3.set_title(
"Angular Velocity ${\omega_3}$ | Angular Acceleration ${\\alpha_3}$"
)
ax3.tick_params("y", colors="#ff7f0e")
ax3.grid(True)
ax3up = ax3.twinx()
ax3up.plot(self.alpha3[:, 0], self.alpha3[:, 1], color="#1f77b4")
ax3up.set_ylabel(
"Angular Acceleration - ${\\alpha_3}$ (rad/s²)", color="#1f77b4"
)
ax3up.tick_params("y", colors="#1f77b4")
plt.subplots_adjust(hspace=0.5)
plt.show()
return None
def plotTrajectoryForceData(self):
"""Prints out all Forces and Moments graphs available about the Flight
Parameters
----------
None
Return
------
None
"""
# Post-process results
if self.postProcessed is False:
self.postProcess()
# Get index of out of rail time
outOfRailTimeIndexs = np.nonzero(self.x[:, 0] == self.outOfRailTime)
outOfRailTimeIndex = (
-1 if len(outOfRailTimeIndexs) == 0 else outOfRailTimeIndexs[0][0]
)
# Get index of time before parachute event
if len(self.parachuteEvents) > 0:
eventTime = self.parachuteEvents[0][0] + self.parachuteEvents[0][1].lag
eventTimeIndex = np.nonzero(self.x[:, 0] == eventTime)[0][0]
else:
eventTime = self.tFinal
eventTimeIndex = -1
# Rail Button Forces
fig6 = plt.figure(figsize=(9, 6))
ax1 = plt.subplot(211)
ax1.plot(
self.railButton1NormalForce[:outOfRailTimeIndex, 0],
self.railButton1NormalForce[:outOfRailTimeIndex, 1],
label="Upper Rail Button",
)
ax1.plot(
self.railButton2NormalForce[:outOfRailTimeIndex, 0],
self.railButton2NormalForce[:outOfRailTimeIndex, 1],
label="Lower Rail Button",
)
ax1.set_xlim(0, self.outOfRailTime if self.outOfRailTime > 0 else self.tFinal)
ax1.legend()
ax1.grid(True)
ax1.set_xlabel("Time (s)")
ax1.set_ylabel("Normal Force (N)")
ax1.set_title("Rail Buttons Normal Force")
ax2 = plt.subplot(212)
ax2.plot(
self.railButton1ShearForce[:outOfRailTimeIndex, 0],
self.railButton1ShearForce[:outOfRailTimeIndex, 1],
label="Upper Rail Button",
)
ax2.plot(
self.railButton2ShearForce[:outOfRailTimeIndex, 0],
self.railButton2ShearForce[:outOfRailTimeIndex, 1],
label="Lower Rail Button",
)
ax2.set_xlim(0, self.outOfRailTime if self.outOfRailTime > 0 else self.tFinal)
ax2.legend()
ax2.grid(True)
ax2.set_xlabel("Time (s)")
ax2.set_ylabel("Shear Force (N)")
ax2.set_title("Rail Buttons Shear Force")
plt.subplots_adjust(hspace=0.5)
plt.show()
# Aerodynamic force and moment plots
fig7 = plt.figure(figsize=(9, 12))
ax1 = plt.subplot(411)
ax1.plot(
self.aerodynamicLift[:eventTimeIndex, 0],
self.aerodynamicLift[:eventTimeIndex, 1],
label="Resultant",
)
ax1.plot(self.R1[:eventTimeIndex, 0], self.R1[:eventTimeIndex, 1], label="R1")
ax1.plot(self.R2[:eventTimeIndex, 0], self.R2[:eventTimeIndex, 1], label="R2")
ax1.set_xlim(0, eventTime)
ax1.legend()
ax1.set_xlabel("Time (s)")
ax1.set_ylabel("Lift Force (N)")
ax1.set_title("Aerodynamic Lift Resultant Force")
ax1.grid()
ax2 = plt.subplot(412)
ax2.plot(
self.aerodynamicDrag[:eventTimeIndex, 0],
self.aerodynamicDrag[:eventTimeIndex, 1],
)
ax2.set_xlim(0, eventTime)
ax2.set_xlabel("Time (s)")
ax2.set_ylabel("Drag Force (N)")
ax2.set_title("Aerodynamic Drag Force")
ax2.grid()
ax3 = plt.subplot(413)
ax3.plot(
self.aerodynamicBendingMoment[:eventTimeIndex, 0],
self.aerodynamicBendingMoment[:eventTimeIndex, 1],
label="Resultant",
)
ax3.plot(self.M1[:eventTimeIndex, 0], self.M1[:eventTimeIndex, 1], label="M1")
ax3.plot(self.M2[:eventTimeIndex, 0], self.M2[:eventTimeIndex, 1], label="M2")
ax3.set_xlim(0, eventTime)
ax3.legend()
ax3.set_xlabel("Time (s)")
ax3.set_ylabel("Bending Moment (N m)")
ax3.set_title("Aerodynamic Bending Resultant Moment")
ax3.grid()
ax4 = plt.subplot(414)
ax4.plot(
self.aerodynamicSpinMoment[:eventTimeIndex, 0],
self.aerodynamicSpinMoment[:eventTimeIndex, 1],
)
ax4.set_xlim(0, eventTime)
ax4.set_xlabel("Time (s)")
ax4.set_ylabel("Spin Moment (N m)")
ax4.set_title("Aerodynamic Spin Moment")
ax4.grid()
plt.subplots_adjust(hspace=0.5)
plt.show()
return None
def plotEnergyData(self):
"""Prints out all Energy components graphs available about the Flight
Returns
-------
None
"""
# Post-process results
if self.postProcessed is False:
self.postProcess()
# Get index of out of rail time
outOfRailTimeIndexs = np.nonzero(self.x[:, 0] == self.outOfRailTime)
outOfRailTimeIndex = (
-1 if len(outOfRailTimeIndexs) == 0 else outOfRailTimeIndexs[0][0]
)
# Get index of time before parachute event
if len(self.parachuteEvents) > 0:
eventTime = self.parachuteEvents[0][0] + self.parachuteEvents[0][1].lag
eventTimeIndex = np.nonzero(self.x[:, 0] == eventTime)[0][0]
else:
eventTime = self.tFinal
eventTimeIndex = -1
fig8 = plt.figure(figsize=(9, 9))
ax1 = plt.subplot(411)
ax1.plot(
self.kineticEnergy[:, 0], self.kineticEnergy[:, 1], label="Kinetic Energy"
)
ax1.plot(
self.rotationalEnergy[:, 0],
self.rotationalEnergy[:, 1],
label="Rotational Energy",
)
ax1.plot(
self.translationalEnergy[:, 0],
self.translationalEnergy[:, 1],
label="Translational Energy",
)
ax1.set_xlim(0, self.apogeeTime if self.apogeeTime != 0.0 else self.tFinal)
ax1.ticklabel_format(style="sci", axis="y", scilimits=(0, 0))
ax1.set_title("Kinetic Energy Components")
ax1.set_xlabel("Time (s)")
ax1.set_ylabel("Energy (J)")
ax1.legend()
ax1.grid()
ax2 = plt.subplot(412)
ax2.plot(self.totalEnergy[:, 0], self.totalEnergy[:, 1], label="Total Energy")
ax2.plot(
self.kineticEnergy[:, 0], self.kineticEnergy[:, 1], label="Kinetic Energy"
)
ax2.plot(
self.potentialEnergy[:, 0],
self.potentialEnergy[:, 1],
label="Potential Energy",
)
ax2.set_xlim(0, self.apogeeTime if self.apogeeTime != 0.0 else self.tFinal)
ax2.ticklabel_format(style="sci", axis="y", scilimits=(0, 0))
ax2.set_title("Total Mechanical Energy Components")
ax2.set_xlabel("Time (s)")
ax2.set_ylabel("Energy (J)")
ax2.legend()
ax2.grid()
ax3 = plt.subplot(413)
ax3.plot(self.thrustPower[:, 0], self.thrustPower[:, 1], label="|Thrust Power|")
ax3.set_xlim(0, self.rocket.motor.burnOutTime)
ax3.ticklabel_format(style="sci", axis="y", scilimits=(0, 0))
ax3.set_title("Thrust Absolute Power")
ax3.set_xlabel("Time (s)")
ax3.set_ylabel("Power (W)")
ax3.legend()
ax3.grid()
ax4 = plt.subplot(414)
ax4.plot(self.dragPower[:, 0], -self.dragPower[:, 1], label="|Drag Power|")
ax4.set_xlim(0, self.apogeeTime if self.apogeeTime != 0.0 else self.tFinal)
ax3.ticklabel_format(style="sci", axis="y", scilimits=(0, 0))
ax4.set_title("Drag Absolute Power")
ax4.set_xlabel("Time (s)")
ax4.set_ylabel("Power (W)")
ax4.legend()
ax4.grid()
plt.subplots_adjust(hspace=1)
plt.show()
return None
def plotFluidMechanicsData(self):
"""Prints out a summary of the Fluid Mechanics graphs available about
the Flight
Parameters
----------
None
Return
------
None
"""
# Post-process results
if self.postProcessed is False:
self.postProcess()
# Get index of out of rail time
outOfRailTimeIndexs = np.nonzero(self.x[:, 0] == self.outOfRailTime)
outOfRailTimeIndex = (
-1 if len(outOfRailTimeIndexs) == 0 else outOfRailTimeIndexs[0][0]
)
# Trajectory Fluid Mechanics Plots
fig10 = plt.figure(figsize=(9, 12))
ax1 = plt.subplot(411)
ax1.plot(self.MachNumber[:, 0], self.MachNumber[:, 1])
ax1.set_xlim(0, self.tFinal)
ax1.set_title("Mach Number")
ax1.set_xlabel("Time (s)")
ax1.set_ylabel("Mach Number")
ax1.grid()
ax2 = plt.subplot(412)
ax2.plot(self.ReynoldsNumber[:, 0], self.ReynoldsNumber[:, 1])
ax2.set_xlim(0, self.tFinal)
ax2.ticklabel_format(style="sci", axis="y", scilimits=(0, 0))
ax2.set_title("Reynolds Number")
ax2.set_xlabel("Time (s)")
ax2.set_ylabel("Reynolds Number")
ax2.grid()
ax3 = plt.subplot(413)
ax3.plot(
self.dynamicPressure[:, 0],
self.dynamicPressure[:, 1],
label="Dynamic Pressure",
)
ax3.plot(
self.totalPressure[:, 0], self.totalPressure[:, 1], label="Total Pressure"
)
ax3.plot(self.pressure[:, 0], self.pressure[:, 1], label="Static Pressure")
ax3.set_xlim(0, self.tFinal)
ax3.legend()
ax3.ticklabel_format(style="sci", axis="y", scilimits=(0, 0))
ax3.set_title("Total and Dynamic Pressure")
ax3.set_xlabel("Time (s)")
ax3.set_ylabel("Pressure (Pa)")
ax3.grid()
ax4 = plt.subplot(414)
ax4.plot(self.angleOfAttack[:, 0], self.angleOfAttack[:, 1])
ax4.set_xlim(
self.outOfRailTime, 10 * self.outOfRailTime + 1
) # +1 Prevents problem when self.outOfRailTime=0
ax4.set_ylim(0, self.angleOfAttack(self.outOfRailTime))
ax4.set_title("Angle of Attack")
ax4.set_xlabel("Time (s)")
ax4.set_ylabel("Angle of Attack (°)")
ax4.grid()
plt.subplots_adjust(hspace=0.5)
plt.show()
return None
def calculateFinFlutterAnalysis(self, finThickness, shearModulus):
"""Calculate, create and plot the Fin Flutter velocity, based on the
pressure profile provided by Atmosferic model selected. It considers the
Flutter Boundary Equation that is based on a calculation published in
NACA Technical Paper 4197.
Be careful, these results are only estimates of a real problem and may
not be useful for fins made from non-isotropic materials. These results
should not be used as a way to fully prove the safety of any rocket’s fins.
IMPORTANT: This function works if only a single set of fins is added
Parameters
----------
finThickness : float
The fin thickness, in meters
shearModulus : float
Shear Modulus of fins' material, must be given in Pascal
Return
------
None
"""
# Post-process results
if self.postProcessed is False:
self.postProcess()
s = (self.rocket.tipChord + self.rocket.rootChord) * self.rocket.span / 2
ar = self.rocket.span * self.rocket.span / s
la = self.rocket.tipChord / self.rocket.rootChord
# Calculate the Fin Flutter Mach Number
self.flutterMachNumber = (
(shearModulus * 2 * (ar + 2) * (finThickness / self.rocket.rootChord) ** 3)
/ (1.337 * (ar ** 3) * (la + 1) * self.pressure)
) ** 0.5
# Calculate difference between Fin Flutter Mach Number and the Rocket Speed
self.difference = self.flutterMachNumber - self.MachNumber
# Calculate a safety factor for flutter
self.safetyFactor = self.flutterMachNumber / self.MachNumber
# Calculate the minimun Fin Flutter Mach Number and Velocity
# Calculate the time and height of minimun Fin Flutter Mach Number
minflutterMachNumberTimeIndex = np.argmin(self.flutterMachNumber[:, 1])
minflutterMachNumber = self.flutterMachNumber[minflutterMachNumberTimeIndex, 1]
minMFTime = self.flutterMachNumber[minflutterMachNumberTimeIndex, 0]
minMFHeight = self.z(minMFTime) - self.env.elevation
minMFVelocity = minflutterMachNumber * self.env.speedOfSound(minMFHeight)
# Calculate minimum difference between Fin Flutter Mach Number and the Rocket Speed
# Calculate the time and height of the difference ...
minDifferenceTimeIndex = np.argmin(self.difference[:, 1])
minDif = self.difference[minDifferenceTimeIndex, 1]
minDifTime = self.difference[minDifferenceTimeIndex, 0]
minDifHeight = self.z(minDifTime) - self.env.elevation
minDifVelocity = minDif * self.env.speedOfSound(minDifHeight)
# Calculate the minimun Fin Flutter Safety factor
# Calculate the time and height of minimun Fin Flutter Safety factor
minSFTimeIndex = np.argmin(self.safetyFactor[:, 1])
minSF = self.safetyFactor[minSFTimeIndex, 1]
minSFTime = self.safetyFactor[minSFTimeIndex, 0]
minSFHeight = self.z(minSFTime) - self.env.elevation
# Print fin's geometric parameters
print("Fin's geometric parameters")
print("Surface area (S): {:.4f} m2".format(s))
print("Aspect ratio (AR): {:.3f}".format(ar))
print("TipChord/RootChord = \u03BB = {:.3f}".format(la))
print("Fin Thickness: {:.5f} m".format(finThickness))
# Print fin's material properties
print("\n\nFin's material properties")
print("Shear Modulus (G): {:.3e} Pa".format(shearModulus))
# Print a summary of the Fin Flutter Analysis
print("\n\nFin Flutter Analysis")
print(
"Minimum Fin Flutter Velocity: {:.3f} m/s at {:.2f} s".format(
minMFVelocity, minMFTime
)
)
print("Minimum Fin Flutter Mach Number: {:.3f} ".format(minflutterMachNumber))
# print(
# "Altitude of minimum Fin Flutter Velocity: {:.3f} m (AGL)".format(
# minMFHeight
# )
# )
print(
"Minimum of (Fin Flutter Mach Number - Rocket Speed): {:.3f} m/s at {:.2f} s".format(
minDifVelocity, minDifTime
)
)
print(
"Minimum of (Fin Flutter Mach Number - Rocket Speed): {:.3f} Mach at {:.2f} s".format(
minDif, minDifTime
)
)
# print(
# "Altitude of minimum (Fin Flutter Mach Number - Rocket Speed): {:.3f} m (AGL)".format(
# minDifHeight
# )
# )
print(
"Minimum Fin Flutter Safety Factor: {:.3f} at {:.2f} s".format(
minSF, minSFTime
)
)
print(
"Altitude of minimum Fin Flutter Safety Factor: {:.3f} m (AGL)\n\n".format(
minSFHeight
)
)
# Create plots
fig12 = plt.figure(figsize=(6, 9))
ax1 = plt.subplot(311)
ax1.plot()
ax1.plot(
self.flutterMachNumber[:, 0],
self.flutterMachNumber[:, 1],
label="Fin flutter Mach Number",
)
ax1.plot(
self.MachNumber[:, 0],
self.MachNumber[:, 1],
label="Rocket Freestream Speed",
)
ax1.set_xlim(0, self.apogeeTime if self.apogeeTime != 0.0 else self.tFinal)
ax1.set_title("Fin Flutter Mach Number x Time(s)")
ax1.set_xlabel("Time (s)")
ax1.set_ylabel("Mach")
ax1.legend()
ax1.grid(True)
ax2 = plt.subplot(312)
ax2.plot(self.difference[:, 0], self.difference[:, 1])
ax2.set_xlim(0, self.apogeeTime if self.apogeeTime != 0.0 else self.tFinal)
ax2.set_title("Mach flutter - Freestream velocity")
ax2.set_xlabel("Time (s)")
ax2.set_ylabel("Mach")
ax2.grid()
ax3 = plt.subplot(313)
ax3.plot(self.safetyFactor[:, 0], self.safetyFactor[:, 1])
ax3.set_xlim(self.outOfRailTime, self.apogeeTime)
ax3.set_ylim(0, 6)
ax3.set_title("Fin Flutter Safety Factor")
ax3.set_xlabel("Time (s)")
ax3.set_ylabel("Safety Factor")
ax3.grid()
plt.subplots_adjust(hspace=0.5)
plt.show()
return None
def plotStabilityAndControlData(self):
"""Prints out Rocket Stability and Control parameters graphs available
about the Flight
Parameters
----------
None
Return
------
None
"""
# Post-process results
if self.postProcessed is False:
self.postProcess()
fig9 = plt.figure(figsize=(9, 6))
ax1 = plt.subplot(211)
ax1.plot(self.staticMargin[:, 0], self.staticMargin[:, 1])
ax1.set_xlim(0, self.staticMargin[:, 0][-1])
ax1.set_title("Static Margin")
ax1.set_xlabel("Time (s)")
ax1.set_ylabel("Static Margin (c)")
ax1.grid()
ax2 = plt.subplot(212)
maxAttitude = max(self.attitudeFrequencyResponse[:, 1])
maxAttitude = maxAttitude if maxAttitude != 0 else 1
ax2.plot(
self.attitudeFrequencyResponse[:, 0],
self.attitudeFrequencyResponse[:, 1] / maxAttitude,
label="Attitude Angle",
)
maxOmega1 = max(self.omega1FrequencyResponse[:, 1])
maxOmega1 = maxOmega1 if maxOmega1 != 0 else 1
ax2.plot(
self.omega1FrequencyResponse[:, 0],
self.omega1FrequencyResponse[:, 1] / maxOmega1,
label="$\omega_1$",
)
maxOmega2 = max(self.omega2FrequencyResponse[:, 1])
maxOmega2 = maxOmega2 if maxOmega2 != 0 else 1
ax2.plot(
self.omega2FrequencyResponse[:, 0],
self.omega2FrequencyResponse[:, 1] / maxOmega2,
label="$\omega_2$",
)
maxOmega3 = max(self.omega3FrequencyResponse[:, 1])
maxOmega3 = maxOmega3 if maxOmega3 != 0 else 1
ax2.plot(
self.omega3FrequencyResponse[:, 0],
self.omega3FrequencyResponse[:, 1] / maxOmega3,
label="$\omega_3$",
)
ax2.set_title("Frequency Response")
ax2.set_xlabel("Frequency (Hz)")
ax2.set_ylabel("Amplitude Magnitude Normalized")
ax2.set_xlim(0, 5)
ax2.legend()
ax2.grid()
plt.subplots_adjust(hspace=0.5)
plt.show()
return None
def plotPressureSignals(self):
"""Prints out all Parachute Trigger Pressure Signals.
This function can be called also for plot pressure data for flights
without Parachutes, in this case the Pressure Signals will be simply
the pressure provided by the atmosfericModel, at Flight z positions.
This means that no noise will be considered if at least one parachute
has not been added.
This function aims to help the engineer to visually check if there
are anomalies with the Flight Simulation.
Parameters
----------
None
Return
------
None
"""
# Post-process results
if self.postProcessed is False:
self.postProcess()
if len(self.rocket.parachutes) == 0:
plt.figure()
ax1 = plt.subplot(111)
ax1.plot(self.z[:, 0], self.env.pressure(self.z[:, 1]))
ax1.set_title("Pressure at Rocket's Altitude")
ax1.set_xlabel("Time (s)")
ax1.set_ylabel("Pressure (Pa)")
ax1.set_xlim(0, self.tFinal)
ax1.grid()
plt.show()
else:
for parachute in self.rocket.parachutes:
print("Parachute: ", parachute.name)
parachute.noiseSignalFunction()
parachute.noisyPressureSignalFunction()
parachute.cleanPressureSignalFunction()
return None
def exportPressures(self, fileName, timeStep):
"""Exports the pressure experienced by the rocket during the flight to
an external file, the '.csv' format is recommended, as the columns will
be separated by commas. It can handle flights with or without parachutes,
although it is not possible to get a noisy pressure signal if no
parachute is added.
If a parachute is added, the file will contain 3 columns: time in seconds,
clean pressure in Pascals and noisy pressure in Pascals. For flights without
parachutes, the third column will be discarded
This function was created especially for the Projeto Jupiter Eletronics
Subsystems team and aims to help in configuring microcontrollers.
Parameters
----------
fileName : string
The final file name,
timeStep : float
Time step desired for the final file
Return
------
None
"""
if self.postProcessed is False:
self.postProcess()
timePoints = np.arange(0, self.tFinal, timeStep)
# Create the file
file = open(fileName, "w")
if len(self.rocket.parachutes) == 0:
pressure = self.env.pressure(self.z(timePoints))
for i in range(0, timePoints.size, 1):
file.write("{:f}, {:.5f}\n".format(timePoints[i], pressure[i]))
else:
for parachute in self.rocket.parachutes:
for i in range(0, timePoints.size, 1):
pCl = parachute.cleanPressureSignalFunction(timePoints[i])
pNs = parachute.noisyPressureSignalFunction(timePoints[i])
file.write("{:f}, {:.5f}, {:.5f}\n".format(timePoints[i], pCl, pNs))
# We need to save only 1 parachute data
pass
file.close()
return None
def allInfo(self):
"""Prints out all data and graphs available about the Flight.
Parameters
----------
None
Return
------
None
"""
# Post-process results
if self.postProcessed is False:
self.postProcess()
# Print initial conditions
print("Initial Conditions\n")
self.printInitialConditionsData()
# Print launch rail orientation
print("\n\nLaunch Rail Orientation\n")
print("Launch Rail Inclination: {:.2f}°".format(self.inclination))
print("Launch Rail Heading: {:.2f}°\n\n".format(self.heading))
# Print a summary of data about the flight
self.info()
print("\n\nNumerical Integration Information\n")
self.printNumericalIntegrationSettings()
print("\n\nTrajectory 3d Plot\n")
self.plot3dTrajectory()
print("\n\nTrajectory Kinematic Plots\n")
self.plotLinearKinematicsData()
print("\n\nAngular Position Plots\n")
self.plotFlightPathAngleData()
print("\n\nPath, Attitude and Lateral Attitude Angle plots\n")
self.plotAttitudeData()
print("\n\nTrajectory Angular Velocity and Acceleration Plots\n")
self.plotAngularKinematicsData()
print("\n\nTrajectory Force Plots\n")
self.plotTrajectoryForceData()
print("\n\nTrajectory Energy Plots\n")
self.plotEnergyData()
print("\n\nTrajectory Fluid Mechanics Plots\n")
self.plotFluidMechanicsData()
print("\n\nTrajectory Stability and Control Plots\n")
self.plotStabilityAndControlData()
return None
def animate(self, start=0, stop=None, fps=12, speed=4, elev=None, azim=None):
"""Plays an animation of the flight. Not implemented yet. Only
kinda works outside notebook.
"""
# Set up stopping time
stop = self.tFinal if stop is None else stop
# Speed = 4 makes it almost real time - matplotlib is way to slow
# Set up graph
fig = plt.figure(figsize=(18, 15))
axes = fig.gca(projection="3d")
# Initialize time
timeRange = np.linspace(start, stop, fps * (stop - start))
# Initialize first frame
axes.set_title("Trajectory and Velocity Animation")
axes.set_xlabel("X (m)")
axes.set_ylabel("Y (m)")
axes.set_zlabel("Z (m)")
axes.view_init(elev, azim)
R = axes.quiver(0, 0, 0, 0, 0, 0, color="r", label="Rocket")
V = axes.quiver(0, 0, 0, 0, 0, 0, color="g", label="Velocity")
W = axes.quiver(0, 0, 0, 0, 0, 0, color="b", label="Wind")
S = axes.quiver(0, 0, 0, 0, 0, 0, color="black", label="Freestream")
axes.legend()
# Animate
for t in timeRange:
R.remove()
V.remove()
W.remove()
S.remove()
# Calculate rocket position
Rx, Ry, Rz = self.x(t), self.y(t), self.z(t)
Ru = 1 * (2 * (self.e1(t) * self.e3(t) + self.e0(t) * self.e2(t)))
Rv = 1 * (2 * (self.e2(t) * self.e3(t) - self.e0(t) * self.e1(t)))
Rw = 1 * (1 - 2 * (self.e1(t) ** 2 + self.e2(t) ** 2))
# Caclulate rocket Mach number
Vx = self.vx(t) / 340.40
Vy = self.vy(t) / 340.40
Vz = self.vz(t) / 340.40
# Caculate wind Mach Number
z = self.z(t)
Wx = self.env.windVelocityX(z) / 20
Wy = self.env.windVelocityY(z) / 20
# Calculate freestream Mach Number
Sx = self.streamVelocityX(t) / 340.40
Sy = self.streamVelocityY(t) / 340.40
Sz = self.streamVelocityZ(t) / 340.40
# Plot Quivers
R = axes.quiver(Rx, Ry, Rz, Ru, Rv, Rw, color="r")
V = axes.quiver(Rx, Ry, Rz, -Vx, -Vy, -Vz, color="g")
W = axes.quiver(Rx - Vx, Ry - Vy, Rz - Vz, Wx, Wy, 0, color="b")
S = axes.quiver(Rx, Ry, Rz, Sx, Sy, Sz, color="black")
# Adjust axis
axes.set_xlim(Rx - 1, Rx + 1)
axes.set_ylim(Ry - 1, Ry + 1)
axes.set_zlim(Rz - 1, Rz + 1)
# plt.pause(1/(fps*speed))
try:
plt.pause(1 / (fps * speed))
except:
time.sleep(1 / (fps * speed))
def timeIterator(self, nodeList):
i = 0
while i < len(nodeList) - 1:
yield i, nodeList[i]
i += 1
class FlightPhases:
def __init__(self, init_list=[]):
self.list = init_list[:]
def __getitem__(self, index):
return self.list[index]
def __len__(self):
return len(self.list)
def __repr__(self):
return str(self.list)
def add(self, flightPhase, index=None):
# Handle first phase
if len(self.list) == 0:
self.list.append(flightPhase)
# Handle appending to last position
elif index is None:
# Check if new flight phase respects time
previousPhase = self.list[-1]
if flightPhase.t > previousPhase.t:
# All good! Add phase.
self.list.append(flightPhase)
elif flightPhase.t == previousPhase.t:
print(
"WARNING: Trying to add a flight phase starting together with the one preceding it."
)
print(
"This may be caused by more than when parachute being triggered simultaneously."
)
flightPhase.t += 1e-7
self.add(flightPhase)
elif flightPhase.t < previousPhase.t:
print(
"WARNING: Trying to add a flight phase starting before the one preceding it."
)
print(
"This may be caused by more than when parachute being triggered simultaneously."
)
self.add(flightPhase, -2)
# Handle inserting into intermediary position
else:
# Check if new flight phase respects time
nextPhase = self.list[index]
previousPhase = self.list[index - 1]
if previousPhase.t < flightPhase.t < nextPhase.t:
# All good! Add phase.
self.list.insert(index, flightPhase)
elif flightPhase.t < previousPhase.t:
print(
"WARNING: Trying to add a flight phase starting before the one preceding it."
)
print(
"This may be caused by more than when parachute being triggered simultaneously."
)
self.add(flightPhase, index - 1)
elif flightPhase.t == previousPhase.t:
print(
"WARNING: Trying to add a flight phase starting together with the one preceding it."
)
print(
"This may be caused by more than when parachute being triggered simultaneously."
)
flightPhase.t += 1e-7
self.add(flightPhase, index)
elif flightPhase.t == nextPhase.t:
print(
"WARNING: Trying to add a flight phase starting together with the one proceding it."
)
print(
"This may be caused by more than when parachute being triggered simultaneously."
)
flightPhase.t += 1e-7
self.add(flightPhase, index + 1)
elif flightPhase.t > nextPhase.t:
print(
"WARNING: Trying to add a flight phase starting after the one proceding it."
)
print(
"This may be caused by more than when parachute being triggered simultaneously."
)
self.add(flightPhase, index + 1)
def addPhase(self, t, derivatives=None, callback=[], clear=True, index=None):
self.add(self.FlightPhase(t, derivatives, callback, clear), index)
def flushAfter(self, index):
del self.list[index + 1 :]
class FlightPhase:
def __init__(self, t, derivative=None, callbacks=[], clear=True):
self.t = t
self.derivative = derivative
self.callbacks = callbacks[:]
self.clear = clear
def __repr__(self):
if self.derivative is None:
return "{Initial Time: " + str(self.t) + " | Derivative: None}"
return (
"{Initial Time: "
+ str(self.t)
+ " | Derivative: "
+ self.derivative.__name__
+ "}"
)
class TimeNodes:
def __init__(self, init_list=[]):
self.list = init_list[:]
def __getitem__(self, index):
return self.list[index]
def __len__(self):
return len(self.list)
def __repr__(self):
return str(self.list)
def add(self, timeNode):
self.list.append(timeNode)
def addNode(self, t, parachutes, callbacks):
self.list.append(self.TimeNode(t, parachutes, callbacks))
def addParachutes(self, parachutes, t_init, t_end):
# Iterate over parachutes
for parachute in parachutes:
# Calculate start of sampling time nodes
pcDt = 1 / parachute.samplingRate
parachute_node_list = [
self.TimeNode(i * pcDt, [parachute], [])
for i in range(
math.ceil(t_init / pcDt), math.floor(t_end / pcDt) + 1
)
]
self.list += parachute_node_list
def sort(self):
self.list.sort(key=(lambda node: node.t))
def merge(self):
# Initialize temporary list
self.tmp_list = [self.list[0]]
self.copy_list = self.list[1:]
# Iterate through all other time nodes
for node in self.copy_list:
# If there is already another node with similar time: merge
if abs(node.t - self.tmp_list[-1].t) < 1e-7:
self.tmp_list[-1].parachutes += node.parachutes
self.tmp_list[-1].callbacks += node.callbacks
# Add new node to tmp list if there is none with the same time
else:
self.tmp_list.append(node)
# Save tmp list to permanent
self.list = self.tmp_list
def flushAfter(self, index):
del self.list[index + 1 :]
class TimeNode:
def __init__(self, t, parachutes, callbacks):
self.t = t
self.parachutes = parachutes
self.callbacks = callbacks
def __repr__(self):
return (
"{Initial Time: "
+ str(self.t)
+ " | Parachutes: "
+ str(len(self.parachutes))
+ "}"
) | /rocket.py-1.0.1.tar.gz/rocket.py-1.0.1/rocketpy/Flight.py | 0.817938 | 0.6149 | Flight.py | pypi |
import logging
import urwid
class CommandInput(urwid.Edit):
"""A specialized urwid.Edit widget that implements the rocket.term command
input box."""
PROMPT = u"> "
def __init__(self, cmd_callback, complete_callback, keymap):
"""
:param cmd_callback: A callback function to be invoked once a command
has been entered. The callback will receive the
full command line that was entered as a string.
:param complete_callback: A callback function to be invoked once a
command completion is requested by the user. The
callback will receive thef ull command line that
was entered as a string. The callback needs to
return the line text to display or None if
nothing could be completed.
"""
super().__init__(caption=self.PROMPT)
self.m_logger = logging.getLogger("CommandInput")
self.m_cmd_callback = cmd_callback
self.m_complete_callback = complete_callback
# here a command history is maintained that can be scrolled back to
self.m_history = []
# the current history position we have
self.m_cur_history_pos = -1
# when scrolling through the history while we're already having new
# input then this new input is stored here to allow it to be restored
# via selectNewerHistoryEntry() later on, without having to actually
# submit the command.
self.m_pending_cmd = ""
self.m_keymap = keymap
self.m_next_input_verbatim = False
def addPrompt(self, text):
"""Prepends text to the command input prompt."""
self.set_caption("{} {}".format(text, self.PROMPT))
def resetPrompt(self):
"""Resets the command input prompt to its default value."""
self.set_caption(self.PROMPT)
def _replaceText(self, line):
"""Replace the command input text by the given string and adjust
the cursor accordingly."""
self.set_edit_text(line)
self.set_edit_pos(len(line))
def _addText(self, to_add):
current = self.text[len(self.caption):]
new = current + to_add
self.set_edit_text(new)
self.set_edit_pos(len(new))
def _getCommandLine(self):
"""Returns the net command line input from the input box."""
return self.text[len(self.caption):]
def _addToHistory(self, line):
"""Adds the given command to the command history."""
self.m_history.append(line)
self.m_cur_history_pos = -1
self.m_pending_cmd = ""
def _selectOlderHistoryEntry(self):
if not self.m_history:
return
if self.m_cur_history_pos == -1:
self.m_cur_history_pos = len(self.m_history) - 1
self.m_pending_cmd = self._getCommandLine()
elif self.m_cur_history_pos == 0:
return
else:
self.m_cur_history_pos -= 1
histline = self.m_history[self.m_cur_history_pos]
self._replaceText(histline)
def _selectNewerHistoryEntry(self):
if not self.m_history:
return
if self.m_cur_history_pos == -1:
return
elif self.m_cur_history_pos == len(self.m_history) - 1:
if self.m_pending_cmd:
self._replaceText(self.m_pending_cmd)
self.m_pending_cmd = ""
else:
self._replaceText("")
self.m_cur_history_pos = -1
return
else:
self.m_cur_history_pos += 1
histline = self.m_history[self.m_cur_history_pos]
self._replaceText(histline)
def keypress(self, size, key):
if self.m_logger.isEnabledFor(logging.DEBUG):
self.m_logger.debug("key event: {}".format(key))
if self.m_next_input_verbatim:
return self._handleVerbatimKey(key)
# first let the EditBox handle the event to e.g. move the cursor
# around or add new characters.
if super().keypress(size, key) is None:
return None
return self._handleRegularKey(key)
def _handleRegularKey(self, key):
command = self._getCommandLine()
if key == 'enter':
if command:
self.set_edit_text(u"")
self.m_cmd_callback(command)
self._addToHistory(command)
return None
elif key == 'tab':
new_line = self.m_complete_callback(command)
if new_line:
self._replaceText(new_line)
return None
elif key == self.m_keymap['cmd_history_older']:
self._selectOlderHistoryEntry()
return None
elif key == self.m_keymap['cmd_history_newer']:
self._selectNewerHistoryEntry()
return None
elif key == 'ctrl v':
self.m_next_input_verbatim = True
return key
def _handleVerbatimKey(self, key):
self.m_next_input_verbatim = False
if key == 'enter':
self._addText("\n")
elif key == 'tab':
self._addText("\t")
return None
class SizedListBox(urwid.ListBox):
"""A ListBox that knows its last size.
urwid widgets by default have no known size. The size is only known
while in the process of rendering. This is quite stupid for certain
situations. Therefore this specialization of ListBox stores its last
size seen during rendering for clients of the ListBox to refer to.
This specialized ListBox also makes the widget non-selectable, because we
don't want the focus to jump around, it needs to stick on the command
input widget.
"""
def __init__(self, *args, **kwargs):
"""
:param size_callback: An optional callback function that will be
invoked when a size change is encountered.
"""
try:
self.m_size_cb = kwargs.pop("size_callback")
except KeyError:
self.m_size_cb = None
super().__init__(*args, **kwargs)
self.m_last_size_seen = None
def _invokeSizeCB(self, old_size):
if self.m_size_cb:
self.m_size_cb(self)
def getLastSizeSeen(self):
return self.m_last_size_seen
def getNumRows(self):
return self.m_last_size_seen[1] if self.m_last_size_seen else 0
def getNumCols(self):
return self.m_last_size_seen[0] if self.m_last_size_seen else 0
def render(self, size, focus=False):
if self.m_last_size_seen != size:
old = self.m_last_size_seen
self.m_last_size_seen = size
self._invokeSizeCB(old)
return super().render(size, focus)
def selectable(self):
return False
def scrollUp(self, small_increments):
"""Wrapper to explicitly scroll the list up.
:param bool small_increments: If set then not a whole page but only a
single list item will be scrolled.
"""
if not self.m_last_size_seen:
return
if small_increments:
self._keypress_up(self.m_last_size_seen)
else:
self._keypress_page_up(self.m_last_size_seen)
def scrollDown(self, small_increments):
"""Wrapper to explicitly scroll the list down.
See scrollUp().
"""
if not self.m_last_size_seen:
return
if small_increments:
self._keypress_down(self.m_last_size_seen)
else:
self._keypress_page_down(self.m_last_size_seen) | /rocket.term-0.3.0.post1.tar.gz/rocket.term-0.3.0.post1/rocketterm/widgets.py | 0.716715 | 0.163846 | widgets.py | pypi |
import hashlib
import time
class RealtimeRequest:
"""Method call or subscription in the RocketChat realtime API."""
_max_id = 0
@staticmethod
def _get_new_id():
RealtimeRequest._max_id += 1
return f'{RealtimeRequest._max_id}'
class Connect(RealtimeRequest):
"""Initialize the connection."""
REQUEST_MSG = {
'msg': 'connect',
'version': '1',
'support': ['1'],
}
@classmethod
async def call(cls, dispatcher):
await dispatcher.call_method(cls.REQUEST_MSG)
class Resume(RealtimeRequest):
"""Log in to the service with a token."""
@staticmethod
def _get_request_msg(msg_id, token):
return {
"msg": "method",
"method": "login",
"id": msg_id,
"params": [
{
"resume": token,
}
]
}
@staticmethod
def _parse(response):
return response['result']['id']
@classmethod
async def call(cls, dispatcher, token):
msg_id = cls._get_new_id()
msg = cls._get_request_msg(msg_id, token)
response = await dispatcher.call_method(msg, msg_id)
return cls._parse(response)
class Login(RealtimeRequest):
"""Log in to the service."""
@staticmethod
def _get_request_msg(msg_id, username, password):
pwd_digest = hashlib.sha256(password.encode()).hexdigest()
return {
"msg": "method",
"method": "login",
"id": msg_id,
"params": [
{
"user": {"username": username},
"password": {
"digest": pwd_digest,
"algorithm": "sha-256"
}
}
]
}
@staticmethod
def _parse(response):
return response['result']['id']
@classmethod
async def call(cls, dispatcher, username, password):
msg_id = cls._get_new_id()
msg = cls._get_request_msg(msg_id, username, password)
response = await dispatcher.call_method(msg, msg_id)
return cls._parse(response)
class GetChannels(RealtimeRequest):
"""Get a list of channels user is currently member of."""
@staticmethod
def _get_request_msg(msg_id):
return {
'msg': 'method',
'method': 'rooms/get',
'id': msg_id,
'params': [],
}
@staticmethod
def _parse(response):
# Return channel IDs and channel types.
return [(r['_id'], r['t']) for r in response['result']]
@classmethod
async def call(cls, dispatcher):
msg_id = cls._get_new_id()
msg = cls._get_request_msg(msg_id)
response = await dispatcher.call_method(msg, msg_id)
return cls._parse(response)
class SendMessage(RealtimeRequest):
"""Send a text message to a channel."""
@staticmethod
def _get_request_msg(msg_id, channel_id, msg_text, thread_id=None):
id_seed = f'{msg_id}:{time.time()}'
msg = {
"msg": "method",
"method": "sendMessage",
"id": msg_id,
"params": [
{
"_id": hashlib.md5(id_seed.encode()).hexdigest()[:12],
"rid": channel_id,
"msg": msg_text
}
]
}
if thread_id is not None:
msg["params"][0]["tmid"] = thread_id
return msg
@classmethod
async def call(cls, dispatcher, msg_text, channel_id, thread_id=None):
msg_id = cls._get_new_id()
msg = cls._get_request_msg(msg_id, channel_id, msg_text, thread_id)
await dispatcher.call_method(msg, msg_id)
class SendReaction(RealtimeRequest):
"""Send a reaction to a specific message."""
@staticmethod
def _get_request_msg(msg_id, orig_msg_id, emoji):
return {
"msg": "method",
"method": "setReaction",
"id": msg_id,
"params": [
emoji,
orig_msg_id,
]
}
@classmethod
async def call(cls, dispatcher, orig_msg_id, emoji):
msg_id = cls._get_new_id()
msg = cls._get_request_msg(msg_id, orig_msg_id, emoji)
await dispatcher.call_method(msg)
class SendTypingEvent(RealtimeRequest):
"""Send the `typing` event to a channel."""
@staticmethod
def _get_request_msg(msg_id, channel_id, username, is_typing):
return {
"msg": "method",
"method": "stream-notify-room",
"id": msg_id,
"params": [
f'{channel_id}/typing',
username,
is_typing
]
}
@classmethod
async def call(cls, dispatcher, channel_id, username, is_typing):
msg_id = cls._get_new_id()
msg = cls._get_request_msg(msg_id, channel_id, username, is_typing)
await dispatcher.call_method(msg, msg_id)
class SubscribeToChannelMessages(RealtimeRequest):
"""Subscribe to all messages in the given channel."""
@staticmethod
def _get_request_msg(msg_id, channel_id):
return {
"msg": "sub",
"id": msg_id,
"name": "stream-room-messages",
"params": [
channel_id,
{
"useCollection": False,
"args": []
}
]
}
@staticmethod
def _wrap(callback):
def fn(msg):
event = msg['fields']['args'][0] # TODO: This looks suspicious.
msg_id = event['_id']
channel_id = event['rid']
thread_id = event.get('tmid')
sender_id = event['u']['_id']
msg = event['msg']
qualifier = event.get('t')
return callback(channel_id, sender_id, msg_id, thread_id, msg,
qualifier)
return fn
@classmethod
async def call(cls, dispatcher, channel_id, callback):
# TODO: document the expected interface of the callback.
msg_id = cls._get_new_id()
msg = cls._get_request_msg(msg_id, channel_id)
await dispatcher.create_subscription(msg, msg_id, cls._wrap(callback))
return msg_id # Return the ID to allow for later unsubscription.
class SubscribeToChannelChanges(RealtimeRequest):
"""Subscribe to all changes in channels."""
@staticmethod
def _get_request_msg(msg_id, user_id):
return {
"msg": "sub",
"id": msg_id,
"name": "stream-notify-user",
"params": [
f'{user_id}/rooms-changed',
False
]
}
@staticmethod
def _wrap(callback):
def fn(msg):
payload = msg['fields']['args']
if payload[0] == 'removed':
return # Nothing else to do - channel has just been deleted.
channel_id = payload[1]['_id']
channel_type = payload[1]['t']
return callback(channel_id, channel_type)
return fn
@classmethod
async def call(cls, dispatcher, user_id, callback):
# TODO: document the expected interface of the callback.
msg_id = cls._get_new_id()
msg = cls._get_request_msg(msg_id, user_id)
await dispatcher.create_subscription(msg, msg_id, cls._wrap(callback))
return msg_id # Return the ID to allow for later unsubscription.
class Unsubscribe(RealtimeRequest):
"""Cancel a subscription"""
@staticmethod
def _get_request_msg(subscription_id):
return {
"msg": "unsub",
"id": subscription_id,
}
@classmethod
async def call(cls, dispatcher, subscription_id):
msg = cls._get_request_msg(subscription_id)
await dispatcher.call_method(msg) | /rocketchat_async-1.2.0.tar.gz/rocketchat_async-1.2.0/rocketchat_async/methods.py | 0.733929 | 0.157105 | methods.py | pypi |
import re
from abc import ABC
from abc import abstractmethod
class AbstractHandler(ABC):
@abstractmethod
def matches(self, bot, message) -> bool:
"""Should return true if this handler feels responsible for handling `message`, false otherwise
:param message: RocketchatMessage object
:return Whether or not this handler wants to handle `message`"""
pass
@abstractmethod
def handle(self, bot, message):
"""Handles a message received by `bot`
:param bot: RocketchatBot
:param message: dict containing a RocketChat message"""
pass
class CommandHandler(AbstractHandler):
"""A handler that responds to commands of the form `$command`"""
def __init__(self, command, callback_function):
"""
:param command: The command this handler should respond to (not including the preceding slash)
:param callback_function: The function to call when a matching message is received.
The callback function is passed the RocketchatBot and RocketchatMessage as arguments
"""
self.command = command
self.callback_function = callback_function
def matches(self, bot, message) -> bool:
if message.is_by_me() or not message.is_new():
return False
if message.data["msg"].startswith("${}".format(self.command)):
return True
return False
def handle(self, bot, message):
self.callback_function(bot, message)
class RegexHandler(AbstractHandler):
"""A handler that responds to messages matching a RegExp"""
def __init__(self, regex, callback_function):
"""
:param regex: A regular expression that matches the message texts this handler should respond to.
:param callback_function: The function to call when a matching message is received.
The callback function is passed the RocketchatBot and RocketchatMessage as arguments
"""
self.regex = re.compile(regex)
self.callback_function = callback_function
def matches(self, bot, message) -> bool:
if message.is_by_me() or not message.is_new():
return False
if message.data["msg"]:
if self.regex.search(message.data["msg"]):
return True
return False
def handle(self, bot, message):
self.callback_function(bot, message)
class MessageHandler(AbstractHandler):
"""A handler that responds to all messages"""
def __init__(self, callback_function):
"""
:param callback_function: The function to call when a matching message is received.
The callback function is passed the RocketchatBot and RocketchatMessage as arguments
"""
self.callback_function = callback_function
def matches(self, bot, message) -> bool:
if message.is_by_me() or not message.is_new():
return False
return True
def handle(self, bot, message):
self.callback_function(bot, message)
class DirectMessageHandler(AbstractHandler):
"""A handler that responds to all messages sent directly to the bot"""
def __init__(self, callback_function):
"""
:param callback_function: The function to call when a matching message is received.
The callback function is passed the RocketchatBot and RocketchatMessage as arguments
"""
self.callback_function = callback_function
def matches(self, bot, message) -> bool:
if message.is_by_me() or not message.is_new() or not message.is_direct():
return False
return True
def handle(self, bot, message):
self.callback_function(bot, message)
class MentionHandler(AbstractHandler):
"""A handler that responds to all messages mentioning the bot (or any specified users)"""
ROOM_MENTIONS = ["all", "here"]
def __init__(self, callback_function, include_all=False, mention_user=None, mention_users=None):
"""
:param callback_function: The function to call when a matching message is received.
:param include_all: boolean indicating whether @all and @here mentions should trigger this handler, default False
:param mention_user: Username of the user whose mentions shall call this handler. If not specified, use the bot's own username.
:param mention_users: List of usernames of the users whose mentions shall call this handler. Supersedes `mention_user` if provided.
The callback function is passed the RocketchatBot and RocketchatMessage as arguments
"""
self.callback_function = callback_function
self.include_all = include_all
self.mention_users = mention_users or ([mention_user] if mention_user else None)
def matches(self, bot, message) -> bool:
if message.is_by_me() or not message.is_new():
return False
mus = self.mention_users
if not mus:
mus = [bot.user["username"]]
for mention in message.data.get("mentions", []):
if mention.get("username") in mus:
return True
if self.include_all and mention.get("username") in self.ROOM_MENTIONS:
return True
return False
def handle(self, bot, message):
self.callback_function(bot, message)
class ReactionHandler(AbstractHandler):
"""A handler that responds to all messages adding reactions to the bot's own messages"""
def __init__(self, callback_function, reactions=None):
"""
:param callback_function: The function to call when a matching message is received.
:param reactions: List of specific reactions to filter for. If left out, all reactions will trigger the handler.
The callback function is passed the RocketchatBot and RocketchatMessage as arguments
"""
self.callback_function = callback_function
self.filter_reactions = reactions
def matches(self, bot, message) -> bool:
if not message.is_by_me():
return False
reactions = message.data.get("reactions")
if not reactions:
return False
if self.filter_reactions:
for reaction in reactions.keys():
if reaction in self.filter_reactions:
return True
return False
return True
def handle(self, bot, message):
self.callback_function(bot, message) | /rocketchat_bot_sdk-0.0.8.tar.gz/rocketchat_bot_sdk-0.0.8/rocketchat_bot_sdk/handlers.py | 0.827898 | 0.173009 | handlers.py | pypi |
import hashlib
import time
class RealtimeRequest:
"""Method call or subscription in the RocketChat realtime API."""
_max_id = 0
@staticmethod
def _get_new_id():
RealtimeRequest._max_id += 1
return f'{RealtimeRequest._max_id}'
class Connect(RealtimeRequest):
"""Initialize the connection."""
REQUEST_MSG = {
'msg': 'connect',
'version': '1',
'support': ['1'],
}
@classmethod
async def call(cls, dispatcher):
await dispatcher.call_method(cls.REQUEST_MSG)
class Login(RealtimeRequest):
"""Log in to the service."""
@staticmethod
def _get_request_msg(msg_id, args):
msg = {
"msg": "method",
"method": "login",
"id": msg_id,
}
if len(args) == 1:
msg["params"] = [{
"resume": args[0]
}]
else:
pwd_digest = hashlib.sha256(args[1].encode()).hexdigest()
msg["params"] = [
{
"user": {"username": args[0]},
"password": {
"digest": pwd_digest,
"algorithm": "sha-256"
}
}
]
return msg
@staticmethod
def _parse(response):
return response['result']['id']
@classmethod
async def call(cls, dispatcher, args):
msg_id = cls._get_new_id()
msg = cls._get_request_msg(msg_id, args)
response = await dispatcher.call_method(msg, msg_id)
return cls._parse(response)
class GetChannels(RealtimeRequest):
"""Get a list of channels user is currently member of."""
@staticmethod
def _get_request_msg(msg_id):
return {
'msg': 'method',
'method': 'rooms/get',
'id': msg_id,
'params': [],
}
@staticmethod
def _parse(response):
# Return channel IDs and channel types.
return [(r['_id'], r['t']) for r in response['result']]
@classmethod
async def call(cls, dispatcher):
msg_id = cls._get_new_id()
msg = cls._get_request_msg(msg_id)
response = await dispatcher.call_method(msg, msg_id)
return cls._parse(response)
class SendMessage(RealtimeRequest):
"""Send a text message to a channel."""
@staticmethod
def _get_request_msg(msg_id, channel_id, msg_text, thread_id=None):
id_seed = f'{msg_id}:{time.time()}'
msg = {
"msg": "method",
"method": "sendMessage",
"id": msg_id,
"params": [
{
"_id": hashlib.md5(id_seed.encode()).hexdigest()[:12],
"rid": channel_id,
"msg": msg_text
}
]
}
if thread_id is not None:
msg["params"][0]["tmid"] = thread_id
return msg
@classmethod
async def call(cls, dispatcher, msg_text, channel_id, thread_id=None):
msg_id = cls._get_new_id()
msg = cls._get_request_msg(msg_id, channel_id, msg_text, thread_id)
await dispatcher.call_method(msg, msg_id)
class SendReaction(RealtimeRequest):
"""Send a reaction to a specific message."""
@staticmethod
def _get_request_msg(msg_id, orig_msg_id, emoji):
return {
"msg": "method",
"method": "setReaction",
"id": msg_id,
"params": [
emoji,
orig_msg_id,
]
}
@classmethod
async def call(cls, dispatcher, orig_msg_id, emoji):
msg_id = cls._get_new_id()
msg = cls._get_request_msg(msg_id, orig_msg_id, emoji)
await dispatcher.call_method(msg)
class SendTypingEvent(RealtimeRequest):
"""Send the `typing` event to a channel."""
@staticmethod
def _get_request_msg(msg_id, channel_id, username, is_typing):
return {
"msg": "method",
"method": "stream-notify-room",
"id": msg_id,
"params": [
f'{channel_id}/typing',
username,
is_typing
]
}
@classmethod
async def call(cls, dispatcher, channel_id, username, is_typing):
msg_id = cls._get_new_id()
msg = cls._get_request_msg(msg_id, channel_id, username, is_typing)
await dispatcher.call_method(msg, msg_id)
class SubscribeToChannelMessages(RealtimeRequest):
"""Subscribe to all messages in the given channel."""
@staticmethod
def _get_request_msg(msg_id, channel_id):
return {
"msg": "sub",
"id": msg_id,
"name": "stream-room-messages",
"params": [
channel_id,
{
"useCollection": False,
"args": []
}
]
}
@staticmethod
def _wrap(callback):
def fn(msg):
message = msg['fields']['args'][0] # TODO: This looks suspicious.
msg_id = message['_id']
channel_id = message['rid']
sender_id = message['u']['_id']
return callback(channel_id, sender_id, msg_id,
message)
return fn
@classmethod
async def call(cls, dispatcher, channel_id, callback):
# TODO: document the expected interface of the callback.
msg_id = cls._get_new_id()
msg = cls._get_request_msg(msg_id, channel_id)
await dispatcher.create_subscription(msg, msg_id, cls._wrap(callback))
return msg_id # Return the ID to allow for later unsubscription.
class SubscribeToChannelChanges(RealtimeRequest):
"""Subscribe to all changes in channels."""
@staticmethod
def _get_request_msg(msg_id, user_id):
return {
"msg": "sub",
"id": msg_id,
"name": "stream-notify-user",
"params": [
f'{user_id}/rooms-changed',
False
]
}
@staticmethod
def _wrap(callback):
def fn(msg):
payload = msg['fields']['args']
if payload[0] == 'removed':
return # Nothing else to do - channel has just been deleted.
channel_id = payload[1]['_id']
channel_type = payload[1]['t']
return callback(channel_id, channel_type)
return fn
@classmethod
async def call(cls, dispatcher, user_id, callback):
# TODO: document the expected interface of the callback.
msg_id = cls._get_new_id()
msg = cls._get_request_msg(msg_id, user_id)
await dispatcher.create_subscription(msg, msg_id, cls._wrap(callback))
return msg_id # Return the ID to allow for later unsubscription.
class Unsubscribe(RealtimeRequest):
"""Cancel a subscription"""
@staticmethod
def _get_request_msg(subscription_id):
return {
"msg": "unsub",
"id": subscription_id,
}
@classmethod
async def call(cls, dispatcher, subscription_id):
msg = cls._get_request_msg(subscription_id)
await dispatcher.call_method(msg) | /rocketchat_bot_sdk-0.0.8.tar.gz/rocketchat_bot_sdk-0.0.8/rocketchat_bot_sdk/rocketchat_async/methods.py | 0.693888 | 0.151028 | methods.py | pypi |
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from apache.rocketmq.v2 import service_pb2 as apache_dot_rocketmq_dot_v2_dot_service__pb2
class MessagingServiceStub(object):
"""For all the RPCs in MessagingService, the following error handling policies
apply:
If the request doesn't bear a valid authentication credential, return a
response with common.status.code == `UNAUTHENTICATED`. If the authenticated
user is not granted with sufficient permission to execute the requested
operation, return a response with common.status.code == `PERMISSION_DENIED`.
If the per-user-resource-based quota is exhausted, return a response with
common.status.code == `RESOURCE_EXHAUSTED`. If any unexpected server-side
errors raise, return a response with common.status.code == `INTERNAL`.
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.QueryRoute = channel.unary_unary(
'/apache.rocketmq.v2.MessagingService/QueryRoute',
request_serializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.QueryRouteRequest.SerializeToString,
response_deserializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.QueryRouteResponse.FromString,
)
self.Heartbeat = channel.unary_unary(
'/apache.rocketmq.v2.MessagingService/Heartbeat',
request_serializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.HeartbeatRequest.SerializeToString,
response_deserializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.HeartbeatResponse.FromString,
)
self.SendMessage = channel.unary_unary(
'/apache.rocketmq.v2.MessagingService/SendMessage',
request_serializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.SendMessageRequest.SerializeToString,
response_deserializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.SendMessageResponse.FromString,
)
self.QueryAssignment = channel.unary_unary(
'/apache.rocketmq.v2.MessagingService/QueryAssignment',
request_serializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.QueryAssignmentRequest.SerializeToString,
response_deserializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.QueryAssignmentResponse.FromString,
)
self.ReceiveMessage = channel.unary_stream(
'/apache.rocketmq.v2.MessagingService/ReceiveMessage',
request_serializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.ReceiveMessageRequest.SerializeToString,
response_deserializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.ReceiveMessageResponse.FromString,
)
self.AckMessage = channel.unary_unary(
'/apache.rocketmq.v2.MessagingService/AckMessage',
request_serializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.AckMessageRequest.SerializeToString,
response_deserializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.AckMessageResponse.FromString,
)
self.ForwardMessageToDeadLetterQueue = channel.unary_unary(
'/apache.rocketmq.v2.MessagingService/ForwardMessageToDeadLetterQueue',
request_serializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.ForwardMessageToDeadLetterQueueRequest.SerializeToString,
response_deserializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.ForwardMessageToDeadLetterQueueResponse.FromString,
)
self.EndTransaction = channel.unary_unary(
'/apache.rocketmq.v2.MessagingService/EndTransaction',
request_serializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.EndTransactionRequest.SerializeToString,
response_deserializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.EndTransactionResponse.FromString,
)
self.Telemetry = channel.stream_stream(
'/apache.rocketmq.v2.MessagingService/Telemetry',
request_serializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.TelemetryCommand.SerializeToString,
response_deserializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.TelemetryCommand.FromString,
)
self.NotifyClientTermination = channel.unary_unary(
'/apache.rocketmq.v2.MessagingService/NotifyClientTermination',
request_serializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.NotifyClientTerminationRequest.SerializeToString,
response_deserializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.NotifyClientTerminationResponse.FromString,
)
self.ChangeInvisibleDuration = channel.unary_unary(
'/apache.rocketmq.v2.MessagingService/ChangeInvisibleDuration',
request_serializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.ChangeInvisibleDurationRequest.SerializeToString,
response_deserializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.ChangeInvisibleDurationResponse.FromString,
)
class MessagingServiceServicer(object):
"""For all the RPCs in MessagingService, the following error handling policies
apply:
If the request doesn't bear a valid authentication credential, return a
response with common.status.code == `UNAUTHENTICATED`. If the authenticated
user is not granted with sufficient permission to execute the requested
operation, return a response with common.status.code == `PERMISSION_DENIED`.
If the per-user-resource-based quota is exhausted, return a response with
common.status.code == `RESOURCE_EXHAUSTED`. If any unexpected server-side
errors raise, return a response with common.status.code == `INTERNAL`.
"""
def QueryRoute(self, request, context):
"""Queries the route entries of the requested topic in the perspective of the
given endpoints. On success, servers should return a collection of
addressable message-queues. Note servers may return customized route
entries based on endpoints provided.
If the requested topic doesn't exist, returns `NOT_FOUND`.
If the specific endpoints is empty, returns `INVALID_ARGUMENT`.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def Heartbeat(self, request, context):
"""Producer or consumer sends HeartbeatRequest to servers periodically to
keep-alive. Additionally, it also reports client-side configuration,
including topic subscription, load-balancing group name, etc.
Returns `OK` if success.
If a client specifies a language that is not yet supported by servers,
returns `INVALID_ARGUMENT`
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def SendMessage(self, request, context):
"""Delivers messages to brokers.
Clients may further:
1. Refine a message destination to message-queues which fulfills parts of
FIFO semantic;
2. Flag a message as transactional, which keeps it invisible to consumers
until it commits;
3. Time a message, making it invisible to consumers till specified
time-point;
4. And more...
Returns message-id or transaction-id with status `OK` on success.
If the destination topic doesn't exist, returns `NOT_FOUND`.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def QueryAssignment(self, request, context):
"""Queries the assigned route info of a topic for current consumer,
the returned assignment result is decided by server-side load balancer.
If the corresponding topic doesn't exist, returns `NOT_FOUND`.
If the specific endpoints is empty, returns `INVALID_ARGUMENT`.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def ReceiveMessage(self, request, context):
"""Receives messages from the server in batch manner, returns a set of
messages if success. The received messages should be acked or redelivered
after processed.
If the pending concurrent receive requests exceed the quota of the given
consumer group, returns `UNAVAILABLE`. If the upstream store server hangs,
return `DEADLINE_EXCEEDED` in a timely manner. If the corresponding topic
or consumer group doesn't exist, returns `NOT_FOUND`. If there is no new
message in the specific topic, returns `OK` with an empty message set.
Please note that client may suffer from false empty responses.
If failed to receive message from remote, server must return only one
`ReceiveMessageResponse` as the reply to the request, whose `Status` indicates
the specific reason of failure, otherwise, the reply is considered successful.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def AckMessage(self, request, context):
"""Acknowledges the message associated with the `receipt_handle` or `offset`
in the `AckMessageRequest`, it means the message has been successfully
processed. Returns `OK` if the message server remove the relevant message
successfully.
If the given receipt_handle is illegal or out of date, returns
`INVALID_ARGUMENT`.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def ForwardMessageToDeadLetterQueue(self, request, context):
"""Forwards one message to dead letter queue if the max delivery attempts is
exceeded by this message at client-side, return `OK` if success.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def EndTransaction(self, request, context):
"""Commits or rollback one transactional message.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def Telemetry(self, request_iterator, context):
"""Once a client starts, it would immediately establishes bi-lateral stream
RPCs with brokers, reporting its settings as the initiative command.
When servers have need of inspecting client status, they would issue
telemetry commands to clients. After executing received instructions,
clients shall report command execution results through client-side streams.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def NotifyClientTermination(self, request, context):
"""Notify the server that the client is terminated.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def ChangeInvisibleDuration(self, request, context):
"""Once a message is retrieved from consume queue on behalf of the group, it
will be kept invisible to other clients of the same group for a period of
time. The message is supposed to be processed within the invisible
duration. If the client, which is in charge of the invisible message, is
not capable of processing the message timely, it may use
ChangeInvisibleDuration to lengthen invisible duration.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_MessagingServiceServicer_to_server(servicer, server):
rpc_method_handlers = {
'QueryRoute': grpc.unary_unary_rpc_method_handler(
servicer.QueryRoute,
request_deserializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.QueryRouteRequest.FromString,
response_serializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.QueryRouteResponse.SerializeToString,
),
'Heartbeat': grpc.unary_unary_rpc_method_handler(
servicer.Heartbeat,
request_deserializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.HeartbeatRequest.FromString,
response_serializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.HeartbeatResponse.SerializeToString,
),
'SendMessage': grpc.unary_unary_rpc_method_handler(
servicer.SendMessage,
request_deserializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.SendMessageRequest.FromString,
response_serializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.SendMessageResponse.SerializeToString,
),
'QueryAssignment': grpc.unary_unary_rpc_method_handler(
servicer.QueryAssignment,
request_deserializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.QueryAssignmentRequest.FromString,
response_serializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.QueryAssignmentResponse.SerializeToString,
),
'ReceiveMessage': grpc.unary_stream_rpc_method_handler(
servicer.ReceiveMessage,
request_deserializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.ReceiveMessageRequest.FromString,
response_serializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.ReceiveMessageResponse.SerializeToString,
),
'AckMessage': grpc.unary_unary_rpc_method_handler(
servicer.AckMessage,
request_deserializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.AckMessageRequest.FromString,
response_serializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.AckMessageResponse.SerializeToString,
),
'ForwardMessageToDeadLetterQueue': grpc.unary_unary_rpc_method_handler(
servicer.ForwardMessageToDeadLetterQueue,
request_deserializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.ForwardMessageToDeadLetterQueueRequest.FromString,
response_serializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.ForwardMessageToDeadLetterQueueResponse.SerializeToString,
),
'EndTransaction': grpc.unary_unary_rpc_method_handler(
servicer.EndTransaction,
request_deserializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.EndTransactionRequest.FromString,
response_serializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.EndTransactionResponse.SerializeToString,
),
'Telemetry': grpc.stream_stream_rpc_method_handler(
servicer.Telemetry,
request_deserializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.TelemetryCommand.FromString,
response_serializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.TelemetryCommand.SerializeToString,
),
'NotifyClientTermination': grpc.unary_unary_rpc_method_handler(
servicer.NotifyClientTermination,
request_deserializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.NotifyClientTerminationRequest.FromString,
response_serializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.NotifyClientTerminationResponse.SerializeToString,
),
'ChangeInvisibleDuration': grpc.unary_unary_rpc_method_handler(
servicer.ChangeInvisibleDuration,
request_deserializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.ChangeInvisibleDurationRequest.FromString,
response_serializer=apache_dot_rocketmq_dot_v2_dot_service__pb2.ChangeInvisibleDurationResponse.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'apache.rocketmq.v2.MessagingService', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
# This class is part of an EXPERIMENTAL API.
class MessagingService(object):
"""For all the RPCs in MessagingService, the following error handling policies
apply:
If the request doesn't bear a valid authentication credential, return a
response with common.status.code == `UNAUTHENTICATED`. If the authenticated
user is not granted with sufficient permission to execute the requested
operation, return a response with common.status.code == `PERMISSION_DENIED`.
If the per-user-resource-based quota is exhausted, return a response with
common.status.code == `RESOURCE_EXHAUSTED`. If any unexpected server-side
errors raise, return a response with common.status.code == `INTERNAL`.
"""
@staticmethod
def QueryRoute(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/apache.rocketmq.v2.MessagingService/QueryRoute',
apache_dot_rocketmq_dot_v2_dot_service__pb2.QueryRouteRequest.SerializeToString,
apache_dot_rocketmq_dot_v2_dot_service__pb2.QueryRouteResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def Heartbeat(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/apache.rocketmq.v2.MessagingService/Heartbeat',
apache_dot_rocketmq_dot_v2_dot_service__pb2.HeartbeatRequest.SerializeToString,
apache_dot_rocketmq_dot_v2_dot_service__pb2.HeartbeatResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def SendMessage(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/apache.rocketmq.v2.MessagingService/SendMessage',
apache_dot_rocketmq_dot_v2_dot_service__pb2.SendMessageRequest.SerializeToString,
apache_dot_rocketmq_dot_v2_dot_service__pb2.SendMessageResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def QueryAssignment(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/apache.rocketmq.v2.MessagingService/QueryAssignment',
apache_dot_rocketmq_dot_v2_dot_service__pb2.QueryAssignmentRequest.SerializeToString,
apache_dot_rocketmq_dot_v2_dot_service__pb2.QueryAssignmentResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def ReceiveMessage(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_stream(request, target, '/apache.rocketmq.v2.MessagingService/ReceiveMessage',
apache_dot_rocketmq_dot_v2_dot_service__pb2.ReceiveMessageRequest.SerializeToString,
apache_dot_rocketmq_dot_v2_dot_service__pb2.ReceiveMessageResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def AckMessage(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/apache.rocketmq.v2.MessagingService/AckMessage',
apache_dot_rocketmq_dot_v2_dot_service__pb2.AckMessageRequest.SerializeToString,
apache_dot_rocketmq_dot_v2_dot_service__pb2.AckMessageResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def ForwardMessageToDeadLetterQueue(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/apache.rocketmq.v2.MessagingService/ForwardMessageToDeadLetterQueue',
apache_dot_rocketmq_dot_v2_dot_service__pb2.ForwardMessageToDeadLetterQueueRequest.SerializeToString,
apache_dot_rocketmq_dot_v2_dot_service__pb2.ForwardMessageToDeadLetterQueueResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def EndTransaction(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/apache.rocketmq.v2.MessagingService/EndTransaction',
apache_dot_rocketmq_dot_v2_dot_service__pb2.EndTransactionRequest.SerializeToString,
apache_dot_rocketmq_dot_v2_dot_service__pb2.EndTransactionResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def Telemetry(request_iterator,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.stream_stream(request_iterator, target, '/apache.rocketmq.v2.MessagingService/Telemetry',
apache_dot_rocketmq_dot_v2_dot_service__pb2.TelemetryCommand.SerializeToString,
apache_dot_rocketmq_dot_v2_dot_service__pb2.TelemetryCommand.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def NotifyClientTermination(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/apache.rocketmq.v2.MessagingService/NotifyClientTermination',
apache_dot_rocketmq_dot_v2_dot_service__pb2.NotifyClientTerminationRequest.SerializeToString,
apache_dot_rocketmq_dot_v2_dot_service__pb2.NotifyClientTerminationResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def ChangeInvisibleDuration(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/apache.rocketmq.v2.MessagingService/ChangeInvisibleDuration',
apache_dot_rocketmq_dot_v2_dot_service__pb2.ChangeInvisibleDurationRequest.SerializeToString,
apache_dot_rocketmq_dot_v2_dot_service__pb2.ChangeInvisibleDurationResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata) | /rocketmq_client-0.1.0.tar.gz/rocketmq_client-0.1.0/rocketmq_client/apache/rocketmq/v2/service_pb2_grpc.py | 0.814607 | 0.151278 | service_pb2_grpc.py | pypi |

<br>
[](https://colab.research.google.com/github/RocketPy-Team/rocketpy/blob/master/docs/notebooks/getting_started_colab.ipynb)
[](https://pypi.org/project/rocketpy/)
[](https://docs.rocketpy.org/en/latest/?badge=latest)
[](https://app.travis-ci.com/RocketPy-Team/RocketPy)
[](https://github.com/RocketPy-Team/RocketPy/graphs/contributors)
[](https://discord.gg/b6xYnNh)
[](https://github.com/sponsors/RocketPy-Team)
[](https://www.linkedin.com/company/rocketpy)
[](http://dx.doi.org/10.1061/%28ASCE%29AS.1943-5525.0001331)
<img src="https://static.scarf.sh/a.png?x-pxid=6f4094ab-00fa-4a8d-9247-b7ed27e7164d" />
# RocketPy
RocketPy is the next-generation trajectory simulation solution for High-Power Rocketry. The code is written as a [Python](http://www.python.org) library and allows for a complete 6 degrees of freedom simulation of a rocket's flight trajectory, including high-fidelity variable mass effects as well as descent under parachutes. Weather conditions, such as wind profiles, can be imported from sophisticated datasets, allowing for realistic scenarios. Furthermore, the implementation facilitates complex simulations, such as multi-stage rockets, design and trajectory optimization and dispersion analysis.
<br>
## Main features
<details>
<summary>Nonlinear 6 degrees of freedom simulations</summary>
<ul>
<li>Rigorous treatment of mass variation effects</li>
<li>Solved using LSODA with adjustable error tolerances</li>
<li>Highly optimized to run fast</li>
</ul>
</details>
<details>
<summary>Accurate weather modeling</summary>
<ul>
<li>International Standard Atmosphere (1976)</li>
<li>Custom atmospheric profiles</li>
<li>Soundings (Wyoming, NOAARuc)</li>
<li>Weather forecasts and reanalysis</li>
<li>Weather ensembles</li>
</ul>
</details>
<details>
<summary>Aerodynamic models</summary>
<ul>
<li>Barrowman equations for lift coefficients (optional)</li>
<li>Drag coefficients can be easily imported from other sources (e.g. CFD simulations)</li>
</ul>
</details>
<details>
<summary>Parachutes with external trigger functions</summary>
<ul>
<li>Test the exact code that will fly</li>
<li>Sensor data can be augmented with noise</li>
</ul>
</details>
<details>
<summary>Solid, Hybrid and Liquid motors models</summary>
<ul>
<li>Burn rate and mass variation properties from thrust curve</li>
<li>Define custom rocket tanks based on their flux data</li>
<li>CSV and ENG file support</li>
</ul>
</details>
<details>
<summary>Monte Carlo simulations</summary>
<ul>
<li>Dispersion analysis</li>
<li>Global sensitivity analysis</li>
</ul>
</details>
<details>
<summary>Flexible and modular</summary>
<ul>
<li>Straightforward engineering analysis (e.g. apogee and lifting off speed as a function of mass)</li>
<li>Non-standard flights (e.g. parachute drop test from a helicopter)</li>
<li>Multi-stage rockets</li>
<li>Custom continuous and discrete control laws</li>
<li>Create new classes (e.g. other types of motors)</li>
</ul>
</details>
<details>
<summary>Integration with MATLAB®</summary>
<ul>
<li>Straightforward way to run RocketPy from MATLAB®</li>
<li>Convert RocketPy results to MATLAB® variables so that they can be processed by MATLAB®</li>
</ul>
</details>
<br>
## Validation
RocketPy's features have been validated in our latest [research article published in the Journal of Aerospace Engineering](http://dx.doi.org/10.1061/%28ASCE%29AS.1943-5525.0001331).
The table below shows a comparison between experimental data and the output from RocketPy.
Flight data and rocket parameters used in this comparison were kindly provided by [EPFL Rocket Team](https://github.com/EPFLRocketTeam) and [Notre Dame Rocket Team](https://ndrocketry.weebly.com/).
| Mission | Result Parameter | RocketPy | Measured | Relative Error |
|:-----------------------:|:-----------------------|:---------:|:---------:|:---------------:|
| Bella Lui Kaltbrumn | Apogee altitude (m) | 461.03 | 458.97 | **0.45 %** |
| Bella Lui Kaltbrumn | Apogee time (s) | 10.61 | 10.56 | **0.47 %** |
| Bella Lui Kaltbrumn | Maximum velocity (m/s) | 86.18 | 90.00 | **-4.24 %** |
| NDRT launch vehicle | Apogee altitude (m) | 1,310.44 | 1,320.37 | **-0.75 %** |
| NDRT launch vehicle | Apogee time (s) | 16.77 | 17.10 | **-1.90 %** |
| NDRT launch vehicle | Maximum velocity (m/s) | 172.86 | 168.95 | **2.31 %** |
<br>
## Documentation
Check out documentation details using the links below:
- [User Guide](https://docs.rocketpy.org/en/latest/user/index.html)
- [Code Documentation](https://docs.rocketpy.org/en/latest/reference/index.html)
- [Development Guide](https://docs.rocketpy.org/en/latest/development/index.html)
<br>
# Join Our Community!
RocketPy is growing fast! Many university groups and rocket hobbyists have already started using it. The number of stars and forks for this repository is skyrocketing. And this is all thanks to a great community of users, engineers, developers, marketing specialists, and everyone interested in helping.
If you want to be a part of this and make RocketPy your own, join our [Discord](https://discord.gg/b6xYnNh) server today!
<br>
# Previewing
You can preview RocketPy's main functionalities by browsing through a sample notebook in [Google Colab](https://colab.research.google.com/github/RocketPy-Team/rocketpy/blob/master/docs/notebooks/getting_started_colab.ipynb). No installation is required!
When you are ready to run RocketPy locally, you can read the *Getting Started* section!
<br>
# Getting Started
## Quick Installation
To install RocketPy's latest stable version from PyPI, just open up your terminal and run:
```shell
pip install rocketpy
```
For other installation options, visit our [Installation Docs](https://docs.rocketpy.org/en/latest/user/installation.html).
To learn more about RocketPy's requirements, visit our [Requirements Docs](https://docs.rocketpy.org/en/latest/user/requirements.html).
<br>
## Running Your First Simulation
In order to run your first rocket trajectory simulation using RocketPy, you can start a Jupyter Notebook and navigate to the _docs/notebooks_ folder. Open _getting_started.ipynb_ and you are ready to go.
Otherwise, you may want to create your own script or your own notebook using RocketPy. To do this, let's see how to use RocketPy's four main classes:
- Environment - Keeps data related to weather.
- Motor - Subdivided into SolidMotor, HybridMotor and LiquidMotor. Keeps data related to rocket motors.
- Rocket - Keeps data related to a rocket.
- Flight - Runs the simulation and keeps the results.
The following image shows how the four main classes interact with each other:

A typical workflow starts with importing these classes from RocketPy:
```python
from rocketpy import Environment, Rocket, SolidMotor, Flight
```
An optional step is to import datetime, which is used to define the date of the simulation:
```python
import datetime
```
Then create an Environment object. To learn more about it, you can use:
```python
help(Environment)
```
A sample code is:
```python
env = Environment(
latitude=32.990254,
longitude=-106.974998,
elevation=1400,
)
tomorrow = datetime.date.today() + datetime.timedelta(days=1)
env.set_date(
(tomorrow.year, tomorrow.month, tomorrow.day, 12), timezone="America/Denver"
) # Tomorrow's date in year, month, day, hour UTC format
env.set_atmospheric_model(type='Forecast', file='GFS')
```
This can be followed up by starting a Solid Motor object. To get help on it, just use:
```python
help(SolidMotor)
```
A sample Motor object can be created by the following code:
```python
Pro75M1670 = SolidMotor(
thrust_source="data/motors/Cesaroni_M1670.eng",
dry_mass=1.815,
dry_inertia=(0.125, 0.125, 0.002),
center_of_dry_mass=0.317,
grains_center_of_mass_position=0.397,
burn_time=3.9,
grain_number=5,
grain_separation=0.005,
grain_density=1815,
grain_outer_radius=0.033,
grain_initial_inner_radius=0.015,
grain_initial_height=0.12,
nozzle_radius=0.033,
throat_radius=0.011,
interpolation_method="linear",
nozzle_position=0,
coordinate_system_orientation="nozzle_to_combustion_chamber",
)
```
With a Solid Motor defined, you are ready to create your Rocket object. As you may have guessed, to get help on it, use:
```python
help(Rocket)
```
A sample code to create a Rocket is:
```python
calisto = Rocket(
radius=0.0635,
mass=14.426, # without motor
inertia=(6.321, 6.321, 0.034),
power_off_drag="data/calisto/powerOffDragCurve.csv",
power_on_drag="data/calisto/powerOnDragCurve.csv",
center_of_mass_without_motor=0,
coordinate_system_orientation="tail_to_nose",
)
buttons = calisto.set_rail_buttons(
upper_button_position=0.0818,
lower_button_position=-0.6182,
angular_position=45,
)
calisto.add_motor(Pro75M1670, position=-1.255)
nose = calisto.add_nose(
length=0.55829, kind="vonKarman", position=1.278
)
fins = calisto.add_trapezoidal_fins(
n=4,
root_chord=0.120,
tip_chord=0.040,
span=0.100,
sweep_length=None,
cant_angle=0,
position=-1.04956,
)
tail = calisto.add_tail(
top_radius=0.0635, bottom_radius=0.0435, length=0.060, position=-1.194656
)
```
You may want to add parachutes to your rocket as well:
```python
main = calisto.add_parachute(
name="main",
cd_s=10.0,
trigger=800, # ejection altitude in meters
sampling_rate=105,
lag=1.5,
noise=(0, 8.3, 0.5),
)
drogue = calisto.add_parachute(
name="drogue",
cd_s=1.0,
trigger="apogee", # ejection at apogee
sampling_rate=105,
lag=1.5,
noise=(0, 8.3, 0.5),
)
```
Finally, you can create a Flight object to simulate your trajectory. To get help on the Flight class, use:
```python
help(Flight)
```
To actually create a Flight object, use:
```python
test_flight = Flight(
rocket=calisto, environment=env, rail_length=5.2, inclination=85, heading=0
)
```
Once the Flight object is created, your simulation is done! Use the following code to get a summary of the results:
```python
test_flight.info()
```
To see all available results, use:
```python
test_flight.all_info()
```
Here is just a quick taste of what RocketPy is able to calculate. There are hundreds of plots and data points computed by RocketPy to enhance your analyses.

If you want to see the trajectory on Google Earth, RocketPy acn easily export a KML file for you:
```python
test_flight.export_kml(file_name="test_flight.kml")
```
<br>
# Authors and Contributors
This package was originally created by [Giovani Ceotto](https://github.com/giovaniceotto/) as part of his work at [Projeto Jupiter](https://github.com/Projeto-Jupiter/). [Rodrigo Schmitt](https://github.com/rodrigo-schmitt/) was one of the first contributors.
Later, [Guilherme Fernandes](https://github.com/Gui-FernandesBR/) and [Lucas Azevedo](https://github.com/lucasfourier/) joined the team to work on the expansion and sustainability of this project.
Since then, the [RocketPy Team](https://github.com/orgs/RocketPy-Team/teams/rocketpy-team) has been growing fast and our contributors are what makes us special!
[](https://github.com/RocketPy-Team/RocketPy/contributors)
See a [detailed list of contributors](https://github.com/RocketPy-Team/RocketPy/contributors) who are actively working on RocketPy.
## Supporting RocketPy and Contributing
The easiest way to help RocketPy is to demonstrate your support by starring our repository!
[](https://starchart.cc/rocketpy-team/rocketpy)
You can also become a [sponsor](https://github.com/sponsors/RocketPy-Team) and help us financially to keep the project going.
If you are actively using RocketPy in one of your projects, reaching out to our core team via [Discord](https://discord.gg/b6xYnNh) and providing feedback can help improve RocketPy a lot!
And if you are interested in going one step further, please read [CONTRIBUTING.md](https://github.com/RocketPy-Team/RocketPy/blob/master/CONTRIBUTING.md) for details on our code of conduct and learn more about how you can contribute to the development of this next-gen trajectory simulation solution for rocketry.
<br>
## License
This project is licensed under the MIT License - see the [LICENSE.md](https://github.com/RocketPy-Team/RocketPy/blob/master/LICENSE) file for details
<br>
## Release Notes
Want to know which bugs have been fixed and the new features of each version? Check out the [release notes](https://github.com/RocketPy-Team/RocketPy/releases).
| /rocketpy-1.0.0a1.tar.gz/rocketpy-1.0.0a1/README.md | 0.440469 | 0.827898 | README.md | pypi |
[](https://rocketpyalpha.readthedocs.io/en/latest/?badge=latest)
[](https://colab.research.google.com/github/giovaniceotto/rocketpy/blob/master/docs/notebooks/getting_started_colab.ipynb)
[](https://mybinder.org/v2/gh/giovaniceotto/RocketPy/master?filepath=docs%2Fnotebooks%2Fgetting_started.ipynb)
[](https://pepy.tech/project/rocketpyalpha)
# RocketPy
RocketPy is a trajectory simulation for High-Power Rocketry built by [Projeto Jupiter](https://www.facebook.com/ProjetoJupiter/). The code is written as a [Python](http://www.python.org) library and allows for a complete 6 degrees of freedom simulation of a rocket's flight trajectory, including high fidelity variable mass effects as well as descent under parachutes. Weather conditions, such as wind profile, can be imported from sophisticated datasets, allowing for realistic scenarios. Furthermore, the implementation facilitates complex simulations, such as multi-stage rockets, design and trajectory optimization and dispersion analysis.
## Previewing
You can preview RocketPy's main functionalities by browsing through a sample notebook either in [Google Colab](https://colab.research.google.com/github/giovaniceotto/rocketpy/blob/master/docs/notebooks/getting_started_colab.ipynb) or in [MyBinder](https://mybinder.org/v2/gh/giovaniceotto/RocketPy/master?filepath=docs%2Fnotebooks%2Fgetting_started.ipynb)!
Then, you can read the *Getting Started* section to get your own copy!
## Getting Started
These instructions will get you a copy of RocketPy up and running on your local machine.
### Prerequisites
The following is needed in order to run RocketPy:
- Python >= 3.0
- Numpy >= 1.0
- Scipy >= 1.0
- Matplotlib >= 3.0
- requests
- netCDF4 >= 1.4 (optional, requires Cython)
All of these packages, with the exception of netCDF4, should be automatically
installed when RocketPy is installed using either pip or conda.
However, in case the user wants to install these packages manually, they can do
so by following the instructions bellow:
The first 4 prerequisites come with Anaconda, but Scipy might need
updating. The nedCDF4 package can be installed if there is interest in
importing weather data from netCDF files. To update Scipy and install
netCDF4 using Conda, the following code is used:
```
$ conda install "scipy>=1.0"
$ conda install -c anaconda "netcdf4>=1.4"
```
Alternatively, if you only have Python 3.X installed, the packages needed can be installed using pip:
```
$ pip install "numpy>=1.0"
$ pip install "scipy>=1.0"
$ pip install "matplotlib>=3.0"
$ pip install "netCDF4>=1.4"
$ pip install "requests"
```
Although [Jupyter Notebooks](http://jupyter.org/) are by no means required to run RocketPy, they are strongly recommend. They already come with Anaconda builds, but can also be installed separately using pip:
```
$ pip install jupyter
```
### Installation
To get a copy of RocketPy using pip, just run:
```
$ pip install rocketpyalpha
```
Alternatively, the package can also be installed using conda:
```
$ conda install -c conda-forge rocketpy
```
If you want to downloaded it from source, you may do so either by:
- Downloading it from [RocketPy's GitHub](https://github.com/giovaniceotto/RocketPy) page
- Unzip the folder and you are ready to go
- Or cloning it to a desired directory using git:
- ```$ git clone https://github.com/giovaniceotto/RocketPy.git```
The RockeyPy library can then be installed by running:
```
$ python setup.py install
```
### Documentations
You can find RocketPy's documentation at [Read the Docs](https://rocketpyalpha.readthedocs.io/en/latest/).
### Running Your First Simulation
In order to run your first rocket trajectory simulation using RocketPy, you can start a Jupyter Notebook and navigate to the **_nbks_** folder. Open **_Getting Started - Examples.ipynb_** and you are ready to go.
Otherwise, you may want to create your own script or your own notebook using RocketPy. To do this, let's see how to use RocketPy's four main classes:
- Environment - Keeps data related to weather.
- SolidMotor - Keeps data related to solid motors. Hybrid motor suport is coming in the next weeks.
- Rocket - Keeps data related to a rocket.
- Flight - Runs the simulation and keeps the results.
A typical workflow starts with importing these classes from RocketPy:
```python
from rocketpy import Environment, Rocket, SolidMotor, Flight
```
Then create an Environment object. To learn more about it, you can use:
```python
help(Environment)
```
A sample code is:
```python
Env = Environment(
railLength=5.2,
latitude=32.990254,
longitude=-106.974998,
elevation=1400,
date=(2020, 3, 4, 12) # Tomorrow's date in year, month, day, hour UTC format
)
Env.setAtmosphericModel(type='Forecast', file='GFS')
```
This can be followed up by starting a Solid Motor object. To get help on it, just use:
```python
help(SolidMotor)
```
A sample Motor object can be created by the following code:
```python
Pro75M1670 = SolidMotor(
thrustSource="../data/motors/Cesaroni_M1670.eng",
burnOut=3.9,
grainNumber=5,
grainSeparation=5/1000,
grainDensity=1815,
grainOuterRadius=33/1000,
grainInitialInnerRadius=15/1000,
grainInitialHeight=120/1000,
nozzleRadius=33/1000,
throatRadius=11/1000,
interpolationMethod='linear'
)
```
With a Solid Motor defined, you are ready to create your Rocket object. As you may have guessed, to get help on it, use:
```python
help(Rocket)
```
A sample code to create a Rocket is:
```python
Calisto = Rocket(
motor=Pro75M1670,
radius=127/2000,
mass=19.197-2.956,
inertiaI=6.60,
inertiaZ=0.0351,
distanceRocketNozzle=-1.255,
distanceRocketPropellant=-0.85704,
powerOffDrag='../data/calisto/powerOffDragCurve.csv',
powerOnDrag='../data/calisto/powerOnDragCurve.csv'
)
Calisto.setRailButtons([0.2, -0.5])
NoseCone = Calisto.addNose(length=0.55829, kind="vonKarman", distanceToCM=0.71971)
FinSet = Calisto.addFins(4, span=0.100, rootChord=0.120, tipChord=0.040, distanceToCM=-1.04956)
Tail = Calisto.addTail(topRadius=0.0635, bottomRadius=0.0435, length=0.060, distanceToCM=-1.194656)
```
You may want to add parachutes to your rocket as well:
```python
def drogueTrigger(p, y):
return True if y[5] < 0 else False
def mainTrigger(p, y):
return True if y[5] < 0 and y[2] < 800 else False
Main = Calisto.addParachute('Main',
CdS=10.0,
trigger=mainTrigger,
samplingRate=105,
lag=1.5,
noise=(0, 8.3, 0.5))
Drogue = Calisto.addParachute('Drogue',
CdS=1.0,
trigger=drogueTrigger,
samplingRate=105,
lag=1.5,
noise=(0, 8.3, 0.5))
```
Finally, you can create a Flight object to simulate your trajectory. To get help on the Flight class, use:
```python
help(Flight)
```
To actually create a Flight object, use:
```python
TestFlight = Flight(rocket=Calisto, environment=Env, inclination=85, heading=0)
```
Once the TestFlight object is created, your simulation is done! Use the following code to get a summary of the results:
```python
TestFlight.info()
```
To seel all available results, use:
```python
TestFlight.allInfo()
```
## Built With
* [Numpy](http://www.numpy.org/)
* [Scipy](https://www.scipy.org/)
* [Matplotlib](https://matplotlib.org/)
* [netCDF4](https://github.com/Unidata/netcdf4-python)
## Contributing
Please read [CONTRIBUTING.md](https://github.com/giovaniceotto/RocketPy/blob/master/CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests to us. - **_Still working on this!_**
## Authors
* **Giovani Hidalgo Ceotto**
See also the list of [contributors](https://github.com/giovaniceotto/RocketPy/contributors) who participated in this project.
## License
This project is licensed under the MIT License - see the [LICENSE.md](https://github.com/giovaniceotto/RocketPy/blob/master/LICENSE) file for details
## Release Notes
Want to know which bugs have been fixed and new features of each version? Check out the [release notes](https://github.com/giovaniceotto/RocketPy/releases).
| /rocketpyalpha-0.9.6.tar.gz/rocketpyalpha-0.9.6/README.md | 0.532668 | 0.98829 | README.md | pypi |
__author__ = "Giovani Hidalgo Ceotto"
__copyright__ = "Copyright 20XX, Projeto Jupiter"
__license__ = "MIT"
import re
import math
import bisect
import warnings
import time
from datetime import datetime, timedelta
from inspect import signature, getsourcelines
from collections import namedtuple
import numpy as np
from scipy import integrate
from scipy import linalg
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from .Function import Function
class Rocket:
"""Keeps all rocket and parachute information.
Attributes
----------
Geometrical attributes:
Rocket.radius : float
Rocket's largest radius in meters.
Rocket.area : float
Rocket's circular cross section largest frontal area in meters
squared.
Rocket.distanceRocketNozzle : float
Distance between rocket's center of mass, without propellant,
to the exit face of the nozzle, in meters. Always positive.
Rocket.distanceRocketPropellant : float
Distance between rocket's center of mass, without propellant,
to the center of mass of propellant, in meters. Always positive.
Mass and Inertia attributes:
Rocket.mass : float
Rocket's mass without propellant in kg.
Rocket.inertiaI : float
Rocket's moment of inertia, without propellant, with respect to
to an axis perpendicular to the rocket's axis of cylindrical
symmetry, in kg*m^2.
Rocket.inertiaZ : float
Rocket's moment of inertia, without propellant, with respect to
the rocket's axis of cylindrical symmetry, in kg*m^2.
Rocket.centerOfMass : Function
Distance of the rocket's center of mass, including propellant,
to rocket's center of mass without propellant, in meters.
Expressed as a function of time.
Rocket.reducedMass : Function
Function of time expressing the reduced mass of the rocket,
defined as the product of the propellant mass and the mass
of the rocket without propellant, divided by the sum of the
propellant mass and the rocket mass.
Rocket.totalMass : Function
Function of time expressing the total mass of the rocket,
defined as the sum of the propellant mass and the rocket
mass without propellant.
Rocket.thrustToWeight : Function
Function of time expressing the motor thrust force divided by rocket
weight. The gravitational acceleration is assumed as 9.80665 m/s^2.
Excentricity attributes:
Rocket.cpExcentricityX : float
Center of pressure position relative to center of mass in the x
axis, perpendicular to axis of cylindrical symmetry, in meters.
Rocket.cpExcentricityY : float
Center of pressure position relative to center of mass in the y
axis, perpendicular to axis of cylindrical symmetry, in meters.
Rocket.thrustExcentricityY : float
Thrust vector position relative to center of mass in the y
axis, perpendicular to axis of cylindrical symmetry, in meters.
Rocket.thrustExcentricityX : float
Thrust vector position relative to center of mass in the x
axis, perpendicular to axis of cylindrical symmetry, in meters.
Parachute attributes:
Rocket.parachutes : list
List of parachutes of the rocket.
Each parachute has the following attributes:
name : string
Parachute name, such as drogue and main. Has no impact in
simulation, as it is only used to display data in a more
organized matter.
CdS : float
Drag coefficient times reference area for parachute. It is
used to compute the drag force exerted on the parachute by
the equation F = ((1/2)*rho*V^2)*CdS, that is, the drag
force is the dynamic pressure computed on the parachute
times its CdS coefficient. Has units of area and must be
given in meters squared.
trigger : function
Function which defines if the parachute ejection system is
to be triggered. It must take as input the freestream
pressure in pascal and the state vector of the simulation,
which is defined by [x, y, z, vx, vy, vz, e0, e1, e2, e3, wx, wy, wz].
It will be called according to the sampling rate given next.
It should return True if the parachute ejection system is
to be triggered and False otherwise.
samplingRate : float, optional
Sampling rate in which the trigger function works. It is used to
simulate the refresh rate of onboard sensors such as barometers.
Default value is 100. Value must be given in Hertz.
lag : float, optional
Time between the parachute ejection system is triggered and the
parachute is fully opened. During this time, the simulation will
consider the rocket as flying without a parachute. Default value
is 0. Must be given in seconds.
noise : tupple, list, optional
List in the format (mean, standard deviation, time-correlation).
The values are used to add noise to the pressure signal which is
passed to the trigger function. Default value is (0, 0, 0). Units
are in Pascal.
noiseSignal : list
List of (t, noise signal) corresponding to signal passed to
trigger function. Completed after running a simulation.
noisyPressureSignal : list
List of (t, noisy pressure signal) that is passed to the
trigger function. Completed after running a simulation.
cleanPressureSignal : list
List of (t, clean pressure signal) corresponding to signal passed to
trigger function. Completed after running a simulation.
noiseSignalFunction : Function
Function of noiseSignal.
noisyPressureSignalFunction : Function
Function of noisyPressureSignal.
cleanPressureSignalFunction : Function
Function of cleanPressureSignal.
Aerodynamic attributes
Rocket.aerodynamicSurfaces : list
List of aerodynamic surfaces of the rocket.
Rocket.staticMargin : float
Float value corresponding to rocket static margin when
loaded with propellant in units of rocket diameter or
calibers.
Rocket.powerOffDrag : Function
Rocket's drag coefficient as a function of Mach number when the
motor is off.
Rocket.powerOnDrag : Function
Rocket's drag coefficient as a function of Mach number when the
motor is on.
Motor attributes:
Rocket.motor : Motor
Rocket's motor. See Motor class for more details.
"""
def __init__(
self,
motor,
mass,
inertiaI,
inertiaZ,
radius,
distanceRocketNozzle,
distanceRocketPropellant,
powerOffDrag,
powerOnDrag,
):
"""Initialize Rocket class, process inertial, geometrical and
aerodynamic parameters.
Parameters
----------
motor : Motor
Motor used in the rocket. See Motor class for more information.
mass : int, float
Unloaded rocket total mass (without propelant) in kg.
inertiaI : int, float
Unloaded rocket lateral (perpendicular to axis of symmetry)
moment of inertia (without propelant) in kg m^2.
inertiaZ : int, float
Unloaded rocket axial moment of inertia (without propelant)
in kg m^2.
radius : int, float
Rocket biggest outer radius in meters.
distanceRocketNozzle : int, float
Distance from rocket's unloaded center of mass to nozzle outlet,
in meters. Generally negative, meaning a negative position in the
z axis which has an origin in the rocket's center of mass (with
out propellant) and points towards the nose cone.
distanceRocketPropellant : int, float
Distance from rocket's unloaded center of mass to propellant
center of mass, in meters. Generally negative, meaning a negative
position in the z axis which has an origin in the rocket's center
of mass (with out propellant) and points towards the nose cone.
powerOffDrag : int, float, callable, string, array
Rockets drag coefficient when the motor is off. Can be given as an
entry to the Function class. See help(Function) for more
information. If int or float is given, it is assumed constant. If
callable, string or array is given, it must be a function o Mach
number only.
powerOnDrag : int, float, callable, string, array
Rockets drag coefficient when the motor is on. Can be given as an
entry to the Function class. See help(Function) for more
information. If int or float is given, it is assumed constant. If
callable, string or array is given, it must be a function o Mach
number only.
Returns
-------
None
"""
# Define rocket inertia attributes in SI units
self.mass = mass
self.inertiaI = inertiaI
self.inertiaZ = inertiaZ
self.centerOfMass = distanceRocketPropellant * motor.mass / (mass + motor.mass)
# Define rocket geometrical parameters in SI units
self.radius = radius
self.area = np.pi * self.radius ** 2
# Center of mass distance to points of interest
self.distanceRocketNozzle = distanceRocketNozzle
self.distanceRocketPropellant = distanceRocketPropellant
# Excentricity data initialization
self.cpExcentricityX = 0
self.cpExcentricityY = 0
self.thrustExcentricityY = 0
self.thrustExcentricityX = 0
# Parachute data initialization
self.parachutes = []
# Rail button data initialization
self.railButtons = None
# Aerodynamic data initialization
self.aerodynamicSurfaces = []
self.cpPosition = 0
self.staticMargin = Function(
lambda x: 0, inputs="Time (s)", outputs="Static Margin (c)"
)
# Define aerodynamic drag coefficients
self.powerOffDrag = Function(
powerOffDrag,
"Mach Number",
"Drag Coefficient with Power Off",
"spline",
"constant",
)
self.powerOnDrag = Function(
powerOnDrag,
"Mach Number",
"Drag Coefficient with Power On",
"spline",
"constant",
)
# Define motor to be used
self.motor = motor
# Important dynamic inertial quantities
self.reducedMass = None
self.totalMass = None
# Calculate dynamic inertial quantities
self.evaluateReducedMass()
self.evaluateTotalMass()
self.thrustToWeight = self.motor.thrust/(9.80665*self.totalMass)
self.thrustToWeight.setInputs('Time (s)')
self.thrustToWeight.setOutputs('Thrust/Weight')
return None
def evaluateReducedMass(self):
"""Calculates and returns the rocket's total reduced mass. The
reduced mass is defined as the product of the propellant mass
and the mass of the rocket with outpropellant, divided by the
sum of the propellant mass and the rocket mass. The function
returns a object of the Function class and is defined as a
function of time.
Parameters
----------
None
Returns
-------
self.reducedMass : Function
Function of time expressing the reduced mass of the rocket,
defined as the product of the propellant mass and the mass
of the rocket without propellant, divided by the sum of the
propellant mass and the rocket mass.
"""
# Make sure there is a motor associated with the rocket
if self.motor is None:
print("Please associate this rocket with a motor!")
return False
# Retrieve propellant mass as a function of time
motorMass = self.motor.mass
# Retrieve constant rocket mass with out propellant
mass = self.mass
# Calculate reduced mass
self.reducedMass = motorMass * mass / (motorMass + mass)
self.reducedMass.setOutputs("Reduced Mass (kg)")
# Return reduced mass
return self.reducedMass
def evaluateTotalMass(self):
"""Calculates and returns the rocket's total mass. The total
mass is defined as the sum of the propellant mass and the
rocket mass without propellant. The function returns an object
of the Function class and is defined as a function of time.
Parameters
----------
None
Returns
-------
self.totalMass : Function
Function of time expressing the total mass of the rocket,
defined as the sum of the propellant mass and the rocket
mass without propellant.
"""
# Make sure there is a motor associated with the rocket
if self.motor is None:
print("Please associate this rocket with a motor!")
return False
# Calculate total mass by summing up propellant and dry mass
self.totalMass = self.mass + self.motor.mass
self.totalMass.setOutputs("Total Mass (Rocket + Propellant) (kg)")
# Return total mass
return self.totalMass
def evaluateStaticMargin(self):
"""Calculates and returns the rocket's static margin when
loaded with propellant. The static margin is saved and returned
in units of rocket diameter or calibers.
Parameters
----------
None
Returns
-------
self.staticMargin : float
Float value corresponding to rocket static margin when
loaded with propellant in units of rocket diameter or
calibers.
"""
# Initialize total lift coeficient derivative and center of pressure
self.totalLiftCoeffDer = 0
self.cpPosition = 0
# Calculate total lift coeficient derivative and center of pressure
if len(self.aerodynamicSurfaces) > 0:
for aerodynamicSurface in self.aerodynamicSurfaces:
self.totalLiftCoeffDer += aerodynamicSurface[1]
self.cpPosition += aerodynamicSurface[1] * aerodynamicSurface[0][2]
self.cpPosition /= self.totalLiftCoeffDer
# Calculate static margin
self.staticMargin = (self.centerOfMass - self.cpPosition) / (2 * self.radius)
self.staticMargin.setInputs("Time (s)")
self.staticMargin.setOutputs("Static Margin (c)")
# Return self
return self
def addTail(self, topRadius, bottomRadius, length, distanceToCM):
"""Create a new tail or rocket diameter change, storing its
parameters as part of the aerodynamicSurfaces list. Its
parameters are the axial position along the rocket and its
derivative of the coefficient of lift in respect to angle of
attack.
Parameters
----------
topRadius : int, float
Tail top radius in meters, considering positive direction
from center of mass to nose cone.
bottomRadius : int, float
Tail bottom radius in meters, considering positive direction
from center of mass to nose cone.
length : int, float
Tail length or height in meters. Must be a positive value.
distanceToCM : int, float
Tail position relative to rocket unloaded center of mass,
considering positive direction from center of mass to nose
cone. Consider the point belonging to the tail which is
closest to the unloaded center of mass to calculate
distance.
Returns
-------
self : Rocket
Object of the Rocket class.
"""
# Calculate ratio between top and bottom radius
r = topRadius / bottomRadius
# Retrieve reference radius
rref = self.radius
# Calculate cp position relative to cm
if distanceToCM < 0:
cpz = distanceToCM - (length / 3) * (1 + (1 - r) / (1 - r ** 2))
else:
cpz = distanceToCM + (length / 3) * (1 + (1 - r) / (1 - r ** 2))
# Calculate clalpha
clalpha = -2 * (1 - r ** (-2)) * (topRadius / rref) ** 2
# Store values as new aerodynamic surface
tail = [(0, 0, cpz), clalpha, "Tail"]
self.aerodynamicSurfaces.append(tail)
# Refresh static margin calculation
self.evaluateStaticMargin()
# Return self
return self.aerodynamicSurfaces[-1]
def addNose(self, length, kind, distanceToCM):
"""Create a nose cone, storing its parameters as part of the
aerodynamicSurfaces list. Its parameters are the axial position
along the rocket and its derivative of the coefficient of lift
in respect to angle of attack.
Parameters
----------
length : int, float
Nose cone length or height in meters. Must be a postive
value.
kind : string
Nose cone type. Von Karman, conical, ogive, and lvhaack are
supported.
distanceToCM : int, float
Nose cone position relative to rocket unloaded center of
mass, considering positive direction from center of mass to
nose cone. Consider the center point belonging to the nose
cone base to calculate distance.
Returns
-------
self : Rocket
Object of the Rocket class.
"""
# Analyze type
if kind == "conical":
k = 1 - 1 / 3
elif kind == "ogive":
k = 1 - 0.534
elif kind == "lvhaack":
k = 1 - 0.437
else:
k = 0.5
# Calculate cp position relative to cm
if distanceToCM > 0:
cpz = distanceToCM + k * length
else:
cpz = distanceToCM - k * length
# Calculate clalpha
clalpha = 2
# Store values
nose = [(0, 0, cpz), clalpha, "Nose Cone"]
self.aerodynamicSurfaces.append(nose)
# Refresh static margin calculation
self.evaluateStaticMargin()
# Return self
return self.aerodynamicSurfaces[-1]
def addFins(self, n, span, rootChord, tipChord, distanceToCM, radius=0):
"""Create a fin set, storing its parameters as part of the
aerodynamicSurfaces list. Its parameters are the axial position
along the rocket and its derivative of the coefficient of lift
in respect to angle of attack.
Parameters
----------
n : int
Number of fins, from 2 to infinity.
span : int, float
Fin span in meters.
rootChord : int, float
Fin root chord in meters.
tipChord : int, float
Fin tip chord in meters.
distanceToCM : int, float
Fin set position relative to rocket unloaded center of
mass, considering positive direction from center of mass to
nose cone. Consider the center point belonging to the top
of the fins to calculate distance.
radius : int, float, optional
Reference radius to calculate lift coefficient. If 0, which
is default, use rocket radius. Otherwise, enter the radius
of the rocket in the section of the fins, as this impacts
its lift coefficient.
Returns
-------
self : Rocket
Object of the Rocket class.
"""
# Retrieve parameters for calculations
Cr = rootChord
Ct = tipChord
Yr = rootChord + tipChord
s = span
Lf = np.sqrt((rootChord / 2 - tipChord / 2) ** 2 + span ** 2)
radius = self.radius if radius == 0 else radius
d = 2 * radius
# Save geometric parameters for later Fin Flutter Analysis
self.rootChord = Cr
self.tipChord = Ct
self.span = s
self.distanceRocketFins = distanceToCM
# Calculate cp position relative to cm
if distanceToCM < 0:
cpz = distanceToCM - (
((Cr - Ct) / 3) * ((Cr + 2 * Ct) / (Cr + Ct))
+ (1 / 6) * (Cr + Ct - Cr * Ct / (Cr + Ct))
)
else:
cpz = distanceToCM + (
((Cr - Ct) / 3) * ((Cr + 2 * Ct) / (Cr + Ct))
+ (1 / 6) * (Cr + Ct - Cr * Ct / (Cr + Ct))
)
# Calculate clalpha
clalpha = (4 * n * (s / d) ** 2) / (1 + np.sqrt(1 + (2 * Lf / Yr) ** 2))
clalpha *= 1 + radius / (s + radius)
# Store values
fin = [(0, 0, cpz), clalpha, "Fins"]
self.aerodynamicSurfaces.append(fin)
# Refresh static margin calculation
self.evaluateStaticMargin()
# Return self
return self.aerodynamicSurfaces[-1]
def addParachute(
self, name, CdS, trigger, samplingRate=100, lag=0, noise=(0, 0, 0)
):
"""Create a new parachute, storing its parameters such as
opening delay, drag coefficients and trigger function.
Parameters
----------
name : string
Parachute name, such as drogue and main. Has no impact in
simulation, as it is only used to display data in a more
organized matter.
CdS : float
Drag coefficient times reference area for parachute. It is
used to compute the drag force exerted on the parachute by
the equation F = ((1/2)*rho*V^2)*CdS, that is, the drag
force is the dynamic pressure computed on the parachute
times its CdS coefficient. Has units of area and must be
given in meters squared.
trigger : function
Function which defines if the parachute ejection system is
to be triggered. It must take as input the freestream
pressure in pascal and the state vector of the simulation,
which is defined by [x, y, z, vx, vy, vz, e0, e1, e2, e3, wx, wy, wz].
It will be called according to the sampling rate given next.
It should return True if the parachute ejection system is
to be triggered and False otherwise.
samplingRate : float, optional
Sampling rate in which the trigger function works. It is used to
simulate the refresh rate of onboard sensors such as barometers.
Default value is 100. Value must be given in Hertz.
lag : float, optional
Time between the parachute ejection system is triggered and the
parachute is fully opened. During this time, the simulation will
consider the rocket as flying without a parachute. Default value
is 0. Must be given in seconds.
noise : tupple, list, optional
List in the format (mean, standard deviation, time-correlation).
The values are used to add noise to the pressure signal which is
passed to the trigger function. Default value is (0, 0, 0). Units
are in Pascal.
Returns
-------
parachute : Parachute Object
Parachute object containing trigger, samplingRate, lag, CdS, noise
and name as attributes. Furthermore, it stores cleanPressureSignal,
noiseSignal and noisyPressureSignal which is filled in during
Flight simulation.
"""
# Create an object to serve as the parachute
parachute = type("", (), {})()
# Store Cds coefficient, lag, name and trigger function
parachute.trigger = trigger
parachute.samplingRate = samplingRate
parachute.lag = lag
parachute.CdS = CdS
parachute.name = name
parachute.noiseBias = noise[0]
parachute.noiseDeviation = noise[1]
parachute.noiseCorr = (noise[2], (1 - noise[2] ** 2) ** 0.5)
alpha, beta = parachute.noiseCorr
parachute.noiseSignal = [[-1e-6, np.random.normal(noise[0], noise[1])]]
parachute.noiseFunction = lambda: alpha * parachute.noiseSignal[-1][
1
] + beta * np.random.normal(noise[0], noise[1])
parachute.cleanPressureSignal = []
parachute.noisyPressureSignal = []
# Add parachute to list of parachutes
self.parachutes.append(parachute)
# Return self
return self.parachutes[-1]
def setRailButtons(self, distanceToCM, angularPosition=45):
""" Adds rail buttons to the rocket, allowing for the
calculation of forces exerted by them when the rocket is
slinding in the launch rail. Furthermore, rail buttons are
also needed for the simulation of the planar flight phase,
when the rocket experiences 3 degree of freedom motion while
only one rail button is still in the launch rail.
Parameters
----------
distanceToCM : tuple, list, array
Two values organized in a tuple, list or array which
represent the distance of each of the two rail buttons
to the center of mass of the rocket without propellant.
If the rail button is position above the center of mass,
its distance should be a positive value. If it is below,
its distance should be a negative value. The order does
not matter. All values should be in meters.
angularPosition : float
Angular postion of the rail buttons in degrees measured
as the rotation around the symmetry axis of the rocket
relative to one of the other principal axis.
Default value is 45 degrees, generally used in rockets with
4 fins.
Returns
-------
None
"""
# Order distance to CM
if distanceToCM[0] < distanceToCM[1]:
distanceToCM.reverse()
# Save
self.railButtons = self.railButtonPair(distanceToCM, angularPosition)
return None
def addCMExcentricity(self, x, y):
"""Move line of action of aerodynamic and thrust forces by
equal translation ammount to simulate an excentricity in the
position of the center of mass of the rocket relative to its
geometrical center line. Should not be used together with
addCPExentricity and addThrustExentricity.
Parameters
----------
x : float
Distance in meters by which the CM is to be translated in
the x direction relative to geometrical center line.
y : float
Distance in meters by which the CM is to be translated in
the y direction relative to geometrical center line.
Returns
-------
self : Rocket
Object of the Rocket class.
"""
# Move center of pressure to -x and -y
self.cpExcentricityX = -x
self.cpExcentricityY = -y
# Move thrust center by -x and -y
self.thrustExcentricityY = -x
self.thrustExcentricityX = -y
# Return self
return self
def addCPExentricity(self, x, y):
"""Move line of action of aerodynamic forces to simulate an
excentricity in the position of the center of pressure relative
to the center of mass of the rocket.
Parameters
----------
x : float
Distance in meters by which the CP is to be translated in
the x direction relative to the center of mass axial line.
y : float
Distance in meters by which the CP is to be translated in
the y direction relative to the center of mass axial line.
Returns
-------
self : Rocket
Object of the Rocket class.
"""
# Move center of pressure by x and y
self.cpExcentricityX = x
self.cpExcentricityY = y
# Return self
return self
def addThrustExentricity(self, x, y):
"""Move line of action of thrust forces to simulate a
disalignment of the thrust vector and the center of mass.
Parameters
----------
x : float
Distance in meters by which the the line of action of the
thrust force is to be translated in the x direction
relative to the center of mass axial line.
y : float
Distance in meters by which the the line of action of the
thrust force is to be translated in the x direction
relative to the center of mass axial line.
Returns
-------
self : Rocket
Object of the Rocket class.
"""
# Move thrust line by x and y
self.thrustExcentricityY = x
self.thrustExcentricityX = y
# Return self
return self
def info(self):
"""Prints out a summary of the data and graphs available about
the Rocket.
Parameters
----------
None
Return
------
None
"""
# Print inertia details
print("Inertia Details")
print("Rocket Dry Mass: " + str(self.mass) + " kg (No Propellant)")
print("Rocket Total Mass: " + str(self.totalMass(0)) + " kg (With Propellant)")
# Print rocket geometrical parameters
print("\nGeometrical Parameters")
print("Rocket Radius: " + str(self.radius) + " m")
# Print rocket aerodynamics quantities
print("\nAerodynamics Stability")
print("Initial Static Margin: " + "{:.3f}".format(self.staticMargin(0)) + " c")
print(
"Final Static Margin: "
+ "{:.3f}".format(self.staticMargin(self.motor.burnOutTime))
+ " c"
)
# Print parachute data
for chute in self.parachutes:
print("\n" + chute.name.title() + " Parachute")
print("CdS Coefficient: " + str(chute.CdS) + " m2")
# Show plots
print("\nAerodynamics Plots")
self.powerOnDrag()
# Return None
return None
def allInfo(self):
"""Prints out all data and graphs available about the Rocket.
Parameters
----------
None
Return
------
None
"""
# Print inertia details
print("Inertia Details")
print("Rocket Mass: {:.3f} kg (No Propellant)".format(self.mass))
print("Rocket Mass: {:.3f} kg (With Propellant)".format(self.totalMass(0)))
print("Rocket Inertia I: {:.3f} kg*m2".format(self.inertiaI))
print("Rocket Inertia Z: {:.3f} kg*m2".format(self.inertiaZ))
# Print rocket geometrical parameters
print("\nGeometrical Parameters")
print("Rocket Maximum Radius: " + str(self.radius) + " m")
print("Rocket Frontal Area: " + "{:.6f}".format(self.area) + " m2")
print("\nRocket Distances")
print(
"Rocket Center of Mass - Nozzle Exit Distance: "
+ str(self.distanceRocketNozzle)
+ " m"
)
print(
"Rocket Center of Mass - Propellant Center of Mass Distance: "
+ str(self.distanceRocketPropellant)
+ " m"
)
print(
"Rocket Center of Mass - Rocket Loaded Center of Mass: "
+ "{:.3f}".format(self.centerOfMass(0))
+ " m"
)
print("\nAerodynamic Coponents Parameters")
print("Currently not implemented.")
# Print rocket aerodynamics quantities
print("\nAerodynamics Lift Coefficient Derivatives")
for aerodynamicSurface in self.aerodynamicSurfaces:
name = aerodynamicSurface[-1]
clalpha = aerodynamicSurface[1]
print(
name + " Lift Coefficient Derivative: {:.3f}".format(clalpha) + "/rad"
)
print("\nAerodynamics Center of Pressure")
for aerodynamicSurface in self.aerodynamicSurfaces:
name = aerodynamicSurface[-1]
cpz = aerodynamicSurface[0][2]
print(name + " Center of Pressure to CM: {:.3f}".format(cpz) + " m")
print(
"Distance - Center of Pressure to CM: "
+ "{:.3f}".format(self.cpPosition)
+ " m"
)
print("Initial Static Margin: " + "{:.3f}".format(self.staticMargin(0)) + " c")
print(
"Final Static Margin: "
+ "{:.3f}".format(self.staticMargin(self.motor.burnOutTime))
+ " c"
)
# Print parachute data
for chute in self.parachutes:
print("\n" + chute.name.title() + " Parachute")
print("CdS Coefficient: " + str(chute.CdS) + " m2")
if chute.trigger.__name__ == "<lambda>":
line = getsourcelines(chute.trigger)[0][0]
print(
"Ejection signal trigger: "
+ line.split("lambda ")[1].split(",")[0].split("\n")[0]
)
else:
print("Ejection signal trigger: " + chute.trigger.__name__)
print("Ejection system refresh rate: " + str(chute.samplingRate) + " Hz.")
print(
"Time between ejection signal is triggered and the "
"parachute is fully opened: " + str(chute.lag) + " s"
)
# Show plots
print("\nMass Plots")
self.totalMass()
self.reducedMass()
print("\nAerodynamics Plots")
self.staticMargin()
self.powerOnDrag()
self.powerOffDrag()
self.thrustToWeight.plot(lower=0, upper=self.motor.burnOutTime)
#ax = plt.subplot(415)
#ax.plot( , self.rocket.motor.thrust()/(self.env.g() * self.rocket.totalMass()))
#ax.set_xlim(0, self.rocket.motor.burnOutTime)
#ax.set_xlabel("Time (s)")
#ax.set_ylabel("Thrust/Weight")
#ax.set_title("Thrust-Weight Ratio")
# Return None
return None
def addFin(
self,
numberOfFins=4,
cl=2 * np.pi,
cpr=1,
cpz=1,
gammas=[0, 0, 0, 0],
angularPositions=None,
):
"Hey! I will document this function later"
self.aerodynamicSurfaces = []
pi = np.pi
# Calculate angular postions if not given
if angularPositions is None:
angularPositions = np.array(range(numberOfFins)) * 2 * pi / numberOfFins
else:
angularPositions = np.array(angularPositions) * pi / 180
# Convert gammas to degree
if isinstance(gammas, (int, float)):
gammas = [(pi / 180) * gammas for i in range(numberOfFins)]
else:
gammas = [(pi / 180) * gamma for gamma in gammas]
for i in range(numberOfFins):
# Get angular position and inclination for current fin
angularPosition = angularPositions[i]
gamma = gammas[i]
# Calculate position vector
cpx = cpr * np.cos(angularPosition)
cpy = cpr * np.sin(angularPosition)
positionVector = np.array([cpx, cpy, cpz])
# Calculate chord vector
auxVector = np.array([cpy, -cpx, 0]) / (cpr)
chordVector = (
np.cos(gamma) * np.array([0, 0, 1]) - np.sin(gamma) * auxVector
)
self.aerodynamicSurfaces.append([positionVector, chordVector])
return None
# Variables
railButtonPair = namedtuple("railButtonPair", "distanceToCM angularPosition") | /rocketpyalpha-0.9.6.tar.gz/rocketpyalpha-0.9.6/rocketpy/Rocket.py | 0.869299 | 0.703218 | Rocket.py | pypi |
__author__ = "Giovani Hidalgo Ceotto"
__copyright__ = "Copyright 20XX, Projeto Jupiter"
__license__ = "MIT"
import re
import math
import bisect
import warnings
import time
from datetime import datetime, timedelta
from inspect import signature, getsourcelines
from collections import namedtuple
import numpy as np
from scipy import integrate
from scipy import linalg
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from .Function import Function
class SolidMotor:
"""Class to specify characteriscts and useful operations for solid
motors.
Attributes
----------
Geometrical attributes:
Motor.nozzleRadius : float
Radius of motor nozzle outlet in meters.
Motor.throatRadius : float
Radius of motor nozzle throat in meters.
Motor.grainNumber : int
Number os solid grains.
Motor.grainSeparation : float
Distance between two grains in meters.
Motor.grainDensity : float
Density of each grain in kg/meters cubed.
Motor.grainOuterRadius : float
Outer radius of each grain in meters.
Motor.grainInitialInnerRadius : float
Initial inner radius of each grain in meters.
Motor.grainInitialHeight : float
Initial height of each grain in meters.
Motor.grainInitialVolume : float
Initial volume of each grain in meters cubed.
Motor.grainInnerRadius : Function
Inner radius of each grain in meters as a function of time.
Motor.grainHeight : Function
Height of each grain in meters as a function of time.
Mass and moment of inertia attributes:
Motor.grainInitialMass : float
Initial mass of each grain in kg.
Motor.propellantInitialMass : float
Total propellant initial mass in kg.
Motor.mass : Function
Propellant total mass in kg as a function of time.
Motor.massDot : Function
Time derivative of propellant total mass in kg/s as a function
of time.
Motor.inertiaI : Function
Propellant moment of inertia in kg*meter^2 with respect to axis
perpendicular to axis of cylindrical symmetry of each grain,
given as a function of time.
Motor.inertiaIDot : Function
Time derivative of inertiaI given in kg*meter^2/s as a function
of time.
Motor.inertiaZ : Function
Propellant moment of inertia in kg*meter^2 with respect to axis of
cylindrical symmetry of each grain, given as a function of time.
Motor.inertiaDot : Function
Time derivative of inertiaZ given in kg*meter^2/s as a function
of time.
Thrust and burn attributes:
Motor.thrust : Function
Motor thrust force, in Newtons, as a function of time.
Motor.totalImpulse : float
Total impulse of the thrust curve in N*s.
Motor.maxThrust : float
Maximum thrust value of the given thrust curve, in N.
Motor.maxThrustTime : float
Time, in seconds, in which the maximum thrust value is achieved.
Motor.averageThrust : float
Average thrust of the motor, given in N.
Motor.burnOutTime : float
Total motor burn out time, in seconds. Must include delay time
when motor takes time to ignite. Also seen as time to end thrust
curve.
Motor.exhaustVelocity : float
Propulsion gases exhaust velocity, assumed constant, in m/s.
Motor.burnArea : Function
Total burn area considering all grains, made out of inner
cylindrical burn area and grain top and bottom faces. Expressed
in meters squared as a function of time.
Motor.Kn : Function
Motor Kn as a function of time. Defined as burnArea divided by
nozzle throat cross sectional area. Has no units.
Motor.burnRate : Function
Propellant burn rate in meter/second as a function of time.
Motor.interpolate : string
Method of interpolation used in case thrust curve is given
by data set in .csv or .eng, or as an array. Options are 'spline'
'akima' and 'linear'. Default is "linear".
"""
def __init__(
self,
thrustSource,
burnOut,
grainNumber,
grainDensity,
grainOuterRadius,
grainInitialInnerRadius,
grainInitialHeight,
grainSeparation=0,
nozzleRadius=0.0335,
throatRadius=0.0114,
reshapeThrustCurve=False,
interpolationMethod="linear",
):
"""Initialize Motor class, process thrust curve and geometrical
parameters and store results.
Parameters
----------
thrustSource : int, float, callable, string, array
Motor's thrust curve. Can be given as an int or float, in which
case the thrust will be considerared constant in time. It can
also be given as a callable function, whose argument is time in
seconds and returns the thrust supplied by the motor in the
instant. If a string is given, it must point to a .csv or .eng file.
The .csv file shall contain no headers and the first column must
specify time in seconds, while the second column specifies thrust.
Arrays may also be specified, following rules set by the class
Function. See help(Function). Thrust units is Newtons.
burnOut : int, float
Motor burn out time in seconds.
grainNumber : int
Number of solid grains
grainDensity : int, float
Solid grain density in kg/m3.
grainOuterRadius : int, float
Solid grain outer radius in meters.
grainInitialInnerRadius : int, float
Solid grain initial inner radius in meters.
grainInitialHeight : int, float
Solid grain initial height in meters.
grainSeparation : int, float, optional
Distance between grains, in meters. Default is 0.
nozzleRadius : int, float, optional
Motor's nozzle outlet radius in meters. Used to calculate Kn curve.
Optional if Kn curve is not if intereste. Its value does not impact
trajectory simulation.
throatRadius : int, float, optional
Motor's nozzle throat radius in meters. Its value has very low
impact in trajectory simulation, only useful to analyze
dynamic instabilities, therefore it is optional.
reshapeThrustCurve : boolean, tuple, optional
If False, the original thrust curve supplied is not altered. If a
tuple is given, whose first parameter is a new burn out time and
whose second parameter is a new total impulse in Ns, the thrust
curve is reshaped to match the new specifications. May be useful
for motors whose thrust curve shape is expected to remain similar
in case the impulse and burn time varies slightly. Default is
False.
interpolationMethod : string, optional
Method of interpolation to be used in case thrust curve is given
by data set in .csv or .eng, or as an array. Options are 'spline'
'akima' and 'linear'. Default is "linear".
Returns
-------
None
"""
# Thrust parameters
self.interpolate = interpolationMethod
self.burnOutTime = burnOut
# Check if thrustSource is csv, eng, function or other
if isinstance(thrustSource, str):
# Determine if csv or eng
if thrustSource[-3:] == "eng":
# Import content
comments, desc, points = self.importEng(thrustSource)
# Process description and points
# diameter = float(desc[1])/1000
# height = float(desc[2])/1000
# mass = float(desc[4])
# nozzleRadius = diameter/4
# throatRadius = diameter/8
# grainNumber = grainnumber
# grainVolume = height*np.pi*((diameter/2)**2 -(diameter/4)**2)
# grainDensity = mass/grainVolume
# grainOuterRadius = diameter/2
# grainInitialInnerRadius = diameter/4
# grainInitialHeight = height
thrustSource = points
self.burnOutTime = points[-1][0]
# Create thrust function
self.thrust = Function(
thrustSource, "Time (s)", "Thrust (N)", self.interpolate, "zero"
)
if callable(thrustSource) or isinstance(thrustSource, (int, float)):
self.thrust.setDiscrete(0, burnOut, 50, self.interpolate, "zero")
# Reshape curve and calculate impulse
if reshapeThrustCurve:
self.reshapeThrustCurve(*reshapeThrustCurve)
else:
self.evaluateTotalImpulse()
# Define motor attributes
# Grain and nozzle parameters
self.nozzleRadius = nozzleRadius
self.throatRadius = throatRadius
self.grainNumber = grainNumber
self.grainSeparation = grainSeparation
self.grainDensity = grainDensity
self.grainOuterRadius = grainOuterRadius
self.grainInitialInnerRadius = grainInitialInnerRadius
self.grainInitialHeight = grainInitialHeight
# Other quantities that will be computed
self.exhaustVelocity = None
self.massDot = None
self.mass = None
self.grainInnerRadius = None
self.grainHeight = None
self.burnArea = None
self.Kn = None
self.burnRate = None
self.inertiaI = None
self.inertiaIDot = None
self.inertiaZ = None
self.inertiaDot = None
self.maxThrust = None
self.maxThrustTime = None
self.averageThrust = None
# Compute uncalculated quantities
# Thrust information - maximum and average
self.maxThrust = np.amax(self.thrust.source[:, 1])
maxThrustIndex = np.argmax(self.thrust.source[:, 1])
self.maxThrustTime = self.thrust.source[maxThrustIndex, 0]
self.averageThrust = self.totalImpulse / self.burnOutTime
# Grains initial geometrical parameters
self.grainInitialVolume = (
self.grainInitialHeight
* np.pi
* (self.grainOuterRadius ** 2 - self.grainInitialInnerRadius ** 2)
)
self.grainInitialMass = self.grainDensity * self.grainInitialVolume
self.propellantInitialMass = self.grainNumber * self.grainInitialMass
# Dynamic quantities
self.evaluateExhaustVelocity()
self.evaluateMassDot()
self.evaluateMass()
self.evaluateGeometry()
self.evaluateInertia()
def reshapeThrustCurve(
self, burnTime, totalImpulse, oldTotalImpulse=None, startAtZero=True
):
"""Transforms the thrust curve supplied by changing its total
burn time and/or its total impulse, without altering the
general shape of the curve. May translate the curve so that
thrust starts at time equals 0, with out any delays.
Parameters
----------
burnTime : float
New desired burn out time in seconds.
totalImpulse : float
New desired total impulse.
oldTotalImpulse : float, optional
Specify the total impulse of the given thrust curve,
overriding the value calculated by numerical integration.
If left as None, the value calculated by numerical
integration will be used in order to reshape the curve.
startAtZero: bool, optional
If True, trims the initial thrust curve points which
are 0 Newtons, translating the thrust curve so that
thrust starts at time equals 0. If False, no translation
is applied.
Returns
-------
None
"""
# Retrieve current thrust curve data points
timeArray = self.thrust.source[:, 0]
thrustArray = self.thrust.source[:, 1]
# Move start to time = 0
if startAtZero and timeArray[0] != 0:
timeArray = timeArray - timeArray[0]
# Reshape time - set burn time to burnTime
self.thrust.source[:, 0] = (burnTime / timeArray[-1]) * timeArray
self.burnOutTime = burnTime
self.thrust.setInterpolation(self.interpolate)
# Reshape thrust - set total impulse
if oldTotalImpulse is None:
oldTotalImpulse = self.evaluateTotalImpulse()
self.thrust.source[:, 1] = (totalImpulse / oldTotalImpulse) * thrustArray
self.thrust.setInterpolation(self.interpolate)
# Store total impulse
self.totalImpulse = totalImpulse
# Return reshaped curve
return self.thrust
def evaluateTotalImpulse(self):
"""Calculates and returns total impulse by numerical
integration of the thrust curve in SI units. The value is
also stored in self.totalImpulse.
Parameters
----------
None
Returns
-------
self.totalImpulse : float
Motor total impulse in Ns.
"""
# Calculate total impulse
self.totalImpulse = self.thrust.integral(0, self.burnOutTime)
# Return total impulse
return self.totalImpulse
def evaluateExhaustVelocity(self):
"""Calculates and returns exhaust velocity by assuming it
as a constant. The formula used is total impulse/propellant
initial mass. The value is also stored in
self.exhaustVelocity.
Parameters
----------
None
Returns
-------
self.exhaustVelocity : float
Constant gas exhaust velocity of the motor.
"""
# Calculate total impulse if not yet done so
if self.totalImpulse is None:
self.evaluateTotalImpulse()
# Calculate exhaust velocity
self.exhaustVelocity = self.totalImpulse / self.propellantInitialMass
# Return exhaust velocity
return self.exhaustVelocity
def evaluateMassDot(self):
"""Calculates and returns the time derivative of propellant
mass by assuming constant exhaust velocity. The formula used
is the opposite of thrust divided by exhaust velocity. The
result is a function of time, object of the Function class,
which is stored in self.massDot.
Parameters
----------
None
Returns
-------
self.massDot : Function
Time derivative of total propellant mas as a function
of time.
"""
# Calculate exhaust velocity if not done so already
if self.exhaustVelocity is None:
self.evaluateExhaustVelocity()
# Create mass dot Function
self.massDot = self.thrust / (-self.exhaustVelocity)
self.massDot.setOutputs("Mass Dot (kg/s)")
self.massDot.setExtrapolation("zero")
# Return Function
return self.massDot
def evaluateMass(self):
"""Calculates and returns the total propellant mass curve by
numerically integrating the MassDot curve, calculated in
evaluateMassDot. Numerical integration is done with the
Trapezoidal Rule, given the same result as scipy.integrate.
odeint but 100x faster. The result is a function of time,
object of the class Function, which is stored in self.mass.
Parameters
----------
None
Returns
-------
self.mass : Function
Total propellant mass as a function of time.
"""
# Retrieve mass dot curve data
t = self.massDot.source[:, 0]
ydot = self.massDot.source[:, 1]
# Set initial conditions
T = [0]
y = [self.propellantInitialMass]
# Solve for each time point
for i in range(1, len(t)):
T += [t[i]]
y += [y[i - 1] + 0.5 * (t[i] - t[i - 1]) * (ydot[i] + ydot[i - 1])]
# Create Function
self.mass = Function(
np.concatenate(([T], [y])).transpose(),
"Time (s)",
"Propellant Total Mass (kg)",
self.interpolate,
"constant",
)
# Return Mass Function
return self.mass
def evaluateGeometry(self):
"""Calculates grain inner radius and grain height as a
function of time by assuming that every propellant mass
burnt is exhausted. In order to do that, a system of
differential equations is solved using scipy.integrate.
odeint. Furthermore, the function calculates burn area,
burn rate and Kn as a function of time using the previous
results. All functions are stored as objects of the class
Function in self.grainInnerRadius, self.grainHeight, self.
burnArea, self.burnRate and self.Kn.
Parameters
----------
None
Returns
-------
geometry : list of Functions
First element is the Function representing the inner
radius of a grain as a function of time. Second
argument is the Function representing the height of a
grain as a function of time.
"""
# Define initial conditions for integration
y0 = [self.grainInitialInnerRadius, self.grainInitialHeight]
# Define time mesh
t = self.massDot.source[:, 0]
# Define system of differential equations
density = self.grainDensity
rO = self.grainOuterRadius
def geometryDot(y, t):
grainMassDot = self.massDot(t) / self.grainNumber
rI, h = y
rIDot = (
-0.5 * grainMassDot / (density * np.pi * (rO ** 2 - rI ** 2 + rI * h))
)
hDot = 1.0 * grainMassDot / (density * np.pi * (rO ** 2 - rI ** 2 + rI * h))
return [rIDot, hDot]
# Solve the system of differential equations
sol = integrate.odeint(geometryDot, y0, t)
# Write down functions for innerRadius and height
self.grainInnerRadius = Function(
np.concatenate(([t], [sol[:, 0]])).transpose().tolist(),
"Time (s)",
"Grain Inner Radius (m)",
self.interpolate,
"constant",
)
self.grainHeight = Function(
np.concatenate(([t], [sol[:, 1]])).transpose().tolist(),
"Time (s)",
"Grain Height (m)",
self.interpolate,
"constant",
)
# Create functions describing burn rate, Kn and burn area
# Burn Area
self.burnArea = (
2
* np.pi
* (
self.grainOuterRadius ** 2
- self.grainInnerRadius ** 2
+ self.grainInnerRadius * self.grainHeight
)
* self.grainNumber
)
self.burnArea.setOutputs("Burn Area (m2)")
# Kn
throatArea = np.pi * (self.throatRadius) ** 2
KnSource = (
np.concatenate(
(
[self.grainInnerRadius.source[:, 1]],
[self.burnArea.source[:, 1] / throatArea],
)
).transpose()
).tolist()
self.Kn = Function(
KnSource,
"Grain Inner Radius (m)",
"Kn (m2/m2)",
self.interpolate,
"constant",
)
# Burn Rate
self.burnRate = (-1) * self.massDot / (self.burnArea * self.grainDensity)
self.burnRate.setOutputs("Burn Rate (m/s)")
return [self.grainInnerRadius, self.grainHeight]
def evaluateInertia(self):
"""Calculates propellant inertia I, relative to directions
perpendicular to the rocket body axis and its time derivative
as a function of time. Also calculates propellant inertia Z,
relative to the axial direction, and its time derivative as a
function of time. Products of inertia are assumed null due to
symmetry. The four functions are stored as an object of the
Function class.
Parameters
----------
None
Returns
-------
list of Functions
The first argument is the Function representing inertia I,
while the second argument is the Function representing
inertia Z.
"""
# Inertia I
# Calculate inertia I for each grain
grainMass = self.mass / self.grainNumber
grainMassDot = self.massDot / self.grainNumber
grainNumber = self.grainNumber
grainInertiaI = grainMass * (
(1 / 4) * (self.grainOuterRadius ** 2 + self.grainInnerRadius ** 2)
+ (1 / 12) * self.grainHeight ** 2
)
# Calculate each grain's distance d to propellant center of mass
initialValue = (grainNumber - 1) / 2
d = np.linspace(-initialValue, initialValue, self.grainNumber)
d = d * (self.grainInitialHeight + self.grainSeparation)
# Calculate inertia for all grains
self.inertiaI = grainNumber * (grainInertiaI) + grainMass * np.sum(d ** 2)
self.inertiaI.setOutputs("Propellant Inertia I (kg*m2)")
# Inertia I Dot
# Calculate each grain's inertia I dot
grainInertiaIDot = (
grainMassDot
* (
(1 / 4) * (self.grainOuterRadius ** 2 + self.grainInnerRadius ** 2)
+ (1 / 12) * self.grainHeight ** 2
)
+ grainMass
* ((1 / 2) * self.grainInnerRadius - (1 / 3) * self.grainHeight)
* self.burnRate
)
# Calculate inertia I dot for all grains
self.inertiaIDot = grainNumber * (grainInertiaIDot) + grainMassDot * np.sum(
d ** 2
)
self.inertiaIDot.setOutputs("Propellant Inertia I Dot (kg*m2/s)")
# Inertia Z
self.inertiaZ = (
(1 / 2.0)
* self.mass
* (self.grainOuterRadius ** 2 + self.grainInnerRadius ** 2)
)
self.inertiaZ.setOutputs("Propellant Inertia Z (kg*m2)")
# Inertia Z Dot
self.inertiaZDot = (
(1 / 2.0) * (self.massDot * self.grainOuterRadius ** 2)
+ (1 / 2.0) * (self.massDot * self.grainInnerRadius ** 2)
+ self.mass * self.grainInnerRadius * self.burnRate
)
self.inertiaZDot.setOutputs("Propellant Inertia Z Dot (kg*m2/s)")
return [self.inertiaI, self.inertiaZ]
def importEng(self, fileName):
""" Read content from .eng file and process it, in order to
return the comments, description and data points.
Parameters
----------
fileName : string
Name of the .eng file. E.g. 'test.eng'.
Note that the .eng file must not contain the 0 0 point.
Returns
-------
comments : list
All comments in the .eng file, separeted by line in a list. Each
line is an entry of the list.
description: list
Description of the motor. All attributes are returned separeted in
a list. E.g. "F32 24 124 5-10-15 .0377 .0695 RV\n" is return as
['F32', '24', '124', '5-10-15', '.0377', '.0695', 'RV\n']
dataPoints: list
List of all data points in file. Each data point is an entry in
the returned list and written as a list of two entries.
"""
# Intiailize arrays
comments = []
description = []
dataPoints = [[0, 0]]
# Open and read .eng file
with open(fileName) as file:
for line in file:
if line[0] == ";":
# Extract comment
comments.append(line)
else:
if description == []:
# Extract description
description = line.split(" ")
else:
# Extract thrust curve data points
time, thrust = re.findall(r"[-+]?\d*\.\d+|[-+]?\d+", line)
dataPoints.append([float(time), float(thrust)])
# Return all extract content
return comments, description, dataPoints
def exportEng(self, fileName, motorName):
""" Exports thrust curve data points and motor description to
.eng file format. A description of the format can be found
here: http://www.thrustcurve.org/raspformat.shtml
Parameters
----------
fileName : string
Name of the .eng file to be exported. E.g. 'test.eng'
motorName : string
Name given to motor. Will appear in the description of the
.eng file. E.g. 'Mandioca'
Returns
-------
None
"""
# Open file
file = open(fileName, "w")
# Write first line
file.write(
motorName
+ " {:3.1f} {:3.1f} 0 {:2.3} {:2.3} PJ \n".format(
2000 * self.grainOuterRadius,
1000
* self.grainNumber
* (self.grainInitialHeight + self.grainSeparation),
self.propellantInitialMass,
self.propellantInitialMass,
)
)
# Write thrust curve data points
for item in self.thrust.source[:-1, :]:
time = item[0]
thrust = item[1]
file.write("{:.4f} {:.3f}\n".format(time, thrust))
# Write last line
file.write("{:.4f} {:.3f}\n".format(self.thrust.source[-1, 0], 0))
# Close file
file.close()
return None
def info(self):
"""Prints out a summary of the data and graphs available about
the Motor.
Parameters
----------
None
Return
------
None
"""
# Print motor details
print("\nMotor Details")
print("Total Burning Time: " + str(self.burnOutTime) + " s")
print(
"Total Propellant Mass: "
+ "{:.3f}".format(self.propellantInitialMass)
+ " kg"
)
print(
"Propellant Exhaust Velocity: "
+ "{:.3f}".format(self.exhaustVelocity)
+ " m/s"
)
print("Average Thrust: " + "{:.3f}".format(self.averageThrust) + " N")
print(
"Maximum Thrust: "
+ str(self.maxThrust)
+ " N at "
+ str(self.maxThrustTime)
+ " s after ignition."
)
print("Total Impulse: " + "{:.3f}".format(self.totalImpulse) + " Ns")
# Show plots
print("\nPlots")
self.thrust()
return None
def allInfo(self):
"""Prints out all data and graphs available about the Motor.
Parameters
----------
None
Return
------
None
"""
# Print nozzle details
print("Nozzle Details")
print("Nozzle Radius: " + str(self.nozzleRadius) + " m")
print("Nozzle Throat Radius: " + str(self.throatRadius) + " m")
# Print grain details
print("\nGrain Details")
print("Number of Grains: " + str(self.grainNumber))
print("Grain Spacing: " + str(self.grainSeparation) + " m")
print("Grain Density: " + str(self.grainDensity) + " kg/m3")
print("Grain Outer Radius: " + str(self.grainOuterRadius) + " m")
print("Grain Inner Radius: " + str(self.grainInitialInnerRadius) + " m")
print("Grain Height: " + str(self.grainInitialHeight) + " m")
print("Grain Volume: " + "{:.3f}".format(self.grainInitialVolume) + " m3")
print("Grain Mass: " + "{:.3f}".format(self.grainInitialMass) + " kg")
# Print motor details
print("\nMotor Details")
print("Total Burning Time: " + str(self.burnOutTime) + " s")
print(
"Total Propellant Mass: "
+ "{:.3f}".format(self.propellantInitialMass)
+ " kg"
)
print(
"Propellant Exhaust Velocity: "
+ "{:.3f}".format(self.exhaustVelocity)
+ " m/s"
)
print("Average Thrust: " + "{:.3f}".format(self.averageThrust) + " N")
print(
"Maximum Thrust: "
+ str(self.maxThrust)
+ " N at "
+ str(self.maxThrustTime)
+ " s after ignition."
)
print("Total Impulse: " + "{:.3f}".format(self.totalImpulse) + " Ns")
# Show plots
print("\nPlots")
self.thrust()
self.mass()
self.massDot()
self.grainInnerRadius()
self.grainHeight()
self.burnRate()
self.burnArea()
self.Kn()
self.inertiaI()
self.inertiaIDot()
self.inertiaZ()
self.inertiaZDot()
return None | /rocketpyalpha-0.9.6.tar.gz/rocketpyalpha-0.9.6/rocketpy/SolidMotor.py | 0.879095 | 0.587943 | SolidMotor.py | pypi |
__author__ = "Giovani Hidalgo Ceotto"
__copyright__ = "Copyright 20XX, Projeto Jupiter"
__license__ = "MIT"
import re
import math
import bisect
import warnings
import time
from datetime import datetime, timedelta
from inspect import signature, getsourcelines
from collections import namedtuple
import numpy as np
from scipy import integrate
from scipy import linalg
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from .Function import Function
class Flight:
"""Keeps all flight information and has a method to simulate flight.
Attributes
----------
Other classes:
Flight.env : Environment
Environment object describing rail length, elevation, gravity and
weather condition. See Environment class for more details.
Flight.rocket : Rocket
Rocket class describing rocket. See Rocket class for more
details.
Flight.parachutes : Parachutes
Direct link to parachutes of the Rocket. See Rocket class
for more details.
Flight.frontalSurfaceWind : float
Surface wind speed in m/s aligned with the launch rail.
Flight.lateralSurfaceWind : float
Surface wind speed in m/s perpendicular to launch rail.
Helper classes:
Flight.flightPhases : class
Helper class to organize and manage different flight phases.
Flight.timeNodes : class
Helper class to manage time discretization during simulation.
Helper functions:
Flight.timeIterator : function
Helper iterator function to generate time discretization points.
Helper parameters:
Flight.effective1RL : float
Original rail length minus the distance measured from nozzle exit
to the upper rail button. It assumes the nozzle to be aligned with
the beginning of the rail.
Flight.effective2RL : float
Original rail length minus the distance measured from nozzle exit
to the lower rail button. It assumes the nozzle to be aligned with
the beginning of the rail.
Numerical Integration settings:
Flight.maxTime : int, float
Maximum simulation time allowed. Refers to physical time
being simulated, not time taken to run simulation.
Flight.maxTimeStep : int, float
Maximum time step to use during numerical integration in seconds.
Flight.minTimeStep : int, float
Minimum time step to use during numerical integration in seconds.
Flight.rtol : int, float
Maximum relative error tolerance to be tolerated in the
numerical integration scheme.
Flight.atol : int, float
Maximum absolute error tolerance to be tolerated in the
integration scheme.
Flight.timeOvershoot : bool, optional
If True, decouples ODE time step from parachute trigger functions
sampling rate. The time steps can overshoot the necessary trigger
function evaluation points and then interpolation is used to
calculate them and feed the triggers. Can greatly improve run
time in some cases.
Flight.terminateOnApogee : bool
Wheater to terminate simulation when rocket reaches apogee.
Flight.solver : scipy.integrate.LSODA
Scipy LSODA integration scheme.
State Space Vector Definition:
(Only available after Flight.postProcess has been called.)
Flight.x : Function
Rocket's X coordinate (positive east) as a function of time.
Flight.y : Function
Rocket's Y coordinate (positive north) as a function of time.
Flight.z : Function
Rocket's z coordinate (positive up) as a function of time.
Flight.vx : Function
Rocket's X velocity as a function of time.
Flight.vy : Function
Rocket's Y velocity as a function of time.
Flight.vz : Function
Rocket's Z velocity as a function of time.
Flight.e0 : Function
Rocket's Euler parameter 0 as a function of time.
Flight.e1 : Function
Rocket's Euler parameter 1 as a function of time.
Flight.e2 : Function
Rocket's Euler parameter 2 as a function of time.
Flight.e3 : Function
Rocket's Euler parameter 3 as a function of time.
Flight.w1 : Function
Rocket's angular velocity Omega 1 as a function of time.
Direction 1 is in the rocket's body axis and points perpendicular
to the rocket's axis of cylindrical symmetry.
Flight.w2 : Function
Rocket's angular velocity Omega 2 as a function of time.
Direction 2 is in the rocket's body axis and points perpendicular
to the rocket's axis of cylindrical symmetry and direction 1.
Flight.w3 : Function
Rocket's angular velocity Omega 3 as a function of time.
Direction 3 is in the rocket's body axis and points in the
direction of cylindrical symmetry.
Solution attributes:
Flight.inclination : int, float
Launch rail inclination angle relative to ground, given in degrees.
Flight.heading : int, float
Launch heading angle relative to north given in degrees.
Flight.initialSolution : list
List defines initial condition - [tInit, xInit,
yInit, zInit, vxInit, vyInit, vzInit, e0Init, e1Init,
e2Init, e3Init, w1Init, w2Init, w3Init]
Flight.tInitial : int, float
Initial simulation time in seconds. Usually 0.
Flight.solution : list
Solution array which keeps results from each numerical
integration.
Flight.t : float
Current integration time.
Flight.y : list
Current integration state vector u.
Flight.postProcessed : bool
Defines if solution data has been post processed.
Solution monitor attributes:
Flight.initialSolution : list
List defines initial condition - [tInit, xInit,
yInit, zInit, vxInit, vyInit, vzInit, e0Init, e1Init,
e2Init, e3Init, w1Init, w2Init, w3Init]
Flight.outOfRailTime : int, float
Time, in seconds, in which the rocket completely leaves the
rail.
Flight.outOfRailState : list
State vector u corresponding to state when the rocket
completely leaves the rail.
Flight.outOfRailVelocity : int, float
Velocity, in m/s, with which the rocket completely leaves the
rail.
Flight.apogeeState : array
State vector u corresponding to state when the rocket's
vertical velocity is zero in the apogee.
Flight.apogeeTime : int, float
Time, in seconds, in which the rocket's vertical velocity
reaches zero in the apogee.
Flight.apogeeX : int, float
X coordinate (positive east) of the center of mass of the
rocket when it reaches apogee.
Flight.apogeeY : int, float
Y coordinate (positive north) of the center of mass of the
rocket when it reaches apogee.
Flight.apogee : int, float
Z coordinate, or altitute, of the center of mass of the
rocket when it reaches apogee.
Flight.xImpact : int, float
X coordinate (positive east) of the center of mass of the
rocket when it impacts ground.
Flight.yImpact : int, float
Y coordinate (positive east) of the center of mass of the
rocket when it impacts ground.
Flight.impactVelocity : int, float
Velocity magnitude of the center of mass of the rocket when
it impacts ground.
Flight.impactState : array
State vector u corresponding to state when the rocket
impacts the ground.
Flight.parachuteEvents : array
List that stores parachute events triggered during flight.
Flight.functionEvaluations : array
List that stores number of derivative function evaluations
during numerical integration in cumulative manner.
Flight.functionEvaluationsPerTimeStep : array
List that stores number of derivative function evaluations
per time step during numerical integration.
Flight.timeSteps : array
List of time steps taking during numerical integration in
seconds.
Flight.flightPhases : Flight.FlightPhases
Stores and manages flight phases.
Solution Secondary Attributes:
(Only available after Flight.postProcess has been called.)
Atmospheric:
Flight.windVelocityX : Function
Wind velocity X (East) experienced by the rocket as a
function of time. Can be called or accessed as array.
Flight.windVelocityY : Function
Wind velocity Y (North) experienced by the rocket as a
function of time. Can be called or accessed as array.
Flight.density : Function
Air density experienced by the rocket as a function of
time. Can be called or accessed as array.
Flight.pressure : Function
Air pressure experienced by the rocket as a function of
time. Can be called or accessed as array.
Flight.dynamicViscosity : Function
Air dynamic viscosity experienced by the rocket as a function of
time. Can be called or accessed as array.
Flight.speedOfSound : Function
Speed of Sound in air experienced by the rocket as a
function of time. Can be called or accessed as array.
Kinematics:
Flight.ax : Function
Rocket's X (East) acceleration as a function of time, in m/s².
Can be called or accessed as array.
Flight.ay : Function
Rocket's Y (North) acceleration as a function of time, in m/s².
Can be called or accessed as array.
Flight.az : Function
Rocket's Z (Up) acceleration as a function of time, in m/s².
Can be called or accessed as array.
Flight.alpha1 : Function
Rocket's angular acceleration Alpha 1 as a function of time.
Direction 1 is in the rocket's body axis and points perpendicular
to the rocket's axis of cylindrical symmetry.
Units of rad/s². Can be called or accessed as array.
Flight.alpha2 : Function
Rocket's angular acceleration Alpha 2 as a function of time.
Direction 2 is in the rocket's body axis and points perpendicular
to the rocket's axis of cylindrical symmetry and direction 1.
Units of rad/s². Can be called or accessed as array.
Flight.alpha3 : Function
Rocket's angular acceleration Alpha 3 as a function of time.
Direction 3 is in the rocket's body axis and points in the
direction of cylindrical symmetry.
Units of rad/s². Can be called or accessed as array.
Flight.speed : Function
Rocket velocity magnitude in m/s relative to ground as a
function of time. Can be called or accessed as array.
Flight.maxSpeed : float
Maximum velocity magnitude in m/s reached by the rocket
relative to ground during flight.
Flight.maxSpeedTime : float
Time in seconds at which rocket reaches maximum velocity
magnitude relative to ground.
Flight.horizontalSpeed : Function
Rocket's velocity magnitude in the horizontal (North-East)
plane in m/s as a function of time. Can be called or
accessed as array.
Flight.Acceleration : Function
Rocket acceleration magnitude in m/s² relative to ground as a
function of time. Can be called or accessed as array.
Flight.maxAcceleration : float
Maximum acceleration magnitude in m/s² reached by the rocket
relative to ground during flight.
Flight.maxAccelerationTime : float
Time in seconds at which rocket reaches maximum acceleration
magnitude relative to ground.
Flight.pathAngle : Function
Rocket's flight path angle, or the angle that the
rocket's velocity makes with the horizontal (North-East)
plane. Measured in degrees and expressed as a function
of time. Can be called or accessed as array.
Flight.attitudeVectorX : Function
Rocket's attiude vector, or the vector that points
in the rocket's axis of symmetry, component in the X
direction (East) as a function of time.
Can be called or accessed as array.
Flight.attitudeVectorY : Function
Rocket's attiude vector, or the vector that points
in the rocket's axis of symmetry, component in the Y
direction (East) as a function of time.
Can be called or accessed as array.
Flight.attitudeVectorZ : Function
Rocket's attiude vector, or the vector that points
in the rocket's axis of symmetry, component in the Z
direction (East) as a function of time.
Can be called or accessed as array.
Flight.attitudeAngle : Function
Rocket's attiude angle, or the angle that the
rocket's axis of symmetry makes with the horizontal (North-East)
plane. Measured in degrees and expressed as a function
of time. Can be called or accessed as array.
Flight.lateralAttitudeAngle : Function
Rocket's lateral attiude angle, or the angle that the
rocket's axis of symmetry makes with plane defined by
the launch rail direction and the Z (up) axis.
Measured in degrees and expressed as a function
of time. Can be called or accessed as array.
Flight.phi : Function
Rocket's Spin Euler Angle, φ, according to the 3-2-3 rotation
system (NASA Standard Aerospace). Measured in degrees and
expressed as a function of time. Can be called or accessed as array.
Flight.theta : Function
Rocket's Nutation Euler Angle, θ, according to the 3-2-3 rotation
system (NASA Standard Aerospace). Measured in degrees and
expressed as a function of time. Can be called or accessed as array.
Flight.psi : Function
Rocket's Precession Euler Angle, ψ, according to the 3-2-3 rotation
system (NASA Standard Aerospace). Measured in degrees and
expressed as a function of time. Can be called or accessed as array.
Dynamics:
Flight.R1 : Function
Resultant force perpendicular to rockets axis due to
aerodynamic forces as a function of time. Units in N.
Expressed as a function of time. Can be called or accessed
as array.
Direction 1 is in the rocket's body axis and points perpendicular
to the rocket's axis of cylindrical symmetry.
Flight.R2 : Function
Resultant force perpendicular to rockets axis due to
aerodynamic forces as a function of time. Units in N.
Expressed as a function of time. Can be called or accessed
as array.
Direction 2 is in the rocket's body axis and points perpendicular
to the rocket's axis of cylindrical symmetry and direction 1.
Flight.R3 : Function
Resultant force in rockets axis due to aerodynamic forces
as a function of time. Units in N. Usually just drag.
Expressed as a function of time. Can be called or accessed
as array.
Direction 3 is in the rocket's body axis and points in the
direction of cylindrical symmetry.
Flight.M1 : Function
Resultant momentum perpendicular to rockets axis due to
aerodynamic forces and excentricity as a function of time.
Units in N*m.
Expressed as a function of time. Can be called or accessed
as array.
Direction 1 is in the rocket's body axis and points perpendicular
to the rocket's axis of cylindrical symmetry.
Flight.M2 : Function
Resultant momentum perpendicular to rockets axis due to
aerodynamic forces and excentricity as a function of time.
Units in N*m.
Expressed as a function of time. Can be called or accessed
as array.
Direction 2 is in the rocket's body axis and points perpendicular
to the rocket's axis of cylindrical symmetry and direction 1.
Flight.M3 : Function
Resultant momentum in rockets axis due to aerodynamic
forces and excentricity as a function of time. Units in N*m.
Expressed as a function of time. Can be called or accessed
as array.
Direction 3 is in the rocket's body axis and points in the
direction of cylindrical symmetry.
Flight.aerodynamicLift : Function
Resultant force perpendicular to rockets axis due to
aerodynamic effects as a function of time. Units in N.
Expressed as a function of time. Can be called or accessed
as array.
Flight.aerodynamicDrag : Function
Resultant force aligned with the rockets axis due to
aerodynamic effects as a function of time. Units in N.
Expressed as a function of time. Can be called or accessed
as array.
Flight.aerodynamicBendingMoment : Function
Resultant moment perpendicular to rocket's axis due to
aerodynamic effects as a function of time. Units in N m.
Expressed as a function of time. Can be called or accessed
as array.
Flight.aerodynamicSpinMoment : Function
Resultant moment aligned with the rockets axis due to
aerodynamic effects as a function of time. Units in N m.
Expressed as a function of time. Can be called or accessed
as array.
Flight.railButton1NormalForce : Function
Upper rail button normal force in N as a function
of time. Can be called or accessed as array.
Flight.maxRailButton1NormalForce : float
Maximum upper rail button normal force experienced
during rail flight phase in N.
Flight.railButton1ShearForce : Function
Upper rail button shear force in N as a function
of time. Can be called or accessed as array.
Flight.maxRailButton1ShearForce : float
Maximum upper rail button shear force experienced
during rail flight phase in N.
Flight.railButton2NormalForce : Function
Lower rail button normal force in N as a function
of time. Can be called or accessed as array.
Flight.maxRailButton2NormalForce : float
Maximum lower rail button normal force experienced
during rail flight phase in N.
Flight.railButton2ShearForce : Function
Lower rail button shear force in N as a function
of time. Can be called or accessed as array.
Flight.maxRailButton2ShearForce : float
Maximum lower rail button shear force experienced
during rail flight phase in N.
Flight.rotationalEnergy : Function
Rocket's rotational kinetic energy as a function of time.
Units in J.
Flight.translationalEnergy : Function
Rocket's translational kinetic energy as a function of time.
Units in J.
Flight.kineticEnergy : Function
Rocket's total kinetic energy as a function of time.
Units in J.
Flight.potentialEnergy : Function
Rocket's gravitational potential energy as a function of
time. Units in J.
Flight.totalEnergy : Function
Rocket's total mechanical energy as a function of time.
Units in J.
Flight.thrustPower : Function
Rocket's engine thrust power output as a function
of time in Watts. Can be called or accessed as array.
Flight.dragPower : Function
Aerodynamic drag power output as a function
of time in Watts. Can be called or accessed as array.
Stability and Control:
Flight.attitudeFrequencyResponse : Function
Fourier Frequency Analysis of the rocket's attitude angle.
Expressed as the absolute vale of the magnitude as a function
of frequency in Hz. Can be called or accessed as array.
Flight.omega1FrequencyResponse : Function
Fourier Frequency Analysis of the rocket's angular velocity omega 1.
Expressed as the absolute vale of the magnitude as a function
of frequency in Hz. Can be called or accessed as array.
Flight.omega2FrequencyResponse : Function
Fourier Frequency Analysis of the rocket's angular velocity omega 2.
Expressed as the absolute vale of the magnitude as a function
of frequency in Hz. Can be called or accessed as array.
Flight.omega3FrequencyResponse : Function
Fourier Frequency Analysis of the rocket's angular velocity omega 3.
Expressed as the absolute vale of the magnitude as a function
of frequency in Hz. Can be called or accessed as array.
Flight.staticMargin : Function
Rocket's static margin during flight in calibers.
Fluid Mechanics:
Flight.streamVelocityX : Function
Freestream velocity x (East) component, in m/s, as a function of
time. Can be called or accessed as array.
Flight.streamVelocityY : Function
Freestream velocity y (North) component, in m/s, as a function of
time. Can be called or accessed as array.
Flight.streamVelocityZ : Function
Freestream velocity z (up) component, in m/s, as a function of
time. Can be called or accessed as array.
Flight.freestreamSpeed : Function
Freestream velocity magnitude, in m/s, as a function of time.
Can be called or accessed as array.
Flight.apogeeFreestreamSpeed : float
Freestream speed of the rocket at apogee in m/s.
Flight.MachNumber : Function
Rocket's Mach number defined as it's freestream speed
devided by the speed of sound at its altitude. Expressed
as a function of time. Can be called or accessed as array.
Flight.maxMachNumber : float
Rocket's maximum Mach number experienced during flight.
Flight.maxMachNumberTime : float
Time at which the rocket experiences the maximum Mach number.
Flight.ReynoldsNumber : Function
Rocket's Reynolds number, using it's diameter as reference
length and freestreamSpeed as reference velocity. Expressed
as a function of time. Can be called or accessed as array.
Flight.maxReynoldsNumber : float
Rocket's maximum Reynolds number experienced during flight.
Flight.maxReynoldsNumberTime : float
Time at which the rocket experiences the maximum Reynolds number.
Flight.dynamicPressure : Function
Dynamic pressure experienced by the rocket in Pa as a function
of time, defined by 0.5*rho*V^2, where rho is air density and V
is the freestream speed. Can be called or accessed as array.
Flight.maxDynamicPressure : float
Maximum dynamic pressure, in Pa, experienced by the rocket.
Flight.maxDynamicPressureTime : float
Time at which the rocket experiences maximum dynamic pressure.
Flight.totalPressure : Function
Total pressure experienced by the rocket in Pa as a function
of time. Can be called or accessed as array.
Flight.maxTotalPressure : float
Maximum total pressure, in Pa, experienced by the rocket.
Flight.maxTotalPressureTime : float
Time at which the rocket experiences maximum total pressure.
Flight.angleOfAttack : Function
Rocket's angle of attack in degrees as a function of time.
Defined as the minimum angle between the attitude vector and
the freestream velocity vector. Can be called or accessed as
array.
Fin Flutter Analysis:
Flight.flutterMachNumber: Function
The freestream velocity at which begins flutter phenomenon in
rocket's fins. It's expressed as a function of the air pressure
experienced for the rocket. Can be called or accessed as array.
Flight.difference: Function
Difference between flutterMachNumber and machNumber, as a function of time.
Flight.safetyFactor: Function
Ratio between the flutterMachNumber and machNumber, as a function of time.
"""
def __init__(
self,
rocket,
environment,
inclination=80,
heading=90,
initialSolution=None,
terminateOnApogee=False,
maxTime=600,
maxTimeStep=np.inf,
minTimeStep=0,
rtol=1e-6,
atol=6 * [1e-3] + 4 * [1e-6] + 3 * [1e-3],
timeOvershoot=True,
verbose=False,
):
"""Run a trajectory simulation.
Parameters
----------
rocket : Rocket
Rocket to simulate. See help(Rocket) for more information.
environment : Environment
Environment to run simulation on. See help(Environment) for
more information.
inclination : int, float, optional
Rail inclination angle relative to ground, given in degrees.
Default is 80.
heading : int, float, optional
Heading angle relative to north given in degrees.
Default is 90, which points in the x direction.
initialSolution : array, optional
Initial solution array to be used. Format is
initialSolution = [self.tInitial,
xInit, yInit, zInit,
vxInit, vyInit, vzInit,
e0Init, e1Init, e2Init, e3Init,
w1Init, w2Init, w3Init].
If None, the initial solution will start with all null values,
except for the euler parameters which will be calculated based
on given values of inclination and heading. Default is None.
terminateOnApogee : boolean, optioanal
Wheater to terminate simulation when rocket reaches apogee.
Default is False.
maxTime : int, float, optional
Maximum time in which to simulate trajectory in seconds.
Using this without setting a maxTimeStep may cause unexpected
errors. Default is 600.
maxTimeStep : int, float, optional
Maximum time step to use during integration in seconds.
Default is 0.01.
minTimeStep : int, float, optional
Minimum time step to use during integration in seconds.
Default is 0.01.
rtol : float, array, optional
Maximum relative error tolerance to be tolerated in the
integration scheme. Can be given as array for each
state space variable. Default is 1e-3.
atol : float, optional
Maximum absolute error tolerance to be tolerated in the
integration scheme. Can be given as array for each
state space variable. Default is 6*[1e-3] + 4*[1e-6] + 3*[1e-3].
timeOvershoot : bool, optional
If True, decouples ODE time step from parachute trigger functions
sampling rate. The time steps can overshoot the necessary trigger
function evaluation points and then interpolation is used to
calculate them and feed the triggers. Can greatly improve run
time in some cases. Default is True.
verbose : bool, optional
If true, verbose mode is activated. Default is False.
Returns
-------
None
"""
# Fetch helper classes and functions
FlightPhases = self.FlightPhases
TimeNodes = self.TimeNodes
timeIterator = self.timeIterator
# Save rocket, parachutes, environment, maximum simulation time
# and termination events
self.env = environment
self.rocket = rocket
self.parachutes = self.rocket.parachutes[:]
self.inclination = inclination
self.heading = heading
self.maxTime = maxTime
self.maxTimeStep = maxTimeStep
self.minTimeStep = minTimeStep
self.rtol = rtol
self.atol = atol
self.initialSolution = initialSolution
self.timeOvershoot = timeOvershoot
self.terminateOnApogee = terminateOnApogee
# Modifying Rail Length for a better out of rail condition
upperRButton = max(self.rocket.railButtons[0])
lowerRButton = min(self.rocket.railButtons[0])
nozzle = self.rocket.distanceRocketNozzle
self.effective1RL = self.env.rL - abs(nozzle - upperRButton)
self.effective2RL = self.env.rL - abs(nozzle - lowerRButton)
# Flight initialization
# Initialize solution monitors
self.outOfRailTime = 0
self.outOfRailState = np.array([0])
self.outOfRailVelocity = 0
self.apogeeState = np.array([0])
self.apogeeTime = 0
self.apogeeX = 0
self.apogeeY = 0
self.apogee = 0
self.xImpact = 0
self.yImpact = 0
self.impactVelocity = 0
self.impactState = np.array([0])
self.parachuteEvents = []
self.postProcessed = False
# Intialize solver monitors
self.functionEvaluations = []
self.functionEvaluationsPerTimeStep = []
self.timeSteps = []
# Initialize solution state
self.solution = []
if self.initialSolution is None:
# Initialize time and state variables
self.tInitial = 0
xInit, yInit, zInit = 0, 0, self.env.elevation
vxInit, vyInit, vzInit = 0, 0, 0
w1Init, w2Init, w3Init = 0, 0, 0
# Initialize attitude
psiInit = -heading * (np.pi / 180) # Precession / Heading Angle
thetaInit = (inclination - 90) * (np.pi / 180) # Nutation Angle
e0Init = np.cos(psiInit / 2) * np.cos(thetaInit / 2)
e1Init = np.cos(psiInit / 2) * np.sin(thetaInit / 2)
e2Init = np.sin(psiInit / 2) * np.sin(thetaInit / 2)
e3Init = np.sin(psiInit / 2) * np.cos(thetaInit / 2)
# Store initial conditions
self.initialSolution = [
self.tInitial,
xInit,
yInit,
zInit,
vxInit,
vyInit,
vzInit,
e0Init,
e1Init,
e2Init,
e3Init,
w1Init,
w2Init,
w3Init,
]
self.tInitial = self.initialSolution[0]
self.solution.append(self.initialSolution)
self.t = self.solution[-1][0]
self.y = self.solution[-1][1:]
# Calculate normal and lateral surface wind
windU = self.env.windVelocityX(self.env.elevation)
windV = self.env.windVelocityY(self.env.elevation)
headingRad = heading * np.pi / 180
self.frontalSurfaceWind = windU * np.sin(headingRad) + windV * np.cos(
headingRad
)
self.lateralSurfaceWind = -windU * np.cos(headingRad) + windV * np.sin(
headingRad
)
# Create knonw flight phases
self.flightPhases = FlightPhases()
self.flightPhases.addPhase(self.tInitial, self.uDotRail1, clear=False)
self.flightPhases.addPhase(self.maxTime)
# Simulate flight
for phase_index, phase in timeIterator(self.flightPhases):
# print('\nCurrent Flight Phase List')
# print(self.flightPhases)
# print('\n\tCurrent Flight Phase')
# print('\tIndex: ', phase_index, ' | Phase: ', phase)
# Determine maximum time for this flight phase
phase.timeBound = self.flightPhases[phase_index + 1].t
# Evaluate callbacks
for callback in phase.callbacks:
callback(self)
# Create solver for this flight phase
self.functionEvaluations.append(0)
phase.solver = integrate.LSODA(
phase.derivative,
t0=phase.t,
y0=self.y,
t_bound=phase.timeBound,
min_step=self.minTimeStep,
max_step=self.maxTimeStep,
rtol=self.rtol,
atol=self.atol,
)
# print('\n\tSolver Initialization Details')
# print('\tInitial Time: ', phase.t)
# print('\tInitial State: ', self.y)
# print('\tTime Bound: ', phase.timeBound)
# print('\tMin Step: ', self.minTimeStep)
# print('\tMax Step: ', self.maxTimeStep)
# print('\tTolerances: ', self.rtol, self.atol)
# Initialize phase time nodes
phase.timeNodes = TimeNodes()
# Add first time node to permanent list
phase.timeNodes.addNode(phase.t, [], [])
# Add non-overshootable parachute time nodes
if self.timeOvershoot is False:
phase.timeNodes.addParachutes(self.parachutes, phase.t, phase.timeBound)
# Add lst time node to permanent list
phase.timeNodes.addNode(phase.timeBound, [], [])
# Sort time nodes
phase.timeNodes.sort()
# Merge equal time nodes
phase.timeNodes.merge()
# Clear triggers from first time node if necessary
if phase.clear:
phase.timeNodes[0].parachutes = []
phase.timeNodes[0].callbacks = []
# print('\n\tPhase Time Nodes')
# print('\tTime Nodes Length: ', str(len(phase.timeNodes)), ' | Time Nodes Preview: ', phase.timeNodes[0:3])
# Iterate through time nodes
for node_index, node in timeIterator(phase.timeNodes):
# print('\n\t\tCurrent Time Node')
# print('\t\tIndex: ', node_index, ' | Time Node: ', node)
# Determine time bound for this time node
node.timeBound = phase.timeNodes[node_index + 1].t
phase.solver.t_bound = node.timeBound
phase.solver._lsoda_solver._integrator.rwork[0] = phase.solver.t_bound
phase.solver._lsoda_solver._integrator.call_args[
4
] = phase.solver._lsoda_solver._integrator.rwork
phase.solver.status = "running"
# Feed required parachute and discrete controller triggers
for callback in node.callbacks:
callback(self)
for parachute in node.parachutes:
# Calculate and save pressure signal
pressure = self.env.pressure.getValueOpt(self.y[2])
parachute.cleanPressureSignal.append([node.t, pressure])
# Calculate and save noise
noise = parachute.noiseFunction()
parachute.noiseSignal.append([node.t, noise])
parachute.noisyPressureSignal.append([node.t, pressure + noise])
if parachute.trigger(pressure + noise, self.y):
# print('\nEVENT DETECTED')
# print('Parachute Triggered')
# print('Name: ', parachute.name, ' | Lag: ', parachute.lag)
# Remove parachute from flight parachutes
self.parachutes.remove(parachute)
# Create flight phase for time after detection and before inflation
self.flightPhases.addPhase(
node.t, phase.derivative, clear=True, index=phase_index + 1
)
# Create flight phase for time after inflation
callbacks = [
lambda self, parachuteCdS=parachute.CdS: setattr(
self, "parachuteCdS", parachuteCdS
)
]
self.flightPhases.addPhase(
node.t + parachute.lag,
self.uDotParachute,
callbacks,
clear=False,
index=phase_index + 2,
)
# Prepare to leave loops and start new flight phase
phase.timeNodes.flushAfter(node_index)
phase.timeNodes.addNode(self.t, [], [])
phase.solver.status = "finished"
# Save parachute event
self.parachuteEvents.append([self.t, parachute])
# Step through simulation
while phase.solver.status == "running":
# Step
phase.solver.step()
# Save step result
self.solution += [[phase.solver.t, *phase.solver.y]]
# Step step metrics
self.functionEvaluationsPerTimeStep.append(
phase.solver.nfev - self.functionEvaluations[-1]
)
self.functionEvaluations.append(phase.solver.nfev)
self.timeSteps.append(phase.solver.step_size)
# Update time and state
self.t = phase.solver.t
self.y = phase.solver.y
if verbose:
print(
"Current Simulation Time: {:3.4f} s".format(self.t),
end="\r",
)
# print('\n\t\t\tCurrent Step Details')
# print('\t\t\tIState: ', phase.solver._lsoda_solver._integrator.istate)
# print('\t\t\tTime: ', phase.solver.t)
# print('\t\t\tAltitude: ', phase.solver.y[2])
# print('\t\t\tEvals: ', self.functionEvaluationsPerTimeStep[-1])
# Check for first out of rail event
if len(self.outOfRailState) == 1 and (
self.y[0] ** 2
+ self.y[1] ** 2
+ (self.y[2] - self.env.elevation) ** 2
>= self.effective1RL ** 2
):
# Rocket is out of rail
# Check exactly when it went out using root finding
# States before and after
# t0 -> 0
# print('\nEVENT DETECTED')
# print('Rocket is Out of Rail!')
# Disconsider elevation
self.solution[-2][3] -= self.env.elevation
self.solution[-1][3] -= self.env.elevation
# Get points
y0 = (
sum([self.solution[-2][i] ** 2 for i in [1, 2, 3]])
- self.effective1RL ** 2
)
yp0 = 2 * sum(
[
self.solution[-2][i] * self.solution[-2][i + 3]
for i in [1, 2, 3]
]
)
t1 = self.solution[-1][0] - self.solution[-2][0]
y1 = (
sum([self.solution[-1][i] ** 2 for i in [1, 2, 3]])
- self.effective1RL ** 2
)
yp1 = 2 * sum(
[
self.solution[-1][i] * self.solution[-1][i + 3]
for i in [1, 2, 3]
]
)
# Put elevation back
self.solution[-2][3] += self.env.elevation
self.solution[-1][3] += self.env.elevation
# Cubic Hermite interpolation (ax**3 + bx**2 + cx + d)
D = float(phase.solver.step_size)
d = float(y0)
c = float(yp0)
b = float((3 * y1 - yp1 * D - 2 * c * D - 3 * d) / (D ** 2))
a = float(-(2 * y1 - yp1 * D - c * D - 2 * d) / (D ** 3))
# Find roots
d0 = b ** 2 - 3 * a * c
d1 = 2 * b ** 3 - 9 * a * b * c + 27 * d * a ** 2
c1 = ((d1 + (d1 ** 2 - 4 * d0 ** 3) ** (0.5)) / 2) ** (1 / 3)
t_roots = []
for k in [0, 1, 2]:
c2 = c1 * (-1 / 2 + 1j * (3 ** 0.5) / 2) ** k
t_roots.append(-(1 / (3 * a)) * (b + c2 + d0 / c2))
# Find correct root
valid_t_root = []
for t_root in t_roots:
if 0 < t_root.real < t1 and abs(t_root.imag) < 0.001:
valid_t_root.append(t_root.real)
if len(valid_t_root) > 1:
raise ValueError(
"Multiple roots found when solving for rail exit time."
)
# Determine final state when upper button is going out of rail
self.t = valid_t_root[0] + self.solution[-2][0]
interpolator = phase.solver.dense_output()
self.y = interpolator(self.t)
self.solution[-1] = [self.t, *self.y]
self.outOfRailTime = self.t
self.outOfRailState = self.y
self.outOfRailVelocity = (
self.y[3] ** 2 + self.y[4] ** 2 + self.y[5] ** 2
) ** (0.5)
# Create new flight phase
self.flightPhases.addPhase(
self.t, self.uDot, index=phase_index + 1
)
# Prepare to leave loops and start new flight phase
phase.timeNodes.flushAfter(node_index)
phase.timeNodes.addNode(self.t, [], [])
phase.solver.status = "finished"
# Check for apogee event
if len(self.apogeeState) == 1 and self.y[5] < 0:
# print('\nPASSIVE EVENT DETECTED')
# print('Rocket Has Reached Apogee!')
# Apogee reported
# Assume linear vz(t) to detect when vz = 0
vz0 = self.solution[-2][6]
t0 = self.solution[-2][0]
vz1 = self.solution[-1][6]
t1 = self.solution[-1][0]
t_root = -(t1 - t0) * vz0 / (vz1 - vz0) + t0
# Fecth state at t_root
interpolator = phase.solver.dense_output()
self.apogeeState = interpolator(t_root)
# Store apogee data
self.apogeeTime = t_root
self.apogeeX = self.apogeeState[0]
self.apogeeY = self.apogeeState[1]
self.apogee = self.apogeeState[2]
if self.terminateOnApogee:
# print('Terminate on Apogee Activated!')
self.t = t_root
self.tFinal = self.t
self.state = self.apogeeState
# Roll back solution
self.solution[-1] = [self.t, *self.state]
# Set last flight phase
self.flightPhases.flushAfter(phase_index)
self.flightPhases.addPhase(self.t)
# Prepare to leave loops and start new flight phase
phase.timeNodes.flushAfter(node_index)
phase.timeNodes.addNode(self.t, [], [])
phase.solver.status = "finished"
# Check for impact event
if self.y[2] < self.env.elevation:
# print('\nPASSIVE EVENT DETECTED')
# print('Rocket Has Reached Ground!')
# Impact reported
# Check exactly when it went out using root finding
# States before and after
# t0 -> 0
# Disconsider elevation
self.solution[-2][3] -= self.env.elevation
self.solution[-1][3] -= self.env.elevation
# Get points
y0 = self.solution[-2][3]
yp0 = self.solution[-2][6]
t1 = self.solution[-1][0] - self.solution[-2][0]
y1 = self.solution[-1][3]
yp1 = self.solution[-1][6]
# Put elevation back
self.solution[-2][3] += self.env.elevation
self.solution[-1][3] += self.env.elevation
# Cubic Hermite interpolation (ax**3 + bx**2 + cx + d)
D = float(phase.solver.step_size)
d = float(y0)
c = float(yp0)
b = float((3 * y1 - yp1 * D - 2 * c * D - 3 * d) / (D ** 2))
a = float(-(2 * y1 - yp1 * D - c * D - 2 * d) / (D ** 3))
# Find roots
d0 = b ** 2 - 3 * a * c
d1 = 2 * b ** 3 - 9 * a * b * c + 27 * d * a ** 2
c1 = ((d1 + (d1 ** 2 - 4 * d0 ** 3) ** (0.5)) / 2) ** (1 / 3)
t_roots = []
for k in [0, 1, 2]:
c2 = c1 * (-1 / 2 + 1j * (3 ** 0.5) / 2) ** k
t_roots.append(-(1 / (3 * a)) * (b + c2 + d0 / c2))
# Find correct root
valid_t_root = []
for t_root in t_roots:
if 0 < t_root.real < t1 and abs(t_root.imag) < 0.001:
valid_t_root.append(t_root.real)
if len(valid_t_root) > 1:
raise ValueError(
"Multiple roots found when solving for impact time."
)
# Determine impact state at t_root
self.t = valid_t_root[0] + self.solution[-2][0]
interpolator = phase.solver.dense_output()
self.y = interpolator(self.t)
# Roll back solution
self.solution[-1] = [self.t, *self.y]
# Save impact state
self.impactState = self.y
self.xImpact = self.impactState[0]
self.yImpact = self.impactState[1]
self.zImpact = self.impactState[2]
self.impactVelocity = self.impactState[5]
self.tFinal = self.t
# Set last flight phase
self.flightPhases.flushAfter(phase_index)
self.flightPhases.addPhase(self.t)
# Prepare to leave loops and start new flight phase
phase.timeNodes.flushAfter(node_index)
phase.timeNodes.addNode(self.t, [], [])
phase.solver.status = "finished"
# List and feed overshootable time nodes
if self.timeOvershoot:
# Initialize phase overshootable time nodes
overshootableNodes = TimeNodes()
# Add overshootable parachute time nodes
overshootableNodes.addParachutes(
self.parachutes, self.solution[-2][0], self.t
)
# Add last time node (always skipped)
overshootableNodes.addNode(self.t, [], [])
if len(overshootableNodes) > 1:
# Sort overshootable time nodes
overshootableNodes.sort()
# Merge equal overshootable time nodes
overshootableNodes.merge()
# Clear if necessary
if overshootableNodes[0].t == phase.t and phase.clear:
overshootableNodes[0].parachutes = []
overshootableNodes[0].callbacks = []
# print('\n\t\t\t\tOvershootable Time Nodes')
# print('\t\t\t\tInterval: ', self.solution[-2][0], self.t)
# print('\t\t\t\tOvershootable Nodes Length: ', str(len(overshootableNodes)), ' | Overshootable Nodes: ', overshootableNodes)
# Feed overshootable time nodes trigger
interpolator = phase.solver.dense_output()
for overshootable_index, overshootableNode in timeIterator(
overshootableNodes
):
# print('\n\t\t\t\tCurrent Overshootable Node')
# print('\t\t\t\tIndex: ', overshootable_index, ' | Overshootable Node: ', overshootableNode)
# Calculate state at node time
overshootableNode.y = interpolator(overshootableNode.t)
# Calculate and save pressure signal
pressure = self.env.pressure.getValueOpt(
overshootableNode.y[2]
)
for parachute in overshootableNode.parachutes:
# Save pressure signal
parachute.cleanPressureSignal.append(
[overshootableNode.t, pressure]
)
# Calculate and save noise
noise = parachute.noiseFunction()
parachute.noiseSignal.append(
[overshootableNode.t, noise]
)
parachute.noisyPressureSignal.append(
[overshootableNode.t, pressure + noise]
)
if parachute.trigger(
pressure + noise, overshootableNode.y
):
# print('\nEVENT DETECTED')
# print('Parachute Triggered')
# print('Name: ', parachute.name, ' | Lag: ', parachute.lag)
# Remove parachute from flight parachutes
self.parachutes.remove(parachute)
# Create flight phase for time after detection and before inflation
self.flightPhases.addPhase(
overshootableNode.t,
phase.derivative,
clear=True,
index=phase_index + 1,
)
# Create flight phase for time after inflation
callbacks = [
lambda self, parachuteCdS=parachute.CdS: setattr(
self, "parachuteCdS", parachuteCdS
)
]
self.flightPhases.addPhase(
overshootableNode.t + parachute.lag,
self.uDotParachute,
callbacks,
clear=False,
index=phase_index + 2,
)
# Rollback history
self.t = overshootableNode.t
self.y = overshootableNode.y
self.solution[-1] = [
overshootableNode.t,
*overshootableNode.y,
]
# Prepare to leave loops and start new flight phase
overshootableNodes.flushAfter(
overshootable_index
)
phase.timeNodes.flushAfter(node_index)
phase.timeNodes.addNode(self.t, [], [])
phase.solver.status = "finished"
# Save parachute event
self.parachuteEvents.append([self.t, parachute])
self.tFinal = self.t
if verbose:
print("Simulation Completed at Time: {:3.4f} s".format(self.t))
def uDotRail1(self, t, u, postProcessing=False):
"""Calculates derivative of u state vector with respect to time
when rocket is flying in 1 DOF motion in the rail.
Parameters
----------
t : float
Time in seconds
u : list
State vector defined by u = [x, y, z, vx, vy, vz, e0, e1,
e2, e3, omega1, omega2, omega3].
postProcessing : bool, optional
If True, adds flight data information directly to self
variables such as self.attackAngle. Default is False.
Return
------
uDot : list
State vector defined by uDot = [vx, vy, vz, ax, ay, az,
e0Dot, e1Dot, e2Dot, e3Dot, alpha1, alpha2, alpha3].
"""
# Check if post processing mode is on
if postProcessing:
# Use uDot post processing code
return self.uDot(t, u, True)
# Retrieve integration data
x, y, z, vx, vy, vz, e0, e1, e2, e3, omega1, omega2, omega3 = u
# Retrieve important quantities
# Mass
M = self.rocket.totalMass.getValueOpt(t)
# Get freestrean speed
freestreamSpeed = (
(self.env.windVelocityX.getValueOpt(z) - vx) ** 2
+ (self.env.windVelocityY.getValueOpt(z) - vy) ** 2
+ (vz) ** 2
) ** 0.5
freestreamMach = freestreamSpeed / self.env.speedOfSound.getValueOpt(z)
dragCoeff = self.rocket.powerOnDrag.getValueOpt(freestreamMach)
# Calculate Forces
Thrust = self.rocket.motor.thrust.getValueOpt(t)
rho = self.env.density.getValueOpt(z)
R3 = -0.5 * rho * (freestreamSpeed ** 2) * self.rocket.area * (dragCoeff)
# Calculate Linear acceleration
a3 = (R3 + Thrust) / M - (e0 ** 2 - e1 ** 2 - e2 ** 2 + e3 ** 2) * self.env.g
if a3 > 0:
ax = 2 * (e1 * e3 + e0 * e2) * a3
ay = 2 * (e2 * e3 - e0 * e1) * a3
az = (1 - 2 * (e1 ** 2 + e2 ** 2)) * a3
else:
ax, ay, az = 0, 0, 0
return [vx, vy, vz, ax, ay, az, 0, 0, 0, 0, 0, 0, 0]
def uDotRail2(self, t, u, postProcessing=False):
"""[Still not implemented] Calculates derivative of u state vector with
respect to time when rocket is flying in 3 DOF motion in the rail.
Parameters
----------
t : float
Time in seconds
u : list
State vector defined by u = [x, y, z, vx, vy, vz, e0, e1,
e2, e3, omega1, omega2, omega3].
postProcessing : bool, optional
If True, adds flight data information directly to self
variables such as self.attackAngle, by default False
Returns
-------
uDot : list
State vector defined by uDot = [vx, vy, vz, ax, ay, az,
e0Dot, e1Dot, e2Dot, e3Dot, alpha1, alpha2, alpha3].
"""
# Hey! We will finish this function later, now we just can use uDot
return self.uDot(t, u, postProcessing= postProcessing)
def uDot(self, t, u, postProcessing=False):
"""Calculates derivative of u state vector with respect to time
when rocket is flying in 6 DOF motion during ascent out of rail
and descent without parachute.
Parameters
----------
t : float
Time in seconds
u : list
State vector defined by u = [x, y, z, vx, vy, vz, e0, e1,
e2, e3, omega1, omega2, omega3].
postProcessing : bool, optional
If True, adds flight data information directly to self
variables such as self.attackAngle, by default False
Returns
-------
uDot : list
State vector defined by uDot = [vx, vy, vz, ax, ay, az,
e0Dot, e1Dot, e2Dot, e3Dot, alpha1, alpha2, alpha3].
"""
# Retrieve integration data
x, y, z, vx, vy, vz, e0, e1, e2, e3, omega1, omega2, omega3 = u
# Determine lift force and moment
R1, R2 = 0, 0
M1, M2, M3 = 0, 0, 0
# Determine current behaviour
if t < self.rocket.motor.burnOutTime:
# Motor burning
# Retrieve important motor quantities
# Inertias
Tz = self.rocket.motor.inertiaZ.getValueOpt(t)
Ti = self.rocket.motor.inertiaI.getValueOpt(t)
TzDot = self.rocket.motor.inertiaZDot.getValueOpt(t)
TiDot = self.rocket.motor.inertiaIDot.getValueOpt(t)
# Mass
MtDot = self.rocket.motor.massDot.getValueOpt(t)
Mt = self.rocket.motor.mass.getValueOpt(t)
# Thrust
Thrust = self.rocket.motor.thrust.getValueOpt(t)
# Off center moment
M1 += self.rocket.thrustExcentricityX * Thrust
M2 -= self.rocket.thrustExcentricityY * Thrust
else:
# Motor stopped
# Retrieve important motor quantities
# Inertias
Tz, Ti, TzDot, TiDot = 0, 0, 0, 0
# Mass
MtDot, Mt = 0, 0
# Thrust
Thrust = 0
# Retrieve important quantities
# Inertias
Rz = self.rocket.inertiaZ
Ri = self.rocket.inertiaI
# Mass
Mr = self.rocket.mass
M = Mt + Mr
mu = (Mt * Mr) / (Mt + Mr)
# Geometry
b = -self.rocket.distanceRocketPropellant
c = -self.rocket.distanceRocketNozzle
a = b * Mt / M
rN = self.rocket.motor.nozzleRadius
# Prepare transformation matrix
a11 = 1 - 2 * (e2 ** 2 + e3 ** 2)
a12 = 2 * (e1 * e2 - e0 * e3)
a13 = 2 * (e1 * e3 + e0 * e2)
a21 = 2 * (e1 * e2 + e0 * e3)
a22 = 1 - 2 * (e1 ** 2 + e3 ** 2)
a23 = 2 * (e2 * e3 - e0 * e1)
a31 = 2 * (e1 * e3 - e0 * e2)
a32 = 2 * (e2 * e3 + e0 * e1)
a33 = 1 - 2 * (e1 ** 2 + e2 ** 2)
# Transformation matrix: (123) -> (XYZ)
K = [[a11, a12, a13], [a21, a22, a23], [a31, a32, a33]]
# Transformation matrix: (XYZ) -> (123) or K transpose
Kt = [[a11, a21, a31], [a12, a22, a32], [a13, a23, a33]]
# Calculate Forces and Moments
# Get freestrean speed
windVelocityX = self.env.windVelocityX.getValueOpt(z)
windVelocityY = self.env.windVelocityY.getValueOpt(z)
freestreamSpeed = (
(windVelocityX - vx) ** 2 + (windVelocityY - vy) ** 2 + (vz) ** 2
) ** 0.5
freestreamMach = freestreamSpeed / self.env.speedOfSound.getValueOpt(z)
# Determine aerodynamics forces
# Determine Drag Force
if t > self.rocket.motor.burnOutTime:
dragCoeff = self.rocket.powerOnDrag.getValueOpt(freestreamMach)
else:
dragCoeff = self.rocket.powerOffDrag.getValueOpt(freestreamMach)
rho = self.env.density.getValueOpt(z)
R3 = -0.5 * rho * (freestreamSpeed ** 2) * self.rocket.area * (dragCoeff)
# Off center moment
M1 += self.rocket.cpExcentricityY * R3
M2 -= self.rocket.cpExcentricityX * R3
# Get rocket velocity in body frame
vxB = a11 * vx + a21 * vy + a31 * vz
vyB = a12 * vx + a22 * vy + a32 * vz
vzB = a13 * vx + a23 * vy + a33 * vz
# Calculate lift and moment for each component of the rocket
for aerodynamicSurface in self.rocket.aerodynamicSurfaces:
compCp = aerodynamicSurface[0][2]
clalpha = aerodynamicSurface[1]
# Component absolute velocity in body frame
compVxB = vxB + compCp * omega2
compVyB = vyB - compCp * omega1
compVzB = vzB
# Wind velocity at component
compZ = z + compCp
compWindVx = self.env.windVelocityX.getValueOpt(compZ)
compWindVy = self.env.windVelocityY.getValueOpt(compZ)
# Component freestream velocity in body frame
compWindVxB = a11 * compWindVx + a21 * compWindVy
compWindVyB = a12 * compWindVx + a22 * compWindVy
compWindVzB = a13 * compWindVx + a23 * compWindVy
compStreamVxB = compWindVxB - compVxB
compStreamVyB = compWindVyB - compVyB
compStreamVzB = compWindVzB - compVzB
compStreamSpeed = (
compStreamVxB ** 2 + compStreamVyB ** 2 + compStreamVzB ** 2
) ** 0.5
# Component attack angle and lift force
compAttackAngle = 0
compLift, compLiftXB, compLiftYB = 0, 0, 0
if compStreamVxB ** 2 + compStreamVyB ** 2 != 0:
# Normalize component stream velocity in body frame
compStreamVzBn = compStreamVzB / compStreamSpeed
if -1 * compStreamVzBn < 1:
compAttackAngle = np.arccos(-compStreamVzBn)
# Component lift force magnitude
compLift = (
0.5
* rho
* (compStreamSpeed ** 2)
* self.rocket.area
* clalpha
* compAttackAngle
)
# Component lift force components
liftDirNorm = (compStreamVxB ** 2 + compStreamVyB ** 2) ** 0.5
compLiftXB = compLift * (compStreamVxB / liftDirNorm)
compLiftYB = compLift * (compStreamVyB / liftDirNorm)
# Add to total lift force
R1 += compLiftXB
R2 += compLiftYB
# Add to total moment
M1 -= (compCp + a) * compLiftYB
M2 += (compCp + a) * compLiftXB
# Calculate derivatives
# Angular acceleration
alpha1 = (
M1
- (
omega2 * omega3 * (Rz + Tz - Ri - Ti - mu * b ** 2)
+ omega1
* (
(TiDot + MtDot * (Mr - 1) * (b / M) ** 2)
- MtDot * ((rN / 2) ** 2 + (c - b * mu / Mr) ** 2)
)
)
) / (Ri + Ti + mu * b ** 2)
alpha2 = (
M2
- (
omega1 * omega3 * (Ri + Ti + mu * b ** 2 - Rz - Tz)
+ omega2
* (
(TiDot + MtDot * (Mr - 1) * (b / M) ** 2)
- MtDot * ((rN / 2) ** 2 + (c - b * mu / Mr) ** 2)
)
)
) / (Ri + Ti + mu * b ** 2)
alpha3 = (M3 - omega3 * (TzDot - MtDot * (rN ** 2) / 2)) / (Rz + Tz)
# Euler parameters derivative
e0Dot = 0.5 * (-omega1 * e1 - omega2 * e2 - omega3 * e3)
e1Dot = 0.5 * (omega1 * e0 + omega3 * e2 - omega2 * e3)
e2Dot = 0.5 * (omega2 * e0 - omega3 * e1 + omega1 * e3)
e3Dot = 0.5 * (omega3 * e0 + omega2 * e1 - omega1 * e2)
# Linear acceleration
L = [
(R1 - b * Mt * (omega2 ** 2 + omega3 ** 2) - 2 * c * MtDot * omega2) / M,
(R2 + b * Mt * (alpha3 + omega1 * omega2) + 2 * c * MtDot * omega1) / M,
(R3 - b * Mt * (alpha2 - omega1 * omega3) + Thrust) / M,
]
ax, ay, az = np.dot(K, L)
az -= self.env.g # Include gravity
# Create uDot
uDot = [
vx,
vy,
vz,
ax,
ay,
az,
e0Dot,
e1Dot,
e2Dot,
e3Dot,
alpha1,
alpha2,
alpha3,
]
if postProcessing:
# Dynamics variables
self.R1.append([t, R1])
self.R2.append([t, R2])
self.R3.append([t, R3])
self.M1.append([t, M1])
self.M2.append([t, M2])
self.M3.append([t, M3])
# Atmospheric Conditions
self.windVelocityX.append([t, self.env.windVelocityX(z)])
self.windVelocityY.append([t, self.env.windVelocityY(z)])
self.density.append([t, self.env.density(z)])
self.dynamicViscosity.append([t, self.env.dynamicViscosity(z)])
self.pressure.append([t, self.env.pressure(z)])
self.speedOfSound.append([t, self.env.speedOfSound(z)])
return uDot
def uDotParachute(self, t, u, postProcessing=False):
"""Calculates derivative of u state vector with respect to time
when rocket is flying under parachute. A 3 DOF aproximation is
used.
Parameters
----------
t : float
Time in seconds
u : list
State vector defined by u = [x, y, z, vx, vy, vz, e0, e1,
e2, e3, omega1, omega2, omega3].
postProcessing : bool, optional
If True, adds flight data information directly to self
variables such as self.attackAngle. Default is False.
Return
------
uDot : list
State vector defined by uDot = [vx, vy, vz, ax, ay, az,
e0Dot, e1Dot, e2Dot, e3Dot, alpha1, alpha2, alpha3].
"""
# Parachute data
CdS = self.parachuteCdS
ka = 1
R = 1.5
rho = self.env.density.getValueOpt(u[2])
to = 1.2
ma = ka * rho * (4 / 3) * np.pi * R ** 3
mp = self.rocket.mass
eta = 1
Rdot = (6 * R * (1 - eta) / (1.2 ** 6)) * (
(1 - eta) * t ** 5 + eta * (to ** 3) * (t ** 2)
)
Rdot = 0
# Get relevant state data
x, y, z, vx, vy, vz, e0, e1, e2, e3, omega1, omega2, omega3 = u
# Get wind data
windVelocityX = self.env.windVelocityX.getValueOpt(z)
windVelocityY = self.env.windVelocityY.getValueOpt(z)
freestreamSpeed = (
(windVelocityX - vx) ** 2 + (windVelocityY - vy) ** 2 + (vz) ** 2
) ** 0.5
freestreamX = vx - windVelocityX
freestreamY = vy - windVelocityY
freestreamZ = vz
# Determine drag force
pseudoD = -0.5 * rho * CdS * freestreamSpeed - ka * rho * 4 * np.pi * (R ** 2) * Rdot
Dx = pseudoD * freestreamX
Dy = pseudoD * freestreamY
Dz = pseudoD * freestreamZ
ax = Dx / (mp + ma)
ay = Dy / (mp + ma)
az = (Dz - 9.8 * mp) / (mp + ma)
if postProcessing:
# Dynamics variables
self.R1.append([t, Dx])
self.R2.append([t, Dy])
self.R3.append([t, Dz])
self.M1.append([t, 0])
self.M2.append([t, 0])
self.M3.append([t, 0])
# Atmospheric Conditions
self.windVelocityX.append([t, self.env.windVelocityX(z)])
self.windVelocityY.append([t, self.env.windVelocityY(z)])
self.density.append([t, self.env.density(z)])
self.dynamicViscosity.append([t, self.env.dynamicViscosity(z)])
self.pressure.append([t, self.env.pressure(z)])
self.speedOfSound.append([t, self.env.speedOfSound(z)])
return [vx, vy, vz, ax, ay, az, 0, 0, 0, 0, 0, 0, 0]
def postProcess(self):
"""Post-process all Flight information produced during
simulation. Includes the calculation of maximum values,
calculation of secundary values such as energy and conversion
of lists to Function objects to facilitate plotting.
Parameters
----------
None
Return
------
None
"""
# Process first type of outputs - state vector
# Transform solution array into Functions
sol = np.array(self.solution)
self.x = Function(
sol[:, [0, 1]], "Time (s)", "X (m)", "spline", extrapolation="natural"
)
self.y = Function(
sol[:, [0, 2]], "Time (s)", "Y (m)", "spline", extrapolation="natural"
)
self.z = Function(
sol[:, [0, 3]], "Time (s)", "Z (m)", "spline", extrapolation="natural"
)
self.vx = Function(
sol[:, [0, 4]], "Time (s)", "Vx (m/s)", "spline", extrapolation="natural"
)
self.vy = Function(
sol[:, [0, 5]], "Time (s)", "Vy (m/s)", "spline", extrapolation="natural"
)
self.vz = Function(
sol[:, [0, 6]], "Time (s)", "Vz (m/s)", "spline", extrapolation="natural"
)
self.e0 = Function(
sol[:, [0, 7]], "Time (s)", "e0", "spline", extrapolation="natural"
)
self.e1 = Function(
sol[:, [0, 8]], "Time (s)", "e1", "spline", extrapolation="natural"
)
self.e2 = Function(
sol[:, [0, 9]], "Time (s)", "e2", "spline", extrapolation="natural"
)
self.e3 = Function(
sol[:, [0, 10]], "Time (s)", "e3", "spline", extrapolation="natural"
)
self.w1 = Function(
sol[:, [0, 11]], "Time (s)", "ω1 (rad/s)", "spline", extrapolation="natural"
)
self.w2 = Function(
sol[:, [0, 12]], "Time (s)", "ω2 (rad/s)", "spline", extrapolation="natural"
)
self.w3 = Function(
sol[:, [0, 13]], "Time (s)", "ω3 (rad/s)", "spline", extrapolation="natural"
)
# Process second type of outputs - accelerations
# Initialize acceleration arrays
self.ax, self.ay, self.az = [], [], []
self.alpha1, self.alpha2, self.alpha3 = [], [], []
# Go throught each time step and calculate accelerations
# Get fligth phases
for phase_index, phase in self.timeIterator(self.flightPhases):
initTime = phase.t
finalTime = self.flightPhases[phase_index + 1].t
currentDerivative = phase.derivative
# Call callback functions
for callback in phase.callbacks:
callback(self)
# Loop through time steps in flight phase
for step in self.solution: # Can be optmized
if initTime < step[0] <= finalTime:
# Get derivatives
uDot = currentDerivative(step[0], step[1:])
# Get accelerations
ax, ay, az = uDot[3:6]
alpha1, alpha2, alpha3 = uDot[10:]
# Save accelerations
self.ax.append([step[0], ax])
self.ay.append([step[0], ay])
self.az.append([step[0], az])
self.alpha1.append([step[0], alpha1])
self.alpha2.append([step[0], alpha2])
self.alpha3.append([step[0], alpha3])
# Convert accelerations to functions
self.ax = Function(self.ax, "Time (s)", "Ax (m/s2)", "spline")
self.ay = Function(self.ay, "Time (s)", "Ay (m/s2)", "spline")
self.az = Function(self.az, "Time (s)", "Az (m/s2)", "spline")
self.alpha1 = Function(self.alpha1, "Time (s)", "α1 (rad/s2)", "spline")
self.alpha2 = Function(self.alpha2, "Time (s)", "α2 (rad/s2)", "spline")
self.alpha3 = Function(self.alpha3, "Time (s)", "α3 (rad/s2)", "spline")
# Process third type of outputs - temporary values calculated during integration
# Initialize force and atmospheric arrays
self.R1, self.R2, self.R3, self.M1, self.M2, self.M3 = [], [], [], [], [], []
self.pressure, self.density, self.dynamicViscosity, self.speedOfSound = (
[],
[],
[],
[],
)
self.windVelocityX, self.windVelocityY = [], []
# Go throught each time step and calculate forces and atmospheric values
# Get fligth phases
for phase_index, phase in self.timeIterator(self.flightPhases):
initTime = phase.t
finalTime = self.flightPhases[phase_index + 1].t
currentDerivative = phase.derivative
# Call callback functions
for callback in phase.callbacks:
callback(self)
# Loop through time steps in flight phase
for step in self.solution: # Can be optmized
if initTime < step[0] <= finalTime or (initTime == 0 and step[0] == 0):
# Call derivatives in post processing mode
uDot = currentDerivative(step[0], step[1:], postProcessing=True)
# Convert forces and atmospheric arrays to functions
self.R1 = Function(self.R1, "Time (s)", "R1 (N)", "spline")
self.R2 = Function(self.R2, "Time (s)", "R2 (N)", "spline")
self.R3 = Function(self.R3, "Time (s)", "R3 (N)", "spline")
self.M1 = Function(self.M1, "Time (s)", "M1 (Nm)", "spline")
self.M2 = Function(self.M2, "Time (s)", "M2 (Nm)", "spline")
self.M3 = Function(self.M3, "Time (s)", "M3 (Nm)", "spline")
self.windVelocityX = Function(
self.windVelocityX, "Time (s)", "Wind Velocity X (East) (m/s)", "spline"
)
self.windVelocityY = Function(
self.windVelocityY, "Time (s)", "Wind Velocity Y (North) (m/s)", "spline"
)
self.density = Function(self.density, "Time (s)", "Density (kg/m³)", "spline")
self.pressure = Function(self.pressure, "Time (s)", "Pressure (Pa)", "spline")
self.dynamicViscosity = Function(
self.dynamicViscosity, "Time (s)", "Dynamic Viscosity (Pa s)", "spline"
)
self.speedOfSound = Function(
self.speedOfSound, "Time (s)", "Speed of Sound (m/s)", "spline"
)
# Process fourth type of output - values calculated from previous outputs
# Kinematicss functions and values
# Velocity Magnitude
self.speed = (self.vx ** 2 + self.vy ** 2 + self.vz ** 2) ** 0.5
self.speed.setOutputs("Speed - Velocity Magnitude (m/s)")
maxSpeedTimeIndex = np.argmax(self.speed[:, 1])
self.maxSpeed = self.speed[maxSpeedTimeIndex, 1]
self.maxSpeedTime = self.speed[maxSpeedTimeIndex, 0]
# Acceleration
self.acceleration = (self.ax ** 2 + self.ay ** 2 + self.az ** 2) ** 0.5
self.acceleration.setOutputs("Acceleration Magnitude (m/s²)")
maxAccelerationTimeIndex = np.argmax(self.acceleration[:, 1])
self.maxAcceleration = self.acceleration[maxAccelerationTimeIndex, 1]
self.maxAccelerationTime = self.acceleration[maxAccelerationTimeIndex, 0]
# Path Angle
self.horizontalSpeed = (self.vx ** 2 + self.vy ** 2) ** 0.5
pathAngle = (180 / np.pi) * np.arctan2(
self.vz[:, 1], self.horizontalSpeed[:, 1]
)
pathAngle = np.column_stack([self.vz[:, 0], pathAngle])
self.pathAngle = Function(pathAngle, "Time (s)", "Path Angle (°)")
# Attitude Angle
self.attitudeVectorX = 2 * (self.e1 * self.e3 + self.e0 * self.e2) # a13
self.attitudeVectorY = 2 * (self.e2 * self.e3 - self.e0 * self.e1) # a23
self.attitudeVectorZ = 1 - 2 * (self.e1 ** 2 + self.e2 ** 2) # a33
horizontalAttitudeProj = (
self.attitudeVectorX ** 2 + self.attitudeVectorY ** 2
) ** 0.5
attitudeAngle = (180 / np.pi) * np.arctan2(
self.attitudeVectorZ[:, 1], horizontalAttitudeProj[:, 1]
)
attitudeAngle = np.column_stack([self.attitudeVectorZ[:, 0], attitudeAngle])
self.attitudeAngle = Function(attitudeAngle, "Time (s)", "Attitude Angle (°)")
# Lateral Attitude Angle
lateralVectorAngle = (np.pi / 180) * (self.heading - 90)
lateralVectorX = np.sin(lateralVectorAngle)
lateralVectorY = np.cos(lateralVectorAngle)
attitudeLateralProj = (
lateralVectorX * self.attitudeVectorX[:, 1]
+ lateralVectorY * self.attitudeVectorY[:, 1]
)
attitudeLateralProjX = attitudeLateralProj * lateralVectorX
attitudeLateralProjY = attitudeLateralProj * lateralVectorY
attiutdeLateralPlaneProjX = self.attitudeVectorX[:, 1] - attitudeLateralProjX
attiutdeLateralPlaneProjY = self.attitudeVectorY[:, 1] - attitudeLateralProjY
attiutdeLateralPlaneProjZ = self.attitudeVectorZ[:, 1]
attiutdeLateralPlaneProj = (
attiutdeLateralPlaneProjX ** 2
+ attiutdeLateralPlaneProjY ** 2
+ attiutdeLateralPlaneProjZ ** 2
) ** 0.5
lateralAttitudeAngle = (180 / np.pi) * np.arctan2(
attitudeLateralProj, attiutdeLateralPlaneProj
)
lateralAttitudeAngle = np.column_stack(
[self.attitudeVectorZ[:, 0], lateralAttitudeAngle]
)
self.lateralAttitudeAngle = Function(
lateralAttitudeAngle, "Time (s)", "Lateral Attitude Angle (°)"
)
# Euler Angles
psi = (180 / np.pi) * (
np.arctan2(self.e3[:, 1], self.e0[:, 1])
+ np.arctan2(-self.e2[:, 1], -self.e1[:, 1])
) # Precession angle
psi = np.column_stack([self.e1[:, 0], psi]) # Precession angle
self.psi = Function(psi, "Time (s)", "Precession Angle - ψ (°)")
phi = (180 / np.pi) * (
np.arctan2(self.e3[:, 1], self.e0[:, 1])
- np.arctan2(-self.e2[:, 1], -self.e1[:, 1])
) # Spin angle
phi = np.column_stack([self.e1[:, 0], phi]) # Spin angle
self.phi = Function(phi, "Time (s)", "Spin Angle - φ (°)")
theta = (
(180 / np.pi)
* 2
* np.arcsin(-((self.e1[:, 1] ** 2 + self.e2[:, 1] ** 2) ** 0.5))
) # Nutation angle
theta = np.column_stack([self.e1[:, 0], theta]) # Nutation angle
self.theta = Function(theta, "Time (s)", "Nutation Angle - θ (°)")
# Dynamics functions and variables
# Rail Button Forces
alpha = self.rocket.railButtons.angularPosition * (
np.pi / 180
) # Rail buttons angular position
D1 = self.rocket.railButtons.distanceToCM[
0
] # Distance from Rail Button 1 (upper) to CM
D2 = self.rocket.railButtons.distanceToCM[
1
] # Distance from Rail Button 2 (lower) to CM
F11 = (self.R1 * D2 - self.M2) / (
D1 + D2
) # Rail Button 1 force in the 1 direction
F12 = (self.R2 * D2 + self.M1) / (
D1 + D2
) # Rail Button 1 force in the 2 direction
F21 = (self.R1 * D1 + self.M2) / (
D1 + D2
) # Rail Button 2 force in the 1 direction
F22 = (self.R2 * D1 - self.M1) / (
D1 + D2
) # Rail Button 2 force in the 2 direction
outOfRailTimeIndex = np.searchsorted(
F11[:, 0], self.outOfRailTime
) # Find out of rail time index
# F11 = F11[:outOfRailTimeIndex + 1, :] # Limit force calculation to when rocket is in rail
# F12 = F12[:outOfRailTimeIndex + 1, :] # Limit force calculation to when rocket is in rail
# F21 = F21[:outOfRailTimeIndex + 1, :] # Limit force calculation to when rocket is in rail
# F22 = F22[:outOfRailTimeIndex + 1, :] # Limit force calculation to when rocket is in rail
self.railButton1NormalForce = F11 * np.cos(alpha) + F12 * np.sin(alpha)
self.railButton1NormalForce.setOutputs("Upper Rail Button Normal Force (N)")
self.railButton1ShearForce = F11 * -np.sin(alpha) + F12 * np.cos(alpha)
self.railButton1ShearForce.setOutputs("Upper Rail Button Shear Force (N)")
self.railButton2NormalForce = F21 * np.cos(alpha) + F22 * np.sin(alpha)
self.railButton2NormalForce.setOutputs("Lower Rail Button Normal Force (N)")
self.railButton2ShearForce = F21 * -np.sin(alpha) + F22 * np.cos(alpha)
self.railButton2ShearForce.setOutputs("Lower Rail Button Shear Force (N)")
# Rail Button Maximum Forces
self.maxRailButton1NormalForce = np.amax(
self.railButton1NormalForce[:outOfRailTimeIndex]
)
self.maxRailButton1ShearForce = np.amax(
self.railButton1ShearForce[:outOfRailTimeIndex]
)
self.maxRailButton2NormalForce = np.amax(
self.railButton2NormalForce[:outOfRailTimeIndex]
)
self.maxRailButton2ShearForce = np.amax(
self.railButton2ShearForce[:outOfRailTimeIndex]
)
# Aerodynamic Lift and Drag
self.aerodynamicLift = (self.R1 ** 2 + self.R2 ** 2) ** 0.5
self.aerodynamicLift.setOutputs("Aerodynamic Lift Force (N)")
self.aerodynamicDrag = -1 * self.R3
self.aerodynamicDrag.setOutputs("Aerodynamic Drag Force (N)")
self.aerodynamicBendingMoment = (self.M1 ** 2 + self.M2 ** 2) ** 0.5
self.aerodynamicBendingMoment.setOutputs("Aerodynamic Bending Moment (N m)")
self.aerodynamicSpinMoment = self.M3
self.aerodynamicSpinMoment.setOutputs("Aerodynamic Spin Moment (N m)")
# Energy
b = -self.rocket.distanceRocketPropellant
totalMass = self.rocket.totalMass
mu = self.rocket.reducedMass
Rz = self.rocket.inertiaZ
Ri = self.rocket.inertiaI
Tz = self.rocket.motor.inertiaZ
Ti = self.rocket.motor.inertiaI
I1, I2, I3 = (Ri + Ti + mu * b ** 2), (Ri + Ti + mu * b ** 2), (Rz + Tz)
# Redefine I1, I2 and I3 grid
grid = self.vx[:, 0]
I1 = Function(np.column_stack([grid, I1(grid)]), "Time (s)")
I2 = Function(np.column_stack([grid, I2(grid)]), "Time (s)")
I3 = Function(np.column_stack([grid, I3(grid)]), "Time (s)")
# Redefine total mass grid
totalMass = Function(np.column_stack([grid, totalMass(grid)]), "Time (s)")
# Redefine thrust grid
thrust = Function(
np.column_stack([grid, self.rocket.motor.thrust(grid)]), "Time (s)"
)
# Get some nicknames
vx, vy, vz = self.vx, self.vy, self.vz
w1, w2, w3 = self.w1, self.w2, self.w3
# Kinetic Energy
self.rotationalEnergy = 0.5 * (I1 * w1 ** 2 + I2 * w2 ** 2 + I3 * w3 ** 2)
self.rotationalEnergy.setOutputs("Rotational Kinetic Energy (J)")
self.translationalEnergy = 0.5 * totalMass * (vx ** 2 + vy ** 2 + vz ** 2)
self.translationalEnergy.setOutputs("Translational Kinetic Energy (J)")
self.kineticEnergy = self.rotationalEnergy + self.translationalEnergy
self.kineticEnergy.setOutputs("Kinetic Energy (J)")
# Potential Energy
self.potentialEnergy = totalMass * self.env.g * self.z
self.potentialEnergy.setInputs("Time (s)")
# Total Mechanical Energy
self.totalEnergy = self.kineticEnergy + self.potentialEnergy
self.totalEnergy.setOutputs("Total Mechanical Energy (J)")
# Thrust Power
self.thrustPower = thrust * self.speed
self.thrustPower.setOutputs("Thrust Power (W)")
# Drag Power
self.dragPower = self.R3 * self.speed
self.dragPower.setOutputs("Drag Power (W)")
# Stability and Control variables
# Angular velocities frequency response - Fourier Analysis
# Omega 1 - w1
Fs = 100.0
# sampling rate
Ts = 1.0 / Fs
# sampling interval
t = np.arange(1, self.tFinal, Ts) # time vector
y = self.w1(t)
y -= np.mean(y)
n = len(y) # length of the signal
k = np.arange(n)
T = n / Fs
frq = k / T # two sides frequency range
frq = frq[range(n // 2)] # one side frequency range
Y = np.fft.fft(y) / n # fft computing and normalization
Y = Y[range(n // 2)]
omega1FrequencyResponse = np.column_stack([frq, abs(Y)])
self.omega1FrequencyResponse = Function(
omega1FrequencyResponse, "Frequency (Hz)", "Omega 1 Angle Fourier Amplitude"
)
# Omega 2 - w2
Fs = 100.0
# sampling rate
Ts = 1.0 / Fs
# sampling interval
t = np.arange(1, self.tFinal, Ts) # time vector
y = self.w2(t)
y -= np.mean(y)
n = len(y) # length of the signal
k = np.arange(n)
T = n / Fs
frq = k / T # two sides frequency range
frq = frq[range(n // 2)] # one side frequency range
Y = np.fft.fft(y) / n # fft computing and normalization
Y = Y[range(n // 2)]
omega2FrequencyResponse = np.column_stack([frq, abs(Y)])
self.omega2FrequencyResponse = Function(
omega2FrequencyResponse, "Frequency (Hz)", "Omega 2 Angle Fourier Amplitude"
)
# Omega 3 - w3
Fs = 100.0
# sampling rate
Ts = 1.0 / Fs
# sampling interval
t = np.arange(1, self.tFinal, Ts) # time vector
y = self.w3(t)
y -= np.mean(y)
n = len(y) # length of the signal
k = np.arange(n)
T = n / Fs
frq = k / T # two sides frequency range
frq = frq[range(n // 2)] # one side frequency range
Y = np.fft.fft(y) / n # fft computing and normalization
Y = Y[range(n // 2)]
omega3FrequencyResponse = np.column_stack([frq, abs(Y)])
self.omega3FrequencyResponse = Function(
omega3FrequencyResponse, "Frequency (Hz)", "Omega 3 Angle Fourier Amplitude"
)
# Attitude Frequency Response
Fs = 100.0
# sampling rate
Ts = 1.0 / Fs
# sampling interval
t = np.arange(1, self.tFinal, Ts) # time vector
y = self.attitudeAngle(t)
y -= np.mean(y)
n = len(y) # length of the signal
k = np.arange(n)
T = n / Fs
frq = k / T # two sides frequency range
frq = frq[range(n // 2)] # one side frequency range
Y = np.fft.fft(y) / n # fft computing and normalization
Y = Y[range(n // 2)]
attitudeFrequencyResponse = np.column_stack([frq, abs(Y)])
self.attitudeFrequencyResponse = Function(
attitudeFrequencyResponse,
"Frequency (Hz)",
"Attitude Angle Fourier Amplitude",
)
# Static Margin
self.staticMargin = self.rocket.staticMargin
# Fluid Mechanics variables
# Freestream Velocity
self.streamVelocityX = self.windVelocityX - self.vx
self.streamVelocityX.setOutputs("Freestream Velocity X (m/s)")
self.streamVelocityY = self.windVelocityY - self.vy
self.streamVelocityY.setOutputs("Freestream Velocity Y (m/s)")
self.streamVelocityZ = -1 * self.vz
self.streamVelocityZ.setOutputs("Freestream Velocity Z (m/s)")
self.freestreamSpeed = (
self.streamVelocityX ** 2
+ self.streamVelocityY ** 2
+ self.streamVelocityZ ** 2
) ** 0.5
self.freestreamSpeed.setOutputs("Freestream Speed (m/s)")
# Apogee Freestream speed
self.apogeeFreestreamSpeed = self.freestreamSpeed(self.apogeeTime)
# Mach Number
self.MachNumber = self.freestreamSpeed / self.speedOfSound
self.MachNumber.setOutputs("Mach Number")
maxMachNumberTimeIndex = np.argmax(self.MachNumber[:, 1])
self.maxMachNumberTime = self.MachNumber[maxMachNumberTimeIndex, 0]
self.maxMachNumber = self.MachNumber[maxMachNumberTimeIndex, 1]
# Reynolds Number
self.ReynoldsNumber = (
self.density * self.freestreamSpeed / self.dynamicViscosity
) * (2 * self.rocket.radius)
self.ReynoldsNumber.setOutputs("Reynolds Number")
maxReynoldsNumberTimeIndex = np.argmax(self.ReynoldsNumber[:, 1])
self.maxReynoldsNumberTime = self.ReynoldsNumber[maxReynoldsNumberTimeIndex, 0]
self.maxReynoldsNumber = self.ReynoldsNumber[maxReynoldsNumberTimeIndex, 1]
# Dynamic Pressure
self.dynamicPressure = 0.5 * self.density * self.freestreamSpeed ** 2
self.dynamicPressure.setOutputs("Dynamic Pressure (Pa)")
maxDynamicPressureTimeIndex = np.argmax(self.dynamicPressure[:, 1])
self.maxDynamicPressureTime = self.dynamicPressure[
maxDynamicPressureTimeIndex, 0
]
self.maxDynamicPressure = self.dynamicPressure[maxDynamicPressureTimeIndex, 1]
# Total Pressure
self.totalPressure = self.pressure * (1 + 0.2 * self.MachNumber ** 2) ** (3.5)
self.totalPressure.setOutputs("Total Pressure (Pa)")
maxtotalPressureTimeIndex = np.argmax(self.totalPressure[:, 1])
self.maxtotalPressureTime = self.totalPressure[maxtotalPressureTimeIndex, 0]
self.maxtotalPressure = self.totalPressure[maxDynamicPressureTimeIndex, 1]
# Angle of Attack
angleOfAttack = []
for i in range(len(self.attitudeVectorX[:, 1])):
dotProduct = -(
self.attitudeVectorX[i, 1] * self.streamVelocityX[i, 1]
+ self.attitudeVectorY[i, 1] * self.streamVelocityY[i, 1]
+ self.attitudeVectorZ[i, 1] * self.streamVelocityZ[i, 1]
)
if self.freestreamSpeed[i, 1] < 1e-6:
angleOfAttack.append([self.freestreamSpeed[i, 0], 0])
else:
dotProductNormalized = dotProduct / self.freestreamSpeed[i, 1]
dotProductNormalized = (
1 if dotProductNormalized > 1 else dotProductNormalized
)
dotProductNormalized = (
-1 if dotProductNormalized < -1 else dotProductNormalized
)
angleOfAttack.append(
[
self.freestreamSpeed[i, 0],
(180 / np.pi) * np.arccos(dotProductNormalized),
]
)
self.angleOfAttack = Function(
angleOfAttack, "Time (s)", "Angle Of Attack (°)", "linear"
)
# Post process other quantities
# Transform parachute sensor feed into functions
for parachute in self.rocket.parachutes:
parachute.cleanPressureSignalFunction = Function(
parachute.cleanPressureSignal,
"Time (s)",
"Pressure - Without Noise (Pa)",
"linear",
)
parachute.noisyPressureSignalFunction = Function(
parachute.noisyPressureSignal,
"Time (s)",
"Pressure - With Noise (Pa)",
"linear",
)
parachute.noiseSignalFunction = Function(
parachute.noiseSignal, "Time (s)", "Pressure Noise (Pa)", "linear"
)
# Register post processing
self.postProcessed = True
return None
def info(self):
"""Prints out a summary of the data available about the Flight.
Parameters
----------
None
Return
------
None
"""
# Post-process results
if self.postProcessed is False:
self.postProcess()
# Get index of out of rail time
outOfRailTimeIndexs = np.nonzero(self.x[:, 0] == self.outOfRailTime)
outOfRailTimeIndex = (
-1 if len(outOfRailTimeIndexs) == 0 else outOfRailTimeIndexs[0][0]
)
# Get index of time before parachute event
if len(self.parachuteEvents) > 0:
eventTime = self.parachuteEvents[0][0] + self.parachuteEvents[0][1].lag
eventTimeIndex = np.nonzero(self.x[:, 0] == eventTime)[0][0]
else:
eventTime = self.tFinal
eventTimeIndex = -1
# Print surface wind conditions
print("Surface Wind Conditions\n")
print("Frontal Surface Wind Speed: {:.2f} m/s".format(self.frontalSurfaceWind))
print("Lateral Surface Wind Speed: {:.2f} m/s".format(self.lateralSurfaceWind))
# Print of rail conditions
print("\n\n Rail Departure State\n")
print("Rail Departure Time: {:.3f} s".format(self.outOfRailTime))
print("Rail Departure Velocity: {:.3f} m/s".format(self.outOfRailVelocity))
print(
"Rail Departure Static Margin: {:.3f} c".format(
self.staticMargin(self.outOfRailTime)
)
)
print(
"Rail Departure Angle of Attack: {:.3f}°".format(
self.angleOfAttack(self.outOfRailTime)
)
)
print(
"Rail Departure Thrust-Weight Ratio: {:.3f}".format(
self.rocket.thrustToWeight(self.outOfRailTime)
)
)
print(
"Rail Departure Reynolds Number: {:.3e}".format(
self.ReynoldsNumber(self.outOfRailTime)
)
)
# Print burnOut conditions
print("\n\nBurnOut State\n")
print("BurnOut time: {:.3f} s".format(self.rocket.motor.burnOutTime))
print(
"Altitude at burnOut: {:.3f} m (AGL)".format(
self.z( self.rocket.motor.burnOutTime ) - self.env.elevation
)
)
print("Rocket velocity at burnOut: {:.3f} m/s".format(
self.speed( self.rocket.motor.burnOutTime )
)
)
print(
"Freestream velocity at burnOut: {:.3f} m/s".format(
(self.streamVelocityX( self.rocket.motor.burnOutTime )**2 +
self.streamVelocityY( self.rocket.motor.burnOutTime )**2 +
self.streamVelocityZ( self.rocket.motor.burnOutTime )**2)**0.5
)
)
print(
"Mach Number at burnOut: {:.3f}".format(
self.MachNumber( self.rocket.motor.burnOutTime))
)
print("Kinetic energy at burnOut: {:.3e} J".format(
self.kineticEnergy(self.rocket.motor.burnOutTime)
)
)
# Print apogee conditions
print("\n\nApogee\n")
print(
"Apogee Altitude: {:.3f} m (ASL) | {:.3f} m (AGL)".format(
self.apogee, self.apogee - self.env.elevation
)
)
print("Apogee Time: {:.3f} s".format(self.apogeeTime))
print("Apogee Freestream Speed: {:.3f} m/s".format(self.apogeeFreestreamSpeed))
# Print events registered
print("\n\nEvents\n")
if len(self.parachuteEvents) == 0:
print("No Parachute Events Were Triggered.")
for event in self.parachuteEvents:
triggerTime = event[0]
parachute = event[1]
openTime = triggerTime + parachute.lag
velocity = self.freestreamSpeed(openTime)
altitude = self.z(openTime)
name = parachute.name.title()
print(name + " Ejection Triggered at: {:.3f} s".format(triggerTime))
print(name + " Parachute Inflated at: {:.3f} s".format(openTime))
print(
name
+ " Parachute Inflated with Freestream Speed of: {:.3f} m/s".format(
velocity
)
)
print(name + " Parachute Inflated at Height of: {:.3f} m (AGL)".format(altitude - self.env.elevation))
# Print impact conditions
if len(self.impactState) != 0:
print("\n\nImpact\n")
print("X Impact: {:.3f} m".format(self.xImpact))
print("Y Impact: {:.3f} m".format(self.yImpact))
print("Time of Impact: {:.3f} s".format(self.tFinal))
print("Velocity at Impact: {:.3f} m/s".format(self.impactVelocity))
elif self.terminateOnApogee is False:
print("\n\nEnd of Simulation\n")
print("Time: {:.3f} s".format(self.solution[-1][0]))
print("Altitude: {:.3f} m".format(self.solution[-1][3]))
# Print maximum values
print("\n\nMaximum Values\n")
print(
"Maximum Speed: {:.3f} m/s at {:.2f} s".format(
self.maxSpeed, self.maxSpeedTime
)
)
print(
"Maximum Mach Number: {:.3f} Mach at {:.2f} s".format(
self.maxMachNumber, self.maxMachNumberTime
)
)
print(
"Maximum Reynolds Number: {:.3e} at {:.2f} s".format(
self.maxReynoldsNumber, self.maxReynoldsNumberTime
)
)
print(
"Maximum Dynamic Pressure: {:.3e} Pa at {:.2f} s".format(
self.maxDynamicPressure, self.maxDynamicPressureTime
)
)
print(
"Maximum Acceleration: {:.3f} m/s² at {:.2f} s".format(
self.maxAcceleration, self.maxAccelerationTime
)
)
print(
"Maximum Gs: {:.3f} g at {:.2f} s".format(
self.maxAcceleration / self.env.g, self.maxAccelerationTime
)
)
print(
"Maximum Upper Rail Button Normal Force: {:.3f} N".format(
self.maxRailButton1NormalForce
)
)
print(
"Maximum Upper Rail Button Shear Force: {:.3f} N".format(
self.maxRailButton1ShearForce
)
)
print(
"Maximum Lower Rail Button Normal Force: {:.3f} N".format(
self.maxRailButton2NormalForce
)
)
print(
"Maximum Lower Rail Button Shear Force: {:.3f} N".format(
self.maxRailButton2ShearForce
)
)
return None
def printInitialConditionsData(self):
"""Prints all initial conditions data available about the flight
Parameters
----------
None
Return
------
None
"""
# Post-process results
if self.postProcessed is False:
self.postProcess()
print(
"Position - x: {:.2f} m | y: {:.2f} m | z: {:.2f} m".format(
self.x(0), self.y(0), self.z(0)
)
)
print(
"Velocity - Vx: {:.2f} m/s | Vy: {:.2f} m/s | Vz: {:.2f} m/s".format(
self.vx(0), self.vy(0), self.vz(0)
)
)
print(
"Attitude - e0: {:.3f} | e1: {:.3f} | e2: {:.3f} | e3: {:.3f}".format(
self.e0(0), self.e1(0), self.e2(0), self.e3(0)
)
)
print(
"Euler Angles - Spin φ : {:.2f}° | Nutation θ: {:.2f}° | Precession ψ: {:.2f}°".format(
self.phi(0), self.theta(0), self.psi(0)
)
)
print(
"Angular Velocity - ω1: {:.2f} rad/s | ω2: {:.2f} rad/s| ω3: {:.2f} rad/s".format(
self.w1(0), self.w2(0), self.w3(0)
)
)
return None
def printNumericalIntegrationSettings(self):
"""Prints out the Numerical Integration settings
Parameters
----------
None
Return
------
None
"""
print("Maximum Allowed Flight Time: {:f} s".format(self.maxTime))
print("Maximum Allowed Time Step: {:f} s".format(self.maxTimeStep))
print("Minimum Allowed Time Step: {:e} s".format(self.minTimeStep))
print("Relative Error Tolerance: ", self.rtol)
print("Absolute Error Tolerance: ", self.atol)
print("Allow Event Overshoot: ", self.timeOvershoot)
print("Terminate Simulation on Apogee: ", self.terminateOnApogee)
print("Number of Time Steps Used: ", len(self.timeSteps))
print(
"Number of Derivative Functions Evaluation: ",
sum(self.functionEvaluationsPerTimeStep),
)
print(
"Average Function Evaluations per Time Step: {:3f}".format(
sum(self.functionEvaluationsPerTimeStep) / len(self.timeSteps))
)
return None
def calculateStallWindVelocity(self, stallAngle):
""" Function to calculate the maximum wind velocity before the angle of
attack exceeds a desired angle, at the instant of departing rail launch.
Can be helpful if you know the exact stall angle of all aerodynamics
surfaces.
Parameters
----------
stallAngle : float
Angle, in degrees, for which you would like to know the maximum wind
speed before the angle of attack exceeds it
Return
------
None
"""
vF = self.outOfRailVelocity
# Convert angle to radians
tetha = self.inclination * np.pi /180
stallAngle = stallAngle * np.pi /180
c = (math.cos(stallAngle)**2 - math.cos(tetha)**2)/ math.sin(stallAngle)**2
wV = (2*vF*math.cos(tetha)/c + (4*vF*vF*math.cos(tetha)*math.cos(tetha)/(c**2) + 4*1*vF*vF/c )**0.5 )/2
# Convert stallAngle to degrees
stallAngle = stallAngle * 180 / np.pi
print("Maximum wind velocity at Rail Departure time before angle of attack exceeds {:.3f}°: {:.3f} m/s".format(stallAngle, wV))
return None
def plot3dTrajectory(self):
"""Plot a 3D graph of the trajectory
Parameters
----------
None
Return
------
None
"""
# Post-process results
if self.postProcessed is False:
self.postProcess()
# Get max and min x and y
maxZ = max(self.z[:, 1] - self.env.elevation )
maxX = max(self.x[:, 1])
minX = min(self.x[:, 1])
maxY = max(self.y[:, 1])
minY = min(self.y[:, 1])
maxXY = max(maxX, maxY)
minXY = min(minX, minY)
# Create figure
fig1 = plt.figure(figsize=(9, 9))
ax1 = plt.subplot(111, projection="3d")
ax1.plot(
self.x[:, 1], self.y[:, 1], zs= 0, zdir="z", linestyle="--"
)
ax1.plot(self.x[:, 1], self.z[:, 1] - self.env.elevation, zs=minXY, zdir="y", linestyle="--")
ax1.plot(self.y[:, 1], self.z[:, 1] - self.env.elevation, zs=minXY, zdir="x", linestyle="--")
ax1.plot(self.x[:, 1], self.y[:, 1], self.z[:, 1] - self.env.elevation, linewidth='2')
ax1.scatter(0, 0, 0)
ax1.set_xlabel("X - East (m)")
ax1.set_ylabel("Y - North (m)")
ax1.set_zlabel("Z - Altitude Above Ground Level (m)")
ax1.set_title("Flight Trajectory")
ax1.set_zlim3d([0, maxZ])
ax1.set_ylim3d([minXY, maxXY])
ax1.set_xlim3d([minXY, maxXY])
ax1.view_init(15, 45)
plt.show()
return None
def plotLinearKinematicsData(self):
"""Prints out all Kinematics graphs available about the Flight
Parameters
----------
None
Return
------
None
"""
# Post-process results
if self.postProcessed is False:
self.postProcess()
# Velocity and acceleration plots
fig2 = plt.figure(figsize=(9, 12))
ax1 = plt.subplot(414)
ax1.plot(self.vx[:, 0], self.vx[:, 1], color="#ff7f0e")
ax1.set_xlim(0, self.tFinal)
ax1.set_title("Velocity X | Acceleration X")
ax1.set_xlabel("Time (s)")
ax1.set_ylabel("Velocity X (m/s)", color="#ff7f0e")
ax1.tick_params("y", colors="#ff7f0e")
ax1.grid(True)
ax1up = ax1.twinx()
ax1up.plot(self.ax[:, 0], self.ax[:, 1], color="#1f77b4")
ax1up.set_ylabel("Acceleration X (m/s²)", color="#1f77b4")
ax1up.tick_params("y", colors="#1f77b4")
ax2 = plt.subplot(413)
ax2.plot(self.vy[:, 0], self.vy[:, 1], color="#ff7f0e")
ax2.set_xlim(0, self.tFinal)
ax2.set_title("Velocity Y | Acceleration Y")
ax2.set_xlabel("Time (s)")
ax2.set_ylabel("Velocity Y (m/s)", color="#ff7f0e")
ax2.tick_params("y", colors="#ff7f0e")
ax2.grid(True)
ax2up = ax2.twinx()
ax2up.plot(self.ay[:, 0], self.ay[:, 1], color="#1f77b4")
ax2up.set_ylabel("Acceleration Y (m/s²)", color="#1f77b4")
ax2up.tick_params("y", colors="#1f77b4")
ax3 = plt.subplot(412)
ax3.plot(self.vz[:, 0], self.vz[:, 1], color="#ff7f0e")
ax3.set_xlim(0, self.tFinal)
ax3.set_title("Velocity Z | Acceleration Z")
ax3.set_xlabel("Time (s)")
ax3.set_ylabel("Velocity Z (m/s)", color="#ff7f0e")
ax3.tick_params("y", colors="#ff7f0e")
ax3.grid(True)
ax3up = ax3.twinx()
ax3up.plot(self.az[:, 0], self.az[:, 1], color="#1f77b4")
ax3up.set_ylabel("Acceleration Z (m/s²)", color="#1f77b4")
ax3up.tick_params("y", colors="#1f77b4")
ax4 = plt.subplot(411)
ax4.plot(self.speed[:, 0], self.speed[:, 1], color="#ff7f0e")
ax4.set_xlim(0, self.tFinal)
ax4.set_title("Velocity Magnitude | Acceleration Magnitude")
ax4.set_xlabel("Time (s)")
ax4.set_ylabel("Velocity (m/s)", color="#ff7f0e")
ax4.tick_params("y", colors="#ff7f0e")
ax4.grid(True)
ax4up = ax4.twinx()
ax4up.plot(self.acceleration[:, 0], self.acceleration[:, 1], color="#1f77b4")
ax4up.set_ylabel("Acceleration (m/s²)", color="#1f77b4")
ax4up.tick_params("y", colors="#1f77b4")
plt.subplots_adjust(hspace=0.5)
plt.show()
return None
def plotAttitudeData(self):
"""Prints out all Angular position graphs available about the Flight
Parameters
----------
None
Return
------
None
"""
# Post-process results
if self.postProcessed is False:
self.postProcess()
# Get index of time before parachute event
if len(self.parachuteEvents) > 0:
eventTime = self.parachuteEvents[0][0] + self.parachuteEvents[0][1].lag
eventTimeIndex = np.nonzero(self.x[:, 0] == eventTime)[0][0]
else:
eventTime = self.tFinal
eventTimeIndex = -1
# Angular position plots
fig3 = plt.figure(figsize=(9, 12))
ax1 = plt.subplot(411)
ax1.plot(self.e0[:, 0], self.e0[:, 1], label="$e_0$")
ax1.plot(self.e1[:, 0], self.e1[:, 1], label="$e_1$")
ax1.plot(self.e2[:, 0], self.e2[:, 1], label="$e_2$")
ax1.plot(self.e3[:, 0], self.e3[:, 1], label="$e_3$")
ax1.set_xlim(0, eventTime)
ax1.set_xlabel("Time (s)")
ax1.set_ylabel("Euler Parameters")
ax1.set_title("Euler Parameters")
ax1.legend()
ax1.grid(True)
ax2 = plt.subplot(412)
ax2.plot(self.psi[:, 0], self.psi[:, 1])
ax2.set_xlim(0, eventTime)
ax2.set_xlabel("Time (s)")
ax2.set_ylabel("ψ (°)")
ax2.set_title("Euler Precession Angle")
ax2.grid(True)
ax3 = plt.subplot(413)
ax3.plot(self.theta[:, 0], self.theta[:, 1], label="θ - Nutation")
ax3.set_xlim(0, eventTime)
ax3.set_xlabel("Time (s)")
ax3.set_ylabel("θ (°)")
ax3.set_title("Euler Nutation Angle")
ax3.grid(True)
ax4 = plt.subplot(414)
ax4.plot(self.phi[:, 0], self.phi[:, 1], label="φ - Spin")
ax4.set_xlim(0, eventTime)
ax4.set_xlabel("Time (s)")
ax4.set_ylabel("φ (°)")
ax4.set_title("Euler Spin Angle")
ax4.grid(True)
plt.subplots_adjust(hspace=0.5)
plt.show()
return None
def plotFlightPathAngleData(self):
"""Prints out Flight path and Rocket Attitude angle graphs available
about the Flight
Parameters
----------
None
Return
------
None
"""
# Post-process results
if self.postProcessed is False:
self.postProcess()
# Get index of time before parachute event
if len(self.parachuteEvents) > 0:
eventTime = self.parachuteEvents[0][0] + self.parachuteEvents[0][1].lag
eventTimeIndex = np.nonzero(self.x[:, 0] == eventTime)[0][0]
else:
eventTime = self.tFinal
eventTimeIndex = -1
# Path, Attitude and Lateral Attitude Angle
# Angular position plots
fig5 = plt.figure(figsize=(9, 6))
ax1 = plt.subplot(211)
ax1.plot(self.pathAngle[:, 0], self.pathAngle[:, 1], label="Flight Path Angle")
ax1.plot(
self.attitudeAngle[:, 0],
self.attitudeAngle[:, 1],
label="Rocket Attitude Angle",
)
ax1.set_xlim(0, eventTime)
ax1.legend()
ax1.grid(True)
ax1.set_xlabel("Time (s)")
ax1.set_ylabel("Angle (°)")
ax1.set_title("Flight Path and Attitude Angle")
ax2 = plt.subplot(212)
ax2.plot(self.lateralAttitudeAngle[:, 0], self.lateralAttitudeAngle[:, 1])
ax2.set_xlim(0, eventTime)
ax2.set_xlabel("Time (s)")
ax2.set_ylabel("Lateral Attitude Angle (°)")
ax2.set_title("Lateral Attitude Angle")
ax2.grid(True)
plt.subplots_adjust(hspace=0.5)
plt.show()
return None
def plotAngularKinematicsData(self):
"""Prints out all Angular veolcity and acceleration graphs available
about the Flight
Parameters
----------
None
Return
------
None
"""
# Post-process results
if self.postProcessed is False:
self.postProcess()
# Get index of time before parachute event
if len(self.parachuteEvents) > 0:
eventTime = self.parachuteEvents[0][0] + self.parachuteEvents[0][1].lag
eventTimeIndex = np.nonzero(self.x[:, 0] == eventTime)[0][0]
else:
eventTime = self.tFinal
eventTimeIndex = -1
# Angular velocity and acceleration plots
fig4 = plt.figure(figsize=(9, 9))
ax1 = plt.subplot(311)
ax1.plot(self.w1[:, 0], self.w1[:, 1], color="#ff7f0e")
ax1.set_xlim(0, eventTime)
ax1.set_xlabel("Time (s)")
ax1.set_ylabel("Angular Velocity - ${\omega_1}$ (rad/s)", color="#ff7f0e")
ax1.set_title(
"Angular Velocity ${\omega_1}$ | Angular Acceleration ${\\alpha_1}$"
)
ax1.tick_params("y", colors="#ff7f0e")
ax1.grid(True)
ax1up = ax1.twinx()
ax1up.plot(self.alpha1[:, 0], self.alpha1[:, 1], color="#1f77b4")
ax1up.set_ylabel(
"Angular Acceleration - ${\\alpha_1}$ (rad/s²)", color="#1f77b4"
)
ax1up.tick_params("y", colors="#1f77b4")
ax2 = plt.subplot(312)
ax2.plot(self.w2[:, 0], self.w2[:, 1], color="#ff7f0e")
ax2.set_xlim(0, eventTime)
ax2.set_xlabel("Time (s)")
ax2.set_ylabel("Angular Velocity - ${\omega_2}$ (rad/s)", color="#ff7f0e")
ax2.set_title(
"Angular Velocity ${\omega_2}$ | Angular Acceleration ${\\alpha_2}$"
)
ax2.tick_params("y", colors="#ff7f0e")
ax2.grid(True)
ax2up = ax2.twinx()
ax2up.plot(self.alpha2[:, 0], self.alpha2[:, 1], color="#1f77b4")
ax2up.set_ylabel(
"Angular Acceleration - ${\\alpha_2}$ (rad/s²)", color="#1f77b4"
)
ax2up.tick_params("y", colors="#1f77b4")
ax3 = plt.subplot(313)
ax3.plot(self.w3[:, 0], self.w3[:, 1], color="#ff7f0e")
ax3.set_xlim(0, eventTime)
ax3.set_xlabel("Time (s)")
ax3.set_ylabel("Angular Velocity - ${\omega_3}$ (rad/s)", color="#ff7f0e")
ax3.set_title(
"Angular Velocity ${\omega_3}$ | Angular Acceleration ${\\alpha_3}$"
)
ax3.tick_params("y", colors="#ff7f0e")
ax3.grid(True)
ax3up = ax3.twinx()
ax3up.plot(self.alpha3[:, 0], self.alpha3[:, 1], color="#1f77b4")
ax3up.set_ylabel(
"Angular Acceleration - ${\\alpha_3}$ (rad/s²)", color="#1f77b4"
)
ax3up.tick_params("y", colors="#1f77b4")
plt.subplots_adjust(hspace=0.5)
plt.show()
return None
def plotTrajectoryForceData(self):
"""Prints out all Forces and Moments graphs available about the Flight
Parameters
----------
None
Return
------
None
"""
# Post-process results
if self.postProcessed is False:
self.postProcess()
# Get index of out of rail time
outOfRailTimeIndexs = np.nonzero(self.x[:, 0] == self.outOfRailTime)
outOfRailTimeIndex = -1 if len(outOfRailTimeIndexs) == 0 else outOfRailTimeIndexs[0][0]
# Get index of time before parachute event
if len(self.parachuteEvents) > 0:
eventTime = self.parachuteEvents[0][0] + self.parachuteEvents[0][1].lag
eventTimeIndex = np.nonzero(self.x[:, 0] == eventTime)[0][0]
else:
eventTime = self.tFinal
eventTimeIndex = -1
# Rail Button Forces
fig6 = plt.figure(figsize=(9, 6))
ax1 = plt.subplot(211)
ax1.plot(
self.railButton1NormalForce[:outOfRailTimeIndex, 0],
self.railButton1NormalForce[:outOfRailTimeIndex, 1],
label="Upper Rail Button",
)
ax1.plot(
self.railButton2NormalForce[:outOfRailTimeIndex, 0],
self.railButton2NormalForce[:outOfRailTimeIndex, 1],
label="Lower Rail Button",
)
ax1.set_xlim(0, self.outOfRailTime)
ax1.legend()
ax1.grid(True)
ax1.set_xlabel("Time (s)")
ax1.set_ylabel("Normal Force (N)")
ax1.set_title("Rail Buttons Normal Force")
ax2 = plt.subplot(212)
ax2.plot(
self.railButton1ShearForce[:outOfRailTimeIndex, 0],
self.railButton1ShearForce[:outOfRailTimeIndex, 1],
label="Upper Rail Button",
)
ax2.plot(
self.railButton2ShearForce[:outOfRailTimeIndex, 0],
self.railButton2ShearForce[:outOfRailTimeIndex, 1],
label="Lower Rail Button",
)
ax2.set_xlim(0, self.outOfRailTime)
ax2.legend()
ax2.grid(True)
ax2.set_xlabel("Time (s)")
ax2.set_ylabel("Shear Force (N)")
ax2.set_title("Rail Buttons Shear Force")
plt.subplots_adjust(hspace=0.5)
plt.show()
# Aerodynamic force and moment plots
fig7 = plt.figure(figsize=(9, 12))
ax1 = plt.subplot(411)
ax1.plot(self.aerodynamicLift[:eventTimeIndex, 0], self.aerodynamicLift[:eventTimeIndex, 1], label='Resultant')
ax1.plot(self.R1[:eventTimeIndex, 0], self.R1[:eventTimeIndex, 1], label='R1')
ax1.plot(self.R2[:eventTimeIndex, 0], self.R2[:eventTimeIndex, 1], label='R2')
ax1.set_xlim(0, eventTime)
ax1.legend()
ax1.set_xlabel("Time (s)")
ax1.set_ylabel("Lift Force (N)")
ax1.set_title("Aerodynamic Lift Resultant Force")
ax1.grid()
ax2 = plt.subplot(412)
ax2.plot(self.aerodynamicDrag[:eventTimeIndex, 0], self.aerodynamicDrag[:eventTimeIndex, 1])
ax2.set_xlim(0, eventTime)
ax2.set_xlabel("Time (s)")
ax2.set_ylabel("Drag Force (N)")
ax2.set_title("Aerodynamic Drag Force")
ax2.grid()
ax3 = plt.subplot(413)
ax3.plot(
self.aerodynamicBendingMoment[:eventTimeIndex, 0],
self.aerodynamicBendingMoment[:eventTimeIndex, 1],
label='Resultant',
)
ax3.plot(self.M1[:eventTimeIndex, 0], self.M1[:eventTimeIndex, 1], label='M1')
ax3.plot(self.M2[:eventTimeIndex, 0], self.M2[:eventTimeIndex, 1], label='M2')
ax3.set_xlim(0, eventTime)
ax3.legend()
ax3.set_xlabel("Time (s)")
ax3.set_ylabel("Bending Moment (N m)")
ax3.set_title("Aerodynamic Bending Resultant Moment")
ax3.grid()
ax4 = plt.subplot(414)
ax4.plot(self.aerodynamicSpinMoment[:eventTimeIndex, 0], self.aerodynamicSpinMoment[:eventTimeIndex, 1])
ax4.set_xlim(0, eventTime)
ax4.set_xlabel("Time (s)")
ax4.set_ylabel("Spin Moment (N m)")
ax4.set_title("Aerodynamic Spin Moment")
ax4.grid()
plt.subplots_adjust(hspace=0.5)
plt.show()
return None
def plotEnergyData(self):
"""Prints out all Energy components graphs available about the Flight
Returns
-------
None
"""
# Post-process results
if self.postProcessed is False:
self.postProcess()
# Get index of out of rail time
outOfRailTimeIndexs = np.nonzero(self.x[:, 0] == self.outOfRailTime)
outOfRailTimeIndex = -1 if len(outOfRailTimeIndexs) == 0 else outOfRailTimeIndexs[0][0]
# Get index of time before parachute event
if len(self.parachuteEvents) > 0:
eventTime = self.parachuteEvents[0][0] + self.parachuteEvents[0][1].lag
eventTimeIndex = np.nonzero(self.x[:, 0] == eventTime)[0][0]
else:
eventTime = self.tFinal
eventTimeIndex = -1
fig8 = plt.figure(figsize=(9, 9))
ax1 = plt.subplot(411)
ax1.plot(
self.kineticEnergy[:, 0], self.kineticEnergy[:, 1], label="Kinetic Energy"
)
ax1.plot(
self.rotationalEnergy[:, 0],
self.rotationalEnergy[:, 1],
label="Rotational Energy",
)
ax1.plot(
self.translationalEnergy[:, 0],
self.translationalEnergy[:, 1],
label="Translational Energy",
)
ax1.set_xlim(0, self.apogeeTime)
ax1.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
ax1.set_title("Kinetic Energy Components")
ax1.set_xlabel("Time (s)")
ax1.set_ylabel("Energy (J)")
ax1.legend()
ax1.grid()
ax2 = plt.subplot(412)
ax2.plot(self.totalEnergy[:, 0], self.totalEnergy[:, 1], label="Total Energy")
ax2.plot(
self.kineticEnergy[:, 0], self.kineticEnergy[:, 1], label="Kinetic Energy"
)
ax2.plot(
self.potentialEnergy[:, 0],
self.potentialEnergy[:, 1],
label="Potential Energy",
)
ax2.set_xlim(0, self.apogeeTime)
ax2.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
ax2.set_title("Total Mechanical Energy Components")
ax2.set_xlabel("Time (s)")
ax2.set_ylabel("Energy (J)")
ax2.legend()
ax2.grid()
ax3 = plt.subplot(413)
ax3.plot(self.thrustPower[:, 0], self.thrustPower[:, 1], label="|Thrust Power|")
ax3.set_xlim(0, self.rocket.motor.burnOutTime)
ax3.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
ax3.set_title("Thrust Absolute Power")
ax3.set_xlabel("Time (s)")
ax3.set_ylabel("Power (W)")
ax3.legend()
ax3.grid()
ax4 = plt.subplot(414)
ax4.plot(self.dragPower[:, 0], -self.dragPower[:, 1], label="|Drag Power|")
ax4.set_xlim(0, self.apogeeTime)
ax3.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
ax4.set_title("Drag Absolute Power")
ax4.set_xlabel("Time (s)")
ax4.set_ylabel("Power (W)")
ax4.legend()
ax4.grid()
plt.subplots_adjust(hspace=1)
plt.show()
return None
def plotFluidMechanicsData(self):
"""Prints out a summary of the Fluid Mechanics graphs available about
the Flight
Parameters
----------
None
Return
------
None
"""
# Post-process results
if self.postProcessed is False:
self.postProcess()
# Get index of out of rail time
outOfRailTimeIndexs = np.nonzero(self.x[:, 0] == self.outOfRailTime)
outOfRailTimeIndex = -1 if len(outOfRailTimeIndexs) == 0 else outOfRailTimeIndexs[0][0]
# Trajectory Fluid Mechanics Plots
fig10 = plt.figure(figsize=(9, 12))
ax1 = plt.subplot(411)
ax1.plot(self.MachNumber[:, 0], self.MachNumber[:, 1])
ax1.set_xlim(0, self.tFinal)
ax1.set_title("Mach Number")
ax1.set_xlabel("Time (s)")
ax1.set_ylabel("Mach Number")
ax1.grid()
ax2 = plt.subplot(412)
ax2.plot(self.ReynoldsNumber[:, 0], self.ReynoldsNumber[:, 1])
ax2.set_xlim(0, self.tFinal)
ax2.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
ax2.set_title("Reynolds Number")
ax2.set_xlabel("Time (s)")
ax2.set_ylabel("Reynolds Number")
ax2.grid()
ax3 = plt.subplot(413)
ax3.plot(
self.dynamicPressure[:, 0],
self.dynamicPressure[:, 1],
label="Dynamic Pressure",
)
ax3.plot(
self.totalPressure[:, 0], self.totalPressure[:, 1], label="Total Pressure"
)
ax3.plot(self.pressure[:, 0], self.pressure[:, 1], label="Static Pressure")
ax3.set_xlim(0, self.tFinal)
ax3.legend()
ax3.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
ax3.set_title("Total and Dynamic Pressure")
ax3.set_xlabel("Time (s)")
ax3.set_ylabel("Pressure (Pa)")
ax3.grid()
ax4 = plt.subplot(414)
ax4.plot(self.angleOfAttack[:, 0], self.angleOfAttack[:, 1])
ax4.set_xlim(self.outOfRailTime, 10*self.outOfRailTime)
ax4.set_ylim(0, self.angleOfAttack(self.outOfRailTime))
ax4.set_title("Angle of Attack")
ax4.set_xlabel("Time (s)")
ax4.set_ylabel("Angle of Attack (°)")
ax4.grid()
plt.subplots_adjust(hspace=0.5)
plt.show()
return None
def calculateFinFlutterAnalysis(self, finThickness, shearModulus):
""" Calculate, create and plot the Fin Flutter velocity, based on the
pressure profile provided by Atmosferic model selected. It considers the
Flutter Boundary Equation that is based on a calculation published in
NACA Technical Paper 4197.
Be careful, these results are only estimates of a real problem and may
not be useful for fins made from non-isotropic materials. These results
should not be used as a way to fully prove the safety of any rocket’s fins.
IMPORTANT: This function works if only a single set of fins is added
Parameters
----------
finThickness : float
The fin thickness, in meters
shearModulus : float
Shear Modulus of fins' material, must be given in Pascal
Return
------
None
"""
# Post-process results
if self.postProcessed is False:
self.postProcess()
s = (self.rocket.tipChord + self.rocket.rootChord) * self.rocket.span /2
ar = self.rocket.span * self.rocket.span / s
la = self.rocket.tipChord / self.rocket.rootChord
# Calculate the Fin Flutter Mach Number
self.flutterMachNumber = ((shearModulus*2*(ar+2)*(finThickness/self.rocket.rootChord)**3)/(1.337 * (ar**3) *(la+1) * self.pressure ))**0.5
# Calculate difference between Fin Flutter Mach Number and the Rocket Speed
self.difference = self.flutterMachNumber - self.MachNumber
# Calculate a safety factor for flutter
self.safetyFactor = self.flutterMachNumber / self.MachNumber
# Calculate the minimun Fin Flutter Mach Number and Velocity
# Calculate the time and height of minimun Fin Flutter Mach Number
minflutterMachNumberTimeIndex = np.argmin(self.flutterMachNumber[:,1])
minflutterMachNumber = self.flutterMachNumber[minflutterMachNumberTimeIndex,1]
minMFTime = self.flutterMachNumber[minflutterMachNumberTimeIndex,0]
minMFHeight = self.z(minMFTime) - self.env.elevation
minMFVelocity = minflutterMachNumber * self.env.speedOfSound(minMFHeight)
# Calculate minimum difference between Fin Flutter Mach Number and the Rocket Speed
# Calculate the time and height of the difference ...
minDifferenceTimeIndex = np.argmin(self.difference[:,1])
minDif = self.difference[minDifferenceTimeIndex,1]
minDifTime = self.difference[minDifferenceTimeIndex,0]
minDifHeight = self.z(minDifTime) - self.env.elevation
minDifVelocity = minDif * self.env.speedOfSound(minDifHeight)
# Calculate the minimun Fin Flutter Safety factor
# Calculate the time and height of minimun Fin Flutter Safety factor
minSFTimeIndex = np.argmin(self.safetyFactor[:,1])
minSF = self.safetyFactor[minSFTimeIndex,1]
minSFTime = self.safetyFactor[minSFTimeIndex,0]
minSFHeight = self.z(minSFTime) - self.env.elevation
# Print fin's geometric parameters
print("Fin's geometric parameters")
print("Surface area (S): {:.4f} m2".format(s))
print("Aspect ratio (AR): {:.3f}".format(ar))
print("TipChord/RootChord = \u03BB = {:.3f}".format(la))
print("Fin Thickness: {:.5f} m".format(finThickness))
# Print fin's material properties
print("\n\nFin's material properties")
print("Shear Modulus (G): {:.3e} Pa".format(shearModulus))
# Print a summary of the Fin Flutter Analysis
print("\n\nFin Flutter Analysis")
print(
"Minimum Fin Flutter Velocity: {:.3f} m/s at {:.2f} s".format(
minMFVelocity, minMFTime
)
)
print(
"Minimum Fin Flutter Mach Number: {:.3f} ".format(minflutterMachNumber)
)
#print(
# "Altitude of minimum Fin Flutter Velocity: {:.3f} m (AGL)".format(
# minMFHeight
# )
#)
print(
"Minimum of (Fin Flutter Mach Number - Rocket Speed): {:.3f} m/s at {:.2f} s".format(
minDifVelocity, minDifTime
)
)
print(
"Minimum of (Fin Flutter Mach Number - Rocket Speed): {:.3f} Mach at {:.2f} s".format(
minDif, minDifTime
)
)
#print(
# "Altitude of minimum (Fin Flutter Mach Number - Rocket Speed): {:.3f} m (AGL)".format(
# minDifHeight
# )
#)
print(
"Minimum Fin Flutter Safety Factor: {:.3f} at {:.2f} s".format(
minSF, minSFTime
)
)
print(
"Altitude of minimum Fin Flutter Safety Factor: {:.3f} m (AGL)\n\n".format(
minSFHeight
)
)
#Create plots
fig12 = plt.figure(figsize=(6, 9))
ax1 = plt.subplot(311)
ax1.plot()
ax1.plot(self.flutterMachNumber[:,0] , self.flutterMachNumber[:,1], label = "Fin flutter Mach Number")
ax1.plot(self.MachNumber[:,0], self.MachNumber[:,1], label= "Rocket Freestream Speed")
ax1.set_xlim(0, self.apogeeTime)
ax1.set_title("Fin Flutter Mach Number x Time(s)")
ax1.set_xlabel("Time (s)")
ax1.set_ylabel("Mach")
ax1.legend()
ax1.grid(True)
ax2 = plt.subplot(312)
ax2.plot(self.difference[:,0], self.difference[:,1])
ax2.set_xlim(0, self.apogeeTime)
ax2.set_title("Mach flutter - Freestream velocity")
ax2.set_xlabel("Time (s)")
ax2.set_ylabel("Mach")
ax2.grid()
ax3 = plt.subplot(313)
ax3.plot(self.safetyFactor[:,0], self.safetyFactor[:,1])
ax3.set_xlim(self.outOfRailTime, self.apogeeTime)
ax3.set_ylim(0, 6)
ax3.set_title("Fin Flutter Safety Factor")
ax3.set_xlabel("Time (s)")
ax3.set_ylabel("Safety Factor")
ax3.grid()
plt.subplots_adjust(hspace=0.5)
plt.show()
return None
def plotStabilityAndControlData(self):
"""Prints out Rocket Stability and Control parameters graphs available
about the Flight
Parameters
----------
None
Return
------
None
"""
# Post-process results
if self.postProcessed is False:
self.postProcess()
fig9 = plt.figure(figsize=(9, 6))
ax1 = plt.subplot(211)
ax1.plot(self.staticMargin[:, 0], self.staticMargin[:, 1])
ax1.set_xlim(0, self.staticMargin[:, 0][-1])
ax1.set_title("Static Margin")
ax1.set_xlabel("Time (s)")
ax1.set_ylabel("Static Margin (c)")
ax1.grid()
ax2 = plt.subplot(212)
maxAttitude = max(self.attitudeFrequencyResponse[:, 1])
maxAttitude = maxAttitude if maxAttitude != 0 else 1
ax2.plot(
self.attitudeFrequencyResponse[:, 0],
self.attitudeFrequencyResponse[:, 1] / maxAttitude,
label="Attitude Angle",
)
maxOmega1 = max(self.omega1FrequencyResponse[:, 1])
maxOmega1 = maxOmega1 if maxOmega1 != 0 else 1
ax2.plot(
self.omega1FrequencyResponse[:, 0],
self.omega1FrequencyResponse[:, 1] / maxOmega1,
label="$\omega_1$",
)
maxOmega2 = max(self.omega2FrequencyResponse[:, 1])
maxOmega2 = maxOmega2 if maxOmega2 != 0 else 1
ax2.plot(
self.omega2FrequencyResponse[:, 0],
self.omega2FrequencyResponse[:, 1] / maxOmega2,
label="$\omega_2$",
)
maxOmega3 = max(self.omega3FrequencyResponse[:, 1])
maxOmega3 = maxOmega3 if maxOmega3 != 0 else 1
ax2.plot(
self.omega3FrequencyResponse[:, 0],
self.omega3FrequencyResponse[:, 1] / maxOmega3,
label="$\omega_3$",
)
ax2.set_title("Frequency Response")
ax2.set_xlabel("Frequency (Hz)")
ax2.set_ylabel("Amplitude Magnitude Normalized")
ax2.set_xlim(0, 5)
ax2.legend()
ax2.grid()
plt.subplots_adjust(hspace=0.5)
plt.show()
return None
def plotPressureSignals(self):
""" Prints out all Parachute Trigger Pressure Signals.
This function can be called also for plot pressure data for flights
without Parachutes, in this case the Pressure Signals will be simply
the pressure provided by the atmosfericModel, at Flight z positions.
This means that no noise will be considered if at least one parachute
has not been added.
This function aims to help the engineer to visually check if there
isn't no anomalies with the Flight Simulation.
Parameters
----------
None
Return
------
None
"""
# Post-process results
if self.postProcessed is False:
self.postProcess()
if len(self.rocket.parachutes) == 0:
plt.figure()
ax1 = plt.subplot(111)
ax1.plot(self.z[:,0], self.env.pressure(self.z[:,1]))
ax1.set_title("Pressure at Rocket's Altitude")
ax1.set_xlabel("Time (s)")
ax1.set_ylabel("Pressure (Pa)")
ax1.set_xlim(0, self.tFinal)
ax1.grid()
plt.show()
else:
for parachute in self.rocket.parachutes:
print('Parachute: ', parachute.name)
parachute.noiseSignalFunction()
parachute.noisyPressureSignalFunction()
parachute.cleanPressureSignalFunction()
return None
def exportPressures(self, fileName, timeStep):
"""Exports the pressure experienced by the rocket during the flight to
an external file, the '.csv' format is recommended, as the columns will
be separated by commas. It can handle flights with or without parachutes,
although it is not possible to get a noisy pressure signal if no
parachute is added.
If a parachute is added, the file will contain 3 columns: time in seconds,
clean pressure in Pascals and noisy pressure in Pascals. For flights without
parachutes, the third column will be discarded
This function was created especially for the Projeto Jupiter Eletronics
Subsystems team and aims to help in configuring microcontrollers.
Parameters
----------
fileName : string
The final file name,
timeStep : float
Time step desired for the final file
Return
------
None
"""
if self.postProcessed is False:
self.postProcess()
timePoints = np.arange(0, self.tFinal, timeStep)
# Create the file
file = open(fileName, 'w')
if len(self.rocket.parachutes) == 0:
pressure = self.env.pressure(self.z(timePoints))
for i in range(0, timePoints.size, 1):
file.write("{:f}, {:.5f}\n".format(timePoints[i], pressure[i]))
else:
for parachute in self.rocket.parachutes:
for i in range(0, timePoints.size, 1):
pCl = parachute.cleanPressureSignalFunction(timePoints[i])
pNs = parachute.noisyPressureSignalFunction(timePoints[i])
file.write("{:f}, {:.5f}, {:.5f}\n".format(timePoints[i], pCl, pNs))
# We need to save only 1 parachute data
pass
file.close()
return None
def allInfo(self):
"""Prints out all data and graphs available about the Flight.
Parameters
----------
None
Return
------
None
"""
# Post-process results
if self.postProcessed is False:
self.postProcess()
# Print initial conditions
print("Initial Conditions\n")
self.printInitialConditionsData()
# Print launch rail orientation
print("\n\nLaunch Rail Orientation\n")
print("Launch Rail Inclination: {:.2f}°".format(self.inclination))
print("Launch Rail Heading: {:.2f}°\n\n".format(self.heading))
# Print a summary of data about the flight
self.info()
print("\n\nNumerical Integration Information\n")
self.printNumericalIntegrationSettings()
print("\n\nTrajectory 3d Plot\n")
self.plot3dTrajectory()
print("\n\nTrajectory Kinematic Plots\n")
self.plotLinearKinematicsData()
print("\n\nAngular Position Plots\n")
self.plotFlightPathAngleData()
print("\n\nPath, Attitude and Lateral Attitude Angle plots\n")
self.plotAttitudeData()
print("\n\nTrajectory Angular Velocity and Acceleration Plots\n")
self.plotAngularKinematicsData()
print("\n\nTrajectory Force Plots\n")
self.plotTrajectoryForceData()
print("\n\nTrajectory Energy Plots\n")
self.plotEnergyData()
print("\n\nTrajectory Fluid Mechanics Plots\n")
self.plotFluidMechanicsData()
print("\n\nTrajectory Stability and Control Plots\n")
self.plotStabilityAndControlData()
return None
def animate(self, start=0, stop=None, fps=12, speed=4, elev=None, azim=None):
"""Plays an animation of the flight. Not implemented yet. Only
kinda works outside notebook.
"""
# Set up stopping time
stop = self.tFinal if stop is None else stop
# Speed = 4 makes it almost real time - matplotlib is way to slow
# Set up graph
fig = plt.figure(figsize=(18, 15))
axes = fig.gca(projection="3d")
# Initialize time
timeRange = np.linspace(start, stop, fps * (stop - start))
# Initialize first frame
axes.set_title("Trajectory and Velocity Animation")
axes.set_xlabel("X (m)")
axes.set_ylabel("Y (m)")
axes.set_zlabel("Z (m)")
axes.view_init(elev, azim)
R = axes.quiver(0, 0, 0, 0, 0, 0, color="r", label="Rocket")
V = axes.quiver(0, 0, 0, 0, 0, 0, color="g", label="Velocity")
W = axes.quiver(0, 0, 0, 0, 0, 0, color="b", label="Wind")
S = axes.quiver(0, 0, 0, 0, 0, 0, color="black", label="Freestream")
axes.legend()
# Animate
for t in timeRange:
R.remove()
V.remove()
W.remove()
S.remove()
# Calculate rocket position
Rx, Ry, Rz = self.x(t), self.y(t), self.z(t)
Ru = 1 * (2 * (self.e1(t) * self.e3(t) + self.e0(t) * self.e2(t)))
Rv = 1 * (2 * (self.e2(t) * self.e3(t) - self.e0(t) * self.e1(t)))
Rw = 1 * (1 - 2 * (self.e1(t) ** 2 + self.e2(t) ** 2))
# Caclulate rocket Mach number
Vx = self.vx(t) / 340.40
Vy = self.vy(t) / 340.40
Vz = self.vz(t) / 340.40
# Caculate wind Mach Number
z = self.z(t)
Wx = self.env.windVelocityX(z) / 20
Wy = self.env.windVelocityY(z) / 20
# Calculate freestream Mach Number
Sx = self.streamVelocityX(t) / 340.40
Sy = self.streamVelocityY(t) / 340.40
Sz = self.streamVelocityZ(t) / 340.40
# Plot Quivers
R = axes.quiver(Rx, Ry, Rz, Ru, Rv, Rw, color="r")
V = axes.quiver(Rx, Ry, Rz, -Vx, -Vy, -Vz, color="g")
W = axes.quiver(Rx - Vx, Ry - Vy, Rz - Vz, Wx, Wy, 0, color="b")
S = axes.quiver(Rx, Ry, Rz, Sx, Sy, Sz, color="black")
# Adjust axis
axes.set_xlim(Rx - 1, Rx + 1)
axes.set_ylim(Ry - 1, Ry + 1)
axes.set_zlim(Rz - 1, Rz + 1)
# plt.pause(1/(fps*speed))
try:
plt.pause(1 / (fps * speed))
except:
time.sleep(1 / (fps * speed))
def timeIterator(self, nodeList):
i = 0
while i < len(nodeList) - 1:
yield i, nodeList[i]
i += 1
class FlightPhases:
def __init__(self, init_list=[]):
self.list = init_list[:]
def __getitem__(self, index):
return self.list[index]
def __len__(self):
return len(self.list)
def __repr__(self):
return str(self.list)
def add(self, flightPhase, index=None):
# Handle first phase
if len(self.list) == 0:
self.list.append(flightPhase)
# Handle appending to last position
elif index is None:
# Check if new flight phase respects time
previousPhase = self.list[-1]
if flightPhase.t > previousPhase.t:
# All good! Add phase.
self.list.append(flightPhase)
elif flightPhase.t == previousPhase.t:
print(
"WARNING: Trying to add a flight phase starting together with the one preceding it."
)
print(
"This may be caused by more than when parachute being triggered simultaneously."
)
flightPhase.t += 1e-7
self.add(flightPhase)
elif flightPhase.t < previousPhase.t:
print(
"WARNING: Trying to add a flight phase starting before the one preceding it."
)
print(
"This may be caused by more than when parachute being triggered simultaneously."
)
self.add(flightPhase, -2)
# Handle inserting into intermediary position
else:
# Check if new flight phase respects time
nextPhase = self.list[index]
previousPhase = self.list[index - 1]
if previousPhase.t < flightPhase.t < nextPhase.t:
# All good! Add phase.
self.list.insert(index, flightPhase)
elif flightPhase.t < previousPhase.t:
print(
"WARNING: Trying to add a flight phase starting before the one preceding it."
)
print(
"This may be caused by more than when parachute being triggered simultaneously."
)
self.add(flightPhase, index - 1)
elif flightPhase.t == previousPhase.t:
print(
"WARNING: Trying to add a flight phase starting together with the one preceding it."
)
print(
"This may be caused by more than when parachute being triggered simultaneously."
)
flightPhase.t += 1e-7
self.add(flightPhase, index)
elif flightPhase.t == nextPhase.t:
print(
"WARNING: Trying to add a flight phase starting together with the one proceding it."
)
print(
"This may be caused by more than when parachute being triggered simultaneously."
)
flightPhase.t += 1e-7
self.add(flightPhase, index + 1)
elif flightPhase.t > nextPhase.t:
print(
"WARNING: Trying to add a flight phase starting after the one proceding it."
)
print(
"This may be caused by more than when parachute being triggered simultaneously."
)
self.add(flightPhase, index + 1)
def addPhase(self, t, derivatives=None, callback=[], clear=True, index=None):
self.add(self.FlightPhase(t, derivatives, callback, clear), index)
def flushAfter(self, index):
del self.list[index + 1 :]
class FlightPhase:
def __init__(self, t, derivative=None, callbacks=[], clear=True):
self.t = t
self.derivative = derivative
self.callbacks = callbacks[:]
self.clear = clear
def __repr__(self):
if self.derivative is None:
return "{Initial Time: " + str(self.t) + " | Derivative: None}"
return (
"{Initial Time: "
+ str(self.t)
+ " | Derivative: "
+ self.derivative.__name__
+ "}"
)
class TimeNodes:
def __init__(self, init_list=[]):
self.list = init_list[:]
def __getitem__(self, index):
return self.list[index]
def __len__(self):
return len(self.list)
def __repr__(self):
return str(self.list)
def add(self, timeNode):
self.list.append(timeNode)
def addNode(self, t, parachutes, callbacks):
self.list.append(self.TimeNode(t, parachutes, callbacks))
def addParachutes(self, parachutes, t_init, t_end):
# Iterate over parachutes
for parachute in parachutes:
# Calculate start of sampling time nodes
pcDt = 1 / parachute.samplingRate
parachute_node_list = [
self.TimeNode(i * pcDt, [parachute], [])
for i in range(
math.ceil(t_init / pcDt), math.floor(t_end / pcDt) + 1
)
]
self.list += parachute_node_list
def sort(self):
self.list.sort(key=(lambda node: node.t))
def merge(self):
# Initialize temporary list
self.tmp_list = [self.list[0]]
self.copy_list = self.list[1:]
# Iterate through all other time nodes
for node in self.copy_list:
# If there is already another node with similar time: merge
if abs(node.t - self.tmp_list[-1].t) < 1e-7:
self.tmp_list[-1].parachutes += node.parachutes
self.tmp_list[-1].callbacks += node.callbacks
# Add new node to tmp list if there is none with the same time
else:
self.tmp_list.append(node)
# Save tmp list to permanent
self.list = self.tmp_list
def flushAfter(self, index):
del self.list[index + 1 :]
class TimeNode:
def __init__(self, t, parachutes, callbacks):
self.t = t
self.parachutes = parachutes
self.callbacks = callbacks
def __repr__(self):
return (
"{Initial Time: "
+ str(self.t)
+ " | Parachutes: "
+ str(len(self.parachutes))
+ "}"
) | /rocketpyalpha-0.9.6.tar.gz/rocketpyalpha-0.9.6/rocketpy/Flight.py | 0.806396 | 0.558869 | Flight.py | pypi |
# Rockets Python Client
> A small client for [Rockets](../README.md) using [JSON-RPC](https://www.jsonrpc.org) as
> communication contract over a [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket).
[](https://travis-ci.org/BlueBrain/Rockets)
[](https://pyup.io/repos/github/BlueBrain/Rockets/)
[](https://pypi.org/project/rockets/)
[](https://pypi.org/project/rockets/)
[](https://github.com/ambv/black)
[](https://lgtm.com/projects/g/BlueBrain/Rockets/context:python)
# Table of Contents
* [Installation](#installation)
* [Usage](#usage)
* [Connection](#connection)
* [Notifications](#notifications)
* [Requests](#requests)
* [Batching](#batching)
### Installation
----------------
You can install this package from [PyPI](https://pypi.org/):
```bash
pip install rockets
```
### Usage
---------
#### `Client` vs. `AsyncClient`
Rockets provides two types of clients to support asychronous and synchronous usage.
The `AsyncClient` exposes all of its functionality as `async` functions, hence an `asyncio`
[event loop](https://docs.python.org/3/library/asyncio-eventloop.html) is needed to complete pending
execution via `await` or `run_until_complete()`.
For simplicity, a synchronous `Client` is provided which automagically executes in a synchronous,
blocking fashion.
#### Connection
Create a client and connect:
```py
from rockets import Client
# client does not connect during __init__;
# either explicit or automatically on any notify/request/send
client = Client('myhost:8080')
client.connect()
print(client.connected())
```
Close the connection with the socket cleanly:
```py
from rockets import Client
client = Client('myhost:8080')
client.connect()
client.disconnect()
print(client.connected())
```
#### Server messages
Listen to server notifications:
```py
from rockets import Client
client = Client('myhost:8080')
client.notifications.subscribe(lambda msg: print("Got message:", msg.data))
```
**NOTE**: The notification object is of type `Notification`.
Listen to any server message:
```py
from rockets import Client
client = Client('myhost:8080')
client.ws_observable.subscribe(lambda msg: print("Got message:", msg))
```
#### Notifications
Send notifications to the server:
```py
from rockets import Client
client = Client('myhost:8080')
client.notify('mymethod', {'ping': True})
```
#### Requests
Make a synchronous, blocking request:
```py
from rockets import Client
client = Client('myhost:8080')
response = client.request('mymethod', {'ping': True})
print(response)
```
Handle a request error:
```py
from rockets import Client, RequestError
client = Client('myhost:8080')
try:
client.request('mymethod')
except RequestError as err:
print(err.code, err.message)
```
**NOTE**: Any error that may occur will be a `RequestError`.
#### Asynchronous requests
Make an asynchronous request, using the `AsyncClient` and `asyncio`:
```py
import asyncio
from rockets import AsyncClient
client = AsyncClient('myhost:8080')
request_task = client.async_request('mymethod', {'ping': True})
asyncio.get_event_loop().run_until_complete(request_task)
print(request_task.result())
```
Alternatively, you can use `add_done_callback()` from the returned `RequestTask` which is called
once the request has finished:
```py
import asyncio
from rockets import AsyncClient
client = AsyncClient('myhost:8080')
request_task = client.async_request('mymethod', {'ping': True})
request_task.add_done_callback(lambda task: print(task.result()))
asyncio.get_event_loop().run_until_complete(request_task)
```
If the `RequestTask` is not needed, i.e. no `cancel()` or `add_progress_callback()` is desired, use
the `request()` coroutine:
```py
import asyncio
from rockets import AsyncClient
client = AsyncClient('myhost:8080')
coro = client.request('mymethod', {'ping': True})
result = asyncio.get_event_loop().run_until_complete(coro)
print(result)
```
If you are already in an `async` function or in a Jupyter notebook cell, you may use `await` to
execute an asynchronous request:
```py
# Inside a notebook cell here
import asyncio
from rockets import AsyncClient
client = AsyncClient('myhost:8080')
result = await client.request('mymethod', {'ping': True})
print(result)
```
Cancel a request:
```py
from rockets import AsyncClient
client = AsyncClient('myhost:8080')
request_task = client.async_request('mymethod')
request_task.cancel()
```
Get progress updates for a request:
```py
from rockets import AsyncClient
client = AsyncClient('myhost:8080')
request_task = client.async_request('mymethod')
request_task.add_progress_callback(lambda progress: print(progress))
```
**NOTE**: The progress object is of type `RequestProgress`.
#### Batching
Make a batch request:
```py
from rockets import Client, Request, Notification
client = Client('myhost:8080')
request = Request('myrequest')
notification = Notification('mynotify')
responses = client.batch([request, notification])
for response in responses:
print(response)
```
Cancel a batch request:
```py
from rockets import AsyncClient
client = AsyncClient('myhost:8080')
request = Request('myrequest')
notification = Notification('mynotify')
request_task = client.async_batch([request, notification])
request_task.cancel()
```
| /rockets-1.0.3.tar.gz/rockets-1.0.3/README.md | 0.450843 | 0.910982 | README.md | pypi |
# Changelog
## [Unreleased](https://github.com/hackingmaterials/rocketsled/tree/HEAD)
[Full Changelog](https://github.com/hackingmaterials/rocketsled/compare/v2019.9.12...HEAD)
**Implemented enhancements:**
- Change versioning [\#81](https://github.com/hackingmaterials/rocketsled/issues/81)
- Enforce a code style [\#78](https://github.com/hackingmaterials/rocketsled/issues/78)
**Fixed bugs:**
- Prepend hostname to the PID for queue checking [\#80](https://github.com/hackingmaterials/rocketsled/issues/80)
- Fix codacy issues [\#58](https://github.com/hackingmaterials/rocketsled/issues/58)
- "scaling" portion of code is confusing [\#53](https://github.com/hackingmaterials/rocketsled/issues/53)
**Closed issues:**
- Update help link to new forum [\#82](https://github.com/hackingmaterials/rocketsled/issues/82)
- upgrade pymongo version [\#72](https://github.com/hackingmaterials/rocketsled/issues/72)
**Merged pull requests:**
- fix some codacy issues [\#92](https://github.com/hackingmaterials/rocketsled/pull/92) ([ardunn](https://github.com/ardunn))
- formatting fixes [\#91](https://github.com/hackingmaterials/rocketsled/pull/91) ([ardunn](https://github.com/ardunn))
- fix req conflict [\#90](https://github.com/hackingmaterials/rocketsled/pull/90) ([ardunn](https://github.com/ardunn))
- Bump matplotlib from 3.1.1 to 3.2.1 [\#89](https://github.com/hackingmaterials/rocketsled/pull/89) ([dependabot-preview[bot]](https://github.com/apps/dependabot-preview))
- Pidhostame [\#88](https://github.com/hackingmaterials/rocketsled/pull/88) ([ardunn](https://github.com/ardunn))
- Bump scipy from 1.3.1 to 1.4.1 [\#87](https://github.com/hackingmaterials/rocketsled/pull/87) ([dependabot-preview[bot]](https://github.com/apps/dependabot-preview))
- Bump fireworks from 1.9.4 to 1.9.5 [\#86](https://github.com/hackingmaterials/rocketsled/pull/86) ([dependabot-preview[bot]](https://github.com/apps/dependabot-preview))
- Bump pymongo from 3.9.0 to 3.10.1 [\#84](https://github.com/hackingmaterials/rocketsled/pull/84) ([dependabot-preview[bot]](https://github.com/apps/dependabot-preview))
- Bump numpy from 1.16.3 to 1.17.2 [\#79](https://github.com/hackingmaterials/rocketsled/pull/79) ([dependabot-preview[bot]](https://github.com/apps/dependabot-preview))
- Bump scipy from 1.2.1 to 1.3.1 [\#77](https://github.com/hackingmaterials/rocketsled/pull/77) ([dependabot-preview[bot]](https://github.com/apps/dependabot-preview))
- Bump fireworks from 1.9.0 to 1.9.4 [\#76](https://github.com/hackingmaterials/rocketsled/pull/76) ([dependabot-preview[bot]](https://github.com/apps/dependabot-preview))
- Bump matplotlib from 3.0.3 to 3.1.1 [\#75](https://github.com/hackingmaterials/rocketsled/pull/75) ([dependabot-preview[bot]](https://github.com/apps/dependabot-preview))
- Bump pymongo from 3.7.2 to 3.9.0 [\#74](https://github.com/hackingmaterials/rocketsled/pull/74) ([dependabot-preview[bot]](https://github.com/apps/dependabot-preview))
- Bump scikit-learn from 0.20.3 to 0.21.3 [\#73](https://github.com/hackingmaterials/rocketsled/pull/73) ([dependabot-preview[bot]](https://github.com/apps/dependabot-preview))
## [v2019.9.12](https://github.com/hackingmaterials/rocketsled/tree/v2019.9.12) (2019-09-11)
[Full Changelog](https://github.com/hackingmaterials/rocketsled/compare/v2019.9.11...v2019.9.12)
## [v2019.9.11](https://github.com/hackingmaterials/rocketsled/tree/v2019.9.11) (2019-09-11)
[Full Changelog](https://github.com/hackingmaterials/rocketsled/compare/v2019.6.5...v2019.9.11)
**Closed issues:**
- General comment on code and examples [\#56](https://github.com/hackingmaterials/rocketsled/issues/56)
## [v2019.6.5](https://github.com/hackingmaterials/rocketsled/tree/v2019.6.5) (2019-06-05)
[Full Changelog](https://github.com/hackingmaterials/rocketsled/compare/v2019.6.4...v2019.6.5)
## [v2019.6.4](https://github.com/hackingmaterials/rocketsled/tree/v2019.6.4) (2019-06-05)
[Full Changelog](https://github.com/hackingmaterials/rocketsled/compare/v2019.5.3...v2019.6.4)
## [v2019.5.3](https://github.com/hackingmaterials/rocketsled/tree/v2019.5.3) (2019-05-04)
[Full Changelog](https://github.com/hackingmaterials/rocketsled/compare/v2019.5.2...v2019.5.3)
## [v2019.5.2](https://github.com/hackingmaterials/rocketsled/tree/v2019.5.2) (2019-05-04)
[Full Changelog](https://github.com/hackingmaterials/rocketsled/compare/v2019.4.17...v2019.5.2)
## [v2019.4.17](https://github.com/hackingmaterials/rocketsled/tree/v2019.4.17) (2019-04-18)
[Full Changelog](https://github.com/hackingmaterials/rocketsled/compare/v2019.3.15...v2019.4.17)
**Closed issues:**
- add paper citation to rocketsled [\#42](https://github.com/hackingmaterials/rocketsled/issues/42)
## [v2019.3.15](https://github.com/hackingmaterials/rocketsled/tree/v2019.3.15) (2019-03-16)
[Full Changelog](https://github.com/hackingmaterials/rocketsled/compare/v2019.2.27...v2019.3.15)
**Closed issues:**
- Transition to unittest [\#64](https://github.com/hackingmaterials/rocketsled/issues/64)
- Comprehensive guide needs update [\#59](https://github.com/hackingmaterials/rocketsled/issues/59)
- tutorial rework [\#55](https://github.com/hackingmaterials/rocketsled/issues/55)
## [v2019.2.27](https://github.com/hackingmaterials/rocketsled/tree/v2019.2.27) (2019-02-27)
[Full Changelog](https://github.com/hackingmaterials/rocketsled/compare/v2019.2.17...v2019.2.27)
**Merged pull requests:**
- Fix typo, when all inputs are floats [\#65](https://github.com/hackingmaterials/rocketsled/pull/65) ([RemiLehe](https://github.com/RemiLehe))
## [v2019.2.17](https://github.com/hackingmaterials/rocketsled/tree/v2019.2.17) (2019-02-19)
[Full Changelog](https://github.com/hackingmaterials/rocketsled/compare/v2019.1.1...v2019.2.17)
**Merged pull requests:**
- Minor corrections to the tutorial and examples [\#63](https://github.com/hackingmaterials/rocketsled/pull/63) ([RemiLehe](https://github.com/RemiLehe))
## [v2019.1.1](https://github.com/hackingmaterials/rocketsled/tree/v2019.1.1) (2019-01-01)
[Full Changelog](https://github.com/hackingmaterials/rocketsled/compare/v2018.12.30...v2019.1.1)
## [v2018.12.30](https://github.com/hackingmaterials/rocketsled/tree/v2018.12.30) (2019-01-01)
[Full Changelog](https://github.com/hackingmaterials/rocketsled/compare/v2018.12.31...v2018.12.30)
## [v2018.12.31](https://github.com/hackingmaterials/rocketsled/tree/v2018.12.31) (2019-01-01)
[Full Changelog](https://github.com/hackingmaterials/rocketsled/compare/v2018.12.26...v2018.12.31)
**Closed issues:**
- Most type checking and metadata can be stored as central db doc [\#57](https://github.com/hackingmaterials/rocketsled/issues/57)
- don't understand check\_dims [\#50](https://github.com/hackingmaterials/rocketsled/issues/50)
- make sure all instance attributes are only set in the \_\_init\_\_ method\(\) [\#48](https://github.com/hackingmaterials/rocketsled/issues/48)
## [v2018.12.26](https://github.com/hackingmaterials/rocketsled/tree/v2018.12.26) (2018-12-27)
[Full Changelog](https://github.com/hackingmaterials/rocketsled/compare/1.1...v2018.12.26)
**Closed issues:**
- suggest rename \_x\_opt and \_y\_opt to simply \_x and \_y [\#54](https://github.com/hackingmaterials/rocketsled/issues/54)
- better documentation for example tasks [\#52](https://github.com/hackingmaterials/rocketsled/issues/52)
- add docs to return\_means [\#51](https://github.com/hackingmaterials/rocketsled/issues/51)
- why is XZ\_new one variable? [\#49](https://github.com/hackingmaterials/rocketsled/issues/49)
- rename n\_boots n\_bootstrap [\#47](https://github.com/hackingmaterials/rocketsled/issues/47)
- "Attributes" section of docstring [\#46](https://github.com/hackingmaterials/rocketsled/issues/46)
- remove random\_proba [\#45](https://github.com/hackingmaterials/rocketsled/issues/45)
- suggest rename of "space" parameter to "dimensions\_file" [\#44](https://github.com/hackingmaterials/rocketsled/issues/44)
- remove db name, host, port, and db\_extras from OptTask [\#43](https://github.com/hackingmaterials/rocketsled/issues/43)
- Batch mode may produce duplicates [\#36](https://github.com/hackingmaterials/rocketsled/issues/36)
- Add ability to disable duplicate checking and actually run optimizations in parallel [\#11](https://github.com/hackingmaterials/rocketsled/issues/11)
## [1.1](https://github.com/hackingmaterials/rocketsled/tree/1.1) (2018-07-30)
[Full Changelog](https://github.com/hackingmaterials/rocketsled/compare/1c24fadc55be95f1bb3dc9c4d271d56d980ca547...1.1)
**Closed issues:**
- Rename XZ\* to Z\* [\#40](https://github.com/hackingmaterials/rocketsled/issues/40)
- Docs should be revised [\#39](https://github.com/hackingmaterials/rocketsled/issues/39)
- Remove hyperparameter optimization + useless optimizers [\#38](https://github.com/hackingmaterials/rocketsled/issues/38)
- Add to analyze/visualize \(and \_predict?\) Ability to rank pareto solutions [\#35](https://github.com/hackingmaterials/rocketsled/issues/35)
- Mutli-objective optimizations only seem to maximize [\#34](https://github.com/hackingmaterials/rocketsled/issues/34)
- Convert dtypes to namedtuple [\#32](https://github.com/hackingmaterials/rocketsled/issues/32)
- Python 3 bson issue [\#31](https://github.com/hackingmaterials/rocketsled/issues/31)
- Add ability to use x only as an index, or unique tag, not as learning features [\#30](https://github.com/hackingmaterials/rocketsled/issues/30)
- Figure out a good way to scale data for optimizers... [\#29](https://github.com/hackingmaterials/rocketsled/issues/29)
- Fix LCB for acquisition function [\#28](https://github.com/hackingmaterials/rocketsled/issues/28)
- Add logging/verbosity [\#27](https://github.com/hackingmaterials/rocketsled/issues/27)
- Add Other optimization algorithms [\#26](https://github.com/hackingmaterials/rocketsled/issues/26)
- Speed improvements [\#25](https://github.com/hackingmaterials/rocketsled/issues/25)
- Figure out parallel bootstrapping [\#24](https://github.com/hackingmaterials/rocketsled/issues/24)
- Choose a good number of default bootstraps [\#23](https://github.com/hackingmaterials/rocketsled/issues/23)
- Change random\_interval to a probability [\#22](https://github.com/hackingmaterials/rocketsled/issues/22)
- Write tests for parallel duplicates [\#21](https://github.com/hackingmaterials/rocketsled/issues/21)
- Make better docs/tutorials [\#20](https://github.com/hackingmaterials/rocketsled/issues/20)
- Stop rs\_examples/benchmarks being its own package [\#19](https://github.com/hackingmaterials/rocketsled/issues/19)
- Decide on a way to store models persistently [\#18](https://github.com/hackingmaterials/rocketsled/issues/18)
- Make an auto-setup [\#17](https://github.com/hackingmaterials/rocketsled/issues/17)
- Add tags to each mongo doc? [\#16](https://github.com/hackingmaterials/rocketsled/issues/16)
- Various probabilistic functions for sampling spaces [\#15](https://github.com/hackingmaterials/rocketsled/issues/15)
- Add uncertainty estimation + more advanced methods of prediction [\#14](https://github.com/hackingmaterials/rocketsled/issues/14)
- Decide on whether hyperparameter optimization is actually useful [\#13](https://github.com/hackingmaterials/rocketsled/issues/13)
- Multi objective optimization [\#12](https://github.com/hackingmaterials/rocketsled/issues/12)
- examples should not use default FireWorks database [\#6](https://github.com/hackingmaterials/rocketsled/issues/6)
- docstring style should be Google [\#5](https://github.com/hackingmaterials/rocketsled/issues/5)
- close issues when done! [\#4](https://github.com/hackingmaterials/rocketsled/issues/4)
- rename root dir [\#3](https://github.com/hackingmaterials/rocketsled/issues/3)
- remove launcher\_\* dirs from github [\#2](https://github.com/hackingmaterials/rocketsled/issues/2)
- remove .idea from github repo [\#1](https://github.com/hackingmaterials/rocketsled/issues/1)
**Merged pull requests:**
- Fix LCB and add hyper-parameters to acq functions [\#41](https://github.com/hackingmaterials/rocketsled/pull/41) ([spacedome](https://github.com/spacedome))
\* *This Changelog was automatically generated by [github_changelog_generator](https://github.com/github-changelog-generator/github-changelog-generator)*
| /rocketsled-1.0.1.20200523.tar.gz/rocketsled-1.0.1.20200523/CHANGELOG.md | 0.716913 | 0.736685 | CHANGELOG.md | pypi |
rockfinder
==========
[](http://rockfinder.readthedocs.io/en/latest/?badge)
[](https://cdn.rawgit.com/thespacedoctor/rockfinder/master/htmlcov/index.html)
*A python package and command-line tools for A python package and command-line suite to generate solar-system body ephemerides and to determine if specific transient dections are in fact known asteroids*.
Command-Line Usage
==================
``` sourceCode
Usage:
rockfinder where [-e] [csv|md|rst|json|yaml] <objectId> <mjd>...
csv output results in csv format
md output results as a markdown table
rst output results as a restructured text table
json output results in json format
yaml output results in yaml format
-e, --extra return extra ephemeris info (verbose)
-h, --help show this help message
```
Installation
============
The easiest way to install rockfinder is to use `pip`:
``` sourceCode
pip install rockfinder
```
Or you can clone the [github repo](https://github.com/thespacedoctor/rockfinder) and install from a local version of the code:
``` sourceCode
git clone git@github.com:thespacedoctor/rockfinder.git
cd rockfinder
python setup.py install
```
To upgrade to the latest version of rockfinder use the command:
``` sourceCode
pip install rockfinder --upgrade
```
Documentation
=============
Documentation for rockfinder is hosted by [Read the Docs](http://rockfinder.readthedocs.org/en/stable/) (last [stable version](http://rockfinder.readthedocs.org/en/stable/) and [latest version](http://rockfinder.readthedocs.org/en/latest/)).
Command-Line Tutorial
=====================
Let’s say we want to generate an ephemeris for Ceres. We can either identify Ceres with its human-friendly name, its MPC number (1) or its MPC packed format (00001). I can grab an ephemeris from the JPL-Horizons for MJD=57967.564 with either of the following commands:
``` sourceCode
rockfinder where 1 57967.546
rockfinder where ceres 57967.546
rockfinder where 00001 57967.546
```
This returns the ephemeris in a neatly formatted table:
``` sourceCode
+-------------+-----------+----------+----------------+-----------------+---------------------+----------------------+---------------+------------------------+--------------------+--------------+
| mjd | ra_deg | dec_deg | ra_3sig_error | dec_3sig_error | ra_arcsec_per_hour | dec_arcsec_per_hour | apparent_mag | heliocentric_distance | observer_distance | phase_angle |
+-------------+-----------+----------+----------------+-----------------+---------------------+----------------------+---------------+------------------------+--------------------+--------------+
| 57967.5460 | 100.2386 | 24.2143 | 0.0000 | 0.0000 | 61.8963 | 0.8853 | 8.9100 | 2.6668 | 3.4864 | 11.2662 |
+-------------+-----------+----------+----------------+-----------------+---------------------+----------------------+---------------+------------------------+--------------------+--------------+
```
To make the results returned from Horizons a little more verbose, use the -e flag:
``` sourceCode
rockfinder where -e ceres 57967.546
```
``` sourceCode
+-------------+-----------+----------+----------------+-----------------+---------------------+----------------------+---------------+------------------------+----------------------+--------------------+------------------+--------------+---------------------+---------------------+-----------------------+-----------------------+----------------------------------+----------------------------+---------------------------+
| mjd | ra_deg | dec_deg | ra_3sig_error | dec_3sig_error | ra_arcsec_per_hour | dec_arcsec_per_hour | apparent_mag | heliocentric_distance | heliocentric_motion | observer_distance | observer_motion | phase_angle | true_anomaly_angle | surface_brightness | sun_obs_target_angle | sun_target_obs_angle | apparent_motion_relative_to_sun | phase_angle_bisector_long | phase_angle_bisector_lat |
+-------------+-----------+----------+----------------+-----------------+---------------------+----------------------+---------------+------------------------+----------------------+--------------------+------------------+--------------+---------------------+---------------------+-----------------------+-----------------------+----------------------------------+----------------------------+---------------------------+
| 57967.5460 | 100.2386 | 24.2143 | 0.0000 | 0.0000 | 61.8963 | 0.8853 | 8.9100 | 2.6668 | -1.2317 | 3.4864 | -13.2972 | 11.2662 | 294.8837 | 6.5600 | 30.8803 | 11.2614 | L | 93.6995 | 1.2823 |
+-------------+-----------+----------+----------------+-----------------+---------------------+----------------------+---------------+------------------------+----------------------+--------------------+------------------+--------------+---------------------+---------------------+-----------------------+-----------------------+----------------------------------+----------------------------+---------------------------+
```
Returning a multi-epoch ephemeris
---------------------------------
To return an ephemeris covering multiple epoch, simply append extra MJD values to the command:
``` sourceCode
rockfinder where ceres 57967.546 57970.146 57975.683 57982.256 57994.547
```
``` sourceCode
+-------------+-----------+----------+----------------+-----------------+---------------------+----------------------+---------------+------------------------+--------------------+--------------+
| mjd | ra_deg | dec_deg | ra_3sig_error | dec_3sig_error | ra_arcsec_per_hour | dec_arcsec_per_hour | apparent_mag | heliocentric_distance | observer_distance | phase_angle |
+-------------+-----------+----------+----------------+-----------------+---------------------+----------------------+---------------+------------------------+--------------------+--------------+
| 57967.5460 | 100.2386 | 24.2143 | 0.0000 | 0.0000 | 61.8963 | 0.8853 | 8.9100 | 2.6668 | 3.4864 | 11.2662 |
| 57970.1460 | 101.4080 | 24.2238 | 0.0000 | 0.0000 | 61.6860 | -0.0088 | 8.9100 | 2.6649 | 3.4666 | 11.7406 |
| 57975.6830 | 103.8887 | 24.2210 | 0.0000 | 0.0000 | 60.6418 | -0.3915 | 8.9200 | 2.6610 | 3.4221 | 12.7383 |
| 57982.2560 | 106.8029 | 24.1784 | 0.0000 | 0.0000 | 60.9023 | -1.6280 | 8.9200 | 2.6565 | 3.3653 | 13.8893 |
| 57994.5470 | 112.1475 | 24.0019 | 0.0000 | 0.0000 | 58.6741 | -2.6660 | 8.9100 | 2.6481 | 3.2476 | 15.9324 |
+-------------+-----------+----------+----------------+-----------------+---------------------+----------------------+---------------+------------------------+--------------------+--------------+
```
Changing the output format
--------------------------
The command-line version of rockfinder has the ability to output the ephemeris results in various formats (csv, json, markdown table, restructured text table, yaml, ascii table). State an output format to render the results:
``` sourceCode
rockfinder where -e json ceres 57967.546
```
``` sourceCode
[
{
"apparent_mag": 8.91,
"apparent_motion_relative_to_sun": "L",
"dec_3sig_error": 0.0,
"dec_arcsec_per_hour": 0.885313,
"dec_deg": 24.2142655,
"heliocentric_distance": 2.666789121428,
"heliocentric_motion": -1.231677,
"mjd": 57967.54600000009,
"observer_distance": 3.48635600851733,
"observer_motion": -13.2971761,
"phase_angle": 11.2662,
"phase_angle_bisector_lat": 1.2823,
"phase_angle_bisector_long": 93.6995,
"ra_3sig_error": 0.0,
"ra_arcsec_per_hour": 61.89635,
"ra_deg": 100.2386357,
"sun_obs_target_angle": 30.8803,
"sun_target_obs_angle": 11.2614,
"surface_brightness": 6.56,
"true_anomaly_angle": 294.8837
}
]
```
| /rockfinder-0.1.2.tar.gz/rockfinder-0.1.2/blog-post.md | 0.705481 | 0.902995 | blog-post.md | pypi |
from typing import Dict, Optional
import pytds
from dls_utilpack.callsign import callsign
from dls_utilpack.require import require
# Crystal plate constants.
from xchembku_api.crystal_plate_objects.constants import TREENODE_NAMES_TO_THING_TYPES
class FtrixClient:
def __init__(self, specification: Dict):
s = f"{callsign(self)} specification"
self.__mssql = require(s, specification, "mssql")
async def connect(self):
pass
async def disconnect(self):
pass
# ----------------------------------------------------------------------------------------
async def query_barcode(self, barcode: str) -> Optional[Dict]:
"""
Query the formulatrix database for te plate record with the given barcode.
"""
server = self.__mssql["server"]
if server == "dummy":
return await self.query_barcode_dummy(barcode)
else:
return await self.query_barcode_mssql(barcode)
# ----------------------------------------------------------------------------------------
async def query_barcode_mssql(self, barcode: str) -> Optional[Dict]:
"""
Query the MSSQL formulatrix database for te plate record with the given barcode.
"""
# Connect to the RockMaker database at every tick.
# TODO: Handle failure to connect to RockMaker database.
connection = pytds.connect(
self.__mssql["server"],
self.__mssql["database"],
self.__mssql["username"],
self.__mssql["password"],
)
# Select only plate types we care about.
treenode_names = [
f"'{str(name)}'" for name in list(TREENODE_NAMES_TO_THING_TYPES.keys())
]
# Plate's treenode is "ExperimentPlate".
# Parent of ExperimentPlate is "Experiment", aka visit
# Parent of Experiment is "Project", aka plate type.
# Parent of Project is "ProjectsFolder", we only care about "XChem"
# Get all xchem barcodes and the associated experiment name.
sql = (
"SELECT"
"\n Plate.ID AS id,"
"\n Plate.Barcode AS barcode,"
"\n experiment_node.Name AS experiment,"
"\n plate_type_node.Name AS plate_type"
"\nFROM Plate"
"\nJOIN Experiment ON experiment.ID = plate.experimentID"
"\nJOIN TreeNode AS experiment_node ON experiment_node.ID = Experiment.TreeNodeID"
"\nJOIN TreeNode AS plate_type_node ON plate_type_node.ID = experiment_node.ParentID"
"\nJOIN TreeNode AS projects_folder_node ON projects_folder_node.ID = plate_type_node.ParentID"
f"\nWHERE Plate.Barcode = '{barcode}'"
"\n AND projects_folder_node.Name = 'xchem'"
f"\n AND plate_type_node.Name IN ({',' .join(treenode_names)})"
)
cursor = connection.cursor()
cursor.execute(sql)
rows = cursor.fetchall()
if len(rows) == 0:
return None
else:
row = rows[0]
record = {
"formulatrix__plate__id": row[0],
"barcode": row[1],
"formulatrix__experiment__name": row[2],
"plate_type": row[3],
}
return record
# ----------------------------------------------------------------------------------------
async def query_barcode_dummy(self, barcode: str) -> Optional[Dict]:
"""
Query the dummy database for te plate record with the given barcode.
"""
database = self.__mssql["database"]
rows = self.__mssql[database]
for row in rows:
if row[1] == barcode:
record = {
"formulatrix__plate__id": row[0],
"barcode": row[1],
"formulatrix__experiment__name": row[2],
"plate_type": row[3],
}
return record
return None
class FtrixClientContext:
def __init__(self, specification):
self.__client = FtrixClient(specification)
async def __aenter__(self):
await self.__client.connect()
return self.__client
async def __aexit__(self, type, value, traceback):
if self.__client is not None:
await self.__client.disconnect()
self.__client = None | /rockingester-3.0.5.tar.gz/rockingester-3.0.5/src/rockingester_lib/ftrix_client.py | 0.701611 | 0.256253 | ftrix_client.py | pypi |
import logging
from typing import Dict
# Base class for an asyncio server context.
from dls_utilpack.server_context_base import ServerContextBase
# Things created in the context.
from rockingester_lib.collectors.collectors import Collectors
logger = logging.getLogger(__name__)
thing_type = "rockingester_lib.collectors.context"
class Context(ServerContextBase):
"""
Asyncio context for a collector object.
On entering, it creates the object according to the specification (a dict).
If specified, it starts the server as a coroutine, thread or process.
If not a server, then it will instatiate a direct access to a collector.
On exiting, it commands the server to shut down and/or releases the direct access resources.
"""
# ----------------------------------------------------------------------------------------
def __init__(self, specification: Dict):
"""
Constructor.
Args:
specification (Dict): specification of the collector object to be constructed within the context.
The only key in the specification that relates to the context is "start_as", which can be "coro", "thread", "process", "direct", or None.
All other keys in the specification relate to creating the collector object.
"""
ServerContextBase.__init__(self, thing_type, specification)
# ----------------------------------------------------------------------------------------
async def aenter(self) -> None:
"""
Asyncio context entry.
Starts and activates service as specified.
Establishes the global (singleton-like) default collector.
"""
# Build the object according to the specification.
self.server = Collectors().build_object(self.specification())
if self.context_specification.get("start_as") == "coro":
await self.server.activate_coro()
elif self.context_specification.get("start_as") == "thread":
await self.server.start_thread()
elif self.context_specification.get("start_as") == "process":
await self.server.start_process()
# Not running as a service?
elif self.context_specification.get("start_as") == "direct":
# We need to activate the tick() task.
await self.server.activate()
# ----------------------------------------------------------------------------------------
async def aexit(self, type=None, value=None, traceback=None):
"""
Asyncio context exit.
Stop service if one was started and releases any client resources.
"""
logger.debug(f"[DISSHU] {thing_type} aexit")
if self.server is not None:
if self.context_specification.get("start_as") == "process":
# The server associated with this context is running?
if await self.is_process_alive():
logger.debug(f"[DISSHU] {thing_type} calling client_shutdown")
# Put in request to shutdown the server.
await self.server.client_shutdown()
if self.context_specification.get("start_as") == "coro":
await self.server.direct_shutdown()
if self.context_specification.get("start_as") == "direct":
await self.server.deactivate() | /rockingester-3.0.5.tar.gz/rockingester-3.0.5/src/rockingester_lib/collectors/context.py | 0.765944 | 0.201715 | context.py | pypi |
import logging
import multiprocessing
import threading
# Utilities.
from dls_utilpack.callsign import callsign
from dls_utilpack.require import require
# Base class which maps flask tasks to methods.
from dls_utilpack.thing import Thing
# Base class for an aiohttp server.
from rockingester_lib.base_aiohttp import BaseAiohttp
# Factory to make a Collector.
from rockingester_lib.collectors.collectors import Collectors
# Collector protocolj things.
from rockingester_lib.collectors.constants import Commands, Keywords
logger = logging.getLogger(__name__)
thing_type = "rockingester_lib.collectors.aiohttp"
# ------------------------------------------------------------------------------------------
class Aiohttp(Thing, BaseAiohttp):
"""
Object representing an image collector.
The behavior is to start a direct collector coro task or process
to waken every few seconds and scan for incoming files.
Then start up a web server to handle generic commands and queries.
"""
# ----------------------------------------------------------------------------------------
def __init__(self, specification=None, predefined_uuid=None):
Thing.__init__(self, thing_type, specification, predefined_uuid=predefined_uuid)
BaseAiohttp.__init__(
self, specification["type_specific_tbd"]["aiohttp_specification"]
)
self.__direct_collector = None
# ----------------------------------------------------------------------------------------
def callsign(self) -> str:
"""
Put the class name into the base class's call sign.
Returns:
str: call sign withi class name in it
"""
return "%s %s" % ("Collector.Aiohttp", BaseAiohttp.callsign(self))
# ----------------------------------------------------------------------------------------
def activate_process(self) -> None:
"""
Activate the direct collector and web server in a new process.
Meant to be called from inside a newly started process.
"""
try:
multiprocessing.current_process().name = "collector"
self.activate_process_base()
except Exception as exception:
logger.exception("exception in collector process", exc_info=exception)
# ----------------------------------------------------------------------------------------
def activate_thread(self, loop) -> None:
"""
Activate the direct collector and web server in a new thread.
Meant to be called from inside a newly created thread.
"""
try:
threading.current_thread().name = "collector"
self.activate_thread_base(loop)
except Exception as exception:
logger.exception(
f"unable to start {callsign(self)} thread", exc_info=exception
)
# ----------------------------------------------------------------------------------------
async def activate_coro(self) -> None:
"""
Activate the direct collector and web server in a two asyncio tasks.
"""
try:
# Turn off noisy debug from the PIL library.
logging.getLogger("PIL").setLevel("INFO")
# Build a local collector for our back-end.
self.__direct_collector = Collectors().build_object(
self.specification()["type_specific_tbd"][
"direct_collector_specification"
]
)
# Get the local implementation started.
await self.__direct_collector.activate()
await BaseAiohttp.activate_coro_base(self)
except Exception as exception:
raise RuntimeError(
"exception while starting collector server"
) from exception
# ----------------------------------------------------------------------------------------
async def direct_shutdown(self) -> None:
"""
Shut down any started sub-process or coro tasks.
Then call the base_direct_shutdown to shut down the webserver.
"""
logger.info(
f"[COLSHUT] in direct_shutdown self.__direct_collector is {self.__direct_collector}"
)
# ----------------------------------------------
if self.__direct_collector is not None:
# Disconnect our local dataface connection, i.e. the one which holds the database connection.
logger.info("[COLSHUT] awaiting self.__direct_collector.deactivate()")
await self.__direct_collector.deactivate()
logger.info(
"[COLSHUT] got return from self.__direct_collector.deactivate()"
)
# ----------------------------------------------
# Let the base class stop the server listener.
await self.base_direct_shutdown()
# ----------------------------------------------------------------------------------------
async def __do_locally(self, function, args, kwargs):
""""""
# logger.info(describe("function", function))
# logger.info(describe("args", args))
# logger.info(describe("kwargs", kwargs))
function = getattr(self.__direct_collector, function)
response = await function(*args, **kwargs)
return response
# ----------------------------------------------------------------------------------------
async def dispatch(self, request_dict, opaque):
""""""
command = require("request json", request_dict, Keywords.COMMAND)
if command == Commands.EXECUTE:
payload = require("request json", request_dict, Keywords.PAYLOAD)
response = await self.__do_locally(
payload["function"], payload["args"], payload["kwargs"]
)
else:
raise RuntimeError("invalid command %s" % (command))
return response | /rockingester-3.0.5.tar.gz/rockingester-3.0.5/src/rockingester_lib/collectors/aiohttp.py | 0.641085 | 0.161056 | aiohttp.py | pypi |
import asyncio
import logging
import os
import shutil
import time
from pathlib import Path
from typing import List
from dls_utilpack.callsign import callsign
from dls_utilpack.explain import explain2
from dls_utilpack.require import require
from dls_utilpack.visit import get_xchem_directory
from PIL import Image
# Crystal plate object interface.
from xchembku_api.crystal_plate_objects.interface import (
Interface as CrystalPlateInterface,
)
# Dataface client context.
from xchembku_api.datafaces.context import Context as XchembkuDatafaceClientContext
# Crystal plate pydantic model.
from xchembku_api.models.crystal_plate_model import CrystalPlateModel
# Crystal well pydantic model.
from xchembku_api.models.crystal_well_model import CrystalWellModel
# Crystal plate objects factory.
from xchembku_lib.crystal_plate_objects.crystal_plate_objects import CrystalPlateObjects
# Base class for collector instances.
from rockingester_lib.collectors.base import Base as CollectorBase
# Object able to talk to the formulatrix database.
from rockingester_lib.ftrix_client import FtrixClient
# Object which can inject new xchembku plate records discovered while looking in subwell images.
from rockingester_lib.plate_injector import PlateInjector
logger = logging.getLogger(__name__)
thing_type = "rockingester_lib.collectors.direct_poll"
# ------------------------------------------------------------------------------------------
class DirectPoll(CollectorBase):
"""
Object representing an image collector.
The behavior is to start a coro task to waken every few seconds and scan for newly created plate directories.
Image files are pushed to xchembku.
Plates for the image files are also pushed to xchembku the first time they are wanted.
"""
# ----------------------------------------------------------------------------------------
def __init__(self, specification, predefined_uuid=None):
CollectorBase.__init__(
self, thing_type, specification, predefined_uuid=predefined_uuid
)
s = f"{callsign(self)} specification", self.specification()
type_specific_tbd = require(s, self.specification(), "type_specific_tbd")
# The sources for the collecting.
self.__plates_directories = require(s, type_specific_tbd, "plates_directories")
# The root directory of all visits.
self.__visits_directory = Path(
require(s, type_specific_tbd, "visits_directory")
)
# The subdirectory under a visit where to put subwell images that are collected.
self.__visit_plates_subdirectory = Path(
require(s, type_specific_tbd, "visit_plates_subdirectory")
)
# Reference the dict entry for the ftrix client specification.
self.__ftrix_client_specification = require(
s, type_specific_tbd, "ftrix_client_specification"
)
# Explicit list of barcodes to process (used when testing a deployment).
self.__ingest_only_barcodes = type_specific_tbd.get("ingest_only_barcodes")
# Maximum time to wait for final image to arrive, relative to time of last arrived image.
self.__max_wait_seconds = require(s, type_specific_tbd, "max_wait_seconds")
# Database where we will get plate barcodes and add new wells.
self.__xchembku_client_context = None
self.__xchembku = None
# Object able to talk to the formulatrix database.
self.__ftrix_client = None
# This flag will stop the ticking async task.
self.__keep_ticking = True
self.__tick_future = None
# The plate names which we have already finished handling within the current instance.
self.__handled_plate_names = []
# ----------------------------------------------------------------------------------------
async def activate(self) -> None:
"""
Activate the object.
Then it starts the coro task to awaken every few seconds to scrape the directories.
"""
# Make the xchembku client context.
s = require(
f"{callsign(self)} specification",
self.specification(),
"type_specific_tbd",
)
s = require(
f"{callsign(self)} type_specific_tbd",
s,
"xchembku_dataface_specification",
)
self.__xchembku_client_context = XchembkuDatafaceClientContext(s)
# Activate the context.
await self.__xchembku_client_context.aenter()
# Get a reference to the xchembku interface provided by the context.
self.__xchembku = self.__xchembku_client_context.get_interface()
# Object able to talk to the formulatrix database.
self.__ftrix_client = FtrixClient(
self.__ftrix_client_specification,
)
# Object which can inject new xchembku plate records discovered while looking in subwell images.
self.__plate_injector = PlateInjector(
self.__ftrix_client,
self.__xchembku,
)
# Poll periodically.
self.__tick_future = asyncio.get_event_loop().create_task(self.tick())
# ----------------------------------------------------------------------------------------
async def deactivate(self) -> None:
"""
Deactivate the object.
Causes the coro task to stop.
This implementation then releases resources relating to the xchembku connection.
"""
if self.__tick_future is not None:
# Set flag to stop the periodic ticking.
self.__keep_ticking = False
# Wait for the ticking to stop.
await self.__tick_future
# Forget we have an xchembku client reference.
self.__xchembku = None
if self.__xchembku_client_context is not None:
await self.__xchembku_client_context.aexit()
self.__xchembku_client_context = None
# ----------------------------------------------------------------------------------------
async def tick(self) -> None:
"""
A coro task which does periodic checking for new files in the directories.
Stops when flag has been set by other tasks.
# TODO: Use an event to awaken ticker early to handle stop requests sooner.
"""
while self.__keep_ticking:
# Scrape all the configured plates directories.
await self.scrape_plates_directories()
# TODO: Make periodic tick period to be configurable.
await asyncio.sleep(1.0)
# ----------------------------------------------------------------------------------------
async def scrape_plates_directories(self) -> None:
"""
Scrape all the configured directories looking in each one for new plate directories.
Normally there is only one in the configured list of these places where plates arrive.
"""
# TODO: Use asyncio tasks to paralellize scraping plates directories.
for directory in self.__plates_directories:
try:
await self.scrape_plates_directory(Path(directory))
except Exception as exception:
# Just log the error, tag as anomaly for reporting, don't die.
logger.error(
"[ANOMALY] "
+ explain2(exception, f"scraping plates directory {directory}"),
exc_info=exception,
)
# ----------------------------------------------------------------------------------------
async def scrape_plates_directory(
self,
plates_directory: Path,
) -> None:
"""
Scrape a single directory looking for subdirectories which correspond to plates.
"""
if not plates_directory.is_dir():
return
plate_names = [
entry.name for entry in os.scandir(plates_directory) if entry.is_dir()
]
# Make sure we scrape the plate directories in barcode-order, which is the same as date order.
plate_names.sort()
logger.debug(
f"[ROCKINGESTER POLL] found {len(plate_names)} plate directories in {plates_directory}"
)
for plate_name in plate_names:
try:
await self.scrape_plate_directory(plates_directory / plate_name)
except Exception as exception:
# Just log the error, tag as anomaly for reporting, don't die.
logger.error(
"[ANOMALY] "
+ explain2(
exception,
f"scraping plate directory {str(plates_directory / plate_name)}",
),
exc_info=exception,
)
# ----------------------------------------------------------------------------------------
async def scrape_plate_directory(
self,
plate_directory: Path,
) -> None:
"""
Scrape a single directory looking for images.
"""
plate_name = plate_directory.name
# We already handled this plate name?
if plate_name in self.__handled_plate_names:
# logger.debug(
# f"[ROCKINGESTER POLL] plate_barcode {plate_barcode}"
# f" is already handled in this instance"
# )
return
# Get the plate's barcode from the directory name.
plate_barcode = plate_name[0:4]
# We have a specific list we want to process?
if self.__ingest_only_barcodes is not None:
if plate_barcode not in self.__ingest_only_barcodes:
return
# Get the matching plate record from the xchembku or formulatrix database.
crystal_plate_model = await self.__plate_injector.find_or_inject_barcode(
plate_barcode,
self.__visits_directory,
)
# The model has not been marked as being in error?
if crystal_plate_model.error is None:
visit_directory = get_xchem_directory(
self.__visits_directory, crystal_plate_model.visit
)
# Scrape the directory when all image files have arrived.
await self.scrape_plate_directory_if_complete(
plate_directory,
crystal_plate_model,
visit_directory,
)
# The model has been marked as being in error?
else:
logger.debug(
f"[ROCKDIR] for plate_barcode {plate_barcode} crystal_plate_model.error is: {crystal_plate_model.error}"
)
# Remember we "handled" this one within the current instance.
# Keeping this list could be obviated if we could move the files out of the plates directory after we process them.
self.__handled_plate_names.append(plate_name)
# ----------------------------------------------------------------------------------------
async def scrape_plate_directory_if_complete(
self,
plate_directory: Path,
crystal_plate_model: CrystalPlateModel,
visit_directory: Path,
) -> None:
"""
Scrape a single directory looking for new files.
Adds discovered files to internal list which gets pushed when it reaches a configurable size.
TODO: Consider some other flow where well images can be copied as they arrive instead of doing them all in a bunch.
Args:
plate_directory: disk directory where to look for subwell images
crystal_plate_model: pre-built crystal plate description
visit_directory: full path to the top of the visit directory
"""
# Name of the destination directory where we will permanently store ingested well image files.
target = (
visit_directory / self.__visit_plates_subdirectory / plate_directory.name
)
# We have already put this plate directory into the visit directory?
# This shouldn't really happen except when someone has been fiddling with the database.
# TODO: Have a way to rebuild rockingest after database wipe, but images have already been copied to the visit.
if target.is_dir():
# Presumably this is done, so no error but log it.
logger.debug(
f"[ROCKDIR] plate directory {plate_directory.name} is apparently already copied to {target}"
)
self.__handled_plate_names.append(plate_directory.stem)
return
# This is the first time we have scraped a directory for this plate record in the database?
if crystal_plate_model.rockminer_collected_stem is None:
# Update the path stem in the crystal plate record.
# TODO: Consider if important to report/record same barcodes on different rockmaker directories.
crystal_plate_model.rockminer_collected_stem = plate_directory.stem
await self.__xchembku.upsert_crystal_plates(
[crystal_plate_model], "update rockminer_collected_stem"
)
# Get all the well images in the plate directory and the latest arrival time.
subwell_names = []
max_wait_seconds = self.__max_wait_seconds
max_mtime = os.stat(plate_directory).st_mtime
with os.scandir(plate_directory) as entries:
for entry in entries:
subwell_names.append(entry.name)
max_mtime = max(max_mtime, entry.stat().st_mtime)
# TODO: Verify that time.time() where rockingester runs matches os.stat() on filesystem from which images are collected.
waited_seconds = time.time() - max_mtime
# Make an object corresponding to the crystal plate model's type.
crystal_plate_object = CrystalPlateObjects().build_object(
{"type": crystal_plate_model.thing_type}
)
# Don't handle the plate directory until all images have arrived or some maximum wait has exceeded.
if len(subwell_names) < crystal_plate_object.get_well_count():
if waited_seconds < max_wait_seconds:
logger.debug(
f"[PLATEWAIT] waiting longer since found only {len(subwell_names)}"
f" out of {crystal_plate_object.get_well_count()} subwell images"
f" in {plate_directory}"
f" after waiting {'%0.1f' % waited_seconds} out of {max_wait_seconds} seconds"
)
return
else:
logger.warning(
f"[PLATEDONE] done waiting even though found only {len(subwell_names)}"
f" out of {crystal_plate_object.get_well_count()} subwell images"
f" in {plate_directory}"
f" after waiting {'%0.1f' % waited_seconds} out of {max_wait_seconds} seconds"
)
else:
logger.debug(
f"[PLATEDONE] done waiting since found all {len(subwell_names)}"
f" out of {crystal_plate_object.get_well_count()} subwell images"
f" in {plate_directory}"
f" after waiting {'%0.1f' % waited_seconds} out of {max_wait_seconds} seconds"
)
# Sort wells by name so that tests are deterministic.
subwell_names.sort()
crystal_well_models: List[CrystalWellModel] = []
for subwell_name in subwell_names:
# Make the well model, including image width/height.
crystal_well_model = await self.ingest_well(
plate_directory,
subwell_name,
crystal_plate_model,
crystal_plate_object,
target,
)
# Append well model to the list of all wells on the plate.
crystal_well_models.append(crystal_well_model)
# Here we create or update the crystal well records into xchembku.
# TODO: Make sure that direct_poll does not double-create crystal well records if scrape is re-run with a different filename path.
await self.__xchembku.upsert_crystal_wells(crystal_well_models)
# Copy scraped directory to visit, replacing what might already be there.
# TODO: Handle case where we upsert the crystal_well record but then unable to copy image file.
shutil.copytree(
plate_directory,
target,
)
logger.info(
f"copied {len(subwell_names)} well images from plate {plate_directory.name} to {target}"
)
# Remember we "handled" this one.
self.__handled_plate_names.append(plate_directory.stem)
# ----------------------------------------------------------------------------------------
async def ingest_well(
self,
plate_directory: Path,
subwell_name: str,
crystal_plate_model: CrystalPlateModel,
crystal_plate_object: CrystalPlateInterface,
target: Path,
) -> CrystalWellModel:
"""
Ingest the well into the database.
Move the well image file to the ingested area.
"""
input_well_filename = plate_directory / subwell_name
ingested_well_filename = target / subwell_name
# Stems are like "9acx_01A_1".
# Convert the stem into a position as shown in soakdb3.
position = crystal_plate_object.normalize_subwell_name(Path(subwell_name).stem)
error = None
try:
image = Image.open(input_well_filename)
width, height = image.size
except Exception as exception:
error = str(exception)
width = None
height = None
crystal_well_model = CrystalWellModel(
position=position,
filename=str(ingested_well_filename),
crystal_plate_uuid=crystal_plate_model.uuid,
error=error,
width=width,
height=height,
)
return crystal_well_model
# ----------------------------------------------------------------------------------------
async def close_client_session(self):
""""""
pass | /rockingester-3.0.5.tar.gz/rockingester-3.0.5/src/rockingester_lib/collectors/direct_poll.py | 0.665628 | 0.1585 | direct_poll.py | pypi |
import logging
from typing import Any, Dict, Optional, Type
# Class managing list of things.
from dls_utilpack.things import Things
from rockingester_lib.collectors.constants import Types
# Exceptions.
from rockingester_lib.exceptions import NotFound
logger = logging.getLogger(__name__)
# -----------------------------------------------------------------------------------------
# Use proper Singleton pattern for global instance of default_collector.
__default_collector = None
# Set the global instance of the default collector.
def collectors_set_default(collector):
global __default_collector
__default_collector = collector
# Get the global instance of the default collector.
def collectors_get_default():
global __default_collector
if __default_collector is None:
raise RuntimeError("collectors_get_default instance is None")
return __default_collector
class Collectors(Things):
"""
Factory to construct a collector from a specification dict.
"""
# ----------------------------------------------------------------------------------------
def __init__(self, name: str = "collectors"):
"""
Constructor.
Args:
name (str, optional): name of the list,
typically only needed in debugging when there are potentially
multiple of these. Defaults to "collectors".
"""
Things.__init__(self, name)
# ----------------------------------------------------------------------------------------
def build_object(
self,
specification: Dict,
predefined_uuid: Optional[str] = None,
) -> Any:
"""
Construct an object from the given specification.
Args:
specification (Dict): specification of the object to be constructed.
The object's type is expected to be a string value in specification["type"].
predefined_uuid (Optional[str], optional): uuid if known beforehand. Defaults to None,
in which case the object will get a newly generated uuid.
Raises:
NotFound: If no matching class can be found.
RuntimeError: When a class is found, but the object cannot be constructed due to some error.
Returns:
object: A constructed object of the desired class type.
"""
# Get a class object from the string name in the specification.
# TODO:
collector_class = self.lookup_class(specification["type"])
try:
# Instantiate the class from the specification dict.
collector_object = collector_class(
specification, predefined_uuid=predefined_uuid
)
except Exception as exception:
raise RuntimeError(
"unable to build collector object of class %s"
% (collector_class.__name__)
) from exception
return collector_object
# ----------------------------------------------------------------------------------------
def lookup_class(self, class_type: str) -> Type:
"""
Return a class object given its string type.
Args:
class_type (str): type of object. Can be a well-known short name
or a Python class name or filename::classname
Raises:
NotFound: If no matching class can be found.
Returns:
class: a class object (not an implementation).
"""
# TODO: Use ABC to declare classes as interfaces with abstract methods.
if class_type == Types.AIOHTTP:
from rockingester_lib.collectors.aiohttp import Aiohttp
return Aiohttp
elif class_type == Types.DIRECT_POLL:
from rockingester_lib.collectors.direct_poll import DirectPoll
return DirectPoll
# Not the nickname of a class type?
else:
try:
# Presume this is a python class name or filename::classname.
RuntimeClass = Things.lookup_class(self, class_type)
return RuntimeClass
except NotFound:
raise NotFound("unable to get collector class for %s" % (class_type)) | /rockingester-3.0.5.tar.gz/rockingester-3.0.5/src/rockingester_lib/collectors/collectors.py | 0.799873 | 0.247578 | collectors.py | pypi |
import json
import logging
from argparse import ArgumentParser
from pathlib import Path
from subprocess import CalledProcessError, check_output
from typing import List, Optional
def report_output(stdout: bytes, label: str) -> List[str]:
ret = stdout.decode().strip().split("\n")
print(f"{label}: {ret}")
return ret
def get_branch_contents(ref: str) -> List[str]:
"""Get the list of directories in a branch."""
stdout = check_output(["git", "ls-tree", "-d", "--name-only", ref])
return report_output(stdout, "Branch contents")
def get_sorted_tags_list() -> List[str]:
"""Get a list of sorted tags in descending order from the repository."""
stdout = check_output(["git", "tag", "-l", "--sort=-v:refname"])
return report_output(stdout, "Tags list")
def get_versions(ref: str, add: Optional[str], remove: Optional[str]) -> List[str]:
"""Generate the file containing the list of all GitHub Pages builds."""
# Get the directories (i.e. builds) from the GitHub Pages branch
try:
builds = set(get_branch_contents(ref))
except CalledProcessError:
builds = set()
logging.warning(f"Cannot get {ref} contents")
# Add and remove from the list of builds
if add:
builds.add(add)
if remove:
assert remove in builds, f"Build '{remove}' not in {sorted(builds)}"
builds.remove(remove)
# Get a sorted list of tags
tags = get_sorted_tags_list()
# Make the sorted versions list from main branches and tags
versions: List[str] = []
for version in ["master", "main"] + tags:
if version in builds:
versions.append(version)
builds.remove(version)
# Add in anything that is left to the bottom
versions += sorted(builds)
print(f"Sorted versions: {versions}")
return versions
def write_json(path: Path, repository: str, versions: str):
org, repo_name = repository.split("/")
struct = [
dict(version=version, url=f"https://{org}.github.io/{repo_name}/{version}/")
for version in versions
]
text = json.dumps(struct, indent=2)
print(f"JSON switcher:\n{text}")
path.write_text(text)
def main(args=None):
parser = ArgumentParser(
description="Make a versions.txt file from gh-pages directories"
)
parser.add_argument(
"--add",
help="Add this directory to the list of existing directories",
)
parser.add_argument(
"--remove",
help="Remove this directory from the list of existing directories",
)
parser.add_argument(
"repository",
help="The GitHub org and repository name: ORG/REPO",
)
parser.add_argument(
"output",
type=Path,
help="Path of write switcher.json to",
)
args = parser.parse_args(args)
# Write the versions file
versions = get_versions("origin/gh-pages", args.add, args.remove)
write_json(args.output, args.repository, versions)
if __name__ == "__main__":
main()
# dae_devops_fingerprint 5fbfeccf513ac4cfddda72c5285e0f4e | /rockingester-3.0.5.tar.gz/rockingester-3.0.5/.github/pages/make_switcher.py | 0.843089 | 0.275245 | make_switcher.py | pypi |
# rockit
[](https://gitlab.kuleuven.be/meco-software/rockit/commits/master)
[](https://meco-software.pages.gitlab.kuleuven.be/rockit/coverage/index.html)
[](http://meco-software.pages.gitlab.kuleuven.be/rockit)
[](http://meco-software.pages.gitlab.kuleuven.be/rockit/documentation-rockit.pdf)
# Description

Rockit (Rapid Optimal Control kit) is a software framework to quickly prototype optimal control problems (aka dynamic optimization) that may arise in engineering: e.g.
iterative learning (ILC), model predictive control (NMPC), system identification, and motion planning.
Notably, the software allows free end-time problems and multi-stage optimal problems.
The software is currently focused on direct methods and relies heavily on [CasADi](http://casadi.org).
The software is developed by the [KU Leuven MECO research team](https://www.mech.kuleuven.be/en/pma/research/meco).
# Installation
Install using pip: `pip install rockit-meco`
# Hello world
(Taken from the [example gallery](https://meco-software.pages.gitlab.kuleuven.be/rockit/examples/))
You may try it live in your browser: [](https://mybinder.org/v2/git/https%3A%2F%2Fgitlab.kuleuven.be%2Fmeco-software%2Frockit.git/v0.1.9?filepath=examples%2Fhello_world.ipynb).
Import the project:
```python
from rockit import *
```
Start an optimal control environment with a time horizon of 10 seconds
starting from t0=0s.
_(free-time problems can be configured with `FreeTime(initial_guess))_
```python
ocp = Ocp(t0=0, T=10)
```
Define two scalar states (vectors and matrices also supported)
```python
x1 = ocp.state()
x2 = ocp.state()
```
Define one piecewise constant control input
_(use `order=1` for piecewise linear)_
```
u = ocp.control()
```
Compose time-dependent expressions a.k.a. signals
_(explicit time-dependence is supported with `ocp.t`)_
```python
e = 1 - x2**2
```
Specify differential equations for states
_(DAEs also supported with `ocp.algebraic` and `add_alg`)_
```python
ocp.set_der(x1, e * x1 - x2 + u)
ocp.set_der(x2, x1)
```
Lagrange objective term: signals in an integrand
```python
ocp.add_objective(ocp.integral(x1**2 + x2**2 + u**2))
```
Mayer objective term: signals evaluated at t_f = t0_+T
```python
ocp.add_objective(ocp.at_tf(x1**2))
```
Path constraints
_(must be valid on the whole time domain running from `t0` to `tf`,
grid options available such as `grid='integrator'` or `grid='inf'`)_
```python
ocp.subject_to(x1 >= -0.25)
ocp.subject_to(-1 <= (u <= 1 ))
```
Boundary constraints
```python
ocp.subject_to(ocp.at_t0(x1) == 0)
ocp.subject_to(ocp.at_t0(x2) == 1)
```
Pick an NLP solver backend
_(CasADi `nlpsol` plugin)_
```python
ocp.solver('ipopt')
```
Pick a solution method
such as `SingleShooting`, `MultipleShooting`, `DirectCollocation`
with arguments:
* N -- number of control intervals
* M -- number of integration steps per control interval
* grid -- could specify e.g. UniformGrid() or GeometricGrid(4)
```python
method = MultipleShooting(N=10, intg='rk')
ocp.method(method)
```
Set initial guesses for states, controls and variables.
Default: zero
```python
ocp.set_initial(x2, 0) # Constant
ocp.set_initial(x1, ocp.t/10) # Function of time
ocp.set_initial(u, linspace(0, 1, 10)) # Array
```
Solve:
```python
sol = ocp.solve()
```
In case the solver fails, you can still look at the solution:
_(you may need to wrap the solve line in try/except to avoid the script aborting)_
```python
sol = ocp.non_converged_solution
```
Show structure:
```python
ocp.spy()
```

Post-processing:
```python
tsa, x1a = sol.sample(x1, grid='control')
tsb, x1b = sol.sample(x1, grid='integrator')
tsc, x1c = sol.sample(x1, grid='integrator', refine=100)
plot(tsa, x1a, '-')
plot(tsb, x1b, 'o')
plot(tsc, x1c, '.')
```

# Matlab interface
Rockit comes with a (almost) feature-complete interface to Matlab.
Installation steps:
1. [Check](https://www.mathworks.com/content/dam/mathworks/mathworks-dot-com/support/sysreq/files/python-support.pdf) which Python versions your Matlab installation supports, e.g. `Python 3.6`
2. Open up a compatible Python environment in a terminal (if you don't have one, consider [miniconda](https://docs.conda.io/en/latest/miniconda.html) and create an environment by performing commands `conda create --name myspace python=3.6` and `conda activate myspace` inside the Anaconda Prompt).
3. Perform `pip install "rockit-meco>=0.1.12" "casadi>=3.5.5"` in that teminal
4. Launch Matlab from that same terminal (Type the full path+name of the Matlab executable. In Windows you may find the Matlab executable by right-clicking the icon from the start menu; use quotes (") to encapsulate the full name if it contains spaces. e.g. `"C:\Program Files\Matlab\bin\matlab.exe"`)
5. Install CasADi for Matlab from https://github.com/casadi/casadi/releases/tag/3.5.5: pick the latest applicable matlab archive, unzip it, and add it to the Matlab path (without subdirectories)
6. Make sure you remove any other CasADi version from the Matlab path.
7. Only for Matlab >=2019b: make sure you do have in-process ExecutionMode for speed `pyenv('ExecutionMode','InProcess')`
8. Add rockit to the matlab path: `addpath(char(py.rockit.matlab_path))`
9. Run the `hello_world` example from the [example directory](https://gitlab.kuleuven.be/meco-software/rockit/-/tree/master/examples)
Debugging:
* Check if the correct CasADi Python is found: py.imp.find_module('casadi')
* Check if the correct CasADi Matlab is found: `edit casadi.SerializerBase`, should have a method called 'connect'
* Matlab error "Conversion to double from py.numpy.ndarray is not possible." -> Consult your Matlab release notes to verify that your Python version is supported
* Matlab error "Python Error: RuntimeError: .../casadi/core/serializing_stream.hpp:171: Assertion "false" failed:" -> May occur on Linux for some configurations. Consult rockit authors
# External interfaces
In the long run, we aim to add a bunch of interfaces to [third-party dynamic optimization solvers](https://github.com/meco-group/dynamic_optimization_inventory/blob/main/list.csv).
At the moment, the following solvers are interfaced:
* [acados](https://github.com/acados/acados) -- [examples](https://gitlab.kuleuven.be/meco-software/rockit/-/tree/master/rockit/external/acados/examples)
* [grampc](https://sourceforge.net/projects/grampc/) -- [examples](https://gitlab.kuleuven.be/meco-software/rockit-plugin-grampc/-/tree/main/examples)
Installation when using rockit from git
* `git submodule update --init --recursive`
* Windows only: install Visual Studio (supported: 2017,2019,2022) with the following components: `C++ Desktop Development` workload, and verify that the following components are also installed: `MSBuild`,`MSVC C++ x64/x86 build tools`,`C++ Cmake tools`,`C++/CLI support`
# Presentations
* Benelux 2020: [Effortless modeling of optimal control problems with rockit](https://youtu.be/dS4U_k6B904)
* Demo @ FM symposium: [Rockit: optimal motion planning made easy](https://github.com/meco-group/rockit_demo)
# Citing
Gillis, Joris ; Vandewal, Bastiaan ; Pipeleers, Goele ; Swevers, Jan
"Effortless modeling of optimal control problems with rockit", 39th Benelux Meeting on Systems and Control 2020, Elspeet, The Netherlands
| /rockit-meco-0.1.32.tar.gz/rockit-meco-0.1.32/README.md | 0.49585 | 0.954563 | README.md | pypi |
from casadi import vertcat, vcat, which_depends, MX, substitute, integrator, Function, depends_on
from .stage import Stage, transcribed
from .placeholders import TranscribedPlaceholders
from .casadi_helpers import vvcat, rockit_pickle_context, rockit_unpickle_context
from .external.manager import external_method
from .direct_method import DirectMethod
class Ocp(Stage):
def __init__(self, t0=0, T=1, **kwargs):
"""Create an Optimal Control Problem environment
Parameters
----------
t0 : float or :obj:`~rockit.freetime.FreeTime`, optional
Starting time of the optimal control horizon
Default: 0
T : float or :obj:`~rockit.freetime.FreeTime`, optional
Total horizon of the optimal control horizon
Default: 1
Examples
--------
>>> ocp = Ocp()
"""
Stage.__init__(self, t0=t0, T=T, **kwargs)
self._master = self
# Flag to make solve() faster when solving a second time
# (e.g. with different parameter values)
self._var_is_transcribed = False
self._transcribed_placeholders = TranscribedPlaceholders()
@transcribed
def jacobian(self, with_label=False):
return self._method.jacobian(with_label=with_label)
@transcribed
def hessian(self, with_label=False):
return self._method.hessian(with_label=with_label)
@transcribed
def spy_jacobian(self):
self._method.spy_jacobian()
@transcribed
def spy_hessian(self):
self._method.spy_hessian()
@transcribed
def spy(self):
import matplotlib.pylab as plt
plt.subplots(1, 2, figsize=(10, 4))
plt.subplot(1, 2, 1)
self.spy_jacobian()
plt.subplot(1, 2, 2)
self.spy_hessian()
@property
def _transcribed(self):
if self._is_original:
if self._is_transcribed:
return self._augmented
else:
import copy
augmented = copy.deepcopy(self)
augmented._master = augmented
augmented._transcribed_placeholders = self._transcribed_placeholders
augmented._var_original = self
self._var_augmented = augmented
augmented._placeholders = self._placeholders
return self._augmented._transcribed
else:
self._transcribe()
return self
def _transcribe(self):
if not self.is_transcribed:
self._transcribed_placeholders.clear()
self._transcribe_recurse(phase=0)
self._placeholders_transcribe_recurse(1,self._transcribed_placeholders)
self._transcribe_recurse(phase=1)
self._original._set_transcribed(True)
self._transcribe_recurse(phase=2,placeholders=self.placeholders_transcribed)
def _untranscribe(self):
if self.is_transcribed:
self._transcribed_placeholders.clear()
self._untranscribe_recurse(phase=0)
self._placeholders_untranscribe_recurse(1)
self._untranscribe_recurse(phase=1)
self._original._set_transcribed(False)
self._untranscribe_recurse(phase=2)
@property
@transcribed
def placeholders_transcribed(self):
"""
May also be called after solving (issue #91)
"""
if self._transcribed_placeholders.is_dirty:
self._placeholders_transcribe_recurse(2, self._transcribed_placeholders)
self._transcribed_placeholders.is_dirty = False
return self._transcribed_placeholders
@property
def non_converged_solution(self):
return self._method.non_converged_solution(self)
@transcribed
def solve(self):
return self._method.solve(self)
@transcribed
def solve_limited(self):
return self._method.solve_limited(self)
def callback(self, fun):
self._set_transcribed(False)
return self._method.callback(self, fun)
@property
def debug(self):
self._method.debug
def solver(self, solver, solver_options={}):
self._method.solver(solver, solver_options)
def show_infeasibilities(self, *args):
self._method.show_infeasibilities(*args)
def debugme(self,e):
print(e,hash(e),e.__hash__())
return e
@property
@transcribed
def gist(self):
"""Obtain an expression packing all information needed to obtain value/sample
The composition of this array may vary between rockit versions
Returns
-------
:obj:`~casadi.MX` column vector
"""
return self._method.gist
@transcribed
def to_function(self, name, args, results, *margs):
return self._method.to_function(self, name, args, results, *margs)
def is_sys_time_varying(self):
# For checks
self._ode()
ode = vvcat([self._state_der[k] for k in self.states])
alg = vvcat(self._alg)
rhs = vertcat(ode,alg)
return depends_on(rhs, self.t)
def is_parameter_appearing_in_sys(self):
# For checks
self._ode()
ode = vvcat([self._state_der[k] for k in self.states])
alg = vvcat(self._alg)
rhs = vertcat(ode,alg)
pall = self.parameters['']+self.parameters['control']
dep = [depends_on(rhs,p) for p in pall]
return dep
def sys_dae(self):
# For checks
self._ode()
ode = vvcat([self._state_der[k] for k in self.states])
alg = vvcat(self._alg)
dae = {}
dae["x"] = self.x
dae["z"] = self.z
t0 = MX.sym("t0")
dt = MX.sym("dt")
tau = MX.sym("tau")
dae["t"] = self.t
pall = self.parameters['']+self.parameters['control']
rhs = vertcat(ode,alg)
dep = [depends_on(rhs,p) for p in pall]
p = vvcat([p for p,dep in zip(pall,dep) if dep])
dae["ode"] = ode
dae["alg"] = alg
dae["p"] = p
dae["u"] = self.u
return dae
def view_api(self, name):
method = self._method
self.method(external_method(name,method=method))
self._transcribed
return self._method
def sys_simulator(self, intg='rk', intg_options=None):
if intg_options is None:
intg_options = {}
intg_options = dict(intg_options)
# For checks
self._ode()
ode = vvcat([self._state_der[k] for k in self.states])
alg = vvcat(self._alg)
dae = {}
dae["x"] = self.x
dae["z"] = self.z
t0 = MX.sym("t0")
dt = MX.sym("dt")
tau = MX.sym("tau")
dae["t"] = tau
pall = self.parameters['']+self.parameters['control']
#dep = which_depends(vertcat(ode,alg),vvcat(pall),1,True)
rhs = vertcat(ode,alg)
dep = [depends_on(rhs,p) for p in pall]
p = vvcat([p for p,dep in zip(pall,dep) if dep])
[ode,alg] = substitute([ode,alg],[self.t],[t0+tau*dt])
dae["ode"] = dt*ode
dae["alg"] = alg
dae["p"] = vertcat(self.u, t0, dt, p)
intg_options["t0"] = 0
intg_options["tf"] = 1
intg = integrator('intg',intg,dae,intg_options)
z_initial_guess = MX.sym("z",self.z.sparsity()) if self.nz>0 else MX(0,1)
intg_out = intg(x0=self.x, p=dae["p"], z0=z_initial_guess)
simulator = Function('simulator',
[self.x, self.u, p, t0, dt, z_initial_guess],
[intg_out["xf"], intg_out["zf"]],
["x","u","p","t0","dt","z_initial_guess"],
["xf","zf"])
return simulator
def save(self,name):
self._untranscribe()
import pickle
with rockit_pickle_context():
pickle.dump(self,open(name,"wb"))
@staticmethod
def load(name):
import pickle
with rockit_unpickle_context():
return pickle.load(open(name,"rb")) | /rockit-meco-0.1.32.tar.gz/rockit-meco-0.1.32/rockit/ocp.py | 0.85203 | 0.305762 | ocp.py | pypi |
import numpy as np
from casadi import vertcat, vcat, DM, Function, hcat, MX
from .casadi_helpers import DM2numpy
from numpy import nan
import functools
class OcpSolution:
def __init__(self, nlpsol, stage):
"""Wrap casadi.nlpsol to simplify access to numerical solution."""
self.sol = nlpsol
self.stage = stage._augmented # SHould this be ocP?
self._gist = np.array(nlpsol.value(self.stage.master.gist)).squeeze()
def __call__(self, stage):
"""Sample expression at solution on a given grid.
Parameters
----------
stage : :obj:`~rockit.stage.Stage`
An optimal control problem stage.
"""
return OcpSolution(self.sol, stage=stage)
def value(self, expr, *args):
"""Get the value of an (non-signal) expression.
Parameters
----------
expr : :obj:`casadi.MX`
Arbitrary expression containing no signals (states, controls) ...
"""
return self.sol.value(self.stage.value(expr, *args))
def sample(self, expr, grid, **kwargs):
"""Sample expression at solution on a given grid.
Parameters
----------
expr : :obj:`casadi.MX`
Arbitrary expression containing states, controls, ...
grid : `str`
At which points in time to sample, options are
'control' or 'integrator' (at integrator discretization
level) or 'integrator_roots'.
refine : int, optional
Refine grid by evaluation the polynomal of the integrater at
intermediate points ("refine" points per interval).
Returns
-------
time : numpy.ndarray
Time from zero to final time, same length as res
res : numpy.ndarray
Numerical values of evaluated expression at points in time vector.
Examples
--------
Assume an ocp with a stage is already defined.
>>> sol = ocp.solve()
>>> tx, xs = sol.sample(x, grid='control')
"""
time, res = self.stage.sample(expr, grid, **kwargs)
res = self.sol.value(res)
return self.sol.value(time), DM2numpy(res, MX(expr).shape, time.numel())
def sampler(self, *args):
"""Returns a function that samples given expressions
This function has two modes of usage:
1) sampler(exprs) -> Python function
2) sampler(name, exprs, options) -> CasADi function
Parameters
----------
exprs : :obj:`casadi.MX` or list of :obj:`casadi.MX`
List of arbitrary expression containing states, controls, ...
name : `str`
Name for CasADi Function
options : dict, optional
Options for CasADi Function
Returns
-------
t -> output
mode 1 : Python Function
Symbolically evaluated expression at points in time vector.
mode 2 : :obj:`casadi.Function`
Time from zero to final time, same length as res
Examples
--------
Assume an ocp with a stage is already defined.
>>> sol = ocp.solve()
>>> s = sol.sampler(x)
>>> s(1.0) # Value of x at t=1.0
"""
s = self.stage.sampler(*args)
ret = functools.partial(s, self.gist)
ret.__doc__ = """
Parameters
----------
t : float or float vector
time or time-points to sample at
Returns
-------
:obj:`np.array`
"""
return ret
@property
def gist(self):
"""All numerical information needed to compute any value/sample
Returns
-------
1D numpy.ndarray
The composition of this array may vary between rockit versions
"""
return self._gist
@property
def stats(self):
"""Retrieve solver statistics
Returns
-------
Dictionary
The information contained is not structured and may change between rockit versions
"""
return self.sol.stats() | /rockit-meco-0.1.32.tar.gz/rockit-meco-0.1.32/rockit/solution.py | 0.908118 | 0.679757 | solution.py | pypi |
from casadi import integrator, Function, MX, hcat, vertcat, vcat, linspace, veccat, DM, repmat, horzsplit, cumsum, inf, mtimes, symvar, horzcat, symvar, vvcat, is_equal
from .direct_method import DirectMethod
from .splines import BSplineBasis, BSpline
from .casadi_helpers import reinterpret_expr, HashOrderedDict
from numpy import nan, inf
import numpy as np
from collections import defaultdict
# Agnostic about free or fixed start or end point:
# Agnostic about time?
class Grid:
def __init__(self, min=0, max=inf):
self.min = min
self.max = max
def __call__(self, t0, T, N):
return linspace(t0+0.0, t0+T+0.0, N+1)
def bounds_finalize(self, opti, control_grid, t0_local, tf, N):
pass
class FixedGrid(Grid):
def __init__(self, localize_t0=False, localize_T=False, **kwargs):
Grid.__init__(self, **kwargs)
self.localize_t0 = localize_t0
self.localize_T = localize_T
def bounds_T(self, T_local, t0_local, k, T, N):
if self.localize_T:
Tk = T_local[k]
if k>=0 and k+1<N:
r = self.constrain_T(T_local[k], T_local[k+1], N)
if r is not None:
yield r
else:
Tk = T*(self.normalized(N)[k+1]-self.normalized(N)[k])
if self.localize_t0 and k>=0:
yield (t0_local[k]+Tk==t0_local[k+1],{})
def get_t0_local(self, opti, k, t0, N):
if self.localize_t0:
if k==0:
return t0
else:
return opti.variable()
else:
return None
def get_T_local(self, opti, k, T, N):
if self.localize_T:
if k==0:
return T*self.scale_first(N)
else:
return opti.variable()
else:
return None
class FreeGrid(FixedGrid):
"""Specify a grid with unprescribed spacing
Parameters
----------
min : float or :obj:`casadi.MX`, optional
Minimum size of control interval
Enforced with constraints
Default: 0
max : float or :obj:`casadi.MX`, optional
Maximum size of control interval
Enforced with constraints
Default: inf
"""
def __init__(self, **kwargs):
FixedGrid.__init__(self, **kwargs)
self.localize_T = True
def constrain_T(self,T,Tnext,N):
pass
def bounds_T(self, T_local, t0_local, k, T, N):
yield (self.min <= (T_local[k] <= self.max),{})
for e in FixedGrid.bounds_T(self, T_local, t0_local, k, T, N):
yield e
def bounds_finalize(self, opti, control_grid, t0_local, tf, N):
opti.subject_to(control_grid[-1]==tf)
def get_T_local(self, opti, k, T, N):
return opti.variable()
class UniformGrid(FixedGrid):
"""Specify a grid with uniform spacing
Parameters
----------
min : float or :obj:`casadi.MX`, optional
Minimum size of control interval
Enforced with constraints
Default: 0
max : float or :obj:`casadi.MX`, optional
Maximum size of control interval
Enforced with constraints
Default: inf
"""
def __init__(self, **kwargs):
FixedGrid.__init__(self, **kwargs)
def constrain_T(self,T,Tnext,N):
return (T==Tnext,{})
def scale_first(self, N):
return 1.0/N
def bounds_T(self, T_local, t0_local, k, T, N):
if k==0:
if self.localize_T:
yield (self.min <= (T_local[0] <= self.max), {})
else:
if self.min==0 and self.max==inf:
pass
else:
yield (self.min <= (T/N <= self.max), {})
for e in FixedGrid.bounds_T(self, T_local, t0_local, k, T, N):
yield e
def normalized(self, N):
return list(np.linspace(0.0, 1.0, N+1))
class GeometricGrid(FixedGrid):
"""Specify a geometrically growing grid
Each control interval is a constant factor larger than its predecessor
Parameters
----------
growth_factor : float>1
See `local` for interpretation
local : bool, optional
if False, last interval is growth_factor larger than first
if True, interval k+1 is growth_factor larger than interval k
Default: False
min : float or :obj:`casadi.MX`, optional
Minimum size of control interval
Enforced with constraints
Default: 0
max : float or :obj:`casadi.MX`, optional
Maximum size of control interval
Enforced with constraints
Default: inf
Examples
--------
>>> MultipleShooting(N=3, grid=GeometricGrid(2)) # grid = [0, 1, 3, 7]*T/7
>>> MultipleShooting(N=3, grid=GeometricGrid(2,local=True)) # grid = [0, 1, 5, 21]*T/21
"""
def __init__(self, growth_factor, local=False, **kwargs):
assert growth_factor>=1
self._growth_factor = growth_factor
self.local = local
FixedGrid.__init__(self, **kwargs)
def __call__(self, t0, T, N):
n = self.normalized(N)
return t0 + hcat(n)*T
def growth_factor(self, N):
if not self.local and N>1:
return self._growth_factor**(1.0/(N-1))
return self._growth_factor
def constrain_T(self,T,Tnext,N):
return (T*self.growth_factor(N)==Tnext,{})
def scale_first(self, N):
return self.normalized(N)[1]
def bounds_T(self, T_local, t0_local, k, T, N):
if self.localize_T:
if k==0 or k==-1:
yield (self.min <= (T_local[k] <= self.max), {})
else:
n = self.normalized(N)
if k==0:
yield (self.min <= (T*n[1] <= self.max),{})
if k==-1:
yield (self.min <= (T*(n[-1]-n[-2]) <= self.max),{})
for e in FixedGrid.bounds_T(self, T_local, t0_local, k, T, N):
yield e
def normalized(self, N):
g = self.growth_factor(N)
base = 1.0
vec = [0]
for i in range(N):
vec.append(vec[-1]+base)
base *= g
for i in range(N+1):
vec[i] = vec[i]/vec[-1]
return vec
class SamplingMethod(DirectMethod):
def __init__(self, N=50, M=1, intg='rk', intg_options=None, grid=UniformGrid(), **kwargs):
"""
Parameters
----------
grid : `str` or tuple of :obj:`casadi.MX`
List of arbitrary expression containing states, controls, ...
name : `str`
Name for CasADi Function
options : dict, optional
Options for CasADi Function
intg : `str`
Rockit-specific methods: 'rk', 'expl_euler' - these allow to make use of signal sampling with 'refine'
Others are passed on as-is to CasADi
"""
DirectMethod.__init__(self, **kwargs)
self.N = N
self.M = M
self.intg = intg
self.intg_options = {} if intg_options is None else intg_options
self.time_grid = grid
self.clean()
def clean(self):
self.X = [] # List that will hold N+1 decision variables for state vector
self.U = [] # List that will hold N decision variables for control vector
self.Z = [] # Algebraic vars
self.T = None # Will be set to numbers/opti.variables
self.t0 = None
self.P = []
self.V = None
self.V_control = []
self.V_control_plus = []
self.V_states = []
self.P_control = []
self.P_control_plus = []
self.poly_coeff = [] # Optional list to save the coefficients for a polynomial
self.poly_coeff_z = [] # Optional list to save the coefficients for a polynomial
self.xk = [] # List for intermediate integrator states
self.zk = []
self.xr = []
self.zr = []
self.tr = []
self.q = 0
def discrete_system(self, stage):
# Coefficient matrix from RK4 to reconstruct 4th order polynomial (k1,k2,k3,k4)
# nstates x (4 * M)
poly_coeffs = []
poly_coeffs_z = []
t0 = MX.sym('t0')
T = MX.sym('T')
DT = T / self.M
# Size of integrator interval
X0 = MX.sym("x", stage.nx) # Initial state
U = MX.sym("u", stage.nu) # Control
P = MX.sym("p", stage.np+stage.v.shape[0])
Z = MX.sym("z", stage.nz)
X = [X0]
Zs = []
# Compute local start time
t0_local = t0
quad = 0
if stage._state_next:
intg = stage._diffeq()
elif hasattr(self, 'intg_' + self.intg):
intg = getattr(self, "intg_" + self.intg)(stage._ode(), X0, U, P, Z)
else:
intg = self.intg_builtin(stage._ode(), X0, U, P, Z)
if intg.has_free():
raise Exception("Free variables found: %s" % str(intg.get_free()))
for j in range(self.M):
intg_res = intg(x0=X[-1], u=U, t0=t0_local, DT=DT, DT_control=T, p=P)
X.append(intg_res["xf"])
Zs.append(intg_res["zf"])
quad = quad + intg_res["qf"]
poly_coeffs.append(intg_res["poly_coeff"])
poly_coeffs_z.append(intg_res["poly_coeff_z"])
t0_local += DT
ret = Function('F', [X0, U, T, t0, P], [X[-1], hcat(X), hcat(poly_coeffs), quad, Zs[-1], hcat(Zs), hcat(poly_coeffs_z)],
['x0', 'u', 'T', 't0', 'p'], ['xf', 'Xi', 'poly_coeff', 'qf', 'zf', 'Zi', 'poly_coeff_z'])
assert not ret.has_free()
return ret
def intg_rk(self, f, X, U, P, Z):
assert Z.is_empty()
DT = MX.sym("DT")
DT_control = MX.sym("DT_control")
t0 = MX.sym("t0")
# A single Runge-Kutta 4 step
k1 = f(x=X, u=U, p=P, t=t0)
k2 = f(x=X + DT / 2 * k1["ode"], u=U, p=P, t=t0+DT/2)
k3 = f(x=X + DT / 2 * k2["ode"], u=U, p=P, t=t0+DT/2)
k4 = f(x=X + DT * k3["ode"], u=U, p=P, t=t0+DT)
f0 = k1["ode"]
f1 = 2/DT*(k2["ode"]-k1["ode"])/2
f2 = 4/DT**2*(k3["ode"]-k2["ode"])/6
f3 = 4*(k4["ode"]-2*k3["ode"]+k1["ode"])/DT**3/24
poly_coeff = hcat([X, f0, f1, f2, f3])
return Function('F', [X, U, t0, DT, DT_control, P], [X + DT / 6 * (k1["ode"] + 2 * k2["ode"] + 2 * k3["ode"] + k4["ode"]), poly_coeff, DT / 6 * (k1["quad"] + 2 * k2["quad"] + 2 * k3["quad"] + k4["quad"]), MX(0, 1), MX()], ['x0', 'u', 't0', 'DT', 'DT_control', 'p'], ['xf', 'poly_coeff', 'qf', 'zf', 'poly_coeff_z'])
def intg_expl_euler(self, f, X, U, P, Z):
assert Z.is_empty()
DT = MX.sym("DT")
DT_control = MX.sym("DT_control")
t0 = MX.sym("t0")
k = f(x=X, u=U, p=P, t=t0)
poly_coeff = hcat([X, k["ode"]])
return Function('F', [X, U, t0, DT, DT_control, P], [X + DT * k["ode"], poly_coeff, DT * k["quad"], MX(0, 1), MX()], ['x0', 'u', 't0', 'DT', 'DT_control', 'p'], ['xf', 'poly_coeff', 'qf', 'zf', 'poly_coeff_z'])
def intg_builtin(self, f, X, U, P, Z):
# A single CVODES step
DT = MX.sym("DT")
DT_control = MX.sym("DT_control")
t = MX.sym("t")
t0 = MX.sym("t0")
res = f(x=X, u=U, p=P, t=t0+t*DT, z=Z)
data = {'x': X, 'p': vertcat(U, DT, DT_control, P, t0), 'z': Z, 't': t, 'ode': DT * res["ode"], 'quad': DT * res["quad"], 'alg': res["alg"]}
options = dict(self.intg_options)
if self.intg in ["collocation"]:
# In rockit, M replaces number_of_finite_elements on a higher level
if "number_of_finite_elements" not in options:
options["number_of_finite_elements"] = 1
I = integrator('intg_'+self.intg, self.intg, data, options)
res = I.call({'x0': X, 'p': vertcat(U, DT, DT_control, P, t0)})
return Function('F', [X, U, t0, DT, DT_control, P], [res["xf"], MX(), res["qf"], res["zf"], MX()], ['x0', 'u', 't0', 'DT', 'DT_control', 'p'], ['xf', 'poly_coeff','qf','zf','poly_coeff_z'])
def untranscribe_placeholders(self, phase, stage):
pass
def transcribe_placeholders(self, phase, stage, placeholders):
"""
Transcription is the process of going from a continuous-time OCP to an NLP
"""
return stage._transcribe_placeholders(phase, self, placeholders)
def transcribe_start(self, stage, opti):
return
def untranscribe(self, stage, phase=1,**kwargs):
self.clean()
def transcribe(self, stage, phase=1,**kwargs):
"""
Transcription is the process of going from a continuous-time OCP to an NLP
"""
if phase==0: return
if phase>1: return
opti = stage.master._method.opti
DM.set_precision(14)
self.transcribe_start(stage, opti)
# Parameters needed before variables because of self.T = self.eval(stage, stage._T)
self.add_parameter(stage, opti)
self.set_parameter(stage, opti)
self.add_variables(stage, opti)
self.integrator_grid = []
for k in range(self.N):
t_local = linspace(self.control_grid[k], self.control_grid[k+1], self.M+1)
self.integrator_grid.append(t_local[:-1] if k<self.N-1 else t_local)
self.add_constraints_before(stage, opti)
self.add_constraints(stage, opti)
self.add_constraints_after(stage, opti)
self.add_objective(stage, opti)
self.set_initial(stage, opti, stage._initial)
T_init = opti.debug.value(self.T, opti.initial())
t0_init = opti.debug.value(self.t0, opti.initial())
initial = HashOrderedDict()
# How to get initial value -> ask opti?
control_grid_init = self.time_grid(t0_init, T_init, self.N)
if self.time_grid.localize_t0:
for k in range(1, self.N):
initial[self.t0_local[k]] = control_grid_init[k]
initial[self.t0_local[self.N]] = control_grid_init[self.N]
if self.time_grid.localize_T:
for k in range(not isinstance(self.time_grid, FreeGrid), self.N):
initial[self.T_local[k]] = control_grid_init[k+1]-control_grid_init[k]
self.set_initial(stage, opti, initial)
self.set_parameter(stage, opti)
def add_constraints_before(self, stage, opti):
for c, meta, args in stage._constraints["point"]:
e = self.eval(stage, c)
if 'r_at_tf' not in [a.name() for a in symvar(e)]:
opti.subject_to(e, args["scale"], meta=meta)
def add_constraints_after(self, stage, opti):
for c, meta, args in stage._constraints["point"]:
e = self.eval(stage, c)
if 'r_at_tf' in [a.name() for a in symvar(e)]:
opti.subject_to(e, args["scale"], meta=meta)
def add_inf_constraints(self, stage, opti, c, k, l, meta):
# Query the discretization method used for polynomial coefficients
# interpretation: state ~= coeff * [t^0;t^1;t^2;...]
# t is physical time, but starting at 0 at the beginning of the interval
coeff = stage._method.poly_coeff[k * self.M + l]
# Represent polynomial as a BSpline object (https://gitlab.kuleuven.be/meco-software/rockit/-/blob/v0.1.28/rockit/splines/spline.py#L392)
degree = coeff.shape[1]-1
basis = BSplineBasis([0]*(degree+1)+[1]*(degree+1),degree)
tscale = self.T / self.N / self.M
tpower = vcat([tscale**i for i in range(degree+1)])
coeff = coeff * repmat(tpower.T,stage.nx,1)
# TODO: bernstein transformation as function of degree
Poly_to_Bernstein_matrix_4 = DM([[1,0,0,0,0],[1,1.0/4, 0, 0, 0],[1, 1.0/2, 1.0/6, 0, 0],[1, 3.0/4, 1.0/2, 1.0/4, 0],[1, 1, 1, 1, 1]])
# Use a direct way to obtain Bernstein coefficients from polynomial coefficients
state_coeff = mtimes(Poly_to_Bernstein_matrix_4,coeff.T)
# Replace symbols for states by BSpline object derivatives
subst_from = list(stage.states)
statesize = [0] + [elem.nnz() for elem in stage.states]
statessizecum = np.cumsum(statesize)
state_coeff_split = horzsplit(state_coeff,statessizecum)
subst_to = [BSpline(basis,coeff) for coeff in state_coeff_split]
lookup = dict(zip(subst_from, subst_to))
# Replace symbols for state derivatives by BSpline object derivatives
subst_from += stage._inf_der.keys()
dt = (self.control_grid[k + 1] - self.control_grid[k])/self.M
subst_to += [lookup[e].derivative()*(1/dt) for e in stage._inf_der.values()]
subst_from += stage._inf_inert.keys()
subst_to += stage._inf_inert.values()
# Here, the actual replacement takes place
c_spline = reinterpret_expr(c, subst_from, subst_to)
# The use of '>=' or '<=' on BSpline objects automatically results in
# those same operations being relayed onto BSpline coefficients
# see https://gitlab.kuleuven.be/meco-software/rockit/-/blob/v0.1.28/rockit/splines/spline.py#L520-521
try:
opti.subject_to(self.eval_at_control(stage, c_spline, k), meta=meta)
except IndexError:
pass
def fill_placeholders_integral_control(self, phase, stage, expr, *args):
if phase==1: return
r = 0
for k in range(self.N):
dt = self.control_grid[k + 1] - self.control_grid[k]
r = r + self.eval_at_control(stage, expr, k)*dt
return r
def fill_placeholders_sum_control(self, phase, stage, expr, *args):
if phase==1: return
r = 0
for k in range(self.N):
r = r + self.eval_at_control(stage, expr, k)
return r
def fill_placeholders_sum_control_plus(self, phase, stage, expr, *args):
if phase==1: return
r = 0
for k in list(range(self.N))+[-1]:
r = r + self.eval_at_control(stage, expr, k)
return r
def placeholders_next(self, stage, expr, *args):
self.eval_at_control(stage, expr, k+1)
def fill_placeholders_at_t0(self, phase, stage, expr, *args):
if phase==1: return
return self.eval_at_control(stage, expr, 0)
def fill_placeholders_at_tf(self, phase, stage, expr, *args):
if phase==1: return
return self.eval_at_control(stage, expr, -1)
def add_objective(self, stage, opti):
opti.add_objective(self.eval(stage, stage._objective))
def add_variables_V(self, stage, opti):
DirectMethod.add_variables(self, stage, opti)
# Create time grid (might be symbolic)
self.T = self.eval(stage, stage._T)
self.t0 = self.eval(stage, stage._t0)
self.t0_local = [None]*(self.N+1)
self.T_local = [None]*self.N
def add_variables_V_control(self, stage, opti, k):
if k==0:
self.V_control = [[] for v in stage.variables['control']]
self.V_control_plus = [[] for v in stage.variables['control+']]
for i, v in enumerate(stage.variables['states']):
self.V_states.append([opti.variable(v.shape[0], v.shape[1], scale=stage._scale[v])])
for i, v in enumerate(stage.variables['control']):
self.V_control[i].append(opti.variable(v.shape[0], v.shape[1], scale=stage._scale[v]))
for i, v in enumerate(stage.variables['control+']):
self.V_control_plus[i].append(opti.variable(v.shape[0], v.shape[1], scale=stage._scale[v]))
for i, v in enumerate(stage.variables['states']):
self.V_states[i].append(opti.variable(v.shape[0], v.shape[1], scale=stage._scale[v]))
self.t0_local[k] = self.time_grid.get_t0_local(opti, k, self.t0, self.N)
self.T_local[k] = self.time_grid.get_T_local(opti, k, self.T, self.N)
def add_variables_V_control_finalize(self, stage, opti):
for i, v in enumerate(stage.variables['control+']):
self.V_control_plus[i].append(opti.variable(v.shape[0], v.shape[1], scale=stage._scale[v]))
if self.time_grid.localize_t0:
self.t0_local[self.N] = opti.variable()
self.control_grid = hcat(self.t0_local)
elif self.time_grid.localize_T:
t0 = self.t0
cumsum = [t0]
for e in self.T_local:
cumsum.append(cumsum[-1]+e)
self.control_grid = hcat(cumsum)
else:
self.control_grid = self.time_grid(self.t0, self.T, self.N)
self.time_grid.bounds_finalize(opti, self.control_grid, self.t0_local, self.t0+self.T, self.N)
def add_coupling_constraints(self, stage, opti, k):
advanced = opti.advanced
for c,kwargs in self.time_grid.bounds_T(self.T_local, self.t0_local, k, self.T, self.N):
if not advanced.is_parametric(c):
opti.subject_to(c,**kwargs)
def get_p_control_at(self, stage, k=-1):
return veccat(*[p[k] for p in self.P_control])
def get_v_control_at(self, stage, k=-1):
return veccat(*[v[k] for v in self.V_control])
def get_p_control_plus_at(self, stage, k=-1):
return veccat(*[p[k] for p in self.P_control_plus])
def get_v_control_plus_at(self, stage, k=-1):
return veccat(*[v[k] for v in self.V_control_plus])
def get_v_states_at(self, stage, k=-1):
return veccat(*[v[k] for v in self.V_states])
def get_p_sys(self, stage, k):
return vertcat(vvcat(self.P), self.get_p_control_at(stage, k), self.get_p_control_plus_at(stage, k), self.V, self.get_v_control_at(stage, k), self.get_v_control_plus_at(stage, k))
def eval(self, stage, expr):
return stage.master._method.eval_top(stage.master, stage._expr_apply(expr, p=veccat(*self.P), v=self.V, t0=stage.t0, T=stage.T))
def eval_at_control(self, stage, expr, k):
try:
syms = symvar(expr)
except:
syms = []
offsets = defaultdict(list)
symbols = defaultdict(list)
for s in syms:
if s in stage._offsets:
e, offset = stage._offsets[s]
offsets[offset].append(e)
symbols[offset].append(s)
subst_from = []
subst_to = []
for offset in offsets.keys():
if k==-1 and offset>0:
raise IndexError()
if k+offset<0:
raise IndexError()
subst_from.append(vvcat(symbols[offset]))
subst_to.append(self._eval_at_control(stage, vvcat(offsets[offset]), k+offset))
#print(expr, subst_from, subst_to)
DT_control = self.get_DT_control_at(k)
DT = self.get_DT_at(k, self.M-1 if k==-1 else 0)
expr = stage._expr_apply(expr, sub=(subst_from, subst_to), t0=self.t0, T=self.T, x=self.X[k], z=self.Z[k] if self.Z else nan, xq=self.q if k==-1 else nan, u=self.U[k], p_control=self.get_p_control_at(stage, k), p_control_plus=self.get_p_control_plus_at(stage, k), v=self.V, p=veccat(*self.P), v_control=self.get_v_control_at(stage, k), v_control_plus=self.get_v_control_plus_at(stage, k), v_states=self.get_v_states_at(stage, k), t=self.control_grid[k], DT=DT, DT_control=DT_control)
expr = stage.master._method.eval_top(stage.master, expr)
#print("expr",expr)
return expr
def get_DT_control_at(self, k):
if k==-1 or k==self.N:
return self.control_grid[-1]-self.control_grid[-2]
return self.control_grid[k+1]-self.control_grid[k]
def get_DT_at(self, k, i):
integrator_grid = self.integrator_grid[k]
if i<integrator_grid.numel()-1:
return integrator_grid[i+1]-integrator_grid[i]
else:
return self.integrator_grid[k+1][0]-self.integrator_grid[k][i]
def _eval_at_control(self, stage, expr, k):
x = self.X[k]
z = self.Z[k] if self.Z else nan
u = self.U[-1] if k==len(self.U) else self.U[k] # Would be fixed if we remove the (k=-1 case)
p_control = self.get_p_control_at(stage, k) if k!=len(self.U) else self.get_p_control_at(stage, k-1)
v_control = self.get_v_control_at(stage, k) if k!=len(self.U) else self.get_v_control_at(stage, k-1)
p_control_plus = self.get_p_control_plus_at(stage, k)
v_control_plus = self.get_v_control_plus_at(stage, k)
v_states = self.get_v_states_at(stage, k)
t = self.control_grid[k]
DT_control = self.get_DT_control_at(k)
if k==-1 or k==len(self.integrator_grid):
DT = self.get_DT_at(len(self.integrator_grid)-1, self.M-1)
else:
DT = self.get_DT_at(k, 0)
return stage._expr_apply(expr, t0=self.t0, T=self.T, x=x, z=z, xq=self.q if k==-1 else nan, u=u, p_control=p_control, p_control_plus=p_control_plus, v=self.V, p=veccat(*self.P), v_control=v_control, v_control_plus=v_control_plus, v_states=v_states, t=t, DT=DT, DT_control=DT_control)
def eval_at_integrator(self, stage, expr, k, i):
DT_control = self.get_DT_control_at(k)
DT = self.get_DT_at(k, i)
return stage.master._method.eval_top(stage.master, stage._expr_apply(expr, t0=self.t0, T=self.T, x=self.xk[k*self.M + i], z=self.zk[k*self.M + i] if self.zk else nan, u=self.U[k], p_control=self.get_p_control_at(stage, k), p_control_plus=self.get_p_control_plus_at(stage, k), v=self.V, p=veccat(*self.P), v_control=self.get_v_control_at(stage, k), v_control_plus=self.get_v_control_plus_at(stage, k), v_states=self.get_v_states_at(stage, k), t=self.integrator_grid[k][i], DT=DT, DT_control=DT_control))
def eval_at_integrator_root(self, stage, expr, k, i, j):
DT_control = self.get_DT_control_at(k)
DT = self.get_DT_at(k, i)
return stage.master._method.eval_top(stage.master, stage._expr_apply(expr, t0=self.t0, T=self.T, x=self.xr[k][i][:,j], z=self.zr[k][i][:,j] if self.zk else nan, u=self.U[k], p_control=self.get_p_control_at(stage, k), p_control_plus=self.get_p_control_plus_at(stage, k),v=self.V, p=veccat(*self.P), v_control=self.get_v_control_at(stage, k), v_control_plus=self.get_v_control_plus_at(stage, k),t=self.tr[k][i][j], DT=DT, DT_control=DT_control))
def set_initial(self, stage, master, initial):
opti = master.opti if hasattr(master, 'opti') else master
opti.cache_advanced()
for var, expr in initial.items():
if is_equal(var, stage.T):
var = self.T
if is_equal(var, stage.t0):
var = self.t0
opti_initial = opti.initial()
for k in list(range(self.N))+[-1]:
target = self.eval_at_control(stage, var, k)
value = DM(opti.debug.value(self.eval_at_control(stage, expr, k), opti_initial)) # HOT line
if target.numel()*(self.N)==value.numel():
if repmat(target, self.N, 1).shape==value.shape:
value = value[k,:]
elif repmat(target, 1, self.N).shape==value.shape:
value = value[:,k]
if target.numel()*(self.N+1)==value.numel():
if repmat(target, self.N+1, 1).shape==value.shape:
value = value[k,:]
elif repmat(target, 1, self.N+1).shape==value.shape:
value = value[:,k]
opti.set_initial(target, value, cache_advanced=True)
def set_value(self, stage, master, parameter, value):
opti = master.opti if hasattr(master, 'opti') else master
found = False
for i, p in enumerate(stage.parameters['']):
if is_equal(parameter, p):
found = True
opti.set_value(self.P[i], value)
for i, p in enumerate(stage.parameters['control']):
if is_equal(parameter, p):
found = True
opti.set_value(hcat(self.P_control[i]), value)
for i, p in enumerate(stage.parameters['control+']):
if is_equal(parameter, p):
found = True
opti.set_value(hcat(self.P_control_plus[i]), value)
assert found, "You attempted to set the value of a non-parameter."
def add_parameter(self, stage, opti):
for p in stage.parameters['']:
self.P.append(opti.parameter(p.shape[0], p.shape[1]))
for p in stage.parameters['control']:
self.P_control.append([opti.parameter(p.shape[0], p.shape[1]) for i in range(self.N)])
for p in stage.parameters['control+']:
self.P_control_plus.append([opti.parameter(p.shape[0], p.shape[1]) for i in range(self.N+1)])
def set_parameter(self, stage, opti):
for i, p in enumerate(stage.parameters['']):
opti.set_value(self.P[i], stage._param_value(p))
for i, p in enumerate(stage.parameters['control']):
opti.set_value(hcat(self.P_control[i]), stage._param_value(p))
for i, p in enumerate(stage.parameters['control+']):
opti.set_value(hcat(self.P_control_plus[i]), stage._param_value(p)) | /rockit-meco-0.1.32.tar.gz/rockit-meco-0.1.32/rockit/sampling_method.py | 0.76856 | 0.35883 | sampling_method.py | pypi |
import casadi as cs
from casadi import *
from collections import defaultdict, OrderedDict
from contextlib import contextmanager
def get_ranges_dict(list_expr):
ret = HashDict()
offset = 0
for e in list_expr:
next_offset = offset+e.nnz()
ret[e] = list(range(offset, next_offset))
offset = next_offset
return ret
def reinterpret_expr(expr, symbols_from, symbols_to):
"""
.. code-block:: python
x = MX.sym("x")
y = MX.sym("y")
z = -(x*y**2+2*x)**4<0
print(reinterpret_expr(z,[y],[sin(y)]))
"""
f = Function('f', symbols_from, [expr])
# Work vector
work = [None for i in range(f.sz_w())]
output_val = [None]
# Loop over the algorithm
for k in range(f.n_instructions()):
# Get the atomic operation
op = f.instruction_id(k)
o = f.instruction_output(k)
i = f.instruction_input(k)
if(op == OP_CONST):
v = f.instruction_MX(k).to_DM()
work[o[0]] = v
else:
if op == OP_INPUT:
work[o[0]] = symbols_to[i[0]]
elif op == OP_OUTPUT:
output_val[o[0]] = work[i[0]]
elif op == OP_ADD:
work[o[0]] = work[i[0]] + work[i[1]]
elif op == OP_TWICE:
work[o[0]] = 2 * work[i[0]]
elif op == OP_SUB:
work[o[0]] = work[i[0]] - work[i[1]]
elif op == OP_MUL:
work[o[0]] = work[i[0]] * work[i[1]]
elif op == OP_MTIMES:
work[o[0]] = np.dot(work[i[1]], work[i[2]]) + work[i[0]]
elif op == OP_PARAMETER:
work[o[0]] = f.instruction_MX(k)
elif op == OP_SQ:
work[o[0]] = work[i[0]]**2
elif op == OP_LE:
work[o[0]] = work[i[0]] <= work[i[1]]
elif op == OP_LT:
work[o[0]] = work[i[0]] < work[i[1]]
elif op == OP_NEG:
work[o[0]] = -work[i[0]]
elif op == OP_CONSTPOW:
work[o[0]] = work[i[0]]**work[i[1]]
else:
print('Unknown operation: ', op)
print('------')
print('Evaluated ' + str(f))
return output_val[0]
def get_meta(base=None):
if base is not None: return base
# Construct meta-data
import sys
import os
try:
frame = sys._getframe(2)
meta = {"stacktrace": [{"file":os.path.abspath(frame.f_code.co_filename),"line":frame.f_lineno,"name":frame.f_code.co_name} ] }
except:
meta = {"stacktrace": []}
return meta
def merge_meta(a, b):
if b is None:
return a
if a is None:
return b
from copy import deepcopy
res = deepcopy(a)
res["stacktrace"] += b["stacktrace"]
return res
def single_stacktrace(m):
from copy import deepcopy
m = deepcopy(m)
m["stacktrace"] = m["stacktrace"][0]
return m
def reshape_number(target, value):
if not isinstance(value,cs.MX):
value = cs.DM(value)
if value.is_scalar():
value = cs.DM.ones(target.shape)*value
return value
def DM2numpy(dm, expr_shape, tdim=None):
if tdim is None:
return np.array(dm).squeeze()
expr_prod = expr_shape[0]*expr_shape[1]
target_shape = (tdim,)+tuple([e for e in expr_shape if e!=1])
res = np.array(dm).reshape(expr_shape[0], tdim, expr_shape[1])
res = np.transpose(res,[1,0,2])
res = res.reshape(target_shape)
return res
class HashWrap:
def __init__(self, arg):
assert not isinstance(arg,HashWrap)
self.arg = arg
def __hash__(self):
return hash(self.arg)
def __eq__(self, b):
# key in dict
b_arg = b
if isinstance(b,HashWrap): b_arg = b.arg
if self.arg is b_arg: return True
r = self.arg==b_arg
return r.is_one()
def __str__(self):
return self.arg.__str__()
def __repr__(self):
return self.arg.__repr__()
class HashDict(dict):
def __init__(self,*args,**kwargs):
r = dict(*args,**kwargs)
dict.__init__(self)
for k,v in r.items():
self[k] = v
def __getitem__(self, k):
return dict.__getitem__(self, HashWrap(k))
def __setitem__(self, k, v):
return dict.__setitem__(self, HashWrap(k), v)
def keys(self):
for k in dict.keys(self):
yield k.arg
def items(self):
for k,v in dict.items(self):
yield k.arg, v
__iter__ = keys
def __copy__(self):
r = HashDict()
for k,v in self.items():
r[k] = v
return r
class HashList(list):
def __init__(self,*args,**kwargs):
r = list(*args,**kwargs)
list.__init__(self)
for v in r:
self.append(v)
self._stored = set()
def append(self, item):
list.append(self, item)
self._stored.add(HashWrap(item))
def __contains__(self, item):
return item in self._stored
def __copy__(self):
r = HashList()
for v in self:
r.append(v)
return r
class HashDefaultDict(defaultdict):
def __init__(self,default_factory=None, *args,**kwargs):
r = defaultdict(default_factory,*args,**kwargs)
defaultdict.__init__(self)
for k,v in r.items():
self[k] = v
def __getitem__(self, k):
return defaultdict.__getitem__(self, HashWrap(k))
def __setitem__(self, k, v):
return defaultdict.__setitem__(self, HashWrap(k), v)
def keys(self):
ret = []
for k in defaultdict.keys(self):
ret.append(k.arg)
return ret
def items(self):
for k,v in defaultdict.items(self):
yield k.arg, v
def __iter__(self):
for k in defaultdict.__iter__(self):
yield k.arg
def __copy__(self):
r = HashDefaultDict(self.default_factory)
for k,v in self.items():
r[k] = v
return r
class HashOrderedDict(OrderedDict):
def __init__(self,*args,**kwargs):
r = OrderedDict(*args,**kwargs)
OrderedDict.__init__(self)
for k,v in r.items():
self[k] = v
def __getitem__(self, k):
return OrderedDict.__getitem__(self, HashWrap(k))
def __setitem__(self, k, v):
return OrderedDict.__setitem__(self, HashWrap(k), v)
def keys(self):
ret = []
for k in self:
ret.append(k)
return ret
def items(self):
for k in self:
yield k, self[k]
def __iter__(self):
for k in OrderedDict.__iter__(self):
yield k.arg
def __copy__(self):
r = HashOrderedDict()
for k,v in self.items():
r[k] = v
return r
def for_all_primitives(expr, rhs, callback, msg, rhs_type=MX):
if expr.is_symbolic():
callback(expr, rhs)
return
if expr.is_valid_input():
# Promote to correct size
rhs = rhs_type(rhs)
if rhs.is_scalar() and not expr.is_scalar():
rhs = rhs*rhs_type(expr.sparsity())
rhs = rhs[expr.sparsity()]
rhs = vec(rhs)
prim = expr.primitives()
rhs = rhs.nz
offset = 0
for p in prim:
callback(p, rhs_type(p.sparsity(), rhs[offset:offset+p.nnz()]))
offset += p.nnz()
else:
raise Exception(msg)
class Node:
def __init__(self,val):
self.val = val
self.nodes = []
class AutoBrancher:
OPEN = 0
DONE = 1
def __init__(self):
self.root = Node(AutoBrancher.OPEN)
self.trace = [self.root]
@property
def current(self):
return self.trace[-1]
def branch(self, alternatives = [True, False]):
alternatives = list(alternatives)
nodes = self.current.nodes
if len(nodes)==0:
nodes += [None]*len(alternatives)
for i,n in enumerate(nodes):
if n is None:
nodes[i] = Node(AutoBrancher.OPEN)
self.trace.append(nodes[i])
self.this_branch.append(alternatives[i])
return alternatives[i]
else:
if n.val == AutoBrancher.OPEN:
self.trace.append(nodes[i])
self.this_branch.append(alternatives[i])
return alternatives[i]
def __iter__(self):
cnt = 0
while self.root.val==AutoBrancher.OPEN:
self.this_branch = []
cnt+=1
yield self
# Indicate that current leaf is done
self.current.val = AutoBrancher.DONE
# Close leaves when subleaves are done
for n in reversed(self.trace[:-1]):
finished = True
for e in n.nodes:
finished = finished and e and e.val==AutoBrancher.DONE
if finished:
n.val = AutoBrancher.DONE
# Reset trace
self.trace = [self.root]
print("Evaluated branch",self.this_branch)
print("Evaluated",cnt,"branches")
def vvcat(arg):
if len(arg)==0:
return cs.MX(0,1)
else:
return cs.vvcat(arg)
def vcat(arg):
if len(arg)==0:
return cs.MX(0,1)
else:
return cs.vcat(arg)
def prepare_build_dir(build_dir_abs):
import os
import shutil
os.makedirs(build_dir_abs,exist_ok=True)
# Clean directory (but do not delete it,
# since this confuses open shells in Linux (e.g. bash, Matlab)
for filename in os.listdir(build_dir_abs):
file_path = os.path.join(build_dir_abs, filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except:
pass
class ConstraintInspector:
def __init__(self, method, stage):
self.opti = Opti()
self.X = self.opti.variable(*stage.x.shape)
self.U = self.opti.variable(*stage.u.shape)
self.V = self.opti.variable(*stage.v.shape)
self.P = self.opti.parameter(*stage.p.shape)
self.t = self.opti.variable()
self.T = self.opti.variable()
offsets = list(stage._offsets.keys())
self.offsets = []
for e in offsets:
self.offsets.append(self.opti.variable(*e.shape))
self.raw = [stage.x,stage.u,stage.p,stage.t, method.v]+offsets
self.optivar = [self.X, self.U, self.P, self.t, self.V]+self.offsets
if method.free_time:
self.raw += [stage.T]
self.optivar += [self.T]
def finalize(self):
self.opti_advanced = self.opti.advanced
def canon(self,expr):
c = substitute([expr],self.raw,self.optivar)[0]
mc = self.opti_advanced.canon_expr(c) # canon_expr should have a static counterpart
return substitute([mc.lb,mc.canon,mc.ub],self.optivar,self.raw), mc
def linear_coeffs(expr, *args):
""" Multi-argument extesion to CasADi linear_coeff"""
J,c = linear_coeff(expr, vcat(args))
cs = np.cumsum([0]+[e.numel() for e in args])
return tuple([J[:,cs[i]:cs[i+1]] for i in range(len(args))])+(c,)
ca_classes = [cs.SX,cs.MX,cs.Function,cs.Sparsity,cs.DM,cs.Opti]
@contextmanager
def rockit_pickle_context():
string_serializer = cs.StringSerializer()
string_serializer.pack("preamble")
string_serializer.encode()
def __getstate__(self):
if isinstance(self,cs.Opti):
raise Exception("Opti cannot be serialized yet. Consider removing the transcribed problem.")
string_serializer.pack(self)
enc = string_serializer.encode()
return {"s":enc}
for c in ca_classes:
setattr(c, '__getstate__', __getstate__)
yield
for c in ca_classes:
delattr(c, '__getstate__')
@contextmanager
def rockit_unpickle_context():
string_serializer = cs.StringSerializer()
string_serializer.pack("preamble")
string_deserializer = cs.StringDeserializer(string_serializer.encode())
string_deserializer.unpack()
def __setstate__(self,state):
string_deserializer.decode(state["s"])
s = string_deserializer.unpack()
self.this = s.this
for c in ca_classes:
setattr(c, '__setstate__', __setstate__)
yield
for c in ca_classes:
delattr(c, '__setstate__') | /rockit-meco-0.1.32.tar.gz/rockit-meco-0.1.32/rockit/casadi_helpers.py | 0.41561 | 0.274767 | casadi_helpers.py | pypi |
from casadi import Opti, jacobian, dot, hessian, symvar, evalf, veccat, DM, vertcat, is_equal
import casadi
import numpy as np
from .casadi_helpers import get_meta, merge_meta, single_stacktrace, MX
from .solution import OcpSolution
from .freetime import FreeTime
class DirectMethod:
"""
Base class for 'direct' solution methods for Optimal Control Problems:
'first discretize, then optimize'
"""
def __init__(self):
self._solver = None
self._solver_options = None
self._callback = None
self.artifacts = []
self.clean()
def clean(self):
self.V = None
self.P = []
def jacobian(self, with_label=False):
J = jacobian(self.opti.g, self.opti.x).sparsity()
if with_label:
return J, "Constraint Jacobian: " + J.dim(True)
else:
return J
def hessian(self, with_label=False):
lag = self.opti.f + dot(self.opti.lam_g, self.opti.g)
H = hessian(lag, self.opti.x)[0].sparsity()
if with_label:
return H, "Lagrange Hessian: " + H.dim(True)
else:
return H
def spy_jacobian(self):
import matplotlib.pylab as plt
J, title = self.jacobian(with_label=True)
plt.spy(np.array(J))
plt.title(title)
def spy_hessian(self):
import matplotlib.pylab as plt
lag = self.opti.f + dot(self.opti.lam_g, self.opti.g)
H, title = self.hessian(with_label=True)
plt.spy(np.array(H))
plt.title(title)
def inherit(self, template):
if template and template._solver is not None:
self._solver = template._solver
if template and template._solver_options is not None:
self._solver_options = template._solver_options
if template and template._callback is not None:
self._callback = template._callback
def eval(self, stage, expr):
return self.eval_top(stage, expr)
def eval_top(self, stage, expr):
return substitute(MX(expr),veccat(*(stage.variables[""]+stage.parameters[""])),vertcat(self.V,veccat(*self.P)))
def add_variables(self, stage, opti):
V = []
for v in stage.variables['']:
V.append(opti.variable(v.shape[0], v.shape[1], scale=stage._scale[v]))
self.V = veccat(*V)
def add_parameters(self, stage, opti):
self.P = []
for p in stage.parameters['']:
self.P.append(opti.parameter(p.shape[0], p.shape[1]))
def untranscribe(self, stage, phase=1,**kwargs):
self.clean()
def untranscribe_placeholders(self, phase, stage):
pass
def main_untranscribe(self,stage, phase=1, **kwargs):
self.opti = None
def main_transcribe(self, stage, phase=1, **kwargs):
if phase==0: return
if phase==1:
self.opti = OptiWrapper(stage)
if self._callback:
self.opti.callback(self._callback)
if self.solver is not None:
if self._solver is None:
raise Exception("You forgot to declare a solver. Use e.g. ocp.solver('ipopt').")
self.opti.solver(self._solver, self._solver_options)
if phase==2:
self.opti.transcribe_placeholders(phase, kwargs["placeholders"])
def transcribe(self, stage, phase=1, **kwargs):
if stage.nx>0 or stage.nu>0:
raise Exception("You forgot to declare a method. Use e.g. ocp.method(MultipleShooting(N=3)).")
if phase==0: return
if phase>1: return
self.add_variables(stage, self.opti)
self.add_parameters(stage, self.opti)
for c, m, _ in stage._constraints["point"]:
self.opti.subject_to(self.eval_top(stage, c), meta = m)
self.opti.add_objective(self.eval_top(stage, stage._objective))
self.set_initial(stage, self.opti, stage._initial)
self.set_parameter(stage, self.opti)
def set_initial(self, stage, master, initial):
opti = master.opti if hasattr(master, 'opti') else master
opti.cache_advanced()
for var, expr in initial.items():
opti_initial = opti.initial()
target = self.eval_top(stage, var)
value = DM(opti.debug.value(self.eval_top(stage, expr), opti_initial)) # HOT line
opti.set_initial(target, value, cache_advanced=True)
def set_parameter(self, stage, opti):
for i, p in enumerate(stage.parameters['']):
opti.set_value(self.P[i], stage._param_value(p))
def set_value(self, stage, master, parameter, value):
opti = master.opti if hasattr(master, 'opti') else master
found = False
for i, p in enumerate(stage.parameters['']):
if is_equal(parameter, p):
found = True
opti.set_value(self.P[i], value)
assert found, "You attempted to set the value of a non-parameter."
def transcribe_placeholders(self, phase, stage, placeholders):
pass
def non_converged_solution(self, stage):
if not hasattr(self, 'opti'):
raise Exception("You forgot to solve first. To avoid your script halting, use a try-catch block.")
return OcpSolution(self.opti.non_converged_solution, stage)
def solve(self, stage):
return OcpSolution(self.opti.solve(), stage)
def solve_limited(self, stage):
return OcpSolution(self.opti.solve_limited(), stage)
def callback(self, stage, fun):
self._callback = lambda iter : fun(iter, OcpSolution(self.opti.non_converged_solution, stage))
@property
def debug(self):
self.opti.debug
def solver(self, solver, solver_options={}):
self._solver = solver
self._solver_options = solver_options
def show_infeasibilities(self, *args):
self.opti.debug.show_infeasibilities(*args)
def initial_value(self, stage, expr):
return self.opti.value(expr, self.opti.initial())
@property
def gist(self):
"""Obtain an expression packing all information needed to obtain value/sample
The composition of this array may vary between rockit versions
Returns
-------
:obj:`~casadi.MX` column vector
"""
return vertcat(self.opti.x, self.opti.p)
def to_function(self, stage, name, args, results, *margs):
return self.opti.to_function(name, [stage.value(a) for a in args], results, *margs)
def fill_placeholders_integral(self, phase, stage, expr, *args):
if phase==1:
I = stage.state(quad=True)
stage.set_der(I, expr)
return stage.at_tf(I)
def fill_placeholders_T(self, phase, stage, expr, *args):
if phase==1:
if isinstance(stage._T, FreeTime):
init = stage._T.T_init
stage.set_T(stage.variable())
stage.subject_to(stage._T>=0)
stage.set_initial(stage._T, init,priority=True)
return stage._T
else:
return stage._T
return self.eval(stage, expr)
def fill_placeholders_t0(self, phase, stage, expr, *args):
if phase==1:
if isinstance(stage._t0, FreeTime):
init = stage._t0.T_init
stage.set_t0(stage.variable())
stage.set_initial(stage._t0, init,priority=True)
return stage._t0
else:
return stage._t0
return self.eval(stage, expr)
def fill_placeholders_t(self, phase, stage, expr, *args):
return None
def fill_placeholders_DT(self, phase, stage, expr, *args):
return None
def fill_placeholders_DT_control(self, phase, stage, expr, *args):
return None
from casadi import substitute
class OptiWrapper(Opti):
def __init__(self, ocp):
self.ocp = ocp
Opti.__init__(self)
self.initial_keys = []
self.initial_values = []
self.constraints = []
self.objective = 0
def subject_to(self, expr=None, scale=1, meta=None):
meta = merge_meta(meta, get_meta())
if expr is None:
self.constraints = []
else:
if isinstance(expr,MX) and expr.is_constant():
if np.all(np.array(evalf(expr)).squeeze()==1):
return
else:
raise Exception("You have a constraint that is never statisfied.")
self.constraints.append((expr, scale, meta))
def add_objective(self, expr):
self.objective = self.objective + expr
def clear_objective(self):
self.objective = 0
def callback(self,fun):
Opti.callback(self, fun)
def initial(self):
return [e for e in Opti.initial(self) if e.dep(0).is_symbolic() or e.dep(1).is_symbolic()]+Opti.value_parameters(self)
@property
def non_converged_solution(self):
return OptiSolWrapper(self, self.debug)
def variable(self,n=1,m=1, scale=1):
if n==0 or m==0:
return MX(n, m)
else:
return scale*Opti.variable(self,n, m)
def cache_advanced(self):
self._advanced_cache = self.advanced
def set_initial(self, key, value, cache_advanced=False):
a = set([hash(e) for e in (self._advanced_cache if cache_advanced else self.advanced).symvar()])
b = set([hash(e) for e in symvar(key)])
if len(a | b)==len(a):
Opti.set_initial(self, key, value) # set_initial logic in direct_collocation needs this
else:
self.initial_keys.append(key)
self.initial_values.append(value)
def transcribe_placeholders(self,phase,placeholders):
opti_advanced = self.advanced
Opti.subject_to(self)
n_constr = len(self.constraints)
res = placeholders([c[0] for c in self.constraints] + [self.objective]+self.initial_keys)
for c, scale, meta in zip(res[:n_constr], [c[1] for c in self.constraints], [c[2] for c in self.constraints]):
try:
if MX(c).is_constant() and MX(c).is_one():
continue
if not MX(scale).is_one():
mc = opti_advanced.canon_expr(c) # canon_expr should have a static counterpart
if mc.type in [casadi.OPTI_INEQUALITY, casadi.OPTI_GENERIC_INEQUALITY, casadi.OPTI_DOUBLE_INEQUALITY]:
print(mc.lb,mc.canon,mc.ub)
lb = mc.lb/scale
canon = mc.canon/scale
ub = mc.ub/scale
# Check for infinities
try:
lb_inf = np.all(np.array(evalf(lb)==-np.inf))
except:
lb_inf = False
try:
ub_inf = np.all(np.array(evalf(ub)==np.inf))
except:
ub_inf = False
if lb_inf:
c = canon <= ub
elif ub_inf:
c = lb <= canon
else:
c = lb <= (canon <= ub)
if mc.type in [casadi.OPTI_EQUALITY, casadi.OPTI_GENERIC_EQUALITY]:
lb = mc.lb/scale
canon = mc.canon/scale
c = lb==canon
Opti.subject_to(self,c)
except Exception as e:
print(meta,c)
raise e
self.update_user_dict(c, single_stacktrace(meta))
Opti.minimize(self,res[n_constr])
for k_orig, k, v in zip(self.initial_keys,res[n_constr+1:],self.initial_values):
Opti.set_initial(self, k, v)
def solve(self):
return OptiSolWrapper(self, Opti.solve(self))
class OptiSolWrapper:
def __init__(self, opti_wrapper, sol):
self.opti_wrapper = opti_wrapper
self.sol = sol
def value(self, expr, *args,**kwargs):
placeholders = self.opti_wrapper.ocp.placeholders_transcribed
return self.sol.value(placeholders(expr), *args, **kwargs)
def stats(self):
return self.sol.stats() | /rockit-meco-0.1.32.tar.gz/rockit-meco-0.1.32/rockit/direct_method.py | 0.658088 | 0.281099 | direct_method.py | pypi |
from ..multiple_shooting import MultipleShooting
from ..sampling_method import SamplingMethod, UniformGrid
from ..solution import OcpSolution
from ..freetime import FreeTime
from ..casadi_helpers import DM2numpy, reshape_number, linear_coeffs
from collections import OrderedDict
from casadi import SX, Sparsity, MX, vcat, veccat, symvar, substitute, sparsify, DM, Opti, is_linear, vertcat, depends_on, jacobian, linear_coeff, quadratic_coeff, mtimes, pinv, evalf, Function, vvcat, inf, sum1, sum2, diag
import casadi
import numpy as np
import scipy
INF = 1e5
def legit_J(J):
"""
Checks if J, a pre-multiplier for states and control, is of legitimate structure
J must a slice of a permuted unit matrix.
"""
try:
J = evalf(J)
except:
return False
if not np.all(np.array(J.nonzeros())==1): # All nonzeros must be one
return False
# Each row must contain exactly 1 nonzero
if not np.all(np.array(sum2(J))==1):
return False
# Each column must contain at most 1 nonzero
if not np.all(np.array(sum1(J))<=1):
return False
return True
def check_Js(J):
"""
Checks if J, a pre-multiplier for slacks, is of legitimate structure
Empty rows are allowed
"""
try:
J = evalf(J)
except:
raise Exception("Slack error")
assert np.all(np.array(J.nonzeros())==1), "All nonzeros must be 1"
# Check if slice of permutation of unit matrix
assert np.all(np.array(sum2(J))<=1), "Each constraint can only depend on one slack at most"
assert np.all(np.array(sum1(J))<=1), "Each constraint must depend on a unique slack, if any"
class ExternalMethod:
def __init__(self,supported=None,N=20,grid=UniformGrid(),linesearch=True,expand=False,**args):
self.N = N
self.args = args
self.grid = grid
self.T = None
self.linesearch = linesearch
self.expand = expand
self.supported = {} if supported is None else supported
self.free_time = False
def inherit(self, parent):
pass
def fill_placeholders_t0(self, phase, stage, expr, *args):
if phase==1:
if isinstance(stage._t0,FreeTime):
return stage.at_t0(self.t)
else:
return stage._t0
return
def fill_placeholders_T(self, phase, stage, expr, *args):
if phase==1:
if isinstance(stage._T,FreeTime):
self.free_time = True
if "free_T" in self.supported:
# Keep placeholder symbol
return
else:
T = stage.register_state(MX.sym('T'))
stage.set_der(T, 0)
self.T = T
stage.set_initial(T, stage._T.T_init)
return stage.at_tf(T)
else:
self.T = stage._T
return stage._T
return
def fill_placeholders_t(self, phase, stage, expr, *args):
if phase==1:
if self.t_state:
t = stage.state()
stage.set_next(t, t+ stage.DT) if stage._state_next else stage.set_der(t, 1)
self.t = t
if not isinstance(stage._t0,FreeTime):
stage.subject_to(stage.at_t0(self.t)==stage._t0)
return t
else:
self.t = MX(1,1)
return
return
def transcribe_placeholders(self, phase, stage, placeholders):
"""
Transcription is the process of going from a continuous-time OCP to an NLP
"""
return stage._transcribe_placeholders(phase, self, placeholders)
def fill_placeholders_sum_control(self, phase, stage, expr, *args):
if phase==1:
return expr
def fill_placeholders_at_t0(self, phase, stage, expr, *args):
if phase==1: return
ret = {}
ks = [stage.x,stage.u]
vs = [self.X_gist[0],self.U_gist[0]]
if not self.t_state:
ks += [stage.t]
vs += [self.control_grid[0]]
ret["normal"] = substitute([expr],ks,vs)[0]
ret["expose"] = expr
return ret
def fill_placeholders_at_tf(self, phase, stage, expr, *args):
if phase==1: return
ret = {}
ks = [stage.x,stage.u]
vs = [self.X_gist[-1],self.U_gist[-1]]
if not self.t_state:
ks += [stage.t]
vs += [self.control_grid[-1]]
ret["normal"] = substitute([expr],ks,vs)[0]
ret["expose"] = expr
return ret
def fill_placeholders_DT(self, phase, stage, expr, *args):
return None
def fill_placeholders_DT_control(self, phase, stage, expr, *args):
return None
def main_transcribe(self, stage, phase=1, **kwargs):
pass
def transcribe(self, stage, phase=1, **kwargs):
if phase==0:
def recursive_depends(expr,t):
expr = MX(expr)
if depends_on(expr, t):
return True
if expr in stage._placeholders:
if recursive_depends(stage._placeholders[expr][1],t):
return True
else:
if expr.is_symbolic():
return depends_on(expr, t)
for s in symvar(expr):
if recursive_depends(s, t):
return True
return False
# Do we need to introduce a helper state for t?
f = stage._diffeq() if stage._state_next else stage._ode()
if not stage._state_next:
if f.sparsity_in('t').nnz()>0:
self.t_state = True
return
# Occurs in lagrange?
obj = MX(stage._objective)
for e in symvar(obj):
if e.name()=='r_sum_control' and recursive_depends(e,stage.t):
self.t_state = True
return
if isinstance(stage._t0, FreeTime):
self.t_state = True
return
if isinstance(stage._T, FreeTime) or isinstance(stage._t0, FreeTime):
for c,_,_ in stage._constraints["control"]+stage._constraints["integrator"]:
if recursive_depends(c,stage.t):
self.t_state = True
return
self.t_state = False
return
if phase==1:
self.transcribe_phase1(stage, **kwargs)
else:
self.transcribe_phase2(stage, **kwargs)
def set_value(self, stage, master, parameter, value):
J = jacobian(parameter, stage.p)
v = reshape_number(parameter, value)
self.P0[J.sparsity().get_col()] = v[J.row()]
@property
def gist(self):
"""Obtain an expression packing all information needed to obtain value/sample
The composition of this array may vary between rockit versions
Returns
-------
:obj:`~casadi.MX` column vector
"""
return vertcat(vcat(self.X_gist), vcat(self.U_gist))
def eval(self, stage, expr):
return expr
def eval_at_control(self, stage, expr, k):
placeholders = stage.placeholders_transcribed
expr = placeholders(expr,max_phase=1)
ks = [stage.x,stage.u]
vs = [self.X_gist[k], self.U_gist[min(k, self.N-1)]]
if not self.t_state:
ks += [stage.t]
vs += [self.control_grid[k]]
return substitute([expr],ks,vs)[0]
class SolWrapper:
def __init__(self, method, x, u):
self.method = method
self.x = x
self.u = u
def value(self, expr, *args,**kwargs):
placeholders = self.method.stage.placeholders_transcribed
ret = evalf(substitute([placeholders(expr)],[self.method.gist],[vertcat(self.x, self.u)])[0])
return ret.toarray(simplify=True) | /rockit-meco-0.1.32.tar.gz/rockit-meco-0.1.32/rockit/external/method.py | 0.64646 | 0.441252 | method.py | pypi |
from rkgb.utils import print_debug
from rockmate.def_chain import RK_Chain
from rockmate.def_sequence import (
SeqBlockFn,
SeqBlockFc,
SeqBlockFe,
SeqBlockBwd,
SeqLoss,
RK_Sequence,
)
# ==========================
# ==== DYNAMIC PROGRAM =====
# ==========================
def psolve_dp_functionnal(chain, mmax, opt_table=None):
"""Returns the optimal table:
Opt[m][lmin][lmax] : int matrix
with lmin = 0...chain.length
and lmax = lmin...chain.length (lmax is not included)
and m = 0...mmax
What[m][lmin][lmax] is :
(True, k) if the optimal choice is a chain chkpt
-> ie F_e this block with solution k
(False,j) if the optimal choice is a leaf chkpt
-> ie F_c and then F_n (j-1) blocks
"""
ln = chain.ln
fw = chain.fw
bw = chain.bw
cw = chain.cw
cbw = chain.cbw
fwd_tmp = chain.fwd_tmp
bwd_tmp = chain.bwd_tmp
ff_fwd_tmp = chain.ff_fwd_tmp
ff_fw = chain.ff_fw
nb_sol = chain.nb_sol
opt, what = opt_table if opt_table is not None else ({}, {})
# opt = dict()
# what = dict()
def opt_add(m, a, b, time):
if not m in opt:
opt[m] = dict()
if not a in opt[m]:
opt[m][a] = dict()
opt[m][a][b] = time
def what_add(m, a, b, time):
if not m in what:
what[m] = dict()
if not a in what[m]:
what[m][a] = dict()
what[m][a][b] = time
# -> Last one is a dict because its indices go from i to l.
# -> Renumbering will wait for C implementation
# -- Initialize borders of the tables for lmax-lmin = 0 --
def case_d_0(m, i):
possibilities = []
for k in range(nb_sol[i]):
limit = max(
cw[i] + cbw[i + 1][k] + fwd_tmp[i][k],
cw[i] + cbw[i + 1][k] + bwd_tmp[i][k],
)
if m >= limit:
possibilities.append((k, fw[i][k] + bw[i][k]))
if possibilities == []:
opt_add(m, i, i, float("inf"))
else:
best_sol = min(possibilities, key=lambda t: t[1])
opt_add(m, i, i, best_sol[1])
what_add(m, i, i, (True, best_sol[0]))
return opt[m][i][i]
# -- dynamic program --
nb_call = 0
def solve_aux(m, a, b):
if (m not in opt) or (a not in opt[m]) or (b not in opt[m][a]):
nonlocal nb_call
nb_call += 1
if a == b:
return case_d_0(m, a)
# lmin = a ; lmax = b
mmin = cw[b + 1] + cw[a + 1] + ff_fwd_tmp[a]
if b > a + 1:
mmin = max(
mmin,
cw[b + 1]
+ max(
cw[j] + cw[j + 1] + ff_fwd_tmp[j]
for j in range(a + 1, b)
),
)
if m < mmin:
opt_add(m, a, b, float("inf"))
else:
# -- Solution 1 --
sols_later = [
(
j,
(
sum(ff_fw[a:j])
+ solve_aux(m - cw[j], j, b)
+ solve_aux(m, a, j - 1)
),
)
for j in range(a + 1, b + 1)
if m >= cw[j]
]
if sols_later:
best_later = min(sols_later, key=lambda t: t[1])
else:
best_later = None
# -- Solution 2 --
# -> we can no longer use opt[i][i] because the cbw
# -> now depend on the F_e chosen.
sols_now = []
for k in range(nb_sol[a]):
mem_f = cw[a + 1] + cbw[a + 1][k] + fwd_tmp[a][k]
mem_b = cw[a] + cbw[a + 1][k] + bwd_tmp[a][k]
limit = max(mem_f, mem_b)
if m >= limit:
time = fw[a][k] + bw[a][k]
time += solve_aux(m - cbw[a + 1][k], a + 1, b)
sols_now.append((k, time))
if sols_now:
best_now = min(sols_now, key=lambda t: t[1])
else:
best_now = None
# -- best of 1 and 2 --
if best_later is None and best_now is None:
opt_add(m, a, b, float("inf"))
elif best_later is None or (
best_now is not None and best_now[1] < best_later[1]
):
opt_add(m, a, b, best_now[1])
what_add(m, a, b, (True, best_now[0]))
else:
opt_add(m, a, b, best_later[1])
what_add(m, a, b, (False, best_later[0]))
return opt[m][a][b]
solve_aux(mmax, 0, ln)
print_debug(f"Nb calls : {nb_call}")
return (opt, what)
# ==========================
# ==== SEQUENCE BUILDER ====
# ==========================
def pseq_builder(chain, memory_limit, opt_table):
# returns :
# - the optimal sequence of computation using mem-persistent algo
mmax = memory_limit - chain.cw[0]
# opt, what = solve_dp_functionnal(chain, mmax, *opt_table)
opt, what = opt_table
# ~~~~~~~~~~~~~~~~~~
def seq_builder_rec(lmin, lmax, cmem):
seq = RK_Sequence()
if lmin > lmax:
return seq
if cmem <= 0:
raise ValueError(
"Can't find a feasible sequence with the given budget"
)
if opt[cmem][lmin][lmax] == float("inf"):
"""
print('a')
print(chain.cw)
print('abar')
for i in range(chain.ln):
print(chain.cbw[i])
print(chain.fwd_tmp[i])
print(chain.bwd_tmp[i])
"""
raise ValueError(
"Can't find a feasible sequence with the given budget"
# f"Can't process this chain from index "
# f"{lmin} to {lmax} with memory {memory_limit}"
)
if lmin == chain.ln:
seq.insert(SeqLoss())
return seq
w = what[cmem][lmin][lmax]
# -- Solution 1 --
if w[0]:
k = w[1]
sol = chain.body[lmin].sols[k]
seq.insert(SeqBlockFe(lmin, sol.fwd_sched))
seq.insert_seq(
seq_builder_rec(lmin + 1, lmax, cmem - chain.cbw[lmin + 1][k])
)
seq.insert(SeqBlockBwd(lmin, sol.bwd_sched))
# -- Solution 1 --
else:
j = w[1]
seq.insert(SeqBlockFc(lmin, chain.body[lmin].Fc_sched))
for k in range(lmin + 1, j):
seq.insert(SeqBlockFn(k, chain.body[k].Fn_sched))
seq.insert_seq(seq_builder_rec(j, lmax, cmem - chain.cw[j]))
seq.insert_seq(seq_builder_rec(lmin, j - 1, cmem))
return seq
# ~~~~~~~~~~~~~~~~~~
seq = seq_builder_rec(0, chain.ln, mmax)
return seq
# ===================================
# ===== interface to C version =====
# ===================================
# The C version produces 'csequence' SeqOps, we have to convert them
import rockmate.csequence as cs
try:
import rockmate.csolver as rs
csolver_present = True
except:
csolver_present = False
def convert_sequence_from_C(chain: RK_Chain, original_sequence):
def convert_op(op):
if isinstance(op, cs.SeqLoss):
return SeqLoss()
body = chain.body[op.index]
if isinstance(op, cs.SeqBlockFn):
return SeqBlockFn(op.index, body.Fn_sched)
if isinstance(op, cs.SeqBlockFc):
return SeqBlockFc(op.index, body.Fc_sched)
if isinstance(op, cs.SeqBlockFe):
return SeqBlockFe(op.index, body.sols[op.option].fwd_sched)
if isinstance(op, cs.SeqBlockBwd):
return SeqBlockBwd(op.index, body.sols[op.option].bwd_sched)
result = RK_Sequence([convert_op(op) for op in original_sequence])
return result
def csolve_dp_functionnal(chain: RK_Chain, mmax, opt_table=None):
if opt_table is None: ## TODO? if opt_table.mmax < mmax, create new table
result = rs.RkTable(chain, mmax)
else:
result = opt_table
result.get_opt(mmax)
return result
def cseq_builder(chain: RK_Chain, mmax, opt_table):
result = opt_table.build_sequence(mmax)
return convert_sequence_from_C(chain, result)
# ===============================================
# ===== generic interface, selects version =====
# ===============================================
def solve_dp_functionnal(chain, mmax, opt_table=None, force_python=False):
if force_python or not csolver_present:
return psolve_dp_functionnal(chain, mmax, opt_table)
else:
return csolve_dp_functionnal(chain, int(mmax), opt_table)
def seq_builder(chain, mmax, opt_table):
if csolver_present and isinstance(opt_table, rs.RkTable):
return cseq_builder(chain, int(mmax), opt_table)
else:
return pseq_builder(chain, mmax, opt_table) | /rockmate-1.0.1.tar.gz/rockmate-1.0.1/src/rotor_solver.py | 0.408867 | 0.295135 | rotor_solver.py | pypi |
from rockmate.def_op import OpSchedule
ref_print_atoms = [True]
# ==========================
# ====== Seq Atom Op =======
# ==========================
class SeqAtomOp:
def __init__(self, op):
header = f"{op.op_type} {op.main_target}"
self.name = header
self.time = op.time
self.op = op
def __str__(self):
return self.name
# ==========================
# ==========================
# ========= Seq Op =========
# ==========================
class SeqOp:
pass
class SeqLoss(SeqOp):
def __init__(self):
self.time = 0
self.mem = 0
def __str__(self):
return "Loss"
# ** Seq Block Op **
# -> Subclasses : Fn,Fc,Fe,Bwd
class SeqBlockOp(SeqOp):
def __init__(self, name, index, op_sched: OpSchedule):
self.name = name
self.index = index
self.op_sched = op_sched
self.time = self.op_sched.time # sum(o.time for o in body)
self.mem = self.op_sched.save[-1] # sum(o.mem for o in body)
self.overhead = self.op_sched.overhead
def __str__(self):
header = f"{self.name} Block {self.index} in {self.time}"
if ref_print_atoms[0]:
sb = "\n| ".join([o.__str__() for o in self.op_sched.op_list])
return f"{header}\n{sb}"
else:
return header
class SeqBlockFn(SeqBlockOp):
def __init__(self, *args):
super().__init__("Fn", *args)
class SeqBlockFc(SeqBlockOp):
def __init__(self, *args):
super().__init__("Fc", *args)
class SeqBlockFe(SeqBlockOp):
def __init__(self, *args):
super().__init__("Fe", *args)
class SeqBlockBwd(SeqBlockOp):
def __init__(self, *args):
super().__init__("Bwd", *args)
# ==========================
# ==========================
# ======== Sequence ========
# ==========================
class RK_Sequence:
def __init__(self, l=None):
if l:
self.seq = l
else:
self.seq = []
def __str__(self):
return "\n".join([str(o) for o in self.seq])
def insert(self, op: SeqOp):
self.seq.append(op)
def insert_seq(self, sub_seq):
self.seq.extend(sub_seq.seq)
def compute_time(self):
return sum([o.time for o in self.seq])
def cut_fwd_bwd(self):
ln = len(self.seq)
for i in range(ln):
if isinstance(self.seq[i], SeqLoss):
return (
RK_Sequence(list(self.seq[:i])),
RK_Sequence(list(self.seq[(i + 1) :])),
)
raise Exception("Can't cut a Sequence which doesn't have SeqLoss")
# ========================== | /rockmate-1.0.1.tar.gz/rockmate-1.0.1/src/def_sequence.py | 0.515376 | 0.250111 | def_sequence.py | pypi |
# %% auto 0
__all__ = ['get_run_data', 'preprocess_image', 'load_model', 'get_prediction', 'main']
# %% ../../notebooks/03_e_predict.ipynb 1
import os
from io import BytesIO
import cv2
import numpy as np
import tensorflow_addons as tfa
import wandb
from hydra import compose, initialize
from tensorflow.keras import models, optimizers
# %% ../../notebooks/03_e_predict.ipynb 2
def get_run_data():
"""Get data for a wandb sweep."""
api = wandb.Api()
entity = "rock-classifiers"
project = "Whats-this-rockv7"
sweep_id = "snemzvnp"
sweep = api.sweep(f"{entity}/{project}/{sweep_id}")
runs = sorted(sweep.runs, key=lambda run: run.summary.get("val_accuracy", 0), reverse=True)
model_found = False
for run in runs:
ext_list = list(map(lambda x: x.name.split(".")[-1], list(run.files())))
if "png" and "h5" in ext_list:
val_acc = run.summary.get("val_accuracy")
print(f"Best run {run.name} with {val_acc}% validation accuracy")
for f in run.files():
file_name = os.path.basename(f.name)
# print(os.path.basename(f.name))
if file_name.endswith("png") and file_name.startswith("Classification"):
# Downloading Classification Report
run.file(file_name).download(replace=True)
print("Classification report donwloaded!")
# Downloading model
run.file("model.h5").download(replace=True)
print("Best model saved to model-best.h5")
model_found = True
break
if not model_found:
print("No model found in wandb sweep, downloading fallback model!")
os.system("wget -O model.h5 https://www.dropbox.com/s/urflwaj6fllr13d/model-best-efficientnet-val-acc-0.74.h5")
def preprocess_image(file, image_size):
"""Decode and resize image.
Parameters
----------
file : _type_
_description_
image_size : _type_
_description_
Returns
-------
_type_
_description_
"""
f = BytesIO(file.download_as_bytearray())
file_bytes = np.asarray(bytearray(f.read()), dtype=np.uint8)
img = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
img = cv2.resize(img, image_size, interpolation=cv2.INTER_AREA)
return img
def load_model():
file_name = "model.h5"
model = models.load_model(file_name)
optimizer = optimizers.Adam()
f1_score = tfa.metrics.F1Score(num_classes=num_classes, average="macro", threshold=0.5)
model.compile(
optimizer=optimizer,
loss="categorical_crossentropy",
metrics=["accuracy", f1_score],
)
print("Model loaded!")
return model
def get_prediction(file):
"""Get prediction for image.
Parameters
----------
file : File
Image file
Returns
-------
str
Prediction with class name and confidence %.
"""
model = load_model()
img = preprocess_image(file, image_size=(cfg.image_size, cfg.image_size))
prediction = model.predict(np.array([img / 255]), batch_size=1)
assert prediction > 0
return (
f"In this image I see {class_names[np.argmax(prediction)]} (with {(max(prediction[0]))*100:.3f}% confidence!)"
)
def main():
# normalization_layer = layers.Rescaling(1.0 / 255)
initialize(config_path="../configs/", version_base="1.2")
cfg = compose(config_name="config")
batch_size = cfg.batch_size
class_names = [
"Basalt",
"Coal",
"Granite",
"Limestone",
"Marble",
"Quartzite",
"Sandstone",
]
num_classes = len(class_names)
get_run_data()
# %% ../../notebooks/03_e_predict.ipynb 3
#| eval: false
if __name__ == "__main__":
main() | /rocks_classifier-0.1.2.tar.gz/rocks_classifier-0.1.2/rocks_classifier/models/predict.py | 0.635901 | 0.278006 | predict.py | pypi |
# %% auto 0
__all__ = ['get_optimizer', 'get_model_weights', 'get_lr_scheduler']
# %% ../../notebooks/03_a_train_utils.ipynb 2
import numpy as np
import tensorflow as tf
from sklearn.utils import class_weight
from tensorflow.keras import optimizers
# %% ../../notebooks/03_a_train_utils.ipynb 3
def get_optimizer(cfg, lr: str) -> optimizers:
"""Get optimizer set with an learning rate.
Parameters
----------
cfg : cfg (omegaconf.DictConfig):
Hydra Configuration
lr : str
learning rate
Returns
-------
tensorflow.keras.optimizers
Tensorflow optimizer
Raises
------
NotImplementedError
Raise error if cfg.optimizer not implemented.
"""
optimizer_dict = {
"adam": optimizers.Adam,
"rms": optimizers.RMSprop,
"sgd": optimizers.SGD,
"adamax": optimizers.Adamax,
}
try:
opt = optimizer_dict[cfg.optimizer](learning_rate=lr)
except NotImplementedError:
raise NotImplementedError("Not implemented.")
return opt
def get_model_weights(train_ds: tf.data.Dataset):
"""Return model weights dict.
Parameters
----------
train_ds : tf.data.Dataset
Tensorflow Dataset.
Returns
-------
dict
Dictionary of class weights.
"""
class_weights = class_weight.compute_class_weight(
class_weight="balanced",
classes=np.unique(train_ds.class_names),
y=train_ds.class_names,
)
train_class_weights = dict(enumerate(class_weights))
return train_class_weights
def get_lr_scheduler(cfg, lr) -> optimizers.schedules:
"""Return A LearningRateSchedule.
Supports [cosine_decay](https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/schedules/CosineDecay), [exponentialdecay](https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/schedules/ExponentialDecay) and [cosine_decay_restarts](https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/schedules/CosineDecayRestarts).
Parameters
----------
cfg : cfg (omegaconf.DictConfig):
Hydra Configuration
lr : str
learning rate
Returns
-------
tensorflow.keras.optimizers.schedules
A LearningRateSchedule
"""
scheduler = {
"cosine_decay": optimizers.schedules.CosineDecay(
lr, decay_steps=cfg.lr_decay_steps
),
"exponentialdecay": optimizers.schedules.ExponentialDecay(
lr,
decay_steps=cfg.lr_decay_steps,
decay_rate=cfg.reduce_lr.factor,
staircase=True,
),
"cosine_decay_restarts": optimizers.schedules.CosineDecayRestarts(
lr, first_decay_steps=cfg.lr_decay_steps
),
}
return scheduler[cfg.lr_schedule] | /rocks_classifier-0.1.2.tar.gz/rocks_classifier-0.1.2/rocks_classifier/models/utils.py | 0.910545 | 0.42313 | utils.py | pypi |
# %% auto 0
__all__ = ['get_backbone', 'get_model']
# %% ../../notebooks/03_b_train_models.ipynb 2
import tensorflow as tf
from tensorflow.keras import applications, layers
# %% ../../notebooks/03_b_train_models.ipynb 3
def get_backbone(cfg) -> tf.keras.models:
"""Get backbone for the model.
List of [supported models](https://www.tensorflow.org/api_docs/python/tf/keras/applications).
Parameters
----------
cfg : cfg (omegaconf.DictConfig):
Hydra Configuration
Returns
-------
tensorflow.keras.model
Tensroflow Model
Raises
------
NotImplementedError
raise error if wrong backbone name passed
"""
weights = None
models_dict = {
# "convnexttiny":applications.ConvNeXtTiny,
"vgg16": applications.VGG16,
"resnet": applications.ResNet50,
"inceptionresnetv2": applications.InceptionResNetV2,
"mobilenetv2": applications.MobileNetV2,
"efficientnetv2": applications.EfficientNetV2B0,
"efficientnetv2m": applications.EfficientNetV2M,
"xception": applications.Xception,
}
if cfg.use_pretrained_weights:
weights = "imagenet"
try:
base_model = models_dict[cfg.backbone](
include_top=False,
weights=weights,
input_shape=(cfg.image_size, cfg.image_size, cfg.image_channels),
)
except NotImplementedError:
raise NotImplementedError("Not implemented for this backbone.")
base_model.trainable = cfg.trainable
return base_model
def get_model(cfg):
"""Get an image classifier with a CNN based backbone.
Calls `get_backbone` and adds a top_model layer to it.
Parameters
----------
cfg : cfg (omegaconf.DictConfig)
Hydra Configuration
Returns
-------
tensorflow.keras.Model
Model object
"""
# Backbone
base_model = get_backbone(cfg)
model = tf.keras.Sequential(
[
base_model,
layers.GlobalAveragePooling2D(),
layers.Dense(1024, activation="relu"),
layers.Dropout(cfg.dropout_rate),
layers.Dense(256, activation="relu"),
layers.Dropout(cfg.dropout_rate),
layers.Dense(64, activation="relu"),
layers.Dropout(cfg.dropout_rate),
layers.Dense(cfg.num_classes, activation="softmax"),
]
)
return model | /rocks_classifier-0.1.2.tar.gz/rocks_classifier-0.1.2/rocks_classifier/models/models.py | 0.864554 | 0.344802 | models.py | pypi |
# %% auto 0
__all__ = ['plotly_confusion_matrix', 'get_classification_report', 'get_confusion_matrix']
# %% ../../notebooks/04_visualization.ipynb 1
import plotly.figure_factory as ff
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.metrics import classification_report, confusion_matrix, ConfusionMatrixDisplay
# %% ../../notebooks/04_visualization.ipynb 2
def plotly_confusion_matrix(labels, y, _y):
l = [0 for _ in range(len(labels))]
z = [[0 for _ in range(len(labels))] for _ in range(len(labels))]
h = [[0 for _ in range(len(labels))] for _ in range(len(labels))]
for i, j in zip(y, _y):
z[j][i] += 1
l[i] += 1
x = labels.copy()
y = labels.copy()
z_labels = [[str(col) if col != 0 else "" for col in row] for row in z]
for i in range(len(labels)):
for j in range(len(labels)):
if i == j:
h[i][j] = (
"Correctly predicted "
+ str(z[i][j])
+ " out of "
+ str(l[i])
+ " "
+ labels[i]
+ " with accuracy "
+ str(z[i][j] / l[i])
)
else:
if z[j][i] == 0:
h[j][i] = ""
else:
h[j][i] = (
"Incorrectly predicted "
+ str(z[j][i])
+ " out of "
+ str(l[i])
+ " "
+ labels[i]
+ " as "
+ labels[j]
)
fig = ff.create_annotated_heatmap(
z,
x=x,
y=y,
text=h,
annotation_text=z_labels,
hoverinfo="text",
colorscale="Blues",
)
fig.update_layout(width=850, height=550)
fig.update_layout(margin=dict(t=100, l=200))
fig.add_annotation(
dict(
font=dict(color="#094973", size=16),
x=0.5,
y=-0.10,
showarrow=False,
text="True Class",
xref="paper",
yref="paper",
)
)
fig.add_annotation(
dict(
font=dict(color="#094973", size=16),
x=-0.17,
y=0.5,
showarrow=False,
text="Predicted Class",
textangle=-90,
xref="paper",
yref="paper",
)
)
fig.show()
return fig
# %% ../../notebooks/04_visualization.ipynb 3
def get_classification_report(true_categories, predicted_categories, labels):
"""Print Classification Report, and return formatted report to log to wandb
Parameters
----------
true_categories : List
actuual categories
predicted_categories : List
predicted categories
labels : List
labels
Returns
-------
dict
Classification report dict
"""
# Classification Report
print(classification_report(
true_categories,
predicted_categories,
labels=[i for i in range(7)], # TODO: Convert to class, and add num_classes instead of 7 from cfg
target_names=labels,
output_dict=False,
))
cl_report = classification_report(
true_categories,
predicted_categories,
labels=[i for i in range(7)], # TODO: Convert to class, and add num_classes instead of 7 from cfg
target_names=labels,
output_dict=True,
)
cr = sns.heatmap(pd.DataFrame(cl_report).iloc[:-1, :].T, annot=True)
plt.savefig("classification_report.png", dpi=400)
return cr
# %% ../../notebooks/04_visualization.ipynb 4
def get_confusion_matrix(true_categories, predicted_categories, labels):
"""Create, plot and save confusion matrix.
Parameters
----------
true_categories : List
Actual categories
predicted_categories : List
Predicted categories
labels : List
labels
Returns
-------
array
Confusion matrix array
"""
# Create confusion matrix and normalizes it over predicted (columns)
result = confusion_matrix(true_categories, predicted_categories, normalize="pred")
disp = ConfusionMatrixDisplay(confusion_matrix=result, display_labels=labels)
disp.plot()
plt.xticks(rotation=35)
plt.savefig("confusion_matrix.png")
plt.close()
return result | /rocks_classifier-0.1.2.tar.gz/rocks_classifier-0.1.2/rocks_classifier/visualization/plot.py | 0.468061 | 0.437763 | plot.py | pypi |
import argparse
import os
import pathlib
import re
from itertools import accumulate
from typing import TypedDict
DIRNAME = pathlib.Path(__file__).parent
class StatType(TypedDict):
name: str
regex: str
class Statistics:
def __init__(self) -> None:
self.stats: dict[str, StatType] = {
"uptime": {
"name": "Uptime",
"regex": "Uptime\(secs\).*?(\d*\.\d*)\stotal",
},
"interval": {
"name": "Interval step",
"regex": "Uptime\(secs\).*?(\d*\.\d*)\sinterval",
},
"interval_stall": {
"name": "Interval Stall",
"regex": "Interval\sstall.*?(\d*\.\d*)\spercent",
},
"cumulative_stall": {
"name": "Cumulative Stall",
"regex": "Cumulative\sstall.*?(\d*\.\d*)\spercent",
},
"interval_writes": {
"name": "Interval Writes",
"regex": "Interval\swrites.*?(\d*\.\d*)\sMB\/s",
},
"cumulative_writes": {
"name": "Cumulative Writes",
"regex": "Cumulative\swrites.*?(\d*\.\d*)\sMB\/s",
},
"cumulative_compaction": {
"name": "Cumulative Compaction",
"regex": "Cumulative\scompaction.*?(\d*\.\d*)\sMB\/s",
},
"interval_compaction": {
"name": "Interval Compaction",
"regex": "Interval\scompaction.*?(\d*\.\d*)\sMB\/s",
},
}
self.legend_list: list[str] = []
self.plots: list[str] = []
self.base_filename = ""
def coordinates_filename(self) -> str:
return self.base_filename + "_coordinates.log"
def save_statistic(
self, key: str, d: StatType, log: str, steps: list[float] | None = None
) -> None:
matches = self.get_matches(d["regex"], log)
new_filename = self.base_filename + f"_{key}"
self.save_to_csv_file(matches, new_filename)
coordinates = self.generate_coordinates(matches, steps)
self.save_coordinates_to_file(coordinates, self.coordinates_filename())
self.legend_list.append(d["name"])
def clean_log(self, log: str) -> list[str]:
regex = re.compile("(2018\S+).*\(([\d,\.]*)\).*\(([\d,\.]*)\).*\(([\d,\.]*)\)")
path = os.path.join(os.getcwd(), "output", log)
with open(path, "r") as f:
matches = regex.findall(f.read())
return [",".join(match) for match in matches]
def get_matches(self, pattern: str, log: str) -> list[str]:
regex = re.compile(pattern)
path = os.path.join(os.getcwd(), log)
with open(path, "r") as f:
matches = regex.findall(f.read())
return matches
def generate_coordinates(
self, matches: list[str], steps: list[float] | None
) -> list[str]:
if not steps:
return [f"({i*1},{match})" for i, match in enumerate(matches)]
return [f"({key},{value})" for key, value in zip(steps, matches)]
def save_to_csv_file(self, data: list[str], filename: str) -> None:
os.makedirs("output", exist_ok=True)
file_path = f"output/{filename}.csv"
with open(file_path, "w") as f:
f.writelines(",".join(data))
print("Saved", filename, "to", file_path)
def save_coordinates_to_file(
self, data: list[str], filename: str, last: bool = False
) -> None:
str_data = "".join(data)
self.plots.append(f"\t\t\\addplot\n\tcoordinates {{ { str_data } }};\n")
def save_coordinate_file(self, filename: str) -> None:
os.makedirs("output", exist_ok=True)
axis = f"""
\\begin{{tikzpicture}}
\\begin{{axis}}[
title={self.base_filename.replace("_", " ")},
xlabel={{}},
ylabel={{MB/s}},
legend style={{
at={{(0.5,-0.2)}},
anchor=north,legend columns=1
}},
ymajorgrids=true,
grid style=dashed,
]
"""
with open(f"output/{filename}", "w") as f:
f.write(axis)
for plot in self.plots:
f.write(plot)
legend = ", ".join(self.legend_list)
f.write(
f"""
\\legend{{{legend}}}
\\end{{axis}}
\\end{{tikzpicture}}
"""
)
def get_steps(self, pattern: str, log: str) -> list[float]:
interval_steps = self.get_matches(pattern, log)[::2]
accumulated_steps = list(accumulate([float(step) for step in interval_steps]))
rounded_steps = [round(step, 2) for step in accumulated_steps]
return rounded_steps
def save_all(self, log: str, statistics: set[str]) -> None:
logfile = pathlib.Path(log)
self.base_filename = logfile.stem
interval_steps = self.get_steps(self.stats["interval"]["regex"], log)
uptime_steps = [
float(step)
for step in self.get_matches(self.stats["uptime"]["regex"], log)[::2]
]
min_interval_step = uptime_steps[0] - interval_steps[0]
steps = [round(step - min_interval_step, 2) for step in uptime_steps]
for key, value in self.stats.items():
if len(statistics) > 0 and key not in statistics:
continue
self.save_statistic(key, value, log, steps)
self.save_coordinate_file(self.coordinates_filename())
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("log", type=str, help="logfile")
parser.add_argument("--statistics", type=str, help="logfile")
args = parser.parse_args()
s = Statistics()
statistics = (
{arg.strip() for arg in args.statistics.split(",")}
if args.statistics
else set()
)
if len(statistics) > 0 and not statistics.intersection(s.stats.keys()):
raise KeyError(
f"Statistic not supported, must use one or more of \"{','.join(s.stats.keys())}\""
)
s.save_all(args.log, statistics) | /rocksdb-statistics-0.0.10.tar.gz/rocksdb-statistics-0.0.10/rocksdb_statistics/rocksdb_statistics.py | 0.633977 | 0.346403 | rocksdb_statistics.py | pypi |
import rockset
from sqlalchemy import types
class BaseType:
__visit_name__ = None
def __str__(self):
return self.__visit_name__
class NullType(BaseType, types.NullType):
__visit_name__ = rockset.document.DATATYPE_NULL
hashable = True
class Int(BaseType, types.BigInteger):
__visit_name__ = rockset.document.DATATYPE_INT
class Float(BaseType, types.Float):
__visit_name__ = rockset.document.DATATYPE_FLOAT
class Bool(BaseType, types.Boolean):
__visit_name__ = rockset.document.DATATYPE_BOOL
class String(BaseType, types.String):
__visit_name__ = rockset.document.DATATYPE_STRING
class Bytes(BaseType, types.LargeBinary):
__visit_name__ = rockset.document.DATATYPE_BYTES
class Array(NullType):
__visit_name__ = rockset.document.DATATYPE_ARRAY
class Object(NullType):
__visit_name__ = rockset.document.DATATYPE_OBJECT
class Date(BaseType, types.DATE):
__visit_name__ = rockset.document.DATATYPE_DATE
class DateTime(BaseType, types.DATETIME):
__visit_name__ = rockset.document.DATATYPE_DATETIME
class Time(BaseType, types.TIME):
__visit_name__ = rockset.document.DATATYPE_TIME
class Timestamp(BaseType, types.String):
__visit_name__ = rockset.document.DATATYPE_TIMESTAMP
class MicrosecondInterval(BaseType, types.Interval):
__visit_name__ = rockset.document.DATATYPE_MICROSECOND_INTERVAL
def bind_processor(self, dialect):
def process(value):
return value
return process
def result_processor(self, dialect, coltype):
def process(value):
return value
return process
class MonthInterval(Object):
__visit_name__ = rockset.document.DATATYPE_MONTH_INTERVAL
class Geography(Object):
__visit_name__ = rockset.document.DATATYPE_GEOGRAPHY
type_map = {
"null": NullType,
"int": Int,
"float": Float,
"bool": Bool,
"string": String,
"bytes": Bytes,
"object": Object,
"array": Array,
"date": Date,
"datetime": DateTime,
"time": Time,
"timestamp": Timestamp,
"microsecond_interval": MicrosecondInterval,
"month_interval": MonthInterval,
"geography": Geography,
} | /rockset_sqlalchemy-0.0.1-py3-none-any.whl/rockset_sqlalchemy/sqlalchemy/types.py | 0.605682 | 0.196575 | types.py | pypi |
import sys
import traceback
import json
import unittest
from setuptools import setup
from setuptools import find_packages
import setup_tests
def get_version():
version = {}
with open("rockset/version.json", "r") as vf:
version = json.load(vf)
return version
def get_long_description():
with open("DESCRIPTION.rst", encoding="utf-8") as fd:
long_description = fd.read()
long_description += "\n"
with open("RELEASE.rst", encoding="utf-8") as fd:
long_description += fd.read()
return long_description
setup(
name="rockset",
version=get_version().get("python", "???"),
description="Rockset Python Client and `rock` CLI",
long_description=get_long_description(),
author="Rockset, Inc",
author_email="api@rockset.io",
url="https://rockset.com",
keywords="Rockset serverless search and analytics",
packages=find_packages(
include=[
"rockset",
"rockset.*",
],
exclude=[
"rockset.internal",
"rockset.internal.*",
"rockset.rock.tests",
"rockset.tests",
"rockset.sql.tests",
],
),
install_requires=[
"docopt >= 0.6.2",
"geojson >= 2.5.0",
"protobuf >= 3.6.0",
"pyyaml >= 5.1.2",
"requests >= 2.19.0",
"requests-toolbelt >= 0.9.1",
"sqlalchemy >= 1.3.10",
"texttable >= 0.8.7",
],
entry_points={
"console_scripts": [
"rock = rockset.rock.main:main",
],
# New versions
"sqlalchemy.dialects": [
"rockset= rockset.sql:RocksetDialect",
],
# Version 0.5
"sqlalchemy.databases": [
"rockset= rockset.sql:RocksetDialect",
],
},
classifiers=[
"License :: OSI Approved :: BSD License",
"Development Status :: 4 - Beta",
"Environment :: Console",
"Environment :: Other Environment",
"Intended Audience :: Developers",
"Intended Audience :: Information Technology",
"Intended Audience :: Science/Research",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: SQL",
"Topic :: Database",
"Topic :: Database :: Database Engines/Servers",
"Topic :: Scientific/Engineering :: Information Analysis",
"Topic :: Software Development",
"Topic :: Software Development :: Libraries",
"Topic :: Software Development :: Libraries :: Application Frameworks",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: System :: Shells",
"Topic :: Internet :: WWW/HTTP :: Indexing/Search",
],
package_data={
"rockset": [
"swagger/apiserver.yaml",
"version.json",
],
},
test_suite="setup_tests.my_test_suite",
) | /rockset_sqlcli-0.8.10.tar.gz/rockset_sqlcli-0.8.10/setup_rockset.py | 0.424054 | 0.205256 | setup_rockset.py | pypi |
import logging
from rockset import Q, F
import rockset.sql as rs
import sqlparse
from .packages.parseutils.meta import FunctionMetadata, ForeignKey
from .encodingutils import unicode2utf8, PY2, utf8tounicode
_logger = logging.getLogger(__name__)
class RSExecute(object):
def __init__(self, api_server, api_key, workspace, **kwargs):
self.api_server = api_server
self.api_key = api_key
self.workspace = workspace
self.account = None
self.username = None
self.superuser = False
self.generate_warnings = kwargs.get("generate_warnings", False)
self.connect()
def connect(self, api_server=None, api_key=None, workspace=None, **kwargs):
api_server = api_server or self.api_server
api_key = api_key or self.api_key
workspace = workspace or self.workspace
generate_warnings = self.generate_warnings or kwargs.get(
"generate_warnings", False
)
conn = rs.connect(
api_server=api_server, api_key=api_key, workspace=workspace, **kwargs
)
self.account = "" # TODO: set this from conn object, post auth
self.username = "" # TODO: set this from conn object, post auth
self.superuser = True # TODO: set this from conn object, post auth
cursor = conn.cursor()
if hasattr(self, "conn"):
self.conn.close()
self.conn = conn
self.conn.autocommit = True
def _select_one(self, cur, sql):
"""
Helper method to run a select and retrieve a single field value
:param cur: cursor
:param sql: string
:return: string
"""
cur.execute(sql, generate_warnings=self.generate_warnings)
return cur.fetchone()
def failed_transaction(self):
return False
def valid_transaction(self):
return False
def run(self, statement, exception_formatter=None, on_error_resume=False):
"""Execute the sql in the database and return the results.
:param statement: A string containing one or more sql statements
:param exception_formatter: A callable that accepts an Exception and
returns a formatted (title, rows, headers, status) tuple that can
act as a query result.
:param on_error_resume: Bool. If true, queries following an exception
(assuming exception_formatter has been supplied) continue to
execute.
:return: Generator yielding tuples containing
(title, rows, headers, status, query, success)
"""
# Remove spaces and EOL
statement = statement.strip()
if not statement: # Empty string
yield (None, None, None, None, statement, False)
# Split the sql into separate queries and run each one.
for sql in sqlparse.split(statement):
# Remove spaces, eol and semi-colons.
sql = sql.rstrip(";")
try:
yield self.execute_normal_sql(sql) + (sql, True)
except rs.exception.DatabaseError as e:
_logger.debug("sql: %r, error: %r", sql, e)
if self._must_raise(e) or not exception_formatter:
raise
yield None, None, None, exception_formatter(e), sql, False
if not on_error_resume:
break
def _must_raise(self, e):
"""Return true if e is an error that should not be caught in ``run``.
``OperationalError``s are raised for errors that are not under the
control of the programmer. Usually that means unexpected disconnects,
which we shouldn't catch; we handle uncaught errors by prompting the
user to reconnect. We *do* want to catch OperationalErrors caused by a
lock being unavailable, as reconnecting won't solve that problem.
:param e: DatabaseError. An exception raised while executing a query.
:return: Bool. True if ``run`` must raise this exception.
"""
return isinstance(e, rs.exception.OperationalError)
def execute_normal_sql(self, split_sql):
"""Returns tuple (title, rows, headers, status)"""
_logger.debug("Regular sql statement. sql: %r", split_sql)
cur = self.conn.cursor()
cur.execute(split_sql, generate_warnings=self.generate_warnings)
title = ""
# cur.description will be None for operations that do not return
# rows.
if cur.description:
headers = [x[0] for x in cur.description]
return title, cur, headers, ""
else:
_logger.debug("No rows in result.")
return title, None, None, ""
def search_path(self):
"""Returns the current search path as a list of schema names"""
return self.schemata()
def schemata(self):
"""Returns a list of schema names in the database"""
return ["commons"]
def _relations(self):
"""Get table or view name metadata
:return: (schema_name, rel_name) tuples
"""
try:
for resource in self.conn._client.list():
for workspace in self.schemata():
yield (workspace, resource.name)
except:
return []
def tables(self):
"""Yields (schema_name, table_name) tuples"""
for row in self._relations():
yield row
def views(self):
"""Yields (schema_name, view_name) tuples."""
return []
def _columns(self):
"""Get column metadata for tables and views
:return: list of (schema_name, relation_name, column_name, column_type) tuples
"""
try:
for (workspace, collection) in self._relations():
sql = Q('describe "{}"'.format(collection))
desc = self.conn._client.sql(sql)
for d in desc:
f = F
for dp in d["path"]:
f = f[dp]
yield (
workspace,
collection,
f.sqlexpression(),
d["type"],
False,
None,
)
except:
return []
def table_columns(self):
return []
def view_columns(self):
return []
def databases(self):
return ["rockset"]
def foreignkeys(self):
return []
def functions(self):
return []
def datatypes(self):
dtypes = ["int", "float", "bool", "string", "array", "document"]
for workspace in self.schemata():
for dt in dtypes:
yield (workspace, dt)
def casing(self):
"""Yields the most common casing for names used in db functions"""
return | /rockset_sqlcli-0.8.10.tar.gz/rockset_sqlcli-0.8.10/rockset_sqlcli/rscli/rsexecute.py | 0.447943 | 0.164651 | rsexecute.py | pypi |
from __future__ import print_function
import sys
import re
import sqlparse
from collections import namedtuple
from sqlparse.sql import Comparison, Identifier, Where
from .parseutils.utils import last_word, find_prev_keyword, parse_partial_identifier
from .parseutils.tables import extract_tables
from .parseutils.ctes import isolate_query_ctes
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str
else:
string_types = basestring
Database = namedtuple("Database", [])
Schema = namedtuple("Schema", ["quoted"])
Schema.__new__.__defaults__ = (False,)
# FromClauseItem is a table/view/function used in the FROM clause
# `table_refs` contains the list of tables/... already in the statement,
# used to ensure that the alias we suggest is unique
FromClauseItem = namedtuple("FromClauseItem", "schema table_refs local_tables")
Table = namedtuple("Table", ["schema", "table_refs", "local_tables"])
View = namedtuple("View", ["schema", "table_refs"])
# JoinConditions are suggested after ON, e.g. 'foo.barid = bar.barid'
JoinCondition = namedtuple("JoinCondition", ["table_refs", "parent"])
# Joins are suggested after JOIN, e.g. 'foo ON foo.barid = bar.barid'
Join = namedtuple("Join", ["table_refs", "schema"])
Function = namedtuple("Function", ["schema", "table_refs", "usage"])
# For convenience, don't require the `usage` argument in Function constructor
Function.__new__.__defaults__ = (None, tuple(), None)
Table.__new__.__defaults__ = (None, tuple(), tuple())
View.__new__.__defaults__ = (None, tuple())
FromClauseItem.__new__.__defaults__ = (None, tuple(), tuple())
Column = namedtuple(
"Column",
["table_refs", "require_last_table", "local_tables", "qualifiable", "context"],
)
Column.__new__.__defaults__ = (None, None, tuple(), False, None)
Keyword = namedtuple("Keyword", ["last_token"])
Keyword.__new__.__defaults__ = (None,)
NamedQuery = namedtuple("NamedQuery", [])
Datatype = namedtuple("Datatype", ["schema"])
Alias = namedtuple("Alias", ["aliases"])
Path = namedtuple("Path", [])
class SqlStatement(object):
def __init__(self, full_text, text_before_cursor):
self.identifier = None
self.word_before_cursor = word_before_cursor = last_word(
text_before_cursor, include="many_punctuations"
)
full_text = _strip_named_query(full_text)
text_before_cursor = _strip_named_query(text_before_cursor)
full_text, text_before_cursor, self.local_tables = isolate_query_ctes(
full_text, text_before_cursor
)
self.text_before_cursor_including_last_word = text_before_cursor
# If we've partially typed a word then word_before_cursor won't be an
# empty string. In that case we want to remove the partially typed
# string before sending it to the sqlparser. Otherwise the last token
# will always be the partially typed string which renders the smart
# completion useless because it will always return the list of
# keywords as completion.
if self.word_before_cursor:
if word_before_cursor[-1] == "(" or word_before_cursor[0] == "\\":
parsed = sqlparse.parse(text_before_cursor)
else:
text_before_cursor = text_before_cursor[: -len(word_before_cursor)]
parsed = sqlparse.parse(text_before_cursor)
self.identifier = parse_partial_identifier(word_before_cursor)
else:
parsed = sqlparse.parse(text_before_cursor)
full_text, text_before_cursor, parsed = _split_multiple_statements(
full_text, text_before_cursor, parsed
)
self.full_text = full_text
self.text_before_cursor = text_before_cursor
self.parsed = parsed
self.last_token = parsed and parsed.token_prev(len(parsed.tokens))[1] or ""
def is_insert(self):
return self.parsed.token_first().value.lower() == "insert"
def get_tables(self, scope="full"):
"""Gets the tables available in the statement.
param `scope:` possible values: 'full', 'insert', 'before'
If 'insert', only the first table is returned.
If 'before', only tables before the cursor are returned.
If not 'insert' and the stmt is an insert, the first table is skipped.
"""
tables = extract_tables(
self.full_text if scope == "full" else self.text_before_cursor
)
if scope == "insert":
tables = tables[:1]
elif self.is_insert():
tables = tables[1:]
return tables
def get_previous_token(self, token):
return self.parsed.token_prev(self.parsed.token_index(token))[1]
def get_identifier_schema(self):
schema = (self.identifier and self.identifier.get_parent_name()) or None
# If schema name is unquoted, lower-case it
if schema and self.identifier.value[0] != '"':
schema = schema.lower()
return schema
def reduce_to_prev_keyword(self, n_skip=0):
prev_keyword, self.text_before_cursor = find_prev_keyword(
self.text_before_cursor, n_skip=n_skip
)
return prev_keyword
def suggest_type(full_text, text_before_cursor):
"""Takes the full_text that is typed so far and also the text before the
cursor to suggest completion type and scope.
Returns a tuple with a type of entity ('table', 'column' etc) and a scope.
A scope for a column category will be a list of tables.
"""
if full_text.startswith("\\i "):
return (Path(),)
# This is a temporary hack; the exception handling
# here should be removed once sqlparse has been fixed
try:
stmt = SqlStatement(full_text, text_before_cursor)
except (TypeError, AttributeError):
return []
return suggest_based_on_last_token(stmt.last_token, stmt)
named_query_regex = re.compile(r"^\s*\\ns\s+[A-z0-9\-_]+\s+")
def _strip_named_query(txt):
"""
This will strip "save named query" command in the beginning of the line:
'\ns zzz SELECT * FROM abc' -> 'SELECT * FROM abc'
' \ns zzz SELECT * FROM abc' -> 'SELECT * FROM abc'
"""
if named_query_regex.match(txt):
txt = named_query_regex.sub("", txt)
return txt
function_body_pattern = re.compile(r"(\$.*?\$)([\s\S]*?)\1", re.M)
def _find_function_body(text):
split = function_body_pattern.search(text)
return (split.start(2), split.end(2)) if split else (None, None)
def _statement_from_function(full_text, text_before_cursor, statement):
current_pos = len(text_before_cursor)
body_start, body_end = _find_function_body(full_text)
if body_start is None:
return full_text, text_before_cursor, statement
if not body_start <= current_pos < body_end:
return full_text, text_before_cursor, statement
full_text = full_text[body_start:body_end]
text_before_cursor = text_before_cursor[body_start:]
parsed = sqlparse.parse(text_before_cursor)
return _split_multiple_statements(full_text, text_before_cursor, parsed)
def _split_multiple_statements(full_text, text_before_cursor, parsed):
if len(parsed) > 1:
# Multiple statements being edited -- isolate the current one by
# cumulatively summing statement lengths to find the one that bounds
# the current position
current_pos = len(text_before_cursor)
stmt_start, stmt_end = 0, 0
for statement in parsed:
stmt_len = len(str(statement))
stmt_start, stmt_end = stmt_end, stmt_end + stmt_len
if stmt_end >= current_pos:
text_before_cursor = full_text[stmt_start:current_pos]
full_text = full_text[stmt_start:]
break
elif parsed:
# A single statement
statement = parsed[0]
else:
# The empty string
return full_text, text_before_cursor, None
token2 = None
if statement.get_type() in ("CREATE", "CREATE OR REPLACE"):
token1 = statement.token_first()
if token1:
token1_idx = statement.token_index(token1)
token2 = statement.token_next(token1_idx)[1]
if token2 and token2.value.upper() == "FUNCTION":
full_text, text_before_cursor, statement = _statement_from_function(
full_text, text_before_cursor, statement
)
return full_text, text_before_cursor, statement
SPECIALS_SUGGESTION = {
"dT": Datatype,
"df": Function,
"dt": Table,
"dv": View,
"sf": Function,
}
def suggest_based_on_last_token(token, stmt):
if isinstance(token, string_types):
token_v = token.lower()
elif isinstance(token, Comparison):
# If 'token' is a Comparison type such as
# 'select * FROM abc a JOIN def d ON a.id = d.'. Then calling
# token.value on the comparison type will only return the lhs of the
# comparison. In this case a.id. So we need to do token.tokens to get
# both sides of the comparison and pick the last token out of that
# list.
token_v = token.tokens[-1].value.lower()
elif isinstance(token, Where):
# sqlparse groups all tokens from the where clause into a single token
# list. This means that token.value may be something like
# 'where foo > 5 and '. We need to look "inside" token.tokens to handle
# suggestions in complicated where clauses correctly
prev_keyword = stmt.reduce_to_prev_keyword()
return suggest_based_on_last_token(prev_keyword, stmt)
elif isinstance(token, Identifier):
# If the previous token is an identifier, we can suggest datatypes if
# we're in a parenthesized column/field list, e.g.:
# CREATE TABLE foo (Identifier <CURSOR>
# CREATE FUNCTION foo (Identifier <CURSOR>
# If we're not in a parenthesized list, the most likely scenario is the
# user is about to specify an alias, e.g.:
# SELECT Identifier <CURSOR>
# SELECT foo FROM Identifier <CURSOR>
prev_keyword, _ = find_prev_keyword(stmt.text_before_cursor)
if prev_keyword and prev_keyword.value == "(":
# Suggest datatypes
return suggest_based_on_last_token("type", stmt)
else:
return (Keyword(),)
else:
token_v = token.value.lower()
if not token:
return (Keyword(),)
elif token_v.endswith("("):
p = sqlparse.parse(stmt.text_before_cursor)[0]
if p.tokens and isinstance(p.tokens[-1], Where):
# Four possibilities:
# 1 - Parenthesized clause like "WHERE foo AND ("
# Suggest columns/functions
# 2 - Function call like "WHERE foo("
# Suggest columns/functions
# 3 - Subquery expression like "WHERE EXISTS ("
# Suggest keywords, in order to do a subquery
# 4 - Subquery OR array comparison like "WHERE foo = ANY("
# Suggest columns/functions AND keywords. (If we wanted to be
# really fancy, we could suggest only array-typed columns)
column_suggestions = suggest_based_on_last_token("where", stmt)
# Check for a subquery expression (cases 3 & 4)
where = p.tokens[-1]
prev_tok = where.token_prev(len(where.tokens) - 1)[1]
if isinstance(prev_tok, Comparison):
# e.g. "SELECT foo FROM bar WHERE foo = ANY("
prev_tok = prev_tok.tokens[-1]
prev_tok = prev_tok.value.lower()
if prev_tok == "exists":
return (Keyword(),)
else:
return column_suggestions
# Get the token before the parens
prev_tok = p.token_prev(len(p.tokens) - 1)[1]
if (
prev_tok
and prev_tok.value
and prev_tok.value.lower().split(" ")[-1] == "using"
):
# tbl1 INNER JOIN tbl2 USING (col1, col2)
tables = stmt.get_tables("before")
# suggest columns that are present in more than one table
return (
Column(
table_refs=tables,
require_last_table=True,
local_tables=stmt.local_tables,
),
)
elif p.token_first().value.lower() == "select":
# If the lparen is preceeded by a space chances are we're about to
# do a sub-select.
if last_word(stmt.text_before_cursor, "all_punctuations").startswith("("):
return (Keyword(),)
prev_prev_tok = prev_tok and p.token_prev(p.token_index(prev_tok))[1]
if prev_prev_tok and prev_prev_tok.normalized == "INTO":
return (Column(table_refs=stmt.get_tables("insert"), context="insert"),)
# We're probably in a function argument list
return (
Column(
table_refs=extract_tables(stmt.full_text),
local_tables=stmt.local_tables,
qualifiable=True,
),
)
elif token_v == "set":
return (Column(table_refs=stmt.get_tables(), local_tables=stmt.local_tables),)
elif token_v in ("select", "where", "having", "by", "distinct"):
# Check for a table alias or schema qualification
parent = (stmt.identifier and stmt.identifier.get_parent_name()) or []
tables = stmt.get_tables()
if parent:
tables = tuple(t for t in tables if identifies(parent, t))
return (
Column(table_refs=tables, local_tables=stmt.local_tables),
Table(schema=parent),
View(schema=parent),
Function(schema=parent),
)
else:
return (
Column(
table_refs=tables, local_tables=stmt.local_tables, qualifiable=True
),
Function(schema=None),
Keyword(token_v.upper()),
)
elif token_v == "as":
# Don't suggest anything for aliases
return ()
elif (token_v.endswith("join") and token.is_keyword) or (
token_v in ("copy", "from", "update", "into", "describe", "truncate")
):
schema = stmt.get_identifier_schema()
tables = extract_tables(stmt.text_before_cursor)
is_join = token_v.endswith("join") and token.is_keyword
# Suggest tables from either the currently-selected schema or the
# public schema if no schema has been specified
suggest = []
if not schema:
# Suggest schemas
suggest.insert(0, Schema())
if token_v == "from" or is_join:
suggest.append(
FromClauseItem(
schema=schema, table_refs=tables, local_tables=stmt.local_tables
)
)
elif token_v == "truncate":
suggest.append(Table(schema))
else:
suggest.extend((Table(schema), View(schema)))
if is_join and _allow_join(stmt.parsed):
tables = stmt.get_tables("before")
suggest.append(Join(table_refs=tables, schema=schema))
return tuple(suggest)
elif token_v == "function":
schema = stmt.get_identifier_schema()
# stmt.get_previous_token will fail for e.g. `SELECT 1 FROM functions WHERE function:`
try:
prev = stmt.get_previous_token(token).value.lower()
if prev in ("drop", "alter", "create", "create or replace"):
return (Function(schema=schema, usage="signature"),)
except ValueError:
pass
return tuple()
elif token_v in ("table", "view"):
# E.g. 'ALTER TABLE <tablname>'
rel_type = {"table": Table, "view": View, "function": Function}[token_v]
schema = stmt.get_identifier_schema()
if schema:
return (rel_type(schema=schema),)
else:
return (Schema(), rel_type(schema=schema))
elif token_v == "column":
# E.g. 'ALTER TABLE foo ALTER COLUMN bar
return (Column(table_refs=stmt.get_tables()),)
elif token_v == "on":
tables = stmt.get_tables("before")
parent = (stmt.identifier and stmt.identifier.get_parent_name()) or None
if parent:
# "ON parent.<suggestion>"
# parent can be either a schema name or table alias
filteredtables = tuple(t for t in tables if identifies(parent, t))
sugs = [
Column(table_refs=filteredtables, local_tables=stmt.local_tables),
Table(schema=parent),
View(schema=parent),
Function(schema=parent),
]
if filteredtables and _allow_join_condition(stmt.parsed):
sugs.append(JoinCondition(table_refs=tables, parent=filteredtables[-1]))
return tuple(sugs)
else:
# ON <suggestion>
# Use table alias if there is one, otherwise the table name
aliases = tuple(t.ref for t in tables)
if _allow_join_condition(stmt.parsed):
return (
Alias(aliases=aliases),
JoinCondition(table_refs=tables, parent=None),
)
else:
return (Alias(aliases=aliases),)
elif token_v in ("c", "use", "database", "template"):
# "\c <db", "use <db>", "DROP DATABASE <db>",
# "CREATE DATABASE <newdb> WITH TEMPLATE <db>"
return (Database(),)
elif token_v == "schema":
# DROP SCHEMA schema_name, SET SCHEMA schema name
prev_keyword = stmt.reduce_to_prev_keyword(n_skip=2)
quoted = prev_keyword and prev_keyword.value.lower() == "set"
return (Schema(quoted),)
elif token_v.endswith(",") or token_v in ("=", "and", "or"):
prev_keyword = stmt.reduce_to_prev_keyword()
if prev_keyword:
return suggest_based_on_last_token(prev_keyword, stmt)
else:
return ()
elif token_v in ("type", "::"):
# ALTER TABLE foo SET DATA TYPE bar
# SELECT foo::bar
# Note that tables are a form of composite type in postgresql, so
# they're suggested here as well
schema = stmt.get_identifier_schema()
suggestions = [Datatype(schema=schema), Table(schema=schema)]
if not schema:
suggestions.append(Schema())
return tuple(suggestions)
elif token_v in {"alter", "create", "drop"}:
return (Keyword(token_v.upper()),)
elif token.is_keyword:
# token is a keyword we haven't implemented any special handling for
# go backwards in the query until we find one we do recognize
prev_keyword = stmt.reduce_to_prev_keyword(n_skip=1)
if prev_keyword:
return suggest_based_on_last_token(prev_keyword, stmt)
else:
return (Keyword(token_v.upper()),)
else:
return (Keyword(),)
def identifies(id, ref):
"""Returns true if string `id` matches TableReference `ref`"""
return (
id == ref.alias
or id == ref.name
or (ref.schema and (id == ref.schema + "." + ref.name))
)
def _allow_join_condition(statement):
"""
Tests if a join condition should be suggested
We need this to avoid bad suggestions when entering e.g.
select * from tbl1 a join tbl2 b on a.id = <cursor>
So check that the preceding token is a ON, AND, or OR keyword, instead of
e.g. an equals sign.
:param statement: an sqlparse.sql.Statement
:return: boolean
"""
if not statement or not statement.tokens:
return False
last_tok = statement.token_prev(len(statement.tokens))[1]
return last_tok.value.lower() in ("on", "and", "or")
def _allow_join(statement):
"""
Tests if a join should be suggested
We need this to avoid bad suggestions when entering e.g.
select * from tbl1 a join tbl2 b <cursor>
So check that the preceding token is a JOIN keyword
:param statement: an sqlparse.sql.Statement
:return: boolean
"""
if not statement or not statement.tokens:
return False
last_tok = statement.token_prev(len(statement.tokens))[1]
return last_tok.value.lower().endswith("join") and last_tok.value.lower() not in (
"cross join",
"natural join",
) | /rockset_sqlcli-0.8.10.tar.gz/rockset_sqlcli-0.8.10/rockset_sqlcli/rscli/packages/sqlcompletion.py | 0.468304 | 0.214198 | sqlcompletion.py | pypi |
from __future__ import print_function
import sqlparse
from collections import namedtuple
from sqlparse.sql import IdentifierList, Identifier, Function
from sqlparse.tokens import Keyword, DML, Punctuation
TableReference = namedtuple(
"TableReference", ["schema", "name", "alias", "is_function"]
)
TableReference.ref = property(
lambda self: self.alias
or (
self.name
if self.name.islower() or self.name[0] == '"'
else '"' + self.name + '"'
)
)
# This code is borrowed from sqlparse example script.
# <url>
def is_subselect(parsed):
if not parsed.is_group:
return False
for item in parsed.tokens:
if item.ttype is DML and item.value.upper() in (
"SELECT",
"INSERT",
"UPDATE",
"CREATE",
"DELETE",
):
return True
return False
def _identifier_is_function(identifier):
return any(isinstance(t, Function) for t in identifier.tokens)
def extract_from_part(parsed, stop_at_punctuation=True):
tbl_prefix_seen = False
for item in parsed.tokens:
if tbl_prefix_seen:
if is_subselect(item):
for x in extract_from_part(item, stop_at_punctuation):
yield x
elif stop_at_punctuation and item.ttype is Punctuation:
raise StopIteration
# An incomplete nested select won't be recognized correctly as a
# sub-select. eg: 'SELECT * FROM (SELECT id FROM user'. This causes
# the second FROM to trigger this elif condition resulting in a
# StopIteration. So we need to ignore the keyword if the keyword
# FROM.
# Also 'SELECT * FROM abc JOIN def' will trigger this elif
# condition. So we need to ignore the keyword JOIN and its variants
# INNER JOIN, FULL OUTER JOIN, etc.
elif (
item.ttype is Keyword
and (not item.value.upper() == "FROM")
and (not item.value.upper().endswith("JOIN"))
):
tbl_prefix_seen = False
else:
yield item
elif item.ttype is Keyword or item.ttype is Keyword.DML:
item_val = item.value.upper()
if (
item_val
in (
"COPY",
"FROM",
"INTO",
"UPDATE",
"TABLE",
)
or item_val.endswith("JOIN")
):
tbl_prefix_seen = True
# 'SELECT a, FROM abc' will detect FROM as part of the column list.
# So this check here is necessary.
elif isinstance(item, IdentifierList):
for identifier in item.get_identifiers():
if identifier.ttype is Keyword and identifier.value.upper() == "FROM":
tbl_prefix_seen = True
break
def extract_table_identifiers(token_stream, allow_functions=True):
"""yields tuples of TableReference namedtuples"""
# We need to do some massaging of the names because postgres is case-
# insensitive and '"Foo"' is not the same table as 'Foo' (while 'foo' is)
def parse_identifier(item):
name = item.get_real_name()
schema_name = item.get_parent_name()
alias = item.get_alias()
if not name:
schema_name = None
name = item.get_name()
alias = alias or name
schema_quoted = schema_name and item.value[0] == '"'
if schema_name and not schema_quoted:
schema_name = schema_name.lower()
quote_count = item.value.count('"')
name_quoted = quote_count > 2 or (quote_count and not schema_quoted)
alias_quoted = alias and item.value[-1] == '"'
if alias_quoted or name_quoted and not alias and name.islower():
alias = '"' + (alias or name) + '"'
if name and not name_quoted and not name.islower():
if not alias:
alias = name
name = name.lower()
return schema_name, name, alias
for item in token_stream:
if isinstance(item, IdentifierList):
for identifier in item.get_identifiers():
# Sometimes Keywords (such as FROM ) are classified as
# identifiers which don't have the get_real_name() method.
try:
schema_name = identifier.get_parent_name()
real_name = identifier.get_real_name()
is_function = allow_functions and _identifier_is_function(
identifier
)
except AttributeError:
continue
if real_name:
yield TableReference(
schema_name, real_name, identifier.get_alias(), is_function
)
elif isinstance(item, Identifier):
schema_name, real_name, alias = parse_identifier(item)
is_function = allow_functions and _identifier_is_function(item)
yield TableReference(schema_name, real_name, alias, is_function)
elif isinstance(item, Function):
schema_name, real_name, alias = parse_identifier(item)
yield TableReference(None, real_name, alias, allow_functions)
# extract_tables is inspired from examples in the sqlparse lib.
def extract_tables(sql):
"""Extract the table names from an SQL statment.
Returns a list of TableReference namedtuples
"""
parsed = sqlparse.parse(sql)
if not parsed:
return ()
# INSERT statements must stop looking for tables at the sign of first
# Punctuation. eg: INSERT INTO abc (col1, col2) VALUES (1, 2)
# abc is the table name, but if we don't stop at the first lparen, then
# we'll identify abc, col1 and col2 as table names.
insert_stmt = parsed[0].token_first().value.lower() == "insert"
stream = extract_from_part(parsed[0], stop_at_punctuation=insert_stmt)
# Kludge: sqlparse mistakenly identifies insert statements as
# function calls due to the parenthesized column list, e.g. interprets
# "insert into foo (bar, baz)" as a function call to foo with arguments
# (bar, baz). So don't allow any identifiers in insert statements
# to have is_function=True
identifiers = extract_table_identifiers(stream, allow_functions=not insert_stmt)
# In the case 'sche.<cursor>', we get an empty TableReference; remove that
return tuple(i for i in identifiers if i.name) | /rockset_sqlcli-0.8.10.tar.gz/rockset_sqlcli-0.8.10/rockset_sqlcli/rscli/packages/parseutils/tables.py | 0.480479 | 0.211356 | tables.py | pypi |
from sqlparse import parse
from sqlparse.tokens import Keyword, CTE, DML
from sqlparse.sql import Identifier, IdentifierList, Parenthesis
from collections import namedtuple
from .meta import TableMetadata, ColumnMetadata
# TableExpression is a namedtuple representing a CTE, used internally
# name: cte alias assigned in the query
# columns: list of column names
# start: index into the original string of the left parens starting the CTE
# stop: index into the original string of the right parens ending the CTE
TableExpression = namedtuple("TableExpression", "name columns start stop")
def isolate_query_ctes(full_text, text_before_cursor):
"""Simplify a query by converting CTEs into table metadata objects"""
if not full_text:
return full_text, text_before_cursor, tuple()
ctes, remainder = extract_ctes(full_text)
if not ctes:
return full_text, text_before_cursor, ()
current_position = len(text_before_cursor)
meta = []
for cte in ctes:
if cte.start < current_position < cte.stop:
# Currently editing a cte - treat its body as the current full_text
text_before_cursor = full_text[cte.start : current_position]
full_text = full_text[cte.start : cte.stop]
return full_text, text_before_cursor, meta
# Append this cte to the list of available table metadata
cols = (ColumnMetadata(name, None, ()) for name in cte.columns)
meta.append(TableMetadata(cte.name, cols))
# Editing past the last cte (ie the main body of the query)
full_text = full_text[ctes[-1].stop :]
text_before_cursor = text_before_cursor[ctes[-1].stop : current_position]
return full_text, text_before_cursor, tuple(meta)
def extract_ctes(sql):
"""Extract constant table expresseions from a query
Returns tuple (ctes, remainder_sql)
ctes is a list of TableExpression namedtuples
remainder_sql is the text from the original query after the CTEs have
been stripped.
"""
p = parse(sql)[0]
# Make sure the first meaningful token is "WITH" which is necessary to
# define CTEs
idx, tok = p.token_next(-1, skip_ws=True, skip_cm=True)
if not (tok and tok.ttype == CTE):
return [], sql
# Get the next (meaningful) token, which should be the first CTE
idx, tok = p.token_next(idx)
if not tok:
return ([], "")
start_pos = token_start_pos(p.tokens, idx)
ctes = []
if isinstance(tok, IdentifierList):
# Multiple ctes
for t in tok.get_identifiers():
cte_start_offset = token_start_pos(tok.tokens, tok.token_index(t))
cte = get_cte_from_token(t, start_pos + cte_start_offset)
if not cte:
continue
ctes.append(cte)
elif isinstance(tok, Identifier):
# A single CTE
cte = get_cte_from_token(tok, start_pos)
if cte:
ctes.append(cte)
idx = p.token_index(tok) + 1
# Collapse everything after the ctes into a remainder query
remainder = u"".join(str(tok) for tok in p.tokens[idx:])
return ctes, remainder
def get_cte_from_token(tok, pos0):
cte_name = tok.get_real_name()
if not cte_name:
return None
# Find the start position of the opening parens enclosing the cte body
idx, parens = tok.token_next_by(Parenthesis)
if not parens:
return None
start_pos = pos0 + token_start_pos(tok.tokens, idx)
cte_len = len(str(parens)) # includes parens
stop_pos = start_pos + cte_len
column_names = extract_column_names(parens)
return TableExpression(cte_name, column_names, start_pos, stop_pos)
def extract_column_names(parsed):
# Find the first DML token to check if it's a SELECT or INSERT/UPDATE/DELETE
idx, tok = parsed.token_next_by(t=DML)
tok_val = tok and tok.value.lower()
if tok_val in ("insert", "update", "delete"):
# Jump ahead to the RETURNING clause where the list of column names is
idx, tok = parsed.token_next_by(idx, (Keyword, "returning"))
elif not tok_val == "select":
# Must be invalid CTE
return ()
# The next token should be either a column name, or a list of column names
idx, tok = parsed.token_next(idx, skip_ws=True, skip_cm=True)
return tuple(t.get_name() for t in _identifiers(tok))
def token_start_pos(tokens, idx):
return sum(len(str(t)) for t in tokens[:idx])
def _identifiers(tok):
if isinstance(tok, IdentifierList):
for t in tok.get_identifiers():
# NB: IdentifierList.get_identifiers() can return non-identifiers!
if isinstance(t, Identifier):
yield t
elif isinstance(tok, Identifier):
yield tok | /rockset_sqlcli-0.8.10.tar.gz/rockset_sqlcli-0.8.10/rockset_sqlcli/rscli/packages/parseutils/ctes.py | 0.666605 | 0.501404 | ctes.py | pypi |
from __future__ import print_function
import re
import sqlparse
from sqlparse.sql import Identifier
from sqlparse.tokens import Token, Error
cleanup_regex = {
# This matches only alphanumerics and underscores.
"alphanum_underscore": re.compile(r"(\w+)$"),
# This matches everything except spaces, parens, colon, and comma
"many_punctuations": re.compile(r"([^():,\s]+)$"),
# This matches everything except spaces, parens, colon, comma, and period
"most_punctuations": re.compile(r"([^\.():,\s]+)$"),
# This matches everything except a space.
"all_punctuations": re.compile(r"([^\s]+)$"),
}
def last_word(text, include="alphanum_underscore"):
r"""
Find the last word in a sentence.
>>> last_word('abc')
'abc'
>>> last_word(' abc')
'abc'
>>> last_word('')
''
>>> last_word(' ')
''
>>> last_word('abc ')
''
>>> last_word('abc def')
'def'
>>> last_word('abc def ')
''
>>> last_word('abc def;')
''
>>> last_word('bac $def')
'def'
>>> last_word('bac $def', include='most_punctuations')
'$def'
>>> last_word('bac \def', include='most_punctuations')
'\\\\def'
>>> last_word('bac \def;', include='most_punctuations')
'\\\\def;'
>>> last_word('bac::def', include='most_punctuations')
'def'
>>> last_word('"foo*bar', include='most_punctuations')
'"foo*bar'
"""
if not text: # Empty string
return ""
if text[-1].isspace():
return ""
else:
regex = cleanup_regex[include]
matches = regex.search(text)
if matches:
return matches.group(0)
else:
return ""
def find_prev_keyword(sql, n_skip=0):
"""Find the last sql keyword in an SQL statement
Returns the value of the last keyword, and the text of the query with
everything after the last keyword stripped
"""
if not sql.strip():
return None, ""
parsed = sqlparse.parse(sql)[0]
flattened = list(parsed.flatten())
flattened = flattened[: len(flattened) - n_skip]
logical_operators = ("AND", "OR", "NOT", "BETWEEN")
for t in reversed(flattened):
if t.value == "(" or (
t.is_keyword and (t.value.upper() not in logical_operators)
):
# Find the location of token t in the original parsed statement
# We can't use parsed.token_index(t) because t may be a child token
# inside a TokenList, in which case token_index thows an error
# Minimal example:
# p = sqlparse.parse('select * from foo where bar')
# t = list(p.flatten())[-3] # The "Where" token
# p.token_index(t) # Throws ValueError: not in list
idx = flattened.index(t)
# Combine the string values of all tokens in the original list
# up to and including the target keyword token t, to produce a
# query string with everything after the keyword token removed
text = "".join(tok.value for tok in flattened[: idx + 1])
return t, text
return None, ""
# Postgresql dollar quote signs look like `$$` or `$tag$`
dollar_quote_regex = re.compile(r"^\$[^$]*\$$")
def is_open_quote(sql):
"""Returns true if the query contains an unclosed quote"""
# parsed can contain one or more semi-colon separated commands
parsed = sqlparse.parse(sql)
return any(_parsed_is_open_quote(p) for p in parsed)
def _parsed_is_open_quote(parsed):
# Look for unmatched single quotes, or unmatched dollar sign quotes
return any(tok.match(Token.Error, ("'", "$")) for tok in parsed.flatten())
def parse_partial_identifier(word):
"""Attempt to parse a (partially typed) word as an identifier
word may include a schema qualification, like `schema_name.partial_name`
or `schema_name.` There may also be unclosed quotation marks, like
`"schema`, or `schema."partial_name`
:param word: string representing a (partially complete) identifier
:return: sqlparse.sql.Identifier, or None
"""
p = sqlparse.parse(word)[0]
n_tok = len(p.tokens)
if n_tok == 1 and isinstance(p.tokens[0], Identifier):
return p.tokens[0]
elif p.token_next_by(m=(Error, '"'))[1]:
# An unmatched double quote, e.g. '"foo', 'foo."', or 'foo."bar'
# Close the double quote, then reparse
return parse_partial_identifier(word + '"')
else:
return None | /rockset_sqlcli-0.8.10.tar.gz/rockset_sqlcli-0.8.10/rockset_sqlcli/rscli/packages/parseutils/utils.py | 0.727104 | 0.35262 | utils.py | pypi |
import datetime
import geojson
# all Rockset data types
DATATYPE_META = "__rockset_type"
DATATYPE_INT = "int"
DATATYPE_FLOAT = "float"
DATATYPE_BOOL = "bool"
DATATYPE_STRING = "string"
DATATYPE_BYTES = "bytes"
DATATYPE_NULL = "null"
DATATYPE_NULL_TYPE = "null_type"
DATATYPE_ARRAY = "array"
DATATYPE_OBJECT = "object"
DATATYPE_DATE = "date"
DATATYPE_DATETIME = "datetime"
DATATYPE_TIME = "time"
DATATYPE_TIMESTAMP = "timestamp"
DATATYPE_MONTH_INTERVAL = "month_interval"
DATATYPE_MICROSECOND_INTERVAL = "microsecond_interval"
DATATYPE_GEOGRAPHY = "geography"
def _date_fromisoformat(s):
dt = datetime.datetime.strptime(s, "%Y-%m-%d")
return dt.date()
def _time_fromisoformat(s):
try:
dt = datetime.datetime.strptime(s, "%H:%M:%S.%f")
except ValueError:
dt = datetime.datetime.strptime(s, "%H:%M:%S")
return datetime.time(
hour=dt.hour, minute=dt.minute, second=dt.second, microsecond=dt.microsecond
)
def _datetime_fromisoformat(s):
try:
dt = datetime.datetime.strptime(s, "%Y-%m-%dT%H:%M:%S.%f")
except ValueError:
dt = datetime.datetime.strptime(s, "%Y-%m-%dT%H:%M:%S")
return dt
def _timedelta_from_microseconds(us):
return datetime.timedelta(microseconds=us)
class Document(dict):
"""Represents a single record or row in query results.
This is a sub-class of dict. So, treat this object as a dict
for all practical purposes.
Only the constructor is overridden to handle the type adaptations
shown in the table above.
"""
def __init__(self, *args, **kwargs):
super(Document, self).__init__(*args, **kwargs)
for k in self.keys():
if not isinstance(self[k], dict):
continue
if DATATYPE_META not in self[k]:
continue
t = self[k][DATATYPE_META].lower()
v = self[k]["value"]
if t == DATATYPE_DATE:
self[k] = _date_fromisoformat(v)
elif t == DATATYPE_TIME:
self[k] = _time_fromisoformat(v)
elif t == DATATYPE_DATETIME:
self[k] = _datetime_fromisoformat(v)
elif t == DATATYPE_MICROSECOND_INTERVAL:
self[k] = _timedelta_from_microseconds(v)
elif t == DATATYPE_GEOGRAPHY:
self[k] = geojson.GeoJSON.to_instance(v)
def _py_type_to_rs_type(self, v):
if isinstance(v, bool):
# check for bool before int, since bools are ints too
return DATATYPE_BOOL
elif isinstance(v, int):
return DATATYPE_INT
elif isinstance(v, float):
return DATATYPE_FLOAT
elif isinstance(v, str):
return DATATYPE_STRING
elif isinstance(v, bytes):
return DATATYPE_BYTES
elif isinstance(v, type(None)):
return DATATYPE_NULL
elif isinstance(v, list):
return DATATYPE_ARRAY
elif isinstance(v, datetime.datetime):
# check for datetime first, since datetimes are dates too
return DATATYPE_DATETIME
elif isinstance(v, datetime.date):
return DATATYPE_DATE
elif isinstance(v, datetime.time):
return DATATYPE_TIME
elif isinstance(v, datetime.timedelta):
return DATATYPE_MICROSECOND_INTERVAL
elif isinstance(v, geojson.GeoJSON):
return DATATYPE_GEOGRAPHY
elif isinstance(v, dict): # keep this in the end
if DATATYPE_META not in v:
return DATATYPE_OBJECT
return v[DATATYPE_META].lower()
def fields(self, columns=None):
columns = columns or sorted(self)
return [
{"name": c, "type": self._py_type_to_rs_type(self.get(c, type(None)))}
for c in columns
] | /rockset-v2-alpha-0.1.13.tar.gz/rockset-v2-alpha-0.1.13/rockset/document.py | 0.486819 | 0.234955 | document.py | pypi |
class RocksetException(Exception):
"""The base exception class for all RocksetExceptions"""
class ApiTypeError(RocksetException, TypeError):
def __init__(self, msg, path_to_item=None, valid_classes=None,
key_type=None):
""" Raises an exception for TypeErrors
Args:
msg (str): the exception message
Keyword Args:
path_to_item (list): a list of keys an indices to get to the
current_item
None if unset
valid_classes (tuple): the primitive classes that current item
should be an instance of
None if unset
key_type (bool): False if our value is a value in a dict
True if it is a key in a dict
False if our item is an item in a list
None if unset
"""
self.path_to_item = path_to_item
self.valid_classes = valid_classes
self.key_type = key_type
full_msg = msg
if path_to_item:
full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
super(ApiTypeError, self).__init__(full_msg)
class ApiValueError(RocksetException, ValueError):
def __init__(self, msg, path_to_item=None):
"""
Args:
msg (str): the exception message
Keyword Args:
path_to_item (list) the path to the exception in the
received_data dict. None if unset
"""
self.path_to_item = path_to_item
full_msg = msg
if path_to_item:
full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
super(ApiValueError, self).__init__(full_msg)
class ApiAttributeError(RocksetException, AttributeError):
def __init__(self, msg, path_to_item=None):
"""
Raised when an attribute reference or assignment fails.
Args:
msg (str): the exception message
Keyword Args:
path_to_item (None/list) the path to the exception in the
received_data dict
"""
self.path_to_item = path_to_item
full_msg = msg
if path_to_item:
full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
super(ApiAttributeError, self).__init__(full_msg)
class ApiKeyError(RocksetException, KeyError):
def __init__(self, msg, path_to_item=None):
"""
Args:
msg (str): the exception message
Keyword Args:
path_to_item (None/list) the path to the exception in the
received_data dict
"""
self.path_to_item = path_to_item
full_msg = msg
if path_to_item:
full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
super(ApiKeyError, self).__init__(full_msg)
class ApiException(RocksetException):
def __init__(self, status=None, reason=None, http_resp=None):
if http_resp:
self.status = http_resp.status
self.reason = http_resp.reason
self.body = http_resp.data
self.headers = http_resp.getheaders()
else:
self.status = status
self.reason = reason
self.body = None
self.headers = None
def __str__(self):
"""Custom error messages for exception"""
error_message = "({0})\n"\
"Reason: {1}\n".format(self.status, self.reason)
if self.headers:
error_message += "HTTP response headers: {0}\n".format(
self.headers)
if self.body:
error_message += "HTTP response body: {0}\n".format(self.body)
return error_message
class NotFoundException(ApiException):
def __init__(self, status=None, reason=None, http_resp=None):
super(NotFoundException, self).__init__(status, reason, http_resp)
class UnauthorizedException(ApiException):
def __init__(self, status=None, reason=None, http_resp=None):
super(UnauthorizedException, self).__init__(status, reason, http_resp)
class ForbiddenException(ApiException):
def __init__(self, status=None, reason=None, http_resp=None):
super(ForbiddenException, self).__init__(status, reason, http_resp)
class ServiceException(ApiException):
def __init__(self, status=None, reason=None, http_resp=None):
super(ServiceException, self).__init__(status, reason, http_resp)
class BadRequestException(ApiException):
def __init__(self, status=None, reason=None, http_resp=None):
super(BadRequestException, self).__init__(status, reason, http_resp)
class InitializationException(RocksetException):
def __init__(self, reason):
super(InitializationException, self).__init__(f"The rockset client was initialized incorrectly: {reason}")
def render_path(path_to_item):
"""Returns a string representation of a path"""
result = ""
for pth in path_to_item:
if isinstance(pth, int):
result += "[{0}]".format(pth)
else:
result += "['{0}']".format(pth)
return result | /rockset-v2-alpha-0.1.13.tar.gz/rockset-v2-alpha-0.1.13/rockset/exceptions.py | 0.807954 | 0.313788 | exceptions.py | pypi |
import re # noqa: F401
import sys # noqa: F401
import typing # noqa: F401
import asyncio
from rockset.api_client import ApiClient, Endpoint as _Endpoint
from rockset.model_utils import ( # noqa: F401
check_allowed_values,
check_validations,
date,
datetime,
file_type,
none_type,
validate_and_convert_types
)
from rockset.model.create_workspace_request import CreateWorkspaceRequest
from rockset.model.create_workspace_response import CreateWorkspaceResponse
from rockset.model.delete_workspace_response import DeleteWorkspaceResponse
from rockset.model.error_model import ErrorModel
from rockset.model.get_workspace_response import GetWorkspaceResponse
from rockset.model.list_workspaces_response import ListWorkspacesResponse
from rockset.models import *
class Workspaces(object):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
self.create_endpoint = _Endpoint(
settings={
'response_type': (CreateWorkspaceResponse,),
'auth': [
'apikey'
],
'endpoint_path': '/v1/orgs/self/ws',
'operation_id': 'create',
'http_method': 'POST',
'servers': None,
},
params_map={
'all': [
'create_workspace_request',
],
'required': [
],
'nullable': [
],
'enum': [
],
'validation': [
]
},
root_map={
'validations': {
},
'allowed_values': {
},
'openapi_types': {
'create_workspace_request':
(CreateWorkspaceRequest,),
},
'attribute_map': {
},
'location_map': {
'create_workspace_request': 'body',
},
'collection_format_map': {
}
},
headers_map={
'accept': [
'application/json'
],
'content_type': [
'application/json'
]
},
api_client=api_client
)
self.delete_endpoint = _Endpoint(
settings={
'response_type': (DeleteWorkspaceResponse,),
'auth': [
'apikey'
],
'endpoint_path': '/v1/orgs/self/ws/{workspace}',
'operation_id': 'delete',
'http_method': 'DELETE',
'servers': None,
},
params_map={
'all': [
'workspace',
],
'required': [
'workspace',
],
'nullable': [
],
'enum': [
],
'validation': [
]
},
root_map={
'validations': {
},
'allowed_values': {
},
'openapi_types': {
'workspace':
(str,),
},
'attribute_map': {
'workspace': 'workspace',
},
'location_map': {
'workspace': 'path',
},
'collection_format_map': {
}
},
headers_map={
'accept': [
'application/json'
],
'content_type': [],
},
api_client=api_client
)
self.get_endpoint = _Endpoint(
settings={
'response_type': (GetWorkspaceResponse,),
'auth': [
'apikey'
],
'endpoint_path': '/v1/orgs/self/ws/{workspace}',
'operation_id': 'get',
'http_method': 'GET',
'servers': None,
},
params_map={
'all': [
'workspace',
],
'required': [
'workspace',
],
'nullable': [
],
'enum': [
],
'validation': [
]
},
root_map={
'validations': {
},
'allowed_values': {
},
'openapi_types': {
'workspace':
(str,),
},
'attribute_map': {
'workspace': 'workspace',
},
'location_map': {
'workspace': 'path',
},
'collection_format_map': {
}
},
headers_map={
'accept': [
'application/json'
],
'content_type': [],
},
api_client=api_client
)
self.list_endpoint = _Endpoint(
settings={
'response_type': (ListWorkspacesResponse,),
'auth': [
'apikey'
],
'endpoint_path': '/v1/orgs/self/ws',
'operation_id': 'list',
'http_method': 'GET',
'servers': None,
},
params_map={
'all': [
],
'required': [],
'nullable': [
],
'enum': [
],
'validation': [
]
},
root_map={
'validations': {
},
'allowed_values': {
},
'openapi_types': {
},
'attribute_map': {
},
'location_map': {
},
'collection_format_map': {
}
},
headers_map={
'accept': [
'application/json'
],
'content_type': [],
},
api_client=api_client
)
def create(
self,
*,
name: str,
description: str = None,
**kwargs
) -> typing.Union[CreateWorkspaceResponse, asyncio.Future]:
"""Create Workspace # noqa: E501
Create a new workspace. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
```python
rs = RocksetClient(api_key=APIKEY)
future = rs.Workspaces.create(
description="Datasets of system logs for the ops team.",
name="event_logs",
async_req=True,
)
result = await future
```
Keyword Args:
description (str): longer explanation for the workspace. [optional]
name (str): descriptive label and unique identifier. [required]
_return_http_data_only (bool): response data without head status
code and headers. Default is True.
_preload_content (bool): if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data.
Default is True.
_request_timeout (int/float/tuple): timeout setting for this request. If
one number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts.
Default is None.
_check_input_type (bool): specifies if type checking
should be done one the data sent to the server.
Default is True.
_check_return_type (bool): specifies if type checking
should be done on the data received from the server.
If False, the client will also not convert nested inner objects
into the respective model types (the outermost object
is still converted to the model).
Default is True.
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_content_type (str/None): force body content-type.
Default is None and content-type will be predicted by allowed
content-types and body.
_host_index (int/None): specifies the index of the server
that we want to use.
Default is read from the configuration.
async_req (bool): execute request asynchronously
Returns:
CreateWorkspaceResponse
If the method is called asynchronously, returns an asyncio.Future which resolves to the response.
"""
kwargs['async_req'] = kwargs.get(
'async_req', False
)
kwargs['_return_http_data_only'] = kwargs.get(
'_return_http_data_only', True
)
kwargs['_preload_content'] = kwargs.get(
'_preload_content', True
)
kwargs['_request_timeout'] = kwargs.get(
'_request_timeout', None
)
kwargs['_check_input_type'] = kwargs.get(
'_check_input_type', True
)
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_spec_property_naming'] = kwargs.get(
'_spec_property_naming', False
)
kwargs['_content_type'] = kwargs.get(
'_content_type')
kwargs['_host_index'] = kwargs.get('_host_index')
kwargs['create_workspace_request'] = \
kwargs['create_workspace_request']
return self.create_endpoint.call_with_http_info(**kwargs)
def delete(
self,
*,
workspace = "commons",
**kwargs
) -> typing.Union[DeleteWorkspaceResponse, asyncio.Future]:
"""Delete Workspace # noqa: E501
Remove a workspace. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
```python
rs = RocksetClient(api_key=APIKEY)
future = rs.Workspaces.delete(
async_req=True,
)
result = await future
```
Keyword Args:
workspace (str): name of the workspace. [required] if omitted the server will use the default value of "commons"
_return_http_data_only (bool): response data without head status
code and headers. Default is True.
_preload_content (bool): if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data.
Default is True.
_request_timeout (int/float/tuple): timeout setting for this request. If
one number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts.
Default is None.
_check_input_type (bool): specifies if type checking
should be done one the data sent to the server.
Default is True.
_check_return_type (bool): specifies if type checking
should be done on the data received from the server.
If False, the client will also not convert nested inner objects
into the respective model types (the outermost object
is still converted to the model).
Default is True.
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_content_type (str/None): force body content-type.
Default is None and content-type will be predicted by allowed
content-types and body.
_host_index (int/None): specifies the index of the server
that we want to use.
Default is read from the configuration.
async_req (bool): execute request asynchronously
Returns:
DeleteWorkspaceResponse
If the method is called asynchronously, returns an asyncio.Future which resolves to the response.
"""
kwargs['async_req'] = kwargs.get(
'async_req', False
)
kwargs['_return_http_data_only'] = kwargs.get(
'_return_http_data_only', True
)
kwargs['_preload_content'] = kwargs.get(
'_preload_content', True
)
kwargs['_request_timeout'] = kwargs.get(
'_request_timeout', None
)
kwargs['_check_input_type'] = kwargs.get(
'_check_input_type', True
)
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_spec_property_naming'] = kwargs.get(
'_spec_property_naming', False
)
kwargs['_content_type'] = kwargs.get(
'_content_type')
kwargs['_host_index'] = kwargs.get('_host_index')
kwargs['workspace'] = \
workspace
return self.delete_endpoint.call_with_http_info(**kwargs)
def get(
self,
*,
workspace = "commons",
**kwargs
) -> typing.Union[GetWorkspaceResponse, asyncio.Future]:
"""Retrieve Workspace # noqa: E501
Get information about a single workspace. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
```python
rs = RocksetClient(api_key=APIKEY)
future = rs.Workspaces.get(
async_req=True,
)
result = await future
```
Keyword Args:
workspace (str): name of the workspace. [required] if omitted the server will use the default value of "commons"
_return_http_data_only (bool): response data without head status
code and headers. Default is True.
_preload_content (bool): if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data.
Default is True.
_request_timeout (int/float/tuple): timeout setting for this request. If
one number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts.
Default is None.
_check_input_type (bool): specifies if type checking
should be done one the data sent to the server.
Default is True.
_check_return_type (bool): specifies if type checking
should be done on the data received from the server.
If False, the client will also not convert nested inner objects
into the respective model types (the outermost object
is still converted to the model).
Default is True.
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_content_type (str/None): force body content-type.
Default is None and content-type will be predicted by allowed
content-types and body.
_host_index (int/None): specifies the index of the server
that we want to use.
Default is read from the configuration.
async_req (bool): execute request asynchronously
Returns:
GetWorkspaceResponse
If the method is called asynchronously, returns an asyncio.Future which resolves to the response.
"""
kwargs['async_req'] = kwargs.get(
'async_req', False
)
kwargs['_return_http_data_only'] = kwargs.get(
'_return_http_data_only', True
)
kwargs['_preload_content'] = kwargs.get(
'_preload_content', True
)
kwargs['_request_timeout'] = kwargs.get(
'_request_timeout', None
)
kwargs['_check_input_type'] = kwargs.get(
'_check_input_type', True
)
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_spec_property_naming'] = kwargs.get(
'_spec_property_naming', False
)
kwargs['_content_type'] = kwargs.get(
'_content_type')
kwargs['_host_index'] = kwargs.get('_host_index')
kwargs['workspace'] = \
workspace
return self.get_endpoint.call_with_http_info(**kwargs)
def list(
self,
**kwargs
) -> typing.Union[ListWorkspacesResponse, asyncio.Future]:
"""List Workspaces # noqa: E501
List all workspaces in an organization. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
```python
rs = RocksetClient(api_key=APIKEY)
future = rs.Workspaces.list(
async_req=True,
)
result = await future
```
Keyword Args:
_return_http_data_only (bool): response data without head status
code and headers. Default is True.
_preload_content (bool): if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data.
Default is True.
_request_timeout (int/float/tuple): timeout setting for this request. If
one number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts.
Default is None.
_check_input_type (bool): specifies if type checking
should be done one the data sent to the server.
Default is True.
_check_return_type (bool): specifies if type checking
should be done on the data received from the server.
If False, the client will also not convert nested inner objects
into the respective model types (the outermost object
is still converted to the model).
Default is True.
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_content_type (str/None): force body content-type.
Default is None and content-type will be predicted by allowed
content-types and body.
_host_index (int/None): specifies the index of the server
that we want to use.
Default is read from the configuration.
async_req (bool): execute request asynchronously
Returns:
ListWorkspacesResponse
If the method is called asynchronously, returns an asyncio.Future which resolves to the response.
"""
kwargs['async_req'] = kwargs.get(
'async_req', False
)
kwargs['_return_http_data_only'] = kwargs.get(
'_return_http_data_only', True
)
kwargs['_preload_content'] = kwargs.get(
'_preload_content', True
)
kwargs['_request_timeout'] = kwargs.get(
'_request_timeout', None
)
kwargs['_check_input_type'] = kwargs.get(
'_check_input_type', True
)
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_spec_property_naming'] = kwargs.get(
'_spec_property_naming', False
)
kwargs['_content_type'] = kwargs.get(
'_content_type')
kwargs['_host_index'] = kwargs.get('_host_index')
return self.list_endpoint.call_with_http_info(**kwargs)
body_params_dict = dict()
return_types_dict = dict()
body_params_dict['create'] = 'create_workspace_request'
return_types_dict['create'] = CreateWorkspaceRequest | /rockset-v2-alpha-0.1.13.tar.gz/rockset-v2-alpha-0.1.13/rockset/api/workspaces_api.py | 0.422743 | 0.166777 | workspaces_api.py | pypi |
import re # noqa: F401
import sys # noqa: F401
import typing # noqa: F401
import asyncio
from rockset.api_client import ApiClient, Endpoint as _Endpoint
from rockset.model_utils import ( # noqa: F401
check_allowed_values,
check_validations,
date,
datetime,
file_type,
none_type,
validate_and_convert_types
)
from rockset.model.error_model import ErrorModel
from rockset.model.organization_response import OrganizationResponse
from rockset.models import *
class Organizations(object):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
self.get_endpoint = _Endpoint(
settings={
'response_type': (OrganizationResponse,),
'auth': [
'apikey'
],
'endpoint_path': '/v1/orgs/self',
'operation_id': 'get',
'http_method': 'GET',
'servers': None,
},
params_map={
'all': [
],
'required': [],
'nullable': [
],
'enum': [
],
'validation': [
]
},
root_map={
'validations': {
},
'allowed_values': {
},
'openapi_types': {
},
'attribute_map': {
},
'location_map': {
},
'collection_format_map': {
}
},
headers_map={
'accept': [
'application/json'
],
'content_type': [],
},
api_client=api_client
)
def get(
self,
**kwargs
) -> typing.Union[OrganizationResponse, asyncio.Future]:
"""Get Organization # noqa: E501
Retrieve information about current organization. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
```python
rs = RocksetClient(api_key=APIKEY)
future = rs.Organizations.get(
async_req=True,
)
result = await future
```
Keyword Args:
_return_http_data_only (bool): response data without head status
code and headers. Default is True.
_preload_content (bool): if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data.
Default is True.
_request_timeout (int/float/tuple): timeout setting for this request. If
one number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts.
Default is None.
_check_input_type (bool): specifies if type checking
should be done one the data sent to the server.
Default is True.
_check_return_type (bool): specifies if type checking
should be done on the data received from the server.
If False, the client will also not convert nested inner objects
into the respective model types (the outermost object
is still converted to the model).
Default is True.
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_content_type (str/None): force body content-type.
Default is None and content-type will be predicted by allowed
content-types and body.
_host_index (int/None): specifies the index of the server
that we want to use.
Default is read from the configuration.
async_req (bool): execute request asynchronously
Returns:
OrganizationResponse
If the method is called asynchronously, returns an asyncio.Future which resolves to the response.
"""
kwargs['async_req'] = kwargs.get(
'async_req', False
)
kwargs['_return_http_data_only'] = kwargs.get(
'_return_http_data_only', True
)
kwargs['_preload_content'] = kwargs.get(
'_preload_content', True
)
kwargs['_request_timeout'] = kwargs.get(
'_request_timeout', None
)
kwargs['_check_input_type'] = kwargs.get(
'_check_input_type', True
)
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_spec_property_naming'] = kwargs.get(
'_spec_property_naming', False
)
kwargs['_content_type'] = kwargs.get(
'_content_type')
kwargs['_host_index'] = kwargs.get('_host_index')
return self.get_endpoint.call_with_http_info(**kwargs)
body_params_dict = dict()
return_types_dict = dict() | /rockset-v2-alpha-0.1.13.tar.gz/rockset-v2-alpha-0.1.13/rockset/api/organizations_api.py | 0.460046 | 0.204759 | organizations_api.py | pypi |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.