text:
#!/usr/bin/env python3

import rospy
import tf2_ros
import tf2_geometry_msgs
from tf.transformations import euler_from_quaternion
from visualization_msgs.msg import MarkerArray
from std_msgs.msg import Float64MultiArray
from tf2_msgs.msg import TFMessage
from geometry_msgs.msg import PoseWithCovarianceStamped, PoseStamped
from nav_msgs.msg import Odometry
from vision_msgs.msg import Detection2DArray
from matplotlib import animation
from matplotlib import pyplot as plt
from matplotlib.ticker import ScalarFormatter
import numpy as np

class Vizualizer:
    """Class for visualization of the environment, ground truth robot position
    and particle filter state estimates."""
    def __init__(self, robot_name, boundary={'x': 10, 'y': 10}):
        self.tf_buffer = tf2_ros.Buffer()
        self.tf_listener = tf2_ros.TransformListener(self.tf_buffer)

        self.robot_name = robot_name
        self.target_frame = 'utm'
        self.groundtruth_frame = 'gt/{}/base_link'.format(self.robot_name)
        self.boundary = boundary
        self.map_objects = self._init_map_objects()
        self.env_lims = self._set_envlims()

        self.fig, self.ax = plt.subplots()
        self.plot_fmt = ScalarFormatter(useOffset=True)
        self.plot_fmt.format = '%.2f'
        self.environment_handles = self.init_plot()

        self.particles = None
        self.groundtruth_pose = None
        self.dr_pose = None
        self.measurements = None
        self.groundtruth_color = 'g'
        self.dr_color = 'c'
        self.particle_color = 'b'
        self.measurement_color = 'k'
        self.groundtruth_line = self.init_empty_line_plot(
            label='groundtruth_pose',
            color=self.groundtruth_color,
            markersize=3)
        self.dr_line = self.init_empty_line_plot(label='dr_pose',
                                                 color=self.dr_color,
                                                 markersize=3)
        self.particles_line = self.init_empty_line_plot(
            label='particles', color=self.particle_color, markersize=1)
        self.measurement_line = self.init_empty_line_plot(
            label='measurements', color=self.measurement_color, markersize=3)

        # summary stats
        self.dr_poses = []
        self.particle_mean = []
        self.particle_variance = []
        self.gt_poses = []
        self.dt = .5
        self.timer = rospy.Timer(rospy.Duration(self.dt),
                                 self.update_summary_stats)

    def _wait_for_transform(self, from_frame):
        """Wait for transform from from_frame to self.target_frame"""
        trans = None
        while trans is None:
            try:
                trans = self.tf_buffer.lookup_transform(
                    self.target_frame, from_frame, rospy.Time(0),
                    rospy.Duration(3.0))
            except (tf2_ros.LookupException, tf2_ros.ConnectivityException,
                    tf2_ros.ExtrapolationException) as error:
                print('Failed to transform. Error: {}'.format(error))
        return trans

    def update_measurements(self, msg):
        pose = msg.detections[0].results[0].pose
        trans = self._wait_for_transform(from_frame=msg.header.frame_id)
        self.measurements = tf2_geometry_msgs.do_transform_pose(pose, trans)

    def _tf_to_pose(self, trans_stamped):
        pose_stamped = PoseStamped()
        pose_stamped.header.stamp = rospy.Time()
        pose_stamped.header.frame_id = self.target_frame

        trans = trans_stamped.transform
        pose_stamped.pose.position = trans.translation
        pose_stamped.pose.orientation = trans.rotation
        return pose_stamped

    def update_groundtruth_pose(self, msg):
        trans = self._wait_for_transform(from_frame=self.groundtruth_frame)
        self.groundtruth_pose = self._tf_to_pose(trans)

    def update_dr_pose(self, msg):
        trans = self._wait_for_transform(from_frame=msg.header.frame_id)
        self.dr_pose = tf2_geometry_msgs.do_transform_pose(msg.pose, trans)

    def update_particles(self, msg):
        num_particles = msg.layout.dim[0].size
        num_states = msg.layout.dim[1].size
        offset = msg.layout.data_offset

        self.particles = np.array(msg.data[offset:]).reshape(
            num_particles, num_states)

    def update_summary_stats(self, timer):
        if not all([(self.particles is not None), self.dr_pose,
                    self.groundtruth_pose]):
            return

        mean = self.particles.mean(axis=0)
        var = self.particles.var(axis=0)

        self.particle_mean.append(mean)
        self.particle_variance.append(var)

        (dr_roll, dr_pitch, dr_yaw) = euler_from_quaternion([
            self.dr_pose.pose.orientation.x, self.dr_pose.pose.orientation.y,
            self.dr_pose.pose.orientation.z, self.dr_pose.pose.orientation.w
        ])
        self.dr_poses.append([
            self.dr_pose.pose.position.x, self.dr_pose.pose.position.y,
            self.dr_pose.pose.position.z, dr_roll, dr_pitch, dr_yaw
        ])

        (groundtruth_roll, groundtruth_pitch,
         groundtruth_yaw) = euler_from_quaternion([
             self.groundtruth_pose.pose.orientation.x,
             self.groundtruth_pose.pose.orientation.y,
             self.groundtruth_pose.pose.orientation.z,
             self.groundtruth_pose.pose.orientation.w
         ])
        self.gt_poses.append([
            self.groundtruth_pose.pose.position.x,
            self.groundtruth_pose.pose.position.y,
            self.groundtruth_pose.pose.position.z, groundtruth_roll,
            groundtruth_pitch, groundtruth_yaw
        ])

    def init_empty_line_plot(self, label, color, markersize):
        line, = self.ax.plot([], [],
                             label=label,
                             c=color,
                             marker='o',
                             ls='',
                             markersize=markersize)
        return line

    def animate_dr_pose(self, i):
        x, y = [], []
        if self.dr_pose is not None:
            x = self.dr_pose.pose.position.x
            y = self.dr_pose.pose.position.y
        self.dr_line.set_xdata(x)
        self.dr_line.set_ydata(y)

    def animate_groundtruth_pose(self, i):
        """
        This method is periodically called by FuncAnimation to update the
        environment plot with the new groundtruth pose.

        Args:
            - i: frame id
            - line: the line object
        """
        x, y = [], []
        if self.groundtruth_pose is not None:
            x = self.groundtruth_pose.pose.position.x
            y = self.groundtruth_pose.pose.position.y
        self.groundtruth_line.set_xdata(x)
        self.groundtruth_line.set_ydata(y)

    def animate_measurement_pose(self, i):
        """
        This method is periodically called by FuncAnimation to update the
        environment plot with the new measurement pose.

        Args:
            - i: frame id
            - line: the line object
        """
        x, y = [], []
        if self.measurements is not None:
            x = self.measurements.pose.position.x
            y = self.measurements.pose.position.y
        self.measurement_line.set_xdata(x)
        self.measurement_line.set_ydata(y)

    def animate_particles(self, i):
        """
        This method is periodically called by FuncAnimation to update the
        environment plot with the new particle states.

        Args:
            - i: frame id
        """
        if self.particles is not None:
            self.particles_line.set_xdata(self.particles[:, 0])
            self.particles_line.set_ydata(self.particles[:, 1])
        return self.particles_line

    def _init_map_objects(self):
        """Wait for /{robot_name}/sim/marked_positions to publish its first
        message, use it to initialize the map with object positions."""

        marked_pos_topic = '/{}/sim/marked_positions'.format(self.robot_name)
        msg = rospy.wait_for_message(marked_pos_topic, MarkerArray)

        map_objects = {}
        for marker in msg.markers:
            map_objects[marker.ns] = {
                'x':
                marker.pose.position.x,
                'y':
                marker.pose.position.y,
                'z':
                marker.pose.position.z,
                'c': (marker.color.r, marker.color.g, marker.color.b,
                      marker.color.a),
                's':
                marker.scale.x
            }
        print(map_objects)
        return map_objects

    def _set_envlims(self):
        """Set limits for all map axes. Bound the axis so that all objects
        in the map can be seen and use self.boundary to determine the size
        of the canvas that should extend from the edge objects."""
        env_lims = {}

        for axis, axis_boundary in self.boundary.items():
            obj_values = [obj[axis] for obj in self.map_objects.values()]
            lim = (min(obj_values) - axis_boundary,
                   max(obj_values) + axis_boundary)
            env_lims[axis] = lim

        return env_lims

    def init_plot(self):
        """Initialize a 2D plot containing all the static map_objects."""
        self.ax.set_xlim(self.env_lims['x'])
        self.ax.set_ylim(self.env_lims['y'])
        self.ax.xaxis.set_major_formatter(self.plot_fmt)
        self.ax.yaxis.set_major_formatter(self.plot_fmt)

        environment_handles = self._static_env_plot()

        plt.title('Environment')
        plt.xlabel('x (m)')
        plt.ylabel('y (m)')
        return environment_handles

    def _static_env_plot(self):
        """
        Plot the map consisting of self.map_objects in 2D plot onto the
        Visualizer's Axes object.
        """
        environment_handles = []

        for obj_id, obj_val in self.map_objects.items():
            # Plot as continuous line or individual point depending on the info given
            if isinstance(obj_val['x'], float):
                handle, = self.ax.plot(obj_val['x'],
                                       obj_val['y'],
                                       c=obj_val['c'],
                                       marker='o',
                                       ls='',
                                       markersize=obj_val['s'] * 10,
                                       label=obj_id)
            elif isinstance(obj_val['x'], tuple):
                x = np.linspace(max(obj_val['x'][0], self.env_lims['x'][0]),
                                min(obj_val['x'][1], self.env_lims['x'][1]),
                                num=100)
                y = np.linspace(max(obj_val['y'][0], self.env_lims['y'][0]),
                                min(obj_val['y'][1], self.env_lims['y'][1]),
                                num=100)
                handle, = self.ax.plot(x,
                                       y,
                                       c=obj_val['c'],
                                       linewidth=obj_val['s'],
                                       label=obj_id)
            environment_handles.append(handle)

        return environment_handles

    def plot_summary_stats(self):
        fig, axes = plt.subplots(nrows=3,
                                 ncols=2,
                                 sharex=True,
                                 figsize=(9, 12))
        x_axis = list(range(len(self.gt_poses)))
        titles = ['x values', 'y values', 'z values', 'roll', 'pitch', 'yaw']

        for i in range(3):
            axes[i][0].yaxis.set_major_formatter(self.plot_fmt)
            axes[i][1].set_ylim(-np.pi, np.pi)
            for j in range(2):
                axes[i][j].set_title(titles[i + j * 3])
                axes[i][j].plot(x_axis,
                                [pose[i + j * 3] for pose in self.gt_poses],
                                color=self.groundtruth_color,
                                label='groundtruth')
                axes[i][j].plot(x_axis,
                                [pose[i + j * 3] for pose in self.dr_poses],
                                color=self.dr_color,
                                label='dr_pose')
                axes[i][j].errorbar(
                    x_axis, [pose[i + j * 3] for pose in self.particle_mean],
                    yerr=[pose[i + j * 3] for pose in self.particle_variance],
                    errorevery=(0, 10),
                    ecolor='lightgray',
                    color=self.particle_color,
                    label='particles')

        plt.legend(bbox_to_anchor=(1.01, .5),
                   loc='lower left',
                   prop={'size': 8},
                   borderaxespad=0.)
        plt.tight_layout()
        plt.show()

        for i in range(6):
            gt_dim = np.array([pose[i] for pose in self.gt_poses])
            dr_dim = np.array([pose[i] for pose in self.dr_poses])
            particle_mean_dim = np.array(
                [pose[i] for pose in self.particle_mean])

            # RMSE
            particle_diff = np.sqrt(np.mean(particle_mean_dim - gt_dim)**2)
            dr_diff = np.sqrt(np.mean(dr_dim - gt_dim)**2)

            print('{} pf error mean: {}, var: {}'.format(
                titles[i], particle_diff.mean(), particle_diff.var()))
            print('{} dr error mean: {}, var: {}\n'.format(
                titles[i], dr_diff.mean(), dr_diff.var()))

