<commit_before>#!/usr/bin/env python

###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# 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.
###############################################################################
"""
Control Planning Analyzer
"""
import argparse
import math
import sys
import threading
import time

import matplotlib
import matplotlib.pyplot as plt
import numpy
import rosbag
import rospy
import tf
import tkFileDialog
from matplotlib import patches
from matplotlib import lines
from std_msgs.msg import String

from modules.localization.proto import localization_pb2
from modules.canbus.proto import chassis_pb2
from modules.planning.proto import planning_pb2
from modules.control.proto import control_cmd_pb2

class ControlInfo(object):
    """
    ControlInfo Class
    """

    def __init__(self, axarr):
        self.throttlecmd = []
        self.throttlefbk = []
        self.brakecmd = []
        self.brakefbk = []
        self.steercmd = []
        self.steerfbk = []
        self.speed = []
        self.curvature = []
        self.imuright = []
        self.imuforward = []
        self.imuup = []
        self.controltime = []
        self.planningtime = []
        self.localizationtime = []
        self.canbustime = []

        self.acceleration_lookup = []
        self.speed_lookup = []
        self.acc_open = []
        self.acc_close = []
        self.station_error = []
        self.speed_error = []

        self.heading_error = []
        self.lateral_error = []
        self.heading_error_rate = []
        self.lateral_error_rate = []

        self.target_speed = []
        self.target_curvature = []
        self.target_acceleration = []
        self.target_heading = []
        self.target_time = []

        self.driving_mode = 0
        self.mode_time = []

        self.ax = axarr

        self.planningavailable = False

        self.lock = threading.Lock()

    def callback_planning(self, entity):
        """
        New Planning Trajectory
        """
        basetime = entity.header.timestamp_sec
        numpoints = len(entity.adc_trajectory_point)
        with self.lock:
            self.pointx = numpy.zeros(numpoints)
            self.pointy = numpy.zeros(numpoints)
            self.pointspeed = numpy.zeros(numpoints)
            self.pointtime = numpy.zeros(numpoints)
            self.pointtheta = numpy.zeros(numpoints)
            self.pointcurvature = numpy.zeros(numpoints)
            self.pointacceleration = numpy.zeros(numpoints)

            for idx in range(numpoints):
                self.pointx[idx] = entity.adc_trajectory_point[idx].x
                self.pointy[idx] = entity.adc_trajectory_point[idx].y
                self.pointspeed[idx] = entity.adc_trajectory_point[idx].speed
                self.pointtheta[idx] = entity.adc_trajectory_point[idx].theta
                self.pointcurvature[idx] = entity.adc_trajectory_point[
                    idx].curvature
                self.pointacceleration[idx] = entity.adc_trajectory_point[
                    idx].acceleration_s
                self.pointtime[
                    idx] = entity.adc_trajectory_point[idx].relative_time + basetime

        if numpoints == 0:
            self.planningavailable = False
        else:
            self.planningavailable = True

    def callback_canbus(self, entity):
        """
        New Canbus
        """
        self.throttlefbk.append(entity.throttle_percentage)
        self.brakefbk.append(entity.brake_percentage)
        self.steerfbk.append(entity.steering_percentage)
        self.speed.append(entity.speed_mps)
        self.canbustime.append(entity.header.timestamp_sec)

        if entity.driving_mode == chassis_pb2.Chassis.COMPLETE_AUTO_DRIVE:
            if self.driving_mode == 0:
                self.mode_time.append(entity.header.timestamp_sec)
                self.driving_mode = 1
        elif self.driving_mode == 1:
            self.mode_time.append(entity.header.timestamp_sec)
            self.driving_mode = 0

    def callback_localization(self, entity):
        """
        New Localization
        """
        self.imuright.append(entity.pose.linear_acceleration_vrf.x)
        self.imuforward.append(entity.pose.linear_acceleration_vrf.y)
        self.imuup.append(entity.pose.linear_acceleration_vrf.z)
        self.localizationtime.append(entity.header.timestamp_sec)

    def callback_control(self, entity):
        """
        New Control Command
        """
        self.throttlecmd.append(entity.throttle)
        self.brakecmd.append(entity.brake)
        self.steercmd.append(entity.steering_target)
        self.controltime.append(entity.header.timestamp_sec)

        self.acceleration_lookup.append(
            entity.debug.simple_lon_debug.acceleration_lookup)
        self.speed_lookup.append(entity.debug.simple_lon_debug.speed_lookup)
        self.acc_open.append(
            entity.debug.simple_lon_debug.preview_acceleration_reference)
        self.acc_close.append(
            entity.debug.simple_lon_debug.acceleration_cmd_closeloop)
        self.station_error.append(entity.debug.simple_lon_debug.station_error)
        self.speed_error.append(entity.debug.simple_lon_debug.speed_error)

        self.curvature.append(entity.debug.simple_lat_debug.curvature)
        self.heading_error.append(entity.debug.simple_lat_debug.heading_error)
        self.lateral_error.append(entity.debug.simple_lat_debug.lateral_error)
        self.heading_error_rate.append(
            entity.debug.simple_lat_debug.heading_error_rate)
        self.lateral_error_rate.append(
            entity.debug.simple_lat_debug.lateral_error_rate)

        with self.lock:
            if self.planningavailable:
                self.target_speed.append(
                    numpy.interp(entity.header.timestamp_sec, self.pointtime,
                                 self.pointspeed))
                self.target_curvature.append(
                    numpy.interp(entity.header.timestamp_sec, self.pointtime,
                                 self.pointcurvature))
                self.target_acceleration.append(
                    numpy.interp(entity.header.timestamp_sec, self.pointtime,
                                 self.pointacceleration))
                self.target_heading.append(
                    numpy.interp(entity.header.timestamp_sec, self.pointtime,
                                 self.pointtheta))
                self.target_time.append(entity.header.timestamp_sec)

    def long(self):
        """

        """
        print "Showing Longitudinal"
        for loc, ax in numpy.ndenumerate(self.ax):
            ax.clear()
        self.ax[0, 0].plot(
            self.canbustime, self.throttlefbk, label='Throttle Feedback')
        self.ax[0, 0].plot(
            self.controltime, self.throttlecmd, label='Throttle Command')
        self.ax[0, 0].plot(
            self.canbustime, self.brakefbk, label='Brake Feedback')
        self.ax[0, 0].plot(
            self.controltime, self.brakecmd, label='Brake Command')
        self.ax[0, 0].legend(fontsize='medium')
        self.ax[0, 0].grid(True)
        self.ax[0, 0].set_title('Throttle Brake Info')
        self.ax[0, 0].set_xlabel('Time')

        self.ax[0, 1].plot(
            self.speed_lookup, self.acceleration_lookup, label='Table Lookup')
        self.ax[0, 1].plot(
            self.target_speed, self.target_acceleration, label='Target')
        self.ax[0, 1].legend(fontsize='medium')
        self.ax[0, 1].grid(True)
        self.ax[0, 1].set_title('Calibration Lookup')
        self.ax[0, 1].set_xlabel('Speed')
        self.ax[0, 1].set_ylabel('Acceleration')

        self.ax[1, 0].plot(self.canbustime, self.speed, label='Vehicle Speed')
        self.ax[1, 0].plot(
            self.target_time, self.target_speed, label='Target Speed')
        self.ax[1, 0].plot(
            self.target_time, self.target_acceleration, label='Target Acc')
        self.ax[1, 0].plot(
            self.localizationtime, self.imuforward, label='IMU Forward')
        self.ax[1, 0].legend(fontsize='medium')
        self.ax[1, 0].grid(True)
        self.ax[1, 0].set_title('Speed Info')
        self.ax[1, 0].set_xlabel('Time')

        self.ax[1, 1].plot(
            self.controltime, self.acceleration_lookup, label='Lookup Acc')
        self.ax[1, 1].plot(self.controltime, self.acc_open, label='Acc Open')
        self.ax[1, 1].plot(self.controltime, self.acc_close, label='Acc Close')
        self.ax[1, 1].plot(
            self.controltime, self.station_error, label='station_error')
        self.ax[1, 1].plot(
            self.controltime, self.speed_error, label='speed_error')
        self.ax[1, 1].legend(fontsize='medium')
        self.ax[1, 1].grid(True)
        self.ax[1, 1].set_title('IMU Info')
        self.ax[1, 1].set_xlabel('Time')

        if len(self.mode_time) % 2 == 1:
            self.mode_time.append(self.controltime[-1])
        for i in range(0, len(self.mode_time), 2):
            self.ax[0, 0].axvspan(
                self.mode_time[i], self.mode_time[i + 1], fc='0.1', alpha=0.1)
            self.ax[1, 0].axvspan(
                self.mode_time[i], self.mode_time[i + 1], fc='0.1', alpha=0.1)
            self.ax[1, 1].axvspan(
                self.mode_time[i], self.mode_time[i + 1], fc='0.1', alpha=0.1)
        plt.draw()

    def lat(self):
        """
        Plot everything in time domain
        """
        print "Showing Lateral"
        for loc, ax in numpy.ndenumerate(self.ax):
            ax.clear()
        self.ax[0, 0].plot(
            self.canbustime, self.steerfbk, label='Steering Feedback')
        self.ax[0, 0].plot(
            self.controltime, self.steercmd, label='Steering Command')
        self.ax[0, 0].plot(self.controltime, self.curvature, label='Curvature')
        self.ax[0, 0].legend(fontsize='medium')
        self.ax[0, 0].grid(True)
        self.ax[0, 0].set_title('Steering Info')
        self.ax[0, 0].set_xlabel('Time')
        """
        self.ax[0, 1].legend(fontsize = 'medium')
        self.ax[0, 1].grid(True)
        self.ax[0, 1].set_title('Calibration Lookup')
        self.ax[0, 1].set_xlabel('Speed')
        self.ax[0, 1].set_ylabel('Acceleration')
        """

        self.ax[1, 0].plot(
            self.controltime, self.heading_error, label='heading_error')
        self.ax[1, 0].plot(
            self.controltime, self.lateral_error, label='lateral_error')
        self.ax[1, 0].legend(fontsize='medium')
        self.ax[1, 0].grid(True)
        self.ax[1, 0].set_title('Error Info')
        self.ax[1, 0].set_xlabel('Time')

        self.ax[1, 1].plot(
            self.controltime,
            self.heading_error_rate,
            label='heading_error_rate')
        self.ax[1, 1].plot(
            self.controltime,
            self.lateral_error_rate,
            label='lateral_error_rate')
        self.ax[1, 1].legend(fontsize='medium')
        self.ax[1, 1].grid(True)
        self.ax[1, 1].set_title('IMU Info')
        self.ax[1, 1].set_xlabel('Time')

        if len(self.mode_time) % 2 == 1:
            self.mode_time.append(self.controltime[-1])
        for i in range(0, len(self.mode_time), 2):
            self.ax[0, 0].axvspan(
                self.mode_time[i], self.mode_time[i + 1], fc='0.1', alpha=0.1)
            self.ax[1, 0].axvspan(
                self.mode_time[i], self.mode_time[i + 1], fc='0.1', alpha=0.1)
            self.ax[1, 1].axvspan(
                self.mode_time[i], self.mode_time[i + 1], fc='0.1', alpha=0.1)
        plt.draw()

    def press(self, event):
        """
        Keyboard events during plotting
        """
        if event.key == 'q' or event.key == 'Q':
            plt.close('all')
        if event.key == 'a' or event.key == 'A':
            self.long()
        if event.key == 'z' or event.key == 'Z':
            self.lat()

