from utils import (
    is_in, argmin, argmax, argmax_random_tie, probability, weighted_sampler,
    memoize, print_table, open_data, PriorityQueue, name,
    distance, vector_add
)

from collections import defaultdict, deque
import math
import random
import sys
import bisect
from operator import itemgetter

infinity = float('inf')

# ______________________________________________________________________________

class Problem(object):

    """The abstract class for a formal problem. You should subclass
    this and implement the methods actions and result, and possibly
    __init__, goal_test, and path_cost. Then you will create instances
    of your subclass and solve them with the various search functions."""

    def __init__(self, initial, goal=None):
        """The constructor specifies the initial state, and possibly a goal
        state, if there is a unique goal. Your subclass's constructor can add
        other arguments."""
        self.initial = initial
        self.goal = goal

    def actions(self, state):
        """Return the actions that can be executed in the given
        state. The result would typically be a list, but if there are
        many actions, consider yielding them one at a time in an
        iterator, rather than building them all at once."""
        raise NotImplementedError

    def result(self, state, action):
        """Return the state that results from executing the given
        action in the given state. The action must be one of
        self.actions(state)."""
        raise NotImplementedError

    def goal_test(self, state):
        """Return True if the state is a goal. The default method compares the
        state to self.goal or checks for state in self.goal if it is a
        list, as specified in the constructor. Override this method if
        checking against a single self.goal is not enough."""
        if isinstance(self.goal, list):
            return is_in(state, self.goal)
        else:
            return state == self.goal

    def path_cost(self, c, state1, action, state2):
        """Return the cost of a solution path that arrives at state2 from
        state1 via action, assuming cost c to get up to state1. If the problem
        is such that the path doesn't matter, this function will only look at
        state2.  If the path does matter, it will consider c and maybe state1
        and action. The default method costs 1 for every step in the path."""
        return c + 1

    def value(self, state):
        """For optimization problems, each state has a value.  Hill-climbing
        and related algorithms try to maximize this value."""
        raise NotImplementedError
# ______________________________________________________________________________

class Node:

    """A node in a search tree. Contains a pointer to the parent (the node
    that this is a successor of) and to the actual state for this node. Note
    that if a state is arrived at by two paths, then there are two nodes with
    the same state.  Also includes the action that got us to this state, and
    the total path_cost (also known as g) to reach the node.  Other functions
    may add an f and h value; see best_first_graph_search and astar_search for
    an explanation of how the f and h values are handled. You will not need to
    subclass this class."""

    def __init__(self, state, parent=None, action=None, path_cost=0):
        """Create a search tree Node, derived from a parent by an action."""
        self.state = state
        self.parent = parent
        self.action = action
        self.path_cost = path_cost
        self.depth = 0
        if parent:
            self.depth = parent.depth + 1

    def __repr__(self):
        return "<Node {}>".format(self.state)

    def __lt__(self, node):
        return self.state < node.state

    def expand(self, problem):
        """List the nodes reachable in one step from this node."""
        return [self.child_node(problem, action)
                for action in problem.actions(self.state)]

    def child_node(self, problem, action):
        """[Figure 3.10]"""
        next_state = problem.result(self.state, action)
        next_node = Node(next_state, self, action,
                    problem.path_cost(self.path_cost, self.state,
                                      action, next_state))
        return next_node

    def solution(self):
        """Return the sequence of actions to go from the root to this node."""
        return [node.action for node in self.path()[1:]]

    def path(self):
        """Return a list of nodes forming the path from the root to this node."""
        node, path_back = self, []
        while node:
            path_back.append(node)
            node = node.parent
        return list(reversed(path_back))

    # We want for a queue of nodes in breadth_first_graph_search or
    # astar_search to have no duplicated states, so we treat nodes
    # with the same state as equal. [Problem: this may not be what you
    # want in other contexts.]

    def __eq__(self, other):
        return isinstance(other, Node) and self.state == other.state

    def __hash__(self):
        return hash(self.state)

# ______________________________________________________________________________
# Uninformed Search algorithms

def breadth_first_tree_search(problem):
    """Search the shallowest nodes in the search tree first.
        Search through the successors of a problem to find a goal.
        The argument frontier should be an empty queue.
        Repeats infinitely in case of loops. [Figure 3.7]"""

    frontier = deque([Node(problem.initial)])  # FIFO queue

    while frontier:
        node = frontier.popleft()
        if problem.goal_test(node.state):
            return node
        frontier.extend(node.expand(problem))
    return None

def depth_first_tree_search(problem):
    """Search the deepest nodes in the search tree first.
        Search through the successors of a problem to find a goal.
        The argument frontier should be an empty queue.
        Repeats infinitely in case of loops. [Figure 3.7]"""

    frontier = [Node(problem.initial)]  # Stack

    while frontier:
        node = frontier.pop()
        if problem.goal_test(node.state):
            return node
        frontier.extend(node.expand(problem))
    return None

def depth_first_graph_search(problem):
    """Search the deepest nodes in the search tree first.
        Search through the successors of a problem to find a goal.
        The argument frontier should be an empty queue.
        Does not get trapped by loops.
        If two paths reach a state, only use the first one. [Figure 3.7]"""
    frontier = [(Node(problem.initial))]  # Stack
    explored = set()
    while frontier:
        node = frontier.pop()
        if problem.goal_test(node.state):
            return node
        explored.add(node.state)
        frontier.extend(child for child in node.expand(problem)
                        if child.state not in explored and
                        child not in frontier)
    return None

