from collections import OrderedDict

from ydk.types import Entity, EntityPath, Identity, Enum, YType, YLeaf, YLeafList, YList, LeafDataList, Bits, Empty, Decimal64
from ydk.filters import YFilter
from ydk.errors import YError, YModelError
from ydk.errors.error_handler import handle_type_error as _handle_type_error

class LogicalProtocol(Enum):
    """
    LogicalProtocol (Enum Class)

    Logical protocol

    .. data:: proto_type_unknown = 0

    	Unknown protocol framing

    .. data:: proto_type_ethernet = 1

    	Ethernet protocol framing

    .. data:: proto_type_otn = 2

    	OTN protocol framing

    """

    proto_type_unknown = Enum.YLeaf(0, "proto-type-unknown")

    proto_type_ethernet = Enum.YLeaf(1, "proto-type-ethernet")

    proto_type_otn = Enum.YLeaf(2, "proto-type-otn")

class TribProtocol(Enum):
    """
    TribProtocol (Enum Class)

    Trib protocol

    .. data:: trib_proto_type_unknown = 0

    	Unknown protocol

    .. data:: trib_proto_type1ge = 1

    	1G Ethernet protocol

    .. data:: trib_proto_type_oc48 = 2

    	OC48 protocol

    .. data:: trib_proto_type_stm16 = 3

    	STM 16 protocol

    .. data:: trib_proto_type10gelan = 4

    	10G Ethernet LAN protocol

    .. data:: trib_proto_type10gewan = 5

    	10G Ethernet WAN protocol

    .. data:: trib_proto_type_oc192 = 6

    	OC 192 (9.6GB) port protocol

    .. data:: trib_proto_type_stm64 = 7

    	STM 64 protocol

    .. data:: trib_proto_type_otu2 = 8

    	OTU 2 protocol

    .. data:: trib_proto_type_otu2e = 9

    	OTU 2e protocol

    .. data:: trib_proto_type_otu1e = 10

    	OTU 1e protocol

    .. data:: trib_proto_type_odu2 = 11

    	ODU 2 protocol

    .. data:: trib_proto_type_odu2e = 12

    	ODU 2e protocol

    .. data:: trib_proto_type40ge = 13

    	40G Ethernet port protocol

    .. data:: trib_proto_type_oc768 = 14

    	OC 768 protocol

    .. data:: trib_proto_type_stm256 = 15

    	STM 256 protocol

    .. data:: trib_proto_type_otu3 = 16

    	OTU 3 protocol

    .. data:: trib_proto_type_odu3 = 17

    	ODU 3 protocol

    .. data:: trib_proto_type100ge = 18

    	100G Ethernet protocol

    .. data:: trib_proto_type100g_mlg = 19

    	100G MLG protocol

    .. data:: trib_proto_type_otu4 = 20

    	OTU4 signal protocol (112G) for transporting

    	100GE signal

    .. data:: trib_proto_type_otu_cn = 21

    	OTU Cn protocol

    .. data:: trib_proto_type_odu4 = 22

    	ODU 4 protocol

    """

    trib_proto_type_unknown = Enum.YLeaf(0, "trib-proto-type-unknown")

    trib_proto_type1ge = Enum.YLeaf(1, "trib-proto-type1ge")

    trib_proto_type_oc48 = Enum.YLeaf(2, "trib-proto-type-oc48")

    trib_proto_type_stm16 = Enum.YLeaf(3, "trib-proto-type-stm16")

    trib_proto_type10gelan = Enum.YLeaf(4, "trib-proto-type10gelan")

    trib_proto_type10gewan = Enum.YLeaf(5, "trib-proto-type10gewan")

    trib_proto_type_oc192 = Enum.YLeaf(6, "trib-proto-type-oc192")

    trib_proto_type_stm64 = Enum.YLeaf(7, "trib-proto-type-stm64")

    trib_proto_type_otu2 = Enum.YLeaf(8, "trib-proto-type-otu2")

    trib_proto_type_otu2e = Enum.YLeaf(9, "trib-proto-type-otu2e")

    trib_proto_type_otu1e = Enum.YLeaf(10, "trib-proto-type-otu1e")

    trib_proto_type_odu2 = Enum.YLeaf(11, "trib-proto-type-odu2")

    trib_proto_type_odu2e = Enum.YLeaf(12, "trib-proto-type-odu2e")

    trib_proto_type40ge = Enum.YLeaf(13, "trib-proto-type40ge")

    trib_proto_type_oc768 = Enum.YLeaf(14, "trib-proto-type-oc768")

    trib_proto_type_stm256 = Enum.YLeaf(15, "trib-proto-type-stm256")

    trib_proto_type_otu3 = Enum.YLeaf(16, "trib-proto-type-otu3")

    trib_proto_type_odu3 = Enum.YLeaf(17, "trib-proto-type-odu3")

    trib_proto_type100ge = Enum.YLeaf(18, "trib-proto-type100ge")

    trib_proto_type100g_mlg = Enum.YLeaf(19, "trib-proto-type100g-mlg")

    trib_proto_type_otu4 = Enum.YLeaf(20, "trib-proto-type-otu4")

    trib_proto_type_otu_cn = Enum.YLeaf(21, "trib-proto-type-otu-cn")

    trib_proto_type_odu4 = Enum.YLeaf(22, "trib-proto-type-odu4")

class TribRateClass(Enum):
    """
    TribRateClass (Enum Class)

    Trib rate class

    .. data:: trib_rate_unknown = 0

    	Unknown tributary signal rate

    .. data:: trib_rate1g = 1

    	1G tributary signal rate

    .. data:: trib_rate25g = 2

    	2.5G tributary signal rate

    .. data:: trib_rate10g = 3

    	10G tributary signal rate

    .. data:: trib_rate40g = 4

    	40G tributary signal rate

    .. data:: trib_rate100g = 5

    	100G tributary signal rate

    """

    trib_rate_unknown = Enum.YLeaf(0, "trib-rate-unknown")

    trib_rate1g = Enum.YLeaf(1, "trib-rate1g")

    trib_rate25g = Enum.YLeaf(2, "trib-rate25g")

    trib_rate10g = Enum.YLeaf(3, "trib-rate10g")

    trib_rate40g = Enum.YLeaf(4, "trib-rate40g")

    trib_rate100g = Enum.YLeaf(5, "trib-rate100g")