def main():
    """
    Main function
    """
    parser = argparse.ArgumentParser(
        description='Process and analyze control and planning data')
    parser.add_argument('--bag', help='Use Rosbag? (t/F)', default='F')
    args = parser.parse_args()

    rospy.init_node('control_info', anonymous=True)

    fig, axarr = plt.subplots(2, 2)
    plt.tight_layout()
    axarr[0, 0].get_shared_x_axes().join(axarr[0, 0], axarr[1, 0])
    axarr[1, 1].get_shared_x_axes().join(axarr[0, 0], axarr[1, 1])

    controlinfo = ControlInfo(axarr)

    if args.bag:
        file_path = args.bag
        bag = rosbag.Bag(file_path)
        for topic, msg, t in bag.read_messages(topics=[
                '/apollo/control', '/apollo/planning',
                '/apollo/localization/pose', '/apollo/canbus/chassis'
        ]):
            print t.to_sec(), topic
            if topic == "/apollo/localization/pose":
                controlinfo.callback_localization(msg)
            elif topic == "/apollo/planning":
                controlinfo.callback_planning(msg)
            elif topic == "/apollo/control":
                controlinfo.callback_control(msg)
            elif topic == "/apollo/canbus/chassis":
                controlinfo.callback_canbus(msg)
        print "Done reading the file"
        bag.close()

    else:
        planningsub = rospy.Subscriber('/apollo/planning',
                                       planning_pb2.ADCTrajectory,
                                       controlinfo.callback_planning)
        localizationsub = rospy.Subscriber(
            '/apollo/localization/pose', localization_pb2.LocalizationEstimate,
            controlinfo.callback_localization)
        controlsub = rospy.Subscriber('/apollo/control',
                                      control_cmd_pb2.ControlCommand,
                                      controlinfo.callback_control)
        canbussub = rospy.Subscriber('/apollo/canbus/chassis',
                                     chassis_pb2.Chassis,
                                     controlinfo.callback_canbus)
        controlinfo.update_subs(planningsub, localizationsub, controlsub,
                                canbussub, axarr)

        raw_input("Press Enter To Stop")

        planningsub.unregister()
        localizationsub.unregister()
        controlsub.unregister()
        canbussub.unregister()

        rospy.sleep(0.5)

    mng = plt.get_current_fig_manager()
    mng.full_screen_toggle()
    controlinfo.long()
    fig.canvas.mpl_connect('key_press_event', controlinfo.press)
    plt.show()

if __name__ == '__main__':
    main()
<commit_msg>control: fix control_info's problem problem. Fix #309<commit_after>#!/usr/bin/env python

###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# 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.
###############################################################################
"""
Control Planning Analyzer
"""
import argparse
import math
import sys
import threading
import time

import matplotlib
import matplotlib.pyplot as plt
import numpy
import rosbag
import rospy
import tf
import tkFileDialog
from matplotlib import patches
from matplotlib import lines
from std_msgs.msg import String

from modules.localization.proto import localization_pb2
from modules.canbus.proto import chassis_pb2
from modules.planning.proto import planning_pb2
from modules.control.proto import control_cmd_pb2