def breadth_first_graph_search(problem):
    """[Figure 3.11]
    Note that this function can be implemented in a
    single line as below:
    return graph_search(problem, FIFOQueue())
    """
    node = Node(problem.initial)
    if problem.goal_test(node.state):
        return node
    frontier = deque([node])
    explored = set()
    while frontier:
        node = frontier.popleft()
        explored.add(node.state)
        for child in node.expand(problem):
            if child.state not in explored and child not in frontier:
                if problem.goal_test(child.state):
                    return child
                frontier.append(child)
    return None

def best_first_graph_search(problem, f):
    """Search the nodes with the lowest f scores first.
    You specify the function f(node) that you want to minimize; for example,
    if f is a heuristic estimate to the goal, then we have greedy best
    first search; if f is node.depth then we have breadth-first search.
    There is a subtlety: the line "f = memoize(f, 'f')" means that the f
    values will be cached on the nodes as they are computed. So after doing
    a best first search you can examine the f values of the path returned."""
    f = memoize(f, 'f')
    node = Node(problem.initial)
    frontier = PriorityQueue('min', f)
    frontier.append(node)
    explored = set()
    while frontier:
        node = frontier.pop()
        if problem.goal_test(node.state):
            return node
        explored.add(node.state)
        for child in node.expand(problem):
            if child.state not in explored and child not in frontier:
                frontier.append(child)
            elif child in frontier:
                incumbent = frontier[child]
                if f(child) < f(incumbent):
                    del frontier[incumbent]
                    frontier.append(child)
    return None

def uniform_cost_search(problem):
    """[Figure 3.14]"""
    return best_first_graph_search(problem, lambda node: node.path_cost)

# ______________________________________________________________________________
# Bidirectional Search
# Pseudocode from https://webdocs.cs.ualberta.ca/%7Eholte/Publications/MM-AAAI2016.pdf

def bidirectional_search(problem):
    e = problem.find_min_edge()
    gF, gB = {problem.initial : 0}, {problem.goal : 0}
    openF, openB = [problem.initial], [problem.goal]
    closedF, closedB = [], []
    U = infinity

    def extend(U, open_dir, open_other, g_dir, g_other, closed_dir):
        """Extend search in given direction"""
        n = find_key(C, open_dir, g_dir)

        open_dir.remove(n)
        closed_dir.append(n)

        for c in problem.actions(n):
            if c in open_dir or c in closed_dir:
                if g_dir[c] <= problem.path_cost(g_dir[n], n, None, c):
                    continue

                open_dir.remove(c)

            g_dir[c] = problem.path_cost(g_dir[n], n, None, c)
            open_dir.append(c)

            if c in open_other:
                U = min(U, g_dir[c] + g_other[c])

        return U, open_dir, closed_dir, g_dir

    def find_min(open_dir, g):
        """Finds minimum priority, g and f values in open_dir"""
        m, m_f = infinity, infinity
        for n in open_dir:
            f = g[n] + problem.h(n)
            pr = max(f, 2*g[n])
            m = min(m, pr)
            m_f = min(m_f, f)

        return m, m_f, min(g.values())

    def find_key(pr_min, open_dir, g):
        """Finds key in open_dir with value equal to pr_min
        and minimum g value."""
        m = infinity
        state = -1
        for n in open_dir:
            pr = max(g[n] + problem.h(n), 2*g[n])
            if pr == pr_min:
                if g[n] < m:
                    m = g[n]
                    state = n

        return state

    while openF and openB:
        pr_min_f, f_min_f, g_min_f = find_min(openF, gF)
        pr_min_b, f_min_b, g_min_b = find_min(openB, gB)
        C = min(pr_min_f, pr_min_b)

        if U <= max(C, f_min_f, f_min_b, g_min_f + g_min_b + e):
            return U

        if C == pr_min_f:
            # Extend forward
            U, openF, closedF, gF = extend(U, openF, openB, gF, gB, closedF)
        else:
            # Extend backward
            U, openB, closedB, gB = extend(U, openB, openF, gB, gF, closedB)

    return infinity

# ______________________________________________________________________________
# Informed (Heuristic) Search

greedy_best_first_graph_search = best_first_graph_search
# Greedy best-first search is accomplished by specifying f(n) = h(n).

class Graph:

    """A graph connects nodes (vertices) by edges (links).  Each edge can also
    have a length associated with it.  The constructor call is something like:
        g = Graph({'A': {'B': 1, 'C': 2})
    this makes a graph with 3 nodes, A, B, and C, with an edge of length 1 from
    A to B,  and an edge of length 2 from A to C.  You can also do:
        g = Graph({'A': {'B': 1, 'C': 2}, directed=False)
    This makes an undirected graph, so inverse links are also added. The graph
    stays undirected; if you add more links with g.connect('B', 'C', 3), then
    inverse link is also added.  You can use g.nodes() to get a list of nodes,
    g.get('A') to get a dict of links out of A, and g.get('A', 'B') to get the
    length of the link from A to B.  'Lengths' can actually be any object at
    all, and nodes can be any hashable object."""

    def __init__(self, graph_dict=None, directed=True):
        self.graph_dict = graph_dict or {}
        self.directed = directed
        if not directed:
            self.make_undirected()

    def make_undirected(self):
        """Make a digraph into an undirected graph by adding symmetric edges."""
        for a in list(self.graph_dict.keys()):
            for (b, dist) in self.graph_dict[a].items():
                self.connect1(b, a, dist)

    def connect(self, A, B, distance=1):
        """Add a link from A and B of given distance, and also add the inverse
        link if the graph is undirected."""
        self.connect1(A, B, distance)
        if not self.directed:
            self.connect1(B, A, distance)

    def connect1(self, A, B, distance):
        """Add a link from A to B of given distance, in one direction only."""
        self.graph_dict.setdefault(A, {})[B] = distance

    def get(self, a, b=None):
        """Return a link distance or a dict of {node: distance} entries.
        .get(a,b) returns the distance or None;
        .get(a) returns a dict of {node: distance} entries, possibly {}."""
        links = self.graph_dict.setdefault(a, {})
        if b is None:
            return links
        else:
            return links.get(b)

    def nodes(self):
        """Return a list of nodes in the graph."""
        s1 = set([k for k in self.graph_dict.keys()])
        s2 = set([k2 for v in self.graph_dict.values() for k2, v2 in v.items()])
        nodes = s1.union(s2)
        return list(nodes)