class OpticalInterface(Entity):
    """
    System\-wide view of interface operational data

    .. attribute:: config_status

    	Table containing status information
    	**type**\:  :py:class:`ConfigStatus <ydk.models.cisco_ios_xr.Cisco_IOS_XR_terminal_device_oper.OpticalInterface.ConfigStatus>`

    .. attribute:: optical_channel_interfaces

    	The operational attributes for a particular optical channel
    	**type**\:  :py:class:`OpticalChannelInterfaces <ydk.models.cisco_ios_xr.Cisco_IOS_XR_terminal_device_oper.OpticalInterface.OpticalChannelInterfaces>`

    .. attribute:: graph

    	Table containing Graph Structure and related info
    	**type**\:  :py:class:`Graph <ydk.models.cisco_ios_xr.Cisco_IOS_XR_terminal_device_oper.OpticalInterface.Graph>`

    .. attribute:: operational_modes

    	The Operational Mode Table
    	**type**\:  :py:class:`OperationalModes <ydk.models.cisco_ios_xr.Cisco_IOS_XR_terminal_device_oper.OpticalInterface.OperationalModes>`

    .. attribute:: optical_logical_interfaces

    	The operational attributes for a logical channel
    	**type**\:  :py:class:`OpticalLogicalInterfaces <ydk.models.cisco_ios_xr.Cisco_IOS_XR_terminal_device_oper.OpticalInterface.OpticalLogicalInterfaces>`

    """

    _prefix = 'terminal-device-oper'
    _revision = '2015-11-09'

    def __init__(self):
        super(OpticalInterface, self).__init__()
        self._top_entity = None

        self.yang_name = "optical-interface"
        self.yang_parent_name = "Cisco-IOS-XR-terminal-device-oper"
        self.is_top_level_class = True
        self.has_list_ancestor = False
        self.ylist_key_names = []
        self._child_container_classes = OrderedDict([("config-status", ("config_status", OpticalInterface.ConfigStatus)), ("optical-channel-interfaces", ("optical_channel_interfaces", OpticalInterface.OpticalChannelInterfaces)), ("graph", ("graph", OpticalInterface.Graph)), ("operational-modes", ("operational_modes", OpticalInterface.OperationalModes)), ("optical-logical-interfaces", ("optical_logical_interfaces", OpticalInterface.OpticalLogicalInterfaces))])
        self._child_list_classes = OrderedDict([])
        self._leafs = OrderedDict()

        self.config_status = OpticalInterface.ConfigStatus()
        self.config_status.parent = self
        self._children_name_map["config_status"] = "config-status"
        self._children_yang_names.add("config-status")

        self.optical_channel_interfaces = OpticalInterface.OpticalChannelInterfaces()
        self.optical_channel_interfaces.parent = self
        self._children_name_map["optical_channel_interfaces"] = "optical-channel-interfaces"
        self._children_yang_names.add("optical-channel-interfaces")

        self.graph = OpticalInterface.Graph()
        self.graph.parent = self
        self._children_name_map["graph"] = "graph"
        self._children_yang_names.add("graph")

        self.operational_modes = OpticalInterface.OperationalModes()
        self.operational_modes.parent = self
        self._children_name_map["operational_modes"] = "operational-modes"
        self._children_yang_names.add("operational-modes")

        self.optical_logical_interfaces = OpticalInterface.OpticalLogicalInterfaces()
        self.optical_logical_interfaces.parent = self
        self._children_name_map["optical_logical_interfaces"] = "optical-logical-interfaces"
        self._children_yang_names.add("optical-logical-interfaces")
        self._segment_path = lambda: "Cisco-IOS-XR-terminal-device-oper:optical-interface"

    class ConfigStatus(Entity):
        """
        Table containing status information

        .. attribute:: partial_config

        	The bag containing partial config status
        	**type**\:  :py:class:`PartialConfig <ydk.models.cisco_ios_xr.Cisco_IOS_XR_terminal_device_oper.OpticalInterface.ConfigStatus.PartialConfig>`

        .. attribute:: slice_tables

        	The container containing slice status information
        	**type**\:  :py:class:`SliceTables <ydk.models.cisco_ios_xr.Cisco_IOS_XR_terminal_device_oper.OpticalInterface.ConfigStatus.SliceTables>`

        """

        _prefix = 'terminal-device-oper'
        _revision = '2015-11-09'

        def __init__(self):
            super(OpticalInterface.ConfigStatus, self).__init__()

            self.yang_name = "config-status"
            self.yang_parent_name = "optical-interface"
            self.is_top_level_class = False
            self.has_list_ancestor = False
            self.ylist_key_names = []
            self._child_container_classes = OrderedDict([("partial-config", ("partial_config", OpticalInterface.ConfigStatus.PartialConfig)), ("slice-tables", ("slice_tables", OpticalInterface.ConfigStatus.SliceTables))])
            self._child_list_classes = OrderedDict([])
            self._leafs = OrderedDict()

            self.partial_config = OpticalInterface.ConfigStatus.PartialConfig()
            self.partial_config.parent = self
            self._children_name_map["partial_config"] = "partial-config"
            self._children_yang_names.add("partial-config")

            self.slice_tables = OpticalInterface.ConfigStatus.SliceTables()
            self.slice_tables.parent = self
            self._children_name_map["slice_tables"] = "slice-tables"
            self._children_yang_names.add("slice-tables")
            self._segment_path = lambda: "config-status"
            self._absolute_path = lambda: "Cisco-IOS-XR-terminal-device-oper:optical-interface/%s" % self._segment_path()

        class PartialConfig(Entity):
            """
            The bag containing partial config status

            .. attribute:: partial_config

            	PartialConfig
            	**type**\: int

            	**range:** 0..255

            """

            _prefix = 'terminal-device-oper'
            _revision = '2015-11-09'

            def __init__(self):
                super(OpticalInterface.ConfigStatus.PartialConfig, self).__init__()

                self.yang_name = "partial-config"
                self.yang_parent_name = "config-status"
                self.is_top_level_class = False
                self.has_list_ancestor = False
                self.ylist_key_names = []
                self._child_container_classes = OrderedDict([])
                self._child_list_classes = OrderedDict([])
                self._leafs = OrderedDict([
                    ('partial_config', YLeaf(YType.uint8, 'partial-config')),
                ])
                self.partial_config = None
                self._segment_path = lambda: "partial-config"
                self._absolute_path = lambda: "Cisco-IOS-XR-terminal-device-oper:optical-interface/config-status/%s" % self._segment_path()

            def __setattr__(self, name, value):
                self._perform_setattr(OpticalInterface.ConfigStatus.PartialConfig, ['partial_config'], name, value)

        class SliceTables(Entity):
            """
            The container containing slice status
            information

            .. attribute:: slice_table

            	The table contains list of slices present
            	**type**\: list of  		 :py:class:`SliceTable <ydk.models.cisco_ios_xr.Cisco_IOS_XR_terminal_device_oper.OpticalInterface.ConfigStatus.SliceTables.SliceTable>`

            """

            _prefix = 'terminal-device-oper'
            _revision = '2015-11-09'

            def __init__(self):
                super(OpticalInterface.ConfigStatus.SliceTables, self).__init__()

                self.yang_name = "slice-tables"
                self.yang_parent_name = "config-status"
                self.is_top_level_class = False
                self.has_list_ancestor = False
                self.ylist_key_names = []
                self._child_container_classes = OrderedDict([])
                self._child_list_classes = OrderedDict([("slice-table", ("slice_table", OpticalInterface.ConfigStatus.SliceTables.SliceTable))])
                self._leafs = OrderedDict()

                self.slice_table = YList(self)
                self._segment_path = lambda: "slice-tables"
                self._absolute_path = lambda: "Cisco-IOS-XR-terminal-device-oper:optical-interface/config-status/%s" % self._segment_path()

            def __setattr__(self, name, value):
                self._perform_setattr(OpticalInterface.ConfigStatus.SliceTables, [], name, value)

            class SliceTable(Entity):
                """
                The table contains list of slices present

                .. attribute:: index  (key)

                	The index of slice
                	**type**\: int

                	**range:** \-2147483648..2147483647

                .. attribute:: slice_status_attr

                	The bag containing slice config status
                	**type**\:  :py:class:`SliceStatusAttr <ydk.models.cisco_ios_xr.Cisco_IOS_XR_terminal_device_oper.OpticalInterface.ConfigStatus.SliceTables.SliceTable.SliceStatusAttr>`

                """

                _prefix = 'terminal-device-oper'
                _revision = '2015-11-09'

                def __init__(self):
                    super(OpticalInterface.ConfigStatus.SliceTables.SliceTable, self).__init__()

                    self.yang_name = "slice-table"
                    self.yang_parent_name = "slice-tables"
                    self.is_top_level_class = False
                    self.has_list_ancestor = False
                    self.ylist_key_names = ['index']
                    self._child_container_classes = OrderedDict([("slice-status-attr", ("slice_status_attr", OpticalInterface.ConfigStatus.SliceTables.SliceTable.SliceStatusAttr))])
                    self._child_list_classes = OrderedDict([])
                    self._leafs = OrderedDict([
                        ('index', YLeaf(YType.int32, 'index')),
                    ])
                    self.index = None

                    self.slice_status_attr = OpticalInterface.ConfigStatus.SliceTables.SliceTable.SliceStatusAttr()
                    self.slice_status_attr.parent = self
                    self._children_name_map["slice_status_attr"] = "slice-status-attr"
                    self._children_yang_names.add("slice-status-attr")
                    self._segment_path = lambda: "slice-table" + "[index='" + str(self.index) + "']"
                    self._absolute_path = lambda: "Cisco-IOS-XR-terminal-device-oper:optical-interface/config-status/slice-tables/%s" % self._segment_path()

                def __setattr__(self, name, value):
                    self._perform_setattr(OpticalInterface.ConfigStatus.SliceTables.SliceTable, ['index'], name, value)

                class SliceStatusAttr(Entity):
                    """
                    The bag containing slice config status

                    .. attribute:: slice

                    	Slice
                    	**type**\: int

                    	**range:** 0..255

                    .. attribute:: prov_status

                    	ProvStatus
                    	**type**\: str

                    	**length:** 0..32

                    .. attribute:: present_config

                    	PresentConfig
                    	**type**\: str

                    	**length:** 0..32

                    .. attribute:: present_timestamp

                    	PresentTimestamp
                    	**type**\: str

                    	**length:** 0..32

                    .. attribute:: past_config

                    	PastConfig
                    	**type**\: str

                    	**length:** 0..32

                    .. attribute:: past_timestamp

                    	PastTimestamp
                    	**type**\: str

                    	**length:** 0..32

                    .. attribute:: err_str

                    	ErrStr
                    	**type**\: str

                    	**length:** 0..1024

                    .. attribute:: err_timestamp

                    	ErrTimestamp
                    	**type**\: str

                    	**length:** 0..32

                    """

                    _prefix = 'terminal-device-oper'
                    _revision = '2015-11-09'

                    def __init__(self):
                        super(OpticalInterface.ConfigStatus.SliceTables.SliceTable.SliceStatusAttr, self).__init__()

                        self.yang_name = "slice-status-attr"
                        self.yang_parent_name = "slice-table"
                        self.is_top_level_class = False
                        self.has_list_ancestor = True
                        self.ylist_key_names = []
                        self._child_container_classes = OrderedDict([])
                        self._child_list_classes = OrderedDict([])
                        self._leafs = OrderedDict([
                            ('slice', YLeaf(YType.uint8, 'slice')),
                            ('prov_status', YLeaf(YType.str, 'prov-status')),
                            ('present_config', YLeaf(YType.str, 'present-config')),
                            ('present_timestamp', YLeaf(YType.str, 'present-timestamp')),
                            ('past_config', YLeaf(YType.str, 'past-config')),
                            ('past_timestamp', YLeaf(YType.str, 'past-timestamp')),
                            ('err_str', YLeaf(YType.str, 'err-str')),
                            ('err_timestamp', YLeaf(YType.str, 'err-timestamp')),
                        ])
                        self.slice = None
                        self.prov_status = None
                        self.present_config = None
                        self.present_timestamp = None
                        self.past_config = None
                        self.past_timestamp = None
                        self.err_str = None
                        self.err_timestamp = None
                        self._segment_path = lambda: "slice-status-attr"

                    def __setattr__(self, name, value):
                        self._perform_setattr(OpticalInterface.ConfigStatus.SliceTables.SliceTable.SliceStatusAttr, ['slice', 'prov_status', 'present_config', 'present_timestamp', 'past_config', 'past_timestamp', 'err_str', 'err_timestamp'], name, value)

    class OpticalChannelInterfaces(Entity):
        """
        The operational attributes for a particular
        optical channel

        .. attribute:: optical_channel_interface

        	The operational attributes for an optical channel
        	**type**\: list of  		 :py:class:`OpticalChannelInterface <ydk.models.cisco_ios_xr.Cisco_IOS_XR_terminal_device_oper.OpticalInterface.OpticalChannelInterfaces.OpticalChannelInterface>`

        """

        _prefix = 'terminal-device-oper'
        _revision = '2015-11-09'

        def __init__(self):
            super(OpticalInterface.OpticalChannelInterfaces, self).__init__()

            self.yang_name = "optical-channel-interfaces"
            self.yang_parent_name = "optical-interface"
            self.is_top_level_class = False
            self.has_list_ancestor = False
            self.ylist_key_names = []
            self._child_container_classes = OrderedDict([])
            self._child_list_classes = OrderedDict([("optical-channel-interface", ("optical_channel_interface", OpticalInterface.OpticalChannelInterfaces.OpticalChannelInterface))])
            self._leafs = OrderedDict()

            self.optical_channel_interface = YList(self)
            self._segment_path = lambda: "optical-channel-interfaces"
            self._absolute_path = lambda: "Cisco-IOS-XR-terminal-device-oper:optical-interface/%s" % self._segment_path()

        def __setattr__(self, name, value):
            self._perform_setattr(OpticalInterface.OpticalChannelInterfaces, [], name, value)

        class OpticalChannelInterface(Entity):
            """
            The operational attributes for an optical
            channel

            .. attribute:: location  (key)

            	The name of the optical\-channel
            	**type**\: str

            	**pattern:** [\\w\\\-\\.\:,\_@#%$\\+=\\\|;]+

            .. attribute:: optical_channel_interface_attr

            	The operational attributes for an optical channel
            	**type**\:  :py:class:`OpticalChannelInterfaceAttr <ydk.models.cisco_ios_xr.Cisco_IOS_XR_terminal_device_oper.OpticalInterface.OpticalChannelInterfaces.OpticalChannelInterface.OpticalChannelInterfaceAttr>`

            """

            _prefix = 'terminal-device-oper'
            _revision = '2015-11-09'

            def __init__(self):
                super(OpticalInterface.OpticalChannelInterfaces.OpticalChannelInterface, self).__init__()

                self.yang_name = "optical-channel-interface"
                self.yang_parent_name = "optical-channel-interfaces"
                self.is_top_level_class = False
                self.has_list_ancestor = False
                self.ylist_key_names = ['location']
                self._child_container_classes = OrderedDict([("optical-channel-interface-attr", ("optical_channel_interface_attr", OpticalInterface.OpticalChannelInterfaces.OpticalChannelInterface.OpticalChannelInterfaceAttr))])
                self._child_list_classes = OrderedDict([])
                self._leafs = OrderedDict([
                    ('location', YLeaf(YType.str, 'location')),
                ])
                self.location = None

                self.optical_channel_interface_attr = OpticalInterface.OpticalChannelInterfaces.OpticalChannelInterface.OpticalChannelInterfaceAttr()
                self.optical_channel_interface_attr.parent = self
                self._children_name_map["optical_channel_interface_attr"] = "optical-channel-interface-attr"
                self._children_yang_names.add("optical-channel-interface-attr")
                self._segment_path = lambda: "optical-channel-interface" + "[location='" + str(self.location) + "']"
                self._absolute_path = lambda: "Cisco-IOS-XR-terminal-device-oper:optical-interface/optical-channel-interfaces/%s" % self._segment_path()

            def __setattr__(self, name, value):
                self._perform_setattr(OpticalInterface.OpticalChannelInterfaces.OpticalChannelInterface, ['location'], name, value)

            class OpticalChannelInterfaceAttr(Entity):
                """
                The operational attributes for an optical
                channel

                .. attribute:: name

                	Name
                	**type**\: str

                	**length:** 0..128

                .. attribute:: index

                	Index
                	**type**\: int

                	**range:** 0..4294967295

                .. attribute:: frequency

                	Frequency
                	**type**\: int

                	**range:** 0..18446744073709551615

                .. attribute:: power

                	Power
                	**type**\: int

                	**range:** 0..18446744073709551615

                .. attribute:: oper_mode

                	OperMode
                	**type**\: int

                	**range:** 0..4294967295

                .. attribute:: line_port

                	LinePort
                	**type**\: str

                	**length:** 0..128

                """

                _prefix = 'terminal-device-oper'
                _revision = '2015-11-09'

                def __init__(self):
                    super(OpticalInterface.OpticalChannelInterfaces.OpticalChannelInterface.OpticalChannelInterfaceAttr, self).__init__()

                    self.yang_name = "optical-channel-interface-attr"
                    self.yang_parent_name = "optical-channel-interface"
                    self.is_top_level_class = False
                    self.has_list_ancestor = True
                    self.ylist_key_names = []
                    self._child_container_classes = OrderedDict([])
                    self._child_list_classes = OrderedDict([])
                    self._leafs = OrderedDict([
                        ('name', YLeaf(YType.str, 'name')),
                        ('index', YLeaf(YType.uint32, 'index')),
                        ('frequency', YLeaf(YType.uint64, 'frequency')),
                        ('power', YLeaf(YType.uint64, 'power')),
                        ('oper_mode', YLeaf(YType.uint32, 'oper-mode')),
                        ('line_port', YLeaf(YType.str, 'line-port')),
                    ])
                    self.name = None
                    self.index = None
                    self.frequency = None
                    self.power = None
                    self.oper_mode = None
                    self.line_port = None
                    self._segment_path = lambda: "optical-channel-interface-attr"

                def __setattr__(self, name, value):
                    self._perform_setattr(OpticalInterface.OpticalChannelInterfaces.OpticalChannelInterface.OpticalChannelInterfaceAttr, ['name', 'index', 'frequency', 'power', 'oper_mode', 'line_port'], name, value)

    class Graph(Entity):
        """
        Table containing Graph Structure and related
        info

        .. attribute:: adj_list_path

        	The path containg file which has adjacency list stored
        	**type**\:  :py:class:`AdjListPath <ydk.models.cisco_ios_xr.Cisco_IOS_XR_terminal_device_oper.OpticalInterface.Graph.AdjListPath>`

        .. attribute:: graph_structure_path

        	The path containg file which has graph structure stored
        	**type**\:  :py:class:`GraphStructurePath <ydk.models.cisco_ios_xr.Cisco_IOS_XR_terminal_device_oper.OpticalInterface.Graph.GraphStructurePath>`

        """

        _prefix = 'terminal-device-oper'
        _revision = '2015-11-09'

        def __init__(self):
            super(OpticalInterface.Graph, self).__init__()

            self.yang_name = "graph"
            self.yang_parent_name = "optical-interface"
            self.is_top_level_class = False
            self.has_list_ancestor = False
            self.ylist_key_names = []
            self._child_container_classes = OrderedDict([("adj-list-path", ("adj_list_path", OpticalInterface.Graph.AdjListPath)), ("graph-structure-path", ("graph_structure_path", OpticalInterface.Graph.GraphStructurePath))])
            self._child_list_classes = OrderedDict([])
            self._leafs = OrderedDict()

            self.adj_list_path = OpticalInterface.Graph.AdjListPath()
            self.adj_list_path.parent = self
            self._children_name_map["adj_list_path"] = "adj-list-path"
            self._children_yang_names.add("adj-list-path")

            self.graph_structure_path = OpticalInterface.Graph.GraphStructurePath()
            self.graph_structure_path.parent = self
            self._children_name_map["graph_structure_path"] = "graph-structure-path"
            self._children_yang_names.add("graph-structure-path")
            self._segment_path = lambda: "graph"
            self._absolute_path = lambda: "Cisco-IOS-XR-terminal-device-oper:optical-interface/%s" % self._segment_path()

        class AdjListPath(Entity):
            """
            The path containg file which has adjacency list
            stored

            .. attribute:: path

            	Path
            	**type**\: str

            	**length:** 0..256

            """

            _prefix = 'terminal-device-oper'
            _revision = '2015-11-09'

            def __init__(self):
                super(OpticalInterface.Graph.AdjListPath, self).__init__()

                self.yang_name = "adj-list-path"
                self.yang_parent_name = "graph"
                self.is_top_level_class = False
                self.has_list_ancestor = False
                self.ylist_key_names = []
                self._child_container_classes = OrderedDict([])
                self._child_list_classes = OrderedDict([])
                self._leafs = OrderedDict([
                    ('path', YLeaf(YType.str, 'path')),
                ])
                self.path = None
                self._segment_path = lambda: "adj-list-path"
                self._absolute_path = lambda: "Cisco-IOS-XR-terminal-device-oper:optical-interface/graph/%s" % self._segment_path()

            def __setattr__(self, name, value):
                self._perform_setattr(OpticalInterface.Graph.AdjListPath, ['path'], name, value)

        class GraphStructurePath(Entity):
            """
            The path containg file which has graph
            structure stored

            .. attribute:: path

            	Path
            	**type**\: str

            	**length:** 0..256

            """

            _prefix = 'terminal-device-oper'
            _revision = '2015-11-09'

            def __init__(self):
                super(OpticalInterface.Graph.GraphStructurePath, self).__init__()

                self.yang_name = "graph-structure-path"
                self.yang_parent_name = "graph"
                self.is_top_level_class = False
                self.has_list_ancestor = False
                self.ylist_key_names = []
                self._child_container_classes = OrderedDict([])
                self._child_list_classes = OrderedDict([])
                self._leafs = OrderedDict([
                    ('path', YLeaf(YType.str, 'path')),
                ])
                self.path = None
                self._segment_path = lambda: "graph-structure-path"
                self._absolute_path = lambda: "Cisco-IOS-XR-terminal-device-oper:optical-interface/graph/%s" % self._segment_path()

            def __setattr__(self, name, value):
                self._perform_setattr(OpticalInterface.Graph.GraphStructurePath, ['path'], name, value)

    class OperationalModes(Entity):
        """
        The Operational Mode Table

        .. attribute:: operational_mode

        	Mode supported on Device
        	**type**\: list of  		 :py:class:`OperationalMode <ydk.models.cisco_ios_xr.Cisco_IOS_XR_terminal_device_oper.OpticalInterface.OperationalModes.OperationalMode>`

        """

        _prefix = 'terminal-device-oper'
        _revision = '2015-11-09'

        def __init__(self):
            super(OpticalInterface.OperationalModes, self).__init__()

            self.yang_name = "operational-modes"
            self.yang_parent_name = "optical-interface"
            self.is_top_level_class = False
            self.has_list_ancestor = False
            self.ylist_key_names = []
            self._child_container_classes = OrderedDict([])
            self._child_list_classes = OrderedDict([("operational-mode", ("operational_mode", OpticalInterface.OperationalModes.OperationalMode))])
            self._leafs = OrderedDict()

            self.operational_mode = YList(self)
            self._segment_path = lambda: "operational-modes"
            self._absolute_path = lambda: "Cisco-IOS-XR-terminal-device-oper:optical-interface/%s" % self._segment_path()

        def __setattr__(self, name, value):
            self._perform_setattr(OpticalInterface.OperationalModes, [], name, value)

        class OperationalMode(Entity):
            """
            Mode supported on Device

            .. attribute:: mode_id  (key)

            	Mode\-id for supported mode on Device
            	**type**\: int

            	**range:** \-2147483648..2147483647

            .. attribute:: operational_mode_attributes

            	The operational attributes for mxp driver fec\-mode
            	**type**\:  :py:class:`OperationalModeAttributes <ydk.models.cisco_ios_xr.Cisco_IOS_XR_terminal_device_oper.OpticalInterface.OperationalModes.OperationalMode.OperationalModeAttributes>`

            """

            _prefix = 'terminal-device-oper'
            _revision = '2015-11-09'

            def __init__(self):
                super(OpticalInterface.OperationalModes.OperationalMode, self).__init__()

                self.yang_name = "operational-mode"
                self.yang_parent_name = "operational-modes"
                self.is_top_level_class = False
                self.has_list_ancestor = False
                self.ylist_key_names = ['mode_id']
                self._child_container_classes = OrderedDict([("operational-mode-attributes", ("operational_mode_attributes", OpticalInterface.OperationalModes.OperationalMode.OperationalModeAttributes))])
                self._child_list_classes = OrderedDict([])
                self._leafs = OrderedDict([
                    ('mode_id', YLeaf(YType.int32, 'mode-id')),
                ])
                self.mode_id = None

                self.operational_mode_attributes = OpticalInterface.OperationalModes.OperationalMode.OperationalModeAttributes()
                self.operational_mode_attributes.parent = self
                self._children_name_map["operational_mode_attributes"] = "operational-mode-attributes"
                self._children_yang_names.add("operational-mode-attributes")
                self._segment_path = lambda: "operational-mode" + "[mode-id='" + str(self.mode_id) + "']"
                self._absolute_path = lambda: "Cisco-IOS-XR-terminal-device-oper:optical-interface/operational-modes/%s" % self._segment_path()

            def __setattr__(self, name, value):
                self._perform_setattr(OpticalInterface.OperationalModes.OperationalMode, ['mode_id'], name, value)

            class OperationalModeAttributes(Entity):
                """
                The operational attributes for mxp driver
                fec\-mode

                .. attribute:: description

                	Description
                	**type**\: str

                	**length:** 0..128

                .. attribute:: vendor_id

                	VendorId
                	**type**\: str

                	**length:** 0..64

                """

                _prefix = 'terminal-device-oper'
                _revision = '2015-11-09'

                def __init__(self):
                    super(OpticalInterface.OperationalModes.OperationalMode.OperationalModeAttributes, self).__init__()

                    self.yang_name = "operational-mode-attributes"
                    self.yang_parent_name = "operational-mode"
                    self.is_top_level_class = False
                    self.has_list_ancestor = True
                    self.ylist_key_names = []
                    self._child_container_classes = OrderedDict([])
                    self._child_list_classes = OrderedDict([])
                    self._leafs = OrderedDict([
                        ('description', YLeaf(YType.str, 'description')),
                        ('vendor_id', YLeaf(YType.str, 'vendor-id')),
                    ])
                    self.description = None
                    self.vendor_id = None
                    self._segment_path = lambda: "operational-mode-attributes"

                def __setattr__(self, name, value):
                    self._perform_setattr(OpticalInterface.OperationalModes.OperationalMode.OperationalModeAttributes, ['description', 'vendor_id'], name, value)

    class OpticalLogicalInterfaces(Entity):
        """
        The operational attributes for a logical channel

        .. attribute:: optical_logical_interface

        	The operational attributes for a logical channel
        	**type**\: list of  		 :py:class:`OpticalLogicalInterface <ydk.models.cisco_ios_xr.Cisco_IOS_XR_terminal_device_oper.OpticalInterface.OpticalLogicalInterfaces.OpticalLogicalInterface>`

        """

        _prefix = 'terminal-device-oper'
        _revision = '2015-11-09'

        def __init__(self):
            super(OpticalInterface.OpticalLogicalInterfaces, self).__init__()

            self.yang_name = "optical-logical-interfaces"
            self.yang_parent_name = "optical-interface"
            self.is_top_level_class = False
            self.has_list_ancestor = False
            self.ylist_key_names = []
            self._child_container_classes = OrderedDict([])
            self._child_list_classes = OrderedDict([("optical-logical-interface", ("optical_logical_interface", OpticalInterface.OpticalLogicalInterfaces.OpticalLogicalInterface))])
            self._leafs = OrderedDict()

            self.optical_logical_interface = YList(self)
            self._segment_path = lambda: "optical-logical-interfaces"
            self._absolute_path = lambda: "Cisco-IOS-XR-terminal-device-oper:optical-interface/%s" % self._segment_path()

        def __setattr__(self, name, value):
            self._perform_setattr(OpticalInterface.OpticalLogicalInterfaces, [], name, value)

        class OpticalLogicalInterface(Entity):
            """
            The operational attributes for a logical
            channel

            .. attribute:: index  (key)

            	The index of the logical\-channel
            	**type**\: int

            	**range:** \-2147483648..2147483647

            .. attribute:: optical_logical_interface_attr

            	The operational attributes for a particular logical channel
            	**type**\:  :py:class:`OpticalLogicalInterfaceAttr <ydk.models.cisco_ios_xr.Cisco_IOS_XR_terminal_device_oper.OpticalInterface.OpticalLogicalInterfaces.OpticalLogicalInterface.OpticalLogicalInterfaceAttr>`

            .. attribute:: optical_logical_interface_logical_channel_assignments

            	The operational attributes for a particular interface
            	**type**\:  :py:class:`OpticalLogicalInterfaceLogicalChannelAssignments <ydk.models.cisco_ios_xr.Cisco_IOS_XR_terminal_device_oper.OpticalInterface.OpticalLogicalInterfaces.OpticalLogicalInterface.OpticalLogicalInterfaceLogicalChannelAssignments>`

            """

            _prefix = 'terminal-device-oper'
            _revision = '2015-11-09'

            def __init__(self):
                super(OpticalInterface.OpticalLogicalInterfaces.OpticalLogicalInterface, self).__init__()

                self.yang_name = "optical-logical-interface"
                self.yang_parent_name = "optical-logical-interfaces"
                self.is_top_level_class = False
                self.has_list_ancestor = False
                self.ylist_key_names = ['index']
                self._child_container_classes = OrderedDict([("optical-logical-interface-attr", ("optical_logical_interface_attr", OpticalInterface.OpticalLogicalInterfaces.OpticalLogicalInterface.OpticalLogicalInterfaceAttr)), ("optical-logical-interface-logical-channel-assignments", ("optical_logical_interface_logical_channel_assignments", OpticalInterface.OpticalLogicalInterfaces.OpticalLogicalInterface.OpticalLogicalInterfaceLogicalChannelAssignments))])
                self._child_list_classes = OrderedDict([])
                self._leafs = OrderedDict([
                    ('index', YLeaf(YType.int32, 'index')),
                ])
                self.index = None

                self.optical_logical_interface_attr = OpticalInterface.OpticalLogicalInterfaces.OpticalLogicalInterface.OpticalLogicalInterfaceAttr()
                self.optical_logical_interface_attr.parent = self
                self._children_name_map["optical_logical_interface_attr"] = "optical-logical-interface-attr"
                self._children_yang_names.add("optical-logical-interface-attr")

                self.optical_logical_interface_logical_channel_assignments = OpticalInterface.OpticalLogicalInterfaces.OpticalLogicalInterface.OpticalLogicalInterfaceLogicalChannelAssignments()
                self.optical_logical_interface_logical_channel_assignments.parent = self
                self._children_name_map["optical_logical_interface_logical_channel_assignments"] = "optical-logical-interface-logical-channel-assignments"
                self._children_yang_names.add("optical-logical-interface-logical-channel-assignments")
                self._segment_path = lambda: "optical-logical-interface" + "[index='" + str(self.index) + "']"
                self._absolute_path = lambda: "Cisco-IOS-XR-terminal-device-oper:optical-interface/optical-logical-interfaces/%s" % self._segment_path()

            def __setattr__(self, name, value):
                self._perform_setattr(OpticalInterface.OpticalLogicalInterfaces.OpticalLogicalInterface, ['index'], name, value)

            class OpticalLogicalInterfaceAttr(Entity):
                """
                The operational attributes for a particular
                logical channel

                .. attribute:: logical_channel_index

                	LogicalChannelIndex
                	**type**\: int

                	**range:** 0..4294967295

                .. attribute:: logical_channel_ifname

                	LogicalChannelIfname
                	**type**\: str

                	**length:** 0..128

                .. attribute:: type

                	Type
                	**type**\: str

                	**length:** 0..32

                .. attribute:: trib_rate_class

                	TribRateClass
                	**type**\:  :py:class:`TribRateClass <ydk.models.cisco_ios_xr.Cisco_IOS_XR_terminal_device_oper.TribRateClass>`

                .. attribute:: trib_protocol

                	TribProtocol
                	**type**\:  :py:class:`TribProtocol <ydk.models.cisco_ios_xr.Cisco_IOS_XR_terminal_device_oper.TribProtocol>`

                .. attribute:: protocol_type

                	ProtocolType
                	**type**\:  :py:class:`LogicalProtocol <ydk.models.cisco_ios_xr.Cisco_IOS_XR_terminal_device_oper.LogicalProtocol>`

                .. attribute:: admin_state

                	AdminState
                	**type**\: int

                	**range:** 0..4294967295

                .. attribute:: loopback_mode

                	LoopbackMode
                	**type**\: int

                	**range:** 0..4294967295

                .. attribute:: ingress_client_port

                	IngressClientPort
                	**type**\: str

                	**length:** 0..128

                .. attribute:: ingress_physical_channel

                	IngressPhysicalChannel
                	**type**\: int

                	**range:** 0..4294967295

                .. attribute:: tti_transmit

                	TtiTransmit
                	**type**\: str

                	**length:** 0..256

                .. attribute:: tti_expected

                	TtiExpected
                	**type**\: str

                	**length:** 0..256

                """

                _prefix = 'terminal-device-oper'
                _revision = '2015-11-09'

                def __init__(self):
                    super(OpticalInterface.OpticalLogicalInterfaces.OpticalLogicalInterface.OpticalLogicalInterfaceAttr, self).__init__()

                    self.yang_name = "optical-logical-interface-attr"
                    self.yang_parent_name = "optical-logical-interface"
                    self.is_top_level_class = False
                    self.has_list_ancestor = True
                    self.ylist_key_names = []
                    self._child_container_classes = OrderedDict([])
                    self._child_list_classes = OrderedDict([])
                    self._leafs = OrderedDict([
                        ('logical_channel_index', YLeaf(YType.uint32, 'logical-channel-index')),
                        ('logical_channel_ifname', YLeaf(YType.str, 'logical-channel-ifname')),
                        ('type', YLeaf(YType.str, 'type')),
                        ('trib_rate_class', YLeaf(YType.enumeration, 'trib-rate-class')),
                        ('trib_protocol', YLeaf(YType.enumeration, 'trib-protocol')),
                        ('protocol_type', YLeaf(YType.enumeration, 'protocol-type')),
                        ('admin_state', YLeaf(YType.uint32, 'admin-state')),
                        ('loopback_mode', YLeaf(YType.uint32, 'loopback-mode')),
                        ('ingress_client_port', YLeaf(YType.str, 'ingress-client-port')),
                        ('ingress_physical_channel', YLeaf(YType.uint32, 'ingress-physical-channel')),
                        ('tti_transmit', YLeaf(YType.str, 'tti-transmit')),
                        ('tti_expected', YLeaf(YType.str, 'tti-expected')),
                    ])
                    self.logical_channel_index = None
                    self.logical_channel_ifname = None
                    self.type = None
                    self.trib_rate_class = None
                    self.trib_protocol = None
                    self.protocol_type = None
                    self.admin_state = None
                    self.loopback_mode = None
                    self.ingress_client_port = None
                    self.ingress_physical_channel = None
                    self.tti_transmit = None
                    self.tti_expected = None
                    self._segment_path = lambda: "optical-logical-interface-attr"

                def __setattr__(self, name, value):
                    self._perform_setattr(OpticalInterface.OpticalLogicalInterfaces.OpticalLogicalInterface.OpticalLogicalInterfaceAttr, ['logical_channel_index', 'logical_channel_ifname', 'type', 'trib_rate_class', 'trib_protocol', 'protocol_type', 'admin_state', 'loopback_mode', 'ingress_client_port', 'ingress_physical_channel', 'tti_transmit', 'tti_expected'], name, value)

            class OpticalLogicalInterfaceLogicalChannelAssignments(Entity):
                """
                The operational attributes for a particular
                interface

                .. attribute:: optical_logical_interface_logical_channel_assignment

                	The operational attributes for a logical channel assignment
                	**type**\: list of  		 :py:class:`OpticalLogicalInterfaceLogicalChannelAssignment <ydk.models.cisco_ios_xr.Cisco_IOS_XR_terminal_device_oper.OpticalInterface.OpticalLogicalInterfaces.OpticalLogicalInterface.OpticalLogicalInterfaceLogicalChannelAssignments.OpticalLogicalInterfaceLogicalChannelAssignment>`

                """

                _prefix = 'terminal-device-oper'
                _revision = '2015-11-09'

                def __init__(self):
                    super(OpticalInterface.OpticalLogicalInterfaces.OpticalLogicalInterface.OpticalLogicalInterfaceLogicalChannelAssignments, self).__init__()

                    self.yang_name = "optical-logical-interface-logical-channel-assignments"
                    self.yang_parent_name = "optical-logical-interface"
                    self.is_top_level_class = False
                    self.has_list_ancestor = True
                    self.ylist_key_names = []
                    self._child_container_classes = OrderedDict([])
                    self._child_list_classes = OrderedDict([("optical-logical-interface-logical-channel-assignment", ("optical_logical_interface_logical_channel_assignment", OpticalInterface.OpticalLogicalInterfaces.OpticalLogicalInterface.OpticalLogicalInterfaceLogicalChannelAssignments.OpticalLogicalInterfaceLogicalChannelAssignment))])
                    self._leafs = OrderedDict()

                    self.optical_logical_interface_logical_channel_assignment = YList(self)
                    self._segment_path = lambda: "optical-logical-interface-logical-channel-assignments"

                def __setattr__(self, name, value):
                    self._perform_setattr(OpticalInterface.OpticalLogicalInterfaces.OpticalLogicalInterface.OpticalLogicalInterfaceLogicalChannelAssignments, [], name, value)

                class OpticalLogicalInterfaceLogicalChannelAssignment(Entity):
                    """
                    The operational attributes for a logical
                    channel assignment

                    .. attribute:: index  (key)

                    	The index of the logical\-channel
                    	**type**\: int

                    	**range:** \-2147483648..2147483647

                    .. attribute:: optical_logical_interface_logical_channel_assignment_attr

                    	The operational attributes for a logical channel assignment
                    	**type**\:  :py:class:`OpticalLogicalInterfaceLogicalChannelAssignmentAttr <ydk.models.cisco_ios_xr.Cisco_IOS_XR_terminal_device_oper.OpticalInterface.OpticalLogicalInterfaces.OpticalLogicalInterface.OpticalLogicalInterfaceLogicalChannelAssignments.OpticalLogicalInterfaceLogicalChannelAssignment.OpticalLogicalInterfaceLogicalChannelAssignmentAttr>`

                    """

                    _prefix = 'terminal-device-oper'
                    _revision = '2015-11-09'

                    def __init__(self):
                        super(OpticalInterface.OpticalLogicalInterfaces.OpticalLogicalInterface.OpticalLogicalInterfaceLogicalChannelAssignments.OpticalLogicalInterfaceLogicalChannelAssignment, self).__init__()

                        self.yang_name = "optical-logical-interface-logical-channel-assignment"
                        self.yang_parent_name = "optical-logical-interface-logical-channel-assignments"
                        self.is_top_level_class = False
                        self.has_list_ancestor = True
                        self.ylist_key_names = ['index']
                        self._child_container_classes = OrderedDict([("optical-logical-interface-logical-channel-assignment-attr", ("optical_logical_interface_logical_channel_assignment_attr", OpticalInterface.OpticalLogicalInterfaces.OpticalLogicalInterface.OpticalLogicalInterfaceLogicalChannelAssignments.OpticalLogicalInterfaceLogicalChannelAssignment.OpticalLogicalInterfaceLogicalChannelAssignmentAttr))])
                        self._child_list_classes = OrderedDict([])
                        self._leafs = OrderedDict([
                            ('index', YLeaf(YType.int32, 'index')),
                        ])
                        self.index = None

                        self.optical_logical_interface_logical_channel_assignment_attr = OpticalInterface.OpticalLogicalInterfaces.OpticalLogicalInterface.OpticalLogicalInterfaceLogicalChannelAssignments.OpticalLogicalInterfaceLogicalChannelAssignment.OpticalLogicalInterfaceLogicalChannelAssignmentAttr()
                        self.optical_logical_interface_logical_channel_assignment_attr.parent = self
                        self._children_name_map["optical_logical_interface_logical_channel_assignment_attr"] = "optical-logical-interface-logical-channel-assignment-attr"
                        self._children_yang_names.add("optical-logical-interface-logical-channel-assignment-attr")
                        self._segment_path = lambda: "optical-logical-interface-logical-channel-assignment" + "[index='" + str(self.index) + "']"

                    def __setattr__(self, name, value):
                        self._perform_setattr(OpticalInterface.OpticalLogicalInterfaces.OpticalLogicalInterface.OpticalLogicalInterfaceLogicalChannelAssignments.OpticalLogicalInterfaceLogicalChannelAssignment, ['index'], name, value)

                    class OpticalLogicalInterfaceLogicalChannelAssignmentAttr(Entity):
                        """
                        The operational attributes for a logical
                        channel assignment

                        .. attribute:: index

                        	Index
                        	**type**\: int

                        	**range:** 0..4294967295

                        .. attribute:: name

                        	Name
                        	**type**\: str

                        	**length:** 0..128

                        .. attribute:: is_logical_link

                        	IsLogicalLink
                        	**type**\: bool

                        .. attribute:: logical_channel

                        	LogicalChannel
                        	**type**\: int

                        	**range:** 0..4294967295

                        .. attribute:: optical_channel

                        	OpticalChannel
                        	**type**\: str

                        	**length:** 0..128

                        .. attribute:: allocation

                        	Allocation
                        	**type**\: int

                        	**range:** 0..4294967295

                        .. attribute:: assignment_type

                        	AssignmentType
                        	**type**\: int

                        	**range:** 0..4294967295

                        """

                        _prefix = 'terminal-device-oper'
                        _revision = '2015-11-09'

                        def __init__(self):
                            super(OpticalInterface.OpticalLogicalInterfaces.OpticalLogicalInterface.OpticalLogicalInterfaceLogicalChannelAssignments.OpticalLogicalInterfaceLogicalChannelAssignment.OpticalLogicalInterfaceLogicalChannelAssignmentAttr, self).__init__()

                            self.yang_name = "optical-logical-interface-logical-channel-assignment-attr"
                            self.yang_parent_name = "optical-logical-interface-logical-channel-assignment"
                            self.is_top_level_class = False
                            self.has_list_ancestor = True
                            self.ylist_key_names = []
                            self._child_container_classes = OrderedDict([])
                            self._child_list_classes = OrderedDict([])
                            self._leafs = OrderedDict([
                                ('index', YLeaf(YType.uint32, 'index')),
                                ('name', YLeaf(YType.str, 'name')),
                                ('is_logical_link', YLeaf(YType.boolean, 'is-logical-link')),
                                ('logical_channel', YLeaf(YType.uint32, 'logical-channel')),
                                ('optical_channel', YLeaf(YType.str, 'optical-channel')),
                                ('allocation', YLeaf(YType.uint32, 'allocation')),
                                ('assignment_type', YLeaf(YType.uint32, 'assignment-type')),
                            ])
                            self.index = None
                            self.name = None
                            self.is_logical_link = None
                            self.logical_channel = None
                            self.optical_channel = None
                            self.allocation = None
                            self.assignment_type = None
                            self._segment_path = lambda: "optical-logical-interface-logical-channel-assignment-attr"

                        def __setattr__(self, name, value):
                            self._perform_setattr(OpticalInterface.OpticalLogicalInterfaces.OpticalLogicalInterface.OpticalLogicalInterfaceLogicalChannelAssignments.OpticalLogicalInterfaceLogicalChannelAssignment.OpticalLogicalInterfaceLogicalChannelAssignmentAttr, ['index', 'name', 'is_logical_link', 'logical_channel', 'optical_channel', 'allocation', 'assignment_type'], name, value)

    def clone_ptr(self):
        self._top_entity = OpticalInterface()
        return self._top_entity


