import cv2
import numpy as np
import math
import sys
import struct

#takes a png file with an alpha channel and plots it to a ply file scaled to the subject's known height.
def cudaPlotSilhouette(png, flength, hsense):
    #4 channel RGBA image represented as a numpy array
    #img[r,c] = [b, g, r, a], img[r,c,3] = alpha channel
    img = cv2.imread(png, -1)
    print(str(img))
    plypoints = []
    #traverse array until you find a border pixel, i.e. pixel where any one of the 8 neighbors has an alpha value of 0
    #repeat until you get back to where you started:
        #find neighbor that is also a border pixel
        #append neighbor as array [r,c] to array plypoints
        #handle edge cases / dead ends, but there should be no holes and only one path around the subject

    # Find first pixel with alpha value 1; our starting point
    # Start from top left, going down every coloumn
    first_border = None
    for r in range(0, img.shape[0]):
        for c in range(0, img.shape[1]):

            if img[r,c,3] != 0:
                first_border = (r,c)
                break

        # Exit after finding the first border pixel
        if first_border is not None:
            break
    print("first border pix: " + str(first_border))
    # Case where there is no pixel with alpha value 1
    if first_border is None:
        print("No pixel with alpha value 1!")
        exit()

    # Used to loop through neighbors, counterclockwise
    #row,column, (Y,X)
    #east, southeast, south, southwest, west, northwest, north, northeast
    bd = [[0,1], [-1,1], [-1,0], [-1,-1], [0, -1], [1,-1], [1,0], [1,1]]

    seen_points = set()
    seen_points.add(first_border)
    point_list = []
    point_list.append(first_border)

    curr = first_border

    #Loop until we find first point again.
    while True:
        children = find_border_children(img, curr, bd)

        next = None
        print("looping through children:" + str(children))
        #it loops through all children not in seen_points, and then iterates through it, so it might be going in reverse order
        for i, child in enumerate(children):
            if child not in seen_points:
                #print(str(i) + ": " + str(child))
                # Found next point
                next = child
        # Case where there are no children; we go backwards
        if next is None:

            # Check if we are in range of starting pixel. If we are, then we are done
            if points_in_range(first_border, curr, bd):
                # This line appends the start point again, which i assume should not happen
                # point_list.append(first_border)
                break

            # Edge case where first_border is the only pixel with alpha = 1 in range
            if len(point_list) == 1:
                print("first_border is the only pixel with alpha = 1 in range")
                exit()

            # go back and get rid of last element
            curr = point_list.pop()

        else:
            # Found next point
            # Append and move on to next set of children
            point_list.append(next)
            seen_points.add(next)
            curr = next
            img[next[0],next[1],0] = 0
            img[next[0],next[1],1] = 0
            img[next[0],next[1],2] = 255

    print( "border pixel found: " + str(curr))
    print("point list: ")
    print(str(point_list))
    #cv2.imshow('image', img)
    fileName = "C:\\Users\\Brilliance\\Desktop\\Projects\\Undergrad-Research\\findborder\\result.png"
    cv2.imwrite(fileName,img)
    #pixel size in meters
    pixelsize = hsense / float(img.shape[1])
    centerx = img.shape[1] / 2.0
    centery = img.shape[0] / 2.0

    print(hsense)
    print(img.shape[1])

    # Compute "normal" to each point, store in an array. Each point has two neighbors, normal for point j is the average of the two lines j - i and j - k for consecutive points i, j, k
    size = len(point_list)
    print(size)
    for j in range(0, size):

        # Computing indices in a circular fashion
        i = j-1
        k = j+1
        if j == 0:
            i = size-1
        elif j == size - 1:
            k = 0
        #print str(j) + " , " + str(k)
        # Compute normal
        v_i = np.array([point_list[i][1], point_list[i][0], 0])
        v_j = np.array([point_list[j][1], point_list[j][0], 0])
        v_k = np.array([point_list[k][1], point_list[k][0], 0])

        ji_norm = (v_j - v_i) / np.linalg.norm(v_j - v_i)
        jk_norm = (v_j - v_k) / np.linalg.norm(v_j - v_k)

        avg_norm = (ji_norm + jk_norm)
        length = np.linalg.norm(avg_norm)
        if length != 0.0:
            avg_norm /= np.linalg.norm(avg_norm)
        else:	#straight line, so just make it perpindicular
            avg_norm = v_j - v_i
            a0 = avg_norm[0]
            avg_norm[0] = -avg_norm[1]
            avg_norm[1] = a0
            avg_norm = avg_norm / np.linalg.norm(avg_norm)
        #need to do an inside outside test
        inoutpix = np.array(point_list[j]) + 3 * np.array([avg_norm[1], avg_norm[0]])
        #flip normal if its pointing inside
        inoutpixtrunc = np.rint(inoutpix).astype(np.int32)
        if img[inoutpixtrunc[0], inoutpixtrunc[1], 3] != 0:
            avg_norm*= -1

        #print(avg_norm)
        y = avg_norm[1] * -1.0
        x = avg_norm[0]

        normal = (x,y)
        #print(normal)

        #point_list is an array of tuples (r,c) so the y coordinate is first
        #x, y, z, nx, ny, nz. coordinates are metric in m
        plypoints.append([(point_list[j][1] - centerx) * pixelsize, -1 * (point_list[j][0] - centery) * pixelsize, -flength ,normal[0], normal[1], 0.0])

    # #append joint positions
    # dct = open(sys.argv[7] + '/deepcut_imgcoords', 'wb')
    # for j in range(0, joints.shape[1]):
    #     #1/27/2020 dump the joints to a text file so the C++ routine can read it
    #     dct.write(struct.pack('i', joints[0][j]))
    #     dct.write(struct.pack('i', joints[1][j]))
    #     plypoints.append(np.array([(joints[0][j] - centerx) * pixelsize, -1 * (joints[1][j] - centery) * pixelsize, -flength, 0.0, 0.0, 0.0]))

    plypoints.append([0.0,0.0,0.0, 0.0, 0.0, 0.0])

    #WRITE TO PLY FILE IN ASCII, don't worry about the shit below
    pointsheader = "ply\nformat ascii 1.0\nelement vertex " + str(len(plypoints)) +"\nproperty float x\nproperty float y\nproperty float z\nproperty float nx\nproperty float ny\nproperty float nz\n"
    edgeheader = "element edge " + str(len(plypoints)-1) + "\nproperty int vertex1\nproperty int vertex2\nproperty uchar red\nproperty uchar green\nproperty uchar blue\nend_header\n"
    plyheader = pointsheader + "end_header\n"  #edgeheader
    plyfile = open("C:\\Users\\Brilliance\\Desktop\Projects\\Undergrad-Research\\findborder\\silhouettes.ply", 'w')
    plyfile.write(plyheader)
    for v in plypoints:
        line = ""
        for f in v:
            line += str(f) + " "
        line = line[:-1]
        line = line + '\n'
        plyfile.write(line)
        #write edge v1 v2 r g b
        #http://paulbourke.net/dataformats/ply/
    return plypoints

# Find neighboring points that are also border pixels
def find_border_children(img, point, bd):
    border_pixels = []
    # Append them in the order starting from above, going counterclockwise.
    for i in range(0,8):
        r = point[0] + bd[i][0]
        c = point[1] + bd[i][1]
        child = (r,c)

        if img[r,c,3] != 0 and is_border_pixel(img, child, bd):
            border_pixels.append(child)

    return border_pixels

def is_border_pixel(img, point, bd):

    # Check if there is a pixel surrounding current point with alpha value = 0
    for i in range(0,8):
        r = point[0] + bd[i][0]
        c = point[1] + bd[i][1]

        # Alpha = 0 so this pixel is a border pixel
        if img[r,c,3] == 0:
            return True

    # No neighbors with alpha = 0
    return False

# Check whether p2 is 1 away from p1
def points_in_range(p1, p2, bd):

    for i in range(0,8):
        r = p2[0] + bd[i][0]
        c = p2[1] + bd[i][1]
        if r == p1[0] and c == p1[1]:
            return True

    return False

##takes a png file with an alpha channel and plots it to a ply file scaled to the subject's known height.
#def cudaPlotSilhouette(png, flength, hsense):
if __name__ == "__main__":
    cudaPlotSilhouette("C:\\Users\\Brilliance\\Desktop\\Projects\\Undergrad-Research\\findborder\\mask0001.png", 0.018, 0.0225)


# import the necessary packages
################################################################
# See this page for discussion https://gurus.pyimagesearch.com/quizzes/advanced-contour-properties-quiz/
################################################################

# import the necessary packages
import numpy as np
import argparse
import cv2
import imutils

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="Path to the image")
args = vars(ap.parse_args())

