import datetime

from google.appengine.api import users

from soc.views.template import Template

from soc.logic import accounts
from soc.modules.gci.models.task import ACTIVE_CLAIMED_TASK
from soc.modules.gci.models.task import GCITask

def siteMenuContext(data):
  """Generates URL links for the hard-coded GCI site menu items.
  """
  redirect = data.redirect
  program = data.program

  from soc.modules.gci.models.program import GCIProgram
  about_page = GCIProgram.about_page.get_value_for_datastore(program)
  connect = GCIProgram.connect_with_us_page.get_value_for_datastore(program)
  help_page = GCIProgram.help_page.get_value_for_datastore(program)
  terms = GCIProgram.terms_and_conditions.get_value_for_datastore(program)

  context = {
      'about_link': redirect.document(about_page).url(),
      'terms_link': redirect.document(terms).url(),
      'events_link': redirect.events().url(),
      'connect_link': redirect.document(connect).url(),
      'help_link': redirect.document(help_page).url(),
  }

  if users.get_current_user():
    context['logout_link'] = redirect.logout().url()
  else:
    context['login_link'] = redirect.login().url()

  if data.user:
    context['dashboard_link'] = redirect.dashboard().url()

  if data.timeline.tasksPubliclyVisible():
    context['tasks_link'] = redirect.program().urlOf('gci_list_tasks')
    if not data.user:
      context['register_as_student_link'] = redirect.createProfile(
          'student').urlOf('create_gci_profile')

  return context

class Header(Template):
  """MainMenu template.
  """

  def __init__(self, data):
    self.data = data

  def templatePath(self):
    return "v2/modules/gci/_header.html"

  def context(self):
    return {
        'home_link': self.data.redirect.homepage().url(),
        # TODO(SRabbelier): make this dynamic somehow
        'gsoc_link': '/gsoc/homepage/google/gsoc2011',
    }

class MainMenu(Template):
  """MainMenu template.
  """

  def __init__(self, data):
    self.data = data

  def context(self):
    context = siteMenuContext(self.data)
    context.update({
        'home_link': self.data.redirect.homepage().url(),
    })

    if self.data.profile:
      self.data.redirect.program()
      if self.data.profile.status == 'active':
        if self.data.timeline.programActive():
          context['profile_link'] = self.data.redirect.urlOf(
              'edit_gci_profile')
        else:
          context['profile_link'] = self.data.redirect.urlOf(
              'show_gci_profile')

        if self.data.is_org_admin:
          # Add org admin dashboard link if the user has active
          # org admin profile and is an org admin of some organization
          context['org_dashboard_link'] = self.data.redirect.urlOf(
              'gci_dashboard')

    if self.data.is_host:
      self.data.redirect.program()
      context['admin_link'] = self.data.redirect.urlOf('gci_admin_dashboard')

    return context

  def templatePath(self):
    return "v2/modules/gci/_mainmenu.html"

class Footer(Template):
  """Footer template.
  """

  def __init__(self, data):
    self.data = data

  def context(self):
    context = siteMenuContext(self.data)
    program = self.data.program

    context.update({
        'privacy_policy_link': program.privacy_policy_url,
        'blogger_link': program.blogger,
        'email_id': program.email,
        'irc_link': program.irc,
        })

    return context

  def templatePath(self):
    return "v2/modules/gci/_footer.html"

class Status(Template):
  """Template to render the status block.
  """

  def __init__(self, data):
    self.data = data

  def getTimeLeftForTask(self, task):
    """Time left to complete the task in human readable format.
    """
    if not task.deadline:
      return ""

    time_now = datetime.datetime.utcnow()
    time_left = task.deadline - time_now
    days_left = time_left.days
    hours_left = time_left.seconds/3600
    minutes_left = (time_left.seconds/60)%60
    return "%s days %s hrs %s min" % (days_left, hours_left, minutes_left)

  def context(self):
    context = {
        'user_email': accounts.denormalizeAccount(self.data.user.account).email(),
        'link_id': self.data.user.link_id,
        'logout_link': self.data.redirect.logout().url(),
        'dashboard_link': self.data.redirect.dashboard().url()
    }

    if self.data.profile:
      if self.data.is_student and self.data.profile.status == 'active':
        q = GCITask.all()
        q.filter('student', self.data.profile)
        q.filter('status IN', ACTIVE_CLAIMED_TASK)
        task = q.get()
        if task:
          context['task'] = task
          context['time_left'] = self.getTimeLeftForTask(task)
          task_url = self.data.redirect.id(
              task.key().id()).urlOf('gci_view_task')
          context['task_url'] = task_url
    return context

  def templatePath(self):
    return "v2/modules/gci/_status_block.html"


import unittest

import attr

import fwdpy11.class_decorators

@fwdpy11.class_decorators.attr_class_to_from_dict
@fwdpy11.class_decorators.attr_add_asblack
@attr.s(auto_attribs=True)
class FauxClass(object):
    a: float
    b: float

class TestClassDecorators(unittest.TestCase):
    @classmethod
    def setUpClass(self):
        self.f = FauxClass(1.0, 3.0)

    def test_black_pretty_print(self):
        try:
            _ = self.f.asblack()
        except:  # NOQA
            self.fail("self.f.asblack() raised unexpected exception")

    def test_to_from_dict(self):
        d = self.f.asdict()
        self.assertEqual(d["a"], self.f.a)
        self.assertEqual(d["b"], self.f.b)
        f = FauxClass.fromdict(d)
        self.assertEqual(f.a, self.f.a)
        self.assertEqual(f.b, self.f.b)

if __name__ == "__main__":
    unittest.main()


from django.shortcuts import render
from WebAppIntermediario.models import Aluno

# Create your views here.

def index(request):
    alunos = Aluno.objects.all()

    chaveAluno ={
        'alunos': alunos
    }

    return render(request, 'index.html', chaveAluno)

def aluno(request, id):
    aluno = Aluno.objects.get(id=id)

    context = {
        'aluno': aluno
    }

    return render(request, 'aluno.html', context)


import sqlite3
import csv

class Iceland_sql():

    def run(self):

        conn = sqlite3.connect('../framework/Produce.db')
        cur = conn.cursor()

        cur.execute('DROP TABLE IF EXISTS Iceland')
        cur.execute('''
        CREATE TABLE "Iceland"(
            "Product_id" TEXT,
            "Image_Url" TEXT,
            "Image_Path" TEXT,
            "Image_Data" BLOP
        )
        ''')

        csv_name ='./iceland_csv/iceland.csv'

        with open(csv_name, encoding='utf-8') as csv_file:
            csv_reader = csv.reader((csv_file))
            for row in csv_reader:
                try:

                    product_id = row[0]
                    image_url =  row[1]
                    image_path =  row[2]
                    with open(image_path,'rb') as f:
                        data = f.read()
                    cur.execute('''INSERT INTO iceland(Product_id,Image_URL,Image_Path,Image_Data)
                            VALUES(?,?,?,?)''', (product_id, image_url, image_path, data))
                    conn.commit()

                except(FileNotFoundError):
                    print(image_path)

        conn.close()


#time
#real	0m5.561s
#user	0m2.616s
#sys	0m0.793s

import PIL
from PIL import Image
import cv2
import sklearn
from sklearn.cluster import KMeans
import colorsys

#DEFINES

#CLUSTER_NUM
CLUSTER_NUM = 4

#set analyzing size
RESIZE_WIDTH = 32

#For Param Tuning
PARAM_TUNING = False

def run(cv2_img):

    #get original image size
    img_height,img_width,_ = cv2_img.shape

    # CALC HEIGHT PARAM
    RESIZE_HEIGHT = RESIZE_WIDTH / img_width * img_height

    #Resizing for increasing speed
    cv2_img = cv2.resize(cv2_img, (int(RESIZE_WIDTH), int(RESIZE_HEIGHT)))
    #rest because of using numpy array
    #cv2_img = cv2.cvtColor(cv2_img, cv2.COLOR_BGR2RGB)

    #analyze main 4 color by sklearn
    cv2_img = cv2_img.reshape(
        (cv2_img.shape[0] * cv2_img.shape[1], 3))

    #Clustring Section
    cluster = KMeans(n_clusters = CLUSTER_NUM)
    cluster.fit(X=cv2_img)

    # cluster.cluster_centers_ returns RGB array of each cluster.
    #rgb(0-255, 0-255, 0-255)
    main_rgb_color = cluster.cluster_centers_

    #hsv(0.0-1.0, 0.0-1.0, 0.0-1.0)
    hsv_color = [[], [], [], []]

    #Convert from RGB to HSV
    for i in range(CLUSTER_NUM):
        hsv_color[i] = colorsys.rgb_to_hsv(main_rgb_color[i][0] / 255.0, main_rgb_color[i][1] / 255.0, main_rgb_color[i][2] / 255.0)
        if PARAM_TUNING:
            print (hsv_color[i])

    # Pick the most impact cluster
    # Rescaled to hsv(0.0-1.0, 0.0-1.0, 0.0-1.0)
    color_result = [0.0, 0.0, 0.0]
    impact = highest = 0.0
    for c in hsv_color:
        impact = c[1]+(c[2]*c[2])
        if impact > highest:
            color_result = c
            highest = impact
    # print('RST' , color_result)
    return color_result

#Method for manual open with this module only
def open_with_file(file_name):
    img = cv2.imread(file_name)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    return run(img)


from django.shortcuts import render
from django.http import HttpResponse, HttpResponseNotFound

# Create your views here.
# def january(request):
#     return HttpResponse("This works!!!")
#
# def february(request):
#     return HttpResponse("Go for Run!!!")

monthly_challenges = {
    "january" : "This works!!!",
    "february" : "Go for Run!!!"

}

def monthly_challenge_by_number(request, m):
    return HttpResponse(m)

def month(request, m):
    try:
        challenge_text = monthly_challenges[m]
        return HttpResponse(challenge_text)
    except:
        return HttpResponseNotFound("Invalid month")


import MeCab
import emoji
import mojimoji
import re
from nltk import ngrams
import spacy
from spacy import displacy

nlp = spacy.load('ja_ginza')
default_t = MeCab.Tagger("-Ochasen")
neologd_t = MeCab.Tagger(" -d /opt/mecab/lib/mecab/dic/mecab-ipadic-neologd")
emoji_lst = emoji.UNICODE_EMOJI
DEF_URL_TAG = "URL"
DEF_EMOJI_TAG = "EMOJI"

def analysis_mecab(text, is_neologd=False):

    def _sep(text):
        tagger = neologd_t if is_neologd else default_t
        return [t for t in tagger.parse(text).split('\n')
                if t not in ["", "EOS"]]

    lst = [t.split("\t") for t in _sep(text)]

    if is_neologd:
        lst = [[s[0]] + s[1].split(",") for s in lst]

    return lst

def sep_by_mecab(text, is_neologd=False, org_form=False):
    if is_neologd:
        idx = 7 if org_form else 0
    else:
        idx = 2 if org_form else 0
    wakati = analysis_mecab(text, is_neologd)
    return [w[idx] for w in wakati]

def get_pos(text, is_neologd=False):
    wakati = analysis_mecab(text, is_neologd=is_neologd)
    if is_neologd:
        pos = [w[1] for w in wakati]
    else:
        pos = [w[3].split("-")[0] for w in wakati]
    return pos

def norm_url(text, url_tag=DEF_URL_TAG):
    url_pattern = r"https?://[\w/:%#\$&\?\(\)~\.=\+\-…]+"
    return re.sub(url_pattern, url_tag, text)

def norm_numeric(text):
    w_lst = sep_by_mecab(text)
    return "".join(["0" if w.isnumeric() else w for w in w_lst])

def norm_emoji(text, emoji_tag=DEF_EMOJI_TAG):
    return "".join([emoji_tag if t in emoji_lst else t for t in text])

def nchars(s, n):
    assert n > 0
    reg = re.compile("(.)\\1{%d,}" % (n - 1))
    while True:
        m = reg.search(s)
        if not m:
            break
        yield m.group(0)
        s = s[m.end():]

def is_continuous_char(text, count):
    c_lst = list(nchars(text, count))
    return len(c_lst) > 0

def is_continuous_word(text, count, org_form=False):
    w_lst = sep_by_mecab(text, org_form)
    e_lst = list(ngrams(w_lst, count))
    return sum([len(set(e)) == 1 for e in e_lst]) != 0

def norm_continuous_char(text, count=3):
    c_lst = list(nchars(text, count))
    for c in c_lst:
        text = text.replace(c, c[0])
    return text

def normalize_text(text):
    text = str(text)
    text = text.lower()  # all lower
    text = mojimoji.zen_to_han(text)  # all hankaku
    text = norm_numeric(text)
    text = norm_emoji(text)
    text = norm_url(text)
    text = norm_continuous_char(text)
    return text