"""
Name: Ardi Artani
Email: ARDI.ARTANI96@myhunter.cuny.edu
Resources: n/a
"""
from sklearn.datasets import load_sample_image
from sklearn.cluster import MiniBatchKMeans

# This function has three inputs and returns an np-array containing the recolored image:
# img: an np-array containing an image, from sklearn.datasets.load_sample_image()sor plt.imread().
# n_clusters: the number of clusters used for MiniBatchKMeans. The default value is 4.
# random_state: the random seed used for the MiniBatchKMeans. The default value is 5.
# The function returns a recolored image, where each pixel is assigned the value of its cluster..

def coloring(img, n_clusters=4, random_state=5):
    new_img_ = (img/255)
    new_img_ = new_img_.reshape(img.shape[0] * img.shape[1], 3)
    kmeans = MiniBatchKMeans(n_clusters=n_clusters,
                             random_state=random_state).fit(new_img_)
    new_color_ = kmeans.cluster_centers_[kmeans.predict(new_img_)]
    return (new_color_.reshape(img.shape))


from django.core.management.base import BaseCommand, CommandError
from Water_QC import models

import os

import arcview
import arcpy

def push_changes():
    folder_object = get_gdb()
    if folder_object is not None:
        update_geodatabase(folder_object)

def update_geodatabase(folder_object):
    folder_object = folder_object #type: models.MonthFolder
    for geodatabase in folder_object.geodatabase_set.all():
        update_feature_class(geodatabase, folder_object.folder_path)

