"""
Test render pipeline by rendering to a texture.
"""

import ctypes
import numpy as np

import pyshader
from pyshader import python2shader, f32, vec2, vec4, i32
import wgpu.backends.rs  # noqa
from pytest import skip, raises
from testutils import run_tests, get_default_device
from testutils import can_use_wgpu_lib, can_use_vulkan_sdk
from renderutils import upload_to_texture, render_to_texture, render_to_screen  # noqa

if not can_use_wgpu_lib:
    skip("Skipping tests that need the wgpu lib", allow_module_level=True)

@python2shader
def vertex_shader(
    index: ("input", "VertexId", i32),
    pos: ("output", "Position", vec4),
    tcoord: ("output", 0, vec2),
):
    positions = [
        vec2(-0.5, -0.5),
        vec2(-0.5, +0.5),
        vec2(+0.5, -0.5),
        vec2(+0.5, +0.5),
    ]
    p = positions[index]
    pos = vec4(p, 0.0, 1.0)  # noqa
    tcoord = vec2(p + 0.5)  # noqa - map to 0..1

# %% rgba textures

def test_render_textured_square_rgba8unorm():
    """Test a texture with format rgba8unorm."""

    @python2shader
    def fragment_shader(
        tex: ("texture", 0, "2d f32"),
        sampler: ("sampler", 1, ""),
        tcoord: ("input", 0, vec2),
        out_color: ("output", 0, vec4),
    ):
        out_color = tex.sample(sampler, tcoord)  # noqa

    # Create texture data
    nx, ny, nz = 2, 2, 1
    x = [50, 50, 0, 255, 100, 100, 0, 255, 150, 150, 0, 255, 200, 200, 0, 255]
    texture_data = (ctypes.c_uint8 * (4 * nx * ny))(*x)

    # Render and validate
    render_textured_square(
        fragment_shader, wgpu.TextureFormat.rgba8unorm, (nx, ny, nz), texture_data
    )

def test_render_textured_square_rgba8uint():
    """Test a texture with format rgba8uint."""

    @python2shader
    def fragment_shader(
        tex: ("texture", 0, "2d i32"),
        sampler: ("sampler", 1, ""),
        tcoord: ("input", 0, vec2),
        out_color: ("output", 0, vec4),
    ):
        out_color = vec4(tex.sample(sampler, tcoord)) / 255.0  # noqa

    # Create texture data
    nx, ny, nz = 2, 2, 1
    x = [50, 50, 0, 255, 100, 100, 0, 255, 150, 150, 0, 255, 200, 200, 0, 255]
    texture_data = (ctypes.c_uint8 * (4 * nx * ny))(*x)

    # Render and validate
    render_textured_square(
        fragment_shader, wgpu.TextureFormat.rgba8uint, (nx, ny, nz), texture_data
    )

def test_render_textured_square_rgba16sint():
    """Test a texture with format rgba16sint."""

    @python2shader
    def fragment_shader(
        tex: ("texture", 0, "2d i32"),
        sampler: ("sampler", 1, ""),
        tcoord: ("input", 0, vec2),
        out_color: ("output", 0, vec4),
    ):
        out_color = vec4(tex.sample(sampler, tcoord)) / 255.0  # noqa

    # Create texture data
    nx, ny, nz = 2, 2, 1
    x = [50, 50, 0, 255, 100, 100, 0, 255, 150, 150, 0, 255, 200, 200, 0, 255]
    texture_data = (ctypes.c_int16 * (4 * nx * ny))(*x)

    # Render and validate
    render_textured_square(
        fragment_shader, wgpu.TextureFormat.rgba16sint, (nx, ny, nz), texture_data
    )

def test_render_textured_square_rgba32float():
    """Test a texture with format rgba32float."""

    @python2shader
    def fragment_shader(
        tex: ("texture", 0, "2d f32"),
        sampler: ("sampler", 1, ""),
        tcoord: ("input", 0, vec2),
        out_color: ("output", 0, vec4),
    ):
        out_color = tex.sample(sampler, tcoord) / 255.0  # noqa

    # Create texture data
    nx, ny, nz = 2, 2, 1
    x = [50, 50, 0, 255, 100, 100, 0, 255, 150, 150, 0, 255, 200, 200, 0, 255]
    texture_data = (ctypes.c_float * (4 * nx * ny))(*x)

    # Render and validate
    render_textured_square(
        fragment_shader, wgpu.TextureFormat.rgba32float, (nx, ny, nz), texture_data
    )

# %% rg textures

def test_render_textured_square_rg8unorm():
    """Test a texture with format rg8unorm.
    The GPU considers blue to be 0 and alpha to be 1.
    """

    @python2shader
    def fragment_shader(
        tex: ("texture", 0, "2d f32"),
        sampler: ("sampler", 1, ""),
        tcoord: ("input", 0, vec2),
        out_color: ("output", 0, vec4),
    ):
        out_color = tex.sample(sampler, tcoord)  # noqa

    # Create texture data
    nx, ny, nz = 2, 2, 1
    x = [50, 50, 100, 100, 150, 150, 200, 200]
    texture_data = (ctypes.c_ubyte * (2 * nx * ny))(*x)

    # Render and validate
    render_textured_square(
        fragment_shader, wgpu.TextureFormat.rg8unorm, (nx, ny, nz), texture_data
    )

def test_render_textured_square_rg8uint():
    """Test a texture with format rg8uint.
    The GPU considers blue to be 0 and alpha to be 1.
    """

    @python2shader
    def fragment_shader(
        tex: ("texture", 0, "2d i32"),
        sampler: ("sampler", 1, ""),
        tcoord: ("input", 0, vec2),
        out_color: ("output", 0, vec4),
    ):
        val = vec2(tex.sample(sampler, tcoord).rg)
        out_color = vec4(val.rg / 255.0, 0, 1.0)  # noqa

    # Create texture data
    nx, ny, nz = 2, 2, 1
    x = [50, 50, 100, 100, 150, 150, 200, 200]
    texture_data = (ctypes.c_ubyte * (2 * nx * ny))(*x)

    # Render and validate
    render_textured_square(
        fragment_shader, wgpu.TextureFormat.rg8uint, (nx, ny, nz), texture_data
    )

def test_render_textured_square_rg16sint():
    """Test a texture with format rg16sint.
    The GPU considers blue to be 0 and alpha to be 1.
    """

    @python2shader
    def fragment_shader(
        tex: ("texture", 0, "2d i32"),
        sampler: ("sampler", 1, ""),
        tcoord: ("input", 0, vec2),
        out_color: ("output", 0, vec4),
    ):
        val = vec2(tex.sample(sampler, tcoord).rg)
        out_color = vec4(val.rg / 255.0, 0.0, 1.0)  # noqa

    # Create texture data
    nx, ny, nz = 2, 2, 1
    x = [50, 50, 100, 100, 150, 150, 200, 200]
    texture_data = (ctypes.c_int16 * (2 * nx * ny))(*x)

    # Render and validate
    render_textured_square(
        fragment_shader, wgpu.TextureFormat.rg16sint, (nx, ny, nz), texture_data
    )

def test_render_textured_square_rg32float():
    """Test a texture with format rg32float.
    The GPU considers blue to be 0 and alpha to be 1.
    """

    @python2shader
    def fragment_shader(
        tex: ("texture", 0, "2d f32"),
        sampler: ("sampler", 1, ""),
        tcoord: ("input", 0, vec2),
        out_color: ("output", 0, vec4),
    ):
        val = tex.sample(sampler, tcoord).rg
        out_color = vec4(val.rg / 255.0, 0.0, 1.0)  # noqa

    # Create texture data
    nx, ny, nz = 2, 2, 1
    x = [50, 50, 100, 100, 150, 150, 200, 200]
    texture_data = (ctypes.c_float * (2 * nx * ny))(*x)

    # Render and validate
    render_textured_square(
        fragment_shader, wgpu.TextureFormat.rg32float, (nx, ny, nz), texture_data
    )

# %% r textures

def test_render_textured_square_r8unorm():
    """Test a texture with format r8unorm."""

    @python2shader
    def fragment_shader(
        tex: ("texture", 0, "2d f32"),
        sampler: ("sampler", 1, ""),
        tcoord: ("input", 0, vec2),
        out_color: ("output", 0, vec4),
    ):
        val = tex.sample(sampler, tcoord).r
        out_color = vec4(val, val, 0.0, 1.0)  # noqa

    # Create texture data
    nx, ny, nz = 2, 2, 1
    x = [50, 100, 150, 200]
    texture_data = (ctypes.c_uint8 * (1 * nx * ny))(*x)

    # Render and validate
    render_textured_square(
        fragment_shader, wgpu.TextureFormat.r8unorm, (nx, ny, nz), texture_data
    )

def test_render_textured_square_r8uint():
    """Test a texture with format r8uint."""

    @python2shader
    def fragment_shader(
        tex: ("texture", 0, "2d i32"),
        sampler: ("sampler", 1, ""),
        tcoord: ("input", 0, vec2),
        out_color: ("output", 0, vec4),
    ):
        val = f32(tex.sample(sampler, tcoord).r)
        out_color = vec4(val / 255.0, val / 255.0, 0.0, 1.0)  # noqa

    # Create texture data
    nx, ny, nz = 2, 2, 1
    x = [50, 100, 150, 200]
    texture_data = (ctypes.c_uint8 * (1 * nx * ny))(*x)

    # Render and validate
    render_textured_square(
        fragment_shader, wgpu.TextureFormat.r8uint, (nx, ny, nz), texture_data
    )

def test_render_textured_square_r16sint():
    """Test a texture with format r16sint. Because e.g. CT data."""

    @python2shader
    def fragment_shader(
        tex: ("texture", 0, "2d r16i"),
        sampler: ("sampler", 1, ""),
        tcoord: ("input", 0, vec2),
        out_color: ("output", 0, vec4),
    ):
        val = f32(tex.sample(sampler, tcoord).r)
        out_color = vec4(val / 255.0, val / 255.0, 0.0, 1.0)  # noqa

    # Create texture data
    nx, ny, nz = 2, 2, 1
    x = [50, 100, 150, 200]
    texture_data = (ctypes.c_int16 * (1 * nx * ny))(*x)

    # Render and validate
    render_textured_square(
        fragment_shader, wgpu.TextureFormat.r16sint, (nx, ny, nz), texture_data
    )

def test_render_textured_square_r32sint():
    """Test a texture with format r32sint. Because e.g. CT data."""

    @python2shader
    def fragment_shader(
        tex: ("texture", 0, "2d r32i"),
        sampler: ("sampler", 1, ""),
        tcoord: ("input", 0, vec2),
        out_color: ("output", 0, vec4),
    ):
        val = f32(tex.sample(sampler, tcoord).r)
        out_color = vec4(val / 255.0, val / 255.0, 0.0, 1.0)  # noqa

    # Create texture data
    nx, ny, nz = 2, 2, 1
    x = [50, 100, 150, 200]
    texture_data = (ctypes.c_int32 * (1 * nx * ny))(*x)

    # Render and validate
    render_textured_square(
        fragment_shader, wgpu.TextureFormat.r32sint, (nx, ny, nz), texture_data
    )

def test_render_textured_square_r32float():
    """Test a texture with format r32float."""

    @python2shader
    def fragment_shader(
        tex: ("texture", 0, "2d r32f"),
        sampler: ("sampler", 1, ""),
        tcoord: ("input", 0, vec2),
        out_color: ("output", 0, vec4),
    ):
        val = f32(tex.sample(sampler, tcoord).r)
        out_color = vec4(val / 255.0, val / 255.0, 0.0, 1.0)  # noqa

    # Create texture data
    nx, ny, nz = 2, 2, 1
    x = [50, 100, 150, 200]
    texture_data = (ctypes.c_float * (1 * nx * ny))(*x)

    # Render and validate
    render_textured_square(
        fragment_shader, wgpu.TextureFormat.r32float, (nx, ny, nz), texture_data
    )

# %% Utils

