import rclpy
from rclpy.action import ActionClient
from rclpy.node import Node
from std_msgs.msg import String
import os
import ast
import time

# Import ACTIONS:
from ros2_data.action import MoveG
from ros2_grasping.action import Attacher

# Import MESSAGES:
from ros2_data.msg import JointPose
from ros2_data.msg import JointPoseS

# Import MultiThreadedExecutor:
from rclpy.executors import MultiThreadedExecutor
RES = "null"

class MoveGclient(Node):

    def __init__(self):
        # 1. Initialise node:
        super().__init__('MoveG_client')
        self._action_client = ActionClient(self, MoveG, 'MoveG')
        # 2. Wait for MoveG server to be available:
        print ("Waiting for MoveG action server to be available...")
        self._action_client.wait_for_server()
        print ("MoveG ACTION SERVER detected.")

    def send_goal(self, GP):
        # 1. Assign variables:
        goal_msg = MoveG.Goal()
        goal_msg.goal = GP
        # 2. ACTION CALL:
        self._send_goal_future = self._action_client.send_goal_async(goal_msg, feedback_callback=self.feedback_callback)
        self._send_goal_future.add_done_callback(self.goal_response_callback)

    def goal_response_callback(self, future):
        goal_handle = future.result()
        if not goal_handle.accepted:
            self.get_logger().info('Goal rejected :(')
            return
        self.get_logger().info('Goal accepted :)')
        self._get_result_future = goal_handle.get_result_async()
        self._get_result_future.add_done_callback(self.get_result_callback)

    def get_result_callback(self, future):
        global RES
        # 1. Assign RESULT variable:
        result = future.result().result
        RES = result.result
        # 2. Print RESULT:
        print ("MoveG ACTION CALL finished.")

    def feedback_callback(self, feedback_msg):
        # 1. Assign FEEDBACK variable:
        feedback = feedback_msg.feedback
        # NO FEEDBACK NEEDED IN MoveG ACTION CALL.

class ATTACHERclient(Node):

    def __init__(self):
        # 1. Initialise node:
        super().__init__('Attacher_client')
        self._action_client = ActionClient(self, Attacher, 'Attacher')
        # 2. Wait for ATTACHER server to be available:
        print ("Waiting for ATTACHER action server to be available...")
        self._action_client.wait_for_server()
        print ("Attacher ACTION SERVER detected.")

    def send_goal(self, object, endeffector):
        # 1. Assign variables:
        print("Im at send_goal")
        goal_msg = Attacher.Goal()
        goal_msg.object = object
        goal_msg.endeffector = endeffector
        # 2. ACTION CALL:
        self._send_goal_future = self._action_client.send_goal_async(goal_msg)

# 12. DETACHER - Publihser:
class DetacherPUB(Node):

    def __init__(self):
        # Declare NODE:
        super().__init__("ros2_PUBLISHER")
        # Declare PUBLISHER:
        self.publisher_ = self.create_publisher(String, "ros2_Detach", 5) #(msgType, TopicName, QueueSize)

# CLASS: Input ROBOT End-Effector MODEL as ROS2 PARAMETER:
PARAM_EE = "schunk"
P_CHECK_EE = True

# CLASS: WARNING + CLOSE:
class CloseProgram():
    def CLOSE():
        print("")
        print("Please execute the program and input all ROS2 parameters in the Ubuntu Terminal as stated below:")
        #print('COMMAND -> ros2 run ros2_execution ros2_execution.py --ros-args -p PROGRAM_FILENAME:="---" -p ROBOT_MODEL:="---" -p EE_MODEL:="---"')
        print("Closing... BYE!")
        time.sleep(5)
        exit()

def main(args=None):
    global RES

    rclpy.init(args=args)

    global PARAM_EE
    global P_CHECK_EE

    if (PARAM_EE == "schunk" ):
        MoveG_CLIENT = MoveGclient()
        Attach_Client = ATTACHERclient()
        Detach_Client = DetacherPUB()

    # Create NODE for LOGGING:
    nodeLOG = rclpy.create_node('node_LOG')
     # OPEN PR_NAME.txt FILE:
    with open("cubePP.txt") as file:
        f = file.readlines()
        i = 1
        seq = dict()
        for line in f:
            seq[str(i)] = ast.literal_eval(line)
            i = i + 1
        file.close()

    # Log number of steps:
    nodeLOG.get_logger().info("Number of steps -> " + str(len(seq)))
    time.sleep(1)

    for i in range (1, len(seq)+1):

        trigger = seq[str(i)]

        if (trigger['action'] == 'Attach'):

            print("")
            print("STEP NUMBER " + str(i) + " -> ATTACH OBJECT:")
            print(trigger['value'])

            OBJ = trigger['value']['object']
            EE = trigger['value']['endeffector']

            Attach_Client.send_goal(OBJ,EE)
            rclpy.spin_once(Attach_Client)

            print("Object ATTACHED successfully.")

        elif (trigger['action'] == 'Detach'):

            print("")
            print("STEP NUMBER " + str(i) + " -> DETACH OBJECT:")
            print(trigger['value'])

            OBJ = trigger['value']['object']

            MSG = String()
            MSG.data = "True"

            t_end = time.time() + 1
            while time.time() < t_end:
                Detach_Client.publisher_.publish(MSG) # Publish repeatedly for a second to make sure that the ATTACHER SERVER receives the message.

            print("Object DETACHED successfully.")

        elif (trigger['action'] == 'GripperOpen'):

            if (PARAM_EE == "schunk"):

                print("")
                print("STEP NUMBER " + str(i) + " -> GripperOpen (MoveG).")

                GP = 0.0
                MoveG_CLIENT.send_goal(GP)

                while rclpy.ok():
                    rclpy.spin_once(MoveG_CLIENT)
                    if (RES != "null"):
                        break

                print ("Result of MoveG ACTION CALL is -> { " + RES + " }")

                if (RES == "MoveG:SUCCESS"):
                    print("MoveG ACTION in step number -> " + str(i) + " successfully executed.")
                    RES = "null"
                else:
                    print("MoveG ACTION in step number -> " + str(i) + " failed.")
                    print("The program will be closed. Bye!")
                    break
        elif (trigger['action'] == 'GripperClose'):

            if (PARAM_EE == "schunk"):

                print("")
                print("STEP NUMBER " + str(i) + " -> GripperClose (MoveG).")

                GP = 0.005
                MoveG_CLIENT.send_goal(GP)

                while rclpy.ok():
                    rclpy.spin_once(MoveG_CLIENT)
                    if (RES != "null"):
                        break

                print ("Result of MoveG ACTION CALL is -> { " + RES + " }")

                if (RES == "MoveG:SUCCESS"):
                    print("MoveG ACTION in step number -> " + str(i) + " successfully executed.")
                    RES = "null"
                else:
                    print("MoveG ACTION in step number -> " + str(i) + " failed.")
                    print("The program will be closed. Bye!")
                    break

        else:
            print("Step number " + str(i) + " -> Action type not identified. Please check.")
            print("The program will be closed. Bye!")
            nodeLOG.get_logger().info("ERROR: Program finished since ACTION NAME in step number -> " + str(i) + " was not identified.")
            break
    print("")
    print("SEQUENCE EXECUTION FINISHED!")
    print("Program will be closed. Bye!")
    nodeLOG.get_logger().info("SUCESS: Program execution sucessfully finished.")
    nodeLOG.destroy_node()
    print("Closing... BYE!")
    time.sleep(5)

if __name__ == '__main__':
    main()


import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

data_url="https://raw.githubusercontent.com/PrateekKumar2109/Assset-production-monitoring/main/Data/df_final3.csv"
df_fin = pd.read_csv(data_url)
df_final = df_fin[df_fin["Platform type"] == "Well head"]
st.set_page_config(layout="wide")

def map_plot(df, texts, font_size, show_lines=False):
    fig, ax = plt.subplots(figsize=(20, 16),dpi=600)
    ax.set_facecolor('#e6f3ff')

    sns.scatterplot(data=df, x='Longitude', y='Latitude', hue='Field', ax=ax, s=60)

    for i in range(len(df)):
        row = df.iloc[i]
        if texts:
            text = f"{row['Platform']}\n" + "\n".join([f"{text}: {row[text]}" for text in texts])
            text_color = 'orange' if row['Rig'] == 'yes' else 'black'
            ax.text(row['Longitude'], row['Latitude'], text, va='bottom', ha='left', fontsize=font_size, color=text_color,
                    bbox=dict(facecolor='white', edgecolor='black', boxstyle='round,pad=0.2'))
        else:
            ax.text(row['Longitude'], row['Latitude'], f"{row['Platform']}", va='bottom', ha='left', fontsize=16,
                    color='green' if row['Rig'] == 'yes' else 'black')

    if show_lines:
        lines = [
            {"start_lat": 18.72, "start_lon": 72.315, "length": 0.04, "angle": 30, "texts": [("Sector-I", 'bottom', 'left')]},
            {"start_lat": 18.77, "start_lon": 72.29, "length": 0.05, "angle": -13, "texts": [("Sector-II", 'top', 'left'), ("Sector-III", 'bottom', 'left')]},
            {"start_lat": 18.50, "start_lon": 72.24, "length": 0.04, "angle": 12, "texts": [("South Heera", 'bottom', 'left')]},
            {"start_lat": 18.609, "start_lon": 72.259, "length": 0.06, "angle": 145, "texts": [("Mid Heera", 'top', 'right'), ("North Heera", 'bottom', 'right')]}
        ]

        for line in lines:
            angle_rad = np.deg2rad(line["angle"])
            end_lat = line["start_lat"] + line["length"] * np.sin(angle_rad)
            end_lon = line["start_lon"] + line["length"] * np.cos(angle_rad)
            plt.plot([line["start_lon"], end_lon], [line["start_lat"], end_lat], linestyle='dashed', color='black')

            for text, va, ha in line['texts']:

                text_x, text_y = (end_lon, end_lat) if line is lines[3] else (line["start_lon"], line["start_lat"])
                text_x -= 0.015  # Shift text_x by -0.1
                text_y -= 0.015  # Shift text_y by -0.1
                ax.text(text_x, text_y, text, va=va, ha=ha, fontsize=font_size,
                        color='red', bbox=dict(facecolor='white', edgecolor='black', boxstyle='round,pad=0.2'))

    plt.title('Offshore Platforms', fontsize=24)
    plt.gca().axes.get_xaxis().set_visible(False)
    plt.gca().axes.get_yaxis().set_visible(False)

    return fig

st.title('NH Asset Platforms')

option = st.sidebar.selectbox('Select Option', ('None', 'OP', 'GP', 'WI', 'GI'), index=0)

show_lines = False
if option == 'None':
    texts = []
    font_size = 16
    show_lines = True
elif option == 'OP':
    df_final = df_final[df_final['LIQUID RATE(BLPD)'] > 0.1]
    column_rename_dict = {"LIQUID RATE(BLPD)": "L blpd", "OIL(BOPD)": "O bopd"}
    df_final.rename(columns=column_rename_dict, inplace=True)
    df_final["L blpd"] = df_final["L blpd"].astype(int)
    df_final["O bopd"] = df_final["O bopd"].astype(int)
    texts = ["L blpd", "O bopd"]
    font_size = 8
elif option == 'GP':
    df_final = df_final[df_final['Free gas'] > 0.1]
    df_final['Free gas'] = df_final['Free gas'].astype(int)
    texts = ['Free gas']
    font_size = 16
elif option == 'WI':
    df_final = df_final[df_final['Injection rate bwpd'] > 0.1]
    column_rename_dict = {'Injection rate bwpd': "WI bwpd"}
    df_final.rename(columns=column_rename_dict, inplace=True)
    df_final["WI bwpd"] = df_final["WI bwpd"].astype(int)
    texts = ["WI bwpd"]
    font_size = 14
elif option == 'GI':
    df_final = df_final[df_final['GAS LIFT RATE(M3/DAY)'] > 0.1]
    column_rename_dict = {'GAS LIFT RATE(M3/DAY)': "GI m3/d"}
    df_final.rename(columns=column_rename_dict, inplace=True)
    df_final["GI m3/d"] = df_final["GI m3/d"].astype(int)
    texts = ["GI m3/d"]
    font_size = 11

st.pyplot(map_plot(df_final, texts, font_size, show_lines))


from xAPIConnector import *
from trading_systems import CrossTrader, BacktestCrossTrader
from trader_utils import *
from trader_db_utils import *
from logger_settings import *
from custom_exceptions import *
import matplotlib.pyplot as plt

from multiprocessing import Process

from tqdm import tqdm
import pickle as pkl
import logging
import time
import os
import sys
import argparse
from multiprocessing import SimpleQueue
from connection_clock import Clock
import warnings
import copy as cp

TRADER_NAME = "ANALYSIS"
test = 1
custom_logger = CustomLogger(test_name=TRADER_NAME)
logger = logging.getLogger(__name__)
logger = custom_logger.setup_logging(logger, TRADER_NAME, console_debug=True)