def update_feature_class(geodatabase_object, folder_path):
    geodatabase_object = geodatabase_object # type: models.Geodatabase
    gdb_path = os.path.join(folder_path, geodatabase_object.geodatabase_name)
    for feature_class in geodatabase_object.featureclass_set.all():
        update_feature(feature_class, gdb_path)

def update_feature(feature_class_object, geodatabase_path):
    feature_class_object = feature_class_object #type: models.FeatureClass

    feature_str = "QC_Region{}_ToBe{}".format(
        feature_class_object.feature_type.feature_name,
        feature_class_object.change_type.change_type,
    )
    feature_path = os.path.join(geodatabase_path, feature_str)

    features = {}

    for feature in feature_class_object.feature_set.all():
        features[feature.rmwid] = [feature.qc_approved, feature.qc_comments]

    if features == {}:
        return

    update_feature_arc(
        feature_path,
        feature_class_object.change_type.change_type,
        features
    )

def update_feature_arc(feature_path, change_type, data):
    if change_type == "Added":
        fields = ["AreaMunicipal_ID", "QC_Approved", "QC_Comments"]
        sql_data = ",".join([id for id in data])
    else:
        fields = ["RMWID", "QC_Approved", "QC_Comments"]
        sql_data = ",".join(["'{}'".format(id) for id in data])

    sql = "\"{}\" IN ({})".format(fields[0], sql_data)

    print("Updating {}".format(feature_path))
    with arcpy.da.UpdateCursor(feature_path, fields, sql) as sc:
        for row in sc:
            id = u'{}'.format(row[0])
            qc_approved, qc_comment = data.get(id, [None, None])
            if qc_approved is True:
                qc_approved = "Yes"
            elif qc_approved is False:
                qc_approved = "No"

            row[1] = qc_approved
            row[2] = qc_comment
            sc.updateRow(row)

