Ejemplo n.º 1
0
def _mdl_error(mdl):
    dsp = sh.BlueDispatcher(
        name=mdl.name,
        description='Calculates the error of calibrated model of a reference.',
    )
    dsp.add_data('inputs_map', getattr(mdl, 'inputs_map', {}))

    dsp.add_function(function_id='select_inputs',
                     function=sh.map_dict,
                     inputs=['inputs_map', 'data'],
                     outputs=['inputs<0>'])

    dsp.add_data('inputs', getattr(mdl, 'inputs', []))
    dsp.add_function(function_id='select_inputs',
                     function=_select_data,
                     inputs=['inputs', 'inputs<0>'],
                     outputs=['inputs<1>'])

    dsp.add_function(function=sh.combine_dicts,
                     inputs=['calibrated_models', 'inputs<1>'],
                     outputs=['prediction_inputs'])

    dsp.add_data('targets', getattr(mdl, 'targets', []))
    dsp.add_function(function_id='select_targets',
                     function=_select_data,
                     inputs=['targets', 'data'],
                     outputs=['references'])

    dsp.add_function(function=sh.SubDispatch(mdl.dsp),
                     inputs=['prediction_inputs', 'calibrated_models'],
                     outputs=['results'])

    dsp.add_data('outputs', getattr(mdl, 'outputs', []))
    dsp.add_func(select_predictions, outputs=['predictions'])

    dsp.add_data('metrics_inputs', getattr(mdl, 'metrics_inputs', {}))
    dsp.add_function(function_id='select_metrics_inputs',
                     function=_select_data,
                     inputs=['metrics_inputs', 'data'],
                     outputs=['metrics_kwargs'])

    dsp.add_data('metrics', getattr(mdl, 'metrics', {}))
    dsp.add_func(calculate_errors, outputs=['errors'])

    dsp.add_data('up_limit', getattr(mdl, 'up_limit', None))
    dsp.add_data('dn_limit', getattr(mdl, 'dn_limit', None))
    dsp.add_func(calculate_calibration_status,
                 inputs_kwargs=True,
                 outputs=['status'])

    return dsp
Ejemplo n.º 2
0
def mdl_selector(name, package=None):
    """
    Defines a model selector for a specific model.

    :param name:
        Model name.
    :type name: str

    :param package:
        Package name.
    :type package: str

    :return:
        Model selector.
    :rtype: schedula.utils.blue.BlueDispatcher
    """
    import importlib
    mdl = importlib.import_module(name, package)
    dsp = sh.BlueDispatcher(name='%s selector' % mdl.name,
                            description='Select the calibrated %s.' % mdl.name)

    err_func = sh.SubDispatch(_mdl_error(mdl),
                              outputs=['errors', 'status'],
                              output_type='list')

    for data_id in calibration_cycles:
        mdl_err, mdl_err_name = _mdl_errors(mdl, data_id, err_func)
        dsp.add_func(sh.SubDispatchFunction(
            mdl_err,
            function_id=mdl_err_name,
            inputs=[data_id] + [k
                                for k in calibration_cycles if k != data_id]),
                     outputs=['error/%s' % data_id])

    # noinspection PyTypeChecker
    dsp.add_function(function=functools.partial(sort_models,
                                                weights=getattr(
                                                    mdl, 'weights', None)),
                     inputs=list(map('error/{}'.format, calibration_cycles)),
                     outputs=['rank'])

    dsp.add_func(format_score, outputs=['score'])

    dsp.add_func(functools.partial(select_best_model,
                                   selector_id='%s selector' % mdl.name),
                 outputs=['model'])

    return dsp
Ejemplo n.º 3
0
def _mdl_errors(mdl, data_id, err_func):
    name = '%s-%s errors' % (mdl.name, data_id)
    dsp = sh.BlueDispatcher(
        name=name, description='Calculates the error of calibrated model.')
    dsp.add_data('models', mdl.models)

    dsp.add_function(function_id='select_models',
                     function=getattr(mdl, 'select_models', _select_data),
                     inputs=['models', data_id],
                     outputs=['calibrated_models'])
    dsp.add_data('data_in', data_id)

    for o in calibration_cycles:
        dsp.add_function(function=_map_list,
                         inputs=['calibrated_models', o],
                         outputs=['input/%s' % o])

        dsp.add_function(function=err_func,
                         inputs=['input/%s' % o],
                         outputs=['error/%s' % o])
    return dsp, name