# load the image and convert it to grayscale
image = cv2.imread(args["image"])
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# find external contours in the image
cnts = cv2.findContours(gray.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
clone = image.copy()

# loop over the contours
for (i, c) in enumerate(cnts):
    # compute the area of the contour along with the bounding box
    # to compute the aspect ratio
    area = cv2.contourArea(c)
    (x, y, w, h) = cv2.boundingRect(c)
    print("Contour{0} - Bounding rectangle (x,y,w,h) = ({1},{2},{3},{4})".format(i+1, x, y, w, h))
    # compute the aspect ratio of the contour, which is simply the width
    # divided by the height of the bounding box
    aspectRatio = w / float(h)

    # use the area of the contour and the bounding box area to compute
    # the extent
    extent = area / float(w * h)

    # compute the convex hull of the contour, then use the area of the
    # original contour and the area of the convex hull to compute the
    # solidity
    hull = cv2.convexHull(c)
    hullArea = cv2.contourArea(hull)
    solidity = area / float(hullArea)
    print("Contour{} - aspect Ratio = {:.2f} - solidity={:.2f} - extent = {:.2f})".format(i + 1, aspectRatio, solidity, extent))
    cv2.drawContours(image, [c], -1, (0, 255, 0), 3)
    cv2.imshow("Contours", image)
    cv2.waitKey()

cv2.waitKey()
cv2.destroyAllWindows()


import skilstak.colors as c
import math
import time as t
def solve_cone():
    """Finds the volume of a cone"""
    height = input(c.cl + "What is the height of your cone? >>> ")
    radius = input(c.cl + "What is the radius of the base of your cone? >>> ")
    x = int(height)
    y = int(radius)
    answer = 3.14 * y**2 * x/3
    print("Your volume is : ",answer)

def solve_sqpyramid():
    base = input(c.cl + "What is the length of the base of your pyramid? >>> ")
    height = input(c.cl + "What is the height of your pyramid? >>> ")
    x = int(base)
    y = int(height)
    answer = x**2 * y/3
    print(c.cl + "Your answer is : ", answer)

def solve_cube():
    """Finds the volume of a cube"""
    height = input("What is the height of your cube? >>> ")
    x = int(height)
    answer = x**3
    print("Your volume is : " ,answer)

def solvesphere():
    """Finds the volume of a sphere based on user input"""
    radius = input("What is the radius of your sphere? >>> ")
    x = int(radius)
    print("pi = 3.14")
    answer = int(4/3 * 3.14 * x**3)
    print("Your volume is : ", answer)
def vsolve_rect():
    l = input("Length >>> ")
    w = input("Width >>> ")
    h = input("Height >>> ")
    ll = int(l)
    ww = int(w)
    hh = int(h)
    me = int
    me = ll * ww * hh
    print("Volume is",me)
def vrectpyramid():
    l = input("Length >>> ")
    w = input("Width >>> ")
    h = input("Height >>> ")
    ll = int(l)
    ww = int(w)
    hh = int(h)
    a = int
    a = ll * ww * hh / 3
    print("Volume is",a)
def vtripyramid():
    l = input("length of triangle >>> ")
    b = input("width of triangle >>> ")
    h = input("height of pyramid >>> ")
    ll = int(l)
    bb = int(b)
    hh = int(h)
    a = int
    a = 1 / 6
    c = int
    c  =  bb * hh * ll * a
    print("Volume is",c)
def vhexagon():
    a = input("Base edge >>> ")
    h = input("Height >>> ")
    aa = int(a)
    hh = int(h)
    w = int
    w = math.sqrt(3) * 3
    r = int
    r = w / 2 * aa * aa * hh
    print("Volume is",r)
def vhemisphere():
    """Finds the volume of a hemisphere based on user input"""
    radius = input("What is the radius of your hemisphere? >>> ")
    x = int(radius)
    print("pi = 3.14")
    answer = int(4/3 * 3.14 * x**3)
    v = int
    v = answer / 2
    print("Your volume is : ",v)
def vtriprism():
    a = input("Base of triangle >>> ")
    b = input("Height of triangle >>> ")
    c = input("Height of prism >>> ")
    aa = int(a)
    bb = int(b)
    cc = int(c)
    ab = int
    ab = aa * bb / 2
    ca = int
    ca = ab * cc
    print("Volume is",ca)
def voctahedron():
    a = input("Edge >>> ")
    aa = int(a)
    a3 = int
    a3 = aa * aa *aa
    x = int
    x = math.sqrt(2) / 3
    xa = int
    xa = x * a3
    print("Volume is",xa)
def vcylinder():
    a = input("Radius >>> ")
    b = input("Height >>> ")
    print("3.14 = pi")
    aa = int(a)
    bb = int(b)
    r = int
    r= aa *aa * 3.14 * bb
    print("Volume is",r)


#!/usr/bin/env python

from testlib.scripts.android.ui import ui_steps
from testlib.base import base_utils
from testlib.scripts.android.ui.ui_step import step as ui_step
from testlib.scripts.android.ui import ui_utils
from testlib.scripts.android.adb.adb_step import step as adb_step
from testlib.scripts.android.adb import adb_steps
from testlib.scripts.browser import browser_utils
from testlib.scripts.android.adb import adb_utils

import time

class open_play_games_settings(ui_step):
    """
        description:
            opens Play Games app Settings

        usage:
            open_play_games_settings()()

        tags:
            android, games, play_games
    """
    def __init__(self, **kwargs):
        ui_step.__init__(self, **kwargs)

    def do(self):
        ui_steps.open_app_from_allapps(serial = self.serial,\
                        view_to_find = {"textContains": "Play Games"},
                        view_to_check = {"textContains": "Play Now"})()
        open_navigation_drawer(serial=self.serial)()
        ui_steps.click_button(serial = self.serial,\
                        view_to_find = {"textContains": "Settings"},
                        view_to_check = {"textContains": "Multiplayer notifications"})()
    def check_condition(self):
        self.uidevice.exists(description="Game Profile")

class open_play_games_inbox(ui_step):
    """
        description:
            opens Inbox from Play Games app

        usage:
            open_play_games_inbox()()

        tags:
            android, games, play_games
    """
    def __init__(self, **kwargs):
        ui_step.__init__(self, **kwargs)

    def do(self):

        ui_steps.open_app_from_allapps(serial = self.serial,\
                view_to_find = {"textContains": "Play Games"},
                view_to_check = {"textContains": "Play Now"})()
        open_navigation_drawer(serial=self.serial)()
        ui_steps.click_button(serial = self.serial,\
                view_to_find = {"textContains": "Inbox"},
                view_to_check = {"text" : "Game on! See invitations and matches in progress here."})()
        ui_steps.click_button(serial = self.serial,\
                        view_to_find = {"text": "GIFTS & REQUESTS"},
                        view_to_check = {"textContains" : "Try sending a gift"})()
        ui_steps.click_button(serial = self.serial,\
                    view_to_find = {"text": "QUESTS"},
                    view_to_check = {"text" : "No quests today! Play Games quests that you've accepted appear here."})()

    def check_condition(self):
        self.uidevice.exists(text = "No quests today!")

class open_play_games_help(ui_step):
    """
        description:
            opens Help menu from Play Games app

        usage:
            open_play_games_help()()

        tags:
            android, games, play_games
    """
    def __init__(self, **kwargs):
        ui_step.__init__(self, **kwargs)

    def do(self):

        ui_steps.open_app_from_allapps(serial = self.serial,\
                        view_to_find = {"textContains": "Play Games"},
                        view_to_check = {"textContains": "Play Now"})()
        open_navigation_drawer(serial=self.serial)()
        ui_steps.click_button(serial = self.serial,\
                    view_to_find = {"textContains": "Help & Feedback"},
                    view_to_check = {"text" : "Play games on your device"})()

    def check_condition(self):
        self.uidevice.exists(text = "Request callback")

class open_play_games_play_now(ui_step):
    """
        description:
            opens Help menu from Play Games app

        usage:
            open_play_games_play_now()()

        tags:
            android, games, play_games
    """
    def __init__(self, **kwargs):
        ui_step.__init__(self, **kwargs)

    def do(self):
        ui_steps.open_app_from_allapps(serial = self.serial,\
                              view_to_find = {"textContains": "Play Games"},
                              view_to_check = {"textContains": "Play Now"})()
        open_navigation_drawer(serial=self.serial)()
        ui_steps.click_button(serial = self.serial,\
                            view_to_find = {"text": "Play Now",\
                                "resourceId" : "com.google.android.play.games:id/action_text"},
                            view_to_check = {"text" : "Discover new games"})()

    def check_condition(self):
        self.uidevice.exists(text = "Discover new games")

class go_for_free_game(ui_step):
    """
        description:
            opens a free game from Play Games app

        usage:
            go_for_free_game()()

        tags:
            android, games, play_games
    """
    def __init__(self, **kwargs):
        ui_step.__init__(self, **kwargs)

    def do(self):
        ui_steps.swipe_down_to_view(serial = self.serial,\
             view_to_check = "FREE")

    def check_condition(self):
             self.uidevice.exists(text = "FREE")

class open_play_games_explore(ui_step):
    """
        description:
            opens Explore menu from Play Games app

        usage:
            open_play_games_explore()()

        tags:
            android, games, play_games
    """
    def __init__(self, **kwargs):
        ui_step.__init__(self, **kwargs)

    def do(self):
        ui_steps.open_app_from_allapps(serial = self.serial,\
                              view_to_find = {"textContains": "Play Games"},
                              view_to_check = {"textContains": "Play Now"})()
        open_navigation_drawer(serial=self.serial)()
        ui_steps.click_button(serial = self.serial,\
                        view_to_find = {"textContains": "Explore"},
                        view_to_check = {"text" : "FEATURED"})()
    def check_condition(self):
        self.uidevice.exists(text = "FEATURED")

class game_has_specific_properties(ui_step):
    """
        description:
            Checks if a game has icon, title, price and if the "Options",\
                    button has "View in Play Store" option

        usage:
            game_has_specific_properties()()

        tags:
            android, games, play_games
    """
    def __init__(self, game_property = "contentDescription", game_price = "text", **kwargs):
        ui_step.__init__(self, **kwargs)
        self.properties_exist = True
    def do(self):
        index = 0
        play_store_exists = ui_utils.is_view_displayed(serial = self.serial,\
                    view_to_find = {"text" : "Play store"})
        if play_store_exists:
            while not ui_utils.is_view_displayed(serial = self.serial,\
                    view_to_find = {"resourceId" : "com.google.android.play.games:id/root_container",\
                    "index":index,
                    "description" : "Play store"}):
                index += 1
        else:
            index = 1
        index += 1
        title_exists = self.uidevice(resourceId="com.google.android.play.games:id/root_container",\
                index=index).child(resourceId="com.google.android.play.games:id/title").exists
        image_exists = self.uidevice(resourceId="com.google.android.play.games:id/root_container",\
                index=index).child(resourceId="com.google.android.play.games:id/image").exists
        price_exists = self.uidevice(resourceId="com.google.android.play.games:id/root_container",\
                index=index).child(resourceId="com.google.android.play.games:id/primary_label").exists
        self.properties_exist = title_exists and image_exists and price_exists

        ui_steps.click_button(serial = self.serial,\
                view_to_find = {"resourceId" : "com.google.android.play.games:id/overflow_menu"},\
                view_to_check = {"text" : "View in Play Store"})()
        ui_steps.press_back(view_to_check = {"text": "FEATURED"})()
    def check_condition(self):
        return self.properties_exist

class my_games_property(ui_step):
    """
        description:
            Verifies if the game exist and then the game's title

        usage:
            game_has_property()()

        tags:
            android, games, play_games
    """
    def __init__(self, **kwargs):
        ui_step.__init__(self, **kwargs)
    def do(self):
        title_exists = self.uidevice(resourceId="com.google.android.play.games:id/root_container").\
                child(resourceId="com.google.android.play.games:id/title").exists or \
                self.uidevice(text = "No games found").exists
        self.property_exists = title_exists
    def check_condition(self):
        return self.property_exists

class open_navigation_drawer(ui_step):
    """
        description:
            Opens Navigation drawer menu from Play Games app

        usage:
            open_navigation_drawer()()

        tags:
            android, games, play_games
    """
    def __init__(self, wait_time = 20000, **kwargs):
        ui_step.__init__(self, **kwargs)
        self.wait_time = wait_time
    def do(self):
        if self.uidevice(description = "Open navigation drawer").wait.exists(timeout = self.wait_time):
            ui_steps.click_button(serial = self.serial,\
                    view_to_find = {"descriptionContains": "Open navigation drawer"},
                    view_to_check = {"text": "My Games"})()
    def check_condition(self):
        self.uidevice.exists(text = "My Games")

class open_my_games(ui_step):
    """
        description:
            opens My Games menu from Play Games app

        usage:
            open_my_games()()

        tags:
            android, games, play_games
    """
    def __init__(self, **kwargs):
        ui_step.__init__(self, **kwargs)

    def do(self):
        ui_steps.open_app_from_allapps(serial = self.serial,\
                              view_to_find = {"textContains": "Play Games"},
                              view_to_check = {"textContains": "Play Now"})()
        open_navigation_drawer(serial=self.serial)()
        ui_steps.click_button(serial = self.serial,\
                view_to_find = {"textContains": "My Games"},
                view_to_check = {"text" : "RECENT GAMES"})()
    def check_condition(self):
        self.uidevice.exists(text = "RECENT GAMES")

class open_players(ui_step):
    """
        description:
            opens Players menu from Play Games app

        usage:
            open_players()()

        tags:
            android, games, play_games
    """
    def __init__(self, **kwargs):
        ui_step.__init__(self, **kwargs)

    def do(self):
        ui_steps.open_app_from_allapps(serial = self.serial,\
                              view_to_find = {"textContains": "Play Games"},
                              view_to_check = {"textContains": "Play Now"})()
        open_navigation_drawer(serial=self.serial)()
        ui_steps.click_button(serial = self.serial,\
                view_to_find = {"textContains": "Players"},
                view_to_check = {"text" : "FOLLOWING"})()
    def check_condition(self):
        self.uidevice.exists(text = "FOLLOWING")

class check_players_properties(ui_step):
    """
        description:
            Verifies for each player profile picture and name, if the player exists

        usage:
            players_properties()()

        tags:
            android, games, play_games
    """
    def __init__(self, check_follow_button = True, **kwargs):
        ui_step.__init__(self, **kwargs)
        self.check_follow_button = check_follow_button

    def do(self):
        title_exists = self.uidevice(resourceId="com.google.android.play.games:id/avatar").exists or \
                self.uidevice(text = "No players found").exists
        image_exists = self.uidevice(resourceId="com.google.android.play.games:id/avatar").\
                child(resourceId = "com.google.android.play.games:id/avatar_image").exists or \
                self.uidevice(text = "No players found").exists

        if self.check_follow_button:
            follow_button = self.uidevice(resourceId = "com.google.android.play.games:id/button", text = "Follow").exists
        else:
            follow_button = True
        self.property_exists = title_exists and image_exists and follow_button
    def check_condition(self):
        return self.property_exists


# -------------------------- Assignment 7 ------------------------------------
# Assignment 7 by Jonathan Alvarez                  Due: 6/15/2018
# In this Assignment we need to create a class called TripleString
# The purpose of the TripleString class is to create objects that can each hold 3 strings.
## -------------------------- Source Code ----------------------------------------

class TripleString:
    """ encapsulates a 3-string object """

    # ------------------- intended class constants ------------------------------------
    MAX_LEN = 50
    MIN_LEN = 1
    DEFAULT_STRING = "(undefined) "

    # ------------ constructor method --------------------------------------------------
    def __init__(self,
                 string1=DEFAULT_STRING,  # Defining each variable
                 string2=DEFAULT_STRING,
                 string3=DEFAULT_STRING):

        if not self.set_string1(string1):
            self.string1 = TripleString.DEFAULT_STRING  # Defining parameters for our constructor

        if not self.set_string2(string2):
            self.string2 = TripleString.DEFAULT_STRING

        if not self.set_string3(string3):
            self.string3 = TripleString.DEFAULT_STRING

    # ----------------------- mutator ("set") methods -------------------------------
    def set_string1(self, string1): # Defining our "setters" for our strings
        if not self.valid_string(string1):
            return False
        else:
            self.string1 = string1
            return True

    def set_string2(self, string2):
        if not self.valid_string(string2):
            return False
        else:
            self.string2 = string2
            return True

    def set_string3(self, string3):
        if not self.valid_string(string3):
            return False
        else:
            self.string3 = string3
            return True

    # ------------------------ accessor ("get") methods -------------------------------

    def get_string1(self): # Defining our getters for our class
        return self.string1

    def get_string2(self):
        return self.string2

    def get_string3(self):
        return self.string3

    # -------------------------- To String Method --------------------------------
    def __str__(self):  # Defining our toString Class
        toString = "strings are:\n\t" + self.string1 + "\n\t" + self.string2 \
                   + "\n\t" + self.string3 + "\n"
        return toString

    # ------------------------ helper methods for entire class -----------------
    @classmethod # Helper methods to check if input is a proper string
    def valid_string(cls, the_str):
        if type(the_str) != str \
                or \
                not (cls.MIN_LEN <= len(the_str) <= cls.MAX_LEN):
            return False
        # else
        return True

# --------------------------- CLIENT --------------------------------------------------

# Create 4 TripleString objects

# Printing Explaination our this Assignment
print("Hello Today we are writing a class that takes on the parameters"
      + " of three strings!\n")

# TEST 1
# Printing out the Default strings without overriding
print("Test 1 (Default):")

triple_string_num_1 = TripleString()
print(triple_string_num_1)

# TEST 2

print("Test 2:")
triple_string_num_2 = TripleString("Hi", "I'm", "Jonathan") # Overriding Default constructors
print(triple_string_num_2)

print("Modifying Test 2:")
triple_string_num_2.set_string1("Hello") # Using mutators to override it again
triple_string_num_2.set_string3("Sleepy")
print(triple_string_num_2)

# TEST 3

print("Test 3:")
triple_string_num_3 = TripleString()
print(triple_string_num_3)

print("Testing mutator with one error:")

triple_string_num_3.set_string1("The") # Using mutators to override the default strings
triple_string_num_3.set_string2("Cat")
triple_string_num_3.set_string3(1) # With one error mutator to check if/else statement works
print(triple_string_num_3)

print("Testing mutator without an error:")
triple_string_num_3.set_string3("in the hat") # Overiding the error mutator to work
print(triple_string_num_3)

# TEST 4
print("Test 4:")

triple_string_num_4 = TripleString("Thing 1", "Thing 2", "The Cat") # Overriding the default strings
print(triple_string_num_4)

print("Lets test our accessor: ")
print("Retrieving String1: " + triple_string_num_4.get_string1())  # Testing accessor

print("Retrieving String3: " + triple_string_num_4.get_string3())  # Testing accessor

## --------------------------- Assignment 7 Output -----------------------------------------
# /Users/jonathanalvarez/Documents/Python_Projects/Assignment_7/venv/bin/python /Users/jonathanalvarez/Documents/Python_Projects/Assignment_7/TripleString.py
# Hello Today we are writing a class that takes on the parameters of three strings!
#
# Test 1 (Default):
# strings are:
# 	(undefined)
# 	(undefined)
# 	(undefined)
#
# Test 2:
# strings are:
# 	Hi
# 	I'm
# 	Jonathan
#
# Modifying Test 2:
# strings are:
# 	Hello
# 	I'm
# 	Sleepy
#
# Test 3:
# strings are:
# 	(undefined)
# 	(undefined)
# 	(undefined)
#
# Testing mutator with one error:
# strings are:
# 	The
# 	Cat
# 	(undefined)
#
# Testing mutator without an error:
# strings are:
# 	The
# 	Cat
# 	in the hat
#
# Test 4:
# strings are:
# 	Thing 1
# 	Thing 2
# 	The Cat
#
# Lets test our accessor:
# Retrieving String1: Thing 1
# Retrieving String3: The Cat


#!/usr/bin/env python3

import hebi
import numpy as np
import os
import sys

# ------------------------------------------------------------------------------
# Add the root folder of the repository to the search path for modules
root_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
sys.path = [root_path] + sys.path
# ------------------------------------------------------------------------------

from util.math_utils import get_grav_comp_efforts
from util.arm import setup_arm_params
from time import sleep, time
from util import math_utils
from hebi.util import create_mobile_io

run_mode = "points"

first_run = True

# Mobile device setup
phone_family = 'HEBI'
phone_name   = "mobileIO"

lookup = hebi.Lookup()
sleep(2)

print('Waiting for Mobile IO device to come online...')
m = create_mobile_io(lookup, phone_family, phone_name)
if m is None:
  raise RuntimeError("Could not find Mobile IO device")
m.set_button_mode(1, 'momentary')
m.set_button_mode(2, 'momentary')
m.set_button_mode(3, 'momentary')
m.update()

quit_demo_button = 8
abort_flag = False
lookup = hebi.Lookup()
sleep(2)

# Arm Setup
arm_family = 'Example Arm'
arm_name   = '6-DoF'
has_gas_spring = False # If you attach a gas spring to the shoulder for extra payload, set this to True.

group, kin, params = setup_arm_params(arm_name, arm_family, has_gas_spring, lookup=lookup)

fbk = hebi.GroupFeedback(group.size)
effort_offset = params.effort_offset
gravity_vec = params.gravity_vec
local_dir = params.local_dir

arm_dof_count = kin.dof_count

print('B1-3 - select different points to move the arm to.')
print('B6 - enables grav comp mode.')
print('B8 - Quits the demo.')

cmd = hebi.GroupCommand(group.size)

# Point coordinates
point_1 = np.asarray([np.pi/4, np.pi/3, 2*np.pi/3, np.pi/3, np.pi/4, 0])
point_2 = np.asarray([-np.pi/4, np.pi/3, 2*np.pi/3, np.pi/3, 3*np.pi/4, 0])
point_3 = np.asarray([0, 0, 0, 0, 0, 0])

end_velocities = np.zeros(arm_dof_count)
end_accels = np.zeros(arm_dof_count)

# Zero the times
t = 0
duration = 0

time_vector = [0, 5]
start = time()

pos_cmd = np.zeros(group.size)
vel_cmd = np.zeros(group.size)
acc_cmd = np.zeros(group.size)

def get_trajectory(curr_pos, curr_vel, curr_acc, point):
  """
  Helper function to create a trajectory
  """
  waypoints = np.empty((group.size, 2))
  waypoints[:, 0] = curr_pos
  waypoints[:, 1] = point

  velocities = np.empty((group.size, 2))
  velocities[:, 0] = curr_vel
  velocities[:, 1] = end_velocities

  accels = np.empty((group.size, 2))
  accels[:, 0] = curr_acc
  accels[:, 1] = end_accels

  trajectory = hebi.trajectory.create_trajectory(time_vector, waypoints, velocities, accels)
  return trajectory

while not abort_flag:
  # Update MobileIO state
  if not m.update():
    print("Failed to get feedback from MobileIO")
    continue

  # Update arm state
  group.get_next_feedback(reuse_fbk=fbk)

  # Check for quit
  if m.get_button_state(quit_demo_button):
    # Set led red and quit
    m.set_led_color("red")
    abort_flag = False
    break

  # On first run go to point 1
  if first_run:
    run_mode = "points"
    first_run = False
    trajectory = get_trajectory(fbk.position, end_velocities, end_accels, point_1)

    duration = trajectory.duration
    start = time()
    t = time() - start

  # If button 1 pressed, create trajectory from current position to point 1
  elif m.get_button_diff(1) == 3: # "ToOn"
    run_mode = "points"
    trajectory = get_trajectory(pos_cmd, vel_cmd, acc_cmd, point_1)

    duration = trajectory.duration
    start = time()
    t = time() - start

  # If button 2 pressed, create trajectory from current position to point 2
  elif m.get_button_diff(2) == 3: # "ToOn"
    run_mode = "points"
    trajectory = get_trajectory(pos_cmd, vel_cmd, acc_cmd, point_2)

    duration = trajectory.duration
    start = time()
    t = time() - start

  # If button 3 pressed, create trajectory from current position to point 3
  elif m.get_button_diff(3) == 3: # "ToOn"
    run_mode = "points"
    trajectory = get_trajectory(pos_cmd, vel_cmd, acc_cmd, point_3)

    duration = trajectory.duration
    start = time()
    t = time() - start

  # If button 5 pressed switch to grav comp mode
  elif m.get_button_diff(5) == 3: # "ToOn"
    run_mode = "grav comp"

  if run_mode == "points":
    # Set led to green for point move mode
    m.set_led_color("green")
    # Move to point
    if t < duration:
      t = time() - start

      # Get new commands from the trajectory
      pos_cmd, vel_cmd, acc_cmd = trajectory.get_state(t)

      # Calculate commanded efforts to assist with tracking the trajectory.
      # Gravity Compensation uses knowledge of the arm's kinematics and mass to
      # compensate for the weight of the arm. Dynamic Compensation uses the
      # kinematics and mass to compensate for the commanded accelerations of the arm.
      eff_cmd = math_utils.get_grav_comp_efforts(kin, fbk.position, [0, 0, 1])
      # NOTE: dynamic compensation effort computation has not yet been added to the APIs

      # Fill in the command and send commands to the arm
      cmd.position = pos_cmd
      cmd.velocity = vel_cmd
      cmd.effort = eff_cmd
      group.send_command(cmd)
    else:
      cmd.position = pos_cmd
      group.send_command(cmd)

  elif run_mode == "grav comp":
    # Set led to blue for grav comp mode
    m.set_led_color("blue")
    # Grav comp mode
    # Update gravity vector the base module of the arm
    params.update_gravity(fbk)
    gravity_vec = params.gravity_vec

    # Calculate required torques to negate gravity at current position
    cmd.effort = get_grav_comp_efforts(kin, fbk.position, -gravity_vec) + effort_offset
    nan_array = np.empty(group.size)
    nan_array[:] = np.nan
    cmd.position = nan_array
    cmd.velocity = nan_array

    # Update these so when creating next trajectory in point move mode they are current
    pos_cmd = fbk.position
    vel_cmd = fbk.velocity
    acc_cmd = end_accels
    # Send to robot
    group.send_command(cmd)


import numpy as np
import pulp
from sys import argv,exit
import os
import random

class MarkovPolicyGenerator:
	def __init__(self,path,algorithm):
		if not os.path.isfile(path):
			exit("Given bandit instance file does not exist.")

		self.process(path)
		if (algorithm == "lp"):
			self.LP()
		else:
			self.HPI()

	def process(self,path):
		f = open(path,'r')
		self.states = int(f.readline().rstrip())
		self.actions = int(f.readline().rstrip())
		self.R = np.zeros([self.states,self.actions,self.states])
		self.T = np.zeros([self.states,self.actions,self.states])

		for i in range(self.states):
			for j in range(self.actions):
				line = f.readline().rstrip()
				self.R[i,j,:] = np.fromstring(line, dtype=float, sep=' ')

		for i in range(self.states):
			for j in range(self.actions):
				line = f.readline().rstrip()
				self.T[i,j,:] = np.fromstring(line, dtype=float, sep=' ')

		self.discount_factor = float(f.readline().rstrip())
		self.taskType = f.readline().rstrip()
		f.close()

	def LP(self):
		prob = pulp.LpProblem("value Function",pulp.LpMinimize)
		Value_function = [pulp.LpVariable('v' + str(i)) for i in range(self.states)]
		prob += sum(Value_function) , "Objective Function"
		for i in range(self.states):
			for j in range(self.actions):
				prob += Value_function[i] >= sum(self.R[i,j,:]*self.T[i,j,:]) + sum(self.T[i,j,:]*Value_function)*self.discount_factor

		if(self.discount_factor == 1):
			prob += Value_function[-1] >= 0
			prob += Value_function[-1] <= 0
		prob.solve()
		if (pulp.LpStatus[prob.status] != "Optimal"):
			exit("No optimal policy found.")

		V = np.zeros(self.states)
		for i,v in enumerate(prob.variables()):
			V[i] = v.varValue

		policy = [0 for i in range(self.states)]
		for i in range(self.states):
			policy[i] = np.argmax([sum(self.R[i,j,:]*self.T[i,j,:]) + sum(self.T[i,j,:]*V)*self.discount_factor for j in range(self.actions)])

		self.print_policy(V,policy)

	def HPI(self):
		policy = [random.randint(0, self.actions-1) for i in range(self.states)]
		while True:
			equations = np.zeros([self.states,self.states+1])
			for i in range(self.states):
				equations[i,i] = 1
				equations[i,:-1] -= self.T[i,policy[i],:]*self.discount_factor
				equations[i,-1] = sum(self.R[i,policy[i],:]*self.T[i,policy[i],:])
			if(self.discount_factor == 1):
				equations[-1,-2] = 1
				equations[-1,-1] = 0

			V = np.linalg.solve(equations[:,:-1], equations[:,-1])
			new_policy = [0 for i in range(self.states)]
			for i in range(self.states):
				new_policy[i] = np.argmax([sum(self.R[i,j,:]*self.T[i,j,:]) + sum(self.T[i,j,:]*V)*self.discount_factor for j in range(self.actions)])
			if (policy == new_policy):
				break
			policy = new_policy[:]

		self.print_policy(V,policy)

	def print_policy(self,V,policy):
		for i in range(self.states):
			print("{:.6f}".format(V[i]) + "\t" + str(policy[i]))

MarkovPolicyGenerator(*argv[1:])


# HW2 Assignment:

''' Question 1: Every node in a binary tree can have 0, 1 or 2 children.  A leaf node has no children.
	Write a Python function to decide whether all nodes, except leaves, in a tree have exactly two children.

# Input:  a node which is the root of the tree
# Output: True if all nodes in the tree have either 0 or 2 children.
#		False if some node has only one child.
# (leaves) or exactly two children (internal nodes).
def  is_full_house( root_node ):
	# your code…
'''
import tree

def addBoolean(b1,b2):
	if (b1 == True and b2 == True):
		return True
	else:
		return False

# def is_full_house2(root_node):
# 	if root_node is None:
# 		return False

# 	if ((root_node.left is None) ^ (root_node.right is None)):
# 		return False

# 	elif (root_node.left is None and root_node.right is None):
# 		return True

# 	else:
# 		left = addBoolean(is_full_house2(root_node.left), True)
# 		right = addBoolean(is_full_house2(root_node.right), True)
# 		return (left and right)

# QUESTION: Could you tell me as part of the feedback, in your opinion, which algorithm looks more technically correct and understandable??
#			is_full_house or is_full_house2  ???
# 			They both always return the same result, but I wrote them slightly differently. Thanks!
def is_full_house(root_node):
	if root_node is None:
		return False

	result = True  # must initialize result
	if ((root_node.left is None) ^ (root_node.right is None)):
		result = False
		return result

	elif (root_node.left is None and root_node.right is None):
		return result

	else:
		left = is_full_house(root_node.left) and result
		right = is_full_house(root_node.right) and result
		return (left and right)

T = tree.random_tree(3)
# tree.draw(T)
print(is_full_house(T))
# print(is_full_house2(T))

''' Question 2: Given the following function

# Input: a list of numbers, L.
# Output: a number
def do_something( L ):			# iterations
	s = 0							1
	for x in L:						n
		s = s + x					1   n(2+n(2+n)) + 3
		print(s)					1
		for y in L:					n
			s = s + y 				1
			print(s, x, y)			1
			for z in L:				n
				s = s + z			1
	s = s*5							1
	return s 						1

Let T(n) be the running time function of do_something.  What is n?

	n is the input size of the function, which depends on the length of the list of numbers i.e. len(L)
'''

''' Question 3: Continuing with problem 2.  Write down T(n) as accurately as you can, with specific numbers.

	T(n) ≈ n(2+n(2+n)) + 3 = 2n + 2n2 + n3 + 3
'''

''' Question 4: Continuing with problem 3.  Describe T(n) using big-O notation.
	T(n) ≈ n(2+n(2+n)) + 3 = 2n + 2n2 + n3 + 3  <= c*g(n) = n^3 + 2n^3 + 2n3 + 3n3 = 8*n^3, with c = 8, for all n > 1
	Thus, f(n) is in O(n^3)
'''

''' Question 5: Given the following function

# Input: a list of numbers L
# Output: a number
def foo(L):
	s = 0
	for x in L:   		n(1+4log2(n)) + 2
		j = len(L)
		while j > 1:
			j = j / 2
			s = s + x
			print(s)
	return s

Let T(n) be the running time function of foo.  Write down T(n) as accurately as you can, with specific numbers.
	T(n) ≈ n(1+4log2(n)) + 2
'''

''' Question 6: Describe T(n) using big-O notation.
	T(n) ≈ n(1+4log2(n)) + 2 = n + 4nlog2(n) + 2 <= c*g(n) = nlog(n) + 4nlog(n) + 2nlog(n) = 7*n*log(n), with c = 6, for all n large enough (> 1)
	Thus, f(n) is in O(n*log(n))
'''

''' Question 7: Describe 20n + 5n^2 using big-O notation.
	f(n) is in O(n^2)
'''

''' Question 8: Describe 10n^3 + 20n^2 using big-O notation.
	f(n) is in O(n^3)

'''


import unittest

from Control.blackjack_controller import BlackjackController
from Control import player, dealer
from Control import config

from Model.deck import Deck

class BlackJackControllerTest(unittest.TestCase):
    def setUp(self):
        self.bjc = BlackjackController()
        self.currentDeck = self.bjc.currentDeck
        self.currentDeck.shuffle()
        self.bet_amount = 100
        self.win = False
        self.default_balance = 10000
        self.starting_blackjack = False
        self.test_player = self.bjc.currentPlayer
        self.test_dealer = self.bjc.currentDealer

    def test_hit_dealer(self):
        """

        testing that the return of hit_dealer is among these return string statements

        1 player_bust test
        2 dealer_bust
        3 player BLACKJACK WIN
        4 player BLACKJACK WIN when both equal 21 but dealer is not blackjack
        5 player  win
        6 player  loses, dealer wins.
        7 Dealer wins with blackjack
        8 tie game
        """
        print("Hit_dealer Return value:", self.bjc.hit_dealer())
        print("Player Score : ", self.test_player.get_score())
        print("Dealer Score:", self.test_dealer.get_score())

        if self.test_player.get_score() > 21:
            self.assertEqual(self.bjc.hit_dealer(), "You bust and lose!", "player Bust  check")
        elif self.test_dealer.get_score() > 21:
            self.assertEqual(self.bjc.hit_dealer(), "Dealer busts! You win!", "Dealer Bust check")
        elif (self.test_player.get_score() != self.test_dealer.get_score()) and self.test_player.has_blackjack():
            self.assertEqual(self.bjc.hit_dealer(), "Blackjack! You Win!", "win condition check player BJ")
        elif (self.test_player.get_score() == self.test_dealer.get_score()) and self.test_player.has_blackjack() and not self.test_dealer.has_blackjack():
            self.assertEqual(self.bjc.hit_dealer(), "BlackJack! You Win!", "player has bj and beats dealers 21 not bj")
        elif self.test_player.get_score() > self.test_dealer.get_score() and not self.test_player.get_score() > 21:
            self.assertEqual(self.bjc.hit_dealer(), "You win!", "Player wins higher score than dealer")
        elif self.test_dealer.get_score() > self.test_player.get_score() and not self.test_dealer.get_score() > 21:
            self.assertEqual(self.bjc.hit_dealer(), "You lose!", "Player loses Dealer had higher score")
        elif self.test_player.get_score()== self.test_dealer.get_score() and self.test_dealer.has_blackjack() and not self.test_player.has_blackjack():
            self.assertEqual(self.bjc.hit_dealer(),"Dealer has BlackJack! You Lose!", "Dealer had BJ player didnt LOSS")
        else:

            self.assertEqual(self.bjc.hit_dealer(), "It's a Tie!", "tie game check")


#-*- coding:utf-8 -*-

# 题 3
# 给定一个只包含字母的字符串，返回单个字母出现的次数
# 考察字典的概念和使用
# 返回值为包含元组的列表，格式如下（对列表中元组的顺序不做要求）
# 参数 "hello"
# 返回值 [('h', 1), ('e', 1), ('l', 2), ('o', 1)]

def letter_count(str):
    a = list(set(str))
    b = []
    for i in a:
        c = 0
        for j in str:
            if i == j:
                c += 1
        b.append((i, c))
    return b


# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models

class User(models.Model):
    """
    The User class model with attributes:

        :id (int) integer ID field and primary key
        :area (str) string area field (a1|a2)
        :tariff (str) string tarrif field (t1|t2|t3)

    :return: None
    """

    AREA = (
        ('a1', 'area1'),
        ('a2', 'area2'),
    )

    TARIFF = (
        ('t1', 'tariff1'),
        ('t2', 'tariff2'),
        ('t3', 'tariff3'),
    )

    id = models.IntegerField(primary_key=True)
    area = models.CharField(max_length=2, choices=AREA)
    tariff = models.CharField(max_length=2, choices=TARIFF)

class Consumption(models.Model):
    """
    The Consumption class model with attributes:

        :user_id (model.User object) instance of User model and foreign key
        :timestamp (str) string datetime field
        :consumption (float) energy consumption used within timestamp

    :return: None
    """

    user_id = models.ForeignKey(User, on_delete=models.CASCADE)
    timestamp = models.DateTimeField()
    consumption = models.FloatField()

    @classmethod
    def get_total(cls, user):
        """
        Get total consumption given a User

        :param user: (model.User object) an instance of User class
        :return: (float) total User consumption
        """

        user_consumptions = Consumption.objects.filter(user_id=user)

        total_consumptions = 0.0

        for consumption_record in user_consumptions:
            total_consumptions += consumption_record.consumption

        return total_consumptions

    @classmethod
    def get_average(cls, user):
        """
        Get average (mean) consumption given a User

        :param user: (model.User object) an instance of User class
        :return: (float) average User consumption
        """

        user_consumptions = Consumption.objects.filter(user_id=user)

        consumptions = []

        for consumption_record in user_consumptions:
            consumptions.append(consumption_record.consumption)

        if consumptions:
            avg_consumption = sum(consumptions)/float(len(consumptions))
        else:
            avg_consumption = 0.0

        return avg_consumption


import torch
from torch.nn import functional as F
from all import nn
from .approximation import Approximation

class QDist(Approximation):
    def __init__(
            self,
            model,
            optimizer,
            n_actions,
            n_atoms,
            v_min,
            v_max,
            name="q_dist",
            **kwargs
    ):
        model = QDistModule(model, n_actions, n_atoms)
        device = next(model.parameters()).device
        self.n_actions = n_actions
        self.atoms = torch.linspace(v_min, v_max, steps=n_atoms).to(device)
        super().__init__(model, optimizer, loss=cross_entropy_loss, name=name, **kwargs)

    def project(self, dist, support):
        # pylint: disable=invalid-name
        target_dist = dist * 0
        atoms = self.atoms
        v_min = atoms[0]
        v_max = atoms[-1]
        delta_z = atoms[1] - atoms[0]
        # vectorized implementation of Algorithm 1
        tz_j = support.clamp(v_min, v_max)
        bj = ((tz_j - v_min) / delta_z)
        l = bj.floor().clamp(0, len(atoms) - 1)
        u = bj.ceil().clamp(0, len(atoms) - 1)
        x = torch.arange(len(dist)).expand(len(atoms), len(dist)).transpose(0, 1)
        target_dist[x, l.long()] += dist * (u - bj)
        target_dist[x, u.long()] += dist * (bj - l)
        return target_dist

class QDistModule(nn.Module):
    def __init__(self, model, n_actions, n_atoms):
        super().__init__()
        self.n_actions = n_actions
        self.n_atoms = n_atoms
        self.device = next(model.parameters()).device
        self.terminal = torch.zeros((n_atoms)).to(self.device)
        self.terminal[(n_atoms // 2)] = 1.0
        self.model = nn.ListNetwork(model)
        self.count = 0

    def forward(self, states, actions=None):
        values = self.model(states).view((len(states), self.n_actions, self.n_atoms))
        values = F.softmax(values, dim=2)
        # trick to convert to terminal without manually looping
        values = (values - self.terminal) * states.mask.view(
            (-1, 1, 1)
        ).float() + self.terminal
        if actions is None:
            return values
        if isinstance(actions, list):
            actions = torch.cat(actions)
        return values[torch.arange(len(states)), actions]

def cross_entropy_loss(dist, target_dist):
    log_dist = torch.log(dist)
    loss_v = -log_dist * target_dist
    return loss_v.sum(dim=-1).mean()


def to_underscore(s):
	a = s.split('_')
	s1 = ''
	for i in a:
		b = list(i)
		if 'a' <= b[0] <= 'z':
			b[0] = chr(ord(b[0])-32)
		s1 += ''.join(b)
	return s1
print(to_underscore('app7_test'))

Convert PascalCase string into snake_case.py


# -*- coding: utf-8 -*-
import math
from xlrd import *
Noise = 999999
Unmarked = 99999

rw = 100
#rw = 30
D = {}
C = {}
X = {}
T = {}
K = {}
Cluster_Label = 0
Minpts = math.log(rw)
#print(Minpts)
count = 0
stack = 0

print(Minpts)

def eps1(x, y):
    return math.sqrt((x.lat - y.lat)**2 + (x.lon - y.lon)**2)

def eps2(x, y):
    return math.sqrt((x.y1 - y.y1)**2 + (x.y2 - y.y2)**2)

def Retrieve_Neighbours(x, n):
    T = {}
    Y = {}
    count = 0
    for r in range(rw):
        if n == r:
            continue
        else:
            e1 = eps1(x, D[r])
            e2 = eps2(x, D[r])
            print(e1, e2)
            if(e1 < 0.1 and e2 < 3):
                Y[count] = Data(D[r].acode, D[r].lat, D[r].lon,  D[r].y1, D[r].y2, D[r].value)
                T[count] = r
                count += 1
                print(count)
    return Y,T

Z={}
Z[0] = Data(D[0].acode, D[0].lat, D[0].lon,  D[0].y1, D[0].y2, D[0].value)
print(Z[count].acode)

def push(x):
     Y = {}
     for j in range(count):
         Y[stack] = Data(D[T[j]].acode, D[T[j]].lat, D[T[j]].lon,  D[T[j]].y1, D[T[j]].y2, D[T[j]].value)
         K[stack] = T[j]
         stack = stack + 1

def pop():
    stack = stack - 1
    return Y[stack]

class Data:
    acode = 0.0
    lat = 0.0
    lon = 0.0
    y1 = 0.0
    y2 = 0.0
    value = 0.0
    clabel = Unmarked
    def __init__(self, acode, lat, lon, y1, y2, value):
        self.lat = lat
        self.lon = lon
        self.y1 = y1
        self.y2 = y2
        self.acode = acode
        self.value = value

for r in range(rw):
    r0 = float(csheet.cell(r,0).value)
    r1 = float(csheet.cell(r,3).value)
    r2 = float(csheet.cell(r,4).value)
    r3 = float(csheet.cell(r,1).value)
    r4 = float(csheet.cell(r,2).value)
    r5 = float(csheet.cell(r,5).value)
    D[r] = Data(r0, r1, r2, r3, r4, r5)

Y[0].value

r0= df['Obs'].as_matrix()
r1= df['Lat'].as_matrix()
r2= df['Longi'].as_matrix()
r3= new_zon
r4= new_mer
r5= df['AirTemp'].as_matrix()

#convert data into new data structure using class Data
rw = 100
for r in range(rw):
    D[r] = Data(r0[r], r1[r], r2[r], r3[r], r4[r], r5[r])

Cluster_label = 0
for r in range(rw):
    if D[r].clabel == Unmarked:
        X,T = Retrieve_Neighbours(D[r], r)

        if len(X) < Minpts:
            D[r].clabel = Noise
            #print("masuk sini ",count)
        else :
            #print("masuk sana")
            Cluster_label = Cluster_label + 1
            for j in range(len(X)):
                D[T[j]].clabel = Cluster_label
                print(D[T[j]].acode, D[T[j]].clabel)
                push(D[T[j]])

                while(stack < 0):
                    CurrentObj = pop()
                    X = Retrieve_Neighbors(CurrentObj, K[stack])

                    if len(X) < Minpts:
                        for j in range(len(X)):
                            if D[T[j]].clabel != Noise or D[T[j]].clabel == Unmarked:
                                D[T[j]].clabel = Cluster_label
                                push(D[T[j]])

import numpy as np
G = []
for i in range(100):
    g = [D[i].acode,D[i].lat,D[i].lon,D[i].y1,D[i].y2,D[i].value,D[i].clabel]
    g = np.asarray(g)
    G.append(g)

G = np.asarray(G)


import cv2
import numpy as np

def on_mouse_click(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONUP:
        blue = image[y, x, 0]
        green = image[y, x, 1]
        red = image[y, x, 2]
        my_image = np.zeros((512, 512, 3), np.uint8)
        my_image[:] = [blue, green, red]
        cv2.imshow('image', image)
        cv2.imshow('color_picker', my_image)

image = cv2.imread('/home/pratik/Downloads/css-colors.jpg')
cv2.imshow('image', image)
cv2.setMouseCallback('image', on_mouse_click)
cv2.waitKey(0)


import codon
import unittest

class TestCase1(unittest.TestCase):
    def test2(self):
        cs = []
        for x in range(1000):
            x = codon.random()
            if codon.validcodon(x):
                cs.append(x)
        #print(cs)
        self.assertTrue(len(cs) == 1000)

    def test1(self):
        bases = []
        for x in range(1000):
            b = codon.randombase()
            if codon.validbase(b):
                bases.append(b)
        #print(bases)
        ones = [x for x in bases if x == 1]
        twos = [x for x in bases if x == 2]
        threes = [x for x in bases if x == 3]
        fours = [x for x in bases if x == 4]
        #print(len(ones))
        #print(len(fours))

        self.assertTrue(len(bases) == 1000)
        self.assertTrue(len(ones) > 0)
        self.assertTrue(len(twos) > 0)
        self.assertTrue(len(threes) > 0)
        self.assertTrue(len(fours) > 0)

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


#! /usr/bin/python3

from iris.test.rdma.utils import *
from infra.common.glopts import GlobalOptions
from infra.common.logging import logger as logger

def Setup(infra, module):
    iterelem = module.iterator.Get()

    logger.info("Iterator Selectors")

    if iterelem:
        if 'base' in iterelem.rdmasession.__dict__:
            logger.info("- rdmasession.base: %s" % iterelem.rdmasession.base)
            module.testspec.selectors.rdmasession.base.Extend(iterelem.rdmasession.base)
    return

def Teardown(infra, module):
    return

def TestCaseSetup(tc):
    logger.info("RDMA TestCaseSetup() Implementation.")
    rs = tc.config.rdmasession

    tc.pvtdata.num_total_bytes = 0x40

    # Read RQ pre state
    rs.lqp.rq.qstate.Read()
    tc.pvtdata.rq_pre_qstate = rs.lqp.rq.qstate.data

    # Read CQ pre state
    rs.lqp.rq_cq.qstate.Read()
    tc.pvtdata.rq_cq_pre_qstate = rs.lqp.rq_cq.qstate.data

    return

def TestCasePreTrigger(tc):
    if (GlobalOptions.dryrun): return
    rs = tc.config.rdmasession
    rs.lqp.rq.qstate.Read()
    logger.info("In TestCasePreTrigger, cb1 state {0}".format(rs.lqp.rq.qstate.data.cb1_state))
    # purposely initialize the CB to error state
    rs.lqp.rq.qstate.data.cb1_state = 2 # ERROR
    rs.lqp.rq.qstate.WriteWithDelay()
    logger.info("In TestCasePreTrigger, updated cb1 state {0}".format(rs.lqp.rq.qstate.data.cb1_state))
    return

def TestCaseTrigger(tc):
    logger.info("RDMA TestCaseTrigger() Implementation.")
    return

def TestCaseStepVerify(tc, step):
    if (GlobalOptions.dryrun): return True
    logger.info("RDMA TestCaseVerify() Implementation.")
    rs = tc.config.rdmasession
    rs.lqp.rq.qstate.Read()
    ring0_mask = (rs.lqp.num_rq_wqes - 1)
    tc.pvtdata.rq_post_qstate = rs.lqp.rq.qstate.data

    ############     RQ VALIDATIONS #################
    # verify that e_psn is NOT incremented
    if not VerifyFieldModify(tc, tc.pvtdata.rq_pre_qstate, tc.pvtdata.rq_post_qstate, 'e_psn', 0):
        return False

    # verify that proxy_cindex is NOT incremented
    if not VerifyFieldMaskModify(tc, tc.pvtdata.rq_pre_qstate, tc.pvtdata.rq_post_qstate, 'proxy_cindex', ring0_mask, 0):
        return False

    # verify that token_id is NOT incremented
    if not VerifyFieldModify(tc, tc.pvtdata.rq_pre_qstate, tc.pvtdata.rq_post_qstate, 'token_id', 0):
        return False

    # verify that nxt_to_go_token_id is NOT incremented
    if not VerifyFieldModify(tc, tc.pvtdata.rq_pre_qstate, tc.pvtdata.rq_post_qstate, 'nxt_to_go_token_id', 0):
        return False

    ############     RQ STATS VALIDATIONS #################
    # verify that num_pkts is NOT incremented
    if not VerifyFieldModify(tc, tc.pvtdata.rq_pre_qstate, tc.pvtdata.rq_post_qstate, 'num_pkts', 0):
        return False

    # verify that num_bytes is incremented by pvtdata.num_total_bytes
    if not VerifyFieldModify(tc, tc.pvtdata.rq_pre_qstate, tc.pvtdata.rq_post_qstate, 'num_bytes', 0):
        return False

    # verify that num_send_msgs is NOT incremented
    if not VerifyFieldModify(tc, tc.pvtdata.rq_pre_qstate, tc.pvtdata.rq_post_qstate, 'num_send_msgs', 0):
        return False

    return True

def TestCaseTeardown(tc):
    logger.info("RDMA TestCaseTeardown() Implementation.")
    ResetErrQState(tc)
    return


# -*- coding: utf-8 -*-
"""
Created on Tue Aug 22 11:21:01 2017

@author: Zlatko
"""

from pyEPR import *

if 0:
    # Specify the HFSS project to be analyzed
    project_info = Project_Info(r"X:\Simulation\\hfss\\KC\\")
    project_info.project_name  = '2013-12-03_9GHzCavity'  # Name of the project file (string). "None" will get the current active one.
    project_info.design_name   = '9GHz_EM_center_SNAIL'  # Name of the desgin file (string). "None" will get the current active one.
    project_info.setup_name    = None       # Name of the setup(string). "None" will get the current active one.

    ## Describe the junctions in the HFSS desgin
    project_info.junctions['snail'] = {'rect':'qubit',  'line': 'JunctionLine', 'Lj_variable':'LJ', 'length':0.0001}
#    project_info.junctions['jBob']   = {'rect':'qubitBob',    'line': 'bob_line',   'Lj_variable':'LJBob',   'length':0.0001}

    # Dissipative elments EPR
    project_info.dissipative.dielectric_surfaces = None         # supply names here, there are more options in  project_info.dissipative.

    # Run analysis
    epr_hfss    = pyEPR_HFSSAnalysis(project_info)
    epr_hfss.do_EPR_analysis() #variations = ['1', '70']

if 1: # Hamiltonian analysis
#    filename = epr_hfss.data_filename
    filename = r'X:\Simulation\hfss\KC\pyEPR_results_2018\2013-12-03_9GHzCavity\9GHz_EM_center_SNAIL\9GHz_EM_center_SNAIL_20180726_170049.hdf5'
    #filename = r'C:\\Users\\rslqulab\\Desktop\\zkm\\2017_pyEPR_data\\\\/2017_08_Zlatko_Shyam_AutStab/2 pyEPR/2 pyEPR_20170825_170550.hdf5'
    epr      = pyEPR_Analysis(filename)

    #result = epr.analyze_variation('1', cos_trunc = 8, fock_trunc = 7)
    epr.analyze_all_variations(cos_trunc = None, fock_trunc = 4) # only quadratic part
    epr.plot_Hresults()

    if 1:
        f0 = epr.results.get_frequencies_HFSS()
        f1 = epr.results.get_frequencies_O1()
        chi = epr.results.get_chi_O1()
        mode_idx = list(f0.index)
        nmodes   = len(mode_idx)
        cmap     = cmap_discrete(nmodes)


from __future__ import print_function
from ortools.constraint_solver import pywrapcp
import random

def read_file(filename):
  """
    Reads the input file and outputs a list of wizard names in alphabetical
    order, and the list of constraints.
  """
  wizards = set()
  constraints = []
  file = open(filename, "r")
  file_text = file.readlines()
  for line in file_text[2:]:
    for name in line.split():
      wizards.add(name)
    constraints.append(line)
  return list(sorted(wizards)), constraints

def check_solution(ordering, constraints):
  """
    Input: An ordering of wizards and a list of constraints.
    Output: Whether the ordering satisfied the entire list of constraints.
    Prints the fraction of constraints satisfied.
  """
  num_constraints = len(constraints)
  correct = True
  count = num_constraints
  for i in range(num_constraints):
    c = constraints[i].split()
    w1 = ordering.index(c[0])
    w2 = ordering.index(c[1])
    w3 = ordering.index(c[2])
    if not((w3 < w1 and w3 < w2) or (w3 > w1 and w3 > w2)):
      count -= 1
      correct = False
  print("%i/%i constraints satisfied" % (count, num_constraints))
  return correct

def make_CP(wizards, constraints):
  """
    Input: A list of wizards and a list of constraints.
    Output: An ordering of wizards.
  """
  solver = pywrapcp.Solver("wizard-ordering")
  num_wizards = len(wizards)
  num_constraints = len(constraints)
  w = [solver.IntVar(0, num_wizards-1, "w%i" % i) for i in range(num_wizards)]

  solver.Add(solver.AllDifferent(w))
  for i in range(num_constraints):
    c = constraints[i].split()
    w1 = w[wizards.index(c[0])]
    w2 = w[wizards.index(c[1])]
    w3 = w[wizards.index(c[2])]
    t1 = solver.IsGreaterCstVar(w3-w1, 0)
    t2 = solver.IsGreaterCstVar(w3-w2, 0)
    solver.Add(t1 == t2)

  db = solver.Phase(w, solver.CHOOSE_FIRST_UNBOUND, solver.ASSIGN_MIN_VALUE)

  solution = solver.Assignment()
  solution.Add(w)
  collector = solver.AllSolutionCollector()
  collector.Add(w)
  solutions_limit = solver.SolutionsLimit(1)

  solution = [] #Fill with (wizard, age) tuples
  if solver.Solve(db, [solutions_limit, collector]):
    print("Solution found")
    for j in range(num_wizards):
      age = collector.Value(0, w[j])
      solution.append((wizards[j], age))
      #print("w%i = " % j, age)
    print("Time:", solver.WallTime(), "ms")
  else:
    print("No solution")

  sort = sorted(solution, key = lambda n: n[1])
  ordering = [s[0] for s in sort]
  print(ordering)
  check_solution(ordering, constraints)
  return wizards

def main():
  file_test = "input35_4.in"
  w, c = read_file(file_test)
  make_CP(w, c)

if __name__ == '__main__':
  main()


import secrets
import json
import requests
import time
import pprint
import data
import datetime

def send_message(app, recipient, message):
    '''
    Send a message to the recipient.
    '''
    app.logger.debug("Sending to {}: {}".format(recipient, message))

    # wants the access token in the query string
    params = {"access_token": secrets.PAGE_ACCESS_TOKEN}
    # needs headers or else it throws an OAuthException
    headers = {"Content-Type": "application/json"}
    # the real meat of the response
    payload = json.dumps({
        "recipient": {
            "id": recipient,
        },
        "message": {
            "text": message,
        },
    })
    r = requests.post("https://graph.facebook.com/v2.6/me/messages", params=params, headers=headers, data=payload)
    if r.status_code != 200:
        app.logger.warning('Failed to send message. Status code: {}'.format(r.status_code))
        app.logger.warning(r.text)

def typing_indicator(app, recipient):
    '''
    Display a typing indicator to the recipient. Will automatically timeout after 20 seconds
    '''
    app.logger.debug("Sending typing indicator to {}".format(recipient))
    params = {"access_token": secrets.PAGE_ACCESS_TOKEN}
    headers = {"Content-Type": "application/json"}
    payload = json.dumps({
        "recipient": {
            "id": recipient,
        },
        "sender_action": "typing_on"
    })
    r = requests.post("https://graph.facebook.com/v2.6/me/messages", params=params, headers=headers, data=payload)
    if r.status_code != 200:
        app.logger.warning('Failed to send message. Status code: {}'.format(r.status_code))
        app.logger.warning(r.text)

def return_message(app, received_data):
    app.logger.debug("Thread running")
    app.logger.info(received_data)
    app.logger.info(type(received_data))

    if 'page' in received_data['object']:
        for entry in received_data['entry']:
            for message_event in entry['messaging']:

                if message_event.get('message'):
                    sender_id = message_event['sender']['id']
                    # recipient_id = message_event['recipient']['id']
                    message_text = message_event['message']['text']

                    # =================
                    # Some logic function to decypher input and return correct response
                    # =================

                    # remove this when  logic in place
                    test_message = "I got your message. Let me repeat it: {}".format(message_text)
                    typing_indicator(app, sender_id)
                    time.sleep(1)
                    send_message(app, sender_id, test_message)
                    # time.sleep(3)

                    # for chunk in domain.first_greet:
                    #     # Pretty much just echo's the received message.
                    #     typing_indicator(sender_id)
                    #     # typing indicator: randomint creates an infinite loop?
                    #     time.sleep(randint(1, 3))
                    #     send_message(sender_id, chunk)

    # so I can see the data better
    pprint.pprint(received_data)

def valid_chores(chore_dict, date=datetime.datetime.now()):
    '''
    Takes a dictionary of chores and a date object. Returns a list of chores up for assignment based on
    time period of chores and elapsed dates.
    '''
    pass

def assign_chores(chore_dict, assignable_chores, users):
    '''
    Takes a dictionary of chores, a list of assignable chores, and a list of users.
    Returns a dict of chores assigned to users based on eligibility

    '''
    pass


# -*- coding: utf-8 -*-

# @Time    : 2020/11/10 16:35

# @Author  : Zhaobin

# @FileName: investment_financing_01.py

# @Software: PyCharm

import os
import sys

sys.path.append(os.path.abspath(os.path.join(os.getcwd(), "..\Parameters")))
from basic_parameters import *
from cost_parameters import *
from income_taxes_parameters import *
import numpy as np
import pandas as pd

class InvestmentFinancing(BasicParameters, CostParameters, IncomeTaxesParameters):

    def __init__(self, **kargs):

        if 'run_time' in kargs.keys() and kargs['run_time'] == 1:
            BasicParameters.default(self)
            CostParameters.default(self)
            IncomeTaxesParameters.default(self)

        if 'capacity_mw' in kargs.keys():
            self.capacity_mw = kargs['capacity_mw']
        if 'eleprice' in kargs.keys():
            self.eleprice = kargs['eleprice']
        if 'investment' in kargs.keys():
            self.investment = float(kargs['investment'])
        if 'annual_effective_hours' in kargs.keys():
            self.annual_effective_hours = kargs['annual_effective_hours']

        # 计算"建设投资资本金"
        self.construction_investment_capital_cal = self.investment * (1 + self.long_loan_rate / 100 / 2) \
                                                   / (1 - self.rate / 100) \
                                                   / (100 / self.rate + 100 * (
                1 + self.long_loan_rate / 100 / 2) / (100 - self.rate))

        # 计算"流动资金"
        self.working_capital_cal = self.capacity_mw * self.indicator_per_kw / 10

        # 计算"流动资金资本金"
        self.working_capital_capital_cal = self.working_capital_cal * self.own_liquidity_rate / 100

        # 计算"长期借款本金"
        self.long_loan_principal_cal = self.investment - self.construction_investment_capital_cal

        # 计算"建设期利息"
        self.construction_period_interest_cal = self.long_loan_principal_cal * self.long_loan_rate / 100 / 2

        # 1.1建设投资明细
        self.construction_investment_detailed = [0 for i in range(0, 22)]
        self.construction_investment_detailed[1] = self.investment
        self.construction_investment_sum = sum(self.construction_investment_detailed)

        # 1.2建设期利息
        self.construction_period_interest_detailed = [0 for i in range(0, 22)]
        self.construction_period_interest_detailed[1] = self.construction_period_interest_cal
        self.construction_period_interest_sum = sum(self.construction_period_interest_detailed)

        # 1.3流动资金
        self.working_capital_detailed = [0 for i in range(0, 22)]
        self.working_capital_detailed[2] = self.working_capital_cal
        self.working_capital_sum = sum(self.working_capital_detailed)

        # 1总投资
        self.total_investment_detailed = [0 for i in range(0, 22)]
        self.total_investment_detailed[1] = self.construction_investment_detailed[1] + \
                                            self.construction_period_interest_detailed[1] + \
                                            self.working_capital_detailed[1]
        self.total_investment_detailed[2] = self.construction_investment_detailed[2] + \
                                            self.construction_period_interest_detailed[2] + \
                                            self.working_capital_detailed[2]
        self.total_investment_sum = sum(self.total_investment_detailed)

        # 2.1.1建设投资资本金
        self.construction_investment_capital_detailed = [0 for i in range(0, 22)]
        self.construction_investment_capital_detailed[1] = self.construction_investment_capital_cal
        self.construction_investment_capital_sum = sum(self.construction_investment_capital_detailed)

        # 2.1.2流动资金资本金
        self.working_capital_capital_detailed = [0 for i in range(0, 22)]
        self.working_capital_capital_detailed[2] = self.working_capital_capital_cal
        self.working_capital_capital_sum = sum(self.working_capital_capital_detailed)

        # 2.1资本金（资金筹措）
        self.capital_fund_detailed = [0 for i in range(0, 22)]
        self.capital_fund_detailed[1] = self.construction_investment_capital_detailed[1] + \
                                        self.working_capital_capital_detailed[1]
        self.capital_fund_detailed[2] = self.construction_investment_capital_detailed[2] + \
                                        self.working_capital_capital_detailed[2]
        self.capital_fund_sum = sum(self.capital_fund_detailed)

        # 2.2.1长期借款
        self.long_term_loan_detailed = [0 for i in range(0, 22)]
        self.long_term_loan_detailed[1] = self.long_loan_principal_cal + self.construction_period_interest_cal
        self.long_term_loan_sum = sum(self.long_term_loan_detailed)

        self.长期借款本金 = [0 for i in range(0, 22)]
        self.长期借款本金[1] = self.investment - self.construction_investment_capital_detailed[1]
        self.长期借款本金_合计 = sum(self.长期借款本金)

        self.建设期利息 = [0 for i in range(0, 22)]
        self.建设期利息[1] = self.长期借款本金[1] * self.long_loan_rate / 100 / 2
        self.建设期利息_合计 = sum(self.建设期利息)

        # 2.2.2流动资金借款
        self.working_capital_loan_detailed = [0 for i in range(0, 22)]
        self.working_capital_loan_detailed[2] = self.working_capital_detailed[2] - \
                                                self.working_capital_capital_detailed[2]
        self.working_capital_loan_sum = sum(self.working_capital_loan_detailed)

        # 2.2借款
        self.total_loan_detailed = [0 for i in range(0, 22)]
        self.total_loan_detailed[1] = self.long_term_loan_detailed[1] + self.working_capital_loan_detailed[1]
        self.total_loan_detailed[2] = self.long_term_loan_detailed[2] + self.working_capital_loan_detailed[2]
        self.total_loan_sum = sum(self.total_loan_detailed)

        # 2资金筹措
        self.fund_raising_detailed = [0 for i in range(0, 22)]
        self.fund_raising_detailed[1] = self.capital_fund_detailed[1] + self.total_loan_detailed[1]
        self.fund_raising_detailed[2] = self.capital_fund_detailed[2] + self.total_loan_detailed[2]
        self.fund_raising_sum = sum(self.fund_raising_detailed)

        self.columns_name_01 = ['第0年', '第1年', '第2年', '第3年', '第4年', '第5年', '第6年', '第7年', '第8年', '第9年', '第10年',
                                '第11年', '第12年', '第13年', '第14年', '第15年', '第16年', '第17年', '第18年', '第19年',
                                '第20年', '第21年']

        self.index_name0_01 = ['1', '1.1', '1.2', '1.3', '2', '2.1', '2.1.1', '2.1.2', '2.2', '2.2.1', '2.2.1.1', '2.2.1.2',
                               '2.2.2', ]

        self.index_name1_01 = ['总投资', '建设投资', '建设期利息0', '流动资金', '资金筹措', '资本金（资金筹措）',
                               '建设投资资本金', '流动资金资本金', '借款', '长期借款', '长期借款本金', '建设期利息1', '流动资金借款', ]

        self.df_01 = pd.DataFrame(
            np.zeros(len(self.index_name1_01) * len(self.columns_name_01)).reshape(
                (len(self.index_name1_01), len(self.columns_name_01))))
        self.df_01 = self.df_01.T
        self.df_01.columns = self.index_name1_01
        self.result = [self.total_investment_detailed, self.construction_investment_detailed,
                       self.construction_period_interest_detailed, self.working_capital_detailed,
                       self.fund_raising_detailed, self.capital_fund_detailed,
                       self.construction_investment_capital_detailed,
                       self.working_capital_capital_detailed, self.total_loan_detailed, self.long_term_loan_detailed,
                       self.长期借款本金, self.建设期利息, self.working_capital_loan_detailed]

    def arry_dic(self, result_list, columns_name,index_name):
        dict_df={}
        for ind in range(0, len(columns_name)):
            dict_df[columns_name[ind]] = result_list[ind]
        self.df=pd.DataFrame(dict_df)
        self.df_f = self.df.T
        self.df_f['项目'] = self.df_f.index
        self.df_f['序号'] = index_name
        self.df_f.set_index(['序号', '项目'], inplace=True)
        self.df_f = self.df_f.iloc[:, 1:]
        self.df_f.insert(0, '合计', self.df_f.sum(axis=1))
        return self.df_f
    def arr_df(self, df, result_list, index_name, columns_name):
        for ind in range(0, len(index_name)):
            df.iloc[:, ind] = result_list[ind]

        self.df_f = df.T
        self.df_f.columns = columns_name
        self.df_f['项目'] = self.df_f.index
        self.df_f['序号'] = index_name
        self.df_f.set_index(['序号', '项目'], inplace=True)
        self.df_f = self.df_f.iloc[:, 1:]
        self.df_f.insert(0, '合计', self.df_f.sum(axis=1))
        return self.df_f

    def cal_df_01(self):

        self.df_01_f = self.arry_dic(self.result, self.index_name1_01, self.index_name0_01)

        return self.df_01_f

    # def total_investment(self):
    #     total_investment_number = "1"
    #     total_investment_name = "总投资"
    #     return total_investment_number, total_investment_name, self.total_investment_sum, \
    #            self.total_investment_detailed[1], self.total_investment_detailed[2]
    #
    # def construction_investment(self, investment=35000):
    #     construction_investment_number = "1.1"
    #     construction_investment_name = "建设投资"
    #     return construction_investment_number, construction_investment_name, self.construction_investment_sum, \
    #            self.construction_investment_detailed[1], self.construction_investment_detailed[2]
    #
    # def construction_period_interest(self):
    #     construction_period_interest_number = "1.2"
    #     construction_period_interest_name = "建设期利息"
    #     return construction_period_interest_number, construction_period_interest_name, self.construction_period_interest_sum, \
    #            self.construction_period_interest_detailed[1], self.construction_period_interest_detailed[2]
    #
    # def working_capital(self):
    #     working_capital_number = "1.3"
    #     working_capital_name = "流动资金"
    #     return working_capital_number, working_capital_name, self.working_capital_sum, \
    #            self.working_capital_detailed[1], self.working_capital_detailed[2]
    #
    # def fund_raising(self):
    #     fund_raising_number = "2"
    #     fund_raising_name = "资金筹措"
    #     return fund_raising_number, fund_raising_name, self.fund_raising_sum, \
    #            self.fund_raising_detailed[1], self.fund_raising_detailed[2]
    #
    # def capital_fund(self):
    #     capital_fund_number = "2.1"
    #     capital_fund_name = "资本金（资金筹措）"
    #     return capital_fund_number, capital_fund_name, self.capital_fund_sum, \
    #            self.capital_fund_detailed[1], self.capital_fund_detailed[2]
    #
    # def construction_investment_capital(self):
    #     construction_investment_capital_number = "2.1.1"
    #     construction_investment_capital_name = "建设投资资本金"
    #     return construction_investment_capital_number, construction_investment_capital_name, self.construction_investment_capital_sum, \
    #            self.construction_investment_capital_detailed[1], self.construction_investment_capital_detailed[2]
    #
    # def working_capital_capital(self):
    #     working_capital_capital_number = "2.1.2"
    #     working_capital_capital_name = "流动资金资本金"
    #     return working_capital_capital_number, working_capital_capital_name, self.working_capital_capital_sum, \
    #            self.working_capital_capital_detailed[1], self.working_capital_capital_detailed[2]
    #
    # def total_loan(self):
    #     total_loan_number = "2.2"
    #     total_loan_name = "借款"
    #     return total_loan_number, total_loan_name, self.total_loan_sum, \
    #            self.total_loan_detailed[1], self.total_loan_detailed[2]
    #
    # def long_term_loan(self):
    #     long_term_loan_number = "2.2.1"
    #     long_term_loan_name = "长期借款"
    #     return long_term_loan_number, long_term_loan_name, self.long_term_loan_sum, \
    #            self.long_term_loan_detailed[1], self.long_term_loan_detailed[2]
    #
    # def working_capital_loan(self):
    #     working_capital_loan_number = "2.2.2"
    #     working_capital_loan_name = "流动资金借款"
    #     return working_capital_loan_number, working_capital_loan_name, self.working_capital_loan_sum, \
    #            self.working_capital_loan_detailed[1], self.working_capital_loan_detailed[2]

if __name__ == "__main__":
    #
    IFprint = InvestmentFinancing(run_time=1, capacity_mw=50, eleprice=0.29, investment=35000,
                                  annual_effective_hours=2800)
    result = IFprint.cal_df_01()
    print(result)
    # print(result.loc[pd.IndexSlice['2.2.1','长期借款'],:])

    # print(IFprint.total_investment())
    # print(IFprint.construction_investment())
    # print(IFprint.construction_period_interest())
    # print(IFprint.working_capital())
    # print(IFprint.fund_raising())
    # print(IFprint.capital_fund())
    # print(IFprint.construction_investment_capital())
    # print(IFprint.working_capital_capital())
    # print(IFprint.total_loan())
    # print(IFprint.long_term_loan())
    # print(IFprint.working_capital_loan())


#!/usr/bin/env python
# encoding: utf-8
# File Name: predict.py
# Author: Jiezhong Qiu
# Create Time: 2017/07/17 21:57
# TODO:

import os
import pickle as pkl
import numpy as np
import scipy.io
import argparse
import logging
from six import iteritems
from collections import defaultdict
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import ShuffleSplit
from sklearn.multiclass import OneVsRestClassifier
from sklearn.metrics import f1_score
from sklearn.metrics import accuracy_score
from sklearn.exceptions import UndefinedMetricWarning
import warnings
from sklearn.grid_search import GridSearchCV
from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.svm import SVC
import operator
from sklearn.preprocessing import normalize

warnings.filterwarnings("ignore", category=UserWarning)
warnings.filterwarnings("ignore", category=UndefinedMetricWarning)

logger = logging.getLogger(__name__)

def sparse_tocoo(temp_y_labels):
  y_labels = [[] for x in range(temp_y_labels.shape[0])]
  cy =  temp_y_labels.tocoo()
  for i, j in zip(cy.row, cy.col):
    y_labels[i].append(j)
  assert sum(len(l) for l in y_labels) == temp_y_labels.nnz
  return y_labels

def sparse2graph(x):
  G = defaultdict(lambda: set())
  cx = x.tocoo()
  for i,j,v in zip(cx.row, cx.col, cx.data):
    G[i].add(j)
  return {str(k): [str(x) for x in v] for k,v in iteritems(G)}

def construct_indicator(y_score, y):
    # rank the labels by the scores directly
    num_label = np.sum(y, axis=1, dtype=np.int)
    y_sort = np.fliplr(np.argsort(y_score, axis=1))
    y_pred = np.zeros_like(y, dtype=np.int)
    for i in range(y.shape[0]):
        for j in range(num_label[i]):
            y_pred[i, y_sort[i, j]] = 1
    return y_pred

def load_w2v_feature(file):
    with open(file, "rb") as f:
        nu = 0
        for line in f:
            content = line.strip().split()
            nu += 1
            if nu == 1:
                n, d = int(content[0]), int(content[1])
                feature = [[] for i in range(n)]
                continue
            index = int(content[0])
            for x in content[1:]:
                feature[index].append(float(x))
    for item in feature:
        assert len(item) == d
    return np.array(feature, dtype=np.float32)

def load_label(file, variable_name="group"):
    data = scipy.io.loadmat(file)
    logger.info("loading mat file %s", file)
    label = data[variable_name].todense().astype(np.int)
    label = np.array(label)
    print(label.shape, type(label), label.min(), label.max())
    return label

def logistic_regression_classification(grid_search):
    lf_classifer = OneVsRestClassifier(LogisticRegression(solver='lbfgs'), n_jobs=-1)
    if grid_search:
        parameters = {
            "estimator__penalty" : ["l1", "l2"],
            "estimator__C": [0.001, 0.01, 0.1, 1, 10, 100, 1000]
        }
        lf_classifer = GridSearchCV(lf_classifer, param_grid=parameters, cv=5, scoring='f1_micro', n_jobs=-1, verbose=0)
    return lf_classifer

def svc_classification(grid_search, test_kernel):
    if test_kernel == "linear":
        svc_classifer = OneVsRestClassifier(SVC(kernel="linear", probability=True),n_jobs=-1)
    if test_kernel == "rbf":
        svc_classifer = OneVsRestClassifier(SVC(kernel="rbf", probability=True), n_jobs=-1)
    if grid_search:
        if test_kernel == "linear":
            parameters = {
                "estimator__C": [0.001, 0.01, 0.1, 1, 10, 100, 1000],
            }
        if test_kernel == "rbf":
            parameters = {
                "estimator__C": [0.001, 0.01, 0.1, 1, 10, 100, 1000],
                "estimator__gamma": [0.001, 0.01, 0.1, 1, 10, 100, 1000]
            }
        svc_classifer = GridSearchCV(svc_classifer, param_grid=parameters, cv=5, scoring='f1_micro', n_jobs=-1, verbose=0)
    return svc_classifer

def predict_cv(args, clf_param_dict, X, normalized_X, y, train_ratio=0.2, n_splits=10, random_state=0):
    labels_count = y.shape[1]
    micro, macro, accu = [], [], []
    shuffle = ShuffleSplit(n_splits=n_splits, test_size=1-train_ratio,
            random_state=random_state)
    i = 0
    for train_index, test_index in shuffle.split(X):
        #print(train_index.shape, test_index.shape)
        assert len(set(train_index) & set(test_index)) == 0
        assert len(train_index) + len(test_index) == X.shape[0]
        X_train, normalized_X_train, X_test, normalized_X_test = X[train_index], normalized_X[train_index], X[test_index], normalized_X[test_index]
        y_train, y_test = y[train_index], y[test_index]
        results = {}

        if args.classifier == 'LR':
            clf1 = logistic_regression_classification(args.grid_search)
            clf2 = logistic_regression_classification(args.grid_search)
        elif args.classifier == 'SVM':
            clf1 = svc_classification(args.grid_search, args.test_kernel)
            clf2 = svc_classification(args.grid_search, args.test_kernel)

        clf1.fit(X_train, y_train)
        y_score1 = clf1.predict_proba(X_test)
        y_pred1 = construct_indicator(y_score1, y_test)
        mi = f1_score(y_test, y_pred1, average="micro")
        ma = f1_score(y_test, y_pred1, average="macro")
        acc = accuracy_score(y_test, y_pred1)
        # logger.info("micro f1 %f macro f1 %f", mi, ma)
        clf_param_dict[train_ratio][i + 1] = str(clf1.best_params_)
        # logger.info("Best Scores with best params: {}".format(str(clf.best_score_)))

        clf2.fit(normalized_X_train, y_train)
        y_score2 = clf2.predict_proba(normalized_X_test)
        y_pred2 = construct_indicator(y_score2, y_test)
        if (mi < f1_score(y_test, y_pred2, average="micro")) :
            mi = f1_score(y_test, y_pred2, average="micro")
            ma = f1_score(y_test, y_pred2, average="macro")
            acc = accuracy_score(y_test, y_pred2)
            clf_param_dict[train_ratio][i + 1] = str(clf2.best_params_)

        micro.append(mi)
        macro.append(ma)
        accu.append(acc)
        i = i+1

    logger.info("%d fold validation, training ratio %f", len(micro), train_ratio)
    logger.info("Average micro %.2f, Average macro %.2f", np.mean(micro) * 100, np.mean(macro) * 100)
    l = [np.mean(micro) * 100, np.mean(macro) * 100, np.mean(accu) * 100]
    return l, clf_param_dict

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--label", type=str, required=True,
                        help="input file path for labels (.mat)")
    parser.add_argument("--embedding", type=str, required=True,
                        help="input file path for embedding (.npy)")
    parser.add_argument("--matfile-variable-name", type=str, default='group',
                        help='variable name of adjacency matrix inside a .mat file.')
    parser.add_argument("--seed", type=int, required=True,
                        help="seed used for random number generator when randomly split data into training/test set.")
    parser.add_argument("--start-train-ratio", type=int, default=10,
                        help="the start value of the train ratio (inclusive).")
    parser.add_argument("--stop-train-ratio", type=int, default=90,
                        help="the end value of the train ratio (inclusive).")
    parser.add_argument("--num-train-ratio", type=int, default=9,
                        help="the number of train ratio chosen from [train-ratio-start, train-ratio-end].")
    parser.add_argument("--num-split", type=int, default=5,
                        help="The number of re-shuffling & splitting for each train ratio.")

    parser.add_argument("--grid_search", default=True, help='If the flag is set, then grid search is used.')
    parser.add_argument("--classifier", default="SVM", choices=["LR", "SVM"],
                        help='Classifier to be used; Choose from "LR" or "SVM"')
    parser.add_argument("--test_kernel", default="linear", choices=["linear", "rbf"],
                        help='Kernel to be used for SVM classifier; Choose from "linear" or "rbf"')

    args = parser.parse_args()
    logging.basicConfig(
        # filename="%s.log" % args.embedding, filemode="w", # uncomment this to log to file
        level=logging.INFO,
        format='%(asctime)s %(message)s')  # include timestamp
    logger.info("Loading label from %s...", args.label)
    label = load_label(file=args.label, variable_name=args.matfile_variable_name)
    logger.info("Label loaded!")

    logger.info("Loading network embedding from %s...", args.embedding)
    ext = os.path.splitext(args.embedding)[1]
    if ext == ".npy":
        embedding = np.load(args.embedding)
    elif ext == ".pkl":
        with open(args.embedding, "rb") as f:
            embedding = pkl.load(f)
    else:
        # Load word2vec format
        embedding = load_w2v_feature(args.embedding)
    logger.info("Network embedding loaded!")
    normalized_embedding = normalize(embedding, norm="l2")

    train_ratios = np.linspace(args.start_train_ratio, args.stop_train_ratio,
                               args.num_train_ratio)
    m_values = list()
    clf_param_dict = {}
    for tr in train_ratios: # [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
        clf_param_dict[tr / 100.] = dict()
        l, clf_param_dict = predict_cv(args, clf_param_dict, embedding, normalized_embedding, label, train_ratio=tr / 100.,
                       n_splits=args.num_split, random_state=args.seed)
        m_values = m_values + l
    with open(str(str.split(args.label, '.')[0])+".txt", 'wb') as fp:
        pkl.dump(m_values, fp)
    with open(str(str.split(args.label, '.')[0])+"_"+"best_params.txt", 'wb') as fp:
        pkl.dump(clf_param_dict, fp)

    return m_values

if __name__ == "__main__":
    main()


# This example creates a comparison between k-means algorithms implementend in fcl
# and the k-means algorithm implemented in scikit-learn.
# The comparison contains optimized and unoptimized version of k-means.
# All comparisons are done with sparse input data. In scikit-learn only the
# traditional k-means algorithm is available for clustering while more sophisticated
# algorithms like 'elkan' do not work yet with sparse data.

from __future__ import print_function
import fcl
import os
import matplotlib
import matplotlib.pyplot as plt
from os.path import abspath, join, dirname
from fcl import kmeans
from fcl.datasets import load_sector_dataset, load_usps_dataset
from fcl.matrix.csr_matrix import get_csr_matrix_from_object
import time
import sklearn.cluster

def timeit(km, X):
  start = time.time()
  km.fit(X)
  km.predict(X)
  return time.time() - start

def do_evaluations(dataset_path, dataset_name):

  # Load dataset directly into csr matrix format this way it only needs to be converted once
  data_as_csrmatrix = get_csr_matrix_from_object(dataset_path)

  # Convert data to numpy array
  data_as_numpy = data_as_csrmatrix.to_numpy()

  # sklearn
  # - uses dense vectors to store the cluster centers. this makes the calculation of the distance between
  #   sparse samples and dense clusters very fast. However if the input data has very large dimensions, storing
  #   dense cluster centers gets very costly.
  #
  # fcl
  # - uses sparse vectors everywhere. Calculating distances between a sparse center and a sparse sample is a lot more expensive
  #   then using a dense center. However it is possible to cluster very high dimensional data into many clusters on a regular
  #   while keeping the memory usage very low.
  algorithm_results = {}

  # These values generate the official repository plot.
  #algorithms = ["elkan", "bv_kmeans", "yinyang", "bv_yinyang", "kmeans"]
  #clusters = [10, 50, 100, 500, 1000]

  # These values are used in order to allow the tests to be more efficient
  algorithms = ["kmeans"]
  clusters = [2, 8]

  for no_clusters in clusters:
    for algorithm in algorithms:
      algorithm_name = "fcl_kmeans_" + algorithm
      if not algorithm_name in algorithm_results:
        algorithm_results[algorithm_name] = {}
      print("evaluating: fcl kmeans (%s) with k=%d and dataset %s"%(algorithm, no_clusters, dataset_name))
      dur = timeit(kmeans.KMeans(n_jobs=1, no_clusters=no_clusters, algorithm=algorithm, init='random', seed = 1, verbose = False)
             , data_as_csrmatrix)
      algorithm_results[algorithm_name][no_clusters] = dur

    algorithm_name = "sklearn_kmeans"
    if not algorithm_name in algorithm_results:
      algorithm_results[algorithm_name] = {}

    # Evaluating the speed of scikit-learn when clustering a sparse matrix
    print("evaluating: sklearn kmeans (sparse matrix) with k=%d and dataset %s"%(no_clusters, dataset_name))
    dur = timeit(sklearn.cluster.KMeans(n_init = 1, n_jobs=1, n_clusters=no_clusters, algorithm='full', init='random', random_state=1)
               , data_as_numpy)
    algorithm_results[algorithm_name][no_clusters] = dur

  # plot the results
  plot_sklearn_comparison(algorithm_results, dataset_name)

def plot_sklearn_comparison(algorithm_results, dataset_name):
  # create subplot showing the overall duration of the algorithm

  fig = plt.figure()
  ax = plt.subplot(111)

  i = 0
  tick_pos = []
  sorted_algorithms = sorted(algorithm_results.keys())
  no_clusters_list = sorted(algorithm_results[sorted_algorithms[0]])
  width = 1 / float(len(algorithm_results) + 1)
  base_tick_pos = (float(width) * len(algorithm_results)) / 2
  tick_pos = []

  algorithm_xvalues = {}
  algorithm_yvalues = {}
  algorithm_legend_data = {}
  for i in range(len(sorted_algorithms)):
    algo_color = next(ax._get_lines.prop_cycler)['color']
    algo_name = sorted_algorithms[i]
    algorithm_legend_data[i] = (algo_color, algo_name)
    algorithm_xvalues[i] = []
    algorithm_yvalues[i] = []

  j = 0
  for no_clusters in no_clusters_list:
    i = 0
    for algorithm in sorted_algorithms:
      algorithm_xvalues[i].append(j + (i * width))
      algorithm_yvalues[i].append(algorithm_results[algorithm][no_clusters])
      i += 1

    tick_pos.append(j + base_tick_pos)
    j += 1

  legend_rects = []
  for i in range(len(sorted_algorithms)):
    (algo_color, algo_name) = algorithm_legend_data[i]
    r = ax.bar(algorithm_xvalues[i], algorithm_yvalues[i], width, color=algo_color)
    legend_rects.append(r[0])

  ax.set_xticks(tick_pos, minor=False)
  ax.set_xticklabels(no_clusters_list, fontdict=None, minor=False)
  ax.set_ylabel('time / s')
  ax.set_xlabel('number of clusters')
  ax.set_title("Overall duration of fcl vs sklearn (kmeans) for dataset %s"%dataset_name)

  lgd = ax.legend(legend_rects, sorted_algorithms, loc='upper left')

  fig.tight_layout()
  destination_filename = join(dirname( __file__ ), "algorithm_speed_comparison_sklearn.png")
  plt.savefig(destination_filename, bbox_extra_artists=(lgd,), bbox_inches='tight')
  print("plot was saved in the current folder to: %s"%destination_filename)

if __name__ == "__main__":
  ds_folder = abspath(join(dirname( __file__ ), os.pardir, os.pardir, os.pardir, 'datasets'))
  do_evaluations(load_sector_dataset(ds_folder), 'sector')