def main():
    rospy.init_node('particle_filter_localization_visualizer',
                    anonymous=True,
                    disable_signals=True)
    rospy.Rate(5)

    robot_name = rospy.get_param('~robot_name')
    boundary = rospy.get_param('~boundary')
    viz = Vizualizer(robot_name, boundary)

    print(viz.env_lims)

    #TODO: refactor - merge animate functions for both groundtruth and particles
    groundtruth_pose_sub = rospy.Subscriber('/tf', TFMessage,
                                            viz.update_groundtruth_pose)
    # It's important to store the FuncAnimation to a variable
    # Otherwise the animation object will be collected by the garbage collector
    animate_groundtruth = animation.FuncAnimation(viz.fig,
                                                  viz.animate_groundtruth_pose,
                                                  interval=50)

    dr_odom_topic = '/{}/dr/odom'.format(viz.robot_name)
    dr_odom_sub = rospy.Subscriber(dr_odom_topic, Odometry, viz.update_dr_pose)
    animate_dr = animation.FuncAnimation(viz.fig,
                                         viz.animate_dr_pose,
                                         interval=50)

    particles_topic = '/{}/localization/particles'.format(viz.robot_name)
    particles_sub = rospy.Subscriber(particles_topic, Float64MultiArray,
                                     viz.update_particles)
    animate_particles = animation.FuncAnimation(viz.fig,
                                                viz.animate_particles,
                                                interval=50)

    measurement_topic = '/{}/payload/sidescan/detection_hypothesis'.format(
        viz.robot_name)
    measurement_sub = rospy.Subscriber(measurement_topic, Detection2DArray,
                                       viz.update_measurements)
    animate_measurements = animation.FuncAnimation(
        viz.fig, viz.animate_measurement_pose, interval=50)

    legend_handles = viz.environment_handles
    legend_handles.extend(
        [viz.groundtruth_line, viz.particles_line, viz.measurement_line])
    plt.legend(handles=legend_handles,
               bbox_to_anchor=(1.01, .5),
               loc='center left',
               prop={'size': 8},
               borderaxespad=0.)
    plt.tight_layout()
    plt.show(block=True)

    viz.plot_summary_stats()