def render_textured_square(fragment_shader, texture_format, texture_size, texture_data):
    """Render, and test the result. The resulting image must be a
    gradient on R and B, zeros on G and ones on A.
    """
    nx, ny, nz = texture_size

    device = get_default_device()

    if can_use_vulkan_sdk:
        pyshader.dev.validate(vertex_shader)
        pyshader.dev.validate(fragment_shader)

    # Create texture
    texture = device.create_texture(
        size=(nx, ny, nz),
        dimension=wgpu.TextureDimension.d2,
        format=texture_format,
        usage=wgpu.TextureUsage.SAMPLED | wgpu.TextureUsage.COPY_DST,
    )
    upload_to_texture(device, texture, texture_data, nx, ny, nz)

    # texture_view = texture.create_view()
    # or:
    texture_view = texture.create_view(
        format=texture_format,
        dimension=wgpu.TextureDimension.d2,
    )
    # But not like these ...
    with raises(ValueError):
        texture_view = texture.create_view(
            dimension=wgpu.TextureDimension.d2,
        )
    with raises(ValueError):
        texture_view = texture.create_view(
            mip_level_count=1,
        )

    sampler = device.create_sampler(mag_filter="linear", min_filter="linear")

    # Determine texture component type from the format
    if texture_format.endswith(("norm", "float")):
        texture_component_type = wgpu.TextureComponentType.float
    elif "uint" in texture_format:
        texture_component_type = wgpu.TextureComponentType.uint
    else:
        texture_component_type = wgpu.TextureComponentType.sint

    # Bindings and layout
    bindings = [
        {"binding": 0, "resource": texture_view},
        {"binding": 1, "resource": sampler},
    ]
    binding_layouts = [
        {
            "binding": 0,
            "visibility": wgpu.ShaderStage.FRAGMENT,
            "type": wgpu.BindingType.sampled_texture,
            "view_dimension": wgpu.TextureViewDimension.d2,
            "texture_component_type": texture_component_type,
        },
        {
            "binding": 1,
            "visibility": wgpu.ShaderStage.FRAGMENT,
            "type": wgpu.BindingType.sampler,
        },
    ]
    bind_group_layout = device.create_bind_group_layout(entries=binding_layouts)
    pipeline_layout = device.create_pipeline_layout(
        bind_group_layouts=[bind_group_layout]
    )
    bind_group = device.create_bind_group(layout=bind_group_layout, entries=bindings)

    # Render
    render_args = device, vertex_shader, fragment_shader, pipeline_layout, bind_group
    # render_to_screen(*render_args)
    a = render_to_texture(*render_args, size=(64, 64))

    # print(a.max(), a[:,:,0].max())

    # Check that the background is all zero
    bg = a.copy()
    bg[16:-16, 16:-16, :] = 0
    assert np.all(bg == 0)

    # Check the square
    sq = a[16:-16, 16:-16, :]
    ref1 = [
        [150, 150, 150, 150, 150, 150, 150, 150, 152, 155, 158, 161],
        [164, 167, 170, 173, 177, 180, 183, 186, 189, 192],
        [195, 198, 200, 200, 200, 200, 200, 200, 200, 200],
    ]
    ref2 = [
        [150, 150, 150, 150, 150, 150, 150, 150, 147, 141, 134, 128],
        [122, 116, 109, 103, 97, 91, 84, 78, 72, 66],
        [59, 53, 50, 50, 50, 50, 50, 50, 50, 50],
    ]
    ref1, ref2 = sum(ref1, []), sum(ref2, [])

    assert np.allclose(sq[0, :, 0], ref1, atol=1)
    assert np.allclose(sq[:, 0, 0], ref2, atol=1)
    assert np.allclose(sq[0, :, 1], ref1, atol=1)
    assert np.allclose(sq[:, 0, 1], ref2, atol=1)
    assert np.all(sq[:, :, 2] == 0)  # blue
    assert np.all(sq[:, :, 3] == 255)  # alpha

if __name__ == "__main__":
    run_tests(globals())


from numpy import cos, pi, sqrt, linspace
import matplotlib.pyplot as plt
R = 0.010
L = 0.07
alpha = linspace(0, 2*pi, 100)
def X(a):
    return sqrt(L**2+R**2-2*L*R*cos(a))
def Xa(b):
    return L*(1-(R/L)*cos(b))
def Erreur(c):
    return ((X(c)- Xa(c) )/X(c)) *100
plt.close()
plt.figure(1)
y = X(alpha)
ymin = min(y)
ymax = max(y)
C = ymax-ymin
"""
plt.plot(alpha, X(alpha), 'r', lw=3, label = 'X exact')
plt.plot(alpha, Xa(alpha), 'b', lw=3, label = 'X approché')
"""
"""
plt.title('Tracé de la courbe de X(alpha)', fontsize =14, fontweight = 'bold', color= 'blue')
plt.ylabel('X en m')
plt.xlabel('alpha en rad', fontsize=12)

plt.xlim(0, max(alpha))
plt.ylim(0.95*min(X(alpha)), 1.05*max(X(alpha)))

plt.legend()
plt.plot(alpha, Erreur(alpha))
"""
liste = [0.02, 0.07, 0.1]
index = 0
maxi = 0
for i in range(len(liste)):
    L= liste[i]
    maxi =0
    index = 0
    plt.subplot(int("23"+ str(i+1)))
    plt.plot(alpha, X(alpha), 'r', label = "X exact")
    plt.plot(alpha, Xa(alpha), 'b', label = 'X approché')
    plt.legend()
    plt.subplot("23" + str(i+4))
    plt.plot(alpha, Erreur(alpha), label = "Erreur pour L =" + str(liste[i]))
    plt.legend()
    for i in range(len(Erreur(alpha))):
        if Erreur(alpha)[i]>maxi:
            maxi = Erreur(alpha)[i]
            index = alpha[i]
    print("Pour L=", L, " on a une erreur max de ", maxi, " atteint pour un angle alpha =", index)

L=0.02
j = max(Erreur(alpha))
while j> 1/100:
    L +=0.01
    j = max(Erreur(alpha))
print("La valeur de L la plus petit assurant une erreur maximale inférieur a 1 % est", round(L, 3), "m")
plt.show()


from unityparser import UnityDocument
from enum import Enum
import yaml
import json
import os

def removeUnityTagAlias(filepath):
    """
    Name:               removeUnityTagAlias()
    Description:        Loads a file object from a Unity textual scene file, which is in a pseudo YAML style, and strips the
                        parts that are not YAML 1.1 compliant. Then returns a string as a stream, which can be passed to PyYAML.
                        Essentially removes the "!u!" tag directive, class type and the "&" file ID directive. PyYAML seems to handle
                        rest just fine after that.
    Returns:                String (YAML stream as string)
    """
    result = str()
    sourceFile = open(filepath, 'r')

    fileID = ''
    for lineNumber,line in enumerate( sourceFile.readlines() ):
        if line.startswith('--- !u!'):
            result += '---' + '\n'
            fileID = line.split(' ')[2].replace('&', '')   # remove the tag, but keep file ID
        else:
            # Just copy the contents...
            result += line
            if fileID != '':
                result += ('  instanceID: ' + fileID + '\n')
                fileID = ''

    sourceFile.close()

    return result

def getPrefabGuid(prefabInstance):
    return prefabInstance['m_SourcePrefab']['guid']

class SupportedPrefabGuid(Enum):
    floor = '25399a8663513438abe48fcceca3e09e'
    floorConcave = '3b68c9bc9bd2648e8852d4d2b19e4673'
    ice = '08c6a9191fe224a179b16832b8d4ff63'
    iceConcave = '311bfe237ebcc4c2085daad068a2412b'
    wall = 'e3a352e5e460640c99199adbd07d7925'
    trap = '9a04efca5190044af8c9cb52b1da8944'
    checkpoint = '57b4cb67c63b54e09ab4f8a32995c2ef'
    lava = 'e1858a08e2538704fbb588752fee4e3e'
    spike = 'c5ca291e14223427ca02c6e1181c1d5e'
    door = 'ac57bdd24b4c040218eb99c8a6b95be9'
    triggerBoard = '6cfeb0107473b4df588127baf9804cd5'

class TriggerAction(Enum):
    move = 'Move'
    resetPosition = 'ResetPosition'

def tryGetValueFromDict(dict, name, defaultValue = None):
    if name in dict:
        return dict[name]
    else:
        return defaultValue

def moveActionHandler(data, actionName):
    params = {
        'x':tryGetValueFromDict(data, actionName + '.arguments.Array.data[0].vector3Argument.x'),
        'y':tryGetValueFromDict(data, actionName + '.arguments.Array.data[0].vector3Argument.y'),
        'z':tryGetValueFromDict(data, actionName + '.arguments.Array.data[0].vector3Argument.z')
    }
    return params

class EventName(Enum):
    onPlayerEnterEvent = 'OnPlayerEnterEvent'
    onPlayerExitEvent = 'OnPlayerExitEvent'

numberOfPrefabs = {}
for item in SupportedPrefabGuid:
    numberOfPrefabs[item] = 0
numberOfPrefabs['other'] = 0

levelName = 'All_Levels(Draft 1).unity'

document = os.getcwd() + '/Assets/Scenes/' + levelName
UnityStreamNoTags = removeUnityTagAlias(document)

ListOfNodes = list()

for data in yaml.safe_load_all(UnityStreamNoTags):
    ListOfNodes.append( data )

prefabInstances = list(filter(lambda x: 'PrefabInstance' in x, ListOfNodes))
gameObjectInstances = list(filter(lambda x: 'GameObject' in x, ListOfNodes))
transformInstances = list(filter(lambda x: 'Transform' in x, ListOfNodes))

def setKey(content, defaultValue=None, *names):
    for name in names:
        if name not in content:
            content[name] = defaultValue

def copyItems(target, source, *names):
    for name in names:
        if source and name in source:
            target[name] = source[name]
        else:
            target[name] = None

def findNodeByID(instanceID, content=ListOfNodes):
    for item in content:
        target = list(item.values())[0]
        if target['instanceID'] == instanceID:
            return target
    return None

def eventListHandler(content, sEventName, actionList):
    if sEventName + '.persistentCalls.calls.Array.size' not in content:
        return
    for x in range(content[sEventName + '.persistentCalls.calls.Array.size']):
            actionName = sEventName + '.persistentCalls.calls.Array.data[{}]'.format(x)
            if actionName + '.memberName' in content:
                action = {}
                action['event'] = sEventName
                action['target'] = content[actionName + '.target']
                action['memberName'] = content[actionName + '.memberName']
                if action['memberName'] == TriggerAction.move.value:
                    action['params'] = moveActionHandler(content, actionName)
                elif action['memberName'] == TriggerAction.resetPosition:
                    pass
                actionList.append(action)

tileFilterKeys = ('m_InstanceID', 'm_Name', 'm_IsActive', 'm_LocalPosition', 'm_LocalRotation',
     'm_SourcePrefab', 'm_Attributes', 'm_Actions')