def get_gdb():
    objects = models.MonthFolder.objects.filter(completed=False).all()
    list_items = [[item.id, item.folder_name] for item in objects]

    print("Enter ID from list or 'q' to quit")
    for item in list_items:
        print("ID: {}\tFolder: {}".format(item[0], item[1]))

    if len(list_items) == 0:
        print("No items")
        return None

    while True:
        id_val = raw_input()
        if id_val == "q":
            return None
        try:
            id_int = int(id_val)
            folder = models.MonthFolder.objects.get(id=id_int)
            return folder
        except:
            print("Not a correct id, choose correct value or enter 'q'")
            pass

class Command(BaseCommand):
    help = "Sync the GDB and the sqlite dbs together"

    def handle(self, *args, **options):
        push_changes()


from keras.preprocessing.image import img_to_array, load_img
from keras.models import load_model
import numpy as np

model = load_model('./model.h5')

paths = ['bocian.jpg', 'kot.jpg', 'pies.jpg']

for path in paths:
    image = load_img(path, target_size=(224, 224))
    image = img_to_array(image)
    image = image / 255
    image = np.expand_dims(image, axis=0)

    result = model.predict(image)
    print(result)  # 1 - ptak, 2 - kot, 3 - pies


from pathlib import Path
from time import time
from os import path as opath, remove as oremove, rename as orename
from subprocess import check_output
from asyncio import sleep as asleep
from requests import get as rget
from config import LOGGER, Config
from bot.client import Client
from bot.core.db.db_func import db
from bot.core.display import convertBytes
from bot.core.progress import progress_for_pyrogram
from pyrogram import filters, enums
from pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton

@Client.on_message((filters.video | filters.audio | filters.document) & filters.private)
async def upload_file_handler(c: Client, m: Message):
    ''' Upload Telegram Files Directly to the UploadEver Server upto 4GB (TG Limit)

    :param media: Telegram File you want to Upload to UploadEver Server.
    :param token: Your Own API token of UploadEver.in
    :param sess_id: Session ID for Remote Upload
    :param server_url: The Server which will take the Request to Upload the Media

    OUTPUT: (Step 1)
    {
      "status": 200,
      "sess_id": "3rexxxxxxxxxx9",
      "result": "http://s1.fileserverdomain.com/cgi-bin/upload.cgi",
      "msg": "OK",
      "server_time": "2021-10-22 05:13:21"
    }
    OUTPUT: (Step 2)
    [
      {
        "file_code": "bxxxxxxxka",
        "file_status": "OK"
      }
    ]
    '''

    Token = await db._getUserToken(m.chat.id)
    if Token is None:
        await m.reply_text("😬 I see, you have not Login, Do /login to Use this Command. ",  quote=True, parse_mode=enums.ParseMode.HTML)
        return

    downMSG = await m.reply_text("🔍 Finding a UploadEver Server to Start Uploading ...", quote=True, parse_mode=enums.ParseMode.HTML)
    resp = rget(f"https://uploadever.in/api/upload/server?key={Token}")
    jdata = resp.json()
    if jdata['status'] == 200:
        SESS_ID = jdata['sess_id']
        UP_SER_URL = jdata['result']
    else:
        await m.reply_text(jdata['msg'])
        return
    await asleep(1.5)

    await downMSG.edit(f"🔍 Found a UploadEver Server for Taking Requests !!\n\n 📤 Starting Media Download...", parse_mode=enums.ParseMode.HTML)
    media = [m.document, m.video, m.audio]
    file = [md for md in media if md is not None][0]
    file_name = file.file_name
    mime_type = file.mime_type
    file_size = file.file_size
    __fileName = f"{Path('./').resolve()}/{Config.DIRECTORY}"
    try:
        __time = time()
        __downLocation = await c.download_media(message=m,
            file_name=__fileName,
            progress=progress_for_pyrogram,
            progress_args=(f"🚄 Fɪʟᴇɴᴀᴍᴇ: {file_name}",
                downMSG,
                __time
            )
        )
    except Exception as err:
        await downMSG.edit(f"⛔ Download Error : {err}")
        LOGGER.error(err)
        return
    LOGGER.info(f"[TG Upload] User: {m.chat.id} File Location: {__downLocation}")

    _newFileName = __downLocation
    try:
        await downMSG.edit(f"🔍 Found a UploadEver Server for Taking Requests !!\n\n  📤 Media Downloaded...\n\n ✏Now Send Me Newfile Name (Optional) (30 sec Timeout)", parse_mode=enums.ParseMode.HTML)
        input_msg: Message = await c.listen(chat_id=m.chat.id, filters=filters.text, timeout=30)
        newname = input_msg.text
        if newname is not None:
            _newFileName = f"{Path('./').resolve()}/{Config.DIRECTORY}/{newname}"
            orename(__downLocation, _newFileName)
        await input_msg.delete()
    except Exception:
        pass

    await downMSG.edit(f"🔍 Found a UploadEver Server for Taking Requests !!\n\n 📤 Media Downloaded, Uploading...", parse_mode=enums.ParseMode.HTML)

    UpData = check_output(f"curl -F 'sess_id={SESS_ID}' -F 'file_0=@{_newFileName}' {UP_SER_URL}", shell=True).decode('utf-8')
    await downMSG.delete()
    filecode = UpData.strip(']}{[').replace(":", ",").replace('"', '').split(',')
    URL = f"https://uploadever.in/{filecode[1]}"
    await m.reply_text(text=f'''📈 Upload Completed 📉

📨 FileName : {opath.basename(_newFileName)}

📋 Type : {mime_type}
📦 Size : {convertBytes(file_size)}

🔗 URL : {URL}
''',
        quote=True,
        parse_mode=enums.ParseMode.HTML,
        reply_markup=InlineKeyboardMarkup([
            [InlineKeyboardButton("📎 UploadEver URL", url=URL)]
        ])
    )
    oremove(_newFileName)