class ControlInfo(object):
    """
    ControlInfo Class
    """

    def __init__(self, axarr):
        self.throttlecmd = []
        self.throttlefbk = []
        self.brakecmd = []
        self.brakefbk = []
        self.steercmd = []
        self.steerfbk = []
        self.speed = []
        self.curvature = []
        self.imuright = []
        self.imuforward = []
        self.imuup = []
        self.controltime = []
        self.planningtime = []
        self.localizationtime = []
        self.canbustime = []

        self.acceleration_lookup = []
        self.speed_lookup = []
        self.acc_open = []
        self.acc_close = []
        self.station_error = []
        self.speed_error = []

        self.heading_error = []
        self.lateral_error = []
        self.heading_error_rate = []
        self.lateral_error_rate = []

        self.target_speed = []
        self.target_curvature = []
        self.target_acceleration = []
        self.target_heading = []
        self.target_time = []

        self.driving_mode = 0
        self.mode_time = []

        self.ax = axarr

        self.planningavailable = False

        self.lock = threading.Lock()

    def callback_planning(self, entity):
        """
        New Planning Trajectory
        """
        basetime = entity.header.timestamp_sec
        numpoints = len(entity.adc_trajectory_point)
        with self.lock:
            self.pointx = numpy.zeros(numpoints)
            self.pointy = numpy.zeros(numpoints)
            self.pointspeed = numpy.zeros(numpoints)
            self.pointtime = numpy.zeros(numpoints)
            self.pointtheta = numpy.zeros(numpoints)
            self.pointcurvature = numpy.zeros(numpoints)
            self.pointacceleration = numpy.zeros(numpoints)

            for idx in range(numpoints):
                self.pointx[idx] = entity.adc_trajectory_point[idx].x
                self.pointy[idx] = entity.adc_trajectory_point[idx].y
                self.pointspeed[idx] = entity.adc_trajectory_point[idx].speed
                self.pointtheta[idx] = entity.adc_trajectory_point[idx].theta
                self.pointcurvature[idx] = entity.adc_trajectory_point[
                    idx].curvature
                self.pointacceleration[idx] = entity.adc_trajectory_point[
                    idx].acceleration_s
                self.pointtime[
                    idx] = entity.adc_trajectory_point[idx].relative_time + basetime

        if numpoints == 0:
            self.planningavailable = False
        else:
            self.planningavailable = True

    def callback_canbus(self, entity):
        """
        New Canbus
        """
        self.throttlefbk.append(entity.throttle_percentage)
        self.brakefbk.append(entity.brake_percentage)
        self.steerfbk.append(entity.steering_percentage)
        self.speed.append(entity.speed_mps)
        self.canbustime.append(entity.header.timestamp_sec)

        if entity.driving_mode == chassis_pb2.Chassis.COMPLETE_AUTO_DRIVE:
            if self.driving_mode == 0:
                self.mode_time.append(entity.header.timestamp_sec)
                self.driving_mode = 1
        elif self.driving_mode == 1:
            self.mode_time.append(entity.header.timestamp_sec)
            self.driving_mode = 0

    def callback_localization(self, entity):
        """
        New Localization
        """
        self.imuright.append(entity.pose.linear_acceleration_vrf.x)
        self.imuforward.append(entity.pose.linear_acceleration_vrf.y)
        self.imuup.append(entity.pose.linear_acceleration_vrf.z)
        self.localizationtime.append(entity.header.timestamp_sec)

    def callback_control(self, entity):
        """
        New Control Command
        """
        self.throttlecmd.append(entity.throttle)
        self.brakecmd.append(entity.brake)
        self.steercmd.append(entity.steering_target)
        self.controltime.append(entity.header.timestamp_sec)

        self.acceleration_lookup.append(
            entity.debug.simple_lon_debug.acceleration_lookup)
        self.speed_lookup.append(entity.debug.simple_lon_debug.speed_lookup)
        self.acc_open.append(
            entity.debug.simple_lon_debug.preview_acceleration_reference)
        self.acc_close.append(
            entity.debug.simple_lon_debug.acceleration_cmd_closeloop)
        self.station_error.append(entity.debug.simple_lon_debug.station_error)
        self.speed_error.append(entity.debug.simple_lon_debug.speed_error)

        self.curvature.append(entity.debug.simple_lat_debug.curvature)
        self.heading_error.append(entity.debug.simple_lat_debug.heading_error)
        self.lateral_error.append(entity.debug.simple_lat_debug.lateral_error)
        self.heading_error_rate.append(
            entity.debug.simple_lat_debug.heading_error_rate)
        self.lateral_error_rate.append(
            entity.debug.simple_lat_debug.lateral_error_rate)

        with self.lock:
            if self.planningavailable:
                self.target_speed.append(
                    numpy.interp(entity.header.timestamp_sec, self.pointtime,
                                 self.pointspeed))
                self.target_curvature.append(
                    numpy.interp(entity.header.timestamp_sec, self.pointtime,
                                 self.pointcurvature))
                self.target_acceleration.append(
                    numpy.interp(entity.header.timestamp_sec, self.pointtime,
                                 self.pointacceleration))
                self.target_heading.append(
                    numpy.interp(entity.header.timestamp_sec, self.pointtime,
                                 self.pointtheta))
                self.target_time.append(entity.header.timestamp_sec)

    def longitudinal(self):
        """
        Showing Longitudinal
        """
        for loc, ax in numpy.ndenumerate(self.ax):
            ax.clear()
        self.ax[0, 0].plot(
            self.canbustime, self.throttlefbk, label='Throttle Feedback')
        self.ax[0, 0].plot(
            self.controltime, self.throttlecmd, label='Throttle Command')
        self.ax[0, 0].plot(
            self.canbustime, self.brakefbk, label='Brake Feedback')
        self.ax[0, 0].plot(
            self.controltime, self.brakecmd, label='Brake Command')
        self.ax[0, 0].legend(fontsize='medium')
        self.ax[0, 0].grid(True)
        self.ax[0, 0].set_title('Throttle Brake Info')
        self.ax[0, 0].set_xlabel('Time')

        self.ax[0, 1].plot(
            self.speed_lookup, self.acceleration_lookup, label='Table Lookup')
        self.ax[0, 1].plot(
            self.target_speed, self.target_acceleration, label='Target')
        self.ax[0, 1].legend(fontsize='medium')
        self.ax[0, 1].grid(True)
        self.ax[0, 1].set_title('Calibration Lookup')
        self.ax[0, 1].set_xlabel('Speed')
        self.ax[0, 1].set_ylabel('Acceleration')

        self.ax[1, 0].plot(self.canbustime, self.speed, label='Vehicle Speed')
        self.ax[1, 0].plot(
            self.target_time, self.target_speed, label='Target Speed')
        self.ax[1, 0].plot(
            self.target_time, self.target_acceleration, label='Target Acc')
        self.ax[1, 0].plot(
            self.localizationtime, self.imuforward, label='IMU Forward')
        self.ax[1, 0].legend(fontsize='medium')
        self.ax[1, 0].grid(True)
        self.ax[1, 0].set_title('Speed Info')
        self.ax[1, 0].set_xlabel('Time')

        self.ax[1, 1].plot(
            self.controltime, self.acceleration_lookup, label='Lookup Acc')
        self.ax[1, 1].plot(self.controltime, self.acc_open, label='Acc Open')
        self.ax[1, 1].plot(self.controltime, self.acc_close, label='Acc Close')
        self.ax[1, 1].plot(
            self.controltime, self.station_error, label='station_error')
        self.ax[1, 1].plot(
            self.controltime, self.speed_error, label='speed_error')
        self.ax[1, 1].legend(fontsize='medium')
        self.ax[1, 1].grid(True)
        self.ax[1, 1].set_title('IMU Info')
        self.ax[1, 1].set_xlabel('Time')

        if len(self.mode_time) % 2 == 1:
            self.mode_time.append(self.controltime[-1])
        for i in range(0, len(self.mode_time), 2):
            self.ax[0, 0].axvspan(
                self.mode_time[i], self.mode_time[i + 1], fc='0.1', alpha=0.1)
            self.ax[1, 0].axvspan(
                self.mode_time[i], self.mode_time[i + 1], fc='0.1', alpha=0.1)
            self.ax[1, 1].axvspan(
                self.mode_time[i], self.mode_time[i + 1], fc='0.1', alpha=0.1)
        plt.draw()

    def lateral(self):
        """
        Plot everything in time domain
        """
        print "Showing Lateral"
        for loc, ax in numpy.ndenumerate(self.ax):
            ax.clear()
        self.ax[0, 0].plot(
            self.canbustime, self.steerfbk, label='Steering Feedback')
        self.ax[0, 0].plot(
            self.controltime, self.steercmd, label='Steering Command')
        self.ax[0, 0].plot(self.controltime, self.curvature, label='Curvature')
        self.ax[0, 0].legend(fontsize='medium')
        self.ax[0, 0].grid(True)
        self.ax[0, 0].set_title('Steering Info')
        self.ax[0, 0].set_xlabel('Time')
        """
        self.ax[0, 1].legend(fontsize = 'medium')
        self.ax[0, 1].grid(True)
        self.ax[0, 1].set_title('Calibration Lookup')
        self.ax[0, 1].set_xlabel('Speed')
        self.ax[0, 1].set_ylabel('Acceleration')
        """

        self.ax[1, 0].plot(
            self.controltime, self.heading_error, label='heading_error')
        self.ax[1, 0].plot(
            self.controltime, self.lateral_error, label='lateral_error')
        self.ax[1, 0].legend(fontsize='medium')
        self.ax[1, 0].grid(True)
        self.ax[1, 0].set_title('Error Info')
        self.ax[1, 0].set_xlabel('Time')

        self.ax[1, 1].plot(
            self.controltime,
            self.heading_error_rate,
            label='heading_error_rate')
        self.ax[1, 1].plot(
            self.controltime,
            self.lateral_error_rate,
            label='lateral_error_rate')
        self.ax[1, 1].legend(fontsize='medium')
        self.ax[1, 1].grid(True)
        self.ax[1, 1].set_title('IMU Info')
        self.ax[1, 1].set_xlabel('Time')

        if len(self.mode_time) % 2 == 1:
            self.mode_time.append(self.controltime[-1])
        for i in range(0, len(self.mode_time), 2):
            self.ax[0, 0].axvspan(
                self.mode_time[i], self.mode_time[i + 1], fc='0.1', alpha=0.1)
            self.ax[1, 0].axvspan(
                self.mode_time[i], self.mode_time[i + 1], fc='0.1', alpha=0.1)
            self.ax[1, 1].axvspan(
                self.mode_time[i], self.mode_time[i + 1], fc='0.1', alpha=0.1)
        plt.draw()

    def press(self, event):
        """
        Keyboard events during plotting
        """
        if event.key == 'q' or event.key == 'Q':
            plt.close('all')
        if event.key == 'a' or event.key == 'A':
            self.longitutidinal()
        if event.key == 'z' or event.key == 'Z':
            self.lateral()

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description='Process and analyze control and planning data')
    parser.add_argument('--bag', type=str, help='use Rosbag')
    args = parser.parse_args()

    rospy.init_node('control_info', anonymous=True)

    fig, axarr = plt.subplots(2, 2)
    plt.tight_layout()
    axarr[0, 0].get_shared_x_axes().join(axarr[0, 0], axarr[1, 0])
    axarr[1, 1].get_shared_x_axes().join(axarr[0, 0], axarr[1, 1])

    controlinfo = ControlInfo(axarr)

    if args.bag:
        file_path = args.bag
        bag = rosbag.Bag(file_path)
        for topic, msg, t in bag.read_messages(topics=[
                '/apollo/control', '/apollo/planning',
                '/apollo/localization/pose', '/apollo/canbus/chassis'
        ]):
            print t.to_sec(), topic
            if topic == "/apollo/localization/pose":
                controlinfo.callback_localization(msg)
            elif topic == "/apollo/planning":
                controlinfo.callback_planning(msg)
            elif topic == "/apollo/control":
                controlinfo.callback_control(msg)
            elif topic == "/apollo/canbus/chassis":
                controlinfo.callback_canbus(msg)
        print "Done reading the file"
        bag.close()

    else:
        planningsub = rospy.Subscriber('/apollo/planning',
                                       planning_pb2.ADCTrajectory,
                                       controlinfo.callback_planning)
        localizationsub = rospy.Subscriber(
            '/apollo/localization/pose', localization_pb2.LocalizationEstimate,
            controlinfo.callback_localization)
        controlsub = rospy.Subscriber('/apollo/control',
                                      control_cmd_pb2.ControlCommand,
                                      controlinfo.callback_control)
        canbussub = rospy.Subscriber('/apollo/canbus/chassis',
                                     chassis_pb2.Chassis,
                                     controlinfo.callback_canbus)
        raw_input("Press Enter To Stop")

        planningsub.unregister()
        localizationsub.unregister()
        controlsub.unregister()
        canbussub.unregister()

        rospy.sleep(0.5)

    mng = plt.get_current_fig_manager()
    controlinfo.longitudinal()
    fig.canvas.mpl_connect('key_press_event', controlinfo.press)
    plt.show()
<|endoftext|>


<commit_before># coding=utf-8
from django.utils.encoding import python_2_unicode_compatible, smart_text
from django.db import models
from django_apogee.models import Pays, InsAdmEtp, Etape
# from core.managers.managers_examen import EtapeExamenManager
# from core.utils import paginator_etudiant
from duck_examen.managers import ExamenCenterManager
import re

class EtapeExamen(InsAdmEtp):
    class Meta:
        proxy = True
        verbose_name = 'Etape examen'

@python_2_unicode_compatible
class ExamCenter(models.Model):
    u"""
    Centre de gestion : Présentiel, etranger et dom-tom
    is_open : ouvre à l'application
    has_demande_ratachement : pour les examens à l'etranger true
    is_centre_principal : indique les centres métropolitains
    """
    label = models.CharField("center name", max_length=200, null=True)
    mailling_address = models.TextField("Adresse du centre")
    sending_address = models.TextField(u"Adresse de l'envoi du matériel", blank=True, null=True)
    last_name_manager = models.CharField(max_length=30, null=True, blank=True)
    first_name = models.CharField(max_length=30, null=True, blank=True)
    email = models.EmailField(null=True, blank=True)
    email_bis = models.EmailField(null=True, blank=True, verbose_name="second email")
    phone = models.CharField(max_length=30, blank=True, null=True)
    fax = models.CharField(max_length=30, null=True, blank=True)
    country = models.ForeignKey(Pays, verbose_name="pays", null=True)

    is_open = models.BooleanField(default=True, verbose_name='Ouvert')
    has_incorporation = models.BooleanField(default=True, verbose_name="Demande rattachement",
                                            help_text=u"l'étudiant doit faire une demande de rattachement")
    is_main_center = models.BooleanField(default=False)
    objects = ExamenCenterManager()
    # @property
    # def adresse_envoi_html(self):
    #     return ''.join([x+'
' for x in self.adresse_envoi_materiel.splitlines()])[:-4]

    class Meta:
        verbose_name = "Centre examen"
        verbose_name_plural = "Centres examens"
        # ordering = ['pays__lib_pay']

    def __str__(self):
        return u"{} {}".format(smart_text(self.label), self.country)

    def name_by_pays(self):
        return u"{} {}".format(self.country, smart_text(self.label))
#
#     def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
#         if not self.adresse_envoi_materiel:
#             self.adresse_envoi_materiel = self.adresse
#
#         super(CentreGestionExamen, self).save(force_insert, force_update, using, update_fields)
#

    def etudiant_by_step_session(self, cod_etp, session):
        query = self.rattachementcentreexamen_set.filter(inscription__cod_etp=cod_etp, session=session)
        return query.order_by('inscription__cod_ind__lib_nom_pat_ind').distinct()

    def nb_etudiant(self, cod_etp, session):
        return self.etudiant_by_step_session(cod_etp, session).count()