if __name__ == '__main__':
    main()


text:
# Recurrent Neural Network

# Part 1 - Data Preprocessing

# Importing the libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Importing the training set

dataset_train = pd.read_csv('Google_Stock_Price_Train.csv')
training_data = dataset_train.iloc[:,1:2].values

# Feature Scaling

from sklearn.preprocessing import MinMaxScaler
sc = MinMaxScaler()
training_set_scaled = sc.fit_transform(training_data)

# Creating a data structure with 60 timesteps and 1 output
X_train = []
y_train = []
for i in range(60,len(training_set_scaled)):
    X_train.append(training_set_scaled[i-60:i,0])
    y_train.append(training_set_scaled[i,0])
X_train,y_train =  np.array(X_train),np.array(y_train)

# Reshaping
X_train = np.reshape(X_train,(X_train.shape[0],X_train.shape[1],1))

# Part 2 - Building the RNN

# Importing the Keras libraries and packages

from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Dropout

# Initialising the RNN
regressor =  Sequential()
# Adding the first LSTM layer and some Dropout regularisation
regressor.add(LSTM(units=50,return_sequences=True,input_shape = (X_train.shape[1],1)))
regressor.add(Dropout(0.2))
# Adding a second LSTM layer and some Dropout regularisation
regressor.add(LSTM(units=50,return_sequences=True))
regressor.add(Dropout(0.2))
# Adding a third LSTM layer and some Dropout regularisation
regressor.add(LSTM(units=50,return_sequences=True))
regressor.add(Dropout(0.2))
# Adding a fourth LSTM layer and some Dropout regularisation
regressor.add(LSTM(units=50))
regressor.add(Dropout(0.2))
# Adding the output layer
regressor.add(Dense(units=1))
# Compiling the RNN
regressor.compile(optimizer = 'adam',loss = 'mean_squared_error')
# Fitting the RNN to the Training set
regressor.fit(X_train,y_train,epochs=100,batch_size=32)