def load_candles():
    trader = BacktestCrossTrader(
        name=f"trader68709:",
        capital=1000,
        max_risk=0.05,
        trader_type="FX",
        logger=logger,
        test=test,
    )

    logger.info(f"OFFLINE TRADER")
    trader.CLOCK.wait_clock()
    trader.start_api_client()

    if os.path.exists("results/symbols_df.pkl"):
        with open("results/symbols_df.pkl", "rb") as f:
            symbols_df = pkl.load(f)
    else:
        commandResponse = trader.CLIENT.commandExecute(commandName="getAllSymbols")
        symbols_df = return_as_df(commandResponse["returnData"])
        trader.DB.insert_symbols(symbols_df)

        with open("results/symbols_df.pkl", "wb") as f:
            pkl.dump(symbols_df, f, pkl.HIGHEST_PROTOCOL)

    trader.update_stocks(
        symbols_df[symbols_df["categoryName"] == "FX"],
        period=1,
        days=360,
        force=True,
    )

def get_slope(prev_candle, c_candle, short_ma, long_ma):
    min_ctm, max_ctm = short_ma, long_ma
    min_close, max_close = c_candle["min"], c_candle["max"]

    prev_ctm = min_max_norm(prev_candle["index"], min_ctm, max_ctm)
    c_ctm = min_max_norm(c_candle["index"], min_ctm, max_ctm)
    prev_short = min_max_norm(prev_candle["short_ma"], min_close, max_close)
    c_short = min_max_norm(c_candle["short_ma"], min_close, max_close)
    prev_long = min_max_norm(prev_candle["long_ma"], min_close, max_close)
    c_long = min_max_norm(c_candle["long_ma"], min_close, max_close)

    p1 = [prev_ctm, prev_short]
    p2 = [c_ctm, c_short]
    x1, y1 = p1
    x2, y2 = p2
    ma_short_slope = (y2 - y1) / (x2 - x1)

    p1 = [prev_ctm, prev_long]
    p2 = [c_ctm, c_long]
    x1, y1 = p1
    x2, y2 = p2
    ma_long_slope = (y2 - y1) / (x2 - x1)
    return ma_short_slope, ma_long_slope

def get_absolute_angles(prev_candle, c_candle, short_ma, long_ma):
    ma_short_slope, ma_long_slope = get_slope(prev_candle, c_candle, short_ma, long_ma)
    angle_short = np.degrees(
        np.arctan((ma_short_slope - 0) / (1 + (ma_short_slope * 0)))
    )
    angle_long = np.degrees(np.arctan((ma_long_slope - 0) / (1 + (ma_long_slope * 0))))
    return angle_short, angle_long

def get_angle_between_slopes(prev_candle, c_candle, short_ma, long_ma):
    m1, m2 = get_slope(prev_candle, c_candle)
    return np.degrees(np.arctan((m1 - m2) / (1 + (m1 * m2))))

def buy_slope(self, prev_candle, c_candle, min_angle, spread):
    buy_short = False
    buy_long = False
    short_a, long_a = get_absolute_angles(prev_candle, c_candle)
    if np.abs(c_candle["short_ma"] - c_candle["long_ma"]) > spread:
        if short_a < -(min_angle * 2) and long_a < -(min_angle / 2):
            # trend is negative
            buy_short = False
            buy_long = True
        elif short_a > (min_angle * 2) and long_a > (min_angle / 2):
            # trend is positive
            buy_short = True
            buy_long = False
        else:
            buy_short = False
            buy_long = False
    else:
        buy_short = False
        buy_long = False
    return buy_short, buy_long

def find_trades(candle):
    index = candle["index"]
    if (
        (candle["angle_short"] < -(min_angle * 2))
        and (candle["angle_long"] > (min_angle / 5))
        and (candle["short_ma"] > candle["long_ma"])
    ):
        short_signals += 2
        buy_signals = 0
        if short_signals > 5 and not short:
            trades[index] = -1
            short_signals = 0
            short = True
            buy = False
        # trades[index] = -1
    elif (candle["angle_short"] < -(min_angle)) and (
        candle["angle_long"] < -(min_angle / 2)
    ):
        short_signals += 2
        buy_signals = 0
        if short_signals > 5 and not short:
            trades[index] = -1
            short_signals = 0
            short = True
            buy = False
        # trades[index] = -1
    elif (
        (candle["angle_short"] > (min_angle * 2))
        and (candle["angle_long"] < -(min_angle / 5))
        and (candle["short_ma"] < candle["long_ma"])
    ):
        short_signals = 0
        buy_signals += 2
        if buy_signals > 5 and not buy:
            trades[index] = 1
            buy_signals = 0
            buy = True
            short = False
        # trades[index] = 1
    elif (candle["angle_short"] > (min_angle)) and (
        candle["angle_long"] > (min_angle / 2)
    ):
        short_signals = 0
        buy_signals += 2
        if buy_signals > 5 and not buy:
            trades[index] = 1
            buy_signals = 0
            buy = True
            short = False
        # trades[index] = 1
    else:
        # short_signals = 0
        # buy_signals = 0
        trades[index] = 0

def run_trade(candles, exit, exit_profit):
    profits = []
    first_candle = candles.iloc[0, :]
    price = np.round(np.average(first_candle[["open", "close", "high", "low"]]), 5)
    first_index = first_candle["index"]
    first_time = first_candle.name
    trade_type = first_candle["trades"]
    for index in range(1, candles.shape[0]):
        candle = candles.iloc[index, :]
        if trade_type == 1:
            # BUY
            order_type = "BUY"
            trigger = candle["short_ma"]
            new_price = np.round(
                np.average(candle[["open", "close", "high", "low"]]), 5
            )
            profits.append(new_price - price)
            if new_price < price:
                close_type = -1
                break

        elif trade_type == -1:
            # SHORT
            order_type = "SHORT"
            trigger = candle["short_ma"]
            new_price = np.round(
                np.average(candle[["open", "close", "high", "low"]]), 5
            )
            profits.append(price - new_price)
            if new_price > price:
                close_type = -1
                break

        if len(profits) > 3:
            if profits[-2] / profits[-1] < exit_profit:
                close_type = 0
                break
            elif profits[-1] > exit:
                close_type = 1
                break
    return (
        profits[-1],
        {
            "Type": order_type,
            "open_index": first_index,
            "open_time": first_time,
            "open_price": price,
            "close_index": candle["index"],
            "close_time": candle.name,
            "close_price": new_price,
            "profit": profits[-1],
            "profits": profits,
        },
        close_type,
    )

if os.path.exists("results/jan2023_forex_candles.pkl"):
    logger.info("Loading Candles of 2022")
    with open("results/jan2023_forex_candles.pkl", "rb") as f:
        fx_candles = pkl.load(f)
else:
    if os.path.exists("results/symbols_df.pkl"):
        logger.info("")
        with open("results/symbols_df.pkl", "rb") as f:
            symbols_df = pkl.load(f)
    else:
        load_candles()

    trader = BacktestCrossTrader(
        name=f"trader68709:",
        capital=1000,
        max_risk=0.05,
        trader_type="FX",
        logger=logger,
        test=test,
    )
    start_date = (datetime.strptime("23-02-2022", "%d-%m-%Y")).strftime("%m-%d-%Y")
    end_date = (datetime.strptime("23-02-2023", "%d-%m-%Y")).strftime("%m-%d-%Y")
    candles = trader.DB.get_candles_range(start_date=start_date, end_date=end_date)
    candles = candles[["symbol", "ctmstring", "open", "high", "low", "close", "vol"]]

    fx_candles = cp.deepcopy(candles)
    fx_symbols = list(symbols_df[symbols_df["categoryName"] == "FX"]["symbol"].values)
    for symbol in candles["symbol"].unique():
        if symbol not in fx_symbols:
            fx_candles = fx_candles[fx_candles["symbol"] != symbol]

    fx_candles["ctmstring"] = pd.to_datetime(fx_candles["ctmstring"])
    fx_candles = fx_candles.set_index("ctmstring")
    fx_candles = fx_candles[fx_candles.index.dayofweek < 5]
    with open("results/last_year_forex_candles.pkl", "wb") as f:
        pkl.dump(fx_candles, f, pkl.HIGHEST_PROTOCOL)

long_ma = 1000
short_ma = 30
spread = 0.00009
min_angle = 30
for symbol in fx_candles["symbol"].unique():
    candles = cp.deepcopy(fx_candles[fx_candles["symbol"] == symbol])
    candles = candles.reset_index()
    candles = candles.drop_duplicates()
    candles = candles.set_index("ctmstring")
    candles["index"] = np.arange(0, candles.shape[0])
    candles["short_ma"] = candles["close"].rolling(60).mean()
    candles["long_ma"] = candles["close"].rolling(long_ma).mean()
    candles["max"] = candles["high"].rolling(long_ma).max()
    candles["min"] = candles["low"].rolling(long_ma).min()

    short_angles = []
    long_angles = []

    candles["prev_ctm"] = 0.999
    candles["c_ctm"] = 1
    candles["prev_short"] = min_max_norm(
        candles["short_ma"].shift(1), candles["min"], candles["max"]
    )
    candles["c_short"] = min_max_norm(
        candles["short_ma"], candles["min"], candles["max"]
    )
    candles["prev_long"] = min_max_norm(
        candles["long_ma"].shift(1), candles["min"], candles["max"]
    )
    candles["c_long"] = min_max_norm(candles["long_ma"], candles["min"], candles["max"])

    candles["ma_short_slope"] = (candles["c_short"] - candles["prev_short"]) / (
        candles["c_ctm"] - candles["prev_ctm"]
    )
    candles["ma_long_slope"] = (candles["c_long"] - candles["prev_long"]) / (
        candles["c_ctm"] - candles["prev_ctm"]
    )

    candles["angle_short"] = np.degrees(
        np.arctan(
            (candles["ma_short_slope"] - 0) / (1 + (candles["ma_short_slope"] * 0))
        )
    )
    candles["angle_long"] = np.degrees(
        np.arctan((candles["ma_long_slope"] - 0) / (1 + (candles["ma_long_slope"] * 0)))
    )

    trades = np.zeros((candles.shape[0]))
    short_signals = 0
    buy_signals = 0
    buy = False
    short = False

    for index in tqdm(range(long_ma, candles.shape[0])):
        # logger.info(f"\nBuy-signals:{buy_signals}\nShort-signals: {short_signals}")
        candle = candles.iloc[index, :]
        if np.abs(candle["short_ma"] - candle["long_ma"] > spread):
            if (
                (candle["angle_short"] < -(min_angle * 2))
                and (candle["angle_long"] > (min_angle / 5))
                and (candle["short_ma"] > candle["long_ma"])
            ):
                short_signals += 1
                buy_signals = 0
                if short_signals < 2 and not short:
                    trades[index] = -1
                    short_signals = 0
                    short = True
                    buy = False
                # trades[index] = -1
                # trades[index] = 0
            elif (candle["angle_short"] < -(min_angle)) and (
                candle["angle_long"] < -(min_angle / 2)
            ):
                short_signals += 1
                buy_signals = 0
                if short_signals < 2 and not short:
                    trades[index] = -1
                    short_signals = 0
                    short = True
                    buy = False
                # trades[index] = -1
                # trades[index] = 0
            elif (
                (candle["angle_short"] > (min_angle * 2))
                and (candle["angle_long"] < -(min_angle / 5))
                and (candle["short_ma"] < candle["long_ma"])
            ):
                short_signals = 0
                buy_signals += 1
                if buy_signals > 2 and not buy:
                    trades[index] = 1
                    buy_signals = 0
                    buy = True
                    short = False
                # trades[index] = 1
                # trades[index] = 0
            elif (candle["angle_short"] > (min_angle)) and (
                candle["angle_long"] > (min_angle / 2)
            ):
                short_signals = 0
                buy_signals += 1
                if buy_signals < 2 and not buy:
                    trades[index] = 1
                    buy_signals = 0
                    buy = True
                    short = False
                # trades[index] = 1
                # trades[index] = 0
            else:
                # short_signals = 0
                # buy_signals = 0
                trades[index] = 0

    candles["trades"] = trades
    plot_stock_simple(
        candles.iloc[:1000, :],
        show=True,
    )
    pass

    indices = list(np.where(candles["trades"] != 0)[0])
    short = False
    buy = False
    last_price = None
    returns = []
    trades = []
    close_types = []
    for index in tqdm(indices):
        ret, trade, close_type = run_trade(
            candles.iloc[index:, :], exit=0.01, exit_profit=0.95
        )
        returns.append(ret)
        trades.append(trade)
        close_types.append(close_type)

    plt.figure()
    plt.bar(range(len(returns)), returns)
    plt.title(f"Result: {np.sum(returns)}")
    plt.figure()
    counts, bins = np.histogram(close_types, bins=3)
    plt.hist(x=["-1", "0", "1"], bins=3, weights=counts, align="mid")
    plt.figure()
    plt.plot(np.cumsum(returns))
    plt.pause(0.1)

    plot_stock_all_trades(candles, trades, show=False)


old_record = float(input())
distance = float(input())
time_per_metter = float(input())
delay = distance // 15 * 12.5

total_time = distance * time_per_metter + delay
if total_time < old_record:
    print(f" Yes, he succeeded! The new world record is {total_time:.2f} seconds.")
else:
    print(f"No, he failed! He was {abs(old_record - total_time):.2f} seconds slower.")


from flask import Flask, jsonify, request
from flask_cors import CORS
import uuid
app = Flask(__name__)

app.config.from_object(__name__)