maps = {}
for node in prefabInstances:
    dataDict = {}
    result = {}
    municipality = False
    levelTransformID = node['PrefabInstance']['m_Modification']['m_TransformParent']['fileID']
    levelTransform = findNodeByID(levelTransformID, transformInstances)
    levelGameObject = mapTransform = mapGameObject = None
    if not levelTransform:
        municipality = True
    else:
        if 'm_GameObject' not in levelTransform:
            continue
        levelGameObject = findNodeByID(levelTransform['m_GameObject']['fileID'], gameObjectInstances)
        mapTransform = findNodeByID(levelTransform['m_Father']['fileID'], transformInstances)
        if not mapTransform:
            municipality = True
        else:
            if 'm_GameObject' not in mapTransform:
                continue
            mapGameObject = findNodeByID(mapTransform['m_GameObject']['fileID'], gameObjectInstances)
    if not municipality:
        mapNode = levelNode = None
        if mapGameObject['m_Name'] not in maps:
            maps[mapGameObject['m_Name']] = {}
            mapNode = maps[mapGameObject['m_Name']]
            mapNode['m_InstanceID'] = mapTransform['instanceID']
            copyItems(mapNode, mapGameObject, 'm_Name', 'm_IsActive')
            copyItems(mapNode, mapTransform, 'm_LocalPosition', 'm_LocalRotation')
            mapNode['m_Levels'] = {}
            mapNode['m_Levels'][levelGameObject['m_Name']] = {}
        elif levelGameObject['m_Name'] not in maps[mapGameObject['m_Name']]['m_Levels']:
            maps[mapGameObject['m_Name']]['m_Levels'][levelGameObject['m_Name']] = {}
        mapNode = maps[mapGameObject['m_Name']]
        levelNode = mapNode['m_Levels'][levelGameObject['m_Name']]
        levelNode['m_InstanceID'] = levelTransform['instanceID']
        copyItems(levelNode, levelGameObject, 'm_Name', 'm_IsActive')
        copyItems(levelNode, levelTransform,'m_LocalPosition', 'm_LocalRotation')
        if 'm_Tiles' not in levelNode:
            levelNode['m_Tiles'] = []
        levelNode['m_Tiles'].append(result)

    modifications = node['PrefabInstance']['m_Modification']['m_Modifications']
    for data in modifications:
        if data['value'] != None:
            dataDict[data['propertyPath']] = data['value']
        else:
            if data['objectReference']['fileID'] == 0:
                continue
            dataDict[data['propertyPath']] = findNodeByID(data['objectReference']['fileID'])['m_PrefabInstance']['fileID']
    dataDict['m_SourcePrefab'] = getPrefabGuid(node['PrefabInstance'])
    dataDict['m_InstanceID'] = node['PrefabInstance']['instanceID']
    dataDict['m_LocalPosition'] = {'x': dataDict['m_LocalPosition.x'], 'y': dataDict['m_LocalPosition.y'], 'z': dataDict['m_LocalPosition.z']}
    dataDict['m_LocalRotation'] = {'x': dataDict['m_LocalRotation.x'], 'y': dataDict['m_LocalRotation.y'],
        'z': dataDict['m_LocalRotation.z'], 'w': dataDict['m_LocalRotation.w']}
    dataDict['m_Attributes'] = {}
    setKey(dataDict, 1, 'm_IsActive')
    # floor logic
    if dataDict['m_SourcePrefab'] == SupportedPrefabGuid.floor.value:
        numberOfPrefabs[SupportedPrefabGuid.floor] = numberOfPrefabs[SupportedPrefabGuid.floor] + 1
        setKey(dataDict['m_Attributes'], None, 'm_floorState', 'declineAfterExit', 'stepsBeforeIncline')
    # floorConcave logic
    elif dataDict['m_SourcePrefab'] == SupportedPrefabGuid.floorConcave.value:
        numberOfPrefabs[SupportedPrefabGuid.floorConcave] = numberOfPrefabs[SupportedPrefabGuid.floorConcave] + 1
    # ice logic
    elif dataDict['m_SourcePrefab'] == SupportedPrefabGuid.ice.value:
        numberOfPrefabs[SupportedPrefabGuid.ice] = numberOfPrefabs[SupportedPrefabGuid.ice] + 1
    # iceConcave logic
    elif dataDict['m_SourcePrefab'] == SupportedPrefabGuid.iceConcave.value:
        numberOfPrefabs[SupportedPrefabGuid.iceConcave] = numberOfPrefabs[SupportedPrefabGuid.iceConcave] + 1
    # wall logic
    elif dataDict['m_SourcePrefab'] == SupportedPrefabGuid.wall.value:
        numberOfPrefabs[SupportedPrefabGuid.wall] = numberOfPrefabs[SupportedPrefabGuid.wall] + 1
    # trap logic
    elif dataDict['m_SourcePrefab'] == SupportedPrefabGuid.trap.value:
        numberOfPrefabs[SupportedPrefabGuid.trap] = numberOfPrefabs[SupportedPrefabGuid.trap] + 1
    # checkpoint logic
    elif dataDict['m_SourcePrefab'] == SupportedPrefabGuid.checkpoint.value:
        numberOfPrefabs[SupportedPrefabGuid.checkpoint] = numberOfPrefabs[SupportedPrefabGuid.checkpoint] + 1
        setKey(dataDict['m_Attributes'], None, 'respawnObject')
    # lava logic
    elif dataDict['m_SourcePrefab'] == SupportedPrefabGuid.lava.value:
        numberOfPrefabs[SupportedPrefabGuid.lava] = numberOfPrefabs[SupportedPrefabGuid.lava] + 1
    # spike logic
    elif dataDict['m_SourcePrefab'] == SupportedPrefabGuid.spike.value:
        numberOfPrefabs[SupportedPrefabGuid.spike] = numberOfPrefabs[SupportedPrefabGuid.spike] + 1
        setKey(dataDict['m_Attributes'], None, 'spikeUp')
    # door logic
    elif dataDict['m_SourcePrefab'] == SupportedPrefabGuid.door.value:
        numberOfPrefabs[SupportedPrefabGuid.door] = numberOfPrefabs[SupportedPrefabGuid.door] + 1
    # triggerBoard logic
    elif dataDict['m_SourcePrefab'] == SupportedPrefabGuid.triggerBoard.value:
        numberOfPrefabs[SupportedPrefabGuid.triggerBoard] = numberOfPrefabs[SupportedPrefabGuid.triggerBoard] + 1
        actionList = list()
        eventListHandler(dataDict, EventName.onPlayerEnterEvent.value, actionList)
        eventListHandler(dataDict, EventName.onPlayerExitEvent.value, actionList)
        setKey(dataDict['m_Attributes'], actionList, 'm_Actions')
    # other logic
    else:
        numberOfPrefabs['other'] = numberOfPrefabs['other'] + 1
    for k in tileFilterKeys:
        if k in dataDict:
            result[k] = dataDict[k]
    #print(result)

sceneData = []
for k, v in maps.items():
    mapData = []
    for key, value in v['m_Levels'].items():
        mapData.append(value)
    v['m_Levels'] = mapData
    sceneData.append(v)

outfilePath = os.getcwd() + '/Assets/StreamingAssets/' + levelName + '.json'
outfile = open(outfilePath, 'w')
json.dump(sceneData, outfile, indent=4)
print('Successfully export to ' + outfilePath + '!')
outfile.close()


import pyverilog.vparser.ast as vast
from pyverilog.vparser.parser import parse
from pyverilog.ast_code_generator.codegen import ASTCodeGenerator

rtl = "test.v"
ast,_ = parse([rtl])
# get the root node of the tree (Description)
desc = ast.description
# get the ModuleDef node
definition = desc.definitions[0]
# get the portlist
# loop over all items with type InstanceList
# print the cell ports and their corresponding arguments

newrtl= []
inputlist = []
outputlist= []
clkgateArgs = [
 vast.PortArg("GCLK", vast.Identifier("__clockgate_output_gclk_")),
 vast.PortArg("GATE", vast.Identifier("EN")),
 vast.PortArg("CLK", vast.Identifier("CLK"))
]

clkgate_cell = vast.Instance(
 "sky130_fd_sc_hd__dlclkp",
 "__clockgate_cell__",
 tuple(clkgateArgs),
 tuple()
)
clockgate_output_gclk = vast.Wire('__clockgate_output_gclk_')

k=0
insertedbefore=0;
newrtl.append(clockgate_output_gclk)
for itemDeclaration in definition.items:
    item_type = type(itemDeclaration).__name__
    if item_type == "InstanceList":
        instance = itemDeclaration.instances[0]
        if(instance.module == "sky130_fd_sc_hd__mux2_1"):
            if insertedbefore ==0:
                newrtl.append(vast.InstanceList("sky130_fd_sc_hd__dlclkp", tuple(), tuple([clkgate_cell])))
                insertedbefore=1
            for hook in instance.portlist:
                if hook.portname == "A1": #input
                    inputlist.append(hook.argname)
                if hook.portname == "A0": #output
                    outputlist.append(hook.argname)
            continue
        print("cell-name: ", instance.module, "instance-name: ", instance.name)
        for hook in instance.portlist:
            if hook.portname == "CLK":
                print("change to clk input which is __clockgate_output_gclk_",hook.argname)
                hook.argname=vast.Identifier('__clockgate_output_gclk_')
            if hook.portname == "D":
                    hook.argname=inputlist[k]
            if hook.portname == "Q":
                    hook.argname=outputlist[k]
        k = k + 1
        print("portname: ", hook.portname, "argname: ", hook.portname)
    newrtl.append(itemDeclaration)

definition.items = tuple(newrtl)
codegen = ASTCodeGenerator()
rslt = codegen.visit(ast)
f = open("testUpdated.v", "w+")
f.write(rslt)
f.close()


from data import CITIES, USERS
from check import mse
import numpy as np

"""computes the item based mse of the complete city"""

mse_getal = 0
users_getal = 1

for city in CITIES:
    for user in USERS[city]:
        a, b = mse(user["user_id"])
        users_getal += b
        if not np.isnan(a):
            mse_getal += a * b
            print(user["user_id"], mse_getal / users_getal)

print(mse_getal / (users_getal - 1))


'''
Created on Jan 19, 2017

@author: Alexandre Day

    Purpose:
        Compute robustness of clustering for indivial data point

'''

import numpy as np
import pickle
from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
from sklearn import datasets
import time
from density_cluster import DCluster

def main():

    n_true_center=15
    n_sample=10000
    X,y=datasets.make_blobs(n_sample,2,n_true_center,random_state=0)

    dcluster=DCluster()
    idx_sub=np.sort(np.random.choice(range(n_sample), round(0.9*n_sample), replace=False))

    X_sub=X[idx_sub]

    cluster_label_X_sub,idx_centers,rho,delta,kd_tree=dcluster.fit(X_sub)

    """cluster_members is a dictionary from cluster (labelled from [0,n_center[ ) to the absolute idx of it's member points
    """

    cluster_label_X=np.full(n_sample,-1,dtype=np.int32)

    cluster_label_X[idx_sub]=cluster_label_X_sub

    cluster_members=group_by_label(cluster_label_X_sub,idx_sub)

    #print(NH_Cluster(idx_sub[np.random.randint(0,5000,5)],cluster_label_X,X,kd_tree,idx_sub))

def NH_Cluster(a_IDX,cluster_label_X,X,kd_tree,idx_sub):
    """
    Purpose:
        Determines the the neighborhood for data points identified
        by their absolute index in a_IDX array.
    Return:
        List of neighborhood (in absolute index) for each data point in a_IDX.
    """

    n_data=len(a_IDX)
    _,nn_r_IDX=kd_tree.query(list(X[a_IDX]), k=40)
    nn_a_IDX=idx_sub[nn_r_IDX]

    cluster_label_a_IDX=cluster_label_X[a_IDX].reshape(-1,1)

    cluster_label_nn_a_IDX=cluster_label_X[nn_a_IDX]

    tmp=(cluster_label_nn_a_IDX == cluster_label_a_IDX)

    return [nn_a_IDX[i][t] for i,t in zip(range(n_data),tmp)]

    #return cluster_members

def group_by_label(cluster_label,idx_sub):
    """
    Purpose:
        Given the cluster labels found for every data point, return a
        dictionnary from cluster label to absolute indices in that cluster
        The absolute indices are the indices of the data in the whole dataset

    """
    sort_idx = np.argsort(cluster_label)
    a_sorted = cluster_label[sort_idx]
    unq_first = np.concatenate(([True], a_sorted[1:] != a_sorted[:-1]))
    unq_items = a_sorted[unq_first]
    unq_count = np.diff(np.nonzero(unq_first)[0])
    groups=np.split(sort_idx, np.cumsum(unq_count))

    return dict(zip(unq_items,[np.sort(idx_sub[g]) for g in groups]))

#def NH_Cluster(a_IDX,cluster_members,):
#===============================================================================
#
#     idx_sub=np.random.shuffle(range(n_sample))[:round(0.9*n_sample)]
#
#
#
#
#     nn_dist,nn_list=tree.query(list(X), k=40)
#===============================================================================

#===============================================================================
#
#
#
# def NH(a_label,cluster,tree): # a_label refers to absolute label
#===============================================================================

if __name__=="__main__":
    main()


# for i in seq:
#     pass
#
# print("ok")

#两个问题：
#　循环次数由序列的一级元素的个数的决定

for item in ["hello",123,[2,3,4]]:
    if item==123:
        continue #结束本次循环
        #break    #结束整个循环
#     print("ok")
    print(item)
else:
    print("ending for")

print("ending")
# print(range(10))
#
# for i in range(10):
#     print("ok")

#while 条件表达式：
#执行代码
# while 2>1:
#     print("ok")

i=1
while i<101:
    print(i)
    i+=1

for i in range(1,101):  #等价于
    print(i)

#遍历并且打印索引方法一：
# count=0
# for i in [11,22,33]:
#     print("%s----$s"%(count,i))
#
#     count+=1

#方法二
# l=[1,2,333,4]
# for i in l:
#     print(l.index(i),i)

#方法三：
l=[1,2,333,4]
for i,v in enumerate(l):
    print(i,v)

#遍历并且打印索引方法一：
# count=0
# for i in [11,22,33]:
#     print("%s----$s"%(count,i))
#
#     count+=1

#方法二
# l=[1,2,333,4]
# for i in l:
#     print(l.index(i),i)

#方法三：
l=[1,2,333,4]
for i,v in enumerate(l):
    print(i,v)


import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import ode
import time

# import my classes
from laser import *
from molecule import *
from integrator import *
from const import *
from expectation_values import *

# close old plots.
# plt.close('all')

class ffa_sim:
    '''
    simulator of field free molecular alignment.  Needs molecule [str], temperature [K], pulse width [s] and intensity[10**14 W cm**-2].
    Default values are provided so you can simply run_sim after creating an instance of the ffa_sim class.
    '''
    def __init__(self, molecule= 'N2', temperature = 100, pulse = 100e-15, intensity = .1):
            self.molecule = molecule
            self.temperature = temperature
            self.pulse = pulse
            self.intensity = intensity

    def run_sim(self):
        # start time
        timer = time.time()
        # create molecule
        mol = molecule(self.molecule, self.temperature)
        # create laser
        las = laser(self.pulse, self.intensity)

        # generate usefule quantities
        Jmax = mol.params()[3]
        delta_alpha = mol.params()[2]
        B = mol.params()[0]
        D = mol.params()[1]
        Jweight = mol.Boltzmann()

        sigma = las.pulse_FWHM*B/hbar
        E0 = 2.74*10**10*las.Int**.5 # electric field amplitude
        strength=0.5*4*np.pi*epsilon0*delta_alpha*E0**2/B

        # create integrator
        intSEq = integrator(mol.params()[3], las.pulse_FWHM*B/hbar, strength, B, D)

        # integrate
        Cstor = intSEq.integrate()

        # Expectation value, incoherent, thermal average.
        exp_val = expectation_values(Jmax, sigma, strength, B, D)
        tt, cos2 = exp_val.cos2(Cstor, Jweight)
        # end timer
        elapsed = time.time() - timer
        print('\n Program took ' + str(round(elapsed)) + ' s to run. \n')
        # plot
        exp_val.cos2plot(tt,cos2, mol.mol_str)

        ## End program
        return tt, cos2

    def save_sim(self,tt,cos2):
        '''
        will put output saver here later.
        '''
        print('Not implemented yet!')