# Part 3 - Making the predictions and visualising the results

# Getting the real stock price of 2017
datadet_test =pd.read_csv('Google_Stock_Price_Test.csv')
real_stock_price = datadet_test.iloc[:,1:2].values

# Getting the predicted stock price of 2017
dataset_total = pd.concat((dataset_train['Open'],datadet_test['Open']),axis=0)
inputs = dataset_total[len(dataset_total)-len(datadet_test)-60:].values
inputs = inputs.reshape(-1,1)
inputs = sc.transform(inputs)

X_test = []
for i in range(60,80):
    X_test.append(inputs[i-60:i,0])
X_test =  np.array(X_test)

X_test = np.reshape(X_test,(X_test.shape[0],X_test.shape[1],1))
predicted_stock_price = regressor.predict(X_test)
predicted_stock_price = sc.inverse_transform(predicted_stock_price)

plt.plot(real_stock_price,color='red',label = 'real')
plt.plot(predicted_stock_price,color='green',label ='prediction')
plt.xlabel('TIme')
plt.ylabel('Google Stock Price')
plt.show()

ext: py

max_stars_repo_path: Predicting Google Stock Price/rnn.py

max_stars_repo_name: ApurvGude/Mini-Projects

max_issues_repo_path: Predicting Google Stock Price/rnn.py

max_issues_repo_name: ApurvGude/Mini-Projects

max_forks_repo_path: Predicting Google Stock Price/rnn.py

max_forks_repo_name: ApurvGude/Mini-Projects

reason: import numpy


text:
#
# Copyright 2016 The BigDL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import pytest
import numpy as np
import tensorflow as tf
import pandas as pd

from bigdl.chronos.data import TSDataset
from unittest import TestCase