@python_2_unicode_compatible
class RattachementCentreExamen(models.Model):
    inscription = models.ForeignKey(InsAdmEtp)
    session = models.CharField(max_length=2, choices=(('1', 'Première session'), ('2', 'Seconde session')))
    centre = models.ForeignKey(ExamCenter)
    ec_manquant = models.BooleanField(default=False, blank=True)

    def __str__(self):
        return u"{} session : {} ec manquant : {}".format(self.centre, self.session, "oui" if self.ec_manquant else 'non')

    def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
        if self.ec_manquant:
            code_etp_actuel = self.inscription.cod_etp
            if code_etp_actuel[0] == 'L' and code_etp_actuel != 'L3NEDU':
                if code_etp_actuel[1] in ['2', '3']:
                    code_etp_anterieur = code_etp_actuel[0] + str(int(code_etp_actuel[1]) - 1) + code_etp_actuel[2:]
                    cod_ind = self.inscription.cod_ind
                    etp = InsAdmEtp.inscrits_condi.filter(cod_ind=cod_ind, cod_etp=code_etp_anterieur).first()
                    if etp:
                        RattachementCentreExamen.objects.get_or_create(inscription=etp, session=self.session, centre=self.centre)

        super(RattachementCentreExamen, self).save(force_insert, force_update, using, update_fields)

# class EtapeExamenModel(Etape):
#     """
#     utiliser pour les examen
#     """
#     objects = EtapeExamenManager()
#
#     def get_centre_exament_etranger(self):
#
#         query = CentreGestionExamen.objects.filter(etudiantcentreexamen__inscription__COD_ETP=self.cod_etp)
#         if self.cod_etp[0] == 'L' and int(self.cod_etp[1]) < 3:
#             code_etp = self.cod_etp[0] + str(int(self.cod_etp[1]) + 1) + self.cod_etp[2:]
#             query |= CentreGestionExamen.objects.filter(etudiantcentreexamen__inscription__COD_ETP=code_etp,
#                                                         etudiantcentreexamen__ec_manquant=True)
#         return query.distinct()
#
#     def get_centre(self, session):
#         query = CentreGestionExamen.objects.filter(etudiantcentreexamen__inscription__COD_ETP=self.cod_etp,
#                                                    etudiantcentreexamen__session=session)
#         if self.cod_etp[0] == 'L' and int(self.cod_etp[1]) < 3:
#             code_etp = self.cod_etp[0] + str(int(self.cod_etp[1]) + 1) + self.cod_etp[2:]
#             query |= CentreGestionExamen.objects.filter(etudiantcentreexamen__inscription__COD_ETP=code_etp,
#                                                         etudiantcentreexamen__ec_manquant=True,
#                                                         etudiantcentreexamen__session=session)
#         return query.distinct()
#
#     def get_centre_premier_session(self):
#         return self.get_centre(1)
#
#     def get_centre_deuxieme_session(self):
#         return self.get_centre(2)
#
#     def get_centre_exception(self, session):
#         query = CentreGestionException.objects.filter(etudiantcentreexamenexception__inscription__COD_ETP=self.cod_etp,
#                                                       etudiantcentreexamenexception__session=session)
#         if self.cod_etp[0] == 'L' and int(self.cod_etp[1]) < 3:
#             code_etp = self.cod_etp[0] + str(int(self.cod_etp[1]) + 1) + self.cod_etp[2:]
#             query |= CentreGestionException.objects.filter(
#                 etudiantcentreexamenexception__inscription__COD_ETP=code_etp,
#                 etudiantcentreexamenexception__ec_manquant=True, etudiantcentreexamenexception__session=session)
#         return query.distinct()
#
#     def get_centre_exception_premiere_session(self):
#         return self.get_centre_exception(1)
#
#     def get_centre_exception_deuxieme_session(self):
#         return self.get_centre_exception(2)
#
#     def get_etudiant_presentiel(self, session):
#         qs = INS_ADM_ETP_IED.inscrits_condi.filter(COD_ETP=self.cod_etp)\
#             .exclude(etudiantcentreexamenexception__session=session).exclude(etudiantcentreexamen__session=session)
#         return qs.distinct()
#
#     def get_etudiant_presentiel_pagine(self, session, nb_amphi, nb_table):
#         t = []
#         result = paginator_etudiant(self.get_etudiant_presentiel(session).order_by('COD_IND__LIB_NOM_PAT_IND'), nb_amphi)
#         for x in result:
#             t.extend(paginator_etudiant(x.object_list, nb_table))
#         return t
#
#     def has_centre_exament_etranger(self):
#         return True if self.get_centre_exament_etranger().count() else False
#
#     def get_url_pdf_centre_etranger(self):
#         return reverse('pdf_centre_etranger', kwargs={'etape': self.cod_etp})
#
#     def get_url_pdf_centre_etranger_recap_premiere_session(self):
#         return reverse('pdf_centre_etranger_recap', kwargs={'etape': self.cod_etp, 'session': 1})
#
#     def get_url_pdf_centre_etranger_recap_deuxieme_session(self):
#         return reverse('pdf_centre_etranger_recap', kwargs={'etape': self.cod_etp, 'session': 2})
#
#     def get_url_pdf_centre_etranger_emargement_premiere_session(self):
#         return reverse('pdf_centre_etranger_emargement', kwargs={'etape': self.cod_etp, 'session': 1})
#
#     def get_url_pdf_centre_etranger_emargement_deuxieme_session(self):
#         return reverse('pdf_centre_etranger_emargement', kwargs={'etape': self.cod_etp, 'session': 2})
#
#     def get_url_pdf_centre_dom_tom_emargement_premiere_session(self):
#         return reverse('pdf_centre_dom_tom_emargement', kwargs={'etape': self.cod_etp, 'session': 1})
#
#     def get_url_pdf_centre_dom_tom_emargement_deuxieme_session(self):
#         return reverse('pdf_centre_dom_tom_emargement', kwargs={'etape': self.cod_etp, 'session': 2})
#
#     def get_url_pdf_paris_emargement_premiere_session(self):
#         return reverse('pdf_paris_emargement', kwargs={'etape': self.cod_etp, 'session': 1})
#
#     def get_url_pdf_paris_emargement_deuxieme_session(self):
#         return reverse('pdf_paris_emargement', kwargs={'etape': self.cod_etp, 'session': 2})
#
#     class Meta:
#         proxy = True
#         ordering = ['cod_etp']

@python_2_unicode_compatible
class DeroulementExamenModel(models.Model):
    etape = models.ForeignKey(Etape)
    session = models.CharField(max_length=2, choices=(('1', 'Première session'), ('2', 'Seconde session')))
    nb_salle = models.IntegerField('nombre de salle', null=True, blank=True)
    nb_table = models.IntegerField('nombre de table par salle', null=True, blank=True)
    deroulement = models.TextField('Le déroulement', help_text='chaque ec doit être séparé par un |', null=True,
                                   blank=True)
    date_examen = models.TextField('Date examen', null=True, blank=True)
    salle_examen = models.TextField('salles examens', null=True, blank=True)

    class Meta:
        verbose_name = "Deroulement"
        verbose_name_plural = "Deroulements"
        db_table = 'core_deroulementexemenmodel'  # faute ortho déjà mis en prod

    def deroulement_parse(self):
        if not self.deroulement:
            return []
        text = self.deroulement.encode('utf-8')
        text = text.replace('\r\n', '').strip()
        resultat = []
        text = re.split(r'(\[[^]]*])', text)[1:]
        for i, token in enumerate(text):
            if i % 2 == 0:
                jour = {'date': text[i][1:-1], 'matieres': []}
                suite = text[i+1]
                suite = re.split(r'(<[^>]*>)', suite)[1:]
                for j, token2 in enumerate(suite):
                    if j % 2 == 0:
                        heure = suite[j].strip('< >'.encode('utf-8')).split(r'-')
                        r = {
                            'heure_debut': heure[0],
                            'heure_fin': heure[1]
                        }
                        deroule = re.split(r'\|', suite[j+1])
                        r['code_ec'] = deroule[0]
                        r['label'] = deroule[1]
                        r['prof'] = deroule[2]
                        jour['matieres'].append(r)
                resultat.append(jour)
        return resultat

    def __str__(self):
        return '{} session {}'.format(self.etape, self.session)

#
# @python_2_unicode_compatible
# class RecapitulatifExamenModel(models.Model):
#     etape = models.ForeignKey(Etape)
#     session = models.CharField(max_length=2, choices=(('1', 'Première session'), ('2', 'Seconde session')))
#     centre = models.ForeignKey(CentreGestionExamen)
#     date_envoie = models.DateField("date envoie des envellopes", null=True, blank=True)
#     date_reception = models.DateField("date réception des enveloppes", null=True, blank=True)
#     anomalie = models.CharField('anomalie', max_length=200, null=True, blank=True)
#     nb_enveloppe = models.IntegerField(null=True, blank=True)
#     nb_colis = models.IntegerField(null=True, blank=True)
#
#     class Meta:
#         app_label = 'core'
#         verbose_name = 'Recap envoie'
#         verbose_name_plural = 'Recaps envoie'
#         ordering = ['centre__pays__lib_pay']
#
#     def __str__(self):
#         return '{} {} {}'.format(self.centre.name_by_pays(), self.etape_id, self.session)
#
<commit_msg>bug impression<commit_after># coding=utf-8
from django.utils.encoding import python_2_unicode_compatible, smart_text
from django.db import models
from django_apogee.models import Pays, InsAdmEtp, Etape
# from core.managers.managers_examen import EtapeExamenManager
# from core.utils import paginator_etudiant
from duck_examen.managers import ExamenCenterManager
import re

class EtapeExamen(InsAdmEtp):
    class Meta:
        proxy = True
        verbose_name = 'Etape examen'