def UndirectedGraph(graph_dict=None):
    """Build a Graph where every edge (including future ones) goes both ways."""
    return Graph(graph_dict = graph_dict, directed=False)

def RandomGraph(nodes=list(range(10)), min_links=2, width=400, height=300,
                curvature=lambda: random.uniform(1.1, 1.5)):
    """Construct a random graph, with the specified nodes, and random links.
    The nodes are laid out randomly on a (width x height) rectangle.
    Then each node is connected to the min_links nearest neighbors.
    Because inverse links are added, some nodes will have more connections.
    The distance between nodes is the hypotenuse times curvature(),
    where curvature() defaults to a random number between 1.1 and 1.5."""
    g = UndirectedGraph()
    g.locations = {}
    # Build the cities
    for node in nodes:
        g.locations[node] = (random.randrange(width), random.randrange(height))
    # Build roads from each city to at least min_links nearest neighbors.
    for i in range(min_links):
        for node in nodes:
            if len(g.get(node)) < min_links:
                here = g.locations[node]

                def distance_to_node(n):
                    if n is node or g.get(node, n):
                        return infinity
                    return distance(g.locations[n], here)
                neighbor = argmin(nodes, key=distance_to_node)
                d = distance(g.locations[neighbor], here) * curvature()
                g.connect(node, neighbor, int(d))
    return g

#setiap lokasi, merupakan keys dari location
map_IT_Del = UndirectedGraph(dict(
    Napitupulu=dict(GD9=91.23, Silo=53.94),
    Silo=dict(GD9=67.91),
    Kaper=dict(Silo=38.92),
    GD9=dict(Kaper=61.36, KB=78.85),
    KB=dict(GD8=66.88, Betfage=66.53),
    GD8=dict(Kaper=65.74),
    Betfage=dict(Perpus=66.75),
    Audit=dict(Perpus=44.40, EH=36.36),
    EH=dict(Affair=28.05, Plaza=72.38, Circle=32.99),
    Plaza=dict(OT=94.48),
    OT=dict(Surti=45.51),
    Surti=dict(Antiokia=58.29),
    Antiokia=dict(GD7=46.21, Studio=55.89, GD5=55.04),
    Studio=dict(GD7=43.06),
    GD7=dict(GD5=67.11, Satpam=101.68),
    GD4=dict(Satpam=22.52, GD5=61.22, Affair=28.91, Circle=53.47, KL=96.22),
    Satpam=dict(KL=87.32),
    KL=dict(Koperasi=21.69, Circle=91.41),
    Pniel=dict(Koperasi=42.86, PerDosen=42.19),
    PerDosen=dict(Satpam1=113.49, Rektorat=78.02),
    Rektorat=dict(Satpam1=89.81),
   ))

#posisi di windows app (x,y)
map_IT_Del.locations = dict(
    Napitupulu=(575,555),Silo=(500, 575),Kaper=(450, 555),
    GD9=(500,500),KB=(450, 470),GD8=(375, 520),
    Betfage=(430,400),Audit=(330, 380),EH=(280, 370),
    Plaza=(300, 500),OT=(240, 575),Surti=(200, 560),
    Antiokia=(130,535),Studio=(50,550),GD7=(30,490),
    GD5=(95,450),GD4=(120, 360),Satpam=(50,310),
    Perpus=(380,380),KL=(165,300),Pniel=(140,220),
    Satpam1=(450,250),Koperasi=(140,260),
    PerDosen=(230,220),Affair=(200, 370),
    Circle=(240,300),Rektorat=(330, 200),
    )

class GraphProblem(Problem):

    """The problem of searching a graph from one node to another."""

    def __init__(self, initial, goal, graph):
        Problem.__init__(self, initial, goal)
        self.graph = graph

    def actions(self, A):
        """The actions at a graph node are just its neighbors."""
        return list(self.graph.get(A).keys())

    def result(self, state, action):
        """The result of going to a neighbor is just that neighbor."""
        return action

    def path_cost(self, cost_so_far, A, action, B):
        return cost_so_far + (self.graph.get(A, B) or infinity)

    def find_min_edge(self):
        """Find minimum value of edges."""
        m = infinity
        for d in self.graph.graph_dict.values():
            local_min = min(d.values())
            m = min(m, local_min)

        return m

    def h(self, node):
        """h function is straight-line distance from a node's state to goal."""
        locs = getattr(self.graph, 'locations', None)
        if locs:
            if type(node) is str:
                return int(distance(locs[node], locs[self.goal]))

            return int(distance(locs[node.state], locs[self.goal]))
        else:
            return infinity