def create_data():
    lookback = 5
    horizon = 1
    def get_data(num_samples):
        values = np.random.randn(num_samples)
        df = pd.DataFrame({'timestep': pd.date_range(start='2010-01-01',
                                                     freq='m',
                                                     periods=num_samples),
                           'value 1': values,
                           'value 2': values,
                           'value 3': values,
                           'value 4': values})
        return df
    tsdata_train = TSDataset.from_pandas(get_data(64),
                                         target_col=['value 1', 'value 2', 'value 3', 'value 4'],
                                         dt_col='timestep',
                                         with_split=False)
    tsdata_test = TSDataset.from_pandas(get_data(16),
                                        target_col=['value 1', 'value 2', 'value 3', 'value 4'],
                                        dt_col='timestep',
                                        with_split=False)
    for tsdata in [tsdata_train, tsdata_test]:
        tsdata.roll(lookback=lookback, horizon=horizon)
    return tsdata_train, tsdata_test

@pytest.mark.skipif(tf.__version__ < '2.0.0', reason="Run only when tf>2.0.0.")
class TestChronosModelMTNetForecaster(TestCase):

    def setUp(self):
        tf.keras.backend.clear_session()

    def tearDown(self):
        pass

    def test_forecast_mtnet(self):
        # TODO hacking to fix a bug
        train_data, test_data = create_data()
        self.x_train, y_train = train_data.to_numpy()
        self.y_train = y_train.reshape(y_train.shape[0], y_train.shape[-1])
        self.x_val, y_val = test_data.to_numpy()
        self.y_val = y_val.reshape(y_val.shape[0], y_val.shape[-1])
        self.x_test, y_test = test_data.to_numpy()
        self.y_test = y_test.reshape(y_test.shape[0], y_test.shape[-1])
        from bigdl.chronos.forecaster.tf.mtnet_forecaster import MTNetForecaster
        model = MTNetForecaster(target_dim=1,
                                feature_dim=self.x_train.shape[-1],
                                long_series_num=4,
                                series_length=1
                                )

        model.fit(data=(self.x_train, y_train),
                  validation_data=(self.x_val, y_val),
                  epochs=2,
                  batch_size=32)
        assert model.evaluate(data=(self.x_test, self.y_test))
        predict_result = model.predict(self.x_test)
        assert predict_result.shape == (self.x_test.shape[0], self.x_test.shape[-1])

if __name__ == "__main__":
    pytest.main([__file__])

max_stars_repo_name: bronzeMe/BigDL

max_issues_repo_name: bronzeMe/BigDL

max_forks_repo_name: bronzeMe/BigDL


text:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
ALEXA Wide Gamut RGB Colourspace
================================

Defines the *ALEXA Wide Gamut RGB* colourspace:

-   :attr:`ALEXA_WIDE_GAMUT_RGB_COLOURSPACE`.

See Also
--------
`RGB Colourspaces IPython Notebook
<http://nbviewer.ipython.org/github/colour-science/colour-ipython/blob/master/notebooks/models/rgb.ipynb>`_  # noqa

References
----------
.. [1]  http://www.arri.com/?eID=registration&file_uid=8026
        (Last accessed 13 April 2014)
"""

from __future__ import division, unicode_literals

import math
import numpy as np

from colour.colorimetry import ILLUMINANTS
from colour.models import RGB_Colourspace
from colour.utilities import CaseInsensitiveMapping

__author__ = 'Colour Developers'
__copyright__ = 'Copyright (C) 2013 - 2014 - Colour Developers'
__license__ = 'New BSD License - http://opensource.org/licenses/BSD-3-Clause'
__maintainer__ = 'Colour Developers'
__email__ = 'colour-science@googlegroups.com'
__status__ = 'Production'

__all__ = ['ALEXA_LOG_C_CURVE_BCL_DATA',
           'ALEXA_LOG_C_CURVE_CONVERSION_DATA',
           'ALEXA_WIDE_GAMUT_RGB_PRIMARIES',
           'ALEXA_WIDE_GAMUT_RGB_WHITEPOINT',
           'ALEXA_WIDE_GAMUT_RGB_TO_XYZ_MATRIX',
           'XYZ_TO_ALEXA_WIDE_GAMUT_RGB_MATRIX',
           'ALEXA_WIDE_GAMUT_RGB_TRANSFER_FUNCTION',
           'ALEXA_WIDE_GAMUT_RGB_INVERSE_TRANSFER_FUNCTION',
           'ALEXA_WIDE_GAMUT_RGB_COLOURSPACE']

ALEXA_LOG_C_CURVE_BCL_DATA = CaseInsensitiveMapping(
    {'SUP 3.x': {
        160: (0.0928, 0.8128),
        200: (0.0928, 0.8341),
        250: (0.0928, 0.8549),
        320: (0.0928, 0.8773),
        400: (0.0928, 0.8968),
        500: (0.0928, 0.9158),
        640: (0.0928, 0.9362),
        800: (0.0928, 0.9539),
        1000: (0.0928, 0.9711),
        1280: (0.0928, 0.9895),
        1600: (0.0928, 1.0000),
        2000: (0.0928, 1.0000),
        2560: (0.0928, 1.0000),
        3200: (0.0928, 1.0000)},
     'SUP 2.x': {
         160: (0.1083, 0.8110),
         200: (0.1115, 0.8320),
         250: (0.1146, 0.8524),
         320: (0.1181, 0.8743),
         400: (0.1213, 0.8935),
         500: (0.1245, 0.9121),
         640: (0.1280, 0.9320),
         800: (0.1311, 0.9494),
         1000: (0.1343, 0.9662),
         1280: (0.1378, 0.9841),
         1600: (0.1409, 0.9997)}})
"""
*ALEXA Log C* curve *Ei, Black, Clipping Level* data.