import re
import csv
from io import StringIO
from os import path
from functools import wraps
import unicodedata

from flask import (abort, current_app, session, request, redirect, url_for)
from flask_login import current_user

from notifications_utils.template import (
    SMSPreviewTemplate,
    EmailPreviewTemplate,
    LetterPDFLinkTemplate,
)

import pyexcel
import pyexcel.ext.io
import pyexcel.ext.xls
import pyexcel.ext.xlsx
import pyexcel.ext.ods3

class BrowsableItem(object):
    """
    Maps for the template browse-list.
    """

    def __init__(self, item, *args, **kwargs):
        self._item = item
        super(BrowsableItem, self).__init__()

    @property
    def title(self):
        pass

    @property
    def link(self):
        pass

    @property
    def hint(self):
        pass

    @property
    def destructive(self):
        pass

def user_has_permissions(*permissions, admin_override=False, any_=False):
    def wrap(func):
        @wraps(func)
        def wrap_func(*args, **kwargs):
            if current_user and current_user.is_authenticated:
                if current_user.has_permissions(
                    permissions=permissions,
                    admin_override=admin_override,
                    any_=any_
                ):
                    return func(*args, **kwargs)
                else:
                    abort(403)
            else:
                abort(401)
        return wrap_func
    return wrap

def redirect_to_sign_in(f):
    @wraps(f)
    def wrapped(*args, **kwargs):
        if 'user_details' not in session:
            return redirect(url_for('main.sign_in'))
        else:
            return f(*args, **kwargs)
    return wrapped

def get_errors_for_csv(recipients, template_type):

    errors = []

    if recipients.rows_with_bad_recipients:
        number_of_bad_recipients = len(list(recipients.rows_with_bad_recipients))
        if 'sms' == template_type:
            if 1 == number_of_bad_recipients:
                errors.append("fix 1 phone number")
            else:
                errors.append("fix {} phone numbers".format(number_of_bad_recipients))
        elif 'email' == template_type:
            if 1 == number_of_bad_recipients:
                errors.append("fix 1 email address")
            else:
                errors.append("fix {} email addresses".format(number_of_bad_recipients))
        elif 'letter' == template_type:
            if 1 == number_of_bad_recipients:
                errors.append("fix 1 address")
            else:
                errors.append("fix {} addresses".format(number_of_bad_recipients))

    if recipients.rows_with_missing_data:
        number_of_rows_with_missing_data = len(list(recipients.rows_with_missing_data))
        if 1 == number_of_rows_with_missing_data:
            errors.append("enter missing data in 1 row")
        else:
            errors.append("enter missing data in {} rows".format(number_of_rows_with_missing_data))

    return errors

def generate_notifications_csv(json_list):
    from app import format_datetime_24h, format_notification_status
    content = StringIO()
    retval = None
    with content as csvfile:
        csvwriter = csv.writer(csvfile)
        csvwriter.writerow(['Row number', 'Recipient', 'Template', 'Type', 'Job', 'Status', 'Time'])
        for x in json_list:
            csvwriter.writerow([
                int(x['job_row_number']) + 2 if 'job_row_number' in x and x['job_row_number'] else '',
                x['to'],
                x['template']['name'],
                x['template']['template_type'],
                x['job']['original_file_name'] if x['job'] else '',
                format_notification_status(x['status'], x['template']['template_type']),
                format_datetime_24h(x['created_at'])])
        retval = content.getvalue()
    return retval

def get_page_from_request():
    if 'page' in request.args:
        try:
            return int(request.args['page'])
        except ValueError:
            return None
    else:
        return 1

def generate_previous_dict(view, service_id, page, url_args=None):
    return generate_previous_next_dict(view, service_id, page - 1, 'Previous page', url_args or {})

def generate_next_dict(view, service_id, page, url_args=None):
    return generate_previous_next_dict(view, service_id, page + 1, 'Next page', url_args or {})

def generate_previous_next_dict(view, service_id, page, title, url_args):
    return {
        'url': url_for(view, service_id=service_id, page=page, **url_args),
        'title': title,
        'label': 'page {}'.format(page)
    }

def email_safe(string, whitespace='.'):
    # strips accents, diacritics etc
    string = ''.join(c for c in unicodedata.normalize('NFD', string) if unicodedata.category(c) != 'Mn')
    string = ''.join(
        word.lower() if word.isalnum() or word == whitespace else ''
        for word in re.sub(r'\s+', whitespace, string.strip())
    )
    string = re.sub(r'\.{2,}', '.', string)
    return string.strip('.')

class Spreadsheet():

    allowed_file_extensions = ['csv', 'xlsx', 'xls', 'ods', 'xlsm', 'tsv']

    def __init__(self, csv_data, filename=''):
        self.filename = filename
        self.as_csv_data = csv_data
        self.as_dict = {
            'file_name': self.filename,
            'data': self.as_csv_data
        }

    @classmethod
    def can_handle(cls, filename):
        return cls.get_extension(filename) in cls.allowed_file_extensions

    @staticmethod
    def get_extension(filename):
        return path.splitext(filename)[1].lower().lstrip('.')

    @staticmethod
    def normalise_newlines(file_content):
        return '\r\n'.join(file_content.read().decode('utf-8').splitlines())

    @classmethod
    def from_rows(cls, rows, filename=''):
        with StringIO() as converted:
            output = csv.writer(converted)

            for row in rows:
                output.writerow(row)
            return cls(converted.getvalue(), filename)

    @classmethod
    def from_file(cls, file_content, filename=''):
        extension = cls.get_extension(filename)

        if extension == 'csv':
            return cls(Spreadsheet.normalise_newlines(file_content), filename)

        if extension == 'tsv':
            file_content = StringIO(Spreadsheet.normalise_newlines(file_content))

        return cls.from_rows(pyexcel.get_sheet(
            file_type=extension,
            file_content=file_content.read()
        ).to_array(), filename)

def get_help_argument():
    return request.args.get('help') if request.args.get('help') in ('1', '2', '3') else None

def is_gov_user(email_address):
    valid_domains = current_app.config['EMAIL_DOMAIN_REGEXES']
    email_regex = (r"[\.|@]({})$".format("|".join(valid_domains)))
    return bool(re.search(email_regex, email_address.lower()))

def get_template(template, service, show_recipient=False, expand_emails=False):
    if 'email' == template['template_type']:
        return EmailPreviewTemplate(
            template,
            from_name=service['name'],
            from_address='{}@notifications.service.gov.uk'.format(service['email_from']),
            expanded=expand_emails,
            show_recipient=show_recipient
        )
    if 'sms' == template['template_type']:
        return SMSPreviewTemplate(
            template,
            prefix=service['name'],
            sender=service['sms_sender'],
            show_recipient=show_recipient
        )
    if 'letter' == template['template_type']:
        return LetterPDFLinkTemplate(
            template,
            service_id=service['id'],
        )


import logging
import os
import paste.translogger

def sesam_logger(logger_name, app=None, timestamp=False):
    if logger_name is None or logger_name is '':
        raise ValueError('Please provide a valid logger name.')
    logger = logging.getLogger(logger_name)
    log_level = os.getenv('LOG_LEVEL')
    level = logging.getLevelName(log_level.upper()) if log_level is not None else None
    stdout_handler = logging.StreamHandler()
    stdout_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'
                                                  if timestamp else '%(name)s - %(levelname)s - %(message)s'))
    logger.addHandler(stdout_handler)
    if app:
        app.wsgi_app = paste.translogger.TransLogger(app.wsgi_app, logger_name=logger.name, setup_console_handler=False)
        app.logger.addHandler(stdout_handler)
        logger.propagate = False
    if not isinstance(level, int):
        logger.warning("Unsupported value or no LOG_LEVEL provided. Hence, setting default log level to INFO.")
        level = logging.INFO
    logger.setLevel(level)
    return logger


from artiq.tools import simple_network_args
import parser
import argparse
import logging
from artiq.tools import verbosity_args, init_logger
from artiq.tools import bind_address_from_args
from artiq.protocols.pc_rpc import simple_server_loop
import sys

class Controller(object):
    default_port = 3249
    args = None
    name = None

    def __init__(self):
        if self.name is None:
            self.name = self.__class__.__name__
        self.add_global_args()
        self.add_args()
        self.parse_args()
        self.create_logger()
        self.load_drivers()

    def add_global_args(self):
        self.parser = argparse.ArgumentParser(description=self.description)
        self.parser.add_argument(
            "-d", "--device", default=None,
            required=True,
            help="serial port (e.g. COM3).")
        simple_network_args(self.parser, self.default_port)
        verbosity_args(self.parser)

    '''
    Implemented in derived class
    '''
    def add_args(self):
        pass

    def parse_args(self):
        self.args = self.parser.parse_args()
        self.bind_address = bind_address_from_args(self.args)
        self.port = self.args.port

    def create_logger(self):
        self.logger = logging.getLogger(self.name)
        init_logger(self.args)

    def load_drivers(self):
        self.drivers = {}
        for device in self.devices:
            try:
                module = __import__("devices.%s.driver" % device, fromlist=["devices.%s" % device])
                class_ = getattr(module, camel_case(device))
                driver = class_(self.args, self.logger)
                if callable(getattr(driver, "close", None)):
                    driver.load()
                self.drivers[device] = driver
                self.logger.info(" Loaded driver for %s" % (device))
            except ImportError:
                self.logger.error(" Unable to import driver for %s" % device)
            except:
                self.logger.error(" Error occured while importing driver for %s" % device)

    def loop(self):
        try:
            for addr in self.bind_address:
                self.logger.info(" Binding to %s on port %s" % (addr, self.port))
            simple_server_loop(self.drivers, self.bind_address, self.port)
        except (KeyboardInterrupt, SystemExit):
            sys.exit(0)
        finally:
            self.close_drivers()

    def close_drivers(self):
        for device, driver in self.drivers.items():
            if callable(getattr(driver, "close", None)):
                self.logger.info(" Closing driver for %s" % device)
                driver.close()

def camel_case(string):
    return string.title().replace("_", "")


# -*- coding: utf-8 -*-
"""
© Michael Widrich, Markus Hofmarcher, 2017
Functions for computations of losses

"""

import tensorflow as tf
import numpy as np
from collections import OrderedDict

from TeLL.initializations import weight_gauss_conv2d
from TeLL.dataprocessing import gaussian_blur