@python_2_unicode_compatible
class ExamCenter(models.Model):
    u"""
    Centre de gestion : Présentiel, etranger et dom-tom
    is_open : ouvre à l'application
    has_demande_ratachement : pour les examens à l'etranger true
    is_centre_principal : indique les centres métropolitains
    """
    label = models.CharField("center name", max_length=200, null=True)
    mailling_address = models.TextField("Adresse du centre")
    sending_address = models.TextField(u"Adresse de l'envoi du matériel", blank=True, null=True)
    last_name_manager = models.CharField(max_length=30, null=True, blank=True)
    first_name = models.CharField(max_length=30, null=True, blank=True)
    email = models.EmailField(null=True, blank=True)
    email_bis = models.EmailField(null=True, blank=True, verbose_name="second email")
    phone = models.CharField(max_length=30, blank=True, null=True)
    fax = models.CharField(max_length=30, null=True, blank=True)
    country = models.ForeignKey(Pays, verbose_name="pays", null=True)

    is_open = models.BooleanField(default=True, verbose_name='Ouvert')
    has_incorporation = models.BooleanField(default=True, verbose_name="Demande rattachement",
                                            help_text=u"l'étudiant doit faire une demande de rattachement")
    is_main_center = models.BooleanField(default=False)
    objects = ExamenCenterManager()
    # @property
    # def adresse_envoi_html(self):
    #     return ''.join([x+'
' for x in self.adresse_envoi_materiel.splitlines()])[:-4]

    class Meta:
        verbose_name = "Centre examen"
        verbose_name_plural = "Centres examens"
        # ordering = ['pays__lib_pay']

    def __str__(self):
        return u"{} {}".format(smart_text(self.label), self.country)

    def name_by_pays(self):
        return u"{} {}".format(self.country, smart_text(self.label))
#
#     def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
#         if not self.adresse_envoi_materiel:
#             self.adresse_envoi_materiel = self.adresse
#
#         super(CentreGestionExamen, self).save(force_insert, force_update, using, update_fields)
#

    def etudiant_by_step_session(self, cod_etp, session):
        query = self.rattachementcentreexamen_set.filter(inscription__cod_etp=cod_etp, session=session)
        return query.order_by('inscription__cod_ind__lib_nom_pat_ind').distinct()

    def nb_etudiant(self, cod_etp, session):
        return self.etudiant_by_step_session(cod_etp, session).count()

@python_2_unicode_compatible
class RattachementCentreExamen(models.Model):
    inscription = models.ForeignKey(InsAdmEtp)
    session = models.CharField(max_length=2, choices=(('1', 'Première session'), ('2', 'Seconde session')))
    centre = models.ForeignKey(ExamCenter)
    ec_manquant = models.BooleanField(default=False, blank=True)

    def __str__(self):
        return u"{} session : {} ec manquant : {}".format(self.centre, self.session, "oui" if self.ec_manquant else 'non')

    def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
        if self.ec_manquant:
            code_etp_actuel = self.inscription.cod_etp
            if code_etp_actuel[0] == 'L' and code_etp_actuel != 'L3NEDU':
                if code_etp_actuel[1] in ['2', '3']:
                    code_etp_anterieur = code_etp_actuel[0] + str(int(code_etp_actuel[1]) - 1) + code_etp_actuel[2:]
                    cod_ind = self.inscription.cod_ind
                    etp = InsAdmEtp.inscrits_condi.filter(cod_ind=cod_ind, cod_etp=code_etp_anterieur).first()
                    if etp:
                        RattachementCentreExamen.objects.get_or_create(inscription=etp, session=self.session, centre=self.centre)

        super(RattachementCentreExamen, self).save(force_insert, force_update, using, update_fields)

# class EtapeExamenModel(Etape):
#     """
#     utiliser pour les examen
#     """
#     objects = EtapeExamenManager()
#
#     def get_centre_exament_etranger(self):
#
#         query = CentreGestionExamen.objects.filter(etudiantcentreexamen__inscription__COD_ETP=self.cod_etp)
#         if self.cod_etp[0] == 'L' and int(self.cod_etp[1]) < 3:
#             code_etp = self.cod_etp[0] + str(int(self.cod_etp[1]) + 1) + self.cod_etp[2:]
#             query |= CentreGestionExamen.objects.filter(etudiantcentreexamen__inscription__COD_ETP=code_etp,
#                                                         etudiantcentreexamen__ec_manquant=True)
#         return query.distinct()
#
#     def get_centre(self, session):
#         query = CentreGestionExamen.objects.filter(etudiantcentreexamen__inscription__COD_ETP=self.cod_etp,
#                                                    etudiantcentreexamen__session=session)
#         if self.cod_etp[0] == 'L' and int(self.cod_etp[1]) < 3:
#             code_etp = self.cod_etp[0] + str(int(self.cod_etp[1]) + 1) + self.cod_etp[2:]
#             query |= CentreGestionExamen.objects.filter(etudiantcentreexamen__inscription__COD_ETP=code_etp,
#                                                         etudiantcentreexamen__ec_manquant=True,
#                                                         etudiantcentreexamen__session=session)
#         return query.distinct()
#
#     def get_centre_premier_session(self):
#         return self.get_centre(1)
#
#     def get_centre_deuxieme_session(self):
#         return self.get_centre(2)
#
#     def get_centre_exception(self, session):
#         query = CentreGestionException.objects.filter(etudiantcentreexamenexception__inscription__COD_ETP=self.cod_etp,
#                                                       etudiantcentreexamenexception__session=session)
#         if self.cod_etp[0] == 'L' and int(self.cod_etp[1]) < 3:
#             code_etp = self.cod_etp[0] + str(int(self.cod_etp[1]) + 1) + self.cod_etp[2:]
#             query |= CentreGestionException.objects.filter(
#                 etudiantcentreexamenexception__inscription__COD_ETP=code_etp,
#                 etudiantcentreexamenexception__ec_manquant=True, etudiantcentreexamenexception__session=session)
#         return query.distinct()
#
#     def get_centre_exception_premiere_session(self):
#         return self.get_centre_exception(1)
#
#     def get_centre_exception_deuxieme_session(self):
#         return self.get_centre_exception(2)
#
#     def get_etudiant_presentiel(self, session):
#         qs = INS_ADM_ETP_IED.inscrits_condi.filter(COD_ETP=self.cod_etp)\
#             .exclude(etudiantcentreexamenexception__session=session).exclude(etudiantcentreexamen__session=session)
#         return qs.distinct()
#
#     def get_etudiant_presentiel_pagine(self, session, nb_amphi, nb_table):
#         t = []
#         result = paginator_etudiant(self.get_etudiant_presentiel(session).order_by('COD_IND__LIB_NOM_PAT_IND'), nb_amphi)
#         for x in result:
#             t.extend(paginator_etudiant(x.object_list, nb_table))
#         return t
#
#     def has_centre_exament_etranger(self):
#         return True if self.get_centre_exament_etranger().count() else False
#
#     def get_url_pdf_centre_etranger(self):
#         return reverse('pdf_centre_etranger', kwargs={'etape': self.cod_etp})
#
#     def get_url_pdf_centre_etranger_recap_premiere_session(self):
#         return reverse('pdf_centre_etranger_recap', kwargs={'etape': self.cod_etp, 'session': 1})
#
#     def get_url_pdf_centre_etranger_recap_deuxieme_session(self):
#         return reverse('pdf_centre_etranger_recap', kwargs={'etape': self.cod_etp, 'session': 2})
#
#     def get_url_pdf_centre_etranger_emargement_premiere_session(self):
#         return reverse('pdf_centre_etranger_emargement', kwargs={'etape': self.cod_etp, 'session': 1})
#
#     def get_url_pdf_centre_etranger_emargement_deuxieme_session(self):
#         return reverse('pdf_centre_etranger_emargement', kwargs={'etape': self.cod_etp, 'session': 2})
#
#     def get_url_pdf_centre_dom_tom_emargement_premiere_session(self):
#         return reverse('pdf_centre_dom_tom_emargement', kwargs={'etape': self.cod_etp, 'session': 1})
#
#     def get_url_pdf_centre_dom_tom_emargement_deuxieme_session(self):
#         return reverse('pdf_centre_dom_tom_emargement', kwargs={'etape': self.cod_etp, 'session': 2})
#
#     def get_url_pdf_paris_emargement_premiere_session(self):
#         return reverse('pdf_paris_emargement', kwargs={'etape': self.cod_etp, 'session': 1})
#
#     def get_url_pdf_paris_emargement_deuxieme_session(self):
#         return reverse('pdf_paris_emargement', kwargs={'etape': self.cod_etp, 'session': 2})
#
#     class Meta:
#         proxy = True
#         ordering = ['cod_etp']

@python_2_unicode_compatible
class DeroulementExamenModel(models.Model):
    etape = models.ForeignKey(Etape)
    session = models.CharField(max_length=2, choices=(('1', 'Première session'), ('2', 'Seconde session')))
    nb_salle = models.IntegerField('nombre de salle', null=True, blank=True)
    nb_table = models.IntegerField('nombre de table par salle', null=True, blank=True)
    deroulement = models.TextField('Le déroulement', help_text='chaque ec doit être séparé par un |', null=True,
                                   blank=True)
    date_examen = models.TextField('Date examen', null=True, blank=True)
    salle_examen = models.TextField('salles examens', null=True, blank=True)

    class Meta:
        verbose_name = "Deroulement"
        verbose_name_plural = "Deroulements"
        db_table = 'core_deroulementexemenmodel'  # faute ortho déjà mis en prod

    def deroulement_parse(self):
        if not self.deroulement:
            return []
        text = self.deroulement.encode('utf-8')
        text = text.replace('\r\n', '').strip()
        resultat = []
        text = re.split(r'(\[[^]]*])', text)[1:]
        for i, token in enumerate(text):
            if i % 2 == 0:
                jour = {'date': text[i][1:-1], 'matieres': []}
                suite = text[i+1]
                suite = re.split(r'(<[^>]*>)', suite)[1:]
                for j, token2 in enumerate(suite):
                    if j % 2 == 0:
                        heure = suite[j].strip('< >'.encode('utf-8')).split(r'-')
                        r = {
                            'heure_debut': heure[0],
                            'heure_fin': heure[1]
                        }
                        deroule = re.split(r'\|', suite[j+1])
                        r['code_ec'] = deroule[0]
                        r['label'] = deroule[1]
                        r['prof'] = deroule[2]
                        jour['matieres'].append(r)
                resultat.append(jour)
        return resultat

    def __str__(self):
        return '{} session {}'.format(self.etape, self.session)