ALEXA_LOG_C_CURVE_BCL_DATA : dict
    ('SUP 3.x', 'SUP 2.x')
"""

# @formatter:off
ALEXA_LOG_C_CURVE_CONVERSION_DATA = CaseInsensitiveMapping(
    {'SUP 3.x': CaseInsensitiveMapping(
        {'Normalised Sensor Signal': {
            160: (0.004680, 40.0, -0.076072, 0.269036, 0.381991, 42.062665, -0.071569, 0.125266),  # noqa
            200: (0.004597, 50.0, -0.118740, 0.266007, 0.382478, 51.986387, -0.110339, 0.128643),  # noqa
            250: (0.004518, 62.5, -0.171260, 0.262978, 0.382966, 64.243053, -0.158224, 0.132021),  # noqa
            320: (0.004436, 80.0, -0.243808, 0.259627, 0.383508, 81.183335, -0.224409, 0.135761),  # noqa
            400: (0.004369, 100.0, -0.325820, 0.256598, 0.383999, 100.295280, -0.299079, 0.139142),  # noqa
            500: (0.004309, 125.0, -0.427461, 0.253569, 0.384493, 123.889239, -0.391261, 0.142526),  # noqa
            640: (0.004249, 160.0, -0.568709, 0.250219, 0.385040, 156.482680, -0.518605, 0.146271),  # noqa
            800: (0.004201, 200.0, -0.729169, 0.247190, 0.385537, 193.235573, -0.662201, 0.149658),  # noqa
            1000: (0.004160, 250.0, -0.928805, 0.244161, 0.386036, 238.584745, -0.839385, 0.153047),  # noqa
            1280: (0.004120, 320.0, -1.207168, 0.240810, 0.386590, 301.197380, -1.084020, 0.156799),  # noqa
            1600: (0.004088, 400.0, -1.524256, 0.237781, 0.387093, 371.761171, -1.359723, 0.160192)},  # noqa
         'Linear Scene Exposure Factor': {
             160: (0.005561, 5.555556, 0.080216, 0.269036, 0.381991, 5.842037, 0.092778, 0.125266),  # noqa
             200: (0.006208, 5.555556, 0.076621, 0.266007, 0.382478, 5.776265, 0.092782, 0.128643),  # noqa
             250: (0.006871, 5.555556, 0.072941, 0.262978, 0.382966, 5.710494, 0.092786, 0.132021),  # noqa
             320: (0.007622, 5.555556, 0.068768, 0.259627, 0.383508, 5.637732, 0.092791, 0.135761),  # noqa
             400: (0.008318, 5.555556, 0.064901, 0.256598, 0.383999, 5.571960, 0.092795, 0.139142),  # noqa
             500: (0.009031, 5.555556, 0.060939, 0.253569, 0.384493, 5.506188, 0.092800, 0.142526),  # noqa
             640: (0.009840, 5.555556, 0.056443, 0.250219, 0.385040, 5.433426, 0.092805, 0.146271),  # noqa
             800: (0.010591, 5.555556, 0.052272, 0.247190, 0.385537, 5.367655, 0.092809, 0.149658),  # noqa
             1000: (0.011361, 5.555556, 0.047996, 0.244161, 0.386036, 5.301883, 0.092814, 0.153047),  # noqa
             1280: (0.012235, 5.555556, 0.043137, 0.240810, 0.386590, 5.229121, 0.092819, 0.156799),  # noqa
             1600: (0.013047, 5.555556, 0.038625, 0.237781, 0.387093, 5.163350, 0.092824, 0.16019)}}),  # noqa
     'SUP 2.x': CaseInsensitiveMapping(
         {'Normalised Sensor Signal': {
             160: (0.003907, 36.439829, -0.053366, 0.269035, 0.391007, 45.593473, -0.069772, 0.10836),  # noqa
             200: (0.003907, 45.549786, -0.088959, 0.266007, 0.391007, 55.709581, -0.106114, 0.11154),  # noqa
             250: (0.003907, 56.937232, -0.133449, 0.262978, 0.391007, 67.887153, -0.150510, 0.11472),  # noqa
             320: (0.003907, 72.879657, -0.195737, 0.259627, 0.391007, 84.167616, -0.210597, 0.11824),  # noqa
             400: (0.003907, 91.099572, -0.266922, 0.256598, 0.391007, 101.811426, -0.276349, 0.12142),  # noqa
             500: (0.003907, 113.874465, -0.355903, 0.253569, 0.391007, 122.608379, -0.354421, 0.12461),  # noqa
             640: (0.003907, 145.759315, -0.480477, 0.250218, 0.391007, 149.703304, -0.456760, 0.12813),  # noqa
             800: (0.003907, 182.199144, -0.622848, 0.247189, 0.391007, 178.216873, -0.564981, 0.13131),  # noqa
             1000: (0.003907, 227.748930, -0.800811, 0.244161, 0.391007, 210.785040, -0.689043, 0.13449),  # noqa
             1280: (0.003907, 291.518630, -1.049959, 0.240810, 0.391007, 251.689459, -0.845336, 0.13801),  # noqa
             1600: (0.003907, 364.398287, -1.334700, 0.237781, 0.391007, 293.073575, -1.003841, 0.14119)},  # noqa
          'Linear Scene Exposure Factor': {
              160: (0.000000, 5.061087, 0.089004, 0.269035, 0.391007, 6.332427, 0.108361, 0.108361),  # noqa
              200: (0.000000, 5.061087, 0.089004, 0.266007, 0.391007, 6.189953, 0.111543, 0.111543),  # noqa
              250: (0.000000, 5.061087, 0.089004, 0.262978, 0.391007, 6.034414, 0.114725, 0.114725),  # noqa
              320: (0.000000, 5.061087, 0.089004, 0.259627, 0.391007, 5.844973, 0.118246, 0.118246),  # noqa
              400: (0.000000, 5.061087, 0.089004, 0.256598, 0.391007, 5.656190, 0.121428, 0.121428),  # noqa
              500: (0.000000, 5.061087, 0.089004, 0.253569, 0.391007, 5.449261, 0.124610, 0.124610),  # noqa
              640: (0.000000, 5.061087, 0.089004, 0.250218, 0.391007, 5.198031, 0.128130, 0.128130),  # noqa
              800: (0.000000, 5.061087, 0.089004, 0.247189, 0.391007, 4.950469, 0.131313, 0.131313),  # noqa
              1000: (0.000000, 5.061087, 0.089004, 0.244161, 0.391007, 4.684112, 0.134495, 0.134495),  # noqa
              1280: (0.000000, 5.061087, 0.089004, 0.240810, 0.391007, 4.369609, 0.138015, 0.138015),  # noqa
              1600: (0.000000, 5.061087, 0.089004, 0.237781, 0.391007, 4.070466, 0.141197, 0.14119)}})})  # noqa
"""
*ALEXA Log C* curve conversion data between signal and linear scene exposure
factor for *SUP 3.x* and signal and normalized sensor signal for *SUP 2.x*.