"""
Module that reduces scenario_trees and create  a graph structure
"""

import time

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

# tree = pd.read_csv('test.csv', delimiter = ';', decimal = ',', header = 0)
# tree = np.array(tree)

# plt.plot(tree)
# n_scen = len(tree[0])
# print(n_scen)

# print('tree_prob', tree_prob)
# print(tree)

class Scenario_builder():
    """Main class, se référer à l'algorithme tel que présenté dans la biblio
    """

    def __init__(self):
        pass

    def data_loader_csv(self, file, header=0):
        """
        Load csv
        """
        tree = pd.read_csv(file, delimiter=';', decimal=',', header=header)
        self.tree = np.array(tree)
        self.tree_prob = np.ones(self.n_scen) / self.n_scen
        # plt.plot(self.tree, color = 'b')
        # plt.show()

    def data_loader_df(self, df):
        """
        Load Data
        """
        tree_with_head = np.array(df)
        tree = tree_with_head[1:, :-1]
        self.tree = tree
        self.tree_prob = np.ones(self.n_scen) / self.n_scen
        plt.plot(self.tree)
        plt.xlabel('nombre d étapes')
        plt.ylabel('Prix en euro')
        plt.title('Arbres de scénarios')
        plt.show()

    def distance_scen_pair(self, i, j, t_max):
        return sum(abs(self.tree.transpose()[
                   i][:t_max] - self.tree.transpose()[j][:t_max]))

    n_scen = property(lambda self: len(self.tree[0]))
    T = property(lambda self: len(self.tree))

    def mat_distance_scen(self, T_max):
        index = {i for i in range(self.n_scen)}
        C_K_J = []
        for k in range(self.n_scen):
            C_J = []
            for j in range(self.n_scen):
                C_J.append(self.distance_scen_pair(k, j, T_max))
            C_K_J.append(C_J)
        C_K_J = np.array(C_K_J)
        self.C_K_J = C_K_J

    def backward_reduction(self, n_deletion, T_max=False):
        if not T_max:
            T_max = self.T
        else:
            pass
        index = {i for i in range(self.n_scen)}
        J = set()
        C_LL = np.zeros(self.n_scen)
        self.mat_distance_scen(T_max)
        for l in range(self.n_scen):
            C_LL[l] = min(self.C_K_J[l][list(index.difference(J | {l}))])
        z_L = self.tree_prob * C_LL
        l = np.argmin(z_L)
        J = J | {l}
        # Redondance avec l'initialisation à voir
        while len(J) < n_deletion:
            Z_L = []
            for l in index.difference(J):
                C_KL = []
                for k in (J | {l}):
                    c_kl = min(self.C_K_J[k][list(index.difference(J | {l}))])
                    C_KL.append(c_kl)
                C_KL = np.array(C_KL)
                z_l = sum(self.tree_prob[np.array(list(J | {l}))] * C_KL)
                # FAire des test sur la taille des listes qui sont crées
                Z_L.append(z_l)
            l = list(index.difference(J))[np.argmin(Z_L)]
            J = J | {l}
        return J

    def backward_reduction_iter(self, index, T_max=False):

        if not T_max:
            T_max = self.T
        else:
            pass
        J = set()
        C_LL = np.zeros(self.n_scen)
        self.mat_distance_scen(T_max)
        while len(J) < self.n_scen:
            Z_L = []
            for l in index.difference(J):
                C_KL = []
                for k in (J | {l}):
                    c_kl = min(self.C_K_J[k][list(index.difference(J | {l}))])
                    C_KL.append(c_kl)
                C_KL = np.array(C_KL)
                z_l = sum(self.tree_prob[np.array(list(J | {l}))] * C_KL)
                # FAire des test sur la taille des listes qui sont crées
                Z_L.append(z_l)
            l = list(index.difference(J))[np.argmin(Z_L)]
            J = J | {l}
            yield J, min(Z_L)

    def scenario_deletion(self, n_deletion):
        index = {i for i in range(self.n_scen)}
        tree_prob = self.tree_prob
        b = sum(self.tree_prob)
        J = self.backward_reduction(n_deletion)
        for i in J:
            j = np.argmin(self.C_K_J[i][list(index.difference(J))])
            j = list(index.difference(J))[j]
            # assert not j in J : A passer en test
            tree_prob[j] += tree_prob[i]

        tree_t = self.tree.transpose()[list(index.difference(J))]
        self.tree = tree_t.transpose()
        self.tree_prob = tree_prob[list(index.difference(J))]
        a = sum(self.tree_prob)
        print(a - b)

    def plot_tree(self):
        plt.plot(self.tree)
        plt.xlabel('nombre d étapes')
        plt.ylabel('Prix en euro')
        plt.title('Arbres de scénarios')
        plt.show()

    def scenario_tree_construction(self, epsilon):
        index = {i for i in range(self.n_scen)}
        boundings = {}
        for pas in range(1, self.T):
            # Reduction

            iter_J = self.backward_reduction_iter(index, self.T - pas + 1)
            J, Z = next(iter_J)
            while Z < epsilon:
                J, Z = next(iter_J)
            # print('k',pas)
            # print('I',index)
            # print('J',J)

            # scenario bundling
            for j in J:
                i = np.argmin(self.C_K_J[j][list(index.difference(J))])
                i = list(index.difference(J))[i]
                self.tree_prob[i] += self.tree_prob[j]
                self.tree[:self.T - pas + 1,
                          j] = self.tree[:self.T - pas + 1, i]
                transfer_bound = [j]
                if j in boundings.keys():
                    bounds = boundings[j]
                    for q in bounds:
                        self.tree[:self.T - pas + 1,
                                  q] = self.tree[:self.T - pas + 1, i]
                    transfer_bound.append(j)
                if i in boundings.keys():
                    boundings[i] = boundings[i] + transfer_bound
                else:
                    boundings[i] = transfer_bound
            # plt.plot(self.tree)
            # plt.show()
            for i in range(2, self.n_scen):
                pass
            index = index.difference(J)
            if len(index) <= 1:
                break

    def nx_graph_builder(self):
        G = nx.DiGraph()
        n, m = self.tree.shape
        G.add_node('root', price=self.tree[0, 0], probability=1)
        for i in range(m):
            last_node = 'root'
            for j in range(1, n):
                G.add_node(
                    f'node{i}_{j}', price=self .tree[j, i], probability=1 / self.n_scen)
                G.add_edge(last_node, f'node{i}_{j}')
                last_node = f'node{i}_{j}'
        self.graph = G

    def plot_graph(self):
        nx.draw_shell(self.graph)
        plt.show()