import folium

from django.http import HttpResponseNotFound
from django.shortcuts import render
from pokemon_entities.models import Pokemon

MOSCOW_CENTER = [55.751244, 37.618423]
DEFAULT_IMAGE_URL = "https://vignette.wikia.nocookie.net/pokemon/images/6/6e/%21.png/revision/latest/fixed-aspect-ratio-down/width/240/height/240?cb=20130525215832&fill=transparent"

def add_pokemon(folium_map, lat, lon, image_url=DEFAULT_IMAGE_URL):
    icon = folium.features.CustomIcon(
        image_url,
        icon_size=(50, 50),
    )
    folium.Marker(
        [lat, lon],
        icon=icon,
    ).add_to(folium_map)

def show_all_pokemons(request):
    pokemons = Pokemon.objects.all()

    folium_map = folium.Map(location=MOSCOW_CENTER, zoom_start=12)
    for pokemon in pokemons:
        for pokemon_entity in pokemon.entities.all():
            add_pokemon(
                folium_map,
                pokemon_entity.lat,
                pokemon_entity.lon,
                request.build_absolute_uri(pokemon.image.url))

    pokemons_on_page = []
    for pokemon in pokemons:
        pokemons_on_page.append({
            'pokemon_id': pokemon.id,
            'img_url': request.build_absolute_uri(pokemon.image.url),
            'title_ru': pokemon.title,
        })

    return render(request, "mainpage.html", context={
        'map': folium_map._repr_html_(),
        'pokemons': pokemons_on_page,
    })

def show_pokemon(request, pokemon_id):
    try:
        requested_pokemon = Pokemon.objects.get(id=pokemon_id)
    except Pokemon.DoesNotExist:
        return HttpResponseNotFound('
Такой покемон не найден
')

    pokemons_entities = requested_pokemon.entities.all()

    folium_map = folium.Map(location=MOSCOW_CENTER, zoom_start=12)
    for pokemon_entity in pokemons_entities:
        add_pokemon(
            folium_map,
            pokemon_entity.lat,
            pokemon_entity.lon,
            request.build_absolute_uri(requested_pokemon.image.url)
        )

    pokemon = {
        "pokemon_id": requested_pokemon.id,
        "title_ru": requested_pokemon.title,
        "title_en": requested_pokemon.title_en,
        "title_jp": requested_pokemon.title_jp,
        "description": requested_pokemon.description,
        "img_url": request.build_absolute_uri(requested_pokemon.image.url),
    }

    pokemons_elements = []
    for element in requested_pokemon.element_type.all():
        pokemons_elements.append({
            'title': element.title,
            'img': request.build_absolute_uri(element.image.url),
            'strong_against': element.strong_against.all(),
        })

    pokemon['element_type'] = pokemons_elements

    try:
        pokemon["previous_evolution"] = {
            "title_ru": requested_pokemon.previous_evolution.title,
            "pokemon_id": requested_pokemon.previous_evolution.id,
            "img_url": requested_pokemon.previous_evolution.image.url
        }
    except AttributeError:
        pass

    for next_evolution in requested_pokemon.next_evolutions.all():
        pokemon["next_evolution"] = {
            "title_ru": next_evolution.title,
            "pokemon_id": next_evolution.id,
            "img_url": next_evolution.image.url
        }

    return render(request, "pokemon.html",
                  context={'map': folium_map._repr_html_(),
                           'pokemon': pokemon})


import itertools

# calculate all "unique" combinations
def calculate_combinations(combinations, N, Sum):
    lucky_tickets = []
    for combination in combinations:
        first_half = combination[:N]
        second_half = combination[N:]
        first_sum = 0
        second_sum = 0

        for char1 in first_half:
            first_sum += int(char1)

        for char2 in second_half:
            second_sum += int(char2)

        if first_sum == second_sum == Sum/2:
            lucky_tickets.append(combination)

    return lucky_tickets

# generate all possible N digit combinations
def generate_list(dimensions):
    combinations = []
    for i in itertools.product(range(10), repeat=dimensions):
        number = ''.join(map(str, i))
        combinations.append(number)
    return combinations

def main():
    inputs = input("Enter input string:").split()

    # ensure valid input
    if len(inputs) >= 2:
        if inputs[0].isdigit() and inputs[1].isdigit():

            N = int(inputs[0])
            Sum = int(inputs[1])
            if 1 <= N <= 50 and 1 <= Sum <+ 1000:
                lis = generate_list(2*N)
                lucky_combinations = calculate_combinations(lis, N, Sum)
                # print(lucky_combinations)
                print(len(lucky_combinations))

            else:
                print("wrong input string")
        else:
            print("wrong input string")

    else:
        print("wrong input string")

if __name__ == "__main__":
    main()


import sqlite3
from hashlib import sha256
import os
import time

def _get_conn(config):
    conn = sqlite3.connect(config['db_host'])
    conn.row_factory = sqlite3.Row
    return conn

def add_document(file_path, config):
    m = sha256()
    with open(file_path, 'rb') as fi:
        doc_text = fi.read()
        m.update(doc_text)

    doc_hash = m.digest().hex()
    doc_name = os.path.split(file_path)[1]

    conn = _get_conn(config)

    try:
        conn.execute('''insert into raw_documents(doc_hash, doc_name, doc_body, update_epoch_time)
                    values (?, ?, ?, ?); ''', ((doc_hash, doc_name, doc_text, int(time.time()))))
    except sqlite3.IntegrityError as e:
        if 'UNIQUE' in e.args[0]:
            pass
        else:
            print(e)
            raise e
            conn.close()

    conn.commit()

    conn.close()

def list_docs(config):
    conn = _get_conn(config)
    curs = conn.cursor()

    curs.execute('''
    Select doc_name, doc_hash, update_epoch_time from raw_documents;
    ''')

    data = curs.fetchall()
    conn.close()
    return data

def get_doc(config, doc_id):
    conn = _get_conn(config)
    curs = conn.cursor()

    curs.execute('''
    Select * from raw_documents where doc_hash = (?);
    ''', (doc_id,))

    data = curs.fetchone()
    conn.close()
    return data

def init(config):
    conn = _get_conn(config)
    curs = conn.cursor()

    curs.execute('''Create table if not exists raw_documents
    (doc_hash text primary key, doc_name text, doc_body text, update_epoch_time int);''')
    curs.execute('''Create table if not exists words (doc_hash text, word text, count int,
                 Foreign Key (doc_hash) references raw_doucments(doc_hash),
                 Constraint words_pk unique (doc_hash, word));''')
    #curs.execute('Create unique index words_pk on words(doc_hash, word);')

    conn.commit()
    conn.close()


from django.shortcuts import render, redirect
from .models import Task
from .forms import TaskForm

def index(request):
    tasks = Task.objects.order_by('id')
    return render(request, 'main/index.html', {'title': 'Николаев Даниил',
                                               'tasks': tasks})

def about(request):
    return render(request, 'main/about.html', {'title': 'Обо мне'})

def create(request):
    error = ''
    if request.method == 'POST':
        form = TaskForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('home')
        else:
            error = 'Форма не верна'

    form = TaskForm()
    context = {
        'form': form,
        'error': error
    }
    return render(request, 'main/create.html', context)


import sys
import argparse
import functools

import tensorflow as tf
import tensorflow_transform as tft

from trainer import input_util
from trainer import metadata
from trainer import model

def parse_arguments(argv):
    """Parse command-line arguments."""

    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--verbosity',
        help='Set logging level.',
        choices=['DEBUG', 'ERROR', 'FATAL', 'INFO', 'WARN'],
        default='INFO',
    )
    parser.add_argument(
        '--train-batch-size',
        help='Batch size for each training step.',
        type=int,
        default=120,
    )
    parser.add_argument(
        '--eval-batch-size',
        help='Batch size for evaluation steps.',
        type=int,
        default=1000,
    )
    parser.add_argument(
        '--eval-start-secs',
        help='How long to wait before starting first evaluation.',
        default=20,
        type=int,
    )
    parser.add_argument(
        '--eval-steps',
        help="""Number of steps to run evaluation for at each checkpoint',
        Set to None to evaluate on the whole evaluation data.
        """,
        default=None,
        type=int,
    )
    parser.add_argument(
        '--num-epochs',
        help="""Maximum number of training data epochs.
        If both --train-size and --num-epochs are specified, --train-steps will
        be: (train-size/train-batch-size) * num-epochs.""",
        default=None,
        type=int,
    )
    parser.add_argument(
        '--job-dir',
        help='GCS location to write checkpoints and export models.',
        required=True,
    )
    parser.add_argument(
        '--input-dir',
        help='GCS or local directory to TFRecord and metadata files.',
        required=True,
    )
    parser.add_argument(
        '--train-steps',
        help="""Steps to run the training job for.
        If --num-epochs and --train-size are specified, then --train-steps will
        be: (train-size/train-batch-size) * num-epochs.""",
        default=10000,
        type=int,
    )
    parser.add_argument(
        '--train-size',
        help='Size of training set (instance count).',
        type=int,
        default=None,
    )
    parser.add_argument(
        '--hidden-units',
        help='Hidden units, default is [10, 10].',
        default=[10, 10],
    )
    parser.add_argument(
        '--first-layer-size',
        help='Number of hidden units in first layer.',
        type=int,
        default=35,
    )
    parser.add_argument(
        '--num-layers',
        help='Number of layers.',
        type=int,
        default=2,
    )
    parser.add_argument(
        '--layer-sizes-scale-factor',
        help="""Determine how the size of the layers in the DNN decays.
        If value = 0 then the provided --hidden-units will be taken as is.""",
        default=0.78535296735911486,
        type=float,
    )
    parser.add_argument(
        '--learning-rate',
        help='Learning rate',
        default=0.021388123321319803,
        type=float,
    )
    parser.add_argument(
        '--threshold',
        help='Confidence Score threshold to resolve class predictions.',
        default=0.34157646920229945,
        type=float,
    )
    parser.add_argument(
        '--checkpoint_steps',
        help='Number of steps between each checkpoint.',
        default=1000,
        type=int,
    )
    return parser.parse_args(argv)

def train_and_evaluate(flags):
    """Runs model training and evaluation using TF Estimator API."""

    # Get TF transform metadata generated during preprocessing
    tf_transform_output = tft.TFTransformOutput(flags.input_dir)

    feature_spec = tf_transform_output.transformed_feature_spec()
    train_input_fn = functools.partial(
        input_util.input_fn,
        input_dir=flags.input_dir,
        mode=tf.estimator.ModeKeys.TRAIN,
        batch_size=flags.train_batch_size,
        num_epochs=flags.num_epochs,
        label_name=metadata.LABEL_COLUMN,
        feature_spec=feature_spec
    )
    train_spec = tf.estimator.TrainSpec(
        train_input_fn, max_steps=flags.train_steps)

    eval_input_fn = functools.partial(
        input_util.input_fn,
        input_dir=flags.input_dir,
        mode=tf.estimator.ModeKeys.EVAL,
        batch_size=flags.eval_batch_size,
        num_epochs=1,
        label_name=metadata.LABEL_COLUMN,
        feature_spec=feature_spec
    )

    exporter = tf.estimator.FinalExporter(
        'export', functools.partial(
            input_util.tfrecord_serving_input_fn,
            feature_spec=feature_spec,
            label_name=metadata.LABEL_COLUMN))

    eval_spec = tf.estimator.EvalSpec(
        eval_input_fn,
        steps=flags.eval_steps,
        start_delay_secs=flags.eval_start_secs,
        exporters=[exporter],
        name='churn-eval'
    )

    run_config = tf.estimator.RunConfig(
        save_checkpoints_steps=flags.checkpoint_steps,
        tf_random_seed=metadata.SEED,
        model_dir=flags.job_dir
    )

    feature_columns = model.get_feature_columns(
        tf_transform_output, exclude_columns=metadata.NON_FEATURE_COLUMNS)
    num_intervals = metadata.NUM_INTERVALS
    estimator = model.build_estimator(
        run_config, flags, feature_columns, num_intervals)

    tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)