Ejemplo n.º 4
0
It contains utility functions and the computational model `dsp` to synchronise
and re-sample data-sets.

Sub-Modules:

.. currentmodule:: syncing.model

.. autosummary::
    :nosignatures:
    :toctree: model/

    interp
"""
import schedula as sh

dsp = sh.BlueDispatcher(name='Computational Model', raises=True)


@sh.add_function(dsp,
                 outputs=['labels'],
                 inputs_kwargs=True,
                 inputs_defaults=True)
def define_labels(x_label='x', y_label='y'):
    """
    Defines `reference-labels` (i.e., "x", "y") for each data-set.

    :param x_label:
        Default `var-name` of the common x-axis to synchronise and re-sampled
        the data-sets.
    :type x_label: str
Ejemplo n.º 5
0
#
# Copyright 2015-2019 European Commission (JRC);
# Licensed under the EUPL (the 'Licence');
# You may not use this work except in compliance with the Licence.
# You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl
"""
Functions and `dsp` model to model the GSPV Approach.
"""
import copy
import numpy as np
import schedula as sh
from .cmv import CMV
from co2mpas.defaults import dfl
from .core import prediction_gears_gsm

dsp = sh.BlueDispatcher(name='Gear Shifting Power Velocity Approach')
dsp.add_data('stop_velocity', dfl.values.stop_velocity)


def _gspv_interpolate_cloud(powers, velocities):
    from sklearn.isotonic import IsotonicRegression
    from scipy.interpolate import InterpolatedUnivariateSpline
    regressor = IsotonicRegression()
    regressor.fit(powers, velocities)
    x = np.linspace(min(powers), max(powers))
    y = regressor.predict(x)
    return InterpolatedUnivariateSpline(x, y, k=1, ext=3)


# noinspection PyMissingOrEmptyDocstring,PyPep8Naming
class GSPV(CMV):
Ejemplo n.º 6
0
"""
Defines the processing model.
"""

import functools
import numpy as np
import schedula as sh
from scipy.integrate import cumtrapz

model = sh.BlueDispatcher()

model.add_function(function_id='calculate_acceleration',
                   function=np.gradient,
                   inputs=['velocity', 'time'],
                   outputs=['acceleration'])

model.add_function(function_id='calculate_distance',
                   function=functools.partial(cumtrapz, initial=0),
                   inputs=['velocity', 'time'],
                   outputs=['distance'])

if __name__ == '__main__':
    model.register().plot(index=True)
Ejemplo n.º 7
0
#
# Copyright 2015-2019 European Commission (JRC);
# Licensed under the EUPL (the 'Licence');
# You may not use this work except in compliance with the Licence.
# You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl
"""
Functions and `dsp` model to bypass the gear box.
"""
import schedula as sh
from co2mpas.defaults import dfl
from .cvt import (
    default_correct_gear, identify_max_speed_velocity_ratio, predict_gears, CVT
)

dsp = sh.BlueDispatcher(
    name='empty model', description='Bypass for the gear box.'
)

dsp.add_func(default_correct_gear, outputs=['correct_gear'])
dsp.add_data('max_gear', 1)
dsp.add_func(predict_gears, outputs=['gears'])
dsp.add_data('stop_velocity', dfl.values.stop_velocity)
dsp.add_func(
    identify_max_speed_velocity_ratio, outputs=['max_speed_velocity_ratio']
)


@sh.add_function(dsp, outputs=['gear_shifting_model'])
def define_gear_shifting_model():
    """
    Return a fake gear shifting model.
Ejemplo n.º 8
0
    :toctree: engine/

    fc
    idle
    thermal
"""
import math
import functools
import numpy as np
import schedula as sh
from co2mpas.defaults import dfl
from .idle import dsp as _idle
from .thermal import dsp as _thermal
from .fc import dsp as _fc

dsp = sh.BlueDispatcher(name='Engine',
                        description='Models the vehicle engine.')


@sh.add_function(dsp, outputs=['fuel_type', 'is_hybrid'])
def define_fuel_type_and_is_hybrid(obd_fuel_type_code):
    """
    Defines engine fuel type and if the vehicle is hybrid.

    :param obd_fuel_type_code:
        OBD fuel type of the vehicle [-].
    :type obd_fuel_type_code: int

    :return:
        Engine fuel type and if the vehicle is hybrid.
    :rtype: (str, bool)
    """