#
# @python_2_unicode_compatible
# class RecapitulatifExamenModel(models.Model):
#     etape = models.ForeignKey(Etape)
#     session = models.CharField(max_length=2, choices=(('1', 'Première session'), ('2', 'Seconde session')))
#     centre = models.ForeignKey(ExamCenter)
#     date_envoie = models.DateField("date envoie des envellopes", null=True, blank=True)
#     date_reception = models.DateField("date réception des enveloppes", null=True, blank=True)
#     anomalie = models.CharField('anomalie', max_length=200, null=True, blank=True)
#     nb_enveloppe = models.IntegerField(null=True, blank=True)
#     nb_colis = models.IntegerField(null=True, blank=True)
#
#     class Meta:
#         verbose_name = 'Recap envoie'
#         verbose_name_plural = 'Recaps envoie'
#         ordering = ['centre__pays__lib_pay']
#
#     def __str__(self):
#         return '{} {} {}'.format(self.centre.name_by_pays(), self.etape_id, self.session)
#
<|endoftext|>


<commit_before>#!/usr/bin/env python3

class Un:
    def __init__(self, number=None, part=None):
        self.number = number
        self.part = part
    def __repr__(self):
        number = self.number
        if self.number is None:
            number = "??"
        if self.part:
            return "u{}_{}".format(number, self.part)
        return "u{}".format(number)
    def __add__(self, other):
        if self.number and self.number and (self.number != other.number or not self.part or not other.part or self.part == other.part):
            raise Exception()
        return self.__class__(self.number)