def image_crossentropy(pred, target, class_weights=None, loss_slack=0, reduce_by='debug', calc_statistics=False,
                       incl_histograms=False, pixel_weights=None):
    """
    Calculate the pixelwise cross-entropy loss.

    Parameters
    -----
    pred : tensorflow tensor
        Predicted classes per pixel as tensor of shape(samples, x, y, features) or
        (samples, sequence_positions, x, y, features); features are the output neurons/features of e.g. a conv. layer
    target : tensorflow tensor shape=(samples, x, y)
        Target classes per pixel as tensor of shape(samples, x, y) or (samples, sequence_positions, x, y);
    class_weights : numpy array shape=(n_classes) or None
        Factors for weighting the classes
    loss_slack : float in range [0, 1]
        Ignore error measured w.r.t. the softmax output (range [0, 1]) and the true labels (range [0, 1]), i.e.
        ce_loss *= ce_loss > tf.log(1-loss_slack); loss_slack should be in range [0, 1];
    reduce_by : string ("mean", "sum", "weighted_sum")
        Reduce losses for each pixel to scalar by either mean (sum/n_pixels), sum, or weighted sum (sum/weighted_pixels)
    calc_statistics : bool
        If False: return tuple with (loss, {})
        If True: return tuple with (loss, loss_statistics), where loss_statistics is a OrderedDict with various tensors
        for loss evaluation
    incl_histograms : bool
        If True: also include histograms in statistics
    pixel_weights : tensor or None
        Float32 tensor holding weights for the individual pixels; Has same shape as target;

    Returns
    -----
    Tuple with cross-entropy loss as tensorflow scalar and optional statistics (see calc_statistics)

    """

    with tf.variable_scope('crossentropy_loss') as scope:
        scope.reuse_variables()
        loss_statistics = OrderedDict()

        # Select predictions where true label != 0
        # flatten label matrix
        target_classes = tf.reshape(target, shape=(-1,))

        if pixel_weights is not None:
            target_weights = tf.reshape(pixel_weights, shape=(-1,))
        else:
            target_weights = tf.ones(target_classes.shape)

        n_pixels = target_classes.get_shape()[0]
        n_classes = pred.get_shape()[-1]
        # generate element-wise indices for selection from flattened matrix
        inds_mult = tf.range(start=0, limit=n_pixels * n_classes, delta=n_classes)
        target_inds = target_classes + inds_mult

        #
        # Calculate numerically stable log-softmax (=cross-entropy softmax)
        #

        # gather relevant predictions (i.e. predictions at target index)
        target_pred = tf.gather(tf.reshape(pred, shape=(-1,)), target_inds)

        # Reshape prediction matrix
        pred_reshaped = tf.reshape(pred, shape=(tf.reduce_prod(pred.get_shape()[:-1]), -1))

        # Calc log-softmax
        if loss_slack > 0:
            # Calculate log-softmax at once (more stable + faster)
            log_softmax = target_pred - tf.reduce_logsumexp(pred_reshaped, axis=[1])
            # Apply slack
            log_softmax *= tf.cast(log_softmax < tf.log(1.0 - loss_slack), dtype=tf.float32)
        else:
            # Calculate log-softmax at once (more stable + faster)
            log_softmax = target_pred - tf.reduce_logsumexp(pred_reshaped, axis=[1])

        #
        # Apply pixel-wise weighting
        #
        if pixel_weights is not None:
            log_softmax *= target_weights

        # Calculate cross-entropy loss
        if class_weights is None:
            ce_loss = log_softmax
        else:
            # turn class_weights into tensorflow tensor
            class_weights = tf.constant(class_weights, dtype=tf.float32)
            # multiply cross-entropies elementwise with corresponding class weigth
            class_weights_pixel = tf.gather(class_weights, target_classes)
            ce_loss = log_softmax * class_weights_pixel

            if calc_statistics:
                for cl in range(n_classes):
                    class_mask = tf.equal(target_classes, tf.constant(cl))
                    pixel_ce_per_class = -tf.boolean_mask(log_softmax, class_mask)
                    if incl_histograms:
                        loss_statistics['pixel ce class {}'.format(cl)] = pixel_ce_per_class
                    loss_statistics['mean ce class {}'.format(cl)] = (tf.reduce_sum(pixel_ce_per_class) /
                                                                      tf.reduce_sum(target_weights))

            if incl_histograms:
                loss_statistics['ce per pixel'] = -ce_loss
            loss_statistics['weighted sum ce'] = -tf.reduce_sum(ce_loss) / tf.reduce_sum(class_weights_pixel *
                                                                                target_weights)

        loss_statistics['mean ce'] = -tf.reduce_sum(ce_loss) / tf.reduce_sum(target_weights)

        # Return cross-entropy loss
        if calc_statistics:
            if reduce_by == 'mean':
                return loss_statistics['mean ce'], loss_statistics
            elif reduce_by == 'sum':
                return tf.reduce_sum(-ce_loss), loss_statistics
            elif reduce_by == 'weighted_sum':
                return loss_statistics['weighted sum ce'], loss_statistics
        else:
            if reduce_by == 'mean':
                return loss_statistics['mean ce'], {}
            elif reduce_by == 'sum':
                return tf.reduce_sum(-ce_loss), {}
            elif reduce_by == 'weighted_sum':
                return loss_statistics['weighted sum ce'], {}

def crossentropy_without_softmax(output, target):
    """Crossentropy between an output tensor and a target tensor.
    In contrast to tf.nn.softmax_crossentropy_with_logits expects probabilities (i.e. does not perform softmax).

    WARNING: Numerically not stable, use at your own risk!

    # Arguments
        output: A tensor resulting from a softmax.
        target: A tensor of the same shape as `output`.
    # Returns
        Output tensor.
    """
    # Note: tf.nn.softmax_cross_entropy_with_logits
    # expects logits, here we expect "probabilities".
    return - tf.reduce_sum(target * tf.log(output), reduction_indices=len(output.get_shape()) - 1)

def softmax(target, axis, name=None):
    """
    Multi dimensional softmax,
    refer to https://github.com/tensorflow/tensorflow/issues/210

    compute softmax along the dimension of target
    the native softmax only supports batch_size x dimension
    """
    with tf.name_scope(name, 'softmax', values=[target]):
        max_axis = tf.reduce_max(target, axis, keep_dims=True)
        target_exp = tf.exp(target - max_axis)
        normalize = tf.reduce_sum(target_exp, axis, keep_dims=True)
        softmax = target_exp / normalize
        return softmax

def blurred_cross_entropy(output, target, filter_size=11, sampling_range=3.5, pixel_weights=None):
    """
    Apply a Gaussian smoothing filter to the target probabilities (i.e. the one-hot
    representation of target) and compute the cross entropy loss between softmax(output)
    and the blurred target probabilities.

    :param output: A rank-4 or rank-5 tensor with shape=(samples, [sequence_position,] x, y, num_classes)
        representing the network input of the output layer (not activated)
    :param target: A rank-3 or rank-4 tensor with shape=(samples, [sequence_position,] x, y) representing
        the target labels. It must contain int values in 0..num_classes-1.
    :param filter_size: A length-2 list of int specifying the size of the Gaussian filter that will be
        applied to the target probabilities.
    :param pixel_weights: A rank-3 or rank-4 tensor with shape=(samples, [sequence_position,] x, y)
        representing factors, that will be applied to the loss of the corresponding pixel. This can be
        e.g. used to void certain pixels by weighting them to 0, i.e. suppress their error induction.
    :return: A scalar operation representing the blurred cross entropy loss.
    """
    # convert target to one-hot
    output_shape = output.shape.as_list()
    one_hot = tf.one_hot(target, output_shape[-1], dtype=tf.float32)

    if (len(output_shape) > 4):
        one_hot = tf.reshape(one_hot, [np.prod(output_shape[:-3])] + output_shape[-3:])

    # blur target probabilities
    #gauss_filter = weight_gauss_conv2d(filter_size + [output_shape[-1], 1])
    #blurred_target = tf.nn.depthwise_conv2d(one_hot, gauss_filter, [1, 1, 1, 1], 'SAME')
    blurred_target = gaussian_blur(one_hot, filter_size, sampling_range)

    if (len(output_shape) > 4):
        blurred_target = tf.reshape(blurred_target, output_shape)

    # compute log softmax predictions and cross entropy
    log_pred = output - tf.reduce_logsumexp(output, axis=[len(output_shape) - 1], keep_dims=True)

    # Apply pixel-wise weighting
    if pixel_weights is not None:
        log_pred *= pixel_weights

    cross_entropy = -tf.reduce_sum(blurred_target * log_pred, axis=[len(output_shape)-1])

    if pixel_weights is not None:
        loss = tf.reduce_sum(cross_entropy) / tf.reduce_sum(pixel_weights)
    else:
        loss = tf.reduce_mean(cross_entropy)

    return loss

def one_hot_patch(x, depth):
    # workaround by name-name
    sparse_labels = tf.reshape(x, [-1, 1])
    derived_size = tf.shape(sparse_labels)[0]
    indices = tf.reshape(tf.range(0, derived_size, 1), [-1, 1])
    concated = tf.concat(axis=1, values=[indices, sparse_labels])
    outshape = tf.concat(axis=0, values=[tf.reshape(derived_size, [1]), tf.reshape(depth, [1])])
    return tf.sparse_to_dense(concated, outshape, 1.0, 0.0)

def iou_loss(pred, target, calc_statistics=False, pixel_weights=None):
    """
    Calculate the approximate IoU loss according to
    "Rahman, A., & Wang, Y. (2016). Optimizing Intersection-Over-Union in Deep Neural Networks for Image Segmentation.
    International Symposium on Visual Computing."
    {http://www.cs.umanitoba.ca/~ywang/papers/isvc16.pdf}

    Parameters
    -----
    pred : tensorflow tensor
        Predicted classes per pixel in a tensor of shape(samples, x, y, features) or
        (samples, sequence_positions, x, y, features); Features are the output neurons/features of e.g. a conv. layer
        to be used for softmax calculation (i.e. linear output units);
    target : tensorflow tensor
        Target classes per pixel in tensor of shape(samples, x, y) or (samples, sequence_positions, x, y);
    calc_statistics : bool
        If False: return tuple with (loss, {})
        If True: return tuple with (loss, loss_statistics), where loss_statistics is a OrderedDict with various tensors
        for loss evaluation
    pixel_weights : tensor or None
        Float32 tensor holding weights for the individual pixels; Has same shape as target;

    Returns
    -----
    Tuple with IoU loss as tensorflow scalar and optional statistics (see calc_statistics)
    """

    # if pixel_weights is not None:
    #     # TODO: pixel_weights for iou loss
    #     raise ValueError("pixel_weights not implemented for iou loss yet; please create a feature request; sorry!")

    with tf.variable_scope('iou_loss') as scope:
        scope.reuse_variables()
        loss_statistics = OrderedDict()

        #
        # Make sure pred and target have correct shape
        #
        pred_shape = pred.get_shape().as_list()
        n_classes = pred_shape[-1]
        if len(pred_shape) == 5:
            pred = tf.reshape(pred, [-1] + pred_shape[2:])
        elif len(pred_shape) == 4:
            pass
        else:
            raise AttributeError("pred must have 4 or 5 dimensions but has shape {}".format(pred_shape))

        target_shape = target.get_shape().as_list()
        if len(target_shape) == 4:
            target = tf.reshape(target, [-1] + target_shape[2:])
            pixel_weights = tf.reshape(pixel_weights, [-1] + target_shape[2:])
        elif len(target_shape) == 3:
            pass
        else:
            raise AttributeError("target must have 3 or 4 dimensions but has shape {}".format(target_shape))

        # Calculate softmax of predictions
        pred_softmax = softmax(pred, 3, name="iou_loss_softmax")

        # Convert targets to one-hot encoding resulting in same shape as prediction (batch, x, y, features)
        # target_onehot = tf.one_hot(target, pred.get_shape()[-1], on_value=1.0, off_value=0.0, dtype=tf.float32)
        target_onehot = tf.reshape(one_hot_patch(tf.reshape(target, shape=(-1,)),
                                                 pred.get_shape()[-1]),
                                   shape=(tuple(target.get_shape().as_list()) + (pred.get_shape().as_list()[-1],)))

        # approximate intersection and union per class (Eq. 3 and 4)
        if pixel_weights is not None:
            intersection = tf.reduce_sum(pred_softmax * target_onehot * tf.expand_dims(pixel_weights, axis=-1),
                                         axis=[-3, -2])
            union = tf.reduce_sum(((pred_softmax + target_onehot) - (pred_softmax * target_onehot))
                                  * tf.expand_dims(pixel_weights, axis=-1), axis=[-3, -2])
        else:
            intersection = tf.reduce_sum(pred_softmax * target_onehot, axis=[-3, -2])
            union = tf.reduce_sum((pred_softmax + target_onehot) - (pred_softmax * target_onehot), axis=[-3, -2])

        # iou_per_sample_per_class has shape (samples, classes)
        iou_per_sample_per_class = tf.div(intersection, union)

        iou_per_sample = list()
        for i in range(0, target_shape[0]):
            nonzero = tf.is_finite(iou_per_sample_per_class[i])
            iou_per_sample.append(tf.reduce_mean(tf.boolean_mask(iou_per_sample_per_class[i], nonzero)))

        iou = tf.reduce_mean(tf.convert_to_tensor(iou_per_sample, dtype=tf.float32))

        # IoU Loss (Eq. 5)
        loss = tf.subtract(tf.constant(1.0, dtype=tf.float32), iou)

        if calc_statistics:
            # Get IoU per class for evaluation purposes
            iou_per_class = tf.reduce_mean(iou_per_sample_per_class, axis=0)
            for cl in range(n_classes):
                loss_statistics['IoU class {}'.format(cl)] = iou_per_class[tf.constant(cl)]

            loss_statistics['IoU mean'] = iou
            return loss, loss_statistics
        else:
            return loss, {}


#python 3.5.2
# -*- coding: utf-8 -*-

def mToken(str):
    return str.split(" ");

# método básico de interpretação
def interpretar(pedacos):
    if pedacos[0] == "some":
        return somar(pedacos)
    elif pedacos[0] == "subt":
        return subtrair(pedacos)
    elif pedacos[0] == "div": # só aceita dois parâmetros
        valor1 = int(pedacos[1])
        valor2 = int(pedacos[2])
        return dividir(valor1, valor2)
    elif pedacos[0] == "mult":
        return multiplicar(pedacos)
    elif pedacos[0] == "raiz":
        indice = int(pedacos[1])
        radicando = int(pedacos[2])
        return raiz(indice, radicando)
    else:
        return "'"+ pedacos[0] + "' não é um comando reconhecido \nDigite 'help' para mais informações:"

def somar(pedacos):
    valores = 0
    tam = pedacos.__len__()
    pedacos[0] = 0
    for i in range(tam):
        if(pedacos[i]) == ' ':
            valores += 0
            i += 1
        elif(pedacos[i]) == '':
            valores += 0
            i += 1
        else:
            valores += int(pedacos[i])
    return valores