Ejemplo n.º 9
0
#
# Copyright 2015-2019 European Commission (JRC);
# Licensed under the EUPL (the 'Licence');
# You may not use this work except in compliance with the Licence.
# You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl
"""
Functions and `dsp` model to model the CMV Approach.
"""
import itertools
import collections
import numpy as np
import schedula as sh
from co2mpas.defaults import dfl
from .core import prediction_gears_gsm, define_gear_filter

dsp = sh.BlueDispatcher(name='Corrected Matrix Velocity Approach')

dsp.add_data('stop_velocity', dfl.values.stop_velocity)


def _correct_gsv(gsv, stop_velocity):
    """
    Corrects gear shifting velocity matrix from unreliable limits.

    :param gsv:
        Gear shifting velocity matrix.
    :type gsv: dict

    :param stop_velocity:
        Maximum velocity to consider the vehicle stopped [km/h].
    :type stop_velocity: float
Ejemplo n.º 10
0
# -*- coding: utf-8 -*-
#
# Copyright 2015-2019 European Commission (JRC);
# Licensed under the EUPL (the 'Licence');
# You may not use this work except in compliance with the Licence.
# You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl
"""
Functions and `dsp` model to model the engine start stop strategy.
"""
import numpy as np
import schedula as sh
from co2mpas.defaults import dfl

dsp = sh.BlueDispatcher(name='start_stop',
                        description='Models the engine start/stop strategy.')

dsp.add_data('has_start_stop', dfl.values.has_start_stop)


@sh.add_function(dsp, outputs=['start_stop_activation_time'])
def default_start_stop_activation_time(has_start_stop):
    """
    Returns the default start stop activation time threshold [s].

    :return:
        Start-stop activation time threshold [s].
    :rtype: float
    """
    if not has_start_stop or dfl.functions.ENABLE_ALL_FUNCTIONS or \
            dfl.functions.default_start_stop_activation_time.ENABLE:
        return dfl.functions.default_start_stop_activation_time.threshold
Ejemplo n.º 11
0
    ~core
    ~cli
    ~utils
    ~defaults
"""
import os
import tqdm
import logging
import webbrowser
import os.path as osp
import schedula as sh
from co2mpas._version import *
from co2mpas.utils import check_first_arg

log = logging.getLogger(__name__)
dsp = sh.BlueDispatcher(name='process')


def init_conf(inputs):
    """
    Initialize CO2MPAS model configurations.

    :param inputs:
         Initialization inputs.
    :type inputs: dict | schedula.Token

    :return:
        Initialization inputs.
    :rtype: dict | schedula.Token
    """
    if inputs is not sh.NONE and inputs.get('model_conf'):
Ejemplo n.º 12
0
    """
    Converts leagues to thou.

    :param th:
        Length [th].
    :type th: float

    :return:
        Length [lea].
    :rtype: float
    """
    return th / 19008e4


# ----------------------------------- MODEL -----------------------------------
imperial = sh.BlueDispatcher(name='Imperial')
imperial.add_func(leagues2miles, outputs=['mi'])
imperial.add_func(miles2furlongs, outputs=['fur'])
imperial.add_func(furlongs2chains, outputs=['ch'])
imperial.add_func(chains2yards, outputs=['yd'])
imperial.add_func(yards2feet, outputs=['ft'])
imperial.add_func(feet2inch, outputs=['in'])
imperial.add_func(inch2thou, outputs=['th'], inputs=['in'])
imperial.add_func(thou2leagues, outputs=['lea'])

if __name__ == '__main__':
    # To plot the imperial model.
    imperial.register().plot(graph_attr={'ratio': '0.5'},
                             engine='neato',
                             body={'style': 'filled'})
Ejemplo n.º 13
0
import schedula as sh
from .cycle import dsp as _cycle
from .vehicle import dsp as _vehicle
from .wheels import dsp as _wheels
from .final_drive import dsp as _final_drive
from .gear_box import dsp as _gear_box
from .clutch_tc import dsp as _clutch_torque_converter
from .electrics import dsp as _electrics
from .engine import dsp as _engine
from .control import dsp as _control
from .after_treat import dsp as _after_treat
from .co2 import dsp as _co2