class Matrix:
    def __init__(self, rows, cols, rowdescrs=None, coldescrs=None, flatvals=None):
        self.rows = rows
        self.cols = cols
        self.m = [ [0.0
                    for _j in range(cols)]
                  for _i in range(rows)]
        if not rowdescrs:
            rowdescrs = [Un() for _i in range(rows)]
        self.rowdescrs = rowdescrs
        if not coldescrs:
            coldescrs = [Un() for _i in range(rows)]
        self.coldescrs = coldescrs
        if flatvals:
            for i, v in enumerate(flatvals):
                self.m[i//cols][i%cols] = v

    def __repr__(self):
        res = "{0:>13}".format("| ")
        for cold in self.coldescrs:
            res += "{:>10} | ".format(cold)
        res += "\n"
        for row,rowd in zip(self.m, self.rowdescrs):
            res += "|{:^10}| ".format(rowd)
            for x in row:
                res += "{0:10.6} | ".format(float(x))
            res += "\n"
        return res

    def __getitem__(self, row):
        return self.m[row]

    def __setitem__(self, row, val):
        self.m[row] = val
        return self

    def swaprow(self, rowA, rowB):
        self.m[rowA], self.m[rowB] = self.m[rowB], self.m[rowA]
        self.rowdescrs[rowA], self.rowdescrs[rowB] = self.rowdescrs[rowB], self.rowdescrs[rowA]
        return self

    def swapcol(self, colA, colB):
        for row in self.m:
            row[colA], row[colB] = row[colB], row[colA]
        self.coldescrs[colA], self.coldescrs[colB] = self.coldescrs[colB], self.coldescrs[colA]
        return self

    def __add__(self, other):
        if self.rows != other.rows or self.cols != other.cols:
            raise Exception()
        res = self.__class__(self.rows, self.cols,
            [x+y for x,y in zip(self.rowdescrs, other.rowdescrs)],
            [x+y for x,y in zip(self.coldescrs, other.coldescrs)])
        for rowId, (rowA, rowB) in enumerate(zip(self.m, other.m)):
            res[rowId] = [x+y for x,y in zip(rowA, rowB)]
        return res

    def cutpart(self, rows, cols):
        res = self.__class__(len(rows), len(cols), [self.rowdescrs[row] for row in rows], [self.coldescrs[col] for col in cols])
        for rowId, rowA in enumerate(rows):
            res[rowId] = [self[rowA][c] for c in cols]
        return res

    @classmethod
    def prodA1(cls, a, b):
        res = cls.prodA2(a, b)
        res.swapcol(0, 1)
        res.swaprow(0, 1)
        return res

    @classmethod
    def prodA2(cls, a, b):
        coldescrs = [a.coldescrs[0], a.coldescrs[1] + b.coldescrs[0], b.coldescrs[1], ""]
        rowdescrs = [a.rowdescrs[0], a.rowdescrs[1] + b.rowdescrs[0], b.rowdescrs[1], ""]
        res = cls(3, 4, coldescrs, rowdescrs)
        res[0] = a[0] + [a[0][2]]
        res[1] = [a[1][0], a[1][1]+b[0][0], b[0][1], a[1][2]+b[0][2]]
        res[2] = [0.0, b[1][0], b[1][1], b[1][2]]
        return res

if __name__ == "__main__":
    a1 = Matrix(2, 3, [Un(0),    Un(1, 1)], [Un(0),    Un(1, 1), ""], [1, 0, 0, 1, -1, 0])
    a2 = Matrix(2, 3, [Un(1, 2), Un(2, 1)], [Un(1, 2), Un(2, 1), ""],       [-1, 1, 0, 1, -1, 0])
    print(a1)
    print(a2)

    b1 = Matrix.prodA1(a1,a2)
    print(b1)
    b1 = b1.cutpart([1,2], [1,2,3])
    print(b1)<commit_msg>HERE HAVE CODE<commit_after>#!/usr/bin/env python3

class Un:
    def __init__(self, number=None, part=None):
        self.number = number
        self.part = part
    def __repr__(self):
        number = self.number
        if self.number is None:
            number = "??"
        if self.part:
            return "u{}_{}".format(number, self.part)
        return "u{}".format(number)
    def __add__(self, other):
        if self.number and self.number and (self.number != other.number or not self.part or not other.part or self.part == other.part):
            raise Exception()
        return self.__class__(self.number)

class Matrix:
    def __init__(self, rows, cols, rowdescrs=None, coldescrs=None, flatvals=None):
        self.rows = rows
        self.cols = cols
        self.m = [ [0.0
                    for _j in range(cols)]
                  for _i in range(rows)]
        if not rowdescrs:
            rowdescrs = [Un() for _i in range(rows)]
        self.rowdescrs = rowdescrs
        if not coldescrs:
            coldescrs = [Un() for _i in range(rows)]
        self.coldescrs = coldescrs
        if flatvals:
            for i, v in enumerate(flatvals):
                self.m[i//cols][i%cols] = v

    def __repr__(self):
        res = "{0:>13}".format("| ")
        for cold in self.coldescrs:
            res += "{:>10} | ".format(cold)
        res += "\n"
        for row,rowd in zip(self.m, self.rowdescrs):
            res += "|{:^10}| ".format(rowd)
            for x in row:
                res += "{0:10.6} | ".format(float(x))
            res += "\n"
        return res

    def __getitem__(self, row):
        return self.m[row]

    def __setitem__(self, row, val):
        self.m[row] = val
        return self

    def swaprow(self, rowA, rowB):
        self.m[rowA], self.m[rowB] = self.m[rowB], self.m[rowA]
        self.rowdescrs[rowA], self.rowdescrs[rowB] = self.rowdescrs[rowB], self.rowdescrs[rowA]
        return self

    def swapcol(self, colA, colB):
        for row in self.m:
            row[colA], row[colB] = row[colB], row[colA]
        self.coldescrs[colA], self.coldescrs[colB] = self.coldescrs[colB], self.coldescrs[colA]
        return self

    def __add__(self, other):
        if self.rows != other.rows or self.cols != other.cols:
            raise Exception()
        res = self.__class__(self.rows, self.cols,
            [x+y for x,y in zip(self.rowdescrs, other.rowdescrs)],
            [x+y for x,y in zip(self.coldescrs, other.coldescrs)])
        for rowId, (rowA, rowB) in enumerate(zip(self.m, other.m)):
            res[rowId] = [x+y for x,y in zip(rowA, rowB)]
        return res

    def cutpart(self, rows, cols):
        res = self.__class__(len(rows), len(cols), [self.rowdescrs[row] for row in rows], [self.coldescrs[col] for col in cols])
        for rowId, rowA in enumerate(rows):
            res[rowId] = [self[rowA][c] for c in cols]
        return res

    def gaussStep(self, baseRowId):
        if self.m[baseRowId][baseRowId] == 0:
            raise Exception()
        self.m[baseRowId] = [x / self.m[baseRowId][baseRowId] for x in self.m[baseRowId]]
        for rowId, _row in enumerate(self.m[baseRowId+1:], baseRowId+1):
            if self.m[rowId][baseRowId] != 0:
                self.m[rowId] = [x - self.m[rowId][baseRowId] * y for x, y in zip(self.m[rowId], self.m[baseRowId])]

        # for rowId, _i in [(0,0)]:  # for full gauss: ... in enumerate(self.m):
        #     if self.m[rowId][rowId] != 0:
        #         self.m[rowId] = [x / self.m[rowId][rowId] for x in self.m[rowId]]
        #     for nextrowId, _j in enumerate(self.m[rowId+1:], rowId+1):
        #         self.m[nextrowId] = [x - self.m[nextrowId][nextrowId-1] * y for x,y in zip(self.m[nextrowId],self.m[rowId])]
        #         self.m[nextrowId][nextrowId-1] = 0.0

    @classmethod
    def prodA1(cls, a, b):
        coldescrs = [a.coldescrs[0], a.coldescrs[1] + b.coldescrs[0], b.coldescrs[1], ""]
        rowdescrs = [a.rowdescrs[0], a.rowdescrs[1] + b.rowdescrs[0], b.rowdescrs[1], ""]
        res = cls(3, 4, coldescrs, rowdescrs)
        res[0] = a[0] + [a[0][2]]
        res[1] = [a[1][0], a[1][1]+b[0][0], b[0][1], a[1][2]+b[0][2]]
        res[2] = [0.0, b[1][0], b[1][1], b[1][2]]
        res.swapcol(0, 1)
        res.swaprow(0, 1)
        res.gaussStep(0)
        return res

    @classmethod
    def prodA2(cls, a, b):
        coldescrs = [a.coldescrs[0], a.coldescrs[1] + b.coldescrs[0], b.coldescrs[1], ""]
        rowdescrs = [a.rowdescrs[0], a.rowdescrs[1] + b.rowdescrs[0], b.rowdescrs[1], ""]
        res = cls(3, 4, coldescrs, rowdescrs)
        res[0] = a[0] + [a[0][2]]
        res[1] = [a[1][0], a[1][1]+b[0][0], b[0][1], a[1][2]+b[0][2]]
        res[2] = [0.0, b[1][0], b[1][1], b[1][2]]
        res.gaussStep(0)
        # res.gaussStep(1)
        return res

globalsolution = [None, None, None, None, None]
if __name__ == "__main__":
    a1 = Matrix(2, 3, [Un(0),    Un(1, 1)], [Un(0),    Un(1, 1), ""], [  1,  0,  0,  1, -1,  0 ])
    a2 = Matrix(2, 3, [Un(1, 2), Un(2, 1)], [Un(1, 2), Un(2, 1), ""], [ -1,  1,  0,  1, -1,  0 ])

    a3 = Matrix(2, 3, [Un(2, 2), Un(3, 1)], [Un(2, 2), Un(3, 1), ""], [ -1,  1,  0,  1, -1,  0 ])
    a4 = Matrix(2, 3, [Un(3, 2), Un(4)], [Un(3, 2), Un(4), ""],       [ -1,  1,  0,  0,  1, 20 ])

    b1 = Matrix.prodA1(a1,a2)
    # print(b1)
    b2 = Matrix.prodA1(a3,a4)
    # print(b2)

    print("b1\n" + str(b1))
    print("b2\n" + str(b2))

    c1 = Matrix.prodA2(b1.cutpart([1,2], [1,2,3]), b2.cutpart([1,2], [1,2,3]))
    print("c1\n" + str(c1))

    for rowId, _i in reversed(list(enumerate(c1.m))):
        globalsolution[c1.rowdescrs[rowId].number] = c1[rowId][-1] + sum(x*globalsolution[y.number] for x,y in zip(c1[rowId][rowId+1:-1], c1.coldescrs[rowId+1:-1]))
        print(c1.rowdescrs[rowId], c1[rowId][rowId+1:-1], c1.coldescrs[rowId+1:-1], globalsolution[c1.rowdescrs[rowId].number])
    print(globalsolution)<|endoftext|>


<commit_before>import unittest
import utilsT
from camera.camera import *
from nose.tools import *
from utils.configUtils import *

class CameraSystem(unittest.TestCase):
	paramUtil = ParamUtils()
	params = None

	configUtil = ConfigUtils()

	#@unittest.skip("skipping system tests")
	def system_test_get_cam_alert_not_activated(self):
		url = self.configUtil.getUrl("cam1")
		cam = Camera(url)
		self.assertFalse(cam.motion_detected())

	def system_test_get_cam_alert_not_activated(self):
		url = self.configUtil.getUrl("cam1")
		cam = Camera(url)
		self.assertFalse(cam.motion_detected())<commit_msg>Added skiped annotation<commit_after>import unittest
import utilsT
from camera.camera import *
from nose.tools import *
from utils.configUtils import *

class CameraSystem(unittest.TestCase):
	paramUtil = ParamUtils()
	params = None

	configUtil = ConfigUtils()

	#@unittest.skip("skipping system tests")
	def system_test_get_cam_alert_not_activated(self):
		url = self.configUtil.getUrl("cam1")
		cam = Camera(url)
		self.assertFalse(cam.motion_detected())

	#@unittest.skip("skipping system tests")
	def system_test_get_cam_alert_not_activated(self):
		url = self.configUtil.getUrl("cam1")
		cam = Camera(url)
		self.assertFalse(cam.motion_detected())<|endoftext|>


<commit_before><commit_msg>Fix docstrings for pause/unpause<commit_after><|endoftext|>


<commit_before>"""
Topographica Bitmap Class

Encapsulates the PIL Image class so that an input matrix can be displayed
as a bitmap image without needing to know about PIL proper.

There are three different base image Classes which inherit Bitmap:

PaletteBitmap  - 1 2D Matrix, 1 1D Color Map
HSVBitmap    - 3 2D Matrices, Color (H), Confidence (S), Strength (V)
RGBBitmap    - 3 2D Matrices, Red, Green, Blue Channels.

All maps are assumed to be normalized to 1.  Matrices are passed in as
part of the constructor and the image is generaed.

The encapsulated PIL Image is accessible through the .bitmap attribute.

---
Creating new Bitmaps:

bitmap1 = PaletteBitmap(inArray,palette)
    inArray: 2D Array
    palette: 768 integers (3x256 of RGB ranged 0-255).

bitmap3 = RGBBitmap(rMapArray,gMapArray,bMapArray)
    Three matrices that are combined into one image, where each matrix
    represents a different color channel.
    3 matrices expected, each should have been normalized to 1.

bitmap4 = HSVBitmap(hMapArray,sMapArray,vMapArray)
    HSV Map inputs, converts to RGB image.
    3 matrices expected, each should have been normalized to 1.

The constructed Image is then in [BitmapObject].bitmap.

$Id$
"""
__version__='$Revision$'

from colorsys import hsv_to_rgb

import Numeric, Image, math

from topo.base.parameter import Parameter
from topo.base.topoobject import TopoObject

### TO DO: - Update the test file.
###        - Write PaletteBitmap when the Palette class is fixed
###        - Get rid of view_info
###        - Get rid of accessing function (copy, show...), though it is not crucial.

class Bitmap(TopoObject):
    """
    Wrapper class for the PIL Image class.

    The main purpose for this base class is to provide a consistent
    interface for defining bitmaps constructed in various different
    ways.  The resulting bitmap is a PIL Image object that can be
    accessed using the normal PIL interface.
    """
    normalize = Parameter(default=0)

    def __init__(self,image):

        self.image = image

        ### JABALERT: Should presumably be deleted; seems to be an
        ### extra copy of the Plot's view_info
        self.view_info = {}

    ### JABALERT: Should presumably be deleted, if bitmap stays public.
    def copy(self):
        """
        Return a copy of the encapsulated image so the original is
        preserved.
        """
        return self.image.copy()

    ### JABALERT: Should presumably be deleted, if bitmap stays public.
    def show(self):
        """
        Renaming of Image.show() for the Bitmap.bitmap attribute.
        """
        self.image.show()

    ### JABALERT: Should presumably be deleted, if bitmap stays public.
    def width(self): return self.image.size[0]
    def height(self): return self.image.size[1]

    def zoom(self, factor):
        """
        Return a resized Image object, given the input 'factor'
        parameter.  1.0 is the same size, 2.0 is doubling the height
        and width, 0.5 is 1/2 the original size.  The original Image
        is not changed.
        """
        x,y = self.image.size
        zx, zy = x*factor, y*factor
        return self.image.resize((zx,zy))

    def _arrayToImage(self, inArray):
        """
        Generate a 1-channel PIL Image from an array of values from 0 to 1.0.

        Values larger than 1.0 are silently cropped.  Returns a one-channel
        (monochrome) Image.
        """

        # PIL 'L' Images use 0 to 255.  Have to scale up.
        inArray = (Numeric.floor(inArray * 255)).astype(Numeric.Int)

        # Clipping if some values are > 255
	if max(inArray.flat) > 255:
	    inArray = Numeric.clip(inArray,0,255)
	    self.debug("clipping is performed")

        r,c = inArray.shape
        # size is (width,height), so we swap r and c:
        newImage = Image.new('L',(c,r),None)
        newImage.putdata(inArray.flat)
        return newImage

class PaletteBitmap(Bitmap):
    """
    A Bitmap constructed using a single 2D array.

    By default, the Image constructed will be monochrome.  More
    colorful Images can be constructed by specifying a Palette.
    """

    def __init__(self,inArray,palette=None):
        """
        inArray should have values in the range from 0 and 1.

        Palette can be any color scale depending on the type of ColorMap
        desired.
        [0,0,0 ... 255,255,255] = Grayscale
        [0,0,0 ... 255,0,0] = Grayscale but through a Red filter.

        If palette is not passed as parameter, Grayscale is default.
        """
        ### JABALERT: Should accept a Palette class, not a data structure,
        ### or we should get rid of the Palette classes.

        newImage = self._arrayToImage(inArray)
        if palette == None:
            palette = [i for i in range(256) for j in range(3)]
        newImage.putpalette(palette)
        newImage = newImage.convert('P')
        super(PaletteBitmap,self).__init__(newImage)

class HSVBitmap(Bitmap):
    """
    HSV Map inputs, converts to RGB image.  3 matrices expected, each should
    have been normalized to 1.
    """

    def __init__(self,hMapArray,sMapArray,vMapArray):
        """
        First matrix sets the Hue (Color).
        Second marix sets the Sauration (How much color)
        Third matrix sets the Value (How bright the pixel will be)
        """
        shape = hMapArray.shape
        rmat = Numeric.array(hMapArray,Numeric.Float)
        gmat = Numeric.array(sMapArray,Numeric.Float)
        bmat = Numeric.array(vMapArray,Numeric.Float)

        # List comprehensions were not used because they were slower.
        for j in range(shape[0]):
            for i in range(shape[1]):
                rgb = hsv_to_rgb(rmat[j,i],gmat[j,i],bmat[j,i])
                rmat[j,i] = rgb[0]
                gmat[j,i] = rgb[1]
                bmat[j,i] = rgb[2]

        rImage = self._arrayToImage(rmat)
        gImage = self._arrayToImage(gmat)
        bImage = self._arrayToImage(bmat)

        super(HSVBitmap,self).__init__(Image.merge('RGB',(rImage,gImage,bImage)))

class RGBBitmap(Bitmap):
    """A Bitmap constructed using three 2D arrays, for Red, Green, and Blue."""

    def __init__(self,rMapArray,gMapArray,bMapArray):
        """Each matrix must be the same size, with values in the range 0.0 to 1.0."""

        rImage = self._arrayToImage(rMapArray)
        gImage = self._arrayToImage(gMapArray)
        bImage = self._arrayToImage(bMapArray)

        super(RGBBitmap,self).__init__(Image.merge('RGB',(rImage,gImage,bImage)))
<commit_msg>Added counting of bad pixels<commit_after>"""
Topographica Bitmap Class

Encapsulates the PIL Image class so that an input matrix can be displayed
as a bitmap image without needing to know about PIL proper.

There are three different base image Classes which inherit Bitmap:

PaletteBitmap  - 1 2D Matrix, 1 1D Color Map
HSVBitmap    - 3 2D Matrices, Color (H), Confidence (S), Strength (V)
RGBBitmap    - 3 2D Matrices, Red, Green, Blue Channels.

All maps are assumed to be normalized to 1.  Matrices are passed in as
part of the constructor and the image is generaed.

The encapsulated PIL Image is accessible through the .bitmap attribute.

---
Creating new Bitmaps:

bitmap1 = PaletteBitmap(inArray,palette)
    inArray: 2D Array
    palette: 768 integers (3x256 of RGB ranged 0-255).

bitmap3 = RGBBitmap(rMapArray,gMapArray,bMapArray)
    Three matrices that are combined into one image, where each matrix
    represents a different color channel.
    3 matrices expected, each should have been normalized to 1.

bitmap4 = HSVBitmap(hMapArray,sMapArray,vMapArray)
    HSV Map inputs, converts to RGB image.
    3 matrices expected, each should have been normalized to 1.

The constructed Image is then in [BitmapObject].bitmap.

$Id$
"""
__version__='$Revision$'

from colorsys import hsv_to_rgb

import Numeric, Image, math

from topo.base.parameter import Parameter
from topo.base.topoobject import TopoObject

### TO DO: - Update the test file.
###        - Write PaletteBitmap when the Palette class is fixed
###        - Get rid of view_info
###        - Get rid of accessing function (copy, show...), though it is not crucial.

class Bitmap(TopoObject):
    """
    Wrapper class for the PIL Image class.

    The main purpose for this base class is to provide a consistent
    interface for defining bitmaps constructed in various different
    ways.  The resulting bitmap is a PIL Image object that can be
    accessed using the normal PIL interface.

    If subclasses use the _arrayToImage() function provided, any
    pixels larger than the maximum that can be displayed will
    be counted before they are clipped; these are stored in the
    clipped_pixels attribute.
    """
    normalize = Parameter(default=0)
    clipped_pixels = 0

    def __init__(self,image):
        self.image = image

        ### JABALERT: Should presumably be deleted; seems to be an
        ### extra copy of the Plot's view_info
        self.view_info = {}

    ### JABALERT: Should presumably be deleted, if bitmap stays public.
    def copy(self):
        """
        Return a copy of the encapsulated image so the original is
        preserved.
        """
        return self.image.copy()

    ### JABALERT: Should presumably be deleted, if bitmap stays public.
    def show(self):
        """
        Renaming of Image.show() for the Bitmap.bitmap attribute.
        """
        self.image.show()

    ### JABALERT: Should presumably be deleted, if bitmap stays public.
    def width(self): return self.image.size[0]
    def height(self): return self.image.size[1]

    def zoom(self, factor):
        """
        Return a resized Image object, given the input 'factor'
        parameter.  1.0 is the same size, 2.0 is doubling the height
        and width, 0.5 is 1/2 the original size.  The original Image
        is not changed.
        """
        x,y = self.image.size
        zx, zy = x*factor, y*factor
        return self.image.resize((zx,zy))

    def _arrayToImage(self, inArray):
        """
        Generate a 1-channel PIL Image from an array of values from 0 to 1.0.

        Values larger than 1.0 are clipped, after adding them to the total
        clipped_pixels.  Returns a one-channel (monochrome) Image.
        """

        # PIL 'L' Images use a range of 0 to 255, so we scale the
        # input array to match
        max_pixel_value=255
        ### JABALERT: Shouldn't this scale by max_pixel_value+1 (256), not max_pixel_value (255)?
        inArray = (Numeric.floor(inArray * max_pixel_value)).astype(Numeric.Int)

        # Clip any values that are still larger than max_pixel_value
        to_clip = sum(Numeric.greater(inArray.flat,max_pixel_value))
	if (to_clip>0):
            self.clipped_pixels = self.clipped_pixels + to_clip
	    inArray = Numeric.clip(inArray,0,max_pixel_value)
	    self.verbose("Bitmap: clipped",to_clip,"image pixels that were out of range")

        r,c = inArray.shape
        # size is (width,height), so we swap r and c:
        newImage = Image.new('L',(c,r),None)
        newImage.putdata(inArray.flat)
        return newImage

class PaletteBitmap(Bitmap):
    """
    A Bitmap constructed using a single 2D array.

    By default, the Image constructed will be monochrome.  More
    colorful Images can be constructed by specifying a Palette.
    """

    def __init__(self,inArray,palette=None):
        """
        inArray should have values in the range from 0 and 1.

        Palette can be any color scale depending on the type of ColorMap
        desired.
        [0,0,0 ... 255,255,255] = Grayscale
        [0,0,0 ... 255,0,0] = Grayscale but through a Red filter.

        If palette is not passed as parameter, Grayscale is default.
        """
        ### JABALERT: Should accept a Palette class, not a data structure,
        ### or we should get rid of the Palette classes.

        newImage = self._arrayToImage(inArray)
        if palette == None:
            palette = [i for i in range(256) for j in range(3)]
        newImage.putpalette(palette)
        newImage = newImage.convert('P')
        super(PaletteBitmap,self).__init__(newImage)

class HSVBitmap(Bitmap):
    """
    HSV Map inputs, converts to RGB image.  3 matrices expected, each should
    have been normalized to 1.
    """

    def __init__(self,hMapArray,sMapArray,vMapArray):
        """
        First matrix sets the Hue (Color).
        Second marix sets the Sauration (How much color)
        Third matrix sets the Value (How bright the pixel will be)
        """
        shape = hMapArray.shape
        rmat = Numeric.array(hMapArray,Numeric.Float)
        gmat = Numeric.array(sMapArray,Numeric.Float)
        bmat = Numeric.array(vMapArray,Numeric.Float)

        # List comprehensions were not used because they were slower.
        for j in range(shape[0]):
            for i in range(shape[1]):
                rgb = hsv_to_rgb(rmat[j,i],gmat[j,i],bmat[j,i])
                rmat[j,i] = rgb[0]
                gmat[j,i] = rgb[1]
                bmat[j,i] = rgb[2]

        rImage = self._arrayToImage(rmat)
        gImage = self._arrayToImage(gmat)
        bImage = self._arrayToImage(bmat)

        super(HSVBitmap,self).__init__(Image.merge('RGB',(rImage,gImage,bImage)))

class RGBBitmap(Bitmap):
    """A Bitmap constructed using three 2D arrays, for Red, Green, and Blue."""

    def __init__(self,rMapArray,gMapArray,bMapArray):
        """Each matrix must be the same size, with values in the range 0.0 to 1.0."""

        rImage = self._arrayToImage(rMapArray)
        gImage = self._arrayToImage(gMapArray)
        bImage = self._arrayToImage(bMapArray)

        super(RGBBitmap,self).__init__(Image.merge('RGB',(rImage,gImage,bImage)))
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
from random import shuffle

separation_artist = 5
separation_title = 5
playlist_path = 'playlist.m3u'
playlist_size = 100

nb_pl = 0

bac = []
playlist = []
artists = []
titles = []
error = []

class Track:
    def __init__(self, artist, title, filename, duration=0):
        self.artist = artist
        self.title = title
        self.filename = filename
        self.duration = duration

def read_folder(folder):
    for song_file in os.listdir(folder):
        artist = os.path.splitext(song_file)[0].split(' - ')[0]
        title = os.path.splitext(song_file)[0].split(' - ')[1]
        filename = os.path.abspath(song_file)
        bac.append(Track(artist, title, filename))
        artists.append(artist)
        titles.append(title)

def get_track(i):
    j = i % len(bac)
    print "i : %d" % i
    print "j : %d" % j
    track = bac[i]
    print track.artist
    playlist.append(track)

read_folder("music")

nb_artist = len(list(set(artists)))/2
nb_titles = len(list(set(titles)))/2

if separation_artist == 0:
    error.append("Warning: separation_artist must be set and greater than 0.")
if separation_title == 0:
    error.append("Warning: separation_title must be set and greater than 0.")
if playlist_path != '':
    error.append("Warning: playlist_path must be set and not empty.")
if playlist_size == 0:
    error.append("Warning: playlist_size must be set and greater than 0.")

if len(error) != 0:
    for err in error:
        print err
    sys.exit(0)

shuffle(bac)

while True:
    get_track(nb_pl)
    nb_pl+=1
    if playlist_size == nb_pl:
        break

m3u = open(playlist_path, 'w')
m3u.write('#EXTM3U\n')

for song in playlist:
    m3u.write('#EXTINF:%s,%s - %s\n' % ('-1',song.artist,song.title))
    m3u.write(song.filename+'\n')
m3u.close()
<commit_msg>Update variables<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
from random import shuffle

separation_artist = 5
separation_title = 5
playlist_path = 'playlist.m3u'
playlist_size = 100

nb_pl = 0

bac = []
playlist = []
artists = []
titles = []
error = []

class Track:
    def __init__(self, artist, title, filename, duration=0):
        self.artist = artist
        self.title = title
        self.filename = filename
        self.duration = duration

def read_folder(folder):
    for song_file in os.listdir(folder):
        split = os.path.splitext(song_file)[0].split(' - ')
        artist = split[0]
        title = split[1]
        filename = os.path.abspath(song_file)
        bac.append(Track(artist, title, filename))
        artists.append(artist)
        titles.append(title)

def get_track(i):
    j = i % len(bac)
    print "i : %d" % i
    print "j : %d" % j
    track = bac[i]
    print track.artist
    playlist.append(track)

read_folder("music")

nb_artist = len(list(set(artists)))/2
nb_titles = len(list(set(titles)))/2

if separation_artist == 0:
    error.append("Warning: separation_artist must be set and greater than 0.")
if separation_title == 0:
    error.append("Warning: separation_title must be set and greater than 0.")
if playlist_path != '':
    error.append("Warning: playlist_path must be set and not empty.")
if playlist_size == 0:
    error.append("Warning: playlist_size must be set and greater than 0.")

if len(error) != 0:
    for err in error:
        print err
    sys.exit(0)

shuffle(bac)

while True:
    get_track(nb_pl)
    nb_pl+=1
    if playlist_size == nb_pl:
        break

m3u = open(playlist_path, 'w')
m3u.write('#EXTM3U\n')

for song in playlist:
    m3u.write('#EXTINF:%s,%s - %s\n' % ('-1',song.artist,song.title))
    m3u.write(song.filename+'\n')
m3u.close()
<|endoftext|>