def subtrair(pedacos):
    valores = 0
    tam = pedacos.__len__()
    pedacos[0] = 0
    for i in range(tam):
        if(pedacos[i]) == ' ':
            valores += 0
            i += 1
        elif(pedacos[i]) == '':
            valores += 0
            i += 1
        else:
            valores -= int(pedacos[i])
    return valores

def dividir(valor1, valor2):
    return valor1 / valor2

def multiplicar(pedacos):
    valores = 1
    tam = pedacos.__len__()
    pedacos[0] = 1
    for i in range(tam):
        if(pedacos[i]) == ' ':
            valores += 1
            i += 1
        elif(pedacos[i]) == '':
            valores += 1
            i += 1
        else:
            valores *= int(pedacos[i])
    return valores

def raiz(indice, radicando):
    return print("Raiz em processo de desenvolvimento...")

def addlog(str):
    file = open("log.bx", "r")
    conteudo = file.readlines()
    conteudo.append(str + "\n")
    file.close()
    file = open("log.bx","w")
    file.writelines(conteudo)
    file.close()

def mostrarlog():
    print("--- Histórico ---\n\n")
    file = open("log.bx","r")
    for linha in file:
        print(linha)

def main():
    print("----- Bem vindo ao BAX!!! -----")
    print("Versão: 0.1-2019")
    print("Digite 'help' para informações:\n")
    while True:
        str = input(">>: ")
        if str == "exit":
            print("Bye bye")
            break
        elif str == "help":
            print("\n----- HELP BAX ----\n")
            print("Comandos possíveis: ")
            print("some : [somar numeros inteiros; vários valores]")
            print("subt : [subtrair numeros inteiros; vários valores]")
            print("mult : [multiplicar numeros inteiros; vários valores]")
            print("div  : [dividir numeros inteiros; somente 2 numeros]\n")
            print("Exemplo de comando: 'some 1 1 2 3 4'\nSaída: 11\n")
            continue
        elif str == "clear":
            print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n")
            print("----- Bem vindo ao BAX!!! -----")
            print("Versão: 0.1-2019")
            print("Digite 'help' para informações:\n")
            continue
        elif str == "log":
            mostrarlog()
            continue
        addlog(str)
        pedacos = mToken(str)
        print(interpretar(pedacos))

main()


"""
:Created: 13 May 2016
:Author: Lucas Connors

"""

from django.shortcuts import render_to_response

from accounts.models import UserAvatar, UserAvatarURL

def require_email(strategy, details, user=None, is_new=False, *args, **kwargs):
    if not details.get('email'):
        return render_to_response('registration/error_email_required.html')

def save_avatar(strategy, details, user=None, is_new=False, *args, **kwargs):
    # Skip if we don't have the user yet
    if not user:
        return

    # Get avatar from provider, skip if no avatar
    provider = kwargs['backend'].name
    try:
        if provider == 'google-oauth2':
            avatar = kwargs['response']['image']
            is_default_avatar = avatar['isDefault']
        elif provider == 'facebook':
            avatar = kwargs['response']['picture']['data']
            is_default_avatar = avatar['is_silhouette']
        else:
            return
    except KeyError:
        return

    # Skip if the user just has the default avatar
    if is_default_avatar:
        return

    # Get avatar URL from provider
    try:
        avatar_url = avatar['url']
    except KeyError:
        return

    # For Google, use larger image than default
    if provider == 'google-oauth2':
        avatar_url = avatar_url.replace('?sz=50', '?sz=150')

    # Save avatar URL
    user_avatar, created = UserAvatar.objects.get_or_create(user=user, provider=provider)
    user_avatar_url, _ = UserAvatarURL.objects.update_or_create(avatar=user_avatar, defaults={'url': avatar_url,})

    # Update user's current avatar if none was ever set
    if created and not user.userprofile.avatar:
        user.userprofile.avatar = user_avatar
        user.userprofile.save()


"""
    tf2tflite.py
    ~~~~~~~~~~~~

    Converts TensorFlow2 model file to TensorFlow lite model file.
    Either Keras model file (.h5) or TF2 SavedModel directory can be converted.

    usage:
        python3 tf2tflite.py my_model.h5 my_model.tflite

        python3 tf2tflite.py models/my_model_saved_model my_model.tflite
"""

import sys
import tensorflow as tf

model_path = sys.argv[1]  # either h5 or SavedModel
outfile = sys.argv[2]  # xxxx.tflite

keras_model = (model_path[-3:] == '.h5')

if keras_model:
    model = tf.keras.models.load_model(model_path)
    converter = tf.lite.TFLiteConverter.from_keras_model(model)
else:
    converter = tf.lite.TFLiteConverter.from_saved_model(model_path)

tflite_model = converter.convert()
open(outfile, "wb").write(tflite_model)


from django.core import validators
from django.utils.translation import ugettext_lazy as _
from django import forms

from apps.main.models import Phrase, UserSuggestion, Post
from apps.validators import validate_suggestion

class NewPhraseForm(forms.ModelForm):
    phrase = forms.CharField(max_length=1000,
        label=_("Add a new phrase or a single word"),
        validators=[
            validators.RegexValidator(
                r'^[a-zA-Z,.;]+(?:)*$',
                _(u'Invalid word(s)'),
                code='Invalid word(s)')
        ],
    )
    translation = forms.CharField(max_length=1000,
        label=_("Submit translation")
    )

    class Meta:
        model = Phrase

class UserSuggestionForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(UserSuggestionForm, self).__init__(*args, **kwargs)
        self.fields['title'].validators.append(validate_suggestion)
        self.fields['body'].validators.append(validate_suggestion)

    class Meta:
        model = UserSuggestion
        fields = ['title', 'body']

class NewPostForm(forms.ModelForm):
    class Meta:
        model = Post
        # exclude = ('slug', 'status',)  Don't use exclude, explicit is better than implicit
        fields = ('title', 'body',)

class PostUpdateForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ('title', 'body',)


# -*- coding: utf-8 -*-
"""
Created on Tue May 23 19:05:01 2017
Machine Learning
Naive Bayes
@author: XU Shijian
"""
import numpy as np
import pickle
import math

X=pickle.load(open('train_data.pkl','rb')).todense() # unsupported in Python 2
y=pickle.load(open('train_targets.pkl','rb'))
Xt=pickle.load(open('test_data.pkl','rb')).todense()

c_n = 5
f_n = 5000
d_f = 2500
c_f = 2500

D = len(y)
D_c = np.zeros(c_n)
D_c_x = np.zeros((c_n, d_f, 2))

mu = np.zeros((c_n, c_f))
sigma = np.zeros((c_n, c_f))

##trian
print("training...")
for i in range(X.shape[0]):
    y_ = int(y[i])
    D_c[y_] += 1

    #离散属性统计
    for j in range(d_f):
        D_c_x[y_, j, int(X[i,j])] += 1

    #连续属性
    mu[y_] = mu[y_] + X[i, d_f:f_n]

for k in range(c_n):
    mu[k] = mu[k]/D_c[k]

for i in range(X.shape[0]):
    y_ = y[i]
    sigma[y_] = sigma[y_] + np.array((X[i,d_f:f_n]-mu[y_]))*np.array((X[i,d_f:f_n]-mu[y_]))

for k in range(c_n):
    sigma[k] = np.sqrt(sigma[k]/D_c[k])

#predict
print("predicting...")
pred = np.zeros(len(Xt))
for i in range(len(Xt)):
    if i%100 == 0:
        print(i)

    yt = 0
    probMax = -math.inf
    for kind in range(c_n):
        prob = 0
        prob = np.log((D_c[kind]+1)/(D+5))

        for j in range(d_f):
            prob += np.log((D_c_x[kind, j, int(Xt[i,j])] + 1)/(D_c[kind]+2))

        for j in range(c_f):
            if Xt[i,j] > 0:
                if sigma[kind,j] ==0 :
                    sigma[kind,j]=0.0001
                temp = ( 1/(np.sqrt(2*np.pi)*sigma[kind,j]) ) *np.exp(- (Xt[i,j]-mu[kind,j])*(Xt[i,j]-mu[kind,j])/(2*sigma[kind,j]*sigma[kind,j]))
                if temp != 0:
                    prob += np.log(temp)
                else:
                    prob+=0

        if prob > probMax:
            probMax = prob
            yt = kind
        else:
            pass

    pred[i]=yt

np.savetxt('test_predictions.csv', pred, fmt="%d", delimiter=",")


#!/usr/local/bin/python3
###!/Users/zhiyang/anaconda3/bin/python3

"""
	This Python script is written by Zhiyang Ong to measure the
		execution time of functions and programs in Python, and
		other processes and programs called from Python scripts
		or programs.

	Synopsis:
	Measure the execution time of functions and programs in Python.

	This script can be executed as follows:
	./performance_measurement.py

	Revision History:
	September 6, 2019			Version 0.1	Script.
"""

__author__ = 'Zhiyang Ong'
__version__ = '1.0'
__date__ = 'September 6, 2019'

#	The MIT License (MIT)

#	Copyright (c) <2019> <Zhiyang Ong>

#	Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

#	The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

#	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#	Email address: echo "cukj -wb- 23wU4X5M589 TROJANS cqkH wiuz2y 0f Mw Stanford" | awk '{ sub("23wU4X5M589","F.d_c_b. ") sub("Stanford","d0mA1n"); print $5, $2, $8; for (i=1; i<=1; i++) print "6\b"; print $9, $7, $6 }' | sed y/kqcbuHwM62z/gnotrzadqmC/ | tr 'q' ' ' | tr -d [:cntrl:] | tr -d 'ir' | tr y "\n"	Che cosa significa?

###############################################################
"""
	Import modules from The Python Standard Library.
	sys			Get access to any command-line arguments.
	os			Use any operating system dependent functionality.
	os.path		For pathname manipulations.

	subprocess -> call
				To make system calls.
	time		To measure elapsed time.
	warnings	Raise warnings.
	re			Use regular expressions.

	pathlib->Path
				For mapping a string to a path.
	datetime	To obtain information about the current date and time.
	time		To obtain information about the current time.
				time_ns version provides information about the
					current time with nanosecond accuracy.
	warnings	Provide warnings to users without terminating the
					program abruptly.
	process_time (& process_time_ns)
				To determine the time stamp using the process
					time method, which is platform independent in
					Python 3.x, and its alternative providing
					nanosecond accuracy.
	perf_counter (& perf_counter_ns)
				To determine the time stamp using the process
					time method, which is platform independent in
					Python 3.x, and its alternative providing
					nanosecond accuracy.
	monotonic (& pm_monotonic_ns)
				To monotonically obtain time stamps, for performance
					measurement, and its alternative providing
					nanosecond accuracy.
"""

import sys
import os
import os.path
#from pathlib import Path
from subprocess import call
import time
import warnings
import re
import datetime
# ImportError: cannot import name 'perf_counter_ns'
from time import perf_counter as pc_timestamp
from time import perf_counter_ns as pc_timestamp_ns
from time import process_time as pt_timestamp
from time import process_time_ns as pt_timestamp_ns
from time import time_ns as t_ns
from time import monotonic as pm_monotonic
from time import monotonic_ns as pm_monotonic_ns

###############################################################
#	Import Custom Python Packages and Modules
"""
	Module to calculate the factorial of a number.
"""
#from get_factorial import calculate_factorial
from utilities.timing_measurements.get_factorial import calculate_factorial