ALEXA_LOG_C_CURVE_CONVERSION_DATA : dict
    ('SUP 3.x', 'SUP 2.x')
"""
# @formatter:on

ALEXA_WIDE_GAMUT_RGB_PRIMARIES = np.array(
    [[0.6840, 0.3130],
     [0.2210, 0.8480],
     [0.0861, -0.1020]])
"""
*ALEXA Wide Gamut RGB* colourspace primaries.

ALEXA_WIDE_GAMUT_RGB_PRIMARIES : ndarray, (3, 2)
"""

ALEXA_WIDE_GAMUT_RGB_WHITEPOINT = ILLUMINANTS.get(
    'CIE 1931 2 Degree Standard Observer').get('D65')
"""
*ALEXA Wide Gamut RGB* colourspace whitepoint.

ALEXA_WIDE_GAMUT_RGB_WHITEPOINT : tuple
"""

ALEXA_WIDE_GAMUT_RGB_TO_XYZ_MATRIX = np.array(
    [[0.638008, 0.214704, 0.097744],
     [0.291954, 0.823841, -0.115795],
     [0.002798, -0.067034, 1.153294]])
"""
*ALEXA Wide Gamut RGB* colourspace to *CIE XYZ* colourspace matrix.

ALEXA_WIDE_GAMUT_RGB_TO_XYZ_MATRIX : array_like, (3, 3)
"""

XYZ_TO_ALEXA_WIDE_GAMUT_RGB_MATRIX = np.linalg.inv(
    ALEXA_WIDE_GAMUT_RGB_TO_XYZ_MATRIX)
"""
*CIE XYZ* colourspace to *ALEXA Wide Gamut RGB* colourspace matrix.

