# Addition

# In this model, you will see a transformation which is the basic property of
# single neurons (i.e., addition). Addition transforms two inputs into a single
# output which is their sum. You will construct a network that adds two inputs.
# The network utilizes two communication channels going into the same neural
# population. Addition is somewhat "free", since the incoming currents from
# different synaptic connections interact linearly.

# This model has ensembles A and B which represent the two inputs to be added.
# The 'Sum' ensemble represents the added value. All the parameters used in the
# model are as described in the book, with the sum ensemble having a radius of
# 2 to account for the maximum range of summing the input values.

# While connecting the inputs to the ensembles A and B, the transform is
# set to 1 (which is the default value) since this should be a communication
# channel. However as described in the book, you can scale a represented
# variable by a constant value by changing the transform. Example: if you
# set the transform of ensemble B to 0 and ensemble A to 2
# (i.e., nengo.Connection(stim_A, ens_A, transform=[2]) ), the sum will be twice
# of the stim_A. You will also need to set an appropriate radius for the
# Sum ensemble to avoid saturation when you change the transform values.

# Press the play button to run the simulation.
# The stim_A and stim_B graphs show the inputs to ensembles A and B
# respectively. The graphs A and B show the decoded value of the activity of
# ensembles A and B respectively. The sum graph shows that the decoded value of
# the activity in the Sum ensemble provides a good estimate of the sum of inputs
# A and B. You can use the sliders to change the input values provided by the
# stim_A and stim_B nodes.

# Setup the environment
import nengo
from nengo.dists import Uniform
from nengo.processes import Piecewise

# Create the network object to which we can add ensembles, connections, etc.
model = nengo.Network(label="Scalar Addition")

with model:
    # Inputs to drive the activity in ensembles A and B
    stim_A = nengo.Node(
        Piecewise({0: -0.75, 1.25: 0.5, 2.5: 0.70, 3.75: 0}), label="Input A"
    )
    stim_B = nengo.Node(
        Piecewise({0: 0.25, 1.25: -0.5, 2.5: 0.85, 3.75: 0}), label="Input B"
    )

    # Ensembles with 100 LIF neurons each
    # Represents the first input (A)
    ens_A = nengo.Ensemble(100, dimensions=1, max_rates=Uniform(100, 200), label="A")
    # Represents the second input (B)
    ens_B = nengo.Ensemble(100, dimensions=1, max_rates=Uniform(100, 200), label="B")
    # Reprsents the sum of two inputs
    ens_sum = nengo.Ensemble(
        100, dimensions=1, max_rates=Uniform(100, 200), radius=2, label="Sum"
    )

    # Connecting the input nodes to ensembles
    nengo.Connection(stim_A, ens_A)
    nengo.Connection(stim_B, ens_B)

    # Connecting ensembles A and B to the Sum ensemble
    nengo.Connection(ens_A, ens_sum)
    nengo.Connection(ens_B, ens_sum)


import tkinter as tk
from datetime import datetime
from tkinter import font
import os

time = datetime.now().strftime("%Y-%m-%d %H%M")
# 获取当前文件所在目录的绝对路径
current_dir = os.path.abspath(os.path.dirname(__file__))
# 获取上两级目录的绝对路径
parent_dir = os.path.abspath(os.path.join(current_dir, os.pardir))
parent_dir = os.path.abspath(os.path.join(parent_dir, os.pardir)) + f'\数据\串口采集数据\{time}.txt'

timestamps = []  # 用于保存时间戳的列表

def save_timestamp():
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")

    timestamps.append(timestamp)  # 将时间戳添加到列表中
    print("时间戳已保存。")

def write_to_file():
    with open( parent_dir, "w") as file:
        for timestamp in timestamps:
            file.write(timestamp + "\n")
    print("时间戳已保存至文件。")

# 创建主窗口
window = tk.Tk()
window.title("保存时间戳")
window.geometry("500x300")

# 创建按钮
button_font = font.Font(size=16)
button_save = tk.Button(window, text="保存时间戳", command=save_timestamp,width=30, height=5,font= button_font)
button_save.pack(padx=20, pady=10)