###############################################################
"""
	Module with methods that measure the execution time of functions
		and programs in Python.

	Support is not provided for storing multiple initial timestamps,
		so that we can measure elapsed times from different initial
		timestamps.
		User have to call the functions (such as monotonic_ns())
			specifically, so that this Python module can be kept
			simple and short.
"""
class execution_time_measurement:
	# Invalid timestamp.
	invalid_timestamp = -123456789012345678901234567890
	# Initial timestamp.
	initial_timestamp = invalid_timestamp
	# Types of performance measurement technique available.
	types_of_performance_measurement_technique = ("perf_counter","perf_counter_ns","process_time","process_time_ns","time","time_ns","monotonic","monotonic_ns")
	"""
		Type/method of current time measurement.
		Default option is: monotonic_ns.
	"""
	type_current_time_measurement = "monotonic_ns"
	# ============================================================
	##	Method to set the initial timestamp.
	#
	#	Use techniques for measuring performance (i.e., user
	#		execution time) and timestamps.
	#
	#	@param type_timestamp - Indicates if either of the following
	#				methods of performance measurement is preferred.
	#				* perf_counter, perf_counter(): pc_timestamp()
	#				* perf_counter_ns, perf_counter_ns(): pc_timestamp_ns()
	#				* process_time, process_time(): pt_timestamp()
	#				* process_time_ns, process_time_ns(): pt_timestamp_ns()
	#				* time, time.time(): time()
	#				* time_ns, time.time_ns(): time_ns()
	#				* monotonic, monotonic(): pm_monotonic()
	#				* monotonic_ns, monotonic_ns(): pm_monotonic_ns()
	#	@return - Nothing.
	#	O(1) method.
	@staticmethod
	def set_initial_timestamp(type_timestamp="monotonic_ns"):
		execution_time_measurement.type_current_time_measurement = type_timestamp
		"""
			Is the option for one of the following methods to measure
				time?
				* perf_counter, perf_counter(): pc_timestamp()
				* perf_counter_ns, perf_counter_ns(): pc_timestamp_ns()
				* process_time, process_time(): pt_timestamp()
				* process_time_ns, process_time_ns(): pt_timestamp_ns()
				* time, time.time(): time.time()
				* time_ns, time.time_ns(): time.time_ns()
				* monotonic, monotonic(): pm_monotonic()
				* monotonic_ns, monotonic_ns(): pm_monotonic_ns()
		"""
		if ("perf_counter" == type_timestamp):
			# Yes. Use perf_counter() to measure performance/time.
			execution_time_measurement.initial_timestamp = pc_timestamp()
		elif ("perf_counter_ns" == type_timestamp):
			# Yes. Use perf_counter_ns() to measure performance/time.
			execution_time_measurement.initial_timestamp = pc_timestamp_ns()
		elif ("process_time" == type_timestamp):
			# Yes. Use process_time() to measure performance/time.
			execution_time_measurement.initial_timestamp = pt_timestamp()
		elif ("process_time_ns" == type_timestamp):
			# Yes. Use process_time_ns() to measure performance/time.
			execution_time_measurement.initial_timestamp = pt_timestamp_ns()
		elif ("time" == type_timestamp):
			# Yes. Use time() to measure performance/time.
			execution_time_measurement.initial_timestamp = time.time()
		elif ("time_ns" == type_timestamp):
			# Yes. Use time_ns() to measure performance/time.
			execution_time_measurement.initial_timestamp = t_ns()
		elif ("monotonic" == type_timestamp):
			# Yes. Use monotonic() to measure performance/time.
			execution_time_measurement.initial_timestamp = pm_monotonic()
		else:
			# The default option is: "monotonic_ns()"
			execution_time_measurement.initial_timestamp = pm_monotonic_ns()
	# ============================================================
	##	Method to reset the initial timestamp to "invalid_timestamp".
	#
	#	@param - None.
	#	@return - Nothing.
	#	O(1) method.
	@staticmethod
	def reset_initial_timestamp():
		execution_time_measurement.initial_timestamp = execution_time_measurement.invalid_timestamp
	# ============================================================
	##	Method to get the initial timestamp.
	#	@return the initial timestamp.
	#	O(1) method.
	@staticmethod
	def get_initial_timestamp():
		return execution_time_measurement.initial_timestamp
	# ============================================================
	##	Method to get the type/method of current time measurement.
	#	@return the type/method of current time measurement.
	#	O(1) method.
	@staticmethod
	def get_type_current_time_measurement():
		return execution_time_measurement.type_current_time_measurement
	# ============================================================
	##	Method to determine the elapsed time from the initial
	#		timestamp.
	#	@return the elapsed time from the initial timestamp.
	#	@postcondition - (elapsed time > 0) shall always be true.
	#		Since methods can have microsecond (or even
	#			nanosecond) precision, I would just compare this to 0.
	#	O(1) method.
	@staticmethod
	def get_elapsed_time():
		"""
			Is the option for one of the following methods to measure
				time?
				* perf_counter, perf_counter(): pc_timestamp()
				* perf_counter_ns, perf_counter_ns(): pc_timestamp_ns()
				* process_time, process_time(): pt_timestamp()
				* process_time_ns, process_time_ns(): pt_timestamp_ns()
				* time, time.time(): time()
				* time_ns, time.time_ns(): time_ns()
				* monotonic, monotonic(): pm_monotonic()
				* monotonic_ns, monotonic_ns(): pm_monotonic_ns()
		"""
		if ("perf_counter" == execution_time_measurement.get_type_current_time_measurement()):
			# Yes. Use perf_counter() to measure performance/time.
			current_timestamp = pc_timestamp()
		elif ("perf_counter_ns" == execution_time_measurement.get_type_current_time_measurement()):
			# Yes. Use perf_counter_ns() to measure performance/time.
			current_timestamp = pc_timestamp_ns()
		elif ("process_time" == execution_time_measurement.get_type_current_time_measurement()):
			# Yes. Use process_time() to measure performance/time.
			current_timestamp = pt_timestamp()
		elif ("process_time_ns" == execution_time_measurement.get_type_current_time_measurement()):
			# Yes. Use process_time_ns() to measure performance/time.
			current_timestamp = pt_timestamp_ns()
		elif ("time" == execution_time_measurement.get_type_current_time_measurement()):
			# Yes. Use time.time() to measure performance/time.
			current_timestamp = time.time()
		elif ("time_ns" == execution_time_measurement.get_type_current_time_measurement()):
			# Yes. Use time.time_ns() to measure performance/time.
			current_timestamp = t_ns()
		elif ("monotonic" == execution_time_measurement.get_type_current_time_measurement()):
			# Yes. Use monotonic() to measure performance/time.
			current_timestamp = pm_monotonic()
		else:
			"""
				The default option is: "monotonic_ns".
				Use monotonic_ns() to measure performance/time.
			"""
			current_timestamp = pm_monotonic_ns()
		# Postcondition. Check if elapsed_time_in_ns > 0.
		elapsed_time_in_ns = current_timestamp - execution_time_measurement.get_initial_timestamp()
		execution_time_measurement.check_elapsed_time(elapsed_time_in_ns)
		return elapsed_time_in_ns
	# ============================================================
	##	Method to convert seconds to days, hours, minutes, and
	#		seconds.
	#	@param time_in_seconds - amount of time in seconds to be
	#								converted to days, hours,
	#								minutes, and seconds.
	#							It has a default value of 0
	#								seconds.
	#	@return - time in days, hours, minutes, and seconds.
	@staticmethod
	def convert_time_in_seconds_to_DD_HH_MM_SS(time_in_seconds=0):
		return datetime.timedelta(seconds=time_in_seconds)
	# ============================================================
	##	Method to compare techniques for measuring elapsed periods.
	#	It calculates the factorial of each number in a list, and
	#		uses each of the following methods of performance
	#		measurement to measure the elapsed periods.
	#		* perf_counter, perf_counter(): pc_timestamp()
	#		* perf_counter_ns, perf_counter_ns(): pc_timestamp_ns()
	#		* process_time, process_time(): pt_timestamp()
	#		* process_time_ns, process_time_ns(): pt_timestamp_ns()
	#		* time, time.time(): time()
	#		* time_ns, time.time_ns(): time_ns()
	#		* monotonic, monotonic(): pm_monotonic()
	#		* monotonic_ns, monotonic_ns(): pm_monotonic_ns()
	#	Subsequently, it writes the elapsed time to an output file.
	#	@return - Nothing.
	#	O(n!) method, where n is the largest number in the
	#		aforementioned list, since we are measuring the
	#		performance of calculating factorials.
	@staticmethod
	def compare_different_methods_to_measure_elapsed_periods():
		"""
			Create a file to store experimental data of measuring
				the performance of recursive and iterative methods.
		"""
		with open("compare_different_methods_to_measure_elapsed_periods.csv","a+") as op_f_obj:
			for perf_measurement_technique in execution_time_measurement.types_of_performance_measurement_technique:
				print("The technique used is:",perf_measurement_technique,"=")
				"""
					Set the initial timestamp for calculating the
						factorial of numbers via recursion.
				"""
				execution_time_measurement.set_initial_timestamp(perf_measurement_technique)
				print("	Calculate the factorial using recursion.")
				print("	= current timestamp:",execution_time_measurement.get_initial_timestamp(),"=")
				for x in range(0,20+1):
					print("		factorial of",x," is:",calculate_factorial.get_factorial_recursion(x),"=")
				"""
					Get the elapsed time for calculating the factorial of
						numbers via recursion.
				"""
				elapsed_time_recursion = execution_time_measurement.get_elapsed_time()
				print("	= elapsed_time_recursion:",elapsed_time_recursion,"=")
				"""
					Set the initial timestamp for calculating the
						factorial of numbers via iteration.
				"""
				execution_time_measurement.set_initial_timestamp(perf_measurement_technique)
				print("	Calculate the factorial using iteration.")
				print("	= current timestamp:",execution_time_measurement.get_initial_timestamp(),"=")
				for x in range(0,20+1):
					print("		factorial of",x," is:",calculate_factorial.get_factorial_iteration(x),"=")
				"""
					Get the elapsed time for calculating the factorial of
						numbers via iteration.
				"""
				elapsed_time_iteration = execution_time_measurement.get_elapsed_time()
				print("	= elapsed_time_iteration:",elapsed_time_iteration,"=")
				"""
					The timeit.timeit() method can result in negative elapsed time.
				"""
				text = perf_measurement_technique + "," + str(elapsed_time_recursion) + "," + str(elapsed_time_iteration) + "\n"
				op_f_obj.write(text)
				#op_f_obj.write("\n")
	# ============================================================
	##	Method to check if the elapsed time is a positive period.
	#	If the elapsed time is not positive, raise a warning to
	#		user.
	#	Use this method as an invariant, precondition, assertion,
	#		or postcondition, to ensure that elapsed time is not
	#		non-positive.
	#	@param elapsed_time - The elapsed time/period in seconds.
	#		Let the default value of the elapsed time/period be
	#			0.0 second (s), or 0 nanosecond (ns), depending
	#			on the selected method for measuring the current
	#			time.
	#	@return - Nothing.
	@staticmethod
	def check_elapsed_time(elapsed_time=0):
		if 0 >= elapsed_time:
			warnings.warn("Elapsed time is <= 0. It shouldn't be, by definition.")

###############################################################
# Main method for the program.

#	If this is executed as a Python script,
if __name__ == "__main__":
	print("==================================================")
	print("Compare techniques for measuring elapsed periods.")
	print("")
	execution_time_measurement.compare_different_methods_to_measure_elapsed_periods()


from __future__ import division

import numpy as np
import tensorflow as tf

from .base import Network

