Public Class Main

    Structure Point

        Dim ix As Integer
        Dim iy As Integer
        Dim iz As Integer

    End Structure

    Structure Concept

        Dim Name As String

        Dim ID As Integer

        Dim Mediator As Integer

        ' узор нейронов
        Dim Pattern As Collection

    End Structure

   
    ' Количество нейромедиаторов
    Public Const N_Med As Integer = 5

    ' Счетчик ID для медиаторов
    Dim ID_Count(N_Med - 1) As Integer

    ' Типы медиаторов
    Public Const M_In As Integer = 0 ' входной сигнал
    Public Const M_Det As Integer = 1 ' сигнал обобщенный
    Public Const M_Internal As Integer = 2 ' сигнал внутренний
    Public Const M_Gip As Integer = 3 ' сигнал гиппокампа
    Public Const M_SideInfo As Integer = 4 ' сторонняя информация

    ' Словарь допустимых понятий (состояний) для каждого из медиаторов
    Dim Dictionary(N_Med - 1) As Collection


    ' Количество дендритных секций
    Public Const N_DS As Integer = 3

    ' Типы дендритных секций
    Public Const D_Det As Integer = 0 ' секция детекции
    Public Const D_Mem_ID As Integer = 1 ' секция памяти
    Public Const D_Mem_SideInfo As Integer = 2 ' секция памяти




    Public X_GC As Integer = 7
    Public Y_GC As Integer = 7

    Public GCol(X_GC - 1, Y_GC - 1) As MiniColumn

    Public Z_Col As Integer = 10

    Public N_BusIn As Integer = 1
    Public N_BusOut As Integer = 1

    Dim NSConc As Integer = 10

   

    ' Число нейронов в волновом паттерне для одной колонки
    Dim Npat As Integer = 2


    ' Информационное состояние гиперколонки
    Public Info(N_Med - 1) As Collection

    Private Sub Main_Load(sender As Object, e As EventArgs) Handles MyBase.Load


        GCol_Ini()

        ' Задание параметров аксанометрической проекции

        Draw.Ini(45 / 180 * Math.PI, 15 / 180 * Math.PI)


        For i = 0 To N_Med - 1

            Dictionary(i) = New Collection

        Next

        ' Задание наборов понятий
        For i = 0 To NSConc - 1

            NewConc(M_In)
            NewConc(M_Det)

        Next



        For Each i In Dictionary(M_In)

            ComboBox1.Items.Add(i.ID)

        Next

        For Each i In Dictionary(M_Det)

            ComboBox2.Items.Add(i.ID)

        Next


        ComboBox3.SelectedIndex = 1

        Field_ini()

        For i = 0 To N_Med - 1

            Info(i) = New Collection

        Next

    End Sub

    Private Sub NewConc(med As Integer)

        Dim key As String

        Dim Conc As New Concept

        With Conc

            .Mediator = med
            .ID = NewID(med)

            .Pattern = New Collection

            For ix = 0 To X_GC - 1
                For iy = 0 To Y_GC - 1

                    If GCol(ix, iy).InUse Then

                        For j = 0 To Npat - 1

                            Dim p As New Point

                            p.ix = ix
                            p.iy = iy

                            p.iz = Rnd() * (Z_Col - 1)

                            key = p.ix.ToString & "-" & p.iy.ToString & "-" & p.iz.ToString

                            If Not .Pattern.Contains(key) Then

                                .Pattern.Add(p, key)

                            End If

                        Next

                    End If

                Next
            Next

        End With

        Dictionary(med).Add(Conc)

    End Sub
    ' Инициализация гиперколонки
    Private Sub GCol_Ini()

        Dim R As Double = X_GC / 2 - 0.5

        For ix = 0 To X_GC - 1
            For iy = 0 To Y_GC - 1

                GCol(ix, iy) = New MiniColumn(Z_Col, N_BusIn, N_BusOut, N_Med, N_DS)

                If (ix - R) ^ 2 + (iy - R) ^ 2 <= R ^ 2 Then

                    GCol(ix, iy).InUse = True

                End If


            Next
        Next

    End Sub

    ' Копирование картинок в буфер обмена
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        My.Computer.Clipboard.SetImage(pic_sp)
    End Sub
    Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
        My.Computer.Clipboard.SetImage(pic_sp2)
    End Sub

    Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
        My.Computer.Clipboard.SetImage(pic_ev)
    End Sub

    ' Одиночное сообщение в пакете
    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

        Dim F1, F2 As Boolean

        Dim x, y As Integer


        Reset_Sp()

        Dim i As Integer = ComboBox1.SelectedIndex + 1

        If i = -1 Then Exit Sub

        With Dictionary(M_In).Item(i)

            For Each p As Point In .Pattern

                GCol(p.ix, p.iy).Column(p.iz).A_Spont = True
                GCol(p.ix, p.iy).Column(p.iz).A_med_sp(.Mediator) = True

            Next

            Info(.Mediator).Add(.ID)

            Detect_col(F1, .ID)

            ' При обнаружении нового сигнала создаем под него колонку-детектор
            If Not F1 Then

                Set_fields_1()

                Field_max(F2, x, y)

                If F2 Then

                    With GCol(x, y)

                        .status = True

                        .W(0) = Dictionary(M_In).Item(i).ID

                        .A = True


                        For iz = 0 To Z_Col - 1

                            .Column(iz).A_Evoked = True

                            .Column(iz).A_med_ev(M_Internal) = True

                        Next



                    End With

                    Draw_Fields()

                End If

            End If

        End With

        DrawA_sp_ev()

        DrawA_ev()

    End Sub

    ' Детектирование информационного сигнала. Определение есть ли миниколонка, настроенная на этот образ.
    Private Sub Detect_col(ByRef res As Boolean, ByVal P_ID As Integer)

        res = False

        For ix = 0 To X_GC - 1
            For iy = 0 To Y_GC - 1

                If GCol(ix, iy).InUse Then
                    If GCol(ix, iy).W(0) = P_ID Then

                        GCol(ix, iy).A = True
                        res = True

                        For iz = 0 To Z_Col - 1

                            GCol(ix, iy).Column(iz).A_Evoked = True

                            GCol(ix, iy).Column(iz).A_med_ev(M_Internal) = True

                        Next


                    End If
                End If

            Next
        Next


    End Sub

    ' Детектирование паттерна колонок. Создание нового ID если паттерн уникален
    Private Sub Detect_col_pat(ByRef FNew As Boolean, ByRef Det As Collection)

        Det.Clear()

        Dim F As Boolean

        FNew = True

        ' Определяем совпадение с существующими паттернами
        ' Пропущен случай, когда новый паттерн содержит уже существующий 

        For Each C As Concept In Dictionary(M_Internal)

            F = True

            For Each d As Point In C.Pattern

                If Not GCol(d.ix, d.iy).Column(d.iz).A_med_ev(M_Internal) Then

                    F = False

                    Exit For

                End If

            Next


            If F Then
                ' обнаружено совпадение с существующим понятием

                FNew = False

                Det.Add(C.ID)

            End If

        Next


        If FNew And Info(M_In).Count > 0 Then
            ' новый ID

            Dim p As New Point

            Dim Conc As New Concept

            With Conc

                .Mediator = M_Internal
                .ID = NewID(M_Internal)

                .Name = .ID.ToString

                .Pattern = New Collection

                For ix = 0 To X_GC - 1
                    For iy = 0 To Y_GC - 1

                        If GCol(ix, iy).InUse Then

                            For iz = 0 To Z_Col - 1

                                If GCol(ix, iy).Column(iz).A_med_ev(M_Internal) Then

                                    p.ix = ix
                                    p.iy = iy
                                    p.iz = iz

                                    .Pattern.Add(p)

                                End If

                            Next

                        End If

                    Next
                Next

            End With

            Dictionary(M_Internal).Add(Conc)

            Det.Add(Conc.ID)

        End If


    End Sub

    ' Внешние понятие (Det)
    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click

        Dim i As Integer = ComboBox2.SelectedIndex + 1

        If i = -1 Then Exit Sub

        Reset_Sp()

        With Dictionary(M_Det).Item(i)

            For Each p As Point In .Pattern

                GCol(p.ix, p.iy).Column(p.iz).A_Spont = True
                GCol(p.ix, p.iy).Column(p.iz).A_med_sp(.Mediator) = True

            Next

            Info(.Mediator).Add(.ID)

        End With

        DrawA_sp_ev()
        DrawA_sp2()

    End Sub

    ' Сброс информации
    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click

        Reset()

        DrawA_sp_ev()
        DrawA_ev()
        DrawA_sp2()

    End Sub

    ' Сброс спонтанной активности (кнопка)
    Private Sub Button14_Click(sender As Object, e As EventArgs) Handles Button14.Click

        Reset_Sp()

        DrawA_sp_ev()
        DrawA_ev()
        DrawA_sp2()

    End Sub

    ' Сброс спонтанной активности
    Private Sub Reset_Sp()

        For ix = 0 To X_GC - 1
            For iy = 0 To Y_GC - 1

                If GCol(ix, iy).InUse Then


                    For iz = 0 To Z_Col - 1

                        With GCol(ix, iy).Column(iz)

                            .A_Spont = False


                            For i = 0 To N_Med - 1

                                .A_med_sp(i) = False

                            Next

                        End With

                    Next

                End If

            Next
        Next


    End Sub

    ' Сброс активности
    Private Sub Reset()

        For ix = 0 To X_GC - 1
            For iy = 0 To Y_GC - 1

                If GCol(ix, iy).InUse Then

                    GCol(ix, iy).A = False

                    For iz = 0 To Z_Col - 1

                        With GCol(ix, iy).Column(iz)

                            .A_Spont = False
                            .A_Evoked = False

                            For i = 0 To N_Med - 1

                                .A_med_sp(i) = False
                                .A_med_ev(i) = False

                            Next

                        End With

                    Next

                End If

            Next
        Next

        For i = 0 To N_Med - 1

            Info(i).Clear()

        Next

    End Sub

   

    ' Конец пакета
    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click

        Dim F As Boolean

        Dim S As New Collection

        ' Детектируем внутренний паттерн. Если он новый, то создаем для него идентификатор
        Detect_col_pat(F, S)

        For Each i In S
            Info(M_Internal).Add(i)
        Next



        Select Case ComboBox3.SelectedIndex


            Case 0
                ' Авто






            Case 1
                ' Обучение по внешнему сигналу

                If Info(M_Det).Count <> 1 Then

                    MsgBox("плохой сигнал det")

                    Exit Sub

                End If

                remember_Det(Info(M_Internal).Item(1))

            Case 2
                ' Переобучение
                
            Case 3
                ' Генерация


        End Select

        DrawA_sp_ev()
     

    End Sub

    ' Фиксация на метаботропных рецепторах сигнала детекции
    Private Sub remember_Det(ID As Integer)

        For ix = 0 To X_GC - 1
            For iy = 0 To Y_GC - 1

                If GCol(ix, iy).A Then

                    For iz = 0 To Z_Col - 1

                        With GCol(ix, iy).Column(iz)

                            If .A_med_sp(M_Det) Then

                                .DS(D_Det).Mem.Add(ID, ID.ToString)

                            End If

                        End With

                    Next

                End If

            Next
        Next


    End Sub


    ' Создание нового уникального идентификатора для определенного идентификатора
    Public Function NewID(M As Integer)

        ID_Count(M) += 1

        NewID = ID_Count(M) + M * 1000

    End Function

    ' Детектирование внешних сигналов по памяти на дендритных сегментах
    Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click

        If Info(M_In).Count = 0 Then

            MsgBox("пустой сигнал")
            Exit Sub

        End If

        Reset_Sp()

        Dim F As Boolean

        Dim S As New Collection

        ' Детектируем внутренний паттерн. Если он новый, то создаем для него идентификатор
        Detect_col_pat(F, S)

        For Each i In S
            Info(M_Internal).Add(i)
        Next

        Set_D(S.Item(1))

        Dim S1 As New Collection

        Detect_Det_pat(F, S1, M_Det)

        For Each i In S1
            Info(M_Det).Add(i)
        Next

        DrawA_sp_ev()
        DrawA_ev()
        DrawA_sp2()


    End Sub

    ' Активация нейронов в активных колонках, узнавших внутренний паттерн
    Private Sub Set_D(ID As Integer)

        For ix = 0 To X_GC - 1
            For iy = 0 To Y_GC - 1

                If GCol(ix, iy).A Then

                    For iz = 0 To Z_Col - 1

                        With GCol(ix, iy).Column(iz)


                            If .DS(D_Det).Mem.Contains(ID.ToString) Then

                                .A_Spont = True
                                .A_med_sp(M_Det) = True

                            End If

                        End With

                    Next

                End If

            Next
        Next


    End Sub

    Private Sub Detect_Det_pat(F As Boolean, ByRef S As Collection, med As Integer)

        Dim N As Integer
        Dim F1 As Boolean

        S.Clear()

        For Each C As Concept In Dictionary(med)

            F1 = True
            N = 0

            ' Проверяем, что все нейроны активные с медиатором med попадают в паттерн понятия. Если это так, то поднимаем его

            For Each p In C.Pattern

                If GCol(p.ix, p.iy).Column(p.iz).A_med_sp(med) Then

                    N += 1

                End If

            Next

            If N > 0 Then

                For ix = 0 To X_GC - 1
                    For iy = 0 To Y_GC - 1

                        If GCol(ix, iy).A Then

                            For iz = 0 To Z_Col - 1

                                If GCol(ix, iy).Column(iz).A_med_sp(med) Then

                                    N -= 1

                                End If

                            Next

                        End If

                    Next
                Next

                If N = 0 Then

                    S.Add(C.ID)

                End If

            End If


        Next

    End Sub

    ' Определяем идентификаторы гиппокампа, подходящие под активность, возникшую при воспоминании
    Private Sub Detect_Gip_pat(F As Boolean, ByRef S As Collection, med As Integer)

        Dim N As Integer
        Dim F1 As Boolean

        S.Clear()

        For Each C As Concept In Dictionary(med)

            F1 = True
            N = 0

            ' Проверяем, что все нейроны активные с медиатором med попадают в паттерн понятия. Если это так, то поднимаем его

            For Each p In C.Pattern

                If GCol(p.ix, p.iy).Column(p.iz).A_med_sp(med) Then

                    N += 1

                End If

            Next

            If N > 0 Then

                For ix = 0 To X_GC - 1
                    For iy = 0 To Y_GC - 1

                        If GCol(ix, iy).A Then

                            For iz = 0 To Z_Col - 1

                                If GCol(ix, iy).Column(iz).A_med_sp(med) Then

                                    N -= 1

                                End If

                            Next

                        End If

                    Next
                Next

                If N = 0 Then

                    S.Add(C.ID)

                End If

            End If


        Next

    End Sub

    ' Идентификатор гиппокампа
    Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click

        NewConc(M_Gip)

        ComboBox4.Items.Add(Dictionary(M_Gip).Item(ID_Count(M_Gip)).id)

        Reset_Sp()

        With Dictionary(M_Gip).Item(ID_Count(M_Gip))

            For Each p As Point In .Pattern

                GCol(p.ix, p.iy).Column(p.iz).A_Spont = True
                GCol(p.ix, p.iy).Column(p.iz).A_med_sp(.Mediator) = True

            Next

            Info(.Mediator).Add(.ID)

        End With

        DrawA_sp_ev()
        DrawA_sp2()


    End Sub

    ' Запоминание события
    Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click

        If Info(M_Gip).Count <> 1 Then

            MsgBox("неправильный формат идентификатора гиппокампа")

            Exit Sub

        End If

        Dim ID_G As Integer = Info(M_Gip).Item(1)

        Dim ID_SI As Integer

        If Info(M_SideInfo).Count > 0 Then
            ID_SI = Info(M_SideInfo).Item(1)
        End If

        For ix = 0 To X_GC - 1
            For iy = 0 To Y_GC - 1

                If GCol(ix, iy).A Then

                    For iz = 0 To Z_Col - 1

                        GCol(ix, iy).Column(iz).DS(D_Mem_ID).Mem.Add(ID_G, ID_G.ToString)

                        If GCol(ix, iy).Column(iz).A_med_sp(M_Gip) Then

                            GCol(ix, iy).Column(iz).DS(D_Mem_SideInfo).Mem.Add(ID_SI, ID_SI.ToString)

                        End If


                    Next

                End If

            Next
        Next





    End Sub

    ' Востановление воспоминания по ID
    Private Sub Button11_Click(sender As Object, e As EventArgs) Handles Button11.Click

        Dim i As Integer = ComboBox4.SelectedIndex + 1

        If i = -1 Then Exit Sub

        Reset_Sp()

        Dim ID As Integer = Dictionary(M_Gip).Item(i).ID

        With Dictionary(M_Gip).Item(i)

            For Each p As Point In .Pattern

                GCol(p.ix, p.iy).Column(p.iz).A_Spont = True
                GCol(p.ix, p.iy).Column(p.iz).A_med_sp(.Mediator) = True

            Next

        End With


        For ix = 0 To X_GC - 1
            For iy = 0 To Y_GC - 1

                For iz = 0 To Z_Col - 1

                    If GCol(ix, iy).Column(iz).DS(D_Mem_ID).Mem.Contains(ID.ToString) Then

                        GCol(ix, iy).Column(iz).A_Spont = True
                        GCol(ix, iy).Column(iz).A_med_sp(M_Internal) = True

                        GCol(ix, iy).A = True

                    End If

                Next

            Next
        Next


        DrawA_sp_ev()
        DrawA_ev()
        DrawA_sp2()

    End Sub

    ' Новый идентификатор сторонней информации
    Private Sub Button13_Click(sender As Object, e As EventArgs) Handles Button13.Click


        NewConc(M_SideInfo)

        ComboBox5.Items.Add(Dictionary(M_SideInfo).Item(ID_Count(M_SideInfo)).id)

        With Dictionary(M_SideInfo).Item(ID_Count(M_SideInfo))

            For Each p As Point In .Pattern

                GCol(p.ix, p.iy).Column(p.iz).A_Spont = True
                GCol(p.ix, p.iy).Column(p.iz).A_med_sp(.Mediator) = True

            Next

            Info(.Mediator).Add(.ID)

        End With

        DrawA_sp_ev()
        DrawA_sp2()


    End Sub

    ' Ассоциативное воспоминание
    Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click

        Dim i As Integer = ComboBox5.SelectedIndex + 1

        If i = -1 Then Exit Sub

        Reset_Sp()

        ' Задаем сторонний информационный идентификатор

        Dim ID As Integer = Dictionary(M_SideInfo).Item(i).ID

        With Dictionary(M_SideInfo).Item(i)

            For Each p As Point In .Pattern

                GCol(p.ix, p.iy).Column(p.iz).A_Spont = True
                GCol(p.ix, p.iy).Column(p.iz).A_med_sp(.Mediator) = True

            Next

        End With

        Dim N1, N2 As Integer
        Dim F1 As Boolean

        ' Для нейронов активных колонок активируем медиатор гиппокампа у тех из них, что содержат воспоминание о внешней информации

        For ix = 0 To X_GC - 1
            For iy = 0 To Y_GC - 1

                If GCol(ix, iy).A Then

                    For iz = 0 To Z_Col - 1

                        If GCol(ix, iy).Column(iz).DS(D_Mem_SideInfo).Mem.Contains(ID.ToString) Then

                            GCol(ix, iy).Column(iz).A_Spont = True
                            GCol(ix, iy).Column(iz).A_med_sp(M_Gip) = True

                        End If

                    Next

                End If

            Next
        Next

        ' Определяем какие воспоминания подходят под паттерн волны гиппокампа

        For Each C As Concept In Dictionary(M_Gip)

            F1 = True
            N1 = 0
            N2 = 0

            For Each p In C.Pattern

                If GCol(p.ix, p.iy).A Then

                    N1 += 1

                    If GCol(p.ix, p.iy).Column(p.iz).A_med_sp(M_Gip) Then
                        N2 += 1
                    End If

                End If


                

            Next

            If N1 = N2 Then

                Info(M_Gip).Add(C.ID)

            End If


        Next
       


        DrawA_sp_ev()
        DrawA_ev()
        DrawA_sp2()



    End Sub
   
End Class