# builder = Scenario_builder()
# plt.show()
# builder.data_loader('test.csv')
# builder.scenario_tree_construction(7)

# builder.plot_tree()


def BracketMatcher(strParam):
    stack = []
    openbracket = ['(']
    cleanString = strParam.replace(" ", "")
    for char in cleanString:
        if char in openbracket:
            stack.append(char)
        elif char.isalpha() or char.isalnum():
            continue
        else:
          if not stack:
            return 0
          current_char = stack.pop()
          if current_char == '(':
              if char != ')':
                  return 0
    if stack:
        return 0
    else:
        return 1

strParam = "(c(oder)) b(yte)"
print(BracketMatcher(strParam))


import ee
from ee_plugin import Map

#Tradicional print
print("Hola Mundo")

#Earth Engine object
print(ee.String('Hello World from Earth Engine!').getInfo())

#Area de estudio
Cordi_blanca = ee.FeatureCollection('users/mastergis01/Cordil_Blanca')
Map.addLayer(Cordi_blanca, {'color': 'red'}, 'Coordillera_Blanca')

#Funcion de fintrado de image collection
Id = ["LANDSAT/LT05/C01/T1_SR", "LANDSAT/LC08/C01/T1_SR"]
Date = ['2010-01-01','2011-01-01','2020-01-01','2021-01-01']
def fun_medTOA(id, date01, date02):
    img = ee.ImageCollection(id)\
            .filterBounds(Cordi_blanca)\
            .filterDate(date01, date02)\
            .filterMetadata('CLOUD_COVER', 'less_than', 10)\
            .median()\
            .clip(Cordi_blanca)

    return img

#Cargar las imagenes del 2010 y 2020
img_2010 = fun_medTOA(Id[0],Date[0], Date[1])
img_2020 = fun_medTOA(Id[1], Date[2], Date[3])
Map.addLayer(img_2010, {'min': 100, 'max': 2000, 'bands': ['B3', 'B2', 'B1']}, 'Img_2010')
Map.addLayer(img_2020, {'min': 100, 'max': 2000, 'bands': ['B4', 'B3', 'B2']}, 'Img_2020')

## Calculo del Indice NDVI para el año 2010 y 2020
#Calculo del NDVI
ndvi_2010 = img_2010.normalizedDifference(['B4', 'B3'])
ndvi_2020 = img_2020.normalizedDifference(['B5', 'B4'])

#Parametros de visualizacion ndvi
vis_parandvi ={
    'min':0,
    'max':0.6,
    'palette':["#051852", "#FFFFFF", "#C7B59B", "#A8B255", "#A3C020", "#76AD00","#429001", "#006400", "#003B00", "#000000"]
}
Map.addLayer(ndvi_2010, vis_parandvi, 'ndvi_2010')
Map.addLayer(ndvi_2020, vis_parandvi, 'ndvi_2020')

## Seleccion de las bandas térmicas 6 y 10 (con temperatura de brillo), sin cálculo
#Banda termica
thermal_2010 = img_2010.select('B6').multiply(0.1)
thermal_2020 = img_2020.select('B10').multiply(0.1)

#Parametros de visualizacion
vis_parathermal ={
    'min':291.918,
    'max':302.382,
    'palette':['042333', '2c3395', '744992', 'b15f82', 'eb7958', 'fbb43d', 'e8fa5b']
}

Map.addLayer(thermal_2010, vis_parathermal, 'thermal_2010')
Map.addLayer(thermal_2020, vis_parathermal, 'thermal_2020')

## Calculo de la Vegetacion fracturada (fv)
#Vegetacion fracturada del 2010 ((NDVI-minNDVI)/(maxNDVI-minNDVI))^2
fv_2010 = (ndvi_2010.subtract(ee.Number(-1)).divide(ee.Number(1).subtract(ee.Number(-1)))).pow(ee.Number(2)).rename('fv')
fv_2020 = (ndvi_2020.subtract(ee.Number(-1)).divide(ee.Number(1).subtract(ee.Number(-1)))).pow(ee.Number(2)).rename('fv')
#Parametros de visualizacion
para_fv ={
    'min':0,
    'max':0.6,
    'palette':['blue', 'white', 'green']
}
Map.addLayer(fv_2010, para_fv, 'fv_2010')
Map.addLayer(fv_2020, para_fv, 'fv_2020')

## Emissivity EM = Fv * 0.04 + 0.986
#Asignacion de valores
a= ee.Number(0.004)
b= ee.Number(0.986)