button_write = tk.Button(window, text="写入文件", command=write_to_file,width=30, height=5,font= button_font)
button_write.pack(padx=20, pady=10)

# 运行主循环
window.mainloop()


import sys,os,unittest,shutil,random,pdb

## Datetime import
import datetime

##scipy import
import scipy as spy

## vtools import.
from vtools.data.timeseries import rts,its
from vtools.data.timeseries import prep_binary
from vtools.data.vtime import ticks,number_intervals
from vtools.data.vtime import ticks_to_time,ticks\
     ,number_intervals,time_sequence,time_interval

## Local import
from merge import *

class TestMerge(unittest.TestCase):

    """ test functionality of shift operations """

    def __init__(self,methodName="runTest"):

        super(TestMerge,self).__init__(methodName)

        # Number of data in a time series.
        self.num_ts=1000
        self.max_val=1000
        self.min_val=0.01
        self.large_data_size=100000
        self.test_interval=[time_interval(minutes=30),time_interval(hours=2),
                            time_interval(days=1)]

    def test_merge_rts_no_intersect(self):
        """ Test merging two rts without intersection."""

        d1=[1]*int(spy.math.pow(2,10))
        d2=[2]*int(spy.math.pow(2,11))

        st1=datetime.datetime(year=1990,month=2,day=3,hour=11, minute=15)
        st2=datetime.datetime(year=1990,month=5,day=3,hour=11, minute=15)

        ts1=rts(d1,st1,time_interval(hours=1))
        ts2=rts(d2,st2,time_interval(hours=1))
        nt=merge(ts1,ts2)

        self.assertEqual(nt.start,ts1.start)
        self.assertEqual(nt.end,ts2.end)

        total_n=number_intervals(ts1.start,ts2.end,ts1.interval)+1

        self.assertEqual(len(nt.data),total_n)
        s1=nt.index_after(ts1.end)
        s2=nt.index_after(ts2.start)

        self.assert_(spy.alltrue(spy.isnan(nt.data[s1+1:s2])))
        self.assert_(spy.allclose(nt.data[0:s1+1],ts1.data))
        self.assert_(spy.allclose(nt.data[s2:len(nt.data)],ts2.data))

    def test_merge_rts_intersect(self):
        """ Test merging two rts with intersection."""

        d1=[1.0]*int(spy.math.pow(2,10))
        d2=[2.0]*int(spy.math.pow(2,11))

        st1=datetime.datetime(year=1990,month=2,day=3,hour=11, minute=15)
        st2=datetime.datetime(year=1990,month=3,day=3,hour=11, minute=15)

        ts1=rts(d1,st1,time_interval(hours=1))
        ts2=rts(d2,st2,time_interval(hours=1))

        ## Intentionally put some nan into ts1 to see effect.
        ii=ts1.index_after(st2)
        num_nan=10
        ts1.data[ii+1:ii+num_nan+2]=spy.nan

        nt=merge(ts1,ts2)

        self.assertEqual(nt.start,ts1.start)
        self.assertEqual(nt.end,ts2.end)

        total_n=number_intervals(ts1.start,ts2.end,ts1.interval)+1

        self.assertEqual(len(nt.data),total_n)

        s1=nt.index_after(ts1.end)
        s2=nt.index_after(ts2.start)
        s3=ts2.index_after(ts1.end)
        self.assert_(spy.allclose(nt.data[0:ii+1],ts1.data[0:ii+1]))
        self.assert_(spy.allclose(nt.data[ii+1:ii+num_nan+2],ts2.data[0:num_nan+1]))
        self.assert_(spy.allclose(nt.data[ii+num_nan+2:s1+1],ts1.data[ii+num_nan+2:s1+1]))
        self.assert_(spy.allclose(nt.data[s1+1:len(nt.data)],ts2.data[s3+1:len(ts2.data)]))

        ## a small test
        d1=[1.0]*4
        d2=[2.0]*2

        st1=datetime.datetime(year=1990,month=2,day=1)
        st2=datetime.datetime(year=1990,month=3,day=1)

        ts1=rts(d1,st1,time_interval(months=1))
        ts2=rts(d2,st2,time_interval(months=1))
        nt=merge(ts1,ts2)
        self.assertEqual(len(nt),len(ts1))
        self.assertEqual(nt.data[-1],ts1.data[-1])

        d1=[1.0,1.0,1.0,spy.nan]
        d2=[2.0,3.0,4.0]

        st1=datetime.datetime(year=1990,month=2,day=1)
        st2=datetime.datetime(year=1990,month=3,day=1)

        ts1=rts(d1,st1,time_interval(months=1))
        ts2=rts(d2,st2,time_interval(months=1))
        nt=merge(ts1,ts2)
        self.assertEqual(len(nt),len(ts1))
        self.assertEqual(nt.data[-1],ts2.data[-1])

    def test_merge_rts_intersect2(self):
        """ Test merging two rts with intersection."""

        d1=[1.0]*4
        d2=[2.0]*4
        d1[2]=spy.nan

        st1=datetime.datetime(year=1990,month=2,day=1)
        st2=datetime.datetime(year=1990,month=3,day=1)

        ts1=rts(d1,st1,time_interval(months=1))
        ts2=rts(d2,st2,time_interval(months=1))

        nt=merge(ts1,ts2)
        ## test ts1 data take priority on valid data
        self.assertEqual(nt.data[1],ts1.data[1])

        ## test ts2 data take prioirty on invalid data of ts1
        self.assertEqual(nt.data[2],ts2.data[2])

    def test_merge_rts_2d_intersect(self):

        """ Test merging of two rts of 2-d data and has intersection."""

        d1=[[1.0,2.0]]*int(spy.math.pow(2,10))
        d2=[[3.0,4.0]]*int(spy.math.pow(2,11))

        st1=datetime.datetime(year=1990,month=2,day=3,hour=11, minute=15)
        st2=datetime.datetime(year=1990,month=3,day=3,hour=11, minute=15)

        ts1=rts(d1,st1,time_interval(hours=1))
        ts2=rts(d2,st2,time_interval(hours=1))

        ## Intentionally put some nan into ts1 to see effect.
        ii=ts1.index_after(st2)
        num_nan=10
        ts1.data[ii+1:ii+num_nan+2,]=spy.nan

        nt=merge(ts1,ts2)

        self.assertEqual(nt.start,ts1.start)
        self.assertEqual(nt.end,ts2.end)

        total_n=number_intervals(ts1.start,ts2.end,ts1.interval)+1

        self.assertEqual(len(nt.data),total_n)
        s1=nt.index_after(ts1.end)
        s2=nt.index_after(ts2.start)
        s3=ts2.index_after(ts1.end)
        self.assert_(spy.allclose(nt.data[0:ii+1,],ts1.data[0:ii+1,]))
        self.assert_(spy.allclose(nt.data[ii+1:ii+num_nan+2,],ts2.data[0:num_nan+1,]))
        self.assert_(spy.allclose(nt.data[ii+num_nan+2:s1+1,],ts1.data[ii+num_nan+2:s1+1,]))
        self.assert_(spy.allclose(nt.data[s1+1:len(nt.data),],ts2.data[s3+1:len(ts2.data),]))

    def test_merge_large_rts(self):

        largenum=250000

        st1=datetime.datetime(1920,1,2)
        data1=range(0,largenum)
        dt=datetime.timedelta(minutes=15)
        rt1=rts(data1,st1,dt,{})

        st2=rt1.end+dt
        data2=range(largenum,2*largenum)
        rt2=rts(data2,st2,dt,{})

        st3=rt2.end+dt
        data3=range(2*largenum,3*largenum)
        rt3=rts(data3,st3,dt,{})

        st4=rt3.end+dt
        data4=range(3*largenum,4*largenum)
        rt4=rts(data4,st4,dt,{})

        ts=merge(rt1,rt2,rt3,rt4)

        self.assertEqual(len(ts),largenum*4)
        self.assertEqual(ts.data[largenum],data2[0])
        self.assertEqual(ts.data[2*largenum],data3[0])
        self.assertEqual(ts.data[3*largenum],data4[0])

if __name__=="__main__":

    unittest.main()