dsp = sh.BlueDispatcher(
    name='CO2MPAS physical model',
    description='Wraps all functions needed to calibrate and predict '
    'light-vehicles\' CO2 emissions.')

dsp.add_data('path_elevations', wildcard=True)

dsp.add_dispatcher(include_defaults=True,
                   dsp_id='cycle_model',
                   dsp=_cycle,
                   inputs=(
                       'max_speed_velocity_ratio',
                       'engine_speed_at_max_power',
                       'unladen_mass',
                       'downscale_factor_threshold',
                       'speed_velocity_ratios',
                       'k1',
                       'k2',
Ejemplo n.º 14
0
"""
Defines the symmetric cryptography model.
"""
import os.path as osp
import schedula as sh
from cryptography.fernet import Fernet

dsp = sh.BlueDispatcher(name='symmetric_cryptography')


@sh.add_function(dsp, outputs=['key'], weight=2)
def generate_key():
    return Fernet.generate_key().decode()


@sh.add_function(dsp, outputs=['encrypted'])
def encrypt_message(key, decrypted):
    return Fernet(key.encode()).encrypt(decrypted.encode()).decode()


@sh.add_function(dsp, outputs=['decrypted'])
def decrypt_message(key, encrypted):
    return Fernet(key.encode()).decrypt(encrypted.encode()).decode()


@sh.add_function(dsp)
def write_key(key_fpath, key):
    with open(key_fpath, 'w') as f:
        f.write(key)

Ejemplo n.º 15
0
.. autosummary::
    :nosignatures:
    :toctree: syncing/

    model
    rw
    cli
"""
import numpy as np
import functools
import schedula as sh
from syncing._version import *
from syncing import model
from syncing.rw import read, write

dsp = sh.BlueDispatcher(name='Processing Model', raises=True)

dsp.add_data('interpolation_method', 'linear')
dsp.add_dispatcher(read.dsp,
                   inputs=[
                       'input_fpath', 'header', 'sets_mapping_fpath',
                       'labels_fpath', 'methods_fpath', 'interpolation_method',
                       'x_label', 'y_label'
                   ],
                   outputs=[
                       'raw_data', 'reference_name', 'sets_mapping', 'labels',
                       'methods'
                   ])


@sh.add_function(dsp, inputs_kwargs=True, outputs=['data'])
Ejemplo n.º 16
0
# -*- coding: utf-8 -*-
#
# Copyright 2015-2019 European Commission (JRC);
# Licensed under the EUPL (the 'Licence');
# You may not use this work except in compliance with the Licence.
# You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl
"""
Functions and model `dsp` to model the mechanic of the clutch.
"""
import numpy as np
import schedula as sh
from co2mpas.defaults import dfl
from .torque_converter import define_k_factor_curve

dsp = sh.BlueDispatcher(name='Clutch', description='Models the clutch.')


@sh.add_function(dsp, outputs=['clutch_window'])
def default_clutch_window():
    """
    Returns a default clutching time window [s] for a generic clutch.

    :return:
        Clutching time window [s].
    :rtype: tuple
    """
    return dfl.functions.default_clutch_window.clutch_window


# noinspection PyUnusedLocal
def _no_model(times, **kwargs):
Ejemplo n.º 17
0
.. currentmodule:: co2mpas.core.model.physical.clutch_tc

.. autosummary::
    :nosignatures:
    :toctree: clutch_tc/

    clutch
    torque_converter
"""
import numpy as np
import schedula as sh
from co2mpas.defaults import dfl
from .clutch import dsp as _clutch
from .torque_converter import dsp as _torque_converter

dsp = sh.BlueDispatcher(name='Clutch and torque-converter',
                        description='Models the clutch and torque-converter.')

dsp.add_data('stop_velocity', dfl.values.stop_velocity)


@sh.add_function(dsp, outputs=['has_torque_converter'])
def default_has_torque_converter(gear_box_type):
    """
    Returns the default has torque converter value [-].

    :param gear_box_type:
        Gear box type (manual or automatic or cvt).
    :type gear_box_type: str

    :return:
        Does the vehicle use torque converter? [-]
Ejemplo n.º 18
0
    def setUp(self):
        dsp_1 = sh.BlueDispatcher(raises='')
        dsp_1.add_function('max', max, inputs=['a', 'b'], outputs=['c'])
        dsp_1.add_function('min',
                           min,
                           inputs=['c', 'b'],
                           outputs=['a'],
                           input_domain=lambda c, b: c * b > 0)
        dsp_1.add_data('a', wildcard=True)
        self.dsp_1 = dsp_1.register()

        dsp = sh.Dispatcher(raises='')

        def f(a, b):
            if b is None:
                return a, sh.NONE
            return a + b, a - b

        dsp.add_function('f', f, inputs=['a', 'b'], outputs=['c', sh.SINK])
        dsp.add_function('f', f, inputs=['c', 'b'], outputs=[sh.SINK, 'd'])
        self.dsp_2 = dsp

        dsp = sh.Dispatcher(raises='')

        dsp.add_function('f',
                         f,
                         inputs=['a', 'b'],
                         outputs=['c', 'd'],
                         out_weight={'d': 100})
        dsp.add_dispatcher(dsp=dsp_1.register(),
                           inputs={
                               'a': 'a',
                               'b': 'b'
                           },
                           outputs={'c': 'd'})
        self.dsp_3 = dsp

        dsp = sh.Dispatcher(raises='')

        dsp.add_function(function=sh.SubDispatchFunction(
            self.dsp_3, 'f', ['b', 'a'], ['c', 'd']),
                         inputs=['b', 'a'],
                         outputs=['c', 'd'],
                         out_weight={'d': 100})
        dsp.add_dispatcher(dsp=dsp_1.register(),
                           inputs={
                               'a': 'a',
                               'b': 'b'
                           },
                           outputs={'c': 'd'})
        self.dsp_4 = dsp

        dsp = sh.Dispatcher(raises='')

        def f(a, b, c=0, f=0):
            return a + b + c + f, a - b + c + f

        dsp.add_data('h', 1)
        dsp.add_function('f',
                         f,
                         inputs=['a', 'b', 'e', 'h'],
                         outputs=['c', sh.SINK])
        dsp.add_data('i', 0, 10)
        dsp.add_data('c', 100, 120)
        dsp.add_function('f',
                         f,
                         inputs=['c', 'b', 'i'],
                         outputs=[sh.SINK, 'd'])
        self.dsp_5 = dsp
Ejemplo n.º 19
0
# -*- coding: utf-8 -*-
#
# Copyright 2015-2019 European Commission (JRC);
# Licensed under the EUPL (the 'Licence');
# You may not use this work except in compliance with the Licence.
# You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl
"""
Functions and `dsp` model to model the electric motor in P3 position.
"""
import schedula as sh

dsp = sh.BlueDispatcher(
    name='Motor P3',
    description='Models the motor P3 (motor upstream the final drive).')


@sh.add_function(dsp,
                 inputs=['motor_p3_front_powers'],
                 outputs=['motor_p3_front_maximum_power'])
@sh.add_function(dsp,
                 inputs=['motor_p3_rear_powers'],
                 outputs=['motor_p3_rear_maximum_power'])
def identify_motor_p3_maximum_power(motor_p3_powers):
    """
    Identify the maximum power of motor P3 [kW].

    :param motor_p3_powers:
        Power at motor P3 [kW].
    :type motor_p3_powers: numpy.array

    :return:
Ejemplo n.º 20
0
Sub-Modules:

.. currentmodule:: co2mpas.core.load.validate

.. autosummary::
    :nosignatures:
    :toctree: validate/

    hard
"""
import logging
import schedula as sh

log = logging.getLogger(__name__)
dsp = sh.BlueDispatcher(
    name='validate_data', description='Validates input data.'
)


def _add_validated_input(data, validate, keys, value, errors):
    from schema import SchemaError
    try:
        k, v = next(iter(validate({keys[-1]: value}).items()))
        if v is not sh.NONE:
            data[k] = v
            return v
    except SchemaError as ex:
        sh.get_nested_dicts(errors, *keys[:-1])[keys[-1]] = ex
    return sh.NONE

Ejemplo n.º 21
0
def mm2km(mm):
    """
    Converts mm to km.

    :param mm:
        Length [mm].
    :type mm: float

    :return:
        Length [km].
    :rtype float
    """
    return mm / 1e6


# ----------------------------------- MODEL -----------------------------------
metric = sh.BlueDispatcher(name='Metric')
metric.add_func(km2m, outputs=['m'])
metric.add_func(m2dm, outputs=['dm'])
metric.add_func(dm2cm, outputs=['cm'])
metric.add_func(cm2mm, outputs=['mm'])
metric.add_func(mm2km, outputs=['km'])

if __name__ == '__main__':
    # To plot the metric model.
    metric.register().plot(graph_attr={'ratio': '0.5'},
                           engine='neato',
                           body={'style': 'filled'},
                           index=True)
Ejemplo n.º 22
0
# -*- coding: utf-8 -*-
#
# Copyright 2015-2019 European Commission (JRC);
# Licensed under the EUPL (the 'Licence');
# You may not use this work except in compliance with the Licence.
# You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl
"""
Functions and `dsp` model to model the electric motor in P4 position.
"""
import numpy as np
import schedula as sh
import co2mpas.utils as co2_utl

dsp = sh.BlueDispatcher(
    name='Motor P4',
    description='Models the motor P4 (motor downstream the final drive).')


@sh.add_function(dsp,
                 inputs=['motor_p4_front_powers'],
                 outputs=['motor_p4_front_maximum_power'])
@sh.add_function(dsp,
                 inputs=['motor_p4_rear_powers'],
                 outputs=['motor_p4_rear_maximum_power'])
def identify_motor_p4_maximum_power(motor_p4_powers):
    """
    Identify the maximum power of motor P4 [kW].

    :param motor_p4_powers:
        Power at motor P4 [kW].
    :type motor_p4_powers: numpy.array
Ejemplo n.º 23
0
"""
Defines the file processing the VBS model.
"""

import schedula as sh
import pandas as pd
from VBSmodel import model

process = sh.BlueDispatcher(name='Processing Model')
# BluePrint create a 'canvas' for the Dispatcher. It is not compiled yet.


@sh.add_function(process, outputs=['raw_data'])
def read_data():  #TODO change input read for different input files format.
    """
    Reads the excel file.

    :param input_fpath:
        Input file path.
    :type input_fpath: str

    :return:
        Raw Data.
    :rtype: dict
    """
    from files.VBSsetup import VBSsetup
    return VBSsetup


process.add_data(data_id='key_mapping',
                 default_value={},
Ejemplo n.º 24
0
# -*- coding: utf-8 -*-
#
# Copyright 2015-2019 European Commission (JRC);
# Licensed under the EUPL (the 'Licence');
# You may not use this work except in compliance with the Licence.
# You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl
"""
Functions and `dsp` model to model the manual gear shifting.
"""
import collections
import numpy as np
import schedula as sh
from .at_gear import CMV

dsp = sh.BlueDispatcher(name='manual GS model',
                        description='Models the manual gear shifting.')


@sh.add_function(dsp, outputs=['engine_max_speed_95'])
def calculate_engine_max_speed_95(full_load_speeds, idle_engine_speed,
                                  engine_max_speed, full_load_curve,
                                  engine_max_power):
    """
    Calculates the maximum engine speed [RPM] at 95% of the nominal power.

    :param full_load_speeds:
        T1 map speed vector [RPM].
    :type full_load_speeds: numpy.array

    :param idle_engine_speed:
        Engine speed idle median and std [RPM].
Ejemplo n.º 25
0
# Licensed under the EUPL (the 'Licence');
# You may not use this work except in compliance with the Licence.
# You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl
"""
Functions and `dsp` model to model the final drive.
"""

import logging
import collections
import numpy as np
import schedula as sh
from co2mpas.defaults import dfl

log = logging.getLogger(__name__)

dsp = sh.BlueDispatcher(name='Final drive',
                        description='Models the final drive.')
dsp.add_data('final_drive_ratio', dfl.values.final_drive_ratio)


@sh.add_function(dsp, inputs_kwargs=True, outputs=['final_drive_ratios'])
def calculate_final_drive_ratios(final_drive_ratio, n_gears=1):
    """
    Defines final drive ratios for each gear [-].

    :param final_drive_ratio:
        Final drive ratio [-].
    :type final_drive_ratio: float

    :param n_gears:
        Number of gears [-].
    :type n_gears: int, optional
Ejemplo n.º 26
0
.. autosummary::
    :nosignatures:
    :toctree: cycle/

    NEDC
    WLTP
"""
import numpy as np
import schedula as sh
from co2mpas.defaults import dfl
from .NEDC import dsp as _nedc_cycle, is_manual
from .WLTP import dsp as _wltp_cycle

dsp = sh.BlueDispatcher(
    name='Cycle model',
    description='Returns the theoretical times, velocities, and gears.')
dsp.add_data('time_sample_frequency', dfl.values.time_sample_frequency)


# noinspection PyMissingOrEmptyDocstring
def is_nedc(kw):
    return kw.get('cycle_type') == 'NEDC'


# noinspection PyMissingOrEmptyDocstring
def is_wltp(kw):
    return kw.get('cycle_type') == 'WLTP'


dsp.add_dispatcher(include_defaults=True,
Ejemplo n.º 27
0
# -*- coding: utf-8 -*-
# !/usr/bin/env python
#
# Copyright 2019-2021 European Commission (JRC);
# Licensed under the EUPL (the 'Licence');
# You may not use this work except in compliance with the Licence.
# You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl
"""
It contains functions and a model `dsp` to read input files.
"""
import schedula as sh
from . import file_ext

#: Read Model.
dsp = sh.BlueDispatcher(name='read_data', raises=True)


@sh.add_function(dsp, outputs=['sets_mapping'], input_domain=file_ext('json'))
def load_sets_mapping(sets_mapping_fpath):
    """
    Load the mapping of data-sets to _process.

    :param sets_mapping_fpath:
        File path (`.json`) of the mapping of data-sets to _process.

        It is like `{"<set-name>": {"<new-name>": "<old-name>", ...}, ...}`.
    :type sets_mapping_fpath: str

    :return:
        Mapping of data-sets to _process.
Ejemplo n.º 28
0
# -*- coding: utf-8 -*-
#
# Copyright 2015-2019 European Commission (JRC);
# Licensed under the EUPL (the 'Licence');
# You may not use this work except in compliance with the Licence.
# You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl
"""
Functions and `dsp` model to model the electric motor in P2 position.
"""
import schedula as sh

dsp = sh.BlueDispatcher(
    name='Motor P2',
    description='Models the motor P2 (motor upstream the gear box).')


@sh.add_function(dsp, outputs=['motor_p2_maximum_power'])
def identify_motor_p2_maximum_power(motor_p2_powers):
    """
    Identify the maximum power of motor P2 [kW].

    :param motor_p2_powers:
        Power at motor P2 [kW].
    :type motor_p2_powers: numpy.array

    :return:
        Maximum power of motor P2 [kW].
    :rtype: float
    """
    from .p4 import identify_motor_p4_maximum_power as func
    return func(motor_p2_powers)
Ejemplo n.º 29
0
# -*- coding: utf-8 -*-
#
# Copyright 2015-2019 European Commission (JRC);
# Licensed under the EUPL (the 'Licence');
# You may not use this work except in compliance with the Licence.
# You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl
"""
Functions and `dsp` model to model the mechanic of the wheels.
"""
import math
import regex
import schedula as sh
from co2mpas.defaults import dfl

dsp = sh.BlueDispatcher(name='Wheel model',
                        description='It models the wheel dynamics.')


def calculate_wheel_power(velocities, accelerations, road_loads, vehicle_mass):
    """
    Calculates the wheel power [kW].

    :param velocities:
        Velocity [km/h].
    :type velocities: numpy.array | float

    :param accelerations:
        Acceleration [m/s2].
    :type accelerations: numpy.array | float

    :param road_loads:
Ejemplo n.º 30
0
import copy
import logging
import numpy as np
import os.path as osp
import schedula as sh

log = logging.getLogger(__name__)
dsp = sh.BlueDispatcher(name="load",
                        description="Read/merge/parse input data.")


def check_ext(fpath, *args, ext=("xls", "xlsx")):
    return osp.splitext(fpath)[1][1:] in ext


@sh.add_function(dsp, outputs=["raw_data"], input_domain=check_ext)
def read_excel(input_path):
    """
    Read input file.

    :param input_path:
        Input file path.
    :type input_path: str

    :return:
        Raw data of input file.
    :rtype: dict
    """
    import xlrd
    import pandas as pd