CORS(app, resources={r"/*":{'origins':"*"}})

#Hello world route
@app.route('/', methods=['GET'])
def greetings():
    return("Hello, world!")

GAMES = []

# GET and POST route handler
@app.route('/games', methods=['GET', 'POST'])
def all_games():
    response_object = {'status':'success'}
    if request.method == "POST":
        post_data = request.get_json()
        GAMES.append({
            'id': uuid.uuid4().hex,
            'title': post_data.get('title'),
            'genre': post_data.get('genre'),
            'played': post_data.get('played'),
            'platinum': post_data.get('platinum')})
        response_object['message'] = 'Game Added!'
    else:
        response_object['games'] = GAMES
    return jsonify(response_object)

# PUT and DELETE route handler
@app.route('/games/<game_id>', methods =['PUT', 'DELETE'])
def single_game(game_id):
    response_object = {'status':'success'}
    if request.method == "PUT":
        post_data = request.get_json()
        remove_game(game_id)
        GAMES.append({
            'id': uuid.uuid4().hex,
            'title': post_data.get('title'),
            'genre': post_data.get('genre'),
            'played': post_data.get('played'),
            'platinum': post_data.get('platinum')})
        response_object['message'] = 'Game Updated!'
    if request.method == "DELETE":
        remove_game(game_id)
        response_object['message'] = 'Game deleted!'
    return jsonify(response_object)

# Removing the game to update it
def remove_game(game_id):
    for game in GAMES:
        if game['id'] == game_id:
            GAMES.remove(game)
            return True
    return False

if __name__ == "__main__":
    app.run(debug=True)


# %%
from keras.preprocessing.image import load_img, img_to_array
import matplotlib.image
import os

from tensorflow import keras
import tensorflow as tf
import numpy as np
from sklearn.metrics import confusion_matrix
import seaborn as sns

import matplotlib.pyplot as plt

# %%
# Set seeds for reproducibility
os.environ['PYTHONHASHSEED'] = '0'
np.random.seed(42)
tf.random.set_seed(42)

# %%

def show_training_plots(history):
    plt.figure(figsize=(12, 4))

    plt.subplot(1, 2, 1)
    plt.plot(history.history['loss'], label='Training Loss')
    plt.plot(history.history['val_loss'], label='Validation Loss')
    plt.title('Training and Validation Loss')
    plt.xlabel('Epochs')
    plt.ylabel('Loss')
    plt.legend()

    plt.subplot(1, 2, 2)
    plt.plot(history.history['accuracy'], label='Training Accuracy')
    plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
    plt.title('Training and Validation Accuracy')
    plt.xlabel('Epochs')
    plt.ylabel('Accuracy')
    plt.legend()

    plt.tight_layout()
    plt.show()

def evaluate_model(model, test_x, test_y):
    loss, accuracy = model.evaluate(test_x, test_y, verbose=0)
    print(f'Test loss: {loss:.3}')
    print(f'Test accuracy: {accuracy:.3}')

# %%  [markdown]
"""
## Excercise 1

### Question 1

- Detected license plates on cars either in a video stream or in a picture.
- In pictures of a street, detect the house numbers.
- Auto checking the answers of a hand written primary school math exam.
- Extracting the amount and bank number from a hand-written check.
- Checking hand written solutions to sudoku puzzles.
"""

# %%
# Load the MNIST dataset
(x_train_raw, y_train_raw), (x_test_raw,
                             y_test_raw) = keras.datasets.mnist.load_data()

# %%

indices = np.arange(len(x_train_raw))
eights = indices[y_train_raw == 8]
selected_index = np.take(eights, 1)
eight = x_train_raw[selected_index]
plt.imshow(eight, cmap="gray")
plt.show()

# %%

matplotlib.image.imsave('eight.png', eight)

# %%
# Check dimesions of the data
print(x_train_raw.shape)
print(x_test_raw.shape)

# %%
# Flatten the data
x_train_flat = x_train_raw.reshape(x_train_raw.shape[0], -1)
x_test_flat = x_test_raw.reshape(x_test_raw.shape[0], -1)

print(x_train_flat.shape)
print(x_test_flat.shape)

# %%
# Rescale the data
x_train_flat = x_train_flat / 255
x_test_flat = x_test_flat / 255

# %%
# Make y categorical
y_train = keras.utils.to_categorical(y_train_raw, 10)
y_test = keras.utils.to_categorical(y_test_raw, 10)

# %%
# Model definition
model = keras.Sequential()
model.add(keras.layers.Dense(256, input_shape=(784,)))
model.add(keras.layers.Dense(10, activation="softmax"))
model.summary()

# %%
# Compile model
model.compile(
    loss='categorical_crossentropy',
    optimizer=keras.optimizers.RMSprop(),
    metrics='accuracy'
)

# %%
history = model.fit(
    x_train_flat,
    y_train,
    batch_size=128,
    epochs=12,
    verbose=1,
    validation_split=0.2
)

# %%
show_training_plots(history)

# %%
evaluate_model(model, x_test_flat, y_test)

# %%
y_pred = model.predict(x_test_flat)
y_pred_classes = np.argmax(y_pred, axis=1)

# Compute the Confusion Matrix
conf_matrix = confusion_matrix(y_test_raw, y_pred_classes)

# Plot the Confusion Matrix

plt.figure(figsize=(10, 8))
sns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues')
plt.xlabel('Predicted Label')
plt.ylabel('True Label')
plt.title('Confusion Matrix')
plt.show()

# %%  [markdown]
"""
### Question 2

1. At the first epoch, we can see that the training accuracy is lower than the validation accuracy, and conversely, the training loss is higher than the validation loss.
This might be due to the fact that the validation set is much smaller, thus has less varation within the dataset to be captured by the model. Since the training set is larger, there's a bigger chance that edge cases occur in it, that might be misclassified when the model hasn't training much yet.
2. Then we see that the training accuracy increases, and the training loss decreases rapidly in the first epochs. The validation loss also decreases, and the accuracy also increases, but not nearly as quickly.
This might be due to the fact that the model learns the features from the training set.  These features might not initially generalise too well to the validation set, but instantly perform way better on the images on which is was trained. In a way it tends towards overfitting to the training set.
3. Then we see that the training accuracy keeps on increases, and the loss decreasing, as the amount of epochs increase. The loss and accuracy of the validation set plateaus after around epoch 3.
This might be due to the fact that the model overfits to the training data over time, while not learning abstract enough features that generalise to the validation set. The features that are learned are specific to the traning data, and thus score high on them. But the features might be idiosyncratic to the training set, and not be a general feature for the entire spectrum of digits, e.g. digits in the validation set.
"""

# %%
# Model definition
relu_model = keras.Sequential()
relu_model.add(keras.layers.Dense(256, input_shape=(784,), activation="relu"))
relu_model.add(keras.layers.Dense(10, activation="softmax"))
relu_model.summary()

# %%
# Compile model
relu_model.compile(
    loss='categorical_crossentropy',
    optimizer=keras.optimizers.RMSprop(),
    metrics='accuracy'
)

# %%
relu_history = relu_model.fit(
    x_train_flat,
    y_train,
    batch_size=128,
    epochs=12,
    verbose=1,
    validation_split=0.2
)

# %%
show_training_plots(relu_history)

# %%
evaluate_model(relu_model, x_test_flat, y_test)

# %%
# Rshape data
x_train_spatial = x_train_raw[..., np.newaxis]
x_test_spatial = x_test_raw[..., np.newaxis]
x_train_spatial = x_train_spatial / 255
x_test_spatial = x_test_spatial / 255

print(x_train_spatial.shape)
print(x_test_spatial.shape)

# %%
cnn_model = keras.Sequential()
cnn_model.add(keras.layers.Conv2D(filters=32, kernel_size=(3, 3),
                                  activation="relu", input_shape=(28, 28, 1)))
cnn_model.add(keras.layers.Conv2D(filters=64, kernel_size=(3, 3),
                                  activation="relu"))
cnn_model.add(keras.layers.MaxPool2D(pool_size=(2, 2)))
cnn_model.add(keras.layers.Flatten())
cnn_model.add(keras.layers.Dense(128, activation="relu"))
cnn_model.add(keras.layers.Dense(10, activation="softmax"))

cnn_model.compile(
    loss='categorical_crossentropy',
    optimizer=keras.optimizers.Adadelta(learning_rate=1),
    metrics='accuracy'
)

# %%
cnn_history = cnn_model.fit(
    x_train_spatial,
    y_train,
    batch_size=128,
    epochs=6,
    verbose=1,
    validation_split=0.2
)

# %%
show_training_plots(cnn_history)

# %%
evaluate_model(cnn_model, x_test_spatial, y_test)

# %%
dropout_cnn_model = keras.Sequential()
dropout_cnn_model.add(keras.layers.Conv2D(filters=32, kernel_size=(3, 3),
                                          activation="relu", input_shape=(28, 28, 1)))
dropout_cnn_model.add(keras.layers.Conv2D(filters=64, kernel_size=(3, 3),
                                          activation="relu"))
dropout_cnn_model.add(keras.layers.MaxPool2D(pool_size=(2, 2)))
dropout_cnn_model.add(keras.layers.Dropout(0.25))
dropout_cnn_model.add(keras.layers.Flatten())
dropout_cnn_model.add(keras.layers.Dense(128, activation="relu"))
dropout_cnn_model.add(keras.layers.Dropout(0.5))
dropout_cnn_model.add(keras.layers.Dense(10, activation="softmax"))

dropout_cnn_model.compile(
    loss='categorical_crossentropy',
    optimizer=keras.optimizers.Adadelta(learning_rate=1),
    metrics='accuracy'
)

# %%
dropout_cnn_history = dropout_cnn_model.fit(
    x_train_spatial,
    y_train,
    batch_size=128,
    epochs=6,
    verbose=1,
    validation_split=0.2
)

# %%
show_training_plots(dropout_cnn_history)

# %%
evaluate_model(dropout_cnn_model, x_test_spatial, y_test)

# %%  [markdown]
"""
## Excercise 2
"""

# %%
(x_train_cifar, y_train_cifar), (x_test_cifar,
                                 y_test_cifar) = keras.datasets.cifar10.load_data()

# %%
x_train_cifar = x_train_cifar / 255
x_test_cifar = x_test_cifar / 255

# %%
y_train_cifar = keras.utils.to_categorical(y_train_cifar, 10)
y_test_cifar = keras.utils.to_categorical(y_test_cifar, 10)

# %%
cifar_cnn = keras.Sequential()
cifar_cnn.add(keras.layers.Conv2D(
    filters=32,
    kernel_size=(3, 3),
    activation="relu",
    input_shape=(32, 32, 3),
    padding="same"
))
cifar_cnn.add(keras.layers.Conv2D(filters=32, kernel_size=(3, 3),
                                  activation="relu"))
cifar_cnn.add(keras.layers.MaxPool2D(pool_size=(2, 2)))
cifar_cnn.add(keras.layers.Dropout(0.25))
cifar_cnn.add(keras.layers.Conv2D(
    filters=32,
    kernel_size=(3, 3),
    activation="relu",
))
cifar_cnn.add(keras.layers.Conv2D(filters=32, kernel_size=(3, 3),
                                  activation="relu"))
cifar_cnn.add(keras.layers.MaxPool2D(pool_size=(2, 2)))
cifar_cnn.add(keras.layers.Dropout(0.25))
cifar_cnn.add(keras.layers.Flatten())
cifar_cnn.add(keras.layers.Dense(512, activation="relu"))
cifar_cnn.add(keras.layers.Dropout(0.5))
cifar_cnn.add(keras.layers.Dense(10, activation="softmax"))

cifar_cnn.compile(
    loss='categorical_crossentropy',
    optimizer=keras.optimizers.RMSprop(
        learning_rate=0.0001, weight_decay=1e-6),
    metrics='accuracy'
)

# %%
cifar_cnn_history = cifar_cnn.fit(
    x_train_cifar,
    y_train_cifar,
    batch_size=32,
    epochs=20,
    verbose=1,
    validation_data=(x_test_cifar, y_test_cifar),
    shuffle=True
)

# %%
show_training_plots(cifar_cnn_history)

# %%  [markdown]
"""
Low level functions
"""

# img = img_to_array(load_img("eight.png", color_mode="grayscale")) / 255
img = img_to_array(load_img("eight.png")) / 255
# Change dims from 28 28 1 to 28 28 3
# img = np.repeat(img, 3, axis=2)
img.shape

# %%

def relu(x):
    """
    Rectified linear unit activation function.

    Parameters
    ----------
    x: np.ndarray, shape=(height, width, feature_maps)
        Input array to apply ReLU to ().

    Returns
    -------
    np.ndarray
        Output array with ReLU applied.
    """
    return np.maximum(x, 0)

relu_img = relu(img)
relu_img.shape
# %%