def build_shrinkage_net(in_dim, landmarks, bw, reg_out,
                        reg_out_bias=0, reg_obs_var=0, scale_reg_by_n=False,
                        dtype=tf.float32,
                        init_out=None, init_out_bias=None,
                        init_obs_var=1, init_tau_sq=1, init_eta_sq=1,
                        opt_tau_sq=True,
                        opt_landmarks=True,
                        shrink_towards=0, opt_shrinkage_mean=False,
                        use_real_R=True,
                        init_R_scale=1, opt_R_scale=False,
                        rbf_R_bw_scale=np.sqrt(2),
                        fixed_cov_matrix=None, use_alpha_reg=False,
                        precompute_feats=None, use_cholesky=True):
    n_land = landmarks.shape[0]

    if precompute_feats is None:
        precompute_feats = not opt_landmarks
    elif precompute_feats:
        assert not opt_landmarks

    net = Network(n_land if precompute_feats else in_dim, n_land, dtype=dtype)
    inputs = net.inputs
    params = net.params

    if precompute_feats:
        net.wants_means_only = True
        net.landmarks = landmarks  # save outside of tensorflow for convenience
        net.gamma = 1 / (2 * bw**2)

    # Model parameters
    params['landmarks'] = tf.Variable(
        tf.constant(landmarks, dtype=dtype), trainable=opt_landmarks)
    params['log_bw'] = tf.Variable(
        tf.constant(np.log(bw), dtype=dtype), trainable=opt_landmarks)

    params['shrink_towards'] = tf.Variable(
        tf.constant(shrink_towards, dtype=dtype, shape=[n_land]),
        trainable=opt_shrinkage_mean)
    params['log_R_scale'] = tf.Variable(
        tf.constant(np.log(init_R_scale), dtype=dtype), trainable=opt_R_scale)

    if init_out is None:
        out = tf.random_normal([n_land], dtype=dtype)
    else:
        assert np.size(init_out) == n_land
        out = tf.constant(np.resize(init_out, [n_land]), dtype=dtype)
    params['out'] = tf.Variable(out)

    if init_out_bias is None:
        out_bias = tf.random_normal([1], dtype=dtype)
    else:
        out_bias = tf.constant(init_out_bias, shape=(), dtype=dtype)
    params['out_bias'] = tf.Variable(out_bias)

    if fixed_cov_matrix is not None:
        params['Sigma'] = tf.Variable(
            tf.constant(fixed_cov_matrix, dtype=dtype), trainable=False)
    else:
        params['log_tau_sq'] = tf.Variable(
            tf.constant(np.log(init_tau_sq), dtype=dtype), trainable=opt_tau_sq)
        tau_sq = tf.exp(params['log_tau_sq'])
    if use_real_R:
        params['log_eta_sq'] = tf.Variable(
            tf.constant(np.log(init_eta_sq), dtype=dtype))
        eta_sq = tf.exp(params['log_eta_sq'])
    params['log_obs_var'] = tf.Variable(
        tf.constant(np.log(init_obs_var), dtype=dtype))

    # compute kernel stuff, reusing some temp values

    Y = params['landmarks']
    YY = tf.matmul(Y, Y, transpose_b=True)  # Y Y^T, Y is matrix of landmarks
    Y_sqnorms = tf.diag_part(YY)  # The norm square of Y

    gamma = 1 / (2 * tf.exp(2 * params['log_bw']))  # = 1 / (2 bw^2)
    if not precompute_feats:
        X = inputs['X']
        XY = tf.matmul(X, Y, transpose_b=True)
        X_sqnorms_s = tf.reduce_sum(tf.square(X), 1, keep_dims=True)
        Y_sqnorms_s = tf.expand_dims(Y_sqnorms, 0)
        kernel_layer = tf.exp(-gamma * (-2 * XY + X_sqnorms_s + Y_sqnorms_s))
    else:
        kernel_layer = inputs['X']

    # Added by Leon, for regularisation parameter of alpha^T K alpha
    if use_alpha_reg:
        net.K = K = tf.exp(-gamma * (
            -2 * YY + tf.expand_dims(Y_sqnorms, 1)
                    + tf.expand_dims(Y_sqnorms, 0)))

    # R matrix, to be used later
    if use_real_R:
        bw_sq = tf.exp(2 * params['log_bw'])
        # R kernel from https://arxiv.org/pdf/1603.02160.pdf appendix A.3
        # Sigma_theta = bw^2 * I
        net.R = R = tf.exp(params['log_R_scale']) * (
            # |2 Sigma_theta^-1 + eta^-2 I_D|^-(1/2)
            #    = | (2 bw^-2 + eta^-2) I_D |^(-1/2)
            #    = (2 bw^-2 + \ta^-2)^(-D/2)
            (2 * np.pi / (2 / bw_sq + 1 / eta_sq)) ** (in_dim/2)
            * tf.exp(-1 / (4 * bw_sq) * (
                - 2 * YY
                + tf.expand_dims(Y_sqnorms, 1)  # Like broadcast it in two ways
                + tf.expand_dims(Y_sqnorms, 0)
            ))
            # - 1/8 (x + y)^T (1/2 Sigma_theta + eta^2 I)^-1 (x + y)
            # = -1/(8(bw^2/2 + eta^2)) (x + y)^T (x + y)
            # = -1/(8(bw^2/2 + eta^2)) (x^T x + y^T y + 2 x^T y)
            * tf.exp(-1 / (8 * (bw_sq/2 + eta_sq)) * (
                2 * YY
                + tf.expand_dims(Y_sqnorms, 1)
                + tf.expand_dims(Y_sqnorms, 0)
            ))
        )
    else:
        gamma /= rbf_R_bw_scale**2
        net.R = R = tf.exp(params['log_R_scale']) * tf.exp(-gamma * (
            -2 * YY + tf.expand_dims(Y_sqnorms, 1)
                    + tf.expand_dims(Y_sqnorms, 0)))

    # Pool bags: shape (n_bags, n_land)
    layer_pool = net.bag_pool_layer(kernel_layer)

    # Bayesian posterior stuff
    # We need (R + c I)^{-1} times a bunch of different matrices, for different
    # values of c. It'd probably be faster to eigendecompose R so that we can
    # quickly get the inverse for different values of c, but it seems like
    # tensorflow 1.0 doesn't have working gradients for eigendecompositions.
    # Note that it's not easy to get a Cholesky factor for different c:
    #   http://math.stackexchange.com/q/1276559/19147
    # Since there's no way to tell tf.matrix_solve that the matrix in question
    # is PSD, though, we might as well use cholesky_solve.

    # make R + tau^2 / n I matrices; shape will be (n_bags, n_land, n_land)
    # TODO: if n is repeated a lot, we could be smarter about this and avoid
    #       doing repeated choleskys...maybe worth it since it often is

    # compute chol(R + Sigma/n_i) matrices; shape (n_bags, n_land, n_land)
    if fixed_cov_matrix is not None:
        adds = (
            tf.expand_dims(params['Sigma'], 0)  # 1, n_land, n_land
            / tf.reshape(inputs['sizes'], [-1, 1, 1])  # n_bags, 1, 1
        )
    else:
        tau_sq = tf.exp(params['log_tau_sq'])
        adds = tf.matrix_diag(
            tf.tile(tf.expand_dims(tau_sq / inputs['sizes'], 1), [1, n_land]))

    to_inverts = tf.expand_dims(R, 0) + adds
    if use_cholesky:
        chols = tf.cholesky(to_inverts)

    b = tf.expand_dims(params['out'], 1)  # n_land, 1
    Rb = tf.matmul(R, b)  # n_land, 1

    # we need a version of Rb that's (n_bags, n_land, 1),
    # since cholesky_solve doesn't broadcast on first axis.
    # but tf.tile won't take a Dimension(None) argument.
    # so, here's a dumb dumb hack. there must be a better way to do this....
    reshaper = 0 * tf.expand_dims(tf.expand_dims(inputs['sizes'], 1), 2)
    Rb_broad = reshaper + tf.expand_dims(Rb, 0)  # n_bags, n_land, 1
    if use_cholesky:
        inv_Rb = tf.cholesky_solve(chols, Rb_broad)  # n_bags, n_land, 1
    else:
        inv_Rb = tf.matrix_solve(to_inverts, Rb_broad)

    # posterior mean is   b^T R (R + tau^2/n I)^-1 (mu_hat - m0) + b^T m0
    m0 = tf.expand_dims(params['shrink_towards'], 0)  # [1, n_land]
    mu_hats = layer_pool  # n_bags, n_land
    mu_hat_deltas = mu_hats - m0

    net.output = posterior_means = (
        params['out_bias']
        + tf.squeeze(tf.matmul(  # n_bags
            tf.expand_dims(mu_hat_deltas, 1),  # n_bags, 1, n_land
            inv_Rb                             # n_bags, n_land, 1
        ), [1, 2])
        + tf.squeeze(tf.matmul(m0, b), [0, 1])
    )

    # posterior var is   b^T R b - b^T R^T (R + tau^2/n_i I)^-1 R b + sigma^2
    t1 = tf.squeeze(tf.matmul(b, Rb, transpose_a=True), [0, 1])
    t2 = tf.squeeze(-tf.matmul(Rb_broad, inv_Rb, transpose_a=True), [1, 2])
    t3 = tf.exp(params['log_obs_var'])
    net.output_var = posterior_vars = t1 + t2 + t3

    net.early_stopper = .5 * tf.reduce_mean(
        tf.log(posterior_vars) +
        tf.square(inputs['y'] - posterior_means) / posterior_vars)

    if scale_reg_by_n:
        n = tf.cast(tf.squeeze(tf.shape(net.output), [0]), dtype)
        reg_out /= n
        reg_out_bias /= n
        reg_obs_var /= n
    if use_alpha_reg:  # a^T K a loss
        loss_weights = tf.squeeze(
            tf.matmul(tf.matmul(b, K, transpose_a=True), b))  # b is n_land, 1
    else:
        loss_weights = tf.nn.l2_loss(b)

    net.loss = (
        net.early_stopper
        + reg_out * loss_weights
        + reg_out_bias * tf.nn.l2_loss(params['out_bias'])
        + reg_obs_var * tf.nn.l2_loss(tf.exp(params['log_obs_var']))
    )

    net.print_out_names = ["out_var"]
    net.print_out = [tf.exp(params['log_obs_var'])]
    if fixed_cov_matrix is None and opt_tau_sq:
        net.print_out_names.append("tau^2")
        net.print_out.append(tau_sq)
    if use_real_R:
        net.print_out_names.append("eta^2")
        net.print_out.append(tf.exp(params['log_eta_sq']))
    if opt_R_scale:
        net.print_out_names.append("R scale")
        net.print_out.append(tf.exp(params['log_R_scale']))

    return net


import os
import globalPar as gp
import Input_file_snippets as script

#######################################
##              WRITE                ##
#######################################
pc = gp.ParametersClass()

directory = 'workingDirectory'
if not os.path.exists(directory):
    os.makedirs(directory)
    os.chdir(directory)
else:
    os.chdir(directory)

alpha_dict = {'1.0':
                       {'GAM2': '1.D0', 'GAM3': '2.D0'},
                   '0.99':
                       {'GAM2': '1.0057065285003852D0', 'GAM3': '1.9914980762383867D0'},
                   '0.5':
                       {'GAM2': '1.12837916709551256D0', 'GAM3': '1.50450555612735015D0'},
                   '0.25':
                       {'GAM2': '1.0880652521310177D0', 'GAM3': '1.2435031452925913D0'},
                   '0.1':
                       {'GAM2': '1.03975413434763642D0', 'GAM3': '1.09447803615540673D0'}
                   }

vel_list = [20000] #vel_list = [1000, 25000, 50000]
s = 2.5
alphaVal = '0.75'
Tm_list = ['2.5D-6']
for Tm in Tm_list:
    for velocity_mm_s in vel_list:
        for d in pc.delta_dict:
            w_file = open('Plate-Alpha=' + alphaVal + '_' + d + '=' + pc.delta[:-2] + '_v=' + str(velocity_mm_s/1000)
                          + '_Tm=' + Tm + '.inp', 'wt')
            w_file.write(script.Heading(alphaVal, d, pc.delta))
            w_file.write(script.PartsAndAssembly('Plates.txt'))
            w_file.write(script.Material(alphaVal, pc.delta_dict[d], pc.alpha_dict[alphaVal]['GAM2'] + ', '
                          + pc.alpha_dict[alphaVal]['GAM3'], Tm, pc.m))
            w_file.write(script.StepAndFields(velocity_mm_s, s, pc.number_of_frames))
            w_file.close()


from pi3d import *
from pi3d import Texture
from pi3d.util import Utility

RECT_NORMALS = c_bytes(( 0,0,-1, 0,0,-1, 0,0,-1, 0,0,-1 ))
RECT_TEX_COORDS = c_bytes(( 0,255, 255,255, 255,0, 0,0))
RECT_TEX_COORDS2 = c_floats(( 0,1, 1,1, 1,0, 0,0))
RECT_VERTS_TL = c_bytes(( 1,0,0, 0,0,0, 0,-1,0, 1,-1,0 ))
RECT_VERTS_CT = c_bytes(( 1,1,0, -1,1,0, -1,-1,0, 1,-1,0 ))
RECT_TRIANGLES = c_bytes(( 3,0,1, 3,1,2 ))

def string(font, string, x, y, z, rot, sclx, scly):
  opengles.glNormalPointer(GL_BYTE, 0, RECT_NORMALS)
  Utility.texture_min_mag()
  opengles.glEnableClientState(GL_TEXTURE_COORD_ARRAY)
  opengles.glBindTexture(GL_TEXTURE_2D,font.tex)
  opengles.glEnable(GL_TEXTURE_2D)

  opengles.glDisable(GL_DEPTH_TEST)
  opengles.glDisable(GL_CULL_FACE)
  opengles.glEnable(GL_BLEND)
  opengles.glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA)

  mtrx =(c_float * 16)()
  opengles.glGetFloatv(GL_MODELVIEW_MATRIX,ctypes.byref(mtrx))
  Utility.translatef(x, y, z)
  Utility.rotatef(rot, 0, 0, 1)
  Utility.scalef(sclx, scly, 1)

  for c in range(0,len(string)):
    v = ord(string[c])-32
    w, h, texc, verts = font.chr[v]
    if v > 0:
      opengles.glVertexPointer(3, GL_FLOAT, 0,verts)
      opengles.glTexCoordPointer(2, GL_FLOAT,0,texc)
      opengles.glDrawElements( GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, RECT_TRIANGLES)
    Utility.translatef(w, 0, 0)

  opengles.glLoadMatrixf(mtrx)
  opengles.glDisable(GL_TEXTURE_2D)
  opengles.glDisable(GL_BLEND)
  opengles.glEnable(GL_DEPTH_TEST)
  opengles.glEnable(GL_CULL_FACE)

def _draw(verts, tex, x, y, w, h, r, z):
  opengles.glNormalPointer(GL_BYTE, 0, RECT_NORMALS);
  opengles.glVertexPointer(3, GL_BYTE, 0, verts);
  Utility.load_identity()
  Utility.translatef(x, y, z)
  Utility.scalef(w, h, 1)
  if r:
    Utility.rotatef(r, 0, 0, 1)
  with Texture.Loader(tex,RECT_TEX_COORDS,GL_BYTE):
    opengles.glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, RECT_TRIANGLES)

def rectangle(tex, x, y, w, h, r=0.0, z=-1.0):
  _draw(RECT_VERTS_TL, tex, x, y, w, h, r, z)

def sprite(tex, x, y, z=-10.0, w=1.0, h=1.0, r=0.0):
  _draw(RECT_VERTS_CT, tex, x, y, w, h, r, z)