def aster2mask(text):
    return re.sub("(\*){2,}", " [MASK]", text)

def norm_ner(text, ners=["DATE", "MONEY"]):
    doc = nlp(text)
    for ent in doc.ents:
        if ent.label_ in ners:
            text = text.replace(ent.text, f"[{ent.label_}]")

def get_tokens(text):
    doc = nlp(text)
    try:
        sent = [sent for sent in doc.sents][0]
    except IndexError:
        return None, None
    root_head_i = [token.head.i for token in sent if token.dep_ == "ROOT"][0]
    return sent, root_head_i

def is_want_text(sent, root_head_i):
    return  len([token.lemma_ for token in sent if token.head.i == root_head_i and token.lemma_ in ["たい"]]) > 0

def is_not_text(sent, root_head_i):
    return  len([token.lemma_ for token in sent if token.head.i == root_head_i and token.lemma_ in ["ない", "ず"]]) > 0

def is_q_text(sent, root_head_i):
    return  len([token.lemma_ for token in sent if token.head.i == root_head_i and token.lemma_ in ["か"]]) > 0

def is_use_text(text):
    sent, root_head_i = get_tokens(text)
    if sent is None:
        return False
    is_q = is_q_text(sent, root_head_i)
    is_not = is_not_text(sent, root_head_i)
    is_want = is_want_text(sent, root_head_i)
    return is_q or is_not or is_want

def get_words_info_ginza(text, plot=False):
    doc = nlp(text)
    for sent in doc.sents:
        for token in sent:
            print(token.i, token.orth_, token.lemma_, token.pos_, token.tag_, token.dep_, token.head.i)
        print('EOS')
    if plot:
        displacy.serve(doc, style="dep")


#!/usr/bin/env python3
'''
Automatically buy and sell stocks.

Part of naps (neopets automation program suite)
'''

import bs4
import re
import sqlite3
import time
from NeoSession import NeoSession

class TradeStocks(NeoSession):
    stock_list = []
    portfolio_list = []
    buy_volume = '1000'

    def __init__(self):
        self.parse()
        self.lowest_stock = self.determine_lowest()
        self.save_data()
        self.buy()
        self.sell()

    def save_data(self):
        stock_data = sqlite3.connect('stockdata.db')
        cur = stock_data.cursor()
        try:
            cur.execute('''CREATE TABLE stocks
                                               (ticker TEXT, volume INTEGER,
                                                open INTEGER, curr INTEGER,
                                                 change TEXT, time FLOAT)''')
            cur.execute('''CREATE TABLE portfolio
                                               (ticker TEXT, volume INTEGER,
                                                price INTEGER, time FLOAT)''')
        except sqlite3.OperationalError:
            for stocks in self.stock_list:
                cur.execute('''INSERT INTO stocks (ticker, volume, open, curr,
                               change, time) VALUES (?, ?, ?, ?, ?, ?)''',
                            (stocks['ticker'], stocks['volume'], stocks['open'],
                             stocks['curr'], stocks['change'], stocks['time']))
            stock_data.commit()
            cur.close()
            print('{}: StockTrade - Stock data written to DB.'.format(
                self.time))

    def buy(self):
        url = 'http://www.neopets.com/stockmarket.phtml?type=buy&ticker={}' \
            .format(self.lowest_stock['ticker'])
        resp = self.get(url)
        ref_ck = re.search(r"'&_ref_ck=(\w*)';", resp.text).group(1)
        url = 'http://www.neopets.com/process_stockmarket.phtml'
        resp = self.post(url, data={'type': 'buy',
                                    'ticker_symbol': self.lowest_stock['ticker'],
                                    'amount_shares': self.buy_volume,
                                    '_ref_ck': ref_ck}, login_check=False)

        if 'Error: Sorry, that would' in resp.text:
            print('{}: StockTrade - Purchase exceeds daily 1000 share limit.'.
                  format(self.time))
            pass
        else:
            self.get('http://www.neopets.com/stockmarket.phtml?type=portfolio')
            print('{}: StockTrade - Bought {} shares of {}.'.format(
                self.time, self.buy_volume,
                self.lowest_stock['ticker']))

            stock_data = sqlite3.connect('stockdata.db')
            cur = stock_data.cursor()
            cur.execute('''INSERT INTO portfolio (ticker, volume, price,
                                      time) VALUES (?, ?, ?, ?)''',
                        (self.lowest_stock['ticker'], self.buy_volume, self.lowest_stock['curr'],
                         self.lowest_stock['time']))
            stock_data.commit()
            cur.close()

    def sell(self):
        stock_data = sqlite3.connect('stockdata.db')
        cur = stock_data.cursor()
        for row in cur.execute('SELECT * FROM portfolio'):
            print(row)
        print('{}: StockTrade - Stocks sold.'.format(self.time))

    def parse(self):
        url = 'http://www.neopets.com/stockmarket.phtml?type=list&full=true'
        resp = self.get(url)
        soup = bs4.BeautifulSoup(resp.text, 'lxml')
        table = soup.findAll('table')[7]
        for row in table.find_all('tr')[1:]:
            cells = row.find_all('td')
            self.stock_list.append({'ticker': cells[1].string.strip(),
                                    'link': cells[1].string.strip(),
                                    'volume': cells[3].string.strip(),
                                    'open': cells[4].string.strip(),
                                    'curr': cells[5].string.strip(),
                                    'change': cells[6].string.strip(),
                                    'time': time.time()})
        return self.stock_list

    def determine_lowest(self):
        negative_stocks = []
        for stocks in self.stock_list:
            if '-' in stocks['change']:
                if int(stocks['volume']) >= 1000:
                    if int(stocks['change']) >= 30:
                        negative_stocks.append(stocks)
            if len(negative_stocks) == 0:
                 pass
            else:
                self.lowest_stock = negative_stocks[0]
                print('{}: Stock Trade - Lowest stock found "{}"'.format(
                    self.time, self.lowest_stock))
                return self.lowest_stock

            if len(negative_stocks) > 1:
                lowest_stock = negative_stocks[0][1]
                if float(negative_stocks[1]) > float(lowest_stock[1]):
                    self.lowest_stock = stocks
                    print('{}: Stock Trade - Lowest stock found "{}"'.format(
                        self.time, self.lowest_stock))
                return self.lowest_stock

def main():
    NeoSession()
    TradeStocks()

if __name__ == '__main__':
    main()


from django.urls import path

from .views import (ModificationListView, ModificationDetailView, ModificationUpdateView,
                    ModificationCreateView, ModificationDeleteView, )

app_name = 'modification'
urlpatterns = [
    path('', ModificationListView.as_view(), name='list'),
    path('dropdown/', ModificationListView.as_view(
        template_name='modification/includes/modification_dropdown.html'),
         name='dropdown_list'),
    path('<int:pk>/', ModificationDetailView.as_view(), name='detail'),
    path('<int:pk>/update/', ModificationUpdateView.as_view(), name='update'),
    path('create/', ModificationCreateView.as_view(), name='create'),
    path('create/modal/', ModificationCreateView.as_view(
            template_name='modification/modification_create_modal.html'),
         name='create_modal'),
    path('<int:pk>/delete/', ModificationDeleteView.as_view(), name='delete'),
]


import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FormatStrFormatter
from os import path

ABS_PATH = path.dirname(path.realpath(__file__))

def read_data(choosenFile):
    frame = None
    read_path = path.join(ABS_PATH, 'stat_data', choosenFile)
    if path.exists(read_path):
        frame = pd.read_csv(read_path)
    return frame

#DrawHist- Draws a Histogram that includes more labels along the x-axis such as the values at the edge of each bar, the percentage of buddies in the bar
#and the value at the center of each bar
#The bars will also be coloured depending upon the side of the graph
#data_set is the data the graph will use *****Buddies are currently always on the Y axis****** The Ylabel is the label for the Y axis

def DrawHist(data_set, title, yLabel):
    fig, ax = plt.subplots()
    counts, bins, patches = ax.hist(data_set, facecolor='yellow', edgecolor='gray')
    plt.title(title)
    plt.ylabel(yLabel)
    # Set the ticks to be at the edges of the bins.
    ax.set_xticks(bins)
    # Set the xaxis's tick labels to be formatted with 1 decimal place...
    ax.xaxis.set_major_formatter(FormatStrFormatter('%0.1f'))

    # Change the colors of bars at the edges...
    twentyfifth, seventyfifth = np.percentile(data_set, [25, 75])
    for patch, rightside, leftside in zip(patches, bins[1:], bins[:-1]):
        if rightside < twentyfifth:
            patch.set_facecolor('green')
        elif leftside > seventyfifth:
            patch.set_facecolor('red')

    # Label the raw counts and the percentages below the x-axis...
    bin_centers = 0.5 * np.diff(bins) + bins[:-1]
    for count, x in zip(counts, bin_centers):
        # Label the raw counts
        ax.annotate(str(count), xy=(x, 0), xycoords=('data', 'axes fraction'),
            xytext=(0, -18), textcoords='offset points', va='top', ha='center')

        # Label the percentages
        percent = '%0.0f%%' % (100 * float(count) / counts.sum())
        ax.annotate(percent, xy=(x, 0), xycoords=('data', 'axes fraction'),
        xytext=(0, -32), textcoords='offset points', va='top', ha='center')

    # Give ourselves some more room at the bottom of the plot
    plt.subplots_adjust(bottom=0.15)
    plt.show()

def total_population_time(frame):
    x = np.zeros(frame['ticks'][0])
    y = np.zeros(frame['ticks'][0])
    for i in range(x.size):
        x[i] = i
        for j in range(len(frame.index)):
            age = frame['age'][j]
            birth = frame['birth_tick'][j]
            # If alive at time tick
            if birth <= i and age + birth+1 >= i:
                y[i] += 1
    fig, ax = plt.subplots()
    ax.plot(x, y, label='Total Population')
    ax.grid()
    ax.legend()
    ax.set(xlabel='Time Ticks', ylabel='Population', title='Total Population/Time')
    plt.show()

def species_population_time(frame):
    x = np.zeros(frame['ticks'][0])
    y_tot = np.zeros(frame['ticks'][0])
    y_evil = np.zeros(frame['ticks'][0])
    y_neutral = np.zeros(frame['ticks'][0])
    for i in range(x.size):
        x[i] = i
        for j in range(len(frame.index)):
            age = frame['age'][j]
            birth = frame['birth_tick'][j]
            # If alive at time tick
            if birth <= i and age + birth+1 >= i:
                y_tot[i] += 1
                if frame['type'][j] == 'ObjectType.NEUTRAL':
                    y_neutral[i] += 1
                else:
                    y_evil[i] += 1
    fig, ax = plt.subplots()
    ax.plot(x, y_tot, label='Total')
    ax.plot(x, y_evil, label='Carnivore')
    ax.plot(x, y_neutral, label='Herbivore')
    ax.grid()
    ax.set(xlabel='Time Ticks', ylabel='Population', title='Population/Time')
    ax.legend()
    plt.show()

def total_stats_time(frame):
    x = np.zeros(frame['ticks'][0])
    speed = np.zeros(frame['ticks'][0])
    agility = np.zeros(frame['ticks'][0])
    intelligence = np.zeros(frame['ticks'][0])
    endurance = np.zeros(frame['ticks'][0])
    strength = np.zeros(frame['ticks'][0])
    fertility = np.zeros(frame['ticks'][0])
    bite_size = np.zeros(frame['ticks'][0])

    for i in range(x.size):
        x[i] = i
        num_alive = 0
        for j in range(len(frame.index)):
            age = frame['age'][j]
            birth = frame['birth_tick'][j]
            # If alive at time tick
            if birth <= i and age + birth+1 >= i:
                num_alive += 1
                speed[i] += frame['speed'][j]
                agility[i] += frame['agility'][j]
                intelligence[i] += frame['intelligence'][j]
                endurance[i] += frame['endurance'][j]
                strength[i] += frame['strength'][j]
                fertility[i] += frame['fertility'][j]
                bite_size[i] += frame['bite_size'][j]
        if num_alive != 0:
            speed[i] /= num_alive
            agility[i] /= num_alive
            intelligence[i] /= num_alive
            endurance[i] /= num_alive
            strength[i] /= num_alive
            fertility[i] /= num_alive
            bite_size[i] /= num_alive

    fig, ax = plt.subplots()
    ax.plot(x, speed, label='Speed Average')
    ax.plot(x, agility, label='Agility Average')
    ax.plot(x, intelligence, label='Intelligence Average')
    ax.plot(x, endurance, label='Endurance Average')
    ax.plot(x, strength, label='Strength Average')
    ax.plot(x, fertility, label='Fertility Average')
    ax.plot(x, bite_size, label='Bite Size Average')
    ax.grid()
    ax.set(xlabel='Time Ticks', ylabel='Average Stat Totals', title='Total Stats Average/Time')
    ax.legend(loc="right", bbox_to_anchor=(1.6,.5))
    plt.show()