XYZ_TO_ALEXA_WIDE_GAMUT_RGB_MATRIX : array_like, (3, 3)
"""

def _alexa_wide_gamut_rgb_transfer_function(
        value,
        firmware='SUP 3.x',
        method='Linear Scene Exposure Factor',
        EI=800):
    """
    Defines the *ALEXA Wide Gamut value* colourspace transfer function.

    Parameters
    ----------
    value : numeric
        value.
    firmware : unicode,
        ('SUP 2.x', 'SUP 3.x')
        Alexa firmware version.
    method : unicode, optional
        ('Linear Scene Exposure Factor', 'Normalised Sensor Signal')
        Conversion method.
    EI : int,  optional
        Ei.

    Returns
    -------
    numeric
        Companded value.
    """

    cut, a, b, c, d, e, f, ecutf = ALEXA_LOG_C_CURVE_CONVERSION_DATA.get(
        firmware).get(method).get(EI)

    return c * math.log10(a * value + b) + d if value > cut else ecutf

def _alexa_wide_gamut_rgb_inverse_transfer_function(
        value,
        firmware='SUP 3.x',
        method='Linear Scene Exposure Factor',
        EI=800):
    """
    Defines the *ALEXA Wide Gamut value* colourspace inverse transfer function.

    Parameters
    ----------
    value : numeric
        value.
    firmware : unicode,
        ('SUP 2.x', 'SUP 3.x')
        Alexa firmware version.
    method : unicode,  optional
        ('Linear Scene Exposure Factor', 'Normalised Sensor Signal')
        Conversion method.
    EI : int,  optional
        Ei.

    Returns
    -------
    numeric
        Companded value.
    """

    cut, a, b, c, d, e, f, ecutf = (
        ALEXA_LOG_C_CURVE_CONVERSION_DATA.get(firmware).get(method).get(EI))

    return ((math.pow(10, (value - d) / c) - b) / a
            if value > ecutf else
            (value - f) / e)

ALEXA_WIDE_GAMUT_RGB_TRANSFER_FUNCTION = (
    _alexa_wide_gamut_rgb_transfer_function)
"""
Transfer function from linear to *ALEXA Wide Gamut RGB* colourspace.

ALEXA_WIDE_GAMUT_RGB_TRANSFER_FUNCTION : object
"""

ALEXA_WIDE_GAMUT_RGB_INVERSE_TRANSFER_FUNCTION = (
    _alexa_wide_gamut_rgb_inverse_transfer_function)
"""
Inverse transfer function from *ALEXA Wide Gamut RGB* colourspace to linear.

ALEXA_WIDE_GAMUT_RGB_INVERSE_TRANSFER_FUNCTION : object
"""

ALEXA_WIDE_GAMUT_RGB_COLOURSPACE = RGB_Colourspace(
    'ALEXA Wide Gamut RGB',
    ALEXA_WIDE_GAMUT_RGB_PRIMARIES,
    ALEXA_WIDE_GAMUT_RGB_WHITEPOINT,
    ALEXA_WIDE_GAMUT_RGB_TO_XYZ_MATRIX,
    XYZ_TO_ALEXA_WIDE_GAMUT_RGB_MATRIX,
    ALEXA_WIDE_GAMUT_RGB_TRANSFER_FUNCTION,
    ALEXA_WIDE_GAMUT_RGB_INVERSE_TRANSFER_FUNCTION)
"""
*ALEXA Wide Gamut RGB* colourspace.

ALEXA_WIDE_GAMUT_RGB_COLOURSPACE : RGB_Colourspace
"""

max_stars_repo_name: canavandl/colour

max_issues_repo_name: canavandl/colour

max_forks_repo_name: canavandl/colour


text:
from numpy import pi, isclose

from pyroll.core import RoundGroove

def test_round():
    g = RoundGroove(depth=15.55, r1=2, r2=15.8)

    assert isclose(g.usable_width, 31.79180677)
    assert isclose(g.alpha1, 82.738129 / 180 * pi)
    assert isclose(g.alpha2, 82.738129 / 180 * pi)
    assert isclose(g.z1, 17.65722232)

max_stars_repo_name: pyroll-project/pyroll-core

max_issues_repo_name: pyroll-project/pyroll-core

max_forks_repo_name: pyroll-project/pyroll-core

reason: from numpy