#Calculo de la emisibidad
EMM_2010 = fv_2010.multiply(a).add(b).rename('EMM')
EMM_2020 = fv_2020.multiply(a).add(b).rename('EMM')

#Parametros de visualizacion
Para_EMM = {
    'min':  0.9865619146722164,
    'max': 0.989699971371314,
    'palette':['181c43', '0c5ebe', '75aabe', 'f1eceb', 'd08b73', 'a52125', '3c0912']
}

#Visualizacion de resultados
Map.addLayer(EMM_2010, Para_EMM, 'EMM_2010')
Map.addLayer(EMM_2020, Para_EMM, 'EMM_2020')

############### Temperatura de la superficie terrestre(LST) en grados Celsius ################
# Land Surface Temperature
def fun_lst(thermal,EMM, Banda):
    lst = thermal.expression(
    '(Tb/(1 + (0.00115* (Tb / 1.438))*log(Ep)))-273.15', {
        'Tb': thermal.select(Banda),
        'Ep': EMM.select('EMM')
    }
    ).rename('LST')
    return lst
#Calculo
LST_2010 = fun_lst(thermal_2010, EMM_2010, 'B6' )
LST_2020 = fun_lst(thermal_2020, EMM_2020, 'B10' )

#Parametros de visualizacion
Para_LST = {
    'min':0,
    'max':10,
    'palette':[
                '040274', '040281', '0502a3', '0502b8', '0502ce', '0502e6',
                '0602ff', '235cb1', '307ef3', '269db1', '30c8e2', '32d3ef',
                '3be285', '3ff38f', '86e26f', '3ae237', 'b5e22e', 'd6e21f',
                'fff705', 'ffd611', 'ffb613', 'ff8b13', 'ff6e08', 'ff500d',
                'ff0000', 'de0101', 'c21301', 'a71001', '911003'
 ]
}

#Visualizacion de resultados LST
Map.addLayer(LST_2010, Para_LST, 'LST_2010')
Map.addLayer(LST_2020, Para_LST, 'LST_2020')


# coding:utf-8

# from .BaseHandler import BaseHandler
# import handlers.BaseHandler
from handlers.BaseHandler import RequestBaseHandler
import os

class ImageHandler(RequestBaseHandler):
    """"""

    def get(self, *args, **kwargs):
        suburl = self.request.uri.split('/')[-1:][0]
        print(suburl)
        pic = open(os.path.join(os.path.dirname("handlers"), "statics/images/" + suburl), 'r')
        print("------")
        # pic = open("../statics/css/" + suburl,'r')
        pics = pic.read()
        print(pics)
        self.set_header("Content-type", "image/png")
        return self.write(pics.encode('utf8'))

    def post(self, *args, **kwargs):
        self.write("this home page")

class CssHandler(RequestBaseHandler):
    """获取css文件接口"""
    def get(self, *args, **kwargs):
        suburl = self.request.uri.split('/')[-1:][0]
        print(suburl)
        pic = open(os.path.join(os.path.dirname("handlers"), "statics/css/" + suburl),'r')
        # pic = open("../statics/css/" + suburl,'r')
        pics = pic.read()
        # self.set_header("Content-type", "image/png")
        return self.write(pics)


# -*- coding: utf-8 -*-
__author__ = 'Tao Kong'
import logging
import os
import time

from common import globalvariable

PATH = lambda path: os.path.abspath(
    os.path.join(
        os.path.dirname(__file__), path
    )
)