def species_stats_time(frame):
    x = np.zeros(frame['ticks'][0])
    evil_speed = np.zeros(frame['ticks'][0])
    evil_agility = np.zeros(frame['ticks'][0])
    evil_intelligence = np.zeros(frame['ticks'][0])
    evil_endurance = np.zeros(frame['ticks'][0])
    evil_strength = np.zeros(frame['ticks'][0])
    evil_fertility = np.zeros(frame['ticks'][0])
    evil_bite_size = np.zeros(frame['ticks'][0])

    neutral_speed = np.zeros(frame['ticks'][0])
    neutral_agility = np.zeros(frame['ticks'][0])
    neutral_intelligence = np.zeros(frame['ticks'][0])
    neutral_endurance = np.zeros(frame['ticks'][0])
    neutral_strength = np.zeros(frame['ticks'][0])
    neutral_fertility = np.zeros(frame['ticks'][0])
    neutral_bite_size = np.zeros(frame['ticks'][0])

    for i in range(x.size):
        x[i] = i
        evil_alive = 0
        neutral_alive = 0
        for j in range(len(frame.index)):
            age = frame['age'][j]
            birth = frame['birth_tick'][j]
            # If alive at time tick
            if birth <= i and age + birth+1 >= i:
                if frame['type'][j] == 'ObjectType.NEUTRAL':
                    neutral_alive += 1
                    neutral_speed[i] += frame['speed'][j]
                    neutral_agility[i] += frame['agility'][j]
                    neutral_intelligence[i] += frame['intelligence'][j]
                    neutral_endurance[i] += frame['endurance'][j]
                    neutral_strength[i] += frame['strength'][j]
                    neutral_fertility[i] += frame['fertility'][j]
                    neutral_bite_size[i] += frame['bite_size'][j]
                else:
                    evil_alive += 1
                    evil_speed[i] += frame['speed'][j]
                    evil_agility[i] += frame['agility'][j]
                    evil_intelligence[i] += frame['intelligence'][j]
                    evil_endurance[i] += frame['endurance'][j]
                    evil_strength[i] += frame['strength'][j]
                    evil_fertility[i] += frame['fertility'][j]
                    evil_bite_size[i] += frame['bite_size'][j]
        if neutral_alive != 0:
            neutral_speed[i] /= neutral_alive
            neutral_agility[i] /= neutral_alive
            neutral_intelligence[i] /= neutral_alive
            neutral_endurance[i] /= neutral_alive
            neutral_strength[i] /= neutral_alive
            neutral_fertility[i] /= neutral_alive
            neutral_bite_size[i] /= neutral_alive
        if evil_alive != 0:
            evil_speed[i] /= evil_alive
            evil_agility[i] /= evil_alive
            evil_intelligence[i] /= evil_alive
            evil_endurance[i] /= evil_alive
            evil_strength[i] /= evil_alive
            evil_fertility[i] /= evil_alive
            evil_bite_size[i] /= evil_alive

    fig, ax = plt.subplots()
    ax.plot(x, evil_speed, 'b-', label='Average Carnivore Speed')
    ax.plot(x, evil_agility, 'g-', label='Average Carnivore Agility')
    ax.plot(x, evil_intelligence, 'r-', label='Average Carnivore Intelligence')
    ax.plot(x, evil_endurance, 'c-', label='Average Carnivore Endurance')
    ax.plot(x, evil_strength, 'm-', label='Average Carnivore Strength')
    ax.plot(x, evil_fertility, 'y-', label='Average Carnivore Fertility')
    ax.plot(x, evil_bite_size, 'k-', label='Average Carnivore Bite Size')

    ax.plot(x, neutral_speed, 'b--', label='Average Herbivore Speed')
    ax.plot(x, neutral_agility, 'g--', label='Average Herbivore Agility')
    ax.plot(x, neutral_intelligence, 'r--', label='Average Herbivore Intelligence')
    ax.plot(x, neutral_endurance, 'c--', label='Average Herbivore Endurance')
    ax.plot(x, neutral_strength, 'm--', label='Average Herbivore Strength')
    ax.plot(x, neutral_fertility, 'y--', label='Average Herbivore Fertility')
    ax.plot(x, neutral_bite_size, 'k--', label='Average Herbivore Bite Size')
    ax.grid()
    ax.legend(loc="right", bbox_to_anchor=(1.6,.5))
    ax.set(xlabel='Time Ticks', ylabel='Average Species Stat Totals', title='Average Species Stats/Time')
    plt.show()

def species_strength_intel_time(frame):
    x = np.zeros(frame['ticks'][0])
    evil_intelligence = np.zeros(frame['ticks'][0])
    evil_strength = np.zeros(frame['ticks'][0])

    neutral_intelligence = np.zeros(frame['ticks'][0])
    neutral_strength = np.zeros(frame['ticks'][0])

    for i in range(x.size):
        x[i] = i
        evil_alive = 0
        neutral_alive = 0
        for j in range(len(frame.index)):
            age = frame['age'][j]
            birth = frame['birth_tick'][j]
            # If alive at time tick
            if birth <= i and age + birth+1 >= i:
                if frame['type'][j] == 'ObjectType.NEUTRAL':
                    neutral_intelligence[i] += frame['intelligence'][j]
                    neutral_strength[i] += frame['strength'][j]
                else:
                    evil_intelligence[i] += frame['intelligence'][j]
                    evil_strength[i] += frame['strength'][j]
        if neutral_alive != 0:
            neutral_intelligence[i] /= neutral_alive
            neutral_strength[i] /= neutral_alive
        if evil_alive != 0:
            evil_intelligence[i] /= evil_alive
            evil_strength[i] /= evil_alive

    fig, ax = plt.subplots()
    ax.plot(x, evil_intelligence, 'b-', label='Carnivore Average Intelligence')
    ax.plot(x, evil_strength, 'g-', label='Carnivore Average Strength')

    ax.plot(x, neutral_intelligence, 'b--', label='Herbivore Average Intelligence')
    ax.plot(x, neutral_strength, 'g--', label='Herbivore Average Strength')
    ax.grid()
    ax.legend()
    ax.set(xlabel='Time Ticks', ylabel='Average Strength & Intelligence', title='Average Strength & Intelligence/Time')
    plt.show()

def run_analysis():
    frame = read_data('agent_data.csv')
    herb_frame = read_data('herb_agent_data.csv')
    carn_frame = read_data('carn_agent_data.csv')
    #total_population_time(frame)
    species_population_time(frame)
    # total_stats_time(frame)
    # species_stats_time(frame)
    # species_strength_intel_time(frame)

    """
    if frame is not None:
        DrawHist(frame.loc[:, 'health'], "Health of Buddies", "Number of Buddies")
        DrawHist(frame.loc[:, 'score'], "Buddy Scores", "Number of Buddies")
        DrawHist(frame.loc[:, 'energy'], "Remaining Buddy Energy", "Number of Buddies")
        DrawHist(frame.loc[:, 'age'], "Buddy Age", "Number of Buddies")
        DrawHist(frame.loc[:, 'children'], "Number of Children", "Number of Buddies")
        DrawHist(frame.loc[:, 'speed'], "Buddy Speed", "Number of Buddies")
        DrawHist(frame.loc[:, 'agility'], "Buddy Agility", "Number of Buddies")
        DrawHist(frame.loc[:, 'intelligence'], "Buddy Intelligence", "Number of Buddies")
        DrawHist(frame.loc[:, 'strength'], "Buddy Strength", "Number of Buddies")
        DrawHist(frame.loc[:, 'fertility'], "Buddy Fetility", "Number of Buddies")

    if carn_frame is not None:

        DrawHist(carn_frame.loc[:, 'speed'], "Carnivore Speed", "Number of Carnivores")
        DrawHist(carn_frame.loc[:, 'agility'], "Carnivore Agility", "Number of Carnivores")
        DrawHist(carn_frame.loc[:, 'intelligence'], "Carnivore Intelligence", "Number of Carnivores")
        DrawHist(carn_frame.loc[:, 'strength'], "Carnivore Strength", "Number of Carnivores")
        DrawHist(carn_frame.loc[:, 'fertility'], "Carnivore Fetility", "Number of Carnivores")
        DrawHist(carn_frame.loc[:, 'gene_stability'], "Carnivore Gene Stablitiy", "Number of Carnivores")
        DrawHist(carn_frame.loc[:, 'bite_size'], "Carnivore Bite Size", "Number of Carnivores")

    if herb_frame is not None:
        DrawHist(herb_frame.loc[:, 'speed'], "Herbivore Speed", "Number of Herbivores")
        DrawHist(herb_frame.loc[:, 'agility'], "Herbivore Agility", "Number of Herbivores")
        DrawHist(herb_frame.loc[:,'intelligence'], "Herbivore Intelligence", "Number of Herbivores")
        DrawHist(herb_frame.loc[:, 'strength'], "Herbivore Strength", "Number of Herbivores")
        DrawHist(herb_frame.loc[:, 'fertility'],"Herbivore Fertility", "Number of Herbivores")
        DrawHist(herb_frame.loc[:, 'gene_stability'], "Herbivore Gene Stablitiy", "Number of Herbivores")
        DrawHist(herb_frame.loc[:, 'bite_size'], "Herbivore Bite Size", "Number of Herbivores")
    """
run_analysis()


"""Given a binary tree and a number ‘S’, find all paths in the tree such that the sum of all
the node values of each path equals ‘S’. Please note that the paths can start or end at any
node but all paths must follow direction from parent to child (top to bottom)"""

from trees import TreeNode, build_binary_tree
from typing import List

def count_paths(root: TreeNode, target: int) -> int:
    count = {'count': 0}

    def helper(root: TreeNode, target: int, current_path: List[int]) -> None:
        if not root:
            return
        i = 0
        if current_path:
            while target < root.val:
                target += current_path[i]
                i += 1
            if target == root.val:
                count['count'] += 1
        target -= root.val
        current_path = current_path[i+1:] if i != 0 else current_path
        helper(root.left, target, current_path + [root.val])
        helper(root.right, target, current_path + [root.val])

    helper(root, target, [])
    return count['count']

if __name__ == '__main__':
    root = build_binary_tree([12, 7, 1, None, 4, 10, 5])
    print(count_paths(root, 6))


import numpy as np
import random
from DATT.python_utils import plotu, polyu
from DATT.refs.base_ref import BaseRef