def max_pooling(x, pool_size):
    """
    Max pooling function.

    Finds the maximum value within each feature map.

    Parameters
    ----------
    x: np.ndarray, shape=(height, width, feature_maps)
        Input array to apply max pooling to.
    pool_size: tuple
        Size of the pooling window, must be 2D (heigth, width).

    Returns
    -------
    np.ndarray
        Output array with max pooling applied.
    """
    pool_heigth, pool_width = pool_size
    height, width, feature_maps = x.shape

    if pool_heigth > height or pool_width > width:
        raise ValueError("Pool size must be smaller than input size.")

    output = np.zeros(
        (height // pool_heigth, width // pool_width, feature_maps))

    for feature_map in range(feature_maps):
        for i in range(0, height, pool_heigth):
            for j in range(0, width, pool_width):
                output[i // pool_heigth, j // pool_width, feature_map] = np\
                    .max(
                    x[i:i + pool_heigth, j:j + pool_width]
                )

    return output

pooled_img = max_pooling(relu_img, (2, 2))
plt.imshow(pooled_img)
plt.show()

# %%
def feature_map_norm(x):
    """
    Normalise values within each feature maps.

    Normalises values to have zero mean and standard deviation of 0.

    Parameters
    ----------
    x: np.ndarray, shape=(height, width, feature_maps)
        Input array to normalise.

    Returns
    -------
    np.ndarray
        Output array with normalised values.
    """
    return (x - np.mean(x)) / np.std(x)

norm_img = feature_map_norm(img)

plt.imshow(norm_img, cmap="gray")
plt.show()

# %%
def create_fully_connected(x, weights):
    """
    Creates a fully connected layer.

    x: np.ndarray, shape=(height, width, feature_maps)
    weights: np.ndarray, shape=(n_input_layers, n_output_layers)

    Returns
    -------
    np.ndarray
        Output array with weights from fully connected layer applied.
    """
    return x.flatten() @ weights

# %%
n_inputs = norm_img.flatten().shape[0]
random_weights = 2 * np.random.rand(n_inputs, 10) - 1
output_activations = create_fully_connected(norm_img, random_weights)

# %%
def softmax(x):
    """
    Apply softmax to array.

    Parameters
    ----------
    x: np.ndarray, shape=(n_inputs,)

    Returns
    -------
    np.ndarray
        Probability distribution over input array, sums to 1.
    """
    return np.exp(x) / np.sum(np.exp(x))

softmax(output_activations)


#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue May 21 16:59:54 2019

@author: lanot
"""

from netCDF4 import Dataset
#from mpl_toolkits.basemap import Basemap
#import matplotlib.pyplot as plt
from time import strftime,strptime
#import cartopy.crs as crrs
#import sys
import os
from glob import glob
#from osgeo import gdal
import numpy as np
from shapely.geometry import Point
import geopandas as gpd
import pandas as pd
import shutil

def fecha(archivo):
    fechaStr = archivo[archivo.find('_e')+2:archivo.find('_c')-2]
    fechaStr = strptime(fechaStr,"%Y%j%H%M%S")
    fechaG16 = strftime("%Y-%m-%dT%H:%M:%SZ",fechaStr)
    ano = strftime("%Y",fechaStr)
    dia = strftime("%j",fechaStr)
    hora = strftime("%H",fechaStr)
    minuto = strftime("%M",fechaStr)
    fechaArch = ano+dia+hora+minuto

    return fechaStr,fechaG16,ano,dia,hora,minuto,fechaArch

def varDatos(ds,variable):
    if variable == 'event':
        lat = ds.variables[variable+'_lat'][:]
        lon = ds.variables[variable+'_lon'][:]
        event_time = ds.variables[variable+'_time_offset'][:]
        #area = ds.variables[variable+'_area'][:]
        energy = ds.variables[variable+'_energy'][:]
        #quality = ds.variables[variable+'_quality_flag'][:]
        id_var = ds.variables[variable+'_id'][:]
        return lat,lon,event_time,energy,id_var
    else :
        lat = ds.variables[variable+'_lat'][:]
        lon = ds.variables[variable+'_lon'][:]
        area = ds.variables[variable+'_area'][:]
        energy = ds.variables[variable+'_energy'][:]
        quality = ds.variables[variable+'_quality_flag'][:]
        id_var = ds.variables[variable+'_id'][:]
        return lat,lon,area,energy,quality,id_var

def generaGeom(lon,lat):
    geom = []
    for x,y in zip(lon,lat):
        coor = Point(x,y)
        geom.append(coor)

    return geom

def generaGDF (id_var,energy,area,quality,time,lon,lat,geom):
    df = pd.DataFrame({'id':id_var,'energy/J':energy,'area/m2':area,'quality':quality,'time':time,'lon':lon,'lat':lat,'geometry':geom} )
    df = df[['id','energy/J','area/m2','quality','time','lon','lat','geometry']]
    gdf = gpd.GeoDataFrame(df,geometry='geometry')
    gdf.crs = '+proj=longlat +ellps=GRS80 +no_defs'

    return gdf

def generaGDF_event (id_var,energy,event_time,time,lon,lat,geom):
    df = pd.DataFrame({'id':id_var,'energy/J':energy,'t_offset/s':event_time,'time':time,'lon':lon,'lat':lat,'geometry':geom} )
    df = df[['id','energy/J','t_offset/s','time','lon','lat','geometry']]
    gdf = gpd.GeoDataFrame(df,geometry='geometry')
    gdf.crs = '+proj=longlat +ellps=GRS80 +no_defs'

    return gdf

def generaShape(gdf,variable,ano,dia,hora,nombre):
    os.system('cd /data1/output/glm/shapefile/fd/;mkdir -p '+dia+'/'+hora)
    os.system('mkdir /data1/output/glm/shapefile/fd/'+dia+'/'+hora+'/'+nombre)
    gdf.to_file(filename='/data1/output/glm/shapefile/fd/'+dia+'/'+hora+'/'+nombre+'/'+nombre+'.shp',driver='ESRI Shapefile')
    shutil.make_archive('/data1/output/glm/shapefile/fd/'+dia+'/'+hora+'/'+nombre, 'zip','/data1/output/glm/shapefile/fd/'+dia+'/'+hora+'/'+nombre)
    #os.system('zip '+'./shapefiles/'+variable+'/'+fechaArch+'.zip'+' ./shapefiles/'+variable+'/'+fechaArch)
    os.system('cd '+'/data1/output/glm/shapefile/fd/'+dia+'/'+hora+'/'+nombre+';rm *')
    os.system('rm -r '+'/data1/output/glm/shapefile/fd/'+dia+'/'+hora+'/'+nombre)

def generaCSV(gdf,variable,ano,dia,hora,nombre):
    os.system('cd /data1/output/glm/csv/fd/;mkdir -p '+dia+'/'+hora)
    gdf.to_csv('/data1/output/glm/csv/fd/'+dia+'/'+hora+'/'+nombre+'.csv')
    #os.system('zip '+'./csv/'+variable+'/'+fechaArch+'.zip'+' ./csv/'+variable+'/'+fechaArch+'.csv')
    #os.system('rm '+'./csv/'+variable+'/'+fechaArch)

def gmlProsesa(variable,glm,ano,dia,hora,nombre):
    if variable == 'event':
        lat,lon,event_time,energy,id_var = varDatos(glm,variable)
        time = np.full(lat.shape,nombre)
        geom = generaGeom(lon,lat)
        gdf = generaGDF_event(id_var,energy,event_time,time,lon,lat,geom)
        generaShape(gdf,variable,ano,dia,hora,nombre)
        generaCSV(gdf,variable,ano,dia,hora,nombre)

    else:
        lat,lon,area,energy,quality,id_var = varDatos(glm,variable)
        time = np.full(lat.shape,fechaG16)
        geom = generaGeom(lon,lat)
        gdf = generaGDF(id_var,energy,area,quality,time,lon,lat,geom)
        generaShape(gdf,variable,ano,dia,hora,nombre)
        generaCSV(gdf,variable,ano,dia,hora,nombre)

#path = '/home/lanot/Documents/GML_data/'
#pathSalida = '/home/lanot/Documents/salida_gml/'

#archivos = glob('./data/*.nc*')
#archivos.sort()

#for i in archivos:

archivo_r = glob('/data1/input/glm/*.nc')
archivo_r.sort()
archivo_r = archivo_r[-15:]

print (archivo_r)

for i in archivo_r:
    print('Procesando archivo: '+i)
    glm = Dataset(i,'r')

    fechaStr,fechaG16,ano,dia,hora,minuto,fechaArch = fecha(i)

    archivo = i[i.find('OR'):-3]

    nombre = archivo[:archivo.find('G16_')]+'FLASH_'+archivo[archivo.find('LCFA_')+5:]
    gmlProsesa('flash',glm,ano,dia,hora,nombre)

    nombre = archivo[:archivo.find('G16_')]+'EVENT_'+archivo[archivo.find('LCFA_')+5:]
    gmlProsesa('event',glm,ano,dia,hora,nombre)

    nombre = archivo[:archivo.find('G16_')]+'GROUP_'+archivo[archivo.find('LCFA_')+5:]

    gmlProsesa('group',glm,ano,dia,hora,nombre)


import numpy as np
from scipy.signal import butter, filtfilt

from ...io import BaseRaw
from ...utils import _validate_type, verbose
from ..nirs import _validate_nirs_info

@verbose
def temporal_derivative_distribution_repair(raw, *, verbose=None):
    """Apply temporal derivative distribution repair to data.

    Applies temporal derivative distribution repair (TDDR) to data
    :footcite:`FishburnEtAl2019`. This approach removes baseline shift
    and spike artifacts without the need for any user-supplied parameters.

    Parameters
    ----------
    raw : instance of Raw
        The raw data.
    %(verbose)s

    Returns
    -------
    raw : instance of Raw
         Data with TDDR applied.

    Notes
    -----
    TDDR was initially designed to be used on optical density fNIRS data but
    has been enabled to be applied on hemoglobin concentration fNIRS data as
    well in MNE. We recommend applying the algorithm to optical density fNIRS
    data as intended by the original author wherever possible.

    There is a shorter alias ``mne.preprocessing.nirs.tddr`` that can be used
    instead of this function (e.g. if line length is an issue).

    References
    ----------
    .. footbibliography::
    """
    raw = raw.copy().load_data()
    _validate_type(raw, BaseRaw, "raw")
    picks = _validate_nirs_info(raw.info)

    if not len(picks):
        raise RuntimeError(
            "TDDR should be run on optical density or " "hemoglobin data."
        )
    for pick in picks:
        raw._data[pick] = _TDDR(raw._data[pick], raw.info["sfreq"])

    return raw

# provide a short alias
tddr = temporal_derivative_distribution_repair

# Taken from https://github.com/frankfishburn/TDDR/ (MIT license).
# With permission https://github.com/frankfishburn/TDDR/issues/1.
# The only modification is the name, scipy signal import and flake fixes.
def _TDDR(signal, sample_rate):
    # This function is the reference implementation for the TDDR algorithm for
    #   motion correction of fNIRS data, as described in:
    #
    #   Fishburn F.A., Ludlum R.S., Vaidya C.J., & Medvedev A.V. (2019).
    #   Temporal Derivative Distribution Repair (TDDR): A motion correction
    #   method for fNIRS. NeuroImage, 184, 171-179.
    #   https://doi.org/10.1016/j.neuroimage.2018.09.025
    #
    # Usage:
    #   signals_corrected = TDDR( signals , sample_rate );
    #
    # Inputs:
    #   signals: A [sample x channel] matrix of uncorrected optical density or
    #            hemoglobin data
    #   sample_rate: A scalar reflecting the rate of acquisition in Hz
    #
    # Outputs:
    #   signals_corrected: A [sample x channel] matrix of corrected optical
    #   density data
    signal = np.array(signal)
    if len(signal.shape) != 1:
        for ch in range(signal.shape[1]):
            signal[:, ch] = _TDDR(signal[:, ch], sample_rate)
        return signal

    # Preprocess: Separate high and low frequencies
    filter_cutoff = 0.5
    filter_order = 3
    Fc = filter_cutoff * 2 / sample_rate
    signal_mean = np.mean(signal)
    signal -= signal_mean
    if Fc < 1:
        fb, fa = butter(filter_order, Fc)
        signal_low = filtfilt(fb, fa, signal, padlen=0)
    else:
        signal_low = signal

    signal_high = signal - signal_low

    # Initialize
    tune = 4.685
    D = np.sqrt(np.finfo(signal.dtype).eps)
    mu = np.inf
    iter = 0

    # Step 1. Compute temporal derivative of the signal
    deriv = np.diff(signal_low)

    # Step 2. Initialize observation weights
    w = np.ones(deriv.shape)

    # Step 3. Iterative estimation of robust weights
    while iter < 50:
        iter = iter + 1
        mu0 = mu

        # Step 3a. Estimate weighted mean
        mu = np.sum(w * deriv) / np.sum(w)

        # Step 3b. Calculate absolute residuals of estimate
        dev = np.abs(deriv - mu)

        # Step 3c. Robust estimate of standard deviation of the residuals
        sigma = 1.4826 * np.median(dev)

        # Step 3d. Scale deviations by standard deviation and tuning parameter
        if sigma == 0:
            break
        r = dev / (sigma * tune)

        # Step 3e. Calculate new weights according to Tukey's biweight function
        w = ((1 - r**2) * (r < 1)) ** 2

        # Step 3f. Terminate if new estimate is within
        # machine-precision of old estimate
        if abs(mu - mu0) < D * max(abs(mu), abs(mu0)):
            break

    # Step 4. Apply robust weights to centered derivative
    new_deriv = w * (deriv - mu)

    # Step 5. Integrate corrected derivative
    signal_low_corrected = np.cumsum(np.insert(new_deriv, 0, 0.0))

    # Postprocess: Center the corrected signal
    signal_low_corrected = signal_low_corrected - np.mean(signal_low_corrected)

    # Postprocess: Merge back with uncorrected high frequency component
    signal_corrected = signal_low_corrected + signal_high + signal_mean

    return signal_corrected


"""
Milan Murray 15/12/19
NEW: Dictionary!
"""
# Other
jugedores_dict = {1: "Milan", 2: "Jonas", 3: "Jarell"}

# Constants

# Input
player = int(input("Please enter the number of the player: "))

# Processes
if player in jugedores_dict:
    player_name = jugedores_dict[player]
    print("\nThis player, number", str(player) + ", is", player_name + ".")
else:
    print("\nThis player, number", str(player) + ", does not exist.")

# Input
player = int(input("What position do you want to insert a player into?: "))

# Processes
if player in jugedores_dict:
    print("Warning, this will replace a player in the dictionary!")
player_name = input("Please enter the name of the player: ")
jugedores_dict[player] = player_name

# Input
player = int(input("Please enter the position of the player you wish to delete: "))

# Processes
if player in jugedores_dict:
    del jugedores_dict[player]
    print("ERADICATED")
else:
    print("Impossible")

# Outputs
print(jugedores_dict)
"""
if 2 in jugedores_dict:
    print(jugedores_dict[2])
else:
    print("Dictionary key 2 does not exist.")

if 4 in jugedores_dict:
    print(jugedores_dict[4])
else:
    print("Dictionary key 4 does not exist.")
"""

print(jugedores_dict.get(2, "Dictionary key 2 does not exist."))
print(jugedores_dict.get(4, "Dictionary key 4 does not exist."))


import os
import time

class color:
   PURPLE = '\033[95m'
   CYAN = '\033[96m'
   DARKCYAN = '\033[36m'
   BLUE = '\033[94m'
   GREEN = '\033[92m'
   YELLOW = '\033[93m'
   RED = '\033[91m'
   BOLD = '\033[1m'
   UNDERLINE = '\033[4m'
   END = '\033[0m'

class PrintStream:
    def __init__(self):
        self.stream = []
        self.context = 50

    def print(self):
        pass

def bold_first_letters(word, n=2, hilight_color=color.CYAN):
    if len(word)>n:
        return color.BOLD + hilight_color + word[:n] + color.END + word[n:]
    else:
        return color.BOLD + hilight_color +  word + color.END

def bold_bookend_letters(word, n=2, hilight_color=color.CYAN):

    if len(word)>n*2:
        return color.BOLD + color.CYAN + word[:n] + color.END + word[n:-n] + color.BOLD + color.YELLOW + word[-n:] + color.END
    else:
        return color.BOLD + color.CYAN +  word + color.END

def print_words_one_at_a_time(file_path):
    # Ensure the file exists
    if not os.path.isfile(file_path):
        print(f"No file found at {file_path}")
        return

    # Open the file
    with open(file_path, 'r') as file:
        # Read the file's contents
        contents = file.read()

        # Split the contents into words, ignoring whitespace and newlines
        words = contents.split()

        # Loop through each word
        for word in words:
            # Clear the terminal
            os.system('cls' if os.name == 'nt' else 'clear')

            # Print the word
            #print(word)
            #print(bold_first_letters(word))
            print(bold_bookend_letters(word))

            # Pause for a moment before moving to the next word
            time.sleep(0.05)

def scroll_words(file_path, line_length=80):
    # Ensure the file exists
    if not os.path.isfile(file_path):
        print(f"No file found at {file_path}")
        return

    # Open the file
    with open(file_path, 'r') as file:
        # Read the file's contents
        contents = file.read()

        # Split the contents into words, ignoring whitespace and newlines
        words = contents.split()

        # Calculate half the line length, rounding down if necessary
        half_line_length = line_length // 2

        # Loop through each word
        for i, word in enumerate(words):
            # Clear the terminal
            os.system('cls' if os.name == 'nt' else 'clear')

            # Determine the surrounding context
            context_before = " ".join(words[max(0, i-half_line_length):i])
            context_after = " ".join(words[i+1:i+half_line_length])

            # Combine the context and focus word
            line = f"{context_before} {color.YELLOW + word + color.END} {context_after}"

            # If the line is too long, truncate it
            if len(line) > line_length:
                overage = len(line) - line_length
                half_overage = overage // 2
                line = line[half_overage:-half_overage]

            # Print the line, ensuring the focus word is centered
            print(f"{line:^{line_length}}")

            # Pause for a moment before moving to the next word
            time.sleep(0.5)

def scroll_words2(file_path, speed=0.1, line_length=80):
    # Ensure the file exists
    if not os.path.isfile(file_path):
        print(f"No file found at {file_path}")
        return

    # Open the file
    with open(file_path, 'r') as file:
        # Read the file's contents
        contents = file.read()

        # Replace newlines with spaces
        contents = contents.replace('\n', ' ')

        # Scroll through the contents
        for i in range(len(contents)):
            # Clear the terminal
            os.system('cls' if os.name == 'nt' else 'clear')

            # Determine the subset of contents to display
            display_contents = contents[i:i+line_length]

            # Determine the index of the center of the line
            center_index = len(display_contents) // 2

            # Find the start and end of the word at the center
            start_of_word = display_contents.rfind(' ', 0, center_index)
            end_of_word = display_contents.find(' ', center_index)

            # If the center is in a word (i.e., not a space), get the center word and the contents before and after it
            if start_of_word != -1 and end_of_word != -1:
                center_word = display_contents[start_of_word+1:end_of_word]
                before_word = display_contents[:start_of_word]
                after_word = display_contents[end_of_word:]
            else:
                center_word = display_contents[center_index]
                before_word = display_contents[:center_index]
                after_word = display_contents[center_index+1:]

            # Print the before word, center word, and after word
            print(before_word + ' ' + color.YELLOW + center_word + color.END + after_word)

            # Pause for a moment before moving to the next character
            time.sleep(speed)

if __name__ == "__main__":
    # Specify the path to your file here
    file_path = '/home/i7qce/docs/scratch/sample_text_3.txt'
    print_words_one_at_a_time(file_path)
    #scroll_words2(file_path, speed=.05)


from bs4 import BeautifulSoup
import requests
import smtplib

info = {'models' : 'prices'}
for i in range(0,3):
    url = f'https://www.flipkart.com/search?q=iphone%20&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=on&as=off&page={i}'
    # url = f'https://www.flipkart.com/search?q=realme+9+5g&as=on&as-show=on&otracker=AS_Query_PredictiveAutoSuggest_8_0_na_na_na&otracker1=AS_Query_PredictiveAutoSuggest_8_0_na_na_na&as-pos=8&as-type=PREDICTIVE&suggestionId=realme+9+5g&requestId=6ac5b34d-ce97-47f8-be70-2495dc160062&page={i}'
    page = requests.get(url)

    soup = BeautifulSoup(page.content, 'html.parser')
    data = soup.find_all('div', class_= '_2kHMtA')

    for entry in data:
        model = entry.find('div', class_='_4rR01T').text
        price = entry.find('div', class_='_30jeq3 _1_WHN1').text
        rating = entry.find('div', class_ = '_3LWZlK').text
        info.update({model: price})

print(info)

if int(info['APPLE iPhone 14 (Starlight, 128 GB)'][1:].replace(',', '')) > 15000:
    smt = smtplib.SMTP("smtp.gmail.com", 587 )
    smt.ehlo()
    smt.starttls()
    smt.login('ripaimdemonoid@gmail.com', 'dccinrdjkbfphqak')
    smt.sendmail('ripaimdemonoid@gmail.com', 'akashlearning2020@gmail.com', f'Subject: Price Notifier \n\n The price of realme 9 5G has dropped. Get it now on Flipkart')
    smt.close()


from datetime import datetime, timedelta
from data_manager import DataManager
from flight_search import FlightSearch
from notification_manager import NotificationManager

flight_search = FlightSearch()
notification_manager = NotificationManager()

data_manager = DataManager()
sheet_data = data_manager.get_destination_data()

print("Welcome to Aleshichev Igor's Flight Club\nWe find the best flight price and email you")
first_name = input("What is your first name?:\n")
last_name = input("What is your last name?:\n")
email = input("What is your email?:\n")
mobile_phone = input("Type your mobile phone (e.x +380...):\n")
city_code = input("Enter the origin city IATA where you want to fly (e.x LON, PRG):\n").upper()
print("Ok. Wait a second")

data_manager.new_user(first_name, last_name, email, mobile_phone, city_code )

if sheet_data[0]['iataCode'] == '':
    for row in sheet_data:
        row['iataCode'] = flight_search.get_destination_code(row['city'])

    data_manager.destination_data = sheet_data
    data_manager.update_destination_codes()

tomorrow = datetime.now() + timedelta(days=1)
six_month_from_today = datetime.now() + timedelta(days=(6 * 30))

for destination in sheet_data:
    flight = flight_search.chek_flights(
        city_code,
        destination["iataCode"],
        from_time=tomorrow,
        to_time=six_month_from_today
    )

    try:
        if flight.price < destination["lowestPrice"]:

            notification_manager.send_sms(
                mobile_phone,
                message=f"Low price alert! Only £{flight.price} to fly from {flight.origin_city}-{flight.origin_airport} "
                        f"to {flight.destination_city}-{flight.destination_airport}, "
                        f"from {flight.out_date} to {flight.return_date}."
            )

            notification_manager.send_emails(
                email,
                message=f"Low price alert! Only £{flight.price} to fly from "
                        f"{flight.origin_city}-{flight.origin_airport} "
                        f"to {flight.destination_city}-{flight.destination_airport}, "
                        f"from {flight.out_date} to {flight.return_date}."
            )
    except AttributeError:
        pass


#!/usr/bin/env Python
# coding   : utf-8
# @Time    : 12/9/2019 5:03 PM
# @Author  : wu.hao
# @File    : docParserExcel.py
# @Note    : 用于excel文件的读写

from interpreterAccounting.docparser.docParserBaseClass import *
from openpyxl import load_workbook,Workbook
import pandas as pd

class DocParserExcel(DocParserBase):
    def __init__(self,gConfig):
        super(DocParserExcel, self).__init__(gConfig)
        self.targetFile = os.path.join(self.workingspace.directory,
                                       '.'.join([os.path.split(self.sourceFile)[-1].split('.')[0],'.xlsx']))
        self.workbook = Workbook()

    def writeToStore(self, dictTable):
        # 专门用于写文件
        table = dictTable['table']
        tableName = dictTable['tableName']
        assert len(table) > 0,("%s is empty : %s"%(tableName,dictTable))
        workbook = load_workbook(self.targetFile)
        if workbook.active.title == "Sheet":  # 表明这是一个空工作薄
            workbook.remove(workbook['Sheet'])  # 删除空工作薄
        writer = pd.ExcelWriter(self.targetFile, engine='openpyxl')
        writer.book = workbook
        dataFrame = pd.DataFrame(table, columns=None, index=None)  # 以第一行为列变量
        dataFrame.to_excel(excel_writer=writer, sheet_name=tableName, index=None)
        writer.save()

    def initialize(self,dictParameter=None):
        self.loggingspace.clear_directory(self.loggingspace.directory)
        if dictParameter is not None:
            self.targetFile = os.path.join(self.workingspace.directory,
                                       '.'.join([os.path.split(dictParameter['sourcefile'])[-1].split('.')[0], 'xlsx']))
        suffix = self.targetFile.split('.')[-1]
        assert suffix in self.gConfig['excelSuffix'.lower()], \
            'suffix of %s is invalid,it must one of %s' % (self.targetFile, self.gConfig['excelSuffix'.lower()])
        if os.path.exists(self.targetFile):
            os.remove(self.targetFile)
        self.workbook = Workbook()
        self.writer = pd.ExcelWriter(self.targetFile, engine='openpyxl')
        self.writer.book = self.workbook
        self.writer.save()  # 生成一个新文件

def create_object(gConfig):
    parser=DocParserExcel(gConfig)
    parser.initialize()
    return parser


# 4. Реализуйте базовый класс Car. У данного класса должны быть следующие атрибуты: speed, color, name, is_police (булево).
# А также методы: go, stop, turn(direction), которые должны сообщать, что машина поехала, остановилась, повернула (куда).
# Опишите несколько дочерних классов: TownCar, SportCar, WorkCar, PoliceCar. Добавьте в базовый класс метод show_speed,
# который должен показывать текущую скорость автомобиля. Для классов TownCar и WorkCar переопределите метод show_speed.
# При значении скорости свыше 60 (TownCar) и 40 (WorkCar) должно выводиться сообщение о превышении скорости.
# Создайте экземпляры классов, передайте значения атрибутов. Выполните доступ к атрибутам, выведите результат.
# Выполните вызов методов и также покажите результат.

from enum import Enum
from user_functions import float_convert

class Trun(Enum):
    left = 1
    rigth = 2
    none = 3

class Car(object):
    car_type = 'Custom'
    speed_limit = None

    def __init__(self, name, color):
        self._speed = 0.0
        self._color = color
        self._name = name
        self._turn = Trun.none
        self._is_police = False

    def __str__(self):
        return f'{self.car_type} {self._name} {self._color}'

    def go(self, speed):
        speed = float_convert(speed)
        if speed != -1:
            self._speed = speed

    def stop(self):
        self._speed = 0.0
        self._turn = Trun.none

    def turn(self, truning=Trun.none):
        self._turn = truning

    def show_speed(self):
        if self.speed_limit and self._speed > self.speed_limit:
            print('Вы превысили скорость', end=' ')
        return self._speed

class SportCar(Car):
    car_type = 'SportCar'

class TownCar(Car):
    car_type = 'TownCar'
    speed_limit = 60

    # def show_speed(self):
    #     if self._speed > speed_limit:
    #         print(f'{self._speed} Вы превысили скорость', end=' ')
    #     return super(TownCar, self).show_speed()

class WorkCar(Car):
    car_type = 'WorkCar'
    speed_limit = 40

    # def show_speed(self):
    #     if self._speed > 40:
    #         print('Вы превысили скорость', end=' ')
    #     return self._speed

class PoliceCar(Car):
    car_type = 'PoliceCar'

    def __init__(self, name, color):
        super().__init__(name, color)
        self._is_police = True

car_1 = SportCar(name='Ferrary', color='Red')
car_2 = WorkCar(name='Ford', color='Brown')
car_3 = TownCar(name='Fiat', color='White')
car_4 = PoliceCar(name='Ford', color='White/Black')

car_1.go(170)
car_2.go(60)
car_3.go(60)
car_4.go(70)
print('Поехали')
print(car_1, car_1.show_speed())
print(car_2, car_2.show_speed())
print(car_3, car_3.show_speed())
print(car_4, car_4.show_speed())

car_1.stop()
car_2.stop()
car_3.stop()
car_4.stop()
print()
print('Автомобили остановились')

print(car_1, car_1.show_speed())
print(car_2, car_2.show_speed())
print(car_3, car_3.show_speed())
print(car_4, car_4.show_speed())


# -*- coding: utf-8 -*-
"""
Created on Sun Dec 11 09:59:29 2022

@author: julia
"""

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# KATALOGI PRACY

import os
KATALOG_PROJEKTU = os.path.join(os.getcwd(),"healthy_dacades")
KATALOG_DANYCH = os.path.join(KATALOG_PROJEKTU,"dane")
KATALOG_WYKRESOW = os.path.join(KATALOG_PROJEKTU, "wykresy")
KATALOG_POINCARE = os.path.join(KATALOG_WYKRESOW, "wykresy poincare")
KATALOG_HISTOGRAMY = os.path.join(KATALOG_WYKRESOW, "histogramy")
KATALOG_WIZUALIZACJI = os.path.join(KATALOG_WYKRESOW, "wizualizacje serii")
os.makedirs(KATALOG_WYKRESOW, exist_ok=True)
os.makedirs(KATALOG_DANYCH, exist_ok=True)
os.makedirs(KATALOG_POINCARE, exist_ok = True)
os.makedirs(KATALOG_HISTOGRAMY, exist_ok = True)
os.makedirs(KATALOG_WIZUALIZACJI, exist_ok= True)

#%%
# ROZPAKOWANIE PLIKÓW

import zipfile
with zipfile.ZipFile('healthy_decades.zip', 'r') as zip_ref:
    zip_ref.extractall(KATALOG_DANYCH)

#%%
import os

# PRZYGOTOWANIE SCIEZEK DOSTEPU DO PLIKOW
sciezki = []
for (root,dirs,files) in os.walk(KATALOG_DANYCH):
    for file in files:
        sciezki.append(os.path.join(root, file))

#%%

ilosc_pomiarow = []

# ILOSC POMIAROW W POSZCZEGOLNYCH PLIKACH
for file in sciezki:
    count = len(open(file).readlines())
    ilosc_pomiarow.append(count)

print('--- POMIARY ---')
print('srednia liczba pomiarow:' , int(np.mean(ilosc_pomiarow)))
print('mediana: ', int(np.median(ilosc_pomiarow)))
print('najmniejsza liczba pomiarow: ',min(ilosc_pomiarow))
print('najwieksza liczba pomiarow: ', max(ilosc_pomiarow))

#%%

# SPRAWDZANIE CZY NIE MA PUSTYCH WARTOSCI
for file in sciezki:
    with open(file) as f:
        for line in f:
            if line.split()[0] == '':
                print('niekompletne')
            if line.split()[0] == '':
                print('niekompletne')
            if line.split()[0] == np.nan:
                print('niekompletne')
            if line.split()[1] == np.nan:
                print('niekompletne')
# nie ma

# SPRAWDZENIE CZY NIE MA BŁĘDNYCH WARTOSCI (UJEMNYCH)
for file in sciezki:
    with open(file) as f:
        for line in f:
            if int(line.split()[0]) <= 0:
                print('bledne dane w pliku: {} '.format(file))

#%%
# SPRAWDZANIE CZY SKURCZE MAJĄ KOLEJNE NUMERY

nr = [] # wszystkie numery skurczy
numery = [] # numery skurczy z podziałem na pliki

for file in sciezki:
    numer = []
    with open(file) as f:
        for line in f:
            nr.append(int(line.split()[1]))
            numer.append(int(line.split()[1]))
        for i in range(0, len(numer)-1):
            if numer[i+1] - numer[i] != 1:
                print('blad w pliku {} , po numerze {}'.format(file[-13:], numer[i]))
    numery.append(numer)

#%%

# PRZYGOTOWANIE DANYCH

RR = []

for file in sciezki:
    with open(file) as f:
        for line in f:
            RR.append(int(line.split()[0]))

if len(RR) != len(set(nr)):
    print('numery skurczy sie powtarzają \n')

# STATYSTYKI DLA WSZYSTKICH DANYCH
print('--- STATYSTYKI ---')
print('ilosc danych: ',len(RR))
print('srednie RR:' , round(np.mean(RR), 2))
print('mediana RR: ',np.median(RR))
print('najmniejsze RR: ',min(RR))
print('najwieksze RR: {} \n'.format(max(RR)))

df= pd.DataFrame(RR)
# STATYSTYKI INNY SPOSOB
print('-- STATYTSYKI INNY SPOSOB --')
print(df.describe())

# NAJCZESCIEJ WYSTEPUJACE RR
print('\nNajczesciej wystepujace wartosci: ')
print(df[0].value_counts().head())

#%%

# PRZYGOTOWANIE DANYCH
# DATAFRAME Z WSZYSTKIMI DANYMI

def dane(skad  = sciezki, pomiary = ilosc_pomiarow):
    df2 = pd.DataFrame()
    RRp = [] #RR z podzialem na pliki

    for file in skad:
        RRf = [] #RR dla danego pliku
        with open(file) as f:
            for line in f:
                    RRf.append(int(line.split()[0]))
        RRp.append(RRf)
        if len(RRf) < max(pomiary):
            RRf1 = RRf.copy() # kopia listy RRf, aby w RRp zachować niezmienioną listę RRf, ponieważ lista jest mutable
            for i in range (max(pomiary) - len(RRf)):
                RRf1.append(np.nan)
            df2[file.split(".txt")[0][-9:]] = RRf1
        else:
            df2[file.split(".txt")[0][-9:]] = RRf

    df3 = df2.transpose()

    return RRp, df3, df2

df3 = dane()[1]
RRp = dane()[0]

#%%

# DODANIE KOLUMN Z WIEKIEM I PŁCIĄ

def index_plec(df):
    indexlist = df.index.tolist()
    for i in range (0,len(indexlist)):
        indexlist[i] = indexlist[i][0]
    return indexlist

def index_wiek(df):
    indexlist = df.index.tolist()
    for i in range (0,len(indexlist)):
        indexlist[i] = indexlist[i][1:3]
    return indexlist

df3.insert(0, 'Płeć', index_plec(df3))
df3.insert(1, 'Wiek', index_wiek(df3))

#%%

#STATYSTYKI KAŻDEGO PACJENTA
# print(df2.describe())
statystyki = dane()[2].describe()
wyniki = statystyki.transpose()

#%%
'''

# WYKRESY POINCARE

def poincare(nr):
    fig  = plt.figure()
    plt.scatter(df3.iloc[nr][2:-1], df3.iloc[nr][3:], lw = 0.5)
    plt.title(df3.index[nr])
    plt.xlabel(r'$RR_n [ms]$')
    plt.ylabel(r'$ RR_{n+1} [ms] $')
    fig.savefig(os.path.join(KATALOG_POINCARE,'{}.jpg'.format(df3.index[nr])), dpi=300 )

for i in range(0, len(df3)):
    poincare(i)

#%%

# HISTOGRAM WSZYSTKICH WARTOSCI

plt.hist(RR)
plt.title('histogram akcji serca ze wszystkich danych')
plt.savefig(os.path.join(KATALOG_HISTOGRAMY,'histogram.jpg'), dpi=300 )
plt.show()

#%%

# HISTOGRAMY DLA KAŻDEGO PACJENTA

def histogram(nr):
    fig = plt.figure()
    plt.hist(RRp[nr])
    plt.title(df3.index[nr])
    plt.xlabel('RR [ms]')
    plt.savefig(os.path.join(KATALOG_HISTOGRAMY, 'histogram_{}.jpg'.format(df3.index[nr])), dpi = 300)

for i in range(0, len(df3)):
    histogram(i)

#%%

# WIZUZALIZACJE SERII DLA KAŻDEGO PACJENTA

for i in range(0, len(RRp)):
    fig = plt.figure(figsize = (20,12))
    plt.plot(numery[i], RRp[i])
    plt.title(df3.index[i])
    plt.savefig(os.path.join(KATALOG_WIZUALIZACJI , '{}.jpg'.format(df3.index[i])), dpi = 300)
    plt.show()
'''
#%%

# RÓŻNICE

def Roznice_f(RRp = RRp, numery = numery):
    Roznice = []
    Roznice2 = []
    for i in range(0, len(RRp)):
        roznicef = [] #roznice miedzy kolejnymi RRf w danym pliku
        roznicef2 = []
        for j in range (0, len(RRp[i])-1):
            if numery[i][j+1] - numery[i][j] == 1:
                roznicef.append(RRp[i][j+1] - RRp[i][j])
                roznicef2.append(RRp[i][j+1] - RRp[i][j])
            else:
                roznicef2.append('nan')
        Roznice.append(roznicef)
        Roznice2.append(roznicef2)
    #return Roznice, Roznice2
    return Roznice, Roznice2

Roznice = Roznice_f()[0]
Roznice2 = Roznice_f()[1]

#%%

# ANALIZA SYGNAŁU W PRZESUWAJĄCYCH OKNACH

okna = [] # podzial na okna
oknapp = [] # okna dla poszczegolnych plikow
oknaw = [] # wyniki dla kolejnych okien
oknawp = [] # wyniki okien w plikach poszczególnych

for i in range(0,len(RRp)):
    oknap = [] # okna dla pliku
    oknawpp = []
    for j in range(0, len(RRp[i]), 100):
        if j+100 <= len(RRp[i]):
            okna.append(RRp[i][j : j + 100])
            oknap.append(RRp[i][j : j + 100])
            oknaw.append((np.mean(RRp[i][j : j+100]) , np.std(RRp[i][j : j+100])))
            oknawpp.append((np.mean(RRp[i][j : j+100]) , np.std(RRp[i][j : j+100])))
        else:
            okna.append(RRp[i][j:])
            oknap.append(RRp[i][j:])
            oknaw.append((np.mean(RRp[i][j : ]) , np.std(RRp[i][j :])))
            oknawpp.append((np.mean(RRp[i][j : ]) , np.std(RRp[i][j :])))
    oknapp.append(oknap)
    oknawp.append(oknawpp)
#%%

# WYKRES DLA SYGNAŁU W PRZESUWAJĄCYCH SIĘ OKNACH

oknadf = pd.DataFrame(oknaw)
oknadf.columns = ['mean', 'std']

fig = plt.figure(figsize = (30,12))
plt.plot(oknadf.index, oknadf['mean'])
plt.title('Analiza sygnału')
plt.ylabel('Srednia')
plt.xlabel('Numer okna')
plt.savefig(os.path.join(KATALOG_WYKRESOW,'sygnal.jpg'), dpi=300 )

# Nie jest stacjonarny

#%%

# ANALIZA ZRÓŻNICOWANEGO SYGNAŁU W PRZESUWAJĄCYCH OKNACH

oknarw = [] #wyniki dla kolejnych okien zroznicowanego sygnalu
oknar = [] #zroznicowane okna

for i in range(0, len(Roznice)):
    for j in range(0,len(Roznice[i]), 100):
        if j+100 <= len(Roznice[i]):
            oknarw.append((np.mean(Roznice[i][j : j+100]) , np.std(Roznice[i][j : j+100])))
            oknar.append(Roznice[i][j : j+100])
        else:
            oknar.append(Roznice[i][j :])
            oknarw.append((np.mean(Roznice[i][j :]) , np.std(Roznice[i][j : ])))

#%%

# ANALIZA ZRÓŻNICOWANEGO SYGNAŁU WYKRES

oknardf = pd.DataFrame(oknarw)
oknardf.columns = ['mean', 'std']

fig = plt.figure(figsize = (30,12))
plt.plot(oknardf.index, oknardf['mean'])
plt.title('Analiza zróznicowanego sygnału')
plt.ylabel('Srednia')
plt.xlabel('Numer okna')
plt.savefig(os.path.join(KATALOG_WYKRESOW,'sygnal_zroznicowany.jpg'), dpi=300 )

#%%

# SDNN
# from statistics import stdev

SDNN = np.array([])

for i in range(0, len(df3)):
    SDNN = np.append(SDNN, np.std(df3.iloc[i][2:]))

wyniki['SDNN'] = SDNN
wyniki['std'] = SDNN #zamiana wyników z describe

#%%

from math import sqrt

#RMSSD

def RMSSD(r = Roznice):
    if type(r[0]) == list:
        RMSSD = np.array([])
        for i in range (0, len(r)):
            suma = 0
            for j in range(0, len(r[i])):
                suma = suma + (r[i][j])**2
            RMSSD = np.append(RMSSD, (sqrt(1/len(r[i]) * suma)))
    else:
        suma = 0
        for i in range(0, len(r)):
            suma = suma + r[i]**2
        RMSSD = sqrt(1/len(r) * suma)
    return RMSSD

wyniki['RMSSD'] = RMSSD()

#%%

# pNN50

def pNN50 (r = Roznice):
    if type(r[0]) == list:
        pNN50 = np.array([])

        for i in range (0, len(r)):
            suma = 0
            for j in range(0, len(r[i])):
                if abs(r[i][j]) > 50:
                    suma += 1
            pNN50 = np.append(pNN50, suma/len(r[i]))
    else:
        suma = 0
        for i in range(0, len(r)):
            if abs(r[i]) > 50:
                suma += 1
            pNN50 = suma/len(r)

    return pNN50

wyniki['pNN50'] = pNN50()

#pNN20

def pNN20(r = Roznice):
    if type(r[0]) == list:
        pNN20 = np.array([])

        for i in range (0, len(r)):
            suma = 0
            for j in range(0, len(r[i])):
                if abs(r[i][j]) > 20:
                    suma += 1
            pNN20 = np.append(pNN20, suma/len(r[i]))
    else:
        suma = 0
        for i in range(0, len(r)):
            if abs(r[i]) > 20:
                suma += 1
            pNN20 = suma/len(r)

    return pNN20

wyniki['pNN20'] = pNN20()

#%%

# SPRAWDZANIE CZY SERCE ZWALNIA CZY PRZYSPIESZA

# Zmiany serca
zmiany = []
def zmiany_serca(nr):
    zmianyf = [] #zmiany dla kazdego pliku
    ilosc_a = 0
    ilosc_d = 0
    ilosc_0 = 0
    ilosc_nan = 0
    for j in range(0, len(Roznice2[nr])):
        if Roznice2[nr][j] == 'nan':
            zmianyf.append('nan')
            ilosc_nan += 1
        elif Roznice2[nr][j] > 0:
            zmianyf.append('d')
            ilosc_d += 1
        elif Roznice2[nr][j] < 0:
            zmianyf.append('a')
            ilosc_a += 1
        else:
            zmianyf.append('0')
            ilosc_0 += 1
    return zmianyf, ilosc_a, ilosc_d, ilosc_0, ilosc_nan

p_a = []
p_d = []
p_0 = []

ilosci_nan = []

for i in range(0, len(Roznice)):
    zmiany.append(zmiany_serca(i)[0])
    ilosci_nan.append(zmiany_serca(i)[4])

#%%

p_a = []
p_d = []
p_0 = []

p_aa = []
p_ad = []
p_a0 = []

# P(da), P(dd), P(d0)

p_da = []
p_dd = []
p_d0 = []

# P(0a), P(0d), P(00)

p_0a = []
p_0d = []
p_00 = []

# P(aaa), P(aad), P(aa0)

p_aaa = []
p_aad = []
p_aa0 = []

# P(ada), P(add), P(ad0)

p_ada = []
p_add = []
p_ad0 = []

# P(a0a), P(a0d), P(a00)

p_a0a = []
p_a0d = []
p_a00 = []

# P(daa), P(dad), P(da0)

p_daa = []
p_dad = []
p_da0 = []

# P(dda), P(ddd), P(dd0)

p_dda = []
p_ddd = []
p_dd0 = []

# P(d0a), P(d0d), P(d00)

p_d0a = []
p_d0d = []
p_d00 = []

# P(0aa), P(0ad), P(0a0)

p_0aa = []
p_0ad = []
p_0a0 = []

# P(0da), P(0dd), P(0d0)

p_0da = []
p_0dd = []
p_0d0 = []

# P(00a), P(00d), P(000)

p_00a = []
p_00d = []
p_000 = []

def zmiany_serca2(r):
    ilosc_a = 0
    ilosc_d = 0
    ilosc_0 = 0

    ilosc_aa = 0
    ilosc_ad = 0
    ilosc_a0 = 0
    ilosc_da = 0
    ilosc_dd = 0
    ilosc_d0 = 0
    ilosc_0a = 0
    ilosc_0d = 0
    ilosc_00 = 0

    ilosc_aaa = 0
    ilosc_aad = 0
    ilosc_aa0 = 0

    ilosc_ada = 0
    ilosc_add = 0
    ilosc_ad0 = 0

    ilosc_a0a = 0
    ilosc_a0d = 0
    ilosc_a00 = 0

    ilosc_daa = 0
    ilosc_dad = 0
    ilosc_da0 = 0

    ilosc_dda = 0
    ilosc_ddd = 0
    ilosc_dd0 = 0

    ilosc_d0a = 0
    ilosc_d0d = 0
    ilosc_d00 = 0

    ilosc_0aa = 0
    ilosc_0ad = 0
    ilosc_0a0 = 0

    ilosc_0da = 0
    ilosc_0dd = 0
    ilosc_0d0 = 0

    ilosc_00a = 0
    ilosc_00d = 0
    ilosc_000 = 0

    for i in range(0, len(r) - 2):
        if r[i] == 'd':
            ilosc_d += 1
            if r[i+1] == 'a':
                ilosc_da += 1
                if r[i+2] == 'a':
                    ilosc_daa += 1
                elif r[i+2] == 'd':
                    ilosc_dad += 1
                elif r[i+2] == '0':
                    ilosc_da0 += 1
            elif r[i+1] == 'd':
                ilosc_dd += 1
                if r[i+2] == 'a':
                    ilosc_dda += 1
                elif r[i+2] == 'd':
                    ilosc_ddd += 1
                elif r[i+2] == '0':
                    ilosc_dd0 += 1
            elif r[i+1] == '0':
                ilosc_d0 += 1
                if r[i+2] == 'a':
                    ilosc_d0a += 1
                elif r[i+2] == 'd':
                    ilosc_d0d += 1
                elif r[i+2] == '0':
                    ilosc_d00 += 1
        elif r[i] == 'a':
            ilosc_a += 1
            if r[i+1] == 'a':
                ilosc_aa += 1
                if r[i+2] == 'a':
                    ilosc_aaa += 1
                elif r[i+2] == 'd':
                    ilosc_aad += 1
                elif r[i+2] == '0':
                    ilosc_aa0 += 1
            elif r[i+1] == 'd':
                ilosc_ad += 1
                if r[i+2] == 'a':
                    ilosc_ada += 1
                elif r[i+2] == 'd':
                    ilosc_add += 1
                elif r[i+2] == '0':
                    ilosc_ad0 += 1
            elif r[i+1] == '0':
                ilosc_a0 += 1
                if r[i+2] == 'a':
                    ilosc_a0a += 1
                elif r[i+2] == 'd':
                    ilosc_a0d += 1
                elif r[i+2] == '0':
                    ilosc_a00 += 1
        elif r[i] == '0':
            ilosc_0 += 1
            if r[i+1] == 'a':
                ilosc_0a += 1
                if r[i+2] == 'a':
                    ilosc_0aa += 1
                elif r[i+2] == 'd':
                    ilosc_0ad += 1
                elif r[i+2] == '0':
                    ilosc_0a0 += 1
            elif r[i+1] == 'd':
                ilosc_0d += 1
                if r[i+2] == 'a':
                    ilosc_0da += 1
                elif r[i+2] == 'd':
                    ilosc_0dd += 1
                elif r[i+2] == '0':
                    ilosc_0d0 += 1
            elif r[i+1] == '0':
                ilosc_00 += 1
                if r[i+2] == 'a':
                    ilosc_00a += 1
                elif r[i+2] == 'd':
                    ilosc_00d += 1
                elif r[i+2] == '0':
                    ilosc_000 += 1
    i = len(r) - 3
    if r[i+1] == 'a':
        ilosc_a += 1
        if r[i+2] == 'a':
            ilosc_aa += 1
        elif r[i+2] == 'd':
            ilosc_ad += 1
        elif r[i+2] == '0':
            ilosc_a0 += 1
    elif r[i+1] == 'd':
        ilosc_d += 1
        if r[i+2] == 'a':
            ilosc_da += 1
        elif r[i+2] == 'd':
            ilosc_dd += 1
        elif r[i+2] == '0':
            ilosc_d0 += 1
    elif r[i+1] == '0':
        ilosc_0 += 1
        if r[i+2] == 'a':
            ilosc_0a += 1
        elif r[i+2] == 'd':
            ilosc_0d += 1
        elif r[i+2] == '0':
            ilosc_00 += 1

    if r[i+2] == 'a':
        ilosc_a += 1
    elif r[i+2] == 'd':
        ilosc_d += 1
    elif r[i+2] == '0':
        ilosc_0 += 1

    #p1 = len(r)
    #pd2 = len(r) - 1
    #pd3 = len(r) -2

    p2 = np.array([ilosc_aa, ilosc_ad, ilosc_a0, ilosc_da, ilosc_dd, ilosc_d0, ilosc_0a, ilosc_0d, ilosc_00,])
    #p2 = p2 / pd2

    p3 = np.array([ ilosc_aaa, ilosc_aad, ilosc_aa0, ilosc_ada, ilosc_add, ilosc_ad0, ilosc_a0a, ilosc_a0d, ilosc_a00, \
    ilosc_daa, ilosc_dad, ilosc_da0, ilosc_dda, ilosc_ddd, ilosc_dd0, ilosc_d0a, ilosc_d0d, ilosc_d00,\
    ilosc_0aa, ilosc_0ad, ilosc_0a0, ilosc_0da, ilosc_0dd, ilosc_0d0, ilosc_00a, ilosc_00d, ilosc_000])
    #p3 = p3/ pd3

    return  ilosc_a, ilosc_d, ilosc_0, p2, p3

for i in range(0, len(zmiany)):
    # len(Roznice[i]) - 1 - liczba 2 elementowych zbiorow z kolejnych elementow listy Roznice[i]
    l1 = len(zmiany[i]) - ilosci_nan[i]
    p_a.append(zmiany_serca2(zmiany[i])[0] / l1)
    p_d.append(zmiany_serca2(zmiany[i])[1] / l1)
    p_0.append(zmiany_serca2(zmiany[i])[2] / l1)

    l2 = len(zmiany[i]) - 1 - 2*ilosci_nan[i]
    p_aa.append(zmiany_serca2(zmiany[i])[3][0]/ l2)
    p_ad.append(zmiany_serca2(zmiany[i])[3][1]/ l2)
    p_a0.append(zmiany_serca2(zmiany[i])[3][2] / l2)

    p_da.append(zmiany_serca2(zmiany[i])[3][3] / l2)
    p_dd.append(zmiany_serca2(zmiany[i])[3][4]/ l2)
    p_d0.append(zmiany_serca2(zmiany[i])[3][5] / l2)

    p_0a.append(zmiany_serca2(zmiany[i])[3][6] / l2)
    p_0d.append(zmiany_serca2(zmiany[i])[3][7] / l2)
    p_00.append(zmiany_serca2(zmiany[i])[3][8] / l2)

    l3 = len(zmiany[i]) - 2 - 3*ilosci_nan[i]
    p_aaa.append(zmiany_serca2(zmiany[i])[4][0] / l3)
    p_aad.append(zmiany_serca2(zmiany[i])[4][1] / l3)
    p_aa0.append(zmiany_serca2(zmiany[i])[4][2] / l3)

    p_ada.append(zmiany_serca2(zmiany[i])[4][3] / l3)
    p_add.append(zmiany_serca2(zmiany[i])[4][4] / l3)
    p_ad0.append(zmiany_serca2(zmiany[i])[4][5] / l3)

    p_a0a.append(zmiany_serca2(zmiany[i])[4][6] / l3)
    p_a0d.append(zmiany_serca2(zmiany[i])[4][7] / l3)
    p_a00.append(zmiany_serca2(zmiany[i])[4][8] / l3)

    p_daa.append(zmiany_serca2(zmiany[i])[4][9] / l3)
    p_dad.append(zmiany_serca2(zmiany[i])[4][10] / l3)
    p_da0.append(zmiany_serca2(zmiany[i])[4][11] / l3)

    p_dda.append(zmiany_serca2(zmiany[i])[4][12] / l3)
    p_ddd.append(zmiany_serca2(zmiany[i])[4][13] / l3)
    p_dd0.append(zmiany_serca2(zmiany[i])[4][14] / l3)

    p_d0a.append(zmiany_serca2(zmiany[i])[4][15] / l3)
    p_d0d.append(zmiany_serca2(zmiany[i])[4][16] / l3)
    p_d00.append(zmiany_serca2(zmiany[i])[4][17] /l3)

    p_0aa.append(zmiany_serca2(zmiany[i])[4][18] / l3)
    p_0ad.append(zmiany_serca2(zmiany[i])[4][19] / l3)
    p_0a0.append(zmiany_serca2(zmiany[i])[4][20] / l3)

    p_0da.append(zmiany_serca2(zmiany[i])[4][21] / l3)
    p_0dd.append(zmiany_serca2(zmiany[i])[4][22] / l3)
    p_0d0.append(zmiany_serca2(zmiany[i])[4][23] / l3)

    p_00a.append(zmiany_serca2(zmiany[i])[4][24] / l3)
    p_00d.append(zmiany_serca2(zmiany[i])[4][25] / l3)
    p_000.append(zmiany_serca2(zmiany[i])[4][26] / l3)

wyniki['p(a)'] = p_a
wyniki['p(d)'] = p_d
wyniki['p(0)'] = p_0

wyniki['p(aa)'] = p_aa
wyniki['p(ad)'] = p_ad
wyniki['p(a0)'] = p_a0

wyniki['p(da)'] = p_da
wyniki['p(dd)'] = p_dd
wyniki['p(d0)'] = p_d0

wyniki['p(0a)'] = p_0a
wyniki['p(0d)'] = p_0d
wyniki['p(00)'] = p_00

wyniki['p(aaa)'] = p_aaa
wyniki['p(aad)'] = p_aad
wyniki['p(aa0)'] = p_aa0
wyniki['p(ada)'] = p_ada
wyniki['p(add)'] = p_add
wyniki['p(ad0)'] = p_ad0
wyniki['p(a0a)'] = p_a0a
wyniki['p(a0d)'] = p_a0d
wyniki['p(a00)'] = p_a00

wyniki['p(daa)'] = p_daa
wyniki['p(dad)'] = p_dad
wyniki['p(da0)'] = p_da0
wyniki['p(dda)'] = p_dda
wyniki['p(ddd)'] = p_ddd
wyniki['p(dd0)'] = p_dd0
wyniki['p(d0a)'] = p_d0a
wyniki['p(d0d)'] = p_d0d
wyniki['p(d00)'] = p_d00

wyniki['p(0aa)'] = p_0aa
wyniki['p(0ad)'] = p_0ad
wyniki['p(0a0)'] = p_0a0
wyniki['p(0da)'] = p_0da
wyniki['p(0dd)'] = p_0dd
wyniki['p(0d0)'] = p_0d0
wyniki['p(00a)'] = p_00a
wyniki['p(00d)'] = p_00d
wyniki['p(000)'] = p_000

#%%

# WZORCE KWANTOWE

# szukam max i min przyrostu

def szukaj_max():
    maximum = max(Roznice[0])
    for i in range(1, len(Roznice)):
        if max(Roznice[i]) > maximum:
            maximum  = max(Roznice[i])
    return maximum /8

def szukaj_min():
    minimum = min(Roznice[0])
    for i in range(1, len(Roznice)):
        if min(Roznice[i]) < minimum:
            minimum  = min(Roznice[i])
    return minimum /8

print(szukaj_max(), szukaj_min())

def wzorce(nr):
    tablica = [0] * int((szukaj_max() + abs(szukaj_min()))+1)
    for i in range(0, len(Roznice[nr])):
        j = int(Roznice[nr][i] / 8)
        tablica[j+37] = tablica[j+37] + 1
    return list(zip((np.arange(-37,38)), tablica)), tablica

wzorce_lista = []
for i in range(0, len(Roznice)):
    wzorce_lista.append(wzorce(i)[1])

wzorce_df = pd.DataFrame(wzorce_lista, columns=(np.arange(-37,38)), index = df3.index)

#%%

# DODANIE KOLUMNY Z PŁCIĄ I WIEKIEM

wyniki.insert(0, 'Płeć', index_plec(wyniki))
wyniki.insert(1, 'Wiek', index_wiek(wyniki))

#%%
# ZAPISANIE TABELI
wyniki.to_csv('wyniki.csv')

#%%

# DODAWANIE WYNIKOW DLA OKNA

def okno_wyniki(okna, nr, numer):
    okno_stats = []
    okno_df = pd.DataFrame(okna[nr])
    oknor1 = Roznice_f(okna, numer)[0][nr]
    oknor = Roznice_f(okna, numer)[1][nr]
    okno_zmiany = []
    stats = okno_df.describe()
    ilosc_nan =  0
    for j in range(0, len(oknor)):
        if oknor[j] == 'nan':
            okno_zmiany.append('nan')
            ilosc_nan += 1
        elif oknor[j] > 0:
            okno_zmiany.append('d')
        elif oknor[j] < 0:
            okno_zmiany.append('a')
        else:
            okno_zmiany.append('0')
    for k in range(0,8):
        okno_stats.append(stats[0][k])
    okno_stats.append(np.std(okna[nr]))
    okno_stats.append(RMSSD(oknor1))
    okno_stats.append(pNN50(oknor1))
    okno_stats.append(pNN20(oknor1))

    l1 = len(okno_zmiany) - ilosc_nan
    okno_stats.append(zmiany_serca2(okno_zmiany)[0] / l1)
    okno_stats.append(zmiany_serca2(okno_zmiany)[1] / l1)
    okno_stats.append(zmiany_serca2(okno_zmiany)[2] / l1)

    l2 = len(okno_zmiany) - 1 - 2*ilosc_nan
    for a in range(0, len(zmiany_serca2(okno_zmiany)[3])):
        okno_stats.append(zmiany_serca2(okno_zmiany)[3][a] / l2)

    if len(okno_zmiany) > 3:
        l3 = len(okno_zmiany) - 2 - 3*ilosc_nan
        for a in range(0, len(zmiany_serca2(okno_zmiany)[4])):
            okno_stats.append(zmiany_serca2(okno_zmiany)[4][a] / l3)
    else:
        for a in range(0, len(zmiany_serca2(okno_zmiany)[4])):
            okno_stats.append(0)
    return okno_stats

#%%

# OKNA Z MAX SR RR i MAX STD

def tworzenie_okien():
    okna_mean = []
    okna_std = []
    num_mean = []
    num_std = []
    temp = []
    for j in range(0, len(oknawp)):
        #num_plik = []
        #nums_plik = []
        temp_mean = 0
        temp_std = 0
        for i in range(0, len(oknawp[j])):
            if oknawp[j][i][0] > oknawp[j][temp_mean][0]:
                temp_mean = i
            if oknawp[j][i][1] > oknawp[j][temp_std][1]:
                temp_std = i
        okna_mean.append(oknapp[j][temp_mean])
        okna_std.append(oknapp[j][temp_std])
        temp.append(temp_mean)
        if len(okna_mean[j]) == 100:
            num_mean.append(numery[j][temp_mean * 100 : temp_mean * 100 + 100])
        else:
            num_mean.append(numery[j][temp_mean * 100 : temp_mean * 100 + len(okna_mean[j])])
        if len(okna_std[j]) == 100:
            num_std.append(numery[j][temp_std * 100 : temp_std * 100 + 100])
        else:
            num_std.append(numery[j][temp_std * 100 : temp_std * 100 + len(okna_mean[j])])
    return okna_mean, okna_std, num_mean, num_std, temp

okna_mean, okna_std, num_mean, num_std, temp = tworzenie_okien()

#%%
# DODAWANIE WYNIKÓW DLA OKNA DO DATAFRAME DLA SREDNICH OKIEN
kolumny = {'count' : [], 'mean' : [], 'std':[], 'min':[], '25%':[], '50%':[], '75%':[],
       'max':[], 'SDNN':[], 'RMSSD':[], 'pNN50':[], 'pNN20':[], 'p(a)':[], 'p(d)':[], 'p(0)':[],
       'p(aa)':[], 'p(ad)':[], 'p(a0)':[], 'p(da)':[], 'p(dd)':[], 'p(d0)':[], 'p(0a)':[], 'p(0d)':[],
       'p(00)':[], 'p(aaa)':[], 'p(aad)':[], 'p(aa0)':[], 'p(ada)':[], 'p(add)':[], 'p(ad0)':[],
       'p(a0a)':[], 'p(a0d)':[], 'p(a00)':[], 'p(daa)':[], 'p(dad)':[], 'p(da0)':[], 'p(dda)':[],
       'p(ddd)':[], 'p(dd0)':[], 'p(d0a)':[], 'p(d0d)':[], 'p(d00)':[], 'p(0aa)':[], 'p(0ad)':[],
       'p(0a0)':[], 'p(0da)':[], 'p(0dd)':[], 'p(0d0)':[], 'p(00a)':[], 'p(00d)':[], 'p(000)':[]}
okna_srednie = pd.DataFrame(kolumny)
for i in range(len(okna_mean)):
    okna_srednie.loc[len(okna_srednie.index)] = okno_wyniki(okna = okna_mean, nr = i, numer = num_mean)

#%%
okna_srednie.insert(0, 'Płeć', index_plec(wyniki))
okna_srednie.insert(1, 'Wiek', index_wiek(wyniki))

okna_srednie.to_csv('okna_sr.csv')
#%%

# DODAWANIE WYNIKÓW DLA OKNA DO DATAFRAME DLA ODCHYLEN OKIEN
kolumny = {'count' : [], 'mean' : [], 'std':[], 'min':[], '25%':[], '50%':[], '75%':[],
       'max':[], 'SDNN':[], 'RMSSD':[], 'pNN50':[], 'pNN20':[], 'p(a)':[], 'p(d)':[], 'p(0)':[],
       'p(aa)':[], 'p(ad)':[], 'p(a0)':[], 'p(da)':[], 'p(dd)':[], 'p(d0)':[], 'p(0a)':[], 'p(0d)':[],
       'p(00)':[], 'p(aaa)':[], 'p(aad)':[], 'p(aa0)':[], 'p(ada)':[], 'p(add)':[], 'p(ad0)':[],
       'p(a0a)':[], 'p(a0d)':[], 'p(a00)':[], 'p(daa)':[], 'p(dad)':[], 'p(da0)':[], 'p(dda)':[],
       'p(ddd)':[], 'p(dd0)':[], 'p(d0a)':[], 'p(d0d)':[], 'p(d00)':[], 'p(0aa)':[], 'p(0ad)':[],
       'p(0a0)':[], 'p(0da)':[], 'p(0dd)':[], 'p(0d0)':[], 'p(00a)':[], 'p(00d)':[], 'p(000)':[]}
okna_odchylenia = pd.DataFrame(kolumny)
for i in range(len(okna_std)):
    okna_odchylenia.loc[len(okna_odchylenia.index)] = okno_wyniki(okna = okna_std, nr = i, numer = num_std)

okna_odchylenia.insert(0, 'Płeć', index_plec(wyniki))
okna_odchylenia.insert(1, 'Wiek', index_wiek(wyniki))

okna_odchylenia.to_csv('okna_std.csv')


'''
A prime is a natural number greater than  that has no
positive divisors other than  and itself. Given a number
determine and print whether it is prime or not prime.

Input Format

The first line contains an integer, , the number of test cases.
Each of the  subsequent lines contains an integer, , to be tested for primality.

Sample Input

3
12
5
7
Sample Output

Not prime
Prime
Prime
Explanation

Test Case 0: .
 is divisible by numbers other than  and itself (i.e.: , , , ), so we print  on a new line.

Test Case 1: .
 is only divisible  and itself, so we print  on a new line.

Test Case 2: .
 is only divisible  and itself, so we print  on a new line.

SOLUTION

To eliminate the input pool, follow the 3 following premises:

1) Eliminate all even numbers
2) no factor can be greater than sqrt of the number.
3) Keep track of prime numbers and only use these as factors.

'''

import math

# get the number of entries to be made
def get_entries():
        # number of lines to be entered (t)
        print("Enter number of entries to be made")
        t = int(input())

        entries = []

        # read t lines from STDIN
        for i in range(0, t):
            entries.append(int(input().strip()))
          #  print(entries[i])

        return entries

def sqrt(num):
    #50 -> 7
    return int(math.sqrt(num))

# generate factors up until the square root of largest num
def generate_factors(entries):

    global factors

    max_num = max(entries)
    #50

    factor = sqrt(max_num)
    # 7

    factors = list(range(2, factor+1))
    #3, 4, 5, 6, 7
    return factors

# Verify if number is a prime number
def check_if_prime(n):

    # 0 and 1 are not prime numbers
    if n == 0 or n == 1:
        print( f"{n} Not prime")
        return

    # eliminate all even numbers at O(1) time
    if n % 2 == 0 and n != 2:
        print(n, "Not Prime")
        return

    isPrime = True

    for p in factors:
        #3, 4, 5, 6, 7
        if p > n:
            break
        if n % p == 0:
            isPrime = False
            break

    print("Prime" if isPrime else "Not Prime")

def main():
    # read input
    entries = get_entries()

    # generate factors from entries

    generate_factors(entries)
     #2, 3, 4, 5, 6, 7

    for num in entries:
        check_if_prime(num)

if __name__ == '__main__': main()