def main():
    flags = parse_arguments(sys.argv[1:])
    tf.logging.set_verbosity(flags.verbosity)
    train_and_evaluate(flags)

if __name__ == '__main__':
    main()


# https://leetcode.com/problems/partition-labels/

from typing import List

class Solution:
    def partitionLabels(self, s: str) -> List[int]:
        end_indexes = {}
        i = 0
        while i < len(s):
            end_indexes[s[i]] = i
            i += 1

        partitions = []
        i = 0
        while i < len(s):
            if end_indexes[s[i]] is None:
                partitions.append(1)
            else:
                start_index = i
                end_index = end_indexes[s[i]]
                while i < end_index:
                    if end_indexes[s[i]] is not None and end_indexes[s[i]] > end_index:
                        end_index = end_indexes[s[i]]
                    i += 1
                partitions.append((end_index - start_index) + 1)
            i += 1
        return partitions

print(Solution().partitionLabels('ababcbacadefegdehijhklij'))
print(Solution().partitionLabels('eccbbbbdec'))


import warnings
warnings.filterwarnings("ignore")

from pymoo.core.problem import ElementwiseProblem

from pymoo.algorithms.moo.nsga2 import NSGA2
from pymoo.operators.crossover.sbx import SBX
from pymoo.operators.mutation.pm import PM
from pymoo.operators.sampling.rnd import FloatRandomSampling

from pymoo.core.problem import StarmapParallelization

from pymoo.termination import get_termination

from pymoo.optimize import minimize

from pymoo.algorithms.soo.nonconvex.de import DE
from pymoo.algorithms.soo.nonconvex.ga import GA
from pymoo.algorithms.soo.nonconvex.cmaes import CMAES
from pymoo.algorithms.soo.nonconvex.pso import PSO
from pymoo.operators.sampling.lhs import LHS

from pymoo.core.population import Population
from pymoo.core.evaluator import Evaluator

import numpy as np
from copy import deepcopy
from datetime import date, datetime
import pandas as pd
import json
from multiprocessing.pool import ThreadPool

from trading.testers.rules_testing import rule_validation
from trading import Asset
from trading.func_brokers import get_assets
from trading.func_aux import timing

np.random.seed(1)

def sell_column(asset, target ):
    asset.df["sell"] = False
    true_values = asset.df[ asset.df["buy"] == True ].index.tolist()
    close = asset.df["close"]

    for i in true_values:
        close_price = close[i] # bought price
        close_aux = close[ i: ]
        close_aux = ( close_aux / close_price ) - 1
        pct_index = close_aux[ close_aux >= target ]

        if len(pct_index) == 0:
            # Este mensaje no importa por el momento, solo nos indica que como no hay mejor, yo no
            # nos moveremos a los siguientes puesto
            # que al no cerrarse esta orden, no podemos abrir ni cerrar las demas.
            # raise Exception( "Testing did not prove a better return." )
            break

        pct_index = pct_index.index[0]

        try:
            asset.df.loc[ pct_index, "sell" ] = True
        except Exception as e:
            raise Exception( f"{e}. Got {type(pct_index)} from {pct_index}." )

    return asset

class TATunning(ElementwiseProblem):

    def __init__(self, assets, **kwargs):
        self.assets = assets
        super().__init__(n_var=kwargs["n_var"],
                         n_obj=1,
                         n_ieq_constr=0,
                         xl=kwargs["xl"], # np.array([7,3, 40]),
                         xu=kwargs["xu"], #np.array([21,14, 90])
        )

    def my_obj_func(self, asset, x):
        """
            Rule selection:
                1:
        """
        asset = deepcopy(asset)

        cols_to_use = []

        if (x[2] >= x[4]) or ( x[10] >= x[11] ):
            return np.inf

        if x[0]:
            cols_to_use.append("rsi")
            asset.df["rsi1"] = asset.rsi_smoth(x[1], x[2])
            asset.df["rsi2"] = asset.rsi_smoth(x[3], x[4])
            asset.df["rsi"] = (asset.df["rsi1"] > asset.df["rsi2"]).astype(int).diff().rolling(2).sum() > 0

            if x[16]:
                cols_to_use.append("rsi2")
                asset.df["rsi2"] = asset.df["rsi2"] < x[17]

        if x[5]:
            cols_to_use.append("rsi_slope")
            asset.df["rsi_slope"] = asset.rsi_smoth_slope(x[6], x[7], x[8]) > 0

        if x[9]:
            cols_to_use.append("ema")
            asset.df["ema1"] = asset.ema(x[10])
            asset.df["ema2"] = asset.ema(x[11])
            asset.df["ema"] = (asset.df["ema1"] > asset.df["ema2"]).astype(int).diff().rolling(2).sum() > 0

        if x[12]:
            cols_to_use.append("rsi_thr")
            asset.df["rsi_thr"] = (asset.rsi( x[13] ) > x[14]).rolling(x[15]).sum() == 0

        if x[21]:
            cols_to_use.append("buy_wf")
            asset.df["buy_wf"] = asset.william_fractals(3, shift=True)

        # if x[14]:
        #     cols_to_use.append("sell_wf")
        #     asset.df["sell_wf"] = asset.william_fractals(3, shift=True, order = "sell").rolling(3).sum() == 0

        # if x[15]:
        #     cols_to_use.append("rsi")
        #     asset.df["rsi"] = asset.rsi_smoth(x[0], x[1]) < x[2]

        if x[18]:
            cols_to_use.append("ema_slope")
            asset.df["ema_slope"] = asset.ema_slope( x[19], x[20] ) > 0

        # if x[17]:
        #     cols_to_use.append("rsi_slope")
        #     asset.df["rsi_slope"] = asset.rsi_smoth_slope( x[6], x[7], x[8] ) > x[9]

        # if x[18]:
        #     cols_to_use.append("oneside_gaussian_filter_slope")
        #     asset.df["oneside_gaussian_filter_slope"] = asset.oneside_gaussian_filter_slope(x[10],x[11]) > x[12]

        # if x[19]:
        #     cols_to_use.append("engulfing_buy")
        #     asset.df["engulfing_buy"] = asset.engulfing() == 1

        # if x[20]:
        #     cols_to_use.append("engulfing_sell")
        #     asset.df["engulfing_sell"] = asset.engulfing() != -1

        # if x[21]:
        #     cols_to_use.append("dema_sma")
        #     asset.df["dema_sma"] = asset.dema( x[22] ) > asset.sma( x[23] )

        if len(cols_to_use) == 0:
            return np.inf

        df = asset.df[ cols_to_use ]

        asset.df[ "buy" ] = df.all(axis = 1)

        # Clean buy columns
        # Get only the first buy column that pops out
        asset.df["extra_buy"] = asset.df["buy"] != asset.df["buy"].shift(1)
        asset.df["buy"] = asset.df["buy"] & asset.df["extra_buy"]

        asset = sell_column(asset, target = 0.0015)

        df = rule_validation(asset)

        if len(df) > 0:
            acc = df["acc"].iloc[-1]
            if acc == 0:
                acc = np.inf
            else:
                acc = 1 / acc
        else:
            acc = np.inf

        # print(acc)
        return acc

    def _evaluate(self, x, out, *args, **kwargs):

        def rounding(i, x):
            return round(x)
            # if i not in [5, 9, 12]:
            #     return round(x)
            # else:
            #     return x

        x = [ rounding(i, xx) for i, xx in enumerate(x) ]

        f = [ self.my_obj_func( asset, x ) for asset in self.assets ]
        out["F"] = [ np.median( f )]

def prep_asset( symbl ):
    asset = Asset(
        symbl,
        start = date(2023,1,21),
        end = date(2023,1,26),
        frequency="3min",
        fiat = "USDT",
        broker = "binance",
        source = "db"
    )

    return asset

@timing
def main(symbols, algorithm_name):

    print(f"------ {algorithm_name} ------")

    gen = 200

    assets = [ prep_asset(i) for i in symbols ]

    # initialize the thread pool and create the runner
    n_threads = 5
    pool = ThreadPool(n_threads)
    runner = StarmapParallelization(pool.starmap)

    problem = TATunning(
        assets = assets,
        n_var = 22,# 24,
        xl = [0, 5, 2, 5, 5, 0, 5, 2, 2, 0, 6, 6, 0, 5, 60, 6, 0, 40, 0, 7, 2, 0],# [ 5,3, 35, 10, 2, -1, 7, 3, 2, -1,2 ,2 , -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10],
        xu = [1, 22, 8, 22, 22, 1, 22, 22, 4, 1, 30, 30, 1, 7, 75, 20, 1, 60, 1, 50, 7, 1],# [ 28, 14, 90 ,120, 5, 1, 28, 14, 5, 1, 5, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 100, 100]
        elementwise_evaluation=True,
        elementwise_runner=runner,
    )

    # Iteration obtained with 100 gens
    X = [0.7272260286390523, 18.00387003160997, 2.1002420079879416, 6.665148402373074, 5.250123872371164, 0.3389001855261586, 6.7582607608022505, 20.307771982806567, 2.134609588376494, 0.0011687823761985868, 18.063884172688574, 28.598043151276272, 0.3928198128907693, 5.505033731932276, 61.34314180656084, 6.113085474847783, 0.9754976040022505, 56.67614988094437, 0.09864090725804009, 20.15538774485999, 4.016661131295658, 0.014239166217713749]

    pop = Population(22)
    pop.set("X", X)
    Evaluator().eval(problem, pop)

    if algorithm_name == "DE":
        algorithm = DE(
            pop_size=80,
            sampling=pop, # LHS(),
            variant="DE/best/2/bin",
            CR=0.2,
            dither="vector",
            jitter=False
        )

    elif algorithm_name == "NSGA2":
        algorithm = NSGA2(
            pop_size=100,
            n_offsprings=10,
            sampling=FloatRandomSampling(),
            crossover=SBX(prob=0.9, eta=15),
            mutation=PM(eta=20),
            eliminate_duplicates=True
        )

    elif algorithm_name == "GA":
        algorithm = GA(
            pop_size=100,
            eliminate_duplicates=True
        )

    elif algorithm_name == "CMAES":
        algorithm = CMAES(x0=np.random.random(problem.n_var))

    elif algorithm_name == "PSO":
        algorithm = PSO()

    termination = get_termination("n_gen", gen)

    res = minimize(problem,
               algorithm,
               termination,
               seed=1,
               save_history=True,
               verbose=True)

    X = res.X
    F = res.F

    def extract(x):
        x = x[0]
        if isinstance( x, float ):
            return x

        return extract( x )

    best_acc = extract( F )

    print("This is acc ", 1/best_acc)

    X = X.tolist()

    if isinstance( X[0], list ):
        print(X[0])

    else:
        print(X)

    data = {
            "acc": 1 / best_acc,
            "param":X
        }

    with open( f"results/metaheuristics/WarmStart_FixBuy_newRSIslope_plus_EMAslope_{algorithm_name}_{gen}.json", "w" ) as fp:
        json.dump( data, fp )

    pool.close()

if __name__ == "__main__":

    symbols = np.random.choice( list(get_assets()["binance"].keys()) , 20 )

    for algorithm in ["DE"]: # Si "DE", "NSGA2", "GA", "PSO"  #No "CMAES",
        main( symbols, algorithm )


import torch
import torch.nn as nn
import torch.nn.functional as NF
import math
from .gru import GRU