class BasePage:
    def __init__(self, appium_driver):
        self.__driver = appium_driver
        self.logger = logging.getLogger(globalvariable.get_value("LOGGER_NAME"))

    @property
    def driver(self):
        return self.__driver

    @property
    def window_width(self):
        width = self.driver.get_window_size()['width']
        return width

    @property
    def window_height(self):
        height = self.driver.get_window_size()['height']
        return height

    @property
    def window_size(self):
        size = self.driver.get_window_size()
        return {'width': size['width'], 'height': size['height']}

    def back(self):
        self.driver.back()

    def press_key(self, code):
        self.driver.press_keycode(code)

    def switch_to_web_view(self, view_name):
        self.driver.switch_to.context(view_name)

    def set_value_by_keys(self, value):
        letterToCodeHashMap = {}
        lettersStr = "a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z @ . + _ 0 1 2 3 4 5 6 7 8 9".split()
        androidCodes = [29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
                        53, 54, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
                        51, 52, 53, 54, 77, 56, 81, 69, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
        for index in range(len(lettersStr)):
            letterToCodeHashMap[lettersStr[index]] = androidCodes[index]
        for i in range(len(value)):
            code = letterToCodeHashMap.get(value[i])
            self.pressKey(code)
            time.sleep(0.5)

    # 屏幕向上滑动
    def swipe_up(self, t=1000):
        x1 = int(self.window_width * 0.5)  # x坐标
        y1 = int(self.window_height * 0.75)  # 起始y坐标
        y2 = int(self.window_height * 0.25)  # 终点y坐标
        self.driver.swipe(x1, y1, x1, y2, t)
        time.sleep(1.5)

    # 屏幕向下滑动
    def swipe_down(self, t=1000):
        x1 = int(self.window_width * 0.5)  # x坐标
        y1 = int(self.window_height * 0.25)  # 起始y坐标
        y2 = int(self.window_height * 0.75)  # 终点y坐标
        self.driver.swipe(x1, y1, x1, y2, t)
        time.sleep(1.5)

    # 屏幕向左滑动
    def swipe_left(self, t=1000):
        x1 = int(self.window_width * 0.75)
        y1 = int(self.window_height * 0.5)
        x2 = int(self.window_width * 0.05)
        self.driver.swipe(x1, y1, x2, y1, t)
        time.sleep(1.5)

    # 屏幕向右滑动
    def swipe_right(self, t=1000):
        x1 = int(self.window_width * 0.05)
        y1 = int(self.window_height * 0.5)
        x2 = int(self.window_width * 0.75)
        self.driver.swipe(x1, y1, x2, y1, t)
        time.sleep(1.5)

    # savePngName:生成图片的名称
    def save_png_name(self, name):
        """
        name：自定义图片的名称
        """
        day = time.strftime('%Y-%m-%d', time.localtime(time.time()))
        fp = os.path.join(".." + os.sep + ".." + os.sep, "result", day, "image", day)
        tm = self.save_time()
        img_type = ".png"
        if os.path.exists(PATH(fp)):
            filename = os.path.join(PATH(fp), tm + "_" + name + img_type)
            print(PATH(filename))
            # print "True"
            return PATH(filename)
        else:
            os.makedirs(PATH(fp))
            filename = os.path.join(PATH(fp), tm + "_" + name + img_type)
            print(PATH(filename))
            # print "True"
            return PATH(filename)

    # 获取系统当前时间
    def save_time(self):
        """
        返回当前系统时间以括号中（2014-08-29-15_21_55）展示
        """
        return time.strftime('%Y-%m-%d-%H_%M_%S', time.localtime(time.time()))

    # saveScreenshot:通过图片名称，进行截图保存
    def save_screenshot(self, name):
        """
        快照截图
        name:图片名称
        """
        # 获取当前路径
        # print os.getcwd()
        image = self.driver.save_screenshot(self.save_png_name(name))
        return image


#!/usr/bin/env python3
import aspio

program = aspio.Program(code=r'''
    p(1).
    p(2).

    q(1, a).
    q(1, b).
    q(1, c).
    q(2, x).
    q(2, y).
    q(3, no).

    %!  OUTPUT {
    %!      result = set {
    %!          query: p(X);
    %!          content: (int(X), set { query: q(X, Y); content: Y; });
    %!      };
    %!  }
''')
# %!  OUTPUT {
# %!      ys(X) = set { query: q(X, Y); content: Y; }
# %!      result = set {
# %!          query: p(X);
# %!          content: (int(X), ys(X));
# %!      }
# %!  }

expected_result = frozenset({
    (1, frozenset({'a', 'b', 'c'})),
    (2, frozenset({'x', 'y'})),
})

for (i, result) in enumerate(program.solve().each_result):
    print('Answer set {0!s}:'.format(i + 1))
    print('Result         : {0!r}'.format(result))
    print('Expected result: {0!r}'.format(expected_result))


from pyDes import *
import binascii
data=binascii.unhexlify('781723860c06c2264608f919887022120b795240cb7049b01c19b33e32804f0b')

key=binascii.unhexlify('ab94fdecf2674fdfb9b391f85d7f76f2ab94fdecf2674fdf')
IV='\0\0\0\0\0\0\0\0'

k=triple_des(key, CBC, IV, pad=None, padmode=PAD_NORMAL)

dd3=k.encrypt(data)

dd3=binascii.hexlify(dd3)

from pyDes import *
import binascii
def KencTDES(data,ka1,kb1):

    data=binascii.unhexlify(data)
    key=ka1+kb1+ka1
    key=binascii.unhexlify(key)
    IV='\0\0\0\0\0\0\0\0'
    k=triple_des(key, CBC, IV, pad=None, padmode=PAD_NORMAL)
    dd3=k.encrypt(data)
    dd3=binascii.hexlify(dd3)
    return dd3


from datetime import datetime
#Default spy details concept of classes is also used
class Spy:

  def __init__(self, name, salutation, age, rating):
    self.name = name
    self.salutation = salutation
    self.age = age
    self.rating = rating
    self.is_online = True
    self.chats = []
    self.current_status_message = None
    self.count=0

spy = Spy('Ishaan', 'Mr', 20, 5.0)

friend_one = Spy('Raja', 'Mr', 27, 4.9)
friend_two = Spy('rani', 'Ms', 21, 4.39)
friend_three = Spy('Barati', 'Dr', 37, 4.95)

friends = [friend_one, friend_two, friend_three]

#class ChatMessage is used to get the message sent by the user to his/her friends
class ChatMessage:

  def __init__(self, message, sent_by_me):
    self.message = message
    self.time = datetime.now()
    self.sent_by_me = sent_by_me


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


import os
import typing as tp

import cv2
import numpy as np
import scipy.ndimage
import time
import tqdm
from PIL import Image

KERNELS = [
    np.array(
        [
            [-1, 2, -1],
            [-1, 2, -1],
            [-1, 2, -1],
        ]
    ),
    np.array(
        [
            [2, -1, -1],
            [-1, 2, -1],
            [-1, -1, 2],
        ]
    ),
    np.array(
        [
            [-1, -1, -1],
            [2, 2, 2],
            [-1, -1, -1],
        ]
    ),
    np.array(
        [
            [-1, -1, 2],
            [-1, 2, -1],
            [2, -1, -1],
        ]
    ),
]

SOURCE_DIR = "/home/andresokol/data/compressed"
MASK_ROOT = "/home/andresokol/data/masks_v2"
ORIENTATION_ROOT = "/home/andresokol/data/orientation_v2"

def get_direction_weights(image: np.ndarray, kernel: np.ndarray) -> np.ndarray:
    channel = cv2.filter2D(image, -1, kernel).astype(float)
    # channel = cv2.boxFilter(channel, -1, (3, 3))
    channel = scipy.ndimage.maximum_filter(channel, size=5)
    return channel

# def directed_sobel(image: np.ndarray, axis: int) -> np.ndarray:
#     channel = scipy.ndimage.sobel(image, axis=axis)
#     channel = np.abs(channel - 128) * 2
#     # channel = scipy.ndimage.maximum_filter(channel, size=3)
#     return channel

# def image_gradient(img: np.ndarray) -> np.ndarray:
#     hor_grad = (img[1:, :] - img[:-1, :])[:, :-1]
#     ver_grad = (img[:, 1:] - img[:, :-1])[:-1:, :]
#     magnitude = np.sqrt(hor_grad ** 2 + ver_grad ** 2)
#     return magnitude

def read_original(img_dir: str, img_name: str) -> np.ndarray:
    image = cv2.imread(f"{SOURCE_DIR}/{img_dir}/{img_name}.jpg")
    image = cv2.resize(image, (512, 512))
    return image

def read_mask(img_dir: str, img_name: str) -> np.ndarray:
    image = cv2.imread(f"{MASK_ROOT}/{img_dir}/{img_name}.png")
    image = cv2.resize(image, (512, 512))
    return image

def adjust_gamma(image, gamma=1.0):
    # build a lookup table mapping the pixel values [0, 255] to
    # their adjusted gamma values
    invGamma = 1.0 / gamma
    table = np.array([((i / 255.0) ** invGamma) * 255
        for i in np.arange(0, 256)]).astype("uint8")
    # apply gamma correction using the lookup table
    return cv2.LUT(image, table)

def extract_structure_data(original: np.ndarray) -> np.ndarray:
    image = np.copy(original)
    image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
#     direction_weights = np.dstack(
#         (
#             get_direction_weights(image, KERNELS[0]),
#             np.maximum(
#                 get_direction_weights(image, KERNELS[1]),
#                 get_direction_weights(image, KERNELS[3]),
#             ),
#             get_direction_weights(image, KERNELS[2]),
#         )
#     )
#     directions = np.argmax(direction_weights, axis=2)

#     blue_channel = directions * 127
#     red_channel = 255 - blue_channel

    axis_0 = scipy.ndimage.convolve1d(image.astype(float), [-1, 1, 0], axis=0)
    axis_0 = np.abs(axis_0)

    axis_1 = scipy.ndimage.convolve1d(image.astype(float), [-1, 1, 0], axis=1)
    axis_1 = np.abs(axis_1)

    composite = np.dstack([
        axis_1,
        np.zeros_like(axis_0),
        axis_0,
    ])

    composite = adjust_gamma(composite.astype('uint8'), gamma=4)

#     image = cv2.merge(
#         (
#             red_channel.astype("uint8"),
#             np.zeros(shape=red_channel.shape, dtype="uint8"),
#             blue_channel.astype("uint8"),
#         )
#     )

    # image = cv2.boxFilter(image, -1, (16, 16))

    # downsampled = cv2.resize(image, (64, 64))

    return composite

def apply_threshold(image: np.ndarray, threshold: float) -> np.ndarray:
    normalized = image.astype(float) / 255.0
    return (normalized > threshold).astype(int) * 255

def process(image: np.ndarray, mask: np.ndarray) -> np.ndarray:
    image = extract_structure_data(image)

    hair_mask, _, _ = cv2.split(mask)
    # hair_mask = cv2.resize(hair_mask, image.shape[:2])
    hair_mask = apply_threshold(hair_mask, 0.4)

    image = np.dstack((image, hair_mask.astype("uint8")))

    return image

def apply_on_original(bg: np.ndarray, image: np.ndarray) -> np.ndarray:
    bg_pil = Image.fromarray(bg).convert("RGBA")
    image_pil = Image.fromarray(image)
    composite = Image.alpha_composite(bg_pil, image_pil)
    return np.asarray(composite)  # type: ignore

def image_paths() -> tp.List[tp.Tuple[str, str]]:
    paths = []
    for dirname in os.listdir(SOURCE_DIR):
        for filename in os.listdir(f"{SOURCE_DIR}/{dirname}"):
            if not os.path.exists(f"{MASK_ROOT}/{dirname}/{filename[:-len('.jpg')]}.png"):
                continue
            if filename.endswith(".jpg"):
                paths.append((dirname, filename[:-len(".jpg")]))
    print(f"Found {len(paths)} images")
    return paths

def main():
    # img_dir, img_name = "01000", "01000"
    for img_dir, img_name in tqdm.tqdm(image_paths()):
        target_dir = f"{ORIENTATION_ROOT}/{img_dir}"
        if not os.path.exists(target_dir):
            os.mkdir(target_dir)

        if os.path.exists(f"{target_dir}/{img_name}.png"):
            continue

        original = read_original(img_dir, img_name)
        mask = read_mask(img_dir, img_name)

        image = process(original, mask)

        structure_overlayed = apply_on_original(original, image)
        cv2.imwrite(
            f"{target_dir}/{img_name}.png",
            structure_overlayed,
        )

    # cv2.imshow("w", structure_overlayed)
    # while cv2.waitKey(5) & 0xFF != 27:
    #     time.sleep(0.5)

if __name__ == "__main__":
    main()