class PolyRef(BaseRef):
    def __init__(self, altitude, use_y=False, t_end=10.0, degree=3, seed=2023, env_diff_seed=False, fixed_seed=False):
        assert degree % 2 == 1

        self.altitude = altitude
        self.degree = degree
        self.t_end = t_end
        self.use_y = use_y
        self.seed = seed
        self.fixed_seed = fixed_seed
        self.env_diff_seed = env_diff_seed
        self.reset_count = 0

        np.random.seed(seed)
        self.reset()

    def generate_coeff(self):
        b = np.random.uniform(-1, 1, size=(self.degree + 1, ))
        b[0] = 0
        b[(self.degree + 1) // 2] = 0

        A = polyu.deriv_fitting_matrix(self.degree + 1, self.t_end)

        return np.linalg.solve(A, b)[::-1]

    def reset(self):
        if self.fixed_seed:
            np.random.seed(self.seed)
        elif self.env_diff_seed and self.reset_count > 0:
            np.random.seed(random.randint(0, 1000000))

        self.x_coeff = self.generate_coeff()
        if self.use_y:
            self.y_coeff = self.generate_coeff()

        self.reset_count += 1

    def pos(self, t):
        x = np.polyval(self.x_coeff, t)
        if self.use_y:
            y = np.polyval(self.y_coeff, t)
        else:
            y = t*0
        return np.array([
            x,
            y,
            t*0 + self.altitude
    ])

    def vel(self, t):
        x = np.polyval(np.polyder(self.x_coeff), t)
        if self.use_y:
            y = np.polyval(np.polyder(self.y_coeff), t)
        else:
            y = t*0
        return np.array([
            x,
            y,
            t*0
            ])

    def acc(self, t):
        x = np.polyval(np.polyder(self.x_coeff, 2), t)
        if self.use_y:
            y = np.polyval(np.polyder(self.y_coeff, 2), t)
        else:
            y = t*0
        return np.array([
            x,
            y,
            t*0
        ])

    def jerk(self, t):
        x = np.polyval(np.polyder(self.x_coeff, 3), t)
        if self.use_y:
            y = np.polyval(np.polyder(self.y_coeff, 3), t)
        else:
            y = t*0
        return np.array([
            x,
            y,
            t*0
        ])

    def snap(self, t):
        x = np.polyval(np.polyder(self.x_coeff, 4), t)
        if self.use_y:
            y = np.polyval(np.polyder(self.y_coeff, 4), t)
        else:
            y = t*0
        return np.array([
            x,
            y,
            t*0
        ])

    def yaw(self, t):
        if isinstance(t, np.ndarray):
            y = np.zeros_like(t)
            # y[(t // self.T) % 2 == 0] = 0
            # y[(t // self.T) % 2 == 1] = np.pi
        else:
            return 0
            # if (t // self.T) % 2 == 0:
            #     return 0
            # else:
            #     return np.pi
        return y

    def yawvel(self, t):
        return np.array([
            t*0,
            t*0,
            t*0
        ])

    def yawacc(self, t):
        return np.array([
            t*0,
            t*0,
            t*0
        ])

if __name__ == '__main__':
    import matplotlib.pyplot as plt

    ref = PolyRef(altitude=1.0, use_y=True, t_end=10.0, degree=3)
    t = np.linspace(0, 10, 500)

    plt.subplot(2, 1, 1)
    plt.plot(t, ref.pos(t)[0, :], label='x')
    plt.subplot(2, 1, 2)
    plt.plot(t, ref.pos(t)[1, :], label='y')
    plt.show()


import numpy as np
# some users might not install torch at the first place
#import torch # optional import

class ReplayBuffer:
    """Fixed-size buffer to store experience tuples."""

    def __init__(self, state_size, action_size, action_type, buffer_size=int(1e5), batch_size=128, seed=0,\
                 no_reward_value    = 0.0,\
                 no_reward_dropout  = 0.0,\
                 pytorch_device     = None):
        """Initialize a ReplayBuffer object.

        Params
        ======
            state_size  (int): dimension of state vector
            action_size (int): dimension of action vector ( 1 for simple DQN)
            action_type (int): np.float32 for DDPG   np.int8 or np.int32 for DQN
            buffer_size (int): maximum size of buffer
            batch_size  (int): size of each training batch
            seed (int): random seed
            pytorch_device: torch.device("cuda:0" if use_cuda else "cpu")
        """
        self.state_size  = state_size
        self.action_size = action_size
        self.action_type = action_type
        self.batch_size  = batch_size
        self.buffer_size = buffer_size
        self.seed        = seed
        self.rand        = np.random.default_rng(seed)
        self.no_reward_value   = no_reward_value
        self.no_reward_dropout = no_reward_dropout
        self.pytorch_device = pytorch_device
        self.states      = np.empty((self.buffer_size,self.state_size),  dtype=np.float32)
        self.actions     = np.empty((self.buffer_size,self.action_size), dtype=action_type)
        self.rewards     = np.empty((self.buffer_size,1),                dtype=np.float32)
        self.next_states = np.empty((self.buffer_size,self.state_size),  dtype=np.float32)
        self.dones       = np.empty((self.buffer_size,1),                dtype=np.float32)

        self.res_states      = np.empty((self.batch_size,self.state_size),  dtype=np.float32)
        self.res_actions     = np.empty((self.batch_size,self.action_size), dtype=action_type)
        self.res_rewards     = np.empty((self.batch_size,1),                dtype=np.float32)
        self.res_next_states = np.empty((self.batch_size,self.state_size),  dtype=np.float32)
        self.res_dones       = np.empty((self.batch_size,1),                dtype=np.float32)
        self.reset()

    def clone(self):
        return ReplayBuffer(state_size=self.state_size, action_size=self.action_size, action_type=self.action_type,\
        buffer_size=self.buffer_size, batch_size=self.batch_size, seed=self.seed,\
        no_reward_value=self.no_reward_value, no_reward_dropout=self.no_reward_dropout,\
        pytorch_device=self.pytorch_device)

    def reset(self):
        self.current_len = 0
        self.count_entered_no_reward = 0

    def __iadd__(self, other):
        for i in range(min(other.current_len,other.buffer_size)):
            self.add(other.states[i,:],other.actions[i,:],other.rewards[i,0],other.next_states[i,:],other.dones[i,0])
        return self # must return this object or else it will be destoryed

    def add(self, state, action, reward, next_state, done):
        """Add a new experience to memory."""
        if not done and (abs(reward) < 1e-8):
            no_reward_dropout = self.count_entered_no_reward * self.no_reward_dropout / (self.current_len + 1)
            if (no_reward_dropout > 0.0) and (self.rand.uniform() < no_reward_dropout):
                return
            self.count_entered_no_reward += 1
            reward = self.no_reward_value
        ind_pos                     = self.current_len % self.buffer_size
        self.current_len           += 1
        self.states[ind_pos,:]      = state
        self.actions[ind_pos,:]     = action
        self.rewards[ind_pos][0]    = reward
        self.next_states[ind_pos,:] = next_state
        self.dones[ind_pos][0]      = done

    def sample(self):
        """Randomly sample a batch of experiences from memory."""
        curr_len = min(self.current_len,self.buffer_size)
        if curr_len < self.batch_size:
            return None

        indexes       =  self.rand.choice(range(curr_len), size=self.batch_size,replace=False)

        self.res_states[:]      = self.states[indexes,:]
        self.res_actions[:]     = self.actions[indexes,:]
        self.res_rewards[:]     = self.rewards[indexes,:]
        self.res_next_states[:] = self.next_states[indexes,:]
        self.res_dones[:]       = self.dones[indexes,:]
        if self.pytorch_device is None:
            # not using pytorch
            return (self.res_states, self.res_actions, self.res_rewards, self.res_next_states, self.res_dones)

        # using pytorch
        import torch # import for this scope only
        states      = torch.from_numpy(self.res_states).float().to(self.pytorch_device)
        if self.action_type == np.float32:
            actions = torch.from_numpy(self.res_actions).float().to(self.pytorch_device)
        else:
            actions = torch.from_numpy(self.res_actions).long().to(self.pytorch_device)
        rewards     = torch.from_numpy(self.res_rewards).float().to(self.pytorch_device)
        next_states = torch.from_numpy(self.res_next_states).float().to(self.pytorch_device)
        dones       = torch.from_numpy(self.res_dones).float().to(self.pytorch_device)
        return (states, actions, rewards, next_states, dones)


# coding: utf-8
'''
Functions which call VSDebugConnector Add-In API for expression evaluation
in VS debugger.
'''

import os
import socket
import tempfile
import re

class ReqType:
    VALUE = 1
    TYPE = 2
    MEMBERS = 3
    ALL = 4

class RespType:
    ERROR = 1
    VALUE = 2
    ARRAY = 3

BEL = '\x07'
PORT_FNAME = 'vsdbg.port'

_port = 0
_host = "localhost"

def _dbg_call(tp, expr):
    global _host, _port
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((_host, _port))
    s.sendall('%d%s%s' % (tp, BEL, expr))
    res = s.recv(4096)
    s.close()
    res = res.split(BEL)
    if len(res) < 2:
        raise Exception('Invalid respose')
    if int(res[0]) == RespType.ERROR:
        raise Exception(res[1])
    elif int(res[0]) == RespType.ARRAY:
        return res[1:]
    else:
        return res[1]

def detect():
    ''' Get port number from temp file '''
    port_fname = os.path.join(tempfile.gettempdir(), PORT_FNAME)
    if os.path.exists(port_fname):
        with open(port_fname) as f:
            global _port
            _port = int(f.readlines()[0])
    else:
        raise Exception('Could not find port number. Please load/realod \
            VS add-in.')

try:
    detect()  # call detect during module loading
except Exception as e:
    print(e)

def port(p):
    global _port
    _port = p

def host(h):
    global _host
    _host = h

def p(expr):
    ''' retrieves expression with all memebers '''
    return _dbg_call(ReqType.ALL, expr)

def v(expr):
    ''' retrieves expression's value '''
    return _dbg_call(ReqType.VALUE, expr)

def t(expr):
    ''' retrieves expression's type '''
    return _dbg_call(ReqType.TYPE, expr)

def m(expr):
    ''' retrieves list of expression's members '''
    return _dbg_call(ReqType.MEMBERS, expr)

def enum_array(expr):
    val = int(re.search('\d+', v(expr)).group(0))
    for x in range(0, val):
        yield '%s[%d]' % (expr, x)

__RE_CLASS_NAME = '[A-Za-z_][\w\.<>,]+'

def __cast_expr(expr, type):
    return "((%s)%s)" % (type, expr)

def __get_base_type(expr):
    for x in m(expr):
        v = re.search('base {(%s)}' % __RE_CLASS_NAME, x)
        if v:
            return v.group(1)

def __get_types(expr):
    def get_types_rec(expr, tp):
        bt = __get_base_type(__cast_expr(expr, tp))
        if bt:
            yield bt
            for x in get_types_rec(expr, bt):
                yield x
    tp = t(expr)
    v = re.search('{(%s)}' % __RE_CLASS_NAME, tp)
    if v:
        tp = v.group(1)
    yield tp
    for x in get_types_rec(expr, tp):
        yield x

def __get_generic_subtypes(expr):
    bt = __get_base_type('%s, raw' % expr)
    if bt:
        v = re.search('<(%s)>' % __RE_CLASS_NAME, bt)
        return (v.group(1) if v else '')

def __is_type(expr, tp):
    bt = __get_base_type('%s, raw' % expr)
    return bt and tp in bt

def __split_indexer(expr):
    ''' splits string as 'xxx[000]' to 'xxx', '[000]' '''
    s = expr.split('[')
    return '['.join(s[:-1]), '[' + s[-1]

def __dump(expr, level, depth):
    def loop_members(e):
        for x in [i.strip() for i in m(e)]:
            if x == '' or x == 'Raw View' or 'base ' in x:  # skip "Raw View", "base {class_name}"
                continue
            elif x[0] == '[':  # [???]
                if x[1] == '0':  # handle index [0x0???] (and skip [class_name] memebers)
                    yield __dump('%s%s' % (e, x), level + 1, depth - 1)
            else:
                yield __dump('%s.%s' % (e, x), level + 1, depth - 1)

    def handle_dictionary(expr):
        e, i = __split_indexer(expr)
        if __is_type(e, 'System.Collections.Generic.Dictionary'):
            expr = "(new System.Collections.Generic.Mscorlib_DictionaryDebugView<%s>(%s)).Items%s" % (__get_generic_subtypes(e), e, i)
            val = v(expr)
            return expr, val
        return expr, None

    if depth == 0:
        return '%s : Max depth reached.' % expr
    res = []
    try:
        val = None
        if expr[-1] == ']':  # if we have index access
            expr, val = handle_dictionary(expr)
        val = (v(expr) if not val else val)

        res.append('%s%s: %s' % ('  ' * level,
                   expr.split('.')[-1].split('>')[-1].replace(')', ''), val))

        exps = [__cast_expr(expr, x) for x in __get_types(expr)]  # cast expr to every possible type to access all hidden members
        for e in (exps if len(exps) > 0 else [expr]):
            res += loop_members(e)
    except Exception as e:
        res.append(str(e))
    return '\n'.join(res)

def dump(expr, maxdepth=10):
    ''' retrieves expression and recursively dump all children '''
    return __dump(expr, 0, maxdepth)  # idealy this functionality should be moved to VSDebugConnector


import os
import tensorflow as tf
import numpy as np
import scipy.io as sio
from PIL import Image
from model import*
from DataReader import*
from matplotlib import pyplot as plt
import datetime
from tensorflow.keras.models import load_model
import argparse
import sys

def dice_metric(seg,gt):
    dice = np.sum(seg[gt==1])*2.0 / (np.sum(seg) + np.sum(gt))
    return dice

def predict(data_dir,image_dim,model_dir,with_label):
    ## Loading Trained model ##
    try:
        models = glob.glob(os.path.join(model_dir,'*.h5'))
        latest_model = max(models, key=os.path.getctime)
        model = load_model(latest_model,compile=False)
    except:
         print("Problems in model loading. Check if model exists")
         sys.exit(0)

    ### Saving the predicted images and their corresponding Dice Accuracy with the GT annotations##
    if not os.path.exists('predictions'):
        os.mkdir('predictions')

    if with_label is True:
        test_im,test_labels = load_dataset(data_dir)
        all_dice =[]
        preds = model.predict(test_im, verbose=1)

        for i,(seg,gt) in enumerate(zip(preds,test_labels)):
            all_dice.append(dice_metric(seg,gt))
            seg = np.squeeze(seg)
            seg = seg.astype(np.uint8)
            seg = Image.fromarray(seg)
            seg = seg.resize((512, 512),resample=Image.NEAREST)
            fname = f'predict_{i}.tiff'
            seg.save(os.path.join('predictions',fname))

        fname = os.path.join("predictions","Dice.txt")
        acc_file = open(fname,"w")
        acc_file.write(np.mean(all_dice))
        return "Predicted successfully.Please Check Prediction Directory"
    else:
        test_im = load_dataset(data_dir,isTest=True)
        preds = model.predict(test_im, verbose=1)
        for i,seg in enumerate(preds):
            seg = np.squeeze(seg)
            seg = seg*255.0
            seg = seg.astype(np.uint8)
            seg = Image.fromarray(seg)
            seg = seg.resize((512, 512),resample=Image.NEAREST)
            fname = f'predict_{i}.tiff'
            seg.save(os.path.join('predictions',fname))
        return "Predicted successfully.Please Check Prediction Directory"

def get_args():
    parser = argparse.ArgumentParser(description='Train the UNet on images and target masks',
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('-dim', '--dimension',metavar='Dim', type=int, default=128,
                        help='Input Image Dimension', dest='dimension')
    parser.add_argument('-d', '--data_dir', dest='data_dir', type=str, default=r"C:\DM\MLops\algea\test",
                        help='Training Data Directory')
    parser.add_argument('-md', '--model_dir', dest='model_dir', type=str, default="chkpoints",
                        help='Percent of the data that is used as validation (0-100)')
    parser.add_argument('-wl', '--with_label', dest='with_label', type=bool, default=True,
                        help='To indicate test dataset has Ground Truth labels or not')

    return parser.parse_args()

if __name__ == "__main__":
    args = get_args()
    try:
        predict( data_dir = args.data_dir,
                 image_dim = args.dimension,
                 model_dir= args.model_dir,
                 with_label = args.with_label)
    except KeyboardInterrupt:
        print('Prediction Inturrepted')
        #logging.info('Training Inturrepted')
        try:
            sys.exit(0)
        except SystemExit:
            os._exit(0)


import matplotlib.pyplot as plt
import pytest
from brian2 import PopulationRateMonitor, units
from brian2.units import *

from meanfield.solvers.MFSolver import MFSolver
from meanfield.zoo.brunel_wang_2001_stp import one_subpopulation
from meanfield.utils import reset_brian2

class TestMF2(object):

    def setup_method(self):
        self.system = one_subpopulation()

    def test_MFSolver(self):
        """Solve for firing rates & voltages with explicit function"""
        up, down, inter = self.system.populations

        up.rate = 1 * Hz
        down.rate = 4 * Hz
        inter.rate = 12 * Hz

        solver = MFSolver.rates_voltages(self.system, solver='simplex', maxiter=1)
        sol = solver.run()
        print(sol)

    def test_graph(self):
        #print(self.system.graph().render('test.png', view=True))
        pass

    @pytest.mark.skip(reason='plotting')
    def test_sim(self):
        reset_brian2()
        up, down, inter = self.system.populations

        # MFState < Eup - rate: 1.055, Eup - v_mean: -0.054, Edown - rate: 4.285, Edown - v_mean: -0.053, I - rate: 11.463, I - v_mean: -0.053 >

        rate_up = PopulationRateMonitor(up.brian2)
        rate_down = PopulationRateMonitor(down.brian2)
        rate_inter = PopulationRateMonitor(inter.brian2)

        net = self.system.collect_brian2_network(rate_up, rate_down, rate_inter)
        net.run(3 * units.second)

        plt.plot(rate_up.t / ms, rate_up.smooth_rate(width=200 * ms) / Hz, label='up')
        plt.plot(rate_down.t / ms, rate_down.smooth_rate(width=200 * ms) / Hz, label='down')
        plt.plot(rate_inter.t / ms, rate_inter.smooth_rate(width=200 * ms) / Hz, label='inter')
        plt.legend()
        plt.show()


import bpy
import mathutils
from pathlib import Path

import random
from anybase import convert
from anyblend import object

############################################################################################
def RandomizeMesh(_objX, _dicMod, **kwargs):
    sModType = _dicMod.get("sType", _dicMod.get("sDTI"))
    lMeshes = _dicMod.get("lMeshes")
    sMesh = random.choice(lMeshes)

    if sMesh not in bpy.data.meshes:
        raise Exception("Mesh '{0}' not found in modifier '{1}'".format(sMesh, sModType))
    _objX.data = bpy.data.meshes[sMesh]

# enddef

############################################################################################
def VoxelRemeshBakeTexture(_objX, _dicMod, **kwargs):
    fRemeshVoxelSize = convert.DictElementToFloat(_dicMod, "fRemeshVoxelSize")
    bRemeshSmoothShade = convert.DictElementToBool(_dicMod, "bRemeshSmoothShade", bDefault=True)
    bDoSmoothSurface = convert.DictElementToBool(_dicMod, "bDoSmoothSurface", bDefault=True)
    iSmoothIterations = convert.DictElementToInt(_dicMod, "iSmoothIterations", iDefault=3)
    fSmoothFactor = convert.DictElementToFloat(_dicMod, "fSmoothFactor", fDefault=0.5)
    iMultiResIterCnt = convert.DictElementToInt(_dicMod, "iMultiResIterations", iDefault=2)
    sLowPolyObjName = convert.DictElementToString(_dicMod, "sLowPolyObjName", sDefault=None, bDoRaise=False)
    lBakedTexRes = convert.DictElementToIntList(_dicMod, "lBakedTexRes", lDefault=[2048, 2048])
    fBakedTexCageExtrusion = convert.DictElementToFloat(_dicMod, "fBakedTexCageExtrusion", fDefault=0.1)
    sTexPath = convert.DictElementToString(_dicMod, "sTexPath", sDefault=None, bDoRaise=False)

    object.VoxelRemesh_BakeTexture(
        _objIn=_objX,
        _fRemeshVoxelSize=fRemeshVoxelSize,
        _bRemeshSmoothShade=bRemeshSmoothShade,
        _bDoSmoothSurface=bDoSmoothSurface,
        _iSmoothIterations=iSmoothIterations,
        _fSmoothFactor=fSmoothFactor,
        _iMultiResIterCnt=iMultiResIterCnt,
        _sLowPolyObjName=sLowPolyObjName,
        _tBakedTexRes=tuple(lBakedTexRes),
        _fBakedTexCageExtrusion=fBakedTexCageExtrusion,
        _pathTex=Path(sTexPath),
    )

# enddef


import argparse

from werkzeug.serving import run_simple
from werkzeug.wsgi import DispatcherMiddleware

from mushi.apps import api, webui

class Command():

    def __init__(self, argv, **kwargs):
        self.argv = argv

    def __call__(self):
        parser = argparse.ArgumentParser(
            prog=self.argv[0],
            description='Manage the Mushi server.')
        subparsers = parser.add_subparsers(dest='subcommand')
        subparsers.required = True

        # create a sub-parser for the run method
        sub = subparsers.add_parser('run', help='run the server')
        sub.add_argument('-p', '--port', dest='port', action='store', type=int, default=5000,
            help='specify the listening port (default: 5000)')
        sub.add_argument('-o', '--host', dest='host', action='store', default='localhost',
            help='specify the hostname to listen on (default: localhost)')
        sub.add_argument('-d', '--debug', dest='debug', action='store_true',
            help='start the server in debug mode')

        args = parser.parse_args(self.argv[1:])
        if args.subcommand == 'run':
            app = DispatcherMiddleware(
                webui.create_app(debug=args.debug),
                {'/api': api.create_app(debug=args.debug)})
            run_simple(args.host, args.port, app, use_reloader=True, use_debugger=True)


from aiogram import types, Dispatcher
import json, string

# ----------------------------------------- ОБЩАЯ ЧАСТЬ ----------------------------------------- #

# Пустой handler обязательно должен быть в самом конце, т.к. хэндлеры читаюстя по порядку
# @dp.message_handler()
async def language_check(message : types.Message):
    if {i.lower().translate(str.maketrans('', '', string.punctuation)) for i in message.text.split(' ')}\
        .intersection(set(json.load(open('cenz.json')))) != set():
            await message.reply('Маты запрещены')
            await message.delete()

def register_handlers_other(dp : Dispatcher):
    dp.register_message_handler(language_check)


import os

from collections import defaultdict

import pdb

import pandas as pd
import numpy as np

import matplotlib as mpl
# set no display
# matplotlib.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns

from .. utils import other as uo
from sklearn.utils import shuffle as skl_shuffle

from sklearn import linear_model
from scipy.special import expit

import logging

mpl.rcParams['font.family'] = 'sans-serif'
mpl.rcParams['font.sans-serif'] = 'DejaVu Sans'
mpl.rcParams['pdf.fonttype'] = 42

def main_log_reg(args, argparser):

    dir_design = os.path.join(args.PATH, args.DESIGN)
    df_design = uo.get_design(args, dir_design)

    df_feature = uo.get_exp(args, args.MATRIX)
    df_feature = df_feature.reindex(df_design["sample"], axis=1)
    df_feature = df_feature[df_design["sample"]]

    num_query = len(np.where(df_design[args.SUBGROUP] == 1)[0])
    query_exp = df_feature.loc[args.ID][:num_query]
    ref_exp = df_feature.loc[args.ID][num_query:]

    X = df_feature.loc[[args.ID]]
    X = X.T
    y = df_design[args.SUBGROUP]

    ########################################################
    #FROM:
    #https://scikit-learn.org/stable/auto_examples/linear_model/plot_logistic.html#sphx-glr-auto-examples-linear-model-plot-logistic-py
    ########################################################
    # Fit the classifier
    clf = linear_model.LogisticRegression(solver="liblinear", C = 1e10, penalty = 'l2', max_iter=1000, class_weight='balanced')
    clf.fit(X, y)

    # and plot the result
    #plt.figure(1, figsize=(4, 3))
    #plt.clf()
    #plt.scatter(X.values.ravel(), y, color='black', zorder=20)
    sns_plot = sns.scatterplot(X.values.ravel(), y, color='black')

    min_x = min(X.values.ravel())
    max_x = max(X.values.ravel())
    print(min_x)
    print(max_x)
    X_test = np.linspace(min_x, max_x, 300)

    loss = expit(X_test * clf.coef_ + clf.intercept_).ravel()
    #plt.plot(X_test, loss, color='red', linewidth=3)
    sns_plot = sns.lineplot(X_test, loss, color='r')#, kwargs=dict(linewidth=3))

    sns_plot.axhline(.5, color='.5')

    #plt.xticks(range(-5, 10))
    #plt.yticks([0, 0.5, 1])
    #plt.ylim(-.25, 1.25)
    #plt.xlim(-4, 10)
    #plt.legend(('Logistic Regression Model', 'Linear Regression Model'),
    #           loc="lower right", fontsize='small')
    #plt.tight_layout()

    fig_dir = os.path.join(args.OUTDIR, "log_reg", args.DESIGN)
    if not os.path.exists(fig_dir):
        os.makedirs(fig_dir)
    fig_file = os.path.join(fig_dir, args.ID + "_log_reg.pdf")
    sns_plot.figure.savefig(fig_file)
    plt.close()


from django.urls import path
from . import views

urlpatterns = [
    path('register/',views.user_register,name = "user_register"),
    path('Add-notes/',views.AddNote,name = "Add_notes"),
    path('Get-notes/',views.GetNotes,name = "Get_notes"),
    path('Get-Metrics/',views.GetMetrics,name = "Get_metrics"),
    path('notes-list/', views.NotesList,name = "notes-list"),
    path('Get-All-notes/',views.GetAllNotes,name = "Get_all_notes"),
    path('Get-recommendation/',views.GetRecommendation,name = "Get_recommendation"),
    path('notes-detail/<str:pk>', views.NotesDetail,name = "notes-detail"),
]


from .user_interface import UserInterface
from .cli import Cli
import platform

cli = Cli()

if platform.machine() == "armv7l":
   gui = None
   active_interface = cli
else:
   try:
      from .gui import Gui
      gui = Gui()
      active_interface = gui
   except ImportError:
      gui = None
      active_interface = cli

suppress_errors = False

def error_decorator(func):
    def print_error(error_msg, details=''):
        global suppress_errors
        if active_interface is gui:
            cli.error(error_msg, details)
            if suppress_errors:
                return
        func(error_msg, details)
    return print_error

def set_suppress_errors(state):
    global suppress_errors
    suppress_errors = state

set_verbose = cli.set_verbose
print_title = cli.print_title
print_message = cli.print_message
print_header = cli.print_header
print_footer = cli.print_footer

info = active_interface.info
error = error_decorator(active_interface.error)
ask = active_interface.ask
ask_value = active_interface.ask_value
select_item = active_interface.select_item
fill_checkbox_list = active_interface.fill_checkbox_list

__all__ = ['print_title', 'print_header', 'print_footer', 'print_message', 'set_verbose',
           'select_item', 'ask', 'ask_value', 'info', 'fill_checkbox_list', 'set_suppress_errors']


from setuptools import setup, find_packages

with open("README.md", "r") as readme_file:
    readme = readme_file.read()

requirements = ['Faker', 'psycopg2-binary']

setup(
    name="models_manager",
    version="1.0.1",
    author="Nikita Filonov",
    author_email="filonov.nikitkaa@gmail.com",
    description="Models Manager",
    long_description=readme,
    long_description_content_type="text/markdown",
    url="https://github.com/Nikita-Filonov/models_manager",
    packages=find_packages(),
    install_requires=requirements,
)


from django.urls import path, include
from . import views

urlpatterns = [
    path('bank-account/', views.bank_account, name='bank-account'),
    path('bank-account-withdraw/', views.bank_account_withdraw, name='bank-account-withdraw'),
    # path('create-entity/', views.create_entity, name='create-entity'),
    # path('create-entity-business/', views.create_entity_business, name='create-entity-business'),
    # path('create-entity-investor/', views.create_entity_investor, name='create-entity-investor'),
    path('dashboard/', views.dashboard, name='dashboard'),
    path('edit-business/', views.edit_business, name='edit-business'),
    path('help-and-support/', views.help_and_support, name='help-and-support'),
    path('invoice/', views.invoice, name='invoice'),
    path('invoice-upload/', views.invoice_upload, name='invoice-upload'),
    path('refer-and-earn/', views.refer_and_earn, name='refer-and-earn'),
    path('transactions/', views.transactions, name='transactions'),
    path('transaction-details/<uuid:pk>', views.transaction_details, name='transaction-details'),
    path('view-details/<int:mode>', views.view_details, name='view-details'),
    path('withdrawal/', views.withdrawal, name='withdrawal'),

]


from pathlib import PureWindowsPath,Path
import os
import readline
from colours import *

##############################################################

path_to_ROMS       = "/media/E_USB/ROMs"
path_to_emulators  = '/mnt/c/Users/LaunchBox/Emulators'

#needed to launch windows shortcut
win_exe = "/mnt/c/Windows/explorer.exe"

win_path_to_ROMS       = "E:\\ROMs"
win_path_to_emulators  = "C:\\Users\\benja\\LaunchBox\\Emulators"

##############################################################

def set_tab_complete_options(options):
    """
    allows user to tab complete inputs
    """

    readline.parse_and_bind("tab: complete")

    def complete(text,state):
        if text:
            results = [s for s in options if s and s.startswith(text)]
        else:
            results = results[:]

        return results[state]

    readline.set_completer(complete)

def find_rom_in_dir(path_to_dir):
    """
    prints & returns the roms within the supplied directory
    """
    repo_list = []
    rom_exts = ['.nds','.gba','.wbfs','.iso','.ISO','.wux','.bin']
    for d in os.listdir(path_to_dir) :
        for rom_ext in rom_exts:
            if rom_ext in d:
                print(' - '+green+str(d)+white)
                repo_list.append(d)

    return repo_list

def print_dirs_in_dir(path_to_dir):
    """
    prints & returns the directories within the supplied directory
    """
    repo_list = []
    for d in os.listdir(path_to_dir) :
        if '.' not in d:
            print(' - '+green+str(d)+white)
            repo_list.append(d)

    return repo_list

def select_emulator(console):
    """
    returns the associated emulator path for  given console
    """
    if console == 'Nintendo DS':
        pass
    if console == 'Nintendo GBA':
        pass
    if console == 'Nintendo Wii':
        emulator =  win_path_to_emulators+"\\Wii\\Dolphin-x64\\Dolphin.exe"
        flags = "-e"
        return emulator,flags
    if console == 'Nintendo Wii U':
        emulator =  win_path_to_emulators+"\\Wii U\\cemu_1.17.4\\Cemu.exe"
        flags = "-g"
        return emulator,flags
    if console == 'Playstation':
        pass
    if console == 'Playstation 2':
        emulator = win_path_to_emulators+"\\PS2\\PCSX2 1.6.0\\pcsx2.exe"
        flags = ""
        return emulator,flags
    if console == 'Playstation 3':
        emulator = win_path_to_emulators+"\\PS3\\rpcs3.exe"
        flags = ""
        return emulator,flags
    if console == 'Playstation Portable':
        pass
    print('emulator not configured yet.')
    exit(0)

def choose_console():
    """
    allows user to pick a console/ dir name
    """
    print('\nConsoles in your library:')
    choice_list = print_dirs_in_dir(path_to_ROMS)
    set_tab_complete_options(choice_list)
    choice = input('\nInput Console you want to play:\n'+input_colour)
    print(''+white)

    if choice == 'exit':
        exit(0)

    if choice in choice_list:
        console = choice
        return console
    else:
        print('not a valid input')
        choose_console()

def choose_game(console):
    """
    ask user to choose the game a preivoulst chosen console
    ,will return path to that rom
    """
    print('\nGames in your {} library:'.format(console))
    choice_list = print_dirs_in_dir(path_to_ROMS+"/"+console)
    set_tab_complete_options(choice_list)
    choice = input('\nInput the game you want to play:\n'+input_colour)
    print(''+white)

    if choice == 'exit':
        exit(0)

    if choice in choice_list:
        game_name = choice.split('.')[0]
        if console == "Playstation 3":
            rom = "PS3_GAME\\USRDIR\\EBOOT.BIN"
        else:
            rom = find_rom_in_dir(path_to_ROMS+"/"+console+"/"+choice)[0]
        game = win_path_to_ROMS+"\\"+console+"\\"+choice + "\\" +rom
        return game,game_name
    else:
        print('not a valid input')
        choose_game()

def make_shortcut(emulator,flags,rom,shortcut_name):
    """
    will generate a windows batch file containing the paths for the emulator
    and rom with the correct emulator flags
    """

    emulator = PureWindowsPath(Path(emulator))
    rom = PureWindowsPath(Path(rom.replace("'","`")))

  #  command  = '"{}" {} "{}"'.format(emulator,flags,game)
    desktop  = win_path_to_desktops + '\\' + shortcut_name+'.lnk'

    ico_check = path_to_ICOS +'/'+ shortcut_name+'.ico'

    if not os.path.exists(ico_check):
        ico_name = win_path_to_ICOS +'\\es_not_found.ico'
    else:
        ico_name = win_path_to_ICOS +'\\'+ shortcut_name +'.ico'

    ico_name = PureWindowsPath(Path(ico_name))

    fcontents = '$WScriptShell = New-Object -ComObject WScript.Shell;$Shortcut = $WScriptShell.CreateShortcut("{}");$Shortcut.TargetPath = \'"{}"\';$ShortCut.Arguments=\'{} "{}"\';$shortcut.IconLocation=\"{}\";$Shortcut.Save()'.format(desktop,emulator,flags,rom,ico_name)
    print(fcontents)
    f = open("make_shortcut.ps1".format(shortcut_name), "w")
    f.write(fcontents)
    f.close()

    ostr = "powershell.exe -ExecutionPolicy Bypass -File make_shortcut.ps1".format(win_exe)
    print(ostr)
    os.system(ostr)

def main_menu():
    """
    main function of this file which acts as an interactive menu call other functions
    """
    print('\nEmulation Station options:')

    console        = choose_console()
    game,game_name = choose_game(console)
    emulator,flags = select_emulator(console)

    make_shortcut(emulator,flags,game,game_name)
    exit(0)

main_menu()

def make_shortcuts_from_list():
    """
    """
    shortcuts = [
                {'emulator':'',
                 'rom' : '',
                 'ico' : ''}]

    for shortcut in shortcuts:
        console  = shortcut['console']
        rom      = shortcut['rom']
        ico      = shortcut['ico']

        make_shortcut(emulator,flags,game,game_name)


import FRQI as frqi
import QPIE as qpie
import var_swap as cal
import numpy as np
from qiskit.circuit.library import QFT
import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams['font.family'] = 'serif'
rcParams['font.sans-serif'] = ['Times']
rcParams['font.size'] = 12

##To use calibration, first empty lists for observations

inits = []
opti_class = []
opti_gd = []
good_g = []

diff_class = []
diff_gd = []

cost_init = []
cost_gd = []
cost_clas = []
cost_g = []

it_clas=[]

his_clas = []
his_q = []

for i in range(1): #number of experience you want

    V_ij = np.random.rand(2,2) #True observation
    g = np.random.rand(2) #True g we want to find
    g = g/np.linalg.norm(g)
    G = np.outer(g,g.T)
    V_ijtilda = G * V_ij #Observed visibilities

    parameters = np.random.rand(2) #random initial gains

    inits.append(parameters)
    good_g.append(g)

    var = cal.swap_calib(V_ij,V_ijtilda)

    cost_init.append(var.cost_function(parameters)) #compute cost for init params
    cost_g.append(var.cost_function(g)) #and for good g

    clas,nit = var.class_opti(parameters) #optimize with classical
    gd = var.grad_desc(parameters) #and with QGD

    # We add to observations the results

    opti_class.append(clas)
    opti_gd.append(gd)
    it_clas.append(nit)

    cost_clas.append(var.cost_function(clas))
    cost_gd.append(var.cost_function(gd))

    diff_class.append(np.abs(clas-g))
    diff_gd.append(np.abs(gd-g))

    his_clas.append(np.abs(clas[0]-g[0]))
    his_clas.append(np.abs(clas[1]-g[1]))
    his_q.append(np.abs(gd[0]-g[0]))
    his_q.append(np.abs(gd[1]-g[1]))

    plt.figure() #plot cost/step for QGD
    plt.xlabel('Step',fontsize=15)
    plt.ylabel('Cost Function', fontsize=15)
    plt.plot(var.steps,var.cost)

#Prints observations
print(inits)
print(opti_class)
print(opti_gd)
print(good_g)
print(diff_class)
print(diff_gd)
print(it_clas)
print(cost_init)
print(cost_clas)
print(cost_gd)
print(cost_g)

print(his_clas)
print(his_q)

counts, bins = np.histogram(his_clas)
plt.figure()

plt.xlabel('% Absolute Error')
plt.ylabel('Counts')

plt.hist(his_clas, bins = bins, color = 'blue', alpha = 0.5, histtype = 'stepfilled')
plt.hist(his_clas, bins = bins, edgecolor = 'blue', alpha = 1.0, histtype = 'step', label='Hybrid')

# counts, bins = np.histogram(his_q)
plt.hist(his_q, bins = bins, color = 'red', alpha = 0.3, histtype = 'stepfilled')
plt.hist(his_q, bins = bins, edgecolor = 'red', alpha = 1.0, histtype = 'step', label = 'QGD')

plt.legend()

plt.show()


import datetime
now = datetime.date.today()
str = now.strftime('%y-%m-%d')
print('now is {0}, {1}'.format(now, str))

birthday = datetime.date(1993, 9, 10)
age = now - birthday
print('days is {0:d}, age is {1:d}'.format(age.days, int(age.days/365)))

import zlib
s = b'hello world hello world'
print('len is {}'.format(len(s)))
t = zlib.compress(s)
print('len compress is {0:d}'.format(len(t)))
print(zlib.crc32(t), zlib.decompress(t))


import json
import numpy as np
import torchvision.transforms.functional as F
import torch
import os
from pathlib import Path
from .utils import get_rays
from torch import Tensor
from typing import Tuple, List, Optional
from PIL import Image
from torch.utils.data import Dataset

class NeRFBlenderDataSet(Dataset):
    def __init__(
        self,
        mode: str,
        data_dir: Path,
        scale: float,
        valid_count: int = -1,
        test_count: int = -1,
        img_list: List[str] = [],
    ):
        """
        Inputs:
            mode: Partition of data to use (train, test, val)
            data_dir: Base directory to get files from
            scale: Image scaling
            valid/test_count: Number of frames to use for validation/test (all if -1)
            img_list: The frames to consider while training
        """
        self.mode = mode
        self.data_dir = data_dir
        self.valid_count = valid_count
        self.test_count = test_count
        self.white_bck = False
        self.img_list = img_list

        with open(data_dir / f"transforms_{mode}.json") as f:
            self.frames = json.load(f)

        # Dimensions of image
        self.w = int(np.floor(800 * scale))
        self.h = int(np.floor(800 * scale))

        # NOTE: Uncomment for center crop
        # self.wc = int(self.w*0.8)
        # self.hc = int(self.h*0.8)

        # Focal length
        self.f = (self.w / 2) * (1 / np.tan(self.frames["camera_angle_x"] / 2))

        # Near and far bounds
        self.near = 2.0
        self.far = 6.0

        # Directions are same in camera coordinates for all
        # NOTE: Uncomment for center crop
        # x, y = torch.meshgrid(torch.arange(self.wc), torch.arange(self.hc), indexing="xy")
        # self.dirs = torch.dstack(
        #     [(x - self.wc / 2) / self.f, -(y - self.hc / 2) / self.f, -torch.ones_like(y)]
        # )
        x, y = torch.meshgrid(torch.arange(self.w), torch.arange(self.h), indexing="xy")
        self.dirs = torch.dstack(
            [(x - self.w / 2) / self.f, -(y - self.h / 2) / self.f, -torch.ones_like(y)]
        )

        # Only sample random rays in train mode
        if self.mode == "train":
            origins = []
            directions = []
            rgbs = []
            for frame in self.frames["frames"]:
                if self.img_list and (
                    not int(os.path.basename(frame["file_path"]).split("_")[1])
                    in self.img_list
                ):
                    continue

                o, d, img = self.gen_from_frame(frame)
                origins.append(o)
                directions.append(d)
                rgbs.append(img)

            self.origins = torch.cat(origins, 0)
            self.directions = torch.cat(directions, 0)
            self.rgbs = torch.cat(rgbs, 0)

    def gen_from_frame(self, frame: dict) -> Tuple[Tensor, Tensor, Tensor]:
        # Generate rays
        mat = torch.Tensor(frame["transform_matrix"])
        o, d = get_rays(mat, self.dirs)
        o = o.reshape(-1, 3)
        d = d.reshape(-1, 3)

        # Get RGB values
        img = Image.open(
            os.path.join(self.data_dir, f"{frame['file_path']}.png")
        ).convert("RGBA")
        bkg = Image.new("RGBA", img.size, (0, 0, 0))
        img = Image.alpha_composite(bkg, img).convert("RGB")
        img = img.resize((self.w, self.h))
        img = F.to_tensor(img).double()

        # NOTE: Uncomment for center crop
        # img = F.center_crop(img, [self.wc, self.hc])

        # NOTE: Uncomment for viewing input image (for debuging)
        # F.to_pil_image(img).save('debug.png')

        img = img.reshape(3, -1).t()
        return o, d, img

    def __getitem__(self, idx: int) -> Tuple[Tensor, Tensor, Tensor, float, float]:
        if self.mode == "train":
            return (
                self.origins[idx],
                self.directions[idx],
                self.rgbs[idx],
                self.near,
                self.far,
            )
        else:
            frame = self.frames["frames"][idx]
            o, d, img = self.gen_from_frame(frame)
            return o, d, img, self.near, self.far

    def __len__(self) -> int:
        if self.mode == "train":
            return self.rgbs.shape[0]
        elif self.mode == "val":
            if self.valid_count < 0:
                return len(self.frames["frames"])
            return self.valid_count
        else:
            if self.test_count < 0:
                return len(self.frames["frames"])
            return self.test_count


import os
import cv2
import click
from pathlib import Path
import numpy as np
from scripts.class_info_manager import ClassInformationManager
from scripts.utils import colorize_mask
from tqdm import tqdm

SCRIPT_DIR = Path(__file__).parent.resolve()

def get_image(file_name, rgb_manager):
    image_bgr = cv2.imread(file_name)
    image = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
    image_undistorted = rgb_manager.correction(image)
    return image_undistorted

def get_image_pathes(input_data_dir):
    image_pathes = sorted([path for path in Path(input_data_dir).glob("*.png")])
    image_path_list = [str(image_path) for image_path in image_pathes]
    return image_path_list

@click.command()
@click.option("--input-data-dir", "-i", default=f"{SCRIPT_DIR}/output")
@click.option("--output-data-dir", "-o", default=f"{SCRIPT_DIR}/mask_colorized")
@click.option("--class-definition-json", "-c", default=f"{SCRIPT_DIR}/cfg/classes.json")
def main(input_data_dir, output_data_dir, class_definition_json):
    class_manager = ClassInformationManager(class_definition_json)
    if not os.path.exists(output_data_dir):
        os.makedirs(output_data_dir)

    label_image_path_list = get_image_pathes(input_data_dir)
    for label_image_path in tqdm(label_image_path_list):
        base_name = Path(label_image_path).name
        label_image = cv2.imread(label_image_path, cv2.IMREAD_ANYDEPTH)
        mask_colorized = colorize_mask(label_image, class_manager)
        mask_colorized_path = str(Path(output_data_dir, base_name))
        cv2.imwrite(mask_colorized_path, mask_colorized)
        cv2.waitKey(10)

if __name__ == "__main__":
    main()


import random
import time

import win32api
import win32con
from pynput.keyboard import Key, Controller

keyboard = Controller()

time.sleep(5)

keyboard.press(Key.ctrl)
keyboard.press('t')
keyboard.release('t')
keyboard.release(Key.ctrl)

time.sleep(1)

keyboard.press(Key.ctrl)
keyboard.press('v')
keyboard.release('v')
keyboard.release(Key.ctrl)

time.sleep(1)

keyboard.press(Key.enter)
keyboard.release(Key.enter)

time.sleep(3)

def type(string):

    for character in string:
        keyboard.type(character)
        delay = random.random() / 3
        time.sleep(delay)

def click(x, y):
    win32api.SetCursorPos((x, y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)

click(500, 420)
type("I better be getting into MIT because of this")
click(400, 400)


import numpy as np
import pandas as pd
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import protein_reconstruction as pr
import rmsd
import os

def plot_distance_statistics(distance_matrix_list,
                             n_bins,
                             title="",
                             savepath="",
                             showfig=True):
    distance_array_list = []
    for matrix in distance_matrix_list:
        distance_array_list.append(matrix.flatten())
    distance_matrix_list = np.concatenate(distance_array_list).ravel()
    plt.hist(distance_matrix_list, bins=n_bins, density=True)
    plt.xlabel("Distanza $[\\AA]$")
    plt.ylabel("Distribuzione di probabilità")
    if title != "":
        plt.title(title)
    if showfig:
        plt.show()
    if savepath != "":
        plt.savefig(savepath, dpi=300)
        plt.clf()

def plot_protein_network(coords_original,
                         distance_matrix,
                         coords_spectral_basic=pd.DataFrame(),
                         spectral_basic_flag=False,
                         coords_modified=pd.DataFrame(),
                         modified_flag=False,
                         drawing_threshold=6,
                         title="",
                         savepath="",
                         showfig=True,
                         view_thet=30,
                         view_phi=30):
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    # Make network to be plotted (low threshold)
    plt_network = pr.make_basic_network_from_distance_matrix(
        distance_matrix, drawing_threshold)
    # Plot original coords
    ax.scatter(coords_original["x"],
               coords_original["y"],
               coords_original["z"],
               label="Originale", c="C0")
    for edge in list(plt_network.edges):
        ax.plot((coords_original.iloc[edge[0]]["x"],
                 coords_original.iloc[edge[1]]["x"]),
                (coords_original.iloc[edge[0]]["y"],
                 coords_original.iloc[edge[1]]["y"]),
                (coords_original.iloc[edge[0]]["z"],
                 coords_original.iloc[edge[1]]["z"]),
                c="grey", alpha=0.7)
    # If any, plot given coords
    if modified_flag:
        # APPLY THE RMSD (you never know...)
        coords_modified = pd.DataFrame(
            rmsd.kabsch_rotate(coords_modified.values, coords_original.values),
            columns=["x", "y", "z"])
        score_modified = rmsd.kabsch_rmsd(
            coords_modified.values, coords_original.values)
        ax.scatter(coords_modified["x"],
                   coords_modified["y"],
                   coords_modified["z"],
                   label="SD Perturbato,\nRMSD = {:.6f}".format(score_modified),
                   c="C1")
        for edge in list(plt_network.edges):
            ax.plot((coords_modified.iloc[edge[0]]["x"],
                     coords_modified.iloc[edge[1]]["x"]),
                    (coords_modified.iloc[edge[0]]["y"],
                     coords_modified.iloc[edge[1]]["y"]),
                    (coords_modified.iloc[edge[0]]["z"],
                     coords_modified.iloc[edge[1]]["z"]),
                    c="red", alpha=0.4)
    # Do you also want the spectral basic?
    if spectral_basic_flag:
        coords_spectral_basic = pd.DataFrame(
            rmsd.kabsch_rotate(coords_spectral_basic.values, coords_original.values),
            columns=["x", "y", "z"])
        score_spectral_basic = rmsd.kabsch_rmsd(
            coords_spectral_basic.values, coords_original.values)
        ax.scatter(coords_spectral_basic["x"],
                   coords_spectral_basic["y"],
                   coords_spectral_basic["z"],
                   label="SD Originale,\nRMSD = {:.6f}".format(score_spectral_basic),
                   c="C2")
        for edge in list(plt_network.edges):
            ax.plot((coords_spectral_basic.iloc[edge[0]]["x"],
                     coords_spectral_basic.iloc[edge[1]]["x"]),
                    (coords_spectral_basic.iloc[edge[0]]["y"],
                     coords_spectral_basic.iloc[edge[1]]["y"]),
                    (coords_spectral_basic.iloc[edge[0]]["z"],
                     coords_spectral_basic.iloc[edge[1]]["z"]),
                    c="green", alpha=0.4)
    ax.legend(loc='right', fontsize='small')
    ax.set_xlabel("X $[\\AA]$")
    ax.set_ylabel("Y $[\\AA]$")
    ax.set_zlabel("Z $[\\AA]$")
    if title != "":
        ax.set_title(title)
    if showfig:
        ax.view_init(view_thet, view_phi)
        plt.show()
    if savepath != "":
        ax.view_init(view_thet, view_phi)
        plt.tight_layout()
        plt.savefig(savepath, dpi=300)
        plt.clf()

def rotational_protein_movie(coords_original,
                             distance_matrix,
                             coords_spectral_basic=pd.DataFrame(),
                             spectral_basic_flag=False,
                             coords_modified=pd.DataFrame(),
                             modified_flag=False,
                             drawing_threshold=8,
                             title="",
                             filename="",
                             view_phi=30,
                             n_frames=360):
    os.system("del \"movie\\foo\\foo*.jpg\"")
    for i, angle in enumerate(np.linspace(0, 360, n_frames, endpoint=False)):
        print(str(i) + "/" + str(n_frames))
        plot_protein_network(coords_original,
                             distance_matrix,
                             coords_spectral_basic,
                             spectral_basic_flag,
                             coords_modified,
                             modified_flag,
                             drawing_threshold,
                             title,
                             ("movie\\foo\\foo" + str(i).zfill(5) + ".jpg"),
                             False,
                             view_phi,
                             angle)
    os.system("ffmpeg -y -i \"movie\\foo\\foo%05d.jpg\" "
              + "movie\\" + filename + ".mp4")


"""
This script aims to test different Pulse-Coupled Neural Network (PCNN) algorithm
Based on :
Zhan, K., Shi, J., Wang, H. et al.
Computational Mechanisms of Pulse-Coupled Neural Networks: A Comprehensive Review.
Arch Computat Methods Eng 24, 573–588 (2017).
https://doi.org/10.1007/s11831-016-9182-3
"""

import os
import numpy as np
import SimpleITK as sitk
import matplotlib.pyplot as plt
from scipy.ndimage import correlate, convolve
from skimage.transform import rescale, rotate
from skimage.util import random_noise
from skimage.filters import median, laplace, gaussian

def PlotArray(Array,Title):

    Figure, Axes = plt.subplots(1, 1, figsize=(5.5, 4.5), dpi=100)
    Axes.imshow(Array, cmap='gray')
    plt.axis('off')
    plt.title(Title)
    plt.tight_layout()
    plt.show()
    plt.close(Figure)

    return
def NormalizeArray(Array):

    N_Array = (Array - Array.min()) / (Array.max()-Array.min())

    return N_Array
def RGB2Gray(RGBImage):
    """
    This function convert color image to gray scale image
    based on matplotlib linear approximation
    """

    R, G, B = RGBImage[:,:,0], RGBImage[:,:,1], RGBImage[:,:,2]
    Gray = 0.2989 * R + 0.5870 * G + 0.1140 * B

    return np.round(Gray).astype('uint8')
def GaussianKernel(Length=5, Sigma=1.):
    """
    Creates gaussian kernel with side length `Length` and a sigma of `Sigma`
    """
    Array = np.linspace(-(Length - 1) / 2., (Length - 1) / 2., Length)
    Gauss = np.exp(-0.5 * np.square(Array) / np.square(Sigma))
    Kernel = np.outer(Gauss, Gauss)
    return Kernel / sum(sum(Kernel))
def CropCenter(Image,CropX,CropY):
    Y, X = Image.shape
    StartX = X//2-(CropX//2)
    StartY = Y//2-(CropY//2)
    return Image[StartY:StartY+CropY,StartX:StartX+CropX]

CurrentDirectory = os.getcwd()
DataDirectory = os.path.join(CurrentDirectory,'Scripts/PCNN/')

Image = sitk.ReadImage(DataDirectory + 'Lena.jpg')
Array = sitk.GetArrayFromImage(Image)
Input = RGB2Gray(Array)
PlotArray(Input,'Input')

S = (Input-Input.min()) / (Input.max()-Input.min()) * 255
S = np.round(S).astype('uint8')

# Algorithm 4, image histogram
Theta = 255
Delta = 1
Vt = 256
Y = np.zeros(S.shape)
H = np.zeros(256)

# Perform analysis
for N in range(256):
    U = S
    Theta = Theta - Delta + Vt * Y
    Y = np.where((U - Theta) > 0, 1, 0)
    H[255 - N] = Y.sum()

npHist, npEdges = np.histogram(S, bins=255)

Figure, Axes = plt.subplots(1, 1, figsize=(5.5, 4.5), dpi=100)
Axes.plot(npEdges[:-1]+0.5,npHist,color=(0,0,1), label='Numpy')
Axes.plot(np.arange(0,256), H,linestyle='none',marker='x',color=(1,0,0), label='PCNN')
plt.legend(loc='best')
plt.tight_layout()
plt.show()
plt.close(Figure)

# Algorithm 5, image segmentation
Input = np.ones((256, 256)) * 230
Input[64:192, 64:192] = 205
Input[:, 128:] = np.round(Input[:, 128:] * 0.5)
PlotArray(Input,'Input')

S = Input
Rows, Columns = S.shape
Y = np.zeros((Rows, Columns))
T = np.zeros((Rows, Columns))
W = GaussianKernel(Length=7, Sigma=1.)
F = S
Beta = 2
Theta = 255 * np.ones((Rows, Columns))
Delta = 1
Vt = 400
FiredNumber = 0
N = 0

while FiredNumber < S.size:

    N += 1
    L = correlate(Y, W, output='float', mode='reflect')
    Theta = Theta - Delta + Vt * Y
    Fire = 1

    while Fire == 1:

        Q = Y
        U = F * (1 + Beta*L)
        Y = (U > Theta) * 1
        if np.array_equal(Q,Y):
            Fire = 0
        else:
            L = correlate(Y, W, output='float', mode='reflect')

    T = T + N*Y
    FiredNumber = FiredNumber + sum(sum(Y))

Output = 256 - T
PlotArray(Output,'Output')

# Algorithm x, feature extraction
def PCNN_Histogram(S):

    Theta = 255
    Delta = 1
    Vt = 256
    Y = np.zeros(S.shape)
    H = np.zeros(256)

    # Perform analysis
    for N in range(256):
        U = S
        Theta = Theta - Delta + Vt * Y
        Y = np.where((U - Theta) > 0, 1, 0)
        H[255 - N] = Y.sum()

    return H
def SpikingCorticalModel(S):

    """
    SCM used for invariant texture retrieval and image processing
    """

    W = np.array([[0.1091, 0.1409, 0.1091],
                  [0.1409, 0,      0.1409],
                  [0.1091, 0.1409, 0.1091]])

    Y = np.zeros(S.shape)
    U = Y
    E = Y + 1

    k = 40
    TS = np.zeros(k)
    for t in range(k):
        U = 0.2 * U + S * correlate(Y, W, output='float', mode='reflect') + S
        E = 0.9 * E + 20 * Y
        X = 1 / (1 + np.exp(E - U))
        Y = (X > 0.5) * 1
        TS[t] = sum(sum(Y))

    return TS

Image = sitk.ReadImage(DataDirectory + 'D12.png')
Array = sitk.GetArrayFromImage(Image)
Input = RGB2Gray(Array)
PlotArray(Input,'Input')

NScaling, NRotation = 2, 3
Figure, Axes = plt.subplots(NScaling*NRotation, 3, figsize=(5.5*NScaling, 4.5*NRotation))
CropY, CropX = np.array(np.array(Input.shape)/2).astype('int')
Line = 0
for Scaling in range(1,NScaling+1):

    ScaledInput = rescale(Input,1/(0.2*Scaling+0.6))

    for Rotation in range(1,NRotation+1):
        RotatedInput = rotate(ScaledInput,Rotation*30-30,resize=True)
        RotatedInput = CropCenter(RotatedInput, CropX, CropY)
        RotatedInput_Normalized = NormalizeArray(RotatedInput)
        H = PCNN_Histogram(RotatedInput_Normalized)
        TS = SpikingCorticalModel(RotatedInput)

        # Plot
        Axes[Line,0].imshow(RotatedInput,cmap='gray')
        Axes[Line,0].set_xticks([])
        Axes[Line,0].set_yticks([])
        Axes[Line,1].plot(H, color=(1, 0, 0))
        Axes[Line,1].set_xticks([])
        Axes[Line,1].set_yticks([])
        Axes[Line,2].plot(TS, color=(1, 0, 0))
        Axes[Line,2].set_xticks([])
        Axes[Line,2].set_yticks([])
        Line += 1
plt.show()
plt.close(Figure)

# Algorithm 6 - Image restoration
Image = sitk.ReadImage(DataDirectory + 'Lena.jpg')
Array = sitk.GetArrayFromImage(Image)
Input = RGB2Gray(Array)
PlotArray(Input,'Input')

Rows, Columns = Input.shape
Size = Input.size

J = random_noise(Input, mode='gaussian', seed=None, clip=True, mean=0, var=0.01)
J = NormalizeArray(J)
PlotArray(J,'Noised')

Input_Median = median(J,mode='reflect')
Input_Median = NormalizeArray(Input_Median)
PlotArray(Input_Median,'Median')
Input_Mean = correlate(J,np.ones((3,3))/9,mode='reflect')
Input_Mean = NormalizeArray(Input_Mean)
PlotArray(Input_Mean,'Mean')

U = np.zeros(Input.shape)
E = U + 1
Y = np.zeros(Input.shape)
B = np.zeros(Input.shape)
T = np.zeros(Input.shape)

f = 0.3
g = 0.99
gamma = 1
N = 0

while sum(sum(B)) < Size:

    N += 1

    for i in range(Rows):
        for j in range(Columns):

            U[i, j] = J[i, j] + f * U[i, j]
            if E[i, j] > 1E2:
                Q = 0
            else:
                Q = 1 / (1 + np.exp(-gamma * (U[i, j] - E[i, j])))

            if Q > 0.5 or E[i, j] < 0.08:
                Y[i, j] = 1
                B[i, j] = 1
                T[i, j] = N
                E[i, j] = 100000
            else:
                Y[i, j] = 0

    E[B != 1] = g * E[B != 1]

S = np.pad(J,1,'symmetric')
T = np.pad(T,1,'symmetric')
I_SCM = np.zeros(Input.shape)
Delta = 0.02

for i in range(1,Rows+1):
    for j in range(1,Columns+1):

        K = T[i-1:i+2,j-1:j+2].flatten()

        if len(np.unique(K)) == 1:
            I_SCM[i-1, j-1] = 1/9 * sum(sum(S[i-1:i+2, j-1:j+2]))
        else:
            Sorted = np.sort(K)

            if Sorted[4] == K[4]:
                I_SCM[i-1, j-1] = S[i, j]
            elif Sorted[0] == K[4]:
                I_SCM[i-1, j-1] = S[i, j] - Delta
            elif Sorted[-1] == K[4]:
                I_SCM[i-1, j-1] = S[i, j] + Delta
            else:
                I_SCM[i-1, j-1] = np.median(S[i-1:i+2, j-1:j+2])
I_SCM = NormalizeArray(I_SCM)
PlotArray(I_SCM,'SCM')

# Algorithm y - Image enhancement (Feature Linking Model FLM)
def GrayStretch(I,Per):

    m, M = FindingMm(I,Per)
    GS = ((I-m) / (M-m) * 255).astype('uint8')

    return GS
def FindingMm(I,Per):
    h = PCNN_Histogram(I)
    All = sum(h)
    ph = h / All
    mth_ceiling = BoundFinding(ph,Per)
    Mph = ph[::-1]
    Mth_floor = BoundFinding(Mph,Per)
    Mth_floor = 256 - Mth_floor + 1
    Difference = np.zeros((256,256)) + np.inf
    for m in range(mth_ceiling,0,-1):
        for M in range(Mth_floor,256):
            if h[m] > 0 and h[M] > 0:
                if np.sum(h[m:M+1]) / All >= Per:
                    Difference[m,M] = M - m

    minD = Difference.min()
    m, M = np.where(Difference == minD)
    minI = m[0]
    MaxI = M[0]

    return [minI,MaxI]
def BoundFinding(ph,Per):
    cumP = np.cumsum(ph)
    n = 1
    residualP = 1 - Per
    while cumP[n-1] < residualP:
        n += 1

    m_ceiling = n

    return m_ceiling
def PCNN_Histogram(S):

    Theta = 255
    Delta = 1
    Vt = 256
    Y = np.zeros(S.shape)
    H = np.zeros(256)

    # Perform analysis
    for N in range(256):
        U = S
        Theta = Theta - Delta + Vt * Y
        Y = np.where((U - Theta) > 0, 1, 0)
        H[255 - N] = Y.sum()

    return H

Image = sitk.ReadImage(DataDirectory + 'Lena.jpg')
Array = sitk.GetArrayFromImage(Image)
Input = RGB2Gray(Array)
PlotArray(Input,'Input')

S = (Input - Input.min()) / (Input.max()-Input.min()) + 1/255
W = np.array([[0.7, 1, 0.7],[1, 0, 1],[0.7, 1, 0.7]])
Y = np.zeros(S.shape)
U = np.zeros(S.shape)
T = np.zeros(S.shape)
SumY = 0
N = 0

Laplacian = np.array([[1/6, 2/3, 1/6],[2/3, -10/3, 2/3],[1/6, 2/3, 1/6]])
Theta = 1 + correlate(S,Laplacian,mode='reflect')
# Theta = 1 + laplace(S,ksize=3)
f = 0.75 * np.exp(-S**2 / 0.16) + 0.05
G = GaussianKernel(7,1)
f = correlate(f, G, mode='reflect')
# f = gaussian(f,sigma=1,mode='reflect')

h = 2E10
d = 2
g = 0.9811
Alpha = 0.01
Beta = 0.03

while SumY < S.size:

    N += 1

    K = correlate(Y,W,mode='reflect')
    Wave = Alpha * K + Beta * S * (K - d)
    U = f * U + S + Wave
    Theta = g * Theta + h * Y
    Y = (U > Theta) * 1
    T += N * Y
    SumY += sum(sum(Y))
    # print(SumY)

T_inv = T.max() + 1 - T
Time = (NormalizeArray(T_inv) * 255).astype('uint8')
Stretched = GrayStretch(Time,0.99)
PlotArray(Stretched,'Output')

Figure, Axes = plt.subplots(1, 1, figsize=(5.5, 4.5), dpi=100)
Axes.hist(Input.flatten()*255, bins=np.arange(0,256), density=True, color=(0,0,1), label='Original')
Axes.hist(Stretched.flatten(), bins=np.arange(0,256), density=True, color=(1,0,0), label='Enhanced')
plt.legend(loc='upper left')
plt.tight_layout()
plt.show()
plt.close(Figure)

H = PCNN_Histogram(Stretched)
Indices = np.where(H == 0)[0]
Suite = np.concatenate([np.diff(Indices),np.array([0])])
Low, High = np.array([0]), np.array([])
i = 0
while i < len(H):
    n = 0
    while H[i+n] == 0:
        n += 1
    if n > 2:
        High = np.concatenate([High,np.array([i])]).astype('int')
        Low = np.concatenate([Low,np.array([i+n-1])]).astype('int')
        i += n
    else:
        i += 1
High = np.concatenate([High,np.array([255])])

Seg = np.zeros(Stretched.shape)
for n in range(len(High)):
    F1 = Stretched > Low[n]
    F2 = Stretched < High[n]
    Seg[F1*F2] = n

a = Seg.copy()
b = np.unique(Seg)
a[a != b[6]] = 100
PlotArray(a,'Seg')