class RecurrentRegularizer(nn.Module):
    '''
    View Selector should be taking warped feature and output the pixel-wise
    weights for each each view.

    Input:
        NxHxWxCxPxP

    Output:
        HxW weights for each view
    '''
    def __init__(self, hparams):
        super(RecurrentRegularizer, self).__init__()
        self.hparams = hparams
        # for unary cost
        fo = self.hparams.feat_scorer_output_channel

        # for binary cost
        NC = self.hparams.num_hidden_channels
        P = 1

        NB = self.hparams.num_hidden_states
        modules = []
        if(not self.hparams.skip_pairwise):
            raw_input_channel = fo * 1 + 4
        else:
            raw_input_channel = fo

        if(NB > 0):
            for i in range(NB):
                ks = 3 if i == 0 else 1
                ic = raw_input_channel if i == 0 else NC
                oc = NC if i == 0 else NC
                module = GRU(ic, oc, ks)
                modules.append(module)

            self.grus = nn.ModuleList(modules)
            self.mlp = nn.Conv2d(NC, 1, P, padding=P//2)
        else:
            self.mlp = nn.Conv2d(raw_input_channel, 1, P, padding=P//2)

    def forward(self, cost, belief_maps):
        out = cost
        NB = self.hparams.num_hidden_states
        if(NB > 0):
            outs = []
            for i, gru in enumerate(self.grus):
                out = gru(out, belief_maps[i].unsqueeze(0))
                outs.append(out)

            final_cost = self.mlp(out)
            updated_beliefs = torch.cat(outs)

            return final_cost, updated_beliefs
        else:
            final_cost = self.mlp(out)
            return final_cost, belief_maps


import json
import os.path as op
import pickle
from os import makedirs

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import colors, cm
from matplotlib.gridspec import GridSpec
from scipy.io import loadmat
from scipy.stats import t as tdist

from mtrf_python import STRF_utils
from mtrf_python.scripts.prepare_regression_data_script import get_delay_matrices, get_data_from_df

agg_subject = 'EC36' # 'Hamilton_Agg_LH_9subjects'
strf_config_flag = 'regression_STRF'
config_flag = 'regression_SO1_PR_phnfeats_750msdelays'
col_ctr_RR = True

# Load paths
with open(f"{op.expanduser('~')}/.config/mtrf_config.json", "r") as f:
    config = json.load(f)
subjects_dir = config['subjects_dir']
loadpath = op.join(subjects_dir, agg_subject, config_flag)

blnsave = True

cv_folder = 'cv-10fold-1'

# [Data prep in run_cv_justEC36.py]

#%%
figurepath = op.join(loadpath, 'Figures')
if not op.exists(figurepath) and blnsave:
    makedirs(figurepath)

#%% Load config

# Regression data: fields and validation data
datapath = op.join(loadpath, f'{agg_subject}_RegressionSetup.pkl')
with open(datapath,'rb') as f:
    data = pickle.load(f)

phnstimnames = data['phnstimnames']
sentence_sel = data['sentence_sel']
electrodes = data['electrodes']
electrode_info = data['electrode_info']
delays = data['delays']
time_lags = data['time_lags']
fs = data['fs']

subjects = data['df'].subject.unique()
Nsubjects = len(subjects)

nchans = len(electrodes) # The number of channels (e.g. electrodes, neurons)
ndim = len(phnstimnames)
ndelays = [len(d) for d in delays]

df = data['df']
del data

#%% Load results

cv_summary_path = op.join(loadpath, f'{cv_folder}_cv_summary.pkl')
with open(cv_summary_path, 'rb') as f:
    data = pickle.load(f)
cv_summaries = data['cv_summaries']

nfolds_outer = len(cv_summaries)
nfolds_inner = cv_summaries[0]['nfolds_inner']

validate_field = 'testing_overall_R2'

# Use the first CV fold to pull out specific model fits
cv1_best_irrr = cv_summaries[0]['best_irrr']
cv1_strfs_irrr = cv1_best_irrr['strfs']
cv1_best_ndims_by_feature = cv1_best_irrr['details']['rec_nonzeros'][-1, :].astype(int)

def mean_and_cis(cv):
    m = cv.mean(-1,keepdims=True)
    s = cv.std(-1,keepdims=True)
    n = cv.shape[-1]
    cis = m + tdist.ppf(0.975,n-1)/np.sqrt(n)*s*np.array([[-1,1]])
    return np.squeeze(m),np.squeeze(cis)

#%% Load sentence details

sentdet_df, featurenames, phnnames = STRF_utils.load_sentence_details(op.join(subjects_dir))

freqs = loadmat(op.join(subjects_dir,'mel_centerF.mat'), squeeze_me=True,
                  variable_names=['binfrqs'])['binfrqs']
fa_corners = freqs[:81]
fa = (fa_corners[1:]+fa_corners[:-1])/2

#%% Compute predicted trajectories

# name_sent = 'fbcg1_si1612'
name_sent = 'fcaj0_si1804' # clockwork
soi = 0
pri = 1
nplot = 2
df_sent = df.loc[df.name == name_sent]
befaft = [0,0]

# Audio timeseries
sentence = sentdet_df.loc[np.equal(sentdet_df.name, name_sent)].iterrows().__next__()[1]
source_befaft = sentence.befaft
soundf = sentence.soundf
sound_padleft = ((source_befaft[0] - befaft[0]) * soundf).astype(int)
sound_padright = ((source_befaft[1] - befaft[1]) * soundf).astype(int)
sound = STRF_utils.remove_pad(sentence.sound[None,:], sound_padleft, sound_padright)[0, :]
sound_ta = np.arange(len(sound))/soundf

# Specgram
padleft = ((source_befaft[0] - befaft[0]) * fs).astype(int)
padright = ((source_befaft[1] - befaft[1]) * fs).astype(int)
melspec = STRF_utils.remove_pad(sentence.aud,padleft,padright).transpose([1,0]) # ntimes x nfreqs

# Features
df_sent = df.loc[df.name == name_sent]
txt = df_sent.iloc[0].txt
phnstim, ta, _, resp, _ = \
    get_data_from_df(df_sent,phnstimnames,subjects,
                     padleft,padright,
                     electrodes_sel=electrodes)
ta = ta[:,0]
onset_times = ta[phnstim[:, soi] > 0]
peakRate_times = ta[phnstim[:, pri] > 0]
dstims, _ = get_delay_matrices(phnstim, phnstimnames, time_lags, fs)

#%% Compare penalty terms across models

plt.close('all')
fig1 = plt.figure(figsize=[5,2])
plt.clf()
gs = GridSpec(1,2,wspace=0.4,hspace=0.5,bottom=0.3)

# Explained Variance
R2_irrr_best_cv = np.array([b['best_irrr'][validate_field] for b in cv_summaries])
R2_irrr_best,R2_irrr_best_cis = mean_and_cis(R2_irrr_best_cv)

R2_ols_cv = np.array([b['ols_model'][validate_field] for b in cv_summaries])
R2_ols,R2_ols_cis = mean_and_cis(R2_ols_cv)

R2_ridge_best_cv = np.array([b['best_ridge_model'][validate_field] for b in cv_summaries])
R2_ridge_best,R2_ridge_best_cis = mean_and_cis(R2_ridge_best_cv)

ax0 = fig1.add_subplot(gs[0,0])
ax0.bar(range(3),[R2_ols,R2_ridge_best,R2_irrr_best],color='grey')
plt.vlines(range(3),
           ymin=[R2_ols_cis[0],R2_ridge_best_cis[0],R2_irrr_best_cis[0]],
           ymax=[R2_ols_cis[1],R2_ridge_best_cis[1],R2_irrr_best_cis[1]],
           colors='k',linewidth=1)
ax0.axhline(0,color='k',linewidth=1)
ax0.set_xticks(range(3))
ax0.set_xticklabels(['OLS','Ridge','iRRR'],rotation=45,ha='right')
ax0.set_ylabel('Testing R^2')
ax0.set_title('Explained Variance')

# parameters
ndims_byFeature_cv = np.stack([b['best_irrr']['details']['rec_nonzeros'][-1, :]
                               for b in cv_summaries], axis=-1)
nparams_iRRR_cv = np.array([np.sum([ncomps * (ndel + nchans + 1)
                                    for ncomps, ndel in
                                    zip(ndims_byFeature_iRRR, ndelays)])
                            for ndims_byFeature_iRRR in ndims_byFeature_cv])
nparams_iRRR, nparams_iRRR_ci = mean_and_cis(nparams_iRRR_cv)

nparams_full = sum(ndelays)*nchans

ax0 = fig1.add_subplot(gs[0,1])
ax0.bar(range(3),[nparams_full,
                  nparams_full,
                  nparams_iRRR],color='grey')
ax0.vlines(2,
           ymin=nparams_iRRR_ci[0],
           ymax=nparams_iRRR_ci[1],
           colors='k',linewidth=1)
ax0.set_xticks(range(3))
ax0.set_xticklabels(['OLS','Ridge','iRRR'],rotation=45,ha='right')
ax0.set_title('# Parameters')

print(f'iRRR uses {(nparams_full-nparams_iRRR)/nparams_full}% fewer parameters than OLS/Ridge')

if blnsave:
    fig1.savefig(op.join(figurepath,f'{agg_subject}_summary_1.svg'))

#%% Latent states
norm = plt.Normalize(ta.min(),ta.max())
cmap = 'jet'

# Aud
fig = plt.figure(num=2,figsize=[5,1.5])
gs = GridSpec(1,1,hspace=0.5,bottom=0.3,top=0.8)

audax = fig.add_subplot(gs[0])
audax.plot(sound_ta, sound, 'k')
for pt in onset_times:
    audax.axvline(pt,linestyle='-',color='k')
for pt in peakRate_times:
    audax.axvline(pt,linestyle='--',color='k')
audax.set_title(txt)
audax.spines['top'].set_visible(False)
audax.spines['right'].set_visible(False)
# audax.set_xticklabels([])
audax.set_yticks([])
STRF_utils.colorline(ta,np.ones(ta.shape)*audax.get_ylim()[0],c=ta,cmap=cmap,norm=norm,linewidth=10)
audax.set_xlim(ta[[0,-1]])

if blnsave:
    fig.savefig(op.join(figurepath,f'{agg_subject}_summary_2.svg'))

#%% Top 3

fig = plt.figure(num=3,figsize=[5,2.5])
fig.clear()
gs = GridSpec(1,nplot,wspace=0.5)

for i,(name,stim,mtrf_approx,ncomponents) in enumerate(zip(phnstimnames[:nplot], dstims, cv1_strfs_irrr, cv1_best_ndims_by_feature)):
    U,S,Vh = STRF_utils.get_svd_of_mtrf(mtrf_approx,ncomponents,True)

    pred = stim @ (U*S)[:,:3]

    if ncomponents>2:
        ax = fig.add_subplot(gs[i],projection='3d')
        STRF_utils.colorline(pred[:,0],pred[:,1],pred[:,2],c=ta,cmap=cmap,norm=norm,ax=ax)
        ax.set_zlim(pred[:,2].min() - pred[:,2].std()/2,pred[:,2].max() + pred[:,2].std()/2)
        ax.set_xlim(pred[:,0].min() - pred[:,0].std()/2,pred[:,0].max() + pred[:,0].std()/2)
        ax.set_ylim(pred[:,1].min() - pred[:,1].std()/2,pred[:,1].max() + pred[:,1].std()/2)

        ax.view_init(elev=47, azim=-65)
        ax.set_xlabel('#1')
        ax.set_ylabel('#2')
        ax.set_zlabel('#3')
        ax.set_xticks(np.arange(0,pred[:,0].max(),5))
    elif ncomponents>1:
        ax = fig.add_subplot(gs[i])
        STRF_utils.colorline(pred[:,0],pred[:,1],c=ta,cmap=cmap,norm=norm,ax=ax)

        ax.set_xlim(pred[:,0].min() - pred[:,0].std()/2,pred[:,0].max() + pred[:,0].std()/2)
        ax.set_ylim(pred[:,1].min() - pred[:,1].std()/2,pred[:,1].max() + pred[:,1].std()/2)
        ax.set_xlabel('#1')
        ax.set_ylabel('#2')
        ax.set_xticks(np.arange(0,pred[:,0].max(),5))

# fig.suptitle(title)

if blnsave:
    fig.savefig(op.join(figurepath,f'{agg_subject}_summary_3.svg'))