#ID	Title	Description	Language	Affiliation	Creator	Publisher	File Format
#HE/FE	Record Origin	Record Created Date	JAX Classification	Subject Keywords	Type

import uuid
from random import random, randint
import os, csv
from datetime import datetime
import time

SIZE = 100
MAX_VIEWS = 100
MAX_DOWNLOADS = 50

LANGUAGES = [("en", 0.1), ("en-GB", 0.7), ("en-US", 0.1), ("fr", 0.2)]
HE_AFFILIATIONS = [("The Open University", 193835),
                ("Leeds Metropolitan University", 41215),
                ("University of Manchester", 39732),
                ("Sheffield Hallam University", 33830),
                ("University of Leeds", 33585),
                ("Manchester Metropolitan University", 33490),
                ("Northumbria University", 32665),
                ("University of Nottingham", 32472),
                ("University of the West of England", 31645),
                ("University of Plymouth", 30930),
                ("Cardiff University", 30010),
                ("University of Birmingham", 29185),
                ("University of the Arts London", 28790),
                ("University of Warwick", 28435),
                ("University of Central Lancashire", 28130),
                ("Teesside University", 27505),
                ("London Metropolitan University", 26380),
                ("University of East London", 26315),
                ("University of Greenwich", 26120),
                ("Liverpool John Moores University", 25995),
                ("Kingston University", 25930),
                ("University of Glamorgan", 25770),
                ("University of Hertfordshire", 25195),
                ("Nottingham Trent University", 24905),
                ("Birmingham City University", 24850),
                ("University of Sheffield", 24715),
                ("University of Edinburgh", 24525),
                ("Edge Hill University", 24340),
                ("London South Bank University", 24280),
                ("University of Glasgow", 24240),
                ("University of Oxford", 23760),
                ("University of Westminster", 23160),
                ("University of Ulster", 23160),
                ("University of Cambridge", 22820),
                ("Queen's University of Belfast", 22810),
                ("University of Derby", 22725),
                ("University of Southampton", 22680),
                ("University of Hull", 22370),
                ("King's College London", 22275),
                ("University of Wolverhampton", 21770),
                ("City University", 21725),
                ("University of Bristol", 21720),
                ("University of Portsmouth", 21605),
                ("University of Huddersfield", 21590),
                ("De Montfort University", 21585),
                ("Middlesex University", 21350),
                ("University of Strathclyde", 21300),
                ("University College London", 21210),
                ("University of Brighton", 20975),
                ("Coventry University", 20230)]
FILE_FORMATS = [("video/mp4", 0.2), ("image/jpeg", 0.3),
                ("impage/png", 0.3), ("application/x-shockwave-flash", 0.1),
                ("application/pdf", 0.1)]
HE_FE = [("HE", 14035), ("FE", 2904)]
FE_AFFILIATIONS = [
        ("Amersham & Wycombe College", 1),
        ("Chelmsford College", 1),
        ("Farnborough College of Technology", 1),
        ("Great Yarmouth College", 1),
        ("Hackney Community College", 1),
        ("Isle of Wight College", 1),
        ("Kidderminster College", 1),
        ("Myerscough College", 1),
        ("New College, Telford", 1),
        ("Reigate College", 1)
    ]
ORIGIN = [("Repository", 0.3), ("Manual Entry", 0.1), ("Bulk Upload", 0.6)]

FE_LD = [
    ("Agriculture Horticulture and Animal Care", 16),
    ("Area Studies / Cultural Studies / Languages / Literature", 94),
    ("Arts and Crafts", 74),
    ("Business / Management / Office Studies", 119),
    ("Catering / Food / Leisure Services / Tourism", 192),
    ("Communication / Media / Publishing", 55),
    ("Construction and Property (Built Environment)", 115),
    ("Education / Training / Teaching", 860),
    ("Engineering", 79),
    ("Environment Protection / Energy / Cleansing / Security", 2),
    ("Family Care / Personal Development / Personal Care and Appearance", 67),
    ("Health Care / Medicine / Health and Safety", 285),
    ("Humanities (History / Archaeology / Religious Studies / Philosophy)", 29),
    ("Information Technology and Information", 281),
    ("Logistics / Distribution / Transport / Driving", 0),
    ("Manufacturing / Production Work", 14),
    ("Oil / Mining / Plastics / Chemicals", 3),
    ("Performing Arts", 121),
    ("Politics / Economics / Law / Social Sciences", 108),
    ("Sales Marketing and Retailing", 94),
    ("Sciences and Mathematics", 264),
    ("Sports Games and Recreation", 32)
    ]

"""
FE_LD = [
    ("Agriculture Horticulture & Animal Care", 16),
    ("Area Studies / Cultural Studies / Languages / Literature", 94),
    ("Arts & Crafts", 74),
    ("Business / Management / Office Studies", 119),
    ("Catering / Food / Leisure Services / Tourism", 192),
    ("Communication / Media / Publishing", 55),
    ("Construction & Property (Built Environment)", 115),
    ("Education / Training / Teaching", 860),
    ("Engineering", 79),
    ("Environment Protection / Energy / Cleansing / Security", 2),
    ("Family Care / Personal Development / Personal Care & Appearance", 67),
    ("Health Care / Medicine / Health & Safety", 285),
    ("Humanities (History / Archaeology / Religious Studies / Philosophy)", 29),
    ("Information Technology & Information", 281),
    ("Logistics / Distribution / Transport / Driving", 0),
    ("Manufacturing / Production Work", 14),
    ("Oil / Mining / Plastics / Chemicals", 3),
    ("Performing Arts", 121),
    ("Politics / Economics / Law / Social Sciences", 108),
    ("Sales Marketing & Retailing", 94),
    ("Sciences & Mathematics", 264),
    ("Sports Games & Recreation", 32)
    ]
"""

"""
FE_LD = [
    ("AGRICULTURE HORTICULTURE and ANIMAL CARE", 16),
    ("AREA STUDIES / CULTURAL STUDIES / LANGUAGES / LITERATURE", 94),
    ("ARTS and CRAFTS", 74),
    ("BUSINESS / MANAGEMENT / OFFICE STUDIES", 119),
    ("CATERING / FOOD / LEISURE SERVICES / TOURISM", 192),
    ("COMMUNICATION / MEDIA / PUBLISHING", 55),
    ("CONSTRUCTION and PROPERTY (BUILT ENVIRONMENT)", 115),
    ("EDUCATION / TRAINING / TEACHING", 860),
    ("Engineering", 79),
    ("Environment Protection / Energy / Cleansing / Security", 2),
    ("FAMILY CARE / PERSONAL DEVELOPMENT / PERSONAL CARE and APPEARANCE", 67),
    ("Health Care / Medicine / Health and Safety", 285),
    ("Humanities (History / Archaeology / Religious Studies / Philosophy)", 29),
    ("Information Technology and Information", 281),
    ("Logistics / Distribution / Transport / Driving", 0),
    ("Manufacturing / Production Work", 14),
    ("Oil / Mining / Plastics / Chemicals", 3),
    ("Performing Arts", 121),
    ("Politics / Economics / Law / Social Sciences", 108),
    ("Sales Marketing and Retailing", 94),
    ("Sciences and Mathematics", 264),
    ("Sports Games and Recreation", 32)
    ]
"""

HE_JACS = [
    ("Architecture, Building & Planning", 66),
    ("Biological Sciences", 366),
    ("Business & Administrative studies", 695),
    ("Creative Arts & Design", 4304),
    ("Eastern, Asiatic, African, American & Australasian Languages, Literature & related subjects", 11),
    ("Education", 1310),
    ("Engineering", 1349),
    ("European Languages, Literature & related subjects", 366),
    ("Historical & Philosophical studies", 925),
    ("Law", 80),
    ("Linguistics, Classics & related subjects", 53),
    ("Mass Communications & Documentation", 139),
#    ("Mathematical & Computer Sciences", 1019), # not in JACS 3.0
    ("Medicine & Dentistry", 307),
    ("Physical Sciences", 547),
    ("Social studies", 1004),
    ("Subjects allied to Medicine", 421),
    ("Technologies", 123),
    ("Veterinary Sciences, Agriculture & related subjects", 950)
    ]

"""
HE_JACS = [
    ("Architecture, Building and Planning", 66),
    ("Biological Sciences", 366),
    ("Business and Administrative studies", 695),
    ("Creative Arts and Design", 4304),
    ("Eastern, Asiatic, African, American and Australasian Languages, Literature and related subjects", 11),
    ("Education", 1310),
    ("Engineering", 1349),
    ("European Languages, Literature and related subjects", 366),
    ("Historical and Philosophical studies", 925),
    ("Law", 80),
    ("Linguistics, Classics and related subjects", 53),
    ("Mass Communications and Documentation", 139),
    ("Mathematical and Computer Sciences", 1019),
    ("Medicine and Dentistry", 307),
    ("Physical Sciences", 547),
    ("Social studies", 1004),
    ("Subjects allied to Medicine", 421),
    ("Technologies", 123),
    ("Veterinary Sciences, Agriculture and related subjects", 950)
    ]
"""

KEYWORDS = {
    "Agriculture Horticulture and Animal Care": ['vet', 'farm', 'dog', 'cow', 'pig'],
    "Area Studies / Cultural Studies / Languages / Literature": ['english', 'french', 'german', 'welsh', 'finnish'],
    "Arts and Crafts": ['buttons', 'textiles', 'handmade', 'collage', 'beads'],
    "Business / Management / Office Studies": ['money', 'power', 'desks', 'corporate', 'structure'],
    "Catering / Food / Leisure Services / Tourism": ['eating', 'restaurant', 'waiting', 'customer', 'gym'],
    "Communication / Media / Publishing": ['newspaper', 'internet', 'magazine', 'layout', 'design'],
    "Construction and Property (Built Environment)": ['concrete', 'architecture', 'engineering', 'lettings', 'foundations'],
    "Education / Training / Teaching": ['course', 'study', 'learn', 'exam', 'class'],
    "Engineering": ['building', 'software', 'physics', 'design', 'technical'],
    "Environment Protection / Energy / Cleansing / Security": ['sustainable', 'nuclear', 'turbine', 'carbon', 'wave'],
    "Family Care / Personal Development / Personal Care and Appearance": ['children', 'washing', 'grooming', 'comb', 'clothes'],
    "Health Care / Medicine / Health and Safety": ['hospital', 'gp', 'antibiotics', 'antiviral', 'compliance'],
    "Humanities (History / Archaeology / Religious Studies / Philosophy)": ['books', 'digging', 'bible', 'neitchze', 'hume'],
    "Information Technology and Information": ['computer', 'software', 'architecture', 'python', 'java'],
    "Logistics / Distribution / Transport / Driving": ['truck', 'van', 'road', 'parcel', 'route'],
    "Manufacturing / Production Work": ['process', 'timeline', 'flow', 'machinery', 'factory'],
    "Oil / Mining / Plastics / Chemicals": ['drill', 'mould', 'dig', 'quarry', 'mine'],
    "Performing Arts": ['dance', 'mime', 'play', 'interpretive', 'theatre'],
    "Politics / Economics / Law / Social Sciences": ['mp', 'mep', 'judge', 'survey', 'model'],
    "Sales Marketing and Retailing": ['research', 'market', 'shop', 'store', 'highstreet'],
    "Sciences and Mathematics": ['physics', 'chemistry', 'biology', 'nuroscience', 'statistics'],
    "Sports Games and Recreation": ['judo', 'fencing', 'wrestling', 'athletics', 'darts'],
    "Architecture, Building & Planning": ['listed', 'neo', 'modern', 'baroque', 'gothic'],
    "Biological Sciences": ['worm', 'organism', 'cell', 'microbe', 'philum'],
    "Business & Administrative studies": ['spreadsheet', 'document', 'tax', 'hr', 'finance'],
    "Creative Arts & Design": ['collage', 'blueprint', 'drawing', 'template', 'theatre'],
    "Eastern, Asiatic, African, American & Australasian Languages, Literature & related subjects": ['mongolian', 'mandarin', 'cantonese', 'taiwanese', 'hindi'],
    "Education": ['primary', 'secondary', 'he', 'fe', 'postgraduate'],
    "Engineering": ['cogs', 'gears', 'bridges', 'buildings', 'software'],
    "European Languages, Literature & related subjects": ['english', 'french', 'german', 'dutch', 'norwegian'],
    "Historical & Philosophical studies": ['neitchze', 'descartes', 'malory', 'hume', 'chaucer'],
    "Law": ['criminal', 'property', 'corporate', 'contract', 'enforcement'],
    "Linguistics, Classics & related subjects": ['phonics', 'syntax', 'grammar', 'latin', 'greek'],
    "Mass Communications & Documentation": ['internet', 'twitter', 'facebook', 'magazine', 'newspaper'],
    "Mathematical & Computer Sciences": ['turing', 'computability', 'completeness', 'programming', 'software'],
    "Medicine & Dentistry": ['teeth', 'organs', 'heart', 'drill', 'liver'],
    "Physical Sciences": ['physics', 'mechanics', 'gravity', 'relativity', 'velocity'],
    "Social studies": ['survey', 'anthropology', 'geography', 'human', 'life'],
    "Subjects allied to Medicine": ['neurology', 'neuroscience', 'holistics', 'pharmacology', 'pharmacy'],
    "Technologies": ['java', 'python', 'windows', 'linux', 'osx'],
    "Veterinary Sciences, Agriculture & related subjects": ['cats', 'dogs', 'pigs', 'cows', 'fish']
}

LETTER_PAIRS = {
    "a" : ["b", "d", "g", "l", "m", "n", "r", "s", "t", "y"],
    "b" : ["a", "e", "i", "l", "o", "r", "y"],
    "c" : ["a", "e", "h", "k", "o"],
    "d" : ["a", "d", "e", "i", "o"],
    "e" : ["d", "g", "l", "m", "n", "p", "r", "s", "t", "y"],
    "f" : ["a", "e", "i", "o"],
    "g" : ["a", "e", "g", "h", "i", "l", "o", "r", "y"],
    "h" : ["a", "e", "i", "o", "u", "y"],
    "i" : ["b", "d", "f", "l", "m", "n", "p", "r", "s", "t"],
    "j" : ["a", "e", "o", "u"],
    "k" : ["a", "e", "i", "l", "n", "o", "s", "y"],
    "l" : ["a", "e", "i", "k", "l", "o", "p", "t", "u", "y"],
    "m" : ["a", "e", "i", "m", "o", "p", "u", "y"],
    "n" : ["a", "d", "e", "g", "i", "k", "n", "o", "s", "u", "y"],
    "o" : ["b", "c", "d", "f", "g", "l", "m", "n", "o", "p", "r", "s", "t", "w", "y"],
    "p" : ["a", "e", "h", "i", "l", "o", "p", "r", "s", "t", "u", "y"],
    "q" : ["u"],
    "r" : ["a", "e", "i", "k", "n", "o", "p", "r", "s", "t", "u", "y"],
    "s" : ["a", "c", "e", "g", "h", "i", "k", "l", "m", "n", "o", "p", "q", "s", "t", "u", "w"],
    "t" : ["a", "e", "h", "i", "o", "r", "t", "u", "w", "y"],
    "u" : ["b", "d", "g", "l", "m", "n", "p", "r", "s", "t"],
    "v" : ["a", "e", "i", "o", "u", "y"],
    "w" : ["a", "d", "e", "h", "i", "l", "o"],
    "x" : ["a", "e", "y"],
    "y" : ["a", "e", "i", "o", "u"],
    "z" : ["e"]
}

WEB_RES_OR_FT = [('wr', 0.5), ('ft', 0.5)]

jacs_csv = csv.reader(open("JACS3_20120529.csv"))
JACS3 = {}
for row in jacs_csv:
    JACS3[row[0]] = row[1]

ld_csv = csv.reader(open("HEIFESFAQ1_LDCS_CODES.csv"))
LD = {}
for row in ld_csv:
    LD[row[0]] = row[1]

def generate_record(id):
    record = {}
    record['id'] = id
    record['title'] = uuid.uuid4()
    record['description'] = 'Lorem Ipsum Dolor'
    record['language'] = select_from(LANGUAGES)
    record['creator_id'] = uuid.uuid4()
    record['creator'] = random_name()
    # FIXME: have omitted publisher, this is very thin on the ground in Jorum
    # record['publisher'] = uuid.uuid4()
    record['format'] = select_from(FILE_FORMATS)
    record['he_fe'] = select_from(HE_FE)
    record['origin'] = select_from(ORIGIN)
    record['type'] = None # what are the options here
    record['created_date'] = random_date()

    # now the conditionals
    if record['he_fe'] == "HE":
        record['affiliation'] = select_from(HE_AFFILIATIONS)
        record['jacs'] = select_from(HE_JACS)
        record['jacs_code'] = jacs_code(record['jacs'])
        record['ld'] = None
        record['ld_code'] = None
    else:
        record['affiliation'] = select_from(FE_AFFILIATIONS)
        record['ld'] = select_from(FE_LD)
        record['ld_code'] = ld_code(record['ld'])
        record['jacs'] = None
        record['jacs_code'] = None

    subject = record['jacs'] if record['jacs'] is not None else record['ld']
    record['keywords'] = random_keywords(subject)

    record['web_resource'] = 'false'
    record['uploaded_resource'] = 'false'
    wr_ft = select_from(WEB_RES_OR_FT)
    if wr_ft == "wr":
        record['web_resource'] = 'true'
    else:
        record['uploaded_resource'] = 'true'

    return record

def ld_code(classification):
    for key, value in LD.iteritems():
        if value.lower() == classification.lower():
            return key
    return None

def jacs_code(classification):
    for key, value in JACS3.iteritems():
        if value.lower() == classification.lower():
            return key
    return None

def random_keywords(jacs):
    kws = KEYWORDS[jacs]
    num = randint(1, 5)
    rkws = []
    for i in range(num):
        select = randint(0, 4)
        k = kws[select]
        if k not in rkws:
            rkws.append(k)
    return rkws

def random_date(after=None):
    max_lookback = 400000000
    now = time.time()
    if after is not None:
        t = time.strptime(after, "%Y-%m-%dT%H:%M:%SZ")
        ts = time.mktime(t)
        max_lookback = now - ts
    return datetime.strftime(datetime.fromtimestamp(now - randint(0, int(max_lookback) - 1)), "%Y-%m-%dT%H:%M:%SZ")

def random_name():
    name = ""
    length = randint(5, 10)
    letter = LETTER_PAIRS.keys()[randint(0, len(LETTER_PAIRS.keys()) - 1)]
    while len(name) < length:
        name += letter
        letter = LETTER_PAIRS[letter][randint(0, len(LETTER_PAIRS[letter]) - 1)]

    initial = LETTER_PAIRS.keys()[randint(0, len(LETTER_PAIRS.keys()) - 1)]
    name = name + ", " + initial
    return name

def select_from(arr):
    narr = normalise_probability_matrix(arr)
    r = random()
    for (option, lower, upper) in narr:
        if r >= lower and r < upper:
            return option
    return None

def normalise_probability_matrix(arr):
    total = 0.0
    for (option, weight) in arr:
        total += float(weight)
    n_ratio = 1.0 / total
    select_arr = []
    last_prob = 0.0
    for (option, weight) in arr:
        prob = float(weight) * n_ratio
        upper = last_prob + prob
        select_arr.append((option, last_prob, upper))
        last_prob = upper
    return select_arr

#ID	Title	Description	Language	Affiliation	Creator	Publisher	File Format
#HE/FE	Record Origin	Record Created Date	JAX Classification	Subject Keywords	Type
oers = []
for id in range(SIZE):
    oers.append(generate_record(id))
oer_csv = open("oers.csv", "w")
writer = csv.writer(oer_csv)

writer.writerow(["OER ID", "Title", "Description", "Language", "Publisher", "Creator", "Creator ID",
                    "File Format", "HE/FE", "Record Origin", "Record Created Date", "JACS Code",
                    "JACS Classification", "Learn Direct Code", "Learn Direct Classification",
                    "Subject Keywords", "Type", "Web Resource", "Uploaded Resource"])
for oer in oers:
    writer.writerow([oer['id'], oer['title'], oer['description'], oer['language'],
                    oer['affiliation'], oer['creator'], oer['creator_id'], oer['format'],
                    oer['he_fe'], oer['origin'], oer['created_date'], oer['jacs_code'], oer['jacs'],
                    oer['ld_code'], oer['ld'], ",".join(oer['keywords']), oer['type'], oer['web_resource'],
                    oer['uploaded_resource']])
oer_csv.close()

def random_ip():
    a = randint(0, 255)
    b = randint(0, 255)
    c = randint(0, 255)
    d = randint(0, 255)
    return str(a) + "." + str(b) + "." + str(c) + "." + str(d)

def random_lat():
    big = randint(-50, 70)
    small = randint(0, 9999)
    lat = str(big) + "." + str(small)
    return lat

def random_long():
    big = randint(-180, 180)
    small = randint(0, 9999)
    long = ""
    if big == 180 or big == -180:
        long = str(big) + ".0000"
    else:
        long = str(big) + "." + str(small)
    return long

def add_create(oer, events):
    event = [oer['id'], 'create', oer['created_date'], random_ip(), random_lat(), random_long()]
    events.append(event)

def add_views(oer, events):
    view_count = randint(1, MAX_VIEWS)
    for i in range(view_count):
        event = [oer['id'], 'view', random_date(oer['created_date']), random_ip(), random_lat(), random_long()]
        events.append(event)

def add_downloads(oer, events):
    view_count = count_views(events)
    if view_count > MAX_DOWNLOADS:
        view_count = MAX_DOWNLOADS
    download_count = randint(1, view_count)
    for i in range(download_count):
        event = [oer['id'], 'download', random_date(oer['created_date']), random_ip(), random_lat(), random_long()]
        events.append(event)

def count_views(events):
    total = 0
    for event in events:
        if event[1] == "view":
            total += 1
    return total

# ID	Statistical Event	Statistical Event Date	Statistical Event IP
# Statistical Event Lat	Statistical Event Long
stat_csv = open("stats.csv", "w")
stat_writer = csv.writer(stat_csv)
stat_writer.writerow(["OER ID", "Statistical Event", "Statistical Event Date",
                        "Statistical Event IP", "Statistical Event Lat", "Statistical Event Long"])
for oer in oers:
    events = []
    add_create(oer, events)
    add_views(oer, events)
    add_downloads(oer, events)
    for event in events:
        stat_writer.writerow(event)
stat_csv.close()


'''
Created on Jul 20, 2016
@author: Niveditha
'''
import math
import re
import sys
import os

class ProbG:
    prob = []
    g = 0.0
    direction = 'F'
    ind = 0

'''
Function name: calculate_error
Description: calculates threshold with minimum error
'''
def calculate_prob_g(y, p, n):
    min_g = sys.float_info.max
    direc = 'N'
    obj1 = ProbG()
    for i in range(1, n):
        pr_plus = 0.0
        pr_minus = 0.0
        pw_plus = 0.0
        pw_minus = 0.0
        for j in range(0, n):
            if (j < i):
                if (y[j] == -1):
                    pw_minus = pw_minus + p[j]
                else:
                    pr_plus = pr_plus + p[j]

            else:
                if (y[j] == -1):
                    pr_minus = pr_minus + p[j]
                else:
                    pw_plus = pw_plus + p[j]

        g = math.sqrt(pr_plus * pw_minus) + math.sqrt(pw_plus * pr_minus)
        direc = 'F'
        if (g > 0.5):
            g = 1 - g
            temp = pr_plus
            pr_plus = pw_plus
            pw_plus = temp
            temp = pr_minus
            pr_minus = pw_minus
            pw_minus = temp
            direc = 'R'

        if (g < min_g):
            obj1.prob = []
            min_g = g
            obj1.g = g
            obj1.direction = direc
            obj1.ind = i
            obj1.prob.append(pr_plus)
            obj1.prob.append(pr_minus)
            obj1.prob.append(pw_plus)
            obj1.prob.append(pw_minus)

    return obj1

'''
Function name: iteration
Description: calculates all the values needed for one iteration
'''
def iteration(n,epsilon,p,x,y):
    global ftemp
    global e_t
    obj_prob_g = calculate_prob_g(y,p,n)
    weak_class = 0.0
    if (obj_prob_g.ind == 0):
        weak_class = (x[obj_prob_g.ind]- 1)
    else:
        weak_class = (x[obj_prob_g.ind] + x[obj_prob_g.ind - 1]) /2

    if (obj_prob_g.direction == 'F'):
        print("The selected weak classifier Ht: I( x < ", weak_class,  ") ")
    elif(obj_prob_g.direction == 'R'):
        print("The selected weak classifier Ht: I( x > ", weak_class, ") ")

    print("The G error value of Ht: ", obj_prob_g.g)
    c_t_plus = (1.0 / 2.0) * math.log(float((obj_prob_g.prob[0] + epsilon) / (obj_prob_g.prob[3] + epsilon)))
    c_t_minus = (1.0 / 2.0) * math.log((obj_prob_g.prob[2] + epsilon) / (obj_prob_g.prob[1] + epsilon))
    print("The weights Ct+, Ct-: ", c_t_plus, ", ",c_t_minus)

    sum = 0.0
    for i in range(0, n):
        if (i < obj_prob_g.ind):
            p[i] = p[i] * math.pow(math.e, (-1) * c_t_plus * y[i])
        else:
            p[i] = p[i] * math.pow(math.e, (-1) * c_t_minus * y[i])
        sum = sum +p[i]

    print("The probabilities normalization factor Zt: ", sum)
    print("The probabilities after normalization: ")
    for i in range(0, n):
        p[i] = p[i] /sum
        if (i == 0):
            print(p[i], end='')
        else:
            print(", ", p[i], end='')
    print()
    errors = 0.0
    print("The values ft(xi) for each one of the examples: ")
    for i in range(0, n):
        if (x[i] < weak_class):
            ftemp[i] = ftemp[i] + c_t_plus

        else:
            ftemp[i] = ftemp[i] + c_t_minus
        if (i == 0):
            print(ftemp[i],end='')
        else:
            print(", ",ftemp[i], end='')

        if ((y[i] > 0 and ftemp[i] < 0) or (y[i] < 0 and ftemp[i] >= 0)):
            errors = errors + 1
    print()
    print("The error of the boosted classifier Et: ", errors /float(n))
    e_t = e_t * sum
    print("The bound on Et: ", e_t)
    return p

x = []
y = []
p = []
ftemp = []
e_t = 1
T_n_epsilon = []
filename = "input.txt"
if os.path.exists(filename):
    try:
        fileobj1 = open(filename, 'r')
        header = fileobj1.readline().strip('\n')
        T_n_epsilon.extend(re.split('\s+', header))
        T_n_epsilon = [float(i) for i in T_n_epsilon]
        line = fileobj1.readline().strip('\n')
        x.extend(re.split('\s+', line))
        x = [float(i) for i in x]
        line = fileobj1.readline().strip('\n')
        y.extend(re.split('\s+', line))
        y = [int(i) for i in y]
        line = fileobj1.readline().strip('\n')
        p.extend(re.split('\s+', line))
        p = [float(i) for i in p]
        fileobj1.close()
        for i in range(0, int(T_n_epsilon[1])):
            ftemp.append(0)

        for j in range(0, int(T_n_epsilon[0])):
            print("Iteration ", (j + 1), ":")
            p =  iteration(int(T_n_epsilon[1]),float(T_n_epsilon[2]), p, x, y)
            print(" ")

    except IOError:
        print("Could not read file:", filename)
        exit(0)

else:
    print("The input file name given does not exist. Please try again with correct input file name")
    exit(0)


import os
import shutil
import dropbox
import requests
import platform
from . import header
from .dropboxhasher import DropboxContentHasher

# OS info
OS_TYPE = platform.system().lower()
ARCH_TYPE = platform.architecture()[0].lower()
CLOUD_DIR = '/%s/%s' % (OS_TYPE, ARCH_TYPE)

def __checksum(path: str) -> str:
    algorithm = DropboxContentHasher()

    with open(path, 'rb') as file:
        for chunk in iter(lambda: file.read(4096), b''):
            algorithm.update(chunk)

    return algorithm.hexdigest()

def __get_files() -> list:
    client = dropbox.Dropbox(oauth2_access_token=header.ACCESS_TOKEN, timeout=None)
    result = []

    try:
        maximum_limit = 2000
        for file in client.files_list_folder(CLOUD_DIR, recursive=True, limit=maximum_limit).entries:
            if file.path_lower != CLOUD_DIR:
                result.append(file)
    except (requests.exceptions.ConnectionError, requests.exceptions.ChunkedEncodingError):
        pass
    finally:
        client.close()
        return result

def download():
    files = __get_files()
    client = dropbox.Dropbox(oauth2_access_token=header.ACCESS_TOKEN, timeout=None)
    os.makedirs(header.UPDATE_DIR, exist_ok=True)

    for file in files:
        if not isinstance(file, dropbox.files.FileMetadata):
            continue

        file_path = os.path.relpath(file.path_display, CLOUD_DIR)
        temp_path = os.path.join(header.UPDATE_DIR, file_path)
        app_path = os.path.join(header.APP_DIR, file_path)
        in_temp = os.path.exists(temp_path) and file.content_hash == __checksum(temp_path)
        in_app = os.path.exists(app_path) and file.content_hash == __checksum(app_path)

        if not in_temp and not in_app:
            os.makedirs(os.path.dirname(temp_path), exist_ok=True)
            client.files_download_to_file(download_path=temp_path, path=file.id)

    client.close()

def update() -> bool:
    valid = False
    if os.path.exists(header.UPDATE_DIR) and len(os.listdir(header.UPDATE_DIR)) > 0:
        shutil.copytree(header.UPDATE_DIR, header.APP_DIR, dirs_exist_ok=True)
        shutil.rmtree(header.UPDATE_DIR, ignore_errors=True)
        valid = True

    return valid


from mxnet import gluon
from mxnet import ndarray as nd
from mxnet import autograd as ag
import datetime
#%matplotlib inline
import matplotlib as mpl
mpl.rcParams['figure.dpi'] = 120
import matplotlib.pyplot as plt
import numpy as np

def train(net, train_data, valid_data, ctx, num_epoches, softmax_cross_entropy, optimizer='adam',
          lr=0.01, lr_decay=0.1, lr_period=50, momentum=0.9, weight_decay=0,
          cost_period=10, print_cost=False):
    if optimizer == 'momentum':
        trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': lr,
                                                              'momentum': momentum,
                                                              'wd': weight_decay})
    elif optimizer == 'adam':
        trainer = gluon.Trainer(net.collect_params(), 'adam', {'learning_rate': lr,
                                                               'wd': weight_decay})

    train_costs = []
    valid_costs = []
    v_loss_train = 0
    n_iter_train = 0
#     v_loss_valid = 0
#     n_iter_valid = 0
    for epoch in range(num_epoches):
        pre_time = datetime.datetime.now()
        train_acc = 0
#         train_loss = 0
        if (epoch+1) % lr_period == 0:
            trainer.set_learning_rate(trainer.learning_rate * lr_decay)
        for data, label in train_data:
            data = data.as_in_context(ctx)
            label = label.astype('float32').as_in_context(ctx)
            with ag.record():
                output = net(data)
                loss = softmax_cross_entropy(output, label)
            loss.backward()
            #trainer.step(batch_size)
            trainer.step(len(data))
            train_acc += nd.mean(output.argmax(axis=1) == label).asscalar()
#             train_loss += nd.mean(loss).asscalar()
            cur_loss = nd.mean(loss).asscalar()
            v_loss_train = 0.9 * v_loss_train + 0.1 * cur_loss
            n_iter_train += 1
            corr_loss_train = v_loss_train / (1 - pow(0.9, n_iter_train))

        cur_time = datetime.datetime.now()
        h, remainder = divmod((cur_time - pre_time).seconds, 3600)
        m, s = divmod(remainder, 60)
        time_str = 'Time %02d:%02d:%02d, ' % (h, m, s)

        if valid_data is not None:
            valid_acc = 0
            valid_loss = 0
            for data, label in valid_data:
                data = data.as_in_context(ctx)
                label = label.astype('float32').as_in_context(ctx)
                output = net(data)
                loss = softmax_cross_entropy(output, label)
                valid_acc += nd.mean(output.argmax(axis=1) == label).asscalar()
#                 cur_loss = nd.mean(loss).asscalar()
#                 v_loss_valid = 0.9 * v_loss_valid + 0.1 * cur_loss
#                 n_iter_valid += 1
#                 corr_loss_valid = v_loss_valid / (1 - pow(0.9, n_iter_valid))
                valid_loss += nd.mean(loss).asscalar()
            epoch_str = 'Epoch %d, Train_loss: %s, Train_acc: %s, Valid_acc: %s, ' % (epoch+1,
                                                                                corr_loss_train,
                                                                                train_acc/len(train_data),
                                                                                valid_acc/len(valid_data))
        else:
            epoch_str = 'Epoch %d, Train_loss: %s, Train_acc: %s, ' % (epoch+1,
                                                                     corr_loss_train,
                                                                     train_acc/len(train_data))
        if print_cost and (epoch+1) % cost_period == 0:
            train_costs.append(corr_loss_train)
#             train_costs.append(train_loss/len(train_data))
            valid_costs.append(valid_loss/len(valid_data))

        print(epoch_str + time_str + 'lr: %f' % trainer.learning_rate)

    if print_cost:
        x_axis = np.linspace(0, num_epoches, len(train_costs), endpoint=True)
        l1, = plt.semilogy(x_axis, train_costs)
        l2, = plt.semilogy(x_axis, valid_costs)
        plt.xlabel('epoch')
        plt.ylabel('loss')
        plt.legend([l1, l2], ['train', 'valid'], loc='upper right')
        plt.show()


import cv2
import numpy as np
import os
import matplotlib.pyplot as plt
import Perspective as Perspective
import MyFilter as Filter
import cluster_line as Cluster
import HoughLine as HoughLine
import find_endpoint as fe
from XML_Creater import XML
from Classifier_v04 import Classifier
import Classifier_v04
import time

################################################## 待调参数 #######################################################
# 数据集路径设置
# path = 'G:\JuntaWu\lane_detection\MyLane_20171103\image\dataSet'
path= 'G:\JuntaWu\lane_detection\MyLane_20171103\image\\test'
# 生成的 xml 文件保存路径
xml_path = 'G:\JuntaWu\lane_detection\MyLane_20171103\MyLaneTrack_v08.7\TSD-Lane-Result'

# canny 滤波参数
low_threshold = 50
high_threshold = 80

# hsv 颜色阈值空间，需与Classifier.py 颜色阈值参数一致
white_low_thres = Classifier_v04.white_low_thres
white_high_thres = Classifier_v04.white_high_thres
yellow_low_thres = Classifier_v04.yellow_low_thres
yellow_high_thres = Classifier_v04.yellow_high_thres

# 检测车道线数
lane_num = 4
###################################################################################################################

folders = os.listdir(path)
for folder in folders:
    # 提示信息与计时
    print('Processing ' + folder + ' :')
    start_time = time.time() # 计时

    image_path = os.path.join(path, folder)
    image_files = os.listdir(image_path)
    # 创建xml文件，存储车道线信息
    # xml_creater = XML('TSD-Lane-%05d-Result.xml' % data_index )
    xml_creater = XML(folder + '-Result.xml')
    # 当前图片帧号
    frameIndex = 0
    # 存储上一帧检测结果，初始化
    previous_extend_lane = np.array([[1194, 1024,  574,  295],  [1194, 900,  574,  250] ])
    for file in image_files:
        try:
            img = cv2.imread(image_path + '\\' + file)
            image = img.copy()
            #######################################################################################################################
            # 预处理：滤波+边缘检测
            median = cv2.medianBlur(img, 5)

            img_1 = (Filter.GaborFilter(median, 5, 0, 3, 5, 1, 0)).astype(np.uint8)  # 利用gabor滤波器提取方向边缘信息
            img_2 = (Filter.GaborFilter(median, 5, 25, 3, 5, 1, 0)).astype(np.uint8)
            img_3 = (Filter.GaborFilter(median, 5, 50, 3, 5, 1, 0)).astype(np.uint8)
            img_4 = (Filter.GaborFilter(median, 5, 90, 3, 5, 1, 0)).astype(np.uint8)
            gabor = np.abs((img_1 + +img_2 + img_3 + img_4)).astype(np.uint8)

            gabor_edges = Filter.CannyFilter(gabor, low_threshold, high_threshold)
            end_point = fe.find_endpoint(img, gabor_edges)
            # cv2.imshow("gabor_result", gabor_edges)

            ROI = np.array([[(0,end_point[1]),(img.shape[1],end_point[1]),(img.shape[1],img.shape[0]),(0,img.shape[0])]],dtype=np.int32)
            roi = Perspective.region_of_interest(gabor_edges, ROI)
            #########################################################################################################################

            ###############################################################################################
            # 获得颜色、虚实检测所需的canny_edges
            # 先进行一轮颜色滤波
            img_color = Filter.Color_Filter(image, (np.array(white_low_thres), np.array(white_high_thres)),
                                            (np.array(yellow_low_thres), np.array(yellow_high_thres)))
            img_gray = cv2.cvtColor(img_color, cv2.COLOR_BGR2GRAY)
            _, img_thres = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
            # cv2.imshow("thres", img_thres)
            ###############################################################################################

            ################################################################################################################################
            # 检测当前帧车道线，检测不到时异常处理
            # 车道检测：直线检测+斜率筛选+聚类+车道挑选
            hough_lines = HoughLine.HoughLineTransform(roi, 'p')
            lines = Cluster.slope_check(hough_lines, 0.2, end_point, img.shape[1], 0.2)
            polars = (Cluster.line_change(lines)).T
            labels, unique_labels = Cluster.dbscan(lines, polars, end_point, 0.1, 3, 280,2)  # epss=0.1, MinPts=3, epss2=350, MinPts2=2)
            lane = Cluster.select_lines(img, lines, polars, labels, unique_labels, end_point, cc=0.2, n_max = lane_num)

            hough = np.zeros_like(img)
            # for line in hough_lines:
            #     cv2.line(hough, (int(line[0, 0]), int(line[0, 1])), (int(line[0, 2]), int(line[0, 3])), [0, 0, 255], 1)
            # cv2.imshow('hough', hough)

            slope_check = np.zeros_like(img)
            # for line in lines:
            #     cv2.line(slope_check, (int(line[0, 0]), int(line[0, 1])), (int(line[0, 2]), int(line[0, 3])), [0, 0, 255], 1)
            # cv2.imshow('slope_check', slope_check)

            ########################################### 显示检测直线的效果 ##############################################
            colors2 = [[0, 0, 255], [0, 255, 0], [255, 0, 0], [0, 0, 0], [255, 255, 0], [255, 0, 255], [0, 255, 255],
                       [255, 255, 255]]  # 红、绿、蓝、黑、青、粉、黄、白   直线颜色按得分高到低从前往后排列
            y1 = img.shape[0]
            y2 = end_point[1]  # 取消失点下方的点
            extend_lane = []     # 延长后的车道
            for line, col in zip(lane, colors2):
                if line[0] == line[2]:
                    x1 = line[0]
                    x2 = line[0]
                else:
                    line_m = (line[1] - line[3]) / (line[0] - line[2])
                    line_b = line[3] - line_m * line[2]
                    x1 = int((y1 - line_b) / line_m)
                    x2 = int((y2 - line_b) / line_m)
                # cv2.line(img, (x1, y1), (x2, y2), col, 10)
                extend_lane.append([x1, y1, x2, y2])
            extend_lane = np.array(extend_lane)
            # cv2.imshow('img', img)
            #############################################################################################################

            # 更新上一帧检测到的车道线结果，以备当前帧检测不到车道线情况
            previous_extend_lane = extend_lane

            # 根据 x1 的数值大小，对检测到的车道线从左到右排序
            # 存储从左到右排好序的车道线端点
            lane_points= np.empty( shape=[0, extend_lane.shape[1] ] )  # lane_points：按x1从小到大排序的车道线
            iter_num = extend_lane.shape[0]
            for index in range( iter_num ):
                min_index = extend_lane[:, 0].argmin()
                lane_points = np.vstack( (lane_points, extend_lane[ min_index, :]) )
                extend_lane = np.delete(extend_lane, min_index, axis=0)
            # print(lane_points)

            # 对检测到的每条车道线进行颜色,类型判断,并将结果写入xml文件
            targetNumber = lane_points.shape[0]
            xml_creater.create_targetNumber(frameIndex, targetNumber)
            targetIndex = 0  # 目标车道线
            for i in range(targetNumber):
                # 检测不到时，异常如何处理 ？？？
                lane_position, color, type = Classifier(image, img_thres, img_thres, ( int(lane_points[i, 0]), int(lane_points[i, 1])), \
                                                        ( int(lane_points[i, 2]), int(lane_points[i, 3]) ), i+1, targetNumber )
                xml_creater.create_target(frameIndex, targetIndex, color, type, lane_position)
                targetIndex += 1

                ############################## 显示检测虚实、黄白的效果 ########################################
                # for point in lane_position:
                #     cv2.circle(image,(point[0], point[1] ), 3, [0, 0, 255], -1)
                if color == True:
                    if type == True:
                        col = [100,100,100] # 白虚线  灰色
                    else:
                        col = [0,0,0] # 白实线  黑色
                else:
                    if type == True:
                        col = [255,255,0] # 黄虚线 青色
                    else:
                        col = [0,255,0] # 黄实线  绿色
                cv2.line(image, ( int(lane_points[i, 0]), int(lane_points[i, 1])), \
                                                        ( int(lane_points[i, 2]), int(lane_points[i, 3]) ), col,7)
                #####################################################################################################
        except:
            pass
            # extend_lane = previous_extend_lane
            # # if(extend_lane)
            # lane_points = np.empty(shape=[0, extend_lane.shape[1]])  # lane_points：按x1从小到大排序的车道线
            # iter_num = extend_lane.shape[0]
            # for index in range(iter_num):
            #     min_index = extend_lane[:, 0].argmin()
            #     lane_points = np.vstack((lane_points, extend_lane[min_index, :]))
            #     extend_lane = np.delete(extend_lane, min_index, axis=0)
            # # print(lane_points)
            #
            # # 对检测到的每条车道线进行颜色,类型判断,并将结果写入xml文件
            # targetNumber = lane_points.shape[0]
            # xml_creater.create_targetNumber(frameIndex, targetNumber)
            # targetIndex = 0  # 目标车道线
            # for i in range(targetNumber):
            #     # 检测不到时，异常如何处理 ？？？
            #     lane_position, color, type = Classifier(image, img_thres, img_thres,
            #                                             (int(lane_points[i, 0]), int(lane_points[i, 1])), \
            #                                             (int(lane_points[i, 2]), int(lane_points[i, 3])), i + 1,
            #                                             targetNumber)
            #     xml_creater.create_target(frameIndex, targetIndex, color, type, lane_position)
            #     targetIndex += 1
            #
            #     ############################## 显示检测虚实、黄白的效果 ########################################
            #     # for point in lane_position:
            #     #     cv2.circle(image,(point[0], point[1] ), 3, [0, 0, 255], -1)
            #     if color == True:
            #         if type == True:
            #             col = [100, 100, 100]  # 白虚线  灰色
            #         else:
            #             col = [0, 0, 0]  # 白实线  黑色
            #     else:
            #         if type == True:
            #             col = [255, 255, 0]  # 黄虚线 青色
            #         else:
            #             col = [0, 255, 0]  # 黄实线  绿色
            #     cv2.line(image, (int(lane_points[i, 0]), int(lane_points[i, 1])), \
            #              (int(lane_points[i, 2]), int(lane_points[i, 3])), col, 7)
            #     #####################################################################################################
        ##############################################################################################################################
        frameIndex += 1

        # 显示检测效果
        # cv2.imshow("annotated_image", image)
        # cv2.waitKey(1)

    # 关闭xml文件
    xml_creater.close()

    ########################## 修改XML格式 #############################
    xml_new = open(xml_path + '\\' + folder + '-Result.xml', 'w', encoding='gb2312')
    with open( folder + '-Result.xml', 'r', encoding='utf-8') as f:
        xml_lines = f.readlines()
        count = 0
        for xml_line in xml_lines:
            if count == 0:
                count += 1
                xml_new.write(xml_line)
                continue
            if '.' in xml_line:
                new_line = ''
                fragments = xml_line.split('.')
                for fragment in fragments:
                    new_line += fragment
                xml_new.write(new_line)
                continue
            count += 1
            xml_new.write(xml_line)
    ########################################################################

    # 计时
    end_time = time.time()
    print(end_time - start_time)


oracion = input("Escribe algo para contar las vocales")
string = oracion.lower()
print (string)
count = 0
vocales = ["a", "e", "i", "o", "u"]
for char in string:
    if char in vocales:
        count = count+1

print ("el número de vocales es", count)


import pygame
import math
from library import *

ColorList = [VERDE, AZUL, ROJO, BLANCO, MORADO]

if __name__ == '__main__':
	pygame.init()
	pantalla = pygame.display.set_mode([ANCHO, ALTO])
	fin = False
	origen = [ANCHO // 2, ALTO // 2]
	Plano(pantalla, origen)
	x = -50

	while x <= 50:
		y = 5*x**3 +10
		pp = CartesianoAPantalla(origen, [x, y])
		pygame.draw.circle(pantalla, VERDE, pp, 2, 2)
		x += 1

	while not fin:
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				fin = True

		pygame.display.flip()


# Now we will learn about sets in python
# A set is a type of data thata stores things
a = set()
print (a)
# you can us .add to add things in the set
a.add(1)
print(a)
a.add(2)
print(a)
# if you try to add the same item in the set twicw it wont be added
# you can use this to iterate
for x in a:
    print (x)
# what if you want to remove duplicates from a list? you can do it like this
given_list = [1,1,2,4,2]
new_set1 = set()
for x in given_list:
    new_set1.add(x)
# you can create a lsit out a set by doing this
print (new_set1)
newlist1 = list()
for x in new_set1:
    newlist1.append(x)
print (newlist1)
# you can add strings and integers in a set
b = set()
b.add("apple")
b.add("banana")
b.add(1)
print (b)
# here is a task, find the sum of the unique elements in the given_list
given_list1 = [1,3,4,1,3]
newset = set()
newlist = list()
total = 0
for x in given_list1:
    newset.add(x)
print(newset)
for x in newset:
    newlist.append(x)
print (newlist)
for x in newlist:
    total = total + x
print (total)
# you can use a shortcut by applying the end sum() function
# Solution
print ("Solution:-")
for x in given_list1:
    newset.add(x)
print(sum (newset))
# or
given_list1 = [1,3,4,1,3]
newset = set()
for x in given_list1:
    newset.add(x)
print(newset)
total1 = 0
for x in newset:
    total1 += x
print (total1)


#!/usr/bin/env python

import numpy as np, os
import numpy.linalg as npl
import sys
import time

start_time = time.time()

np.set_printoptions(linewidth = 200)

molGeom = open('.\\Input_Files\\water.txt', 'r')
geomCont = molGeom.readlines()

hessRaw = open('.\\Input_Files\\waterHessian.txt', 'r')
hessCont = hessRaw.readlines()
molGeom.close()
hessRaw.close()

try:
	if(hessCont[0] != geomCont[0]):
		raise Exception("Number of Atoms in input and inputHessian do not match!")
except Exception as err:
	print("ERROR: " + str(err))
	sys.exit()

atomCount = int(geomCont[0].replace('\n', ''))
geomCont = geomCont[1:]
hessCont = hessCont[1:]

def pos(content):

	posMatrix = np.array([])

	for i in content:

		i = i.split('\t')
		i[-1] = i[-1].replace('\n','')
		i = i[1:]
		i = [float(x) for x in i]
		posMatrix = np.append(posMatrix, i)

	posMatrix = np.reshape(posMatrix, (len(content),3))

	return posMatrix

def atomicMass(content):

	an = np.array([])

	for i in content:

		i = i.split('\t')
		i = i[:1]
		i = [float(x) for x in i]
		an = np.append(an,i)

	for x in range(len(an)):
		if(an[x] == 6.):
			an[x] = 12.
		elif(an[x] == 8):
			an[x] = 16

	return an

def hessianDat(hess):

	hessMatrix = np.array([])

	for i in hess:
		i = i.split('\t')
		i[-1] = i[-1].replace('\n','')
		i = [float(x) for x in i]
		hessMatrix = np.append(hessMatrix, i)

	hessMatrix = np.reshape(hessMatrix, (atomCount*3,atomCount*3))

	return hessMatrix

def massWeight(H, masses):

	I = np.zeros(atomCount*3)

	for i in range(0, atomCount*3,3):

		I[i] = masses[int(i/3)]
		I[i+1] = masses[int(i/3)]
		I[i+2] = masses[int(i/3)]

	M = np.outer(I,I)
	M = np.sqrt(M)
	H = np.divide(H,M)

	return H

def hessFrequencies(H):

	evec, ev = npl.eigh(H)
	evec = np.sort(evec)
	evec = evec[::-1]

	evec = [np.sqrt(evec[i]*(1.0432*10**9))/(2*np.pi) for i in range(len(evec))]

	return evec

def v_(atom1, atom2, positions = pos(geomCont)):

	v_ij = (positions[atom2]-positions[atom1])
	return v_ij

def main(geometry, hessian):

	positions = pos(geometry)
	atomicMasses = atomicMass(geometry)
	hess = hessianDat(hessian)
	MH = massWeight(hess,atomicMasses)
	ev = hessFrequencies(MH)

	print("\nPositions:")
	print(positions)
	print("\nHessian:")
	print(hess)
	print("\nMass Weighted Hessian:")
	print(MH)
	print("\nHessian Eigenvalues:")

	print(np.around(ev, 6))

	return None

main(geomCont,hessCont)
print("--- %s seconds ---" % (time.time() - start_time))


from difflib import SequenceMatcher
import pandas as pd
from itertools import combinations

#Dupicate Delete - Deletes similar strings in a list of strings.
#yenilistemiz = remove_duplicatish(list)
def remove_duplicatish(alist):
    list_remove = []
    alist = list(set(alist))
    listcomb = list(combinations(alist, 2))
    for birtuple in listcomb:
        item1 = birtuple[0]
        item2 = birtuple[1]
        if SequenceMatcher(None, item1.lower(), item2.lower()).ratio() > 0.6: #change this ratio
            list_remove.append(item2)
    list_difference = list(set(list_remove))
    list_final = [x for x in alist if x not in list_difference]
    return list_final

#Another duplicate deleter simple is better.
from difflib import SequenceMatcher
liste = ["PARALAR", "paralar", "kapıcı", "parasız", "kapı", "geldiğin yere geri dön", "geldiğin yere geri dönme", "Özdilek Park Gucci", "Özdilek Park 2.Kat Gucci"]
def eliminate_duplicates(liste, ratio = 0.8):
    newlist= []
    for item in liste:
        for itemcompare in newlist:
            if SequenceMatcher(None, item.lower(), itemcompare.lower()).ratio() > ratio:
                break
        else:
            newlist.append(item)
    return newlist
print(eliminate_duplicates(liste))


import json
import os, os.path
import errno
from pathlib import Path

def mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError as exc:
        if exc.errno == errno.EEXIST and os.path.isdir(path):
            pass
        else:
            raise

def safe_open_w(path):
    mkdir_p(os.path.dirname(path))
    return open(path, 'w')

def write_json(path, content, sorting=False):
    path = get_main_path() + path
    with safe_open_w(path) as file:
        json.dump(content, file, indent=4, sort_keys=sorting)

def read_json(path):
    path = get_main_path() + path
    try:
        with open(path, "r") as file:
            content = json.load(file)
        return content
    except FileNotFoundError:
        print(f"File at the path {path} was not found")
        return False

def get_main_path():
    path = Path(__file__).parent
    while os.path.basename(os.path.normpath(path)) != "GoblinsCaverns":
        path = path.parent
    return str(path)


import sys
from collections import deque

N = int(sys.stdin.readline())

for i in range(N):
  S = sys.stdin.readline().rstrip()
  result = ''
  N_deque = deque()
  for j in range(0, len(S)):
    if S[j] == '(':
      N_deque.insert(j,'(')
      N_deque.insert(j+1,')')

  for k in N_deque:
    result += k

  if S == result:
    print('YES')
  else:
    print('NO')


import gym
import gym_prescan as gp

# env = gym.make('prescan-without-matlabengine-v0',verbose=True,host='172.21.217.140')
env_dict = {
    'id':       'prescan-without-matlabengine-v0',
    'verbose':  True,
    'host':     '172.21.217.140',
    # 'delay':    2
    'nget':       500
}
env = gym.make(**env_dict)
for _ in range(3):
    env.reset()
    for i in range(3000):
        env.render()
        # env.step(env.action_space.sample()) # take a random action
        n = 200
        a = 3
        if i%n == 0:
            if i%(2*n) == 0:
                a = 0
            else:
                a = 1
        s,r,done, _ = env.step(a)
        if done:
            env.reset()
    # env.close()

    print('+++++++++++++++++++++++++++++++++++++')
# env.reset()
# env.step(5)


#!/usr/bin/env python

import os
from collections import OrderedDict
from copy import deepcopy

import numpy as np
from multistate_kernel.util import MultiStateData

from snad import OSCCurve, BazinFitter, SNFiles, transform_bands_msd
from snad.interpolate.gp import GPInterpolator
from snad.process.util import preprocess_curve_default, zero_negative_fluxes

PROJECT_ROOT = os.path.dirname(os.path.dirname(__file__))
DATA_ROOT = os.path.join(PROJECT_ROOT, 'data')
FIG_ROOT = os.path.join(PROJECT_ROOT, 'fig')
SNE_PATH = os.path.join(PROJECT_ROOT, 'sne')
COLORS = {'B': 'b', 'R': 'deeppink', 'I': 'olive',
          'g': 'g', 'r': 'r', 'i': 'brown',
          "g'": 'g', "r'": 'r', "i'": 'brown',}

def _peak(interpolator, peak_band, bazin_fitter=None):
    X = interpolator.msd.X
    x_for_peak_search = np.linspace(X[:, 1].min(), X[:, 1].max(), 101)
    msd = interpolator(x_for_peak_search, compute_err=False)
    if bazin_fitter is not None:
        msd_bazin = bazin_fitter(x_for_peak_search)
        msd = msd + msd_bazin
    x_peak = msd.odict[peak_band].x[np.argmax(msd.odict[peak_band].y)]
    return x_peak

def _plot(fig_dir, orig_curve, interpolator, msd, msd_bazin=None, msd_plus_bazin=None, msd_transformed=None):
    import matplotlib; matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    plt.clf()
    vsize = 1 + int(msd_bazin is not None) + int(msd_transformed is not None)
    fig, ax_ = plt.subplots(vsize, 3, figsize=(10, 4*vsize), sharex=True)
    ax_ = np.atleast_2d(ax_)
    for i, band in enumerate(bands):
        plt.sca(ax_[0, i])
        if i == 1:
            plt.title('{}  {}{}'.format(
                orig_curve.name,
                ', '.join(msd.odict.keys()),
                ' Near bounds' * interpolator.near_bounds
            ))

        blc = orig_curve.odict[band]
        normal = blc[(np.isfinite(blc.err)) & (~blc.isupperlimit)]
        wo_errors = blc[(~np.isfinite(blc.err)) & (~blc.isupperlimit)]
        upper_limit = blc[blc.isupperlimit]
        plt.errorbar(normal.x, normal.y, normal.err, marker='x', ls='', label=band, color=COLORS[band])
        plt.plot(wo_errors.x, wo_errors.y, '*', color=COLORS[band])
        plt.plot(upper_limit.x, upper_limit.y, 'v', color=COLORS[band])

        if msd_bazin is not None and msd_plus_bazin is not None:
            plt.plot(msd_bazin.odict[band].x, msd_bazin.odict[band].y, '--', color=COLORS[band])
            odict = msd_plus_bazin.odict
        else:
            odict = msd.odict
        plt.plot(odict[band].x, odict[band].y, color=COLORS[band])
        plt.fill_between(odict[band].x,
                         odict[band].y - odict[band].err, odict[band].y + odict[band].err,
                         color='grey', alpha=0.2)
        # plt.ylim([0, None])
        plt.grid()
        plt.legend()

        if msd_bazin is not None:
            plt.sca(ax_[1, i])
            odict = msd.odict[band]
            plt.errorbar(odict.x, odict.y, odict.err, marker='x', ls='', color=COLORS[band])
            plt.plot(msd.odict[band].x, msd.odict[band].y, color=COLORS[band], label=band)
            plt.fill_between(msd.odict[band].x,
                             msd.odict[band].y - msd.odict[band].err, msd.odict[band].y + msd.odict[band].err,
                             color='grey', alpha=0.2)
            plt.grid()
            plt.legend()

    if msd_transformed is not None:
        for i, (band, lc) in enumerate(msd_transformed.odict.items()):
            plt.sca(ax_[vsize-1, i])
            plt.plot(lc.x, lc.y, color=COLORS[band], label=band)
            plt.grid()
            plt.legend()

    fig_path = os.path.join(fig_dir, '{}.png'.format(orig_curve.name))
    print(fig_path)
    plt.savefig(fig_path)

def interpolate(sn, bands, peak_band, rng=np.linspace(-50, 100, 151), fig_dir='.',
                plot=True, with_bazin=True, transform=None):
    rng_width = rng.max() - rng.min()

    orig_curve = OSCCurve.from_json(sn, bands=bands)
    curve = preprocess_curve_default(orig_curve, keep_interval=(-2*rng_width, 2*rng_width), peak_band=peak_band)

    kernels_ = GPInterpolator.default_initial_kernels(curve, min_length_limits=(1, 0.5*rng_width))
    m, m_bounds = GPInterpolator.default_constant_matrix(len(curve))
    bazin_fitter = None
    if with_bazin:
        bazin_fitter = BazinFitter(curve, curve.name)
        bazin_fitter.fit(use_gradient=True)
        curve = curve - bazin_fitter()
    interpolator = GPInterpolator(
        curve, kernels_, m, m_bounds,
        normalize_y=with_bazin,
        optimize_method='trust-constr',
        n_restarts_optimizer=0,
        raise_on_bounds=False,
        add_err=0,
        random_state=0,
    )

    x_peak = _peak(interpolator, peak_band, bazin_fitter)
    x_ = rng + x_peak

    msd = interpolator(x_, compute_err=True)
    msd_bazin = None
    msd_plus_bazin = None
    if with_bazin:
        msd_bazin = bazin_fitter(x_)
        msd_plus_bazin = msd + msd_bazin

    msd = zero_negative_fluxes(msd, x_peak)

    msd_transformed = None
    if transform is not None:
        if with_bazin:
            msd_transformed = transform_bands_msd(msd_plus_bazin, transform, fill_value=0)
        else:
            msd_transformed = transform_bands_msd(msd, transform, fill_value=0)

    if plot:
        _plot(fig_dir, orig_curve, interpolator, msd, msd_bazin, msd_plus_bazin, msd_transformed)

    if transform:
        return interpolator, msd_transformed
    if with_bazin:
        return interpolator, msd_plus_bazin
    return interpolator, msd

def results_to_table(results, old_table, bands, table_bands, rng):
    import pandas

    df = pandas.read_csv(old_table, sep=',')
    deriv = pandas.DataFrame(index=df.index, columns=['deriv_{}'.format(band) for band in bands])
    weight_deriv = pandas.DataFrame(index=df.index, columns=['weight_deriv_{}'.format(band) for band in bands])
    logl = pandas.Series(index=df.index, name='log_likehood')
    theta = pandas.DataFrame(index=df.index, columns=['theta_{}'.format(i) for i in range(9)])
    curves = pandas.DataFrame(index=df.index,
                              columns=['{}{:+03d}'.format(band[0], int(t)) for band in table_bands for t in rng],
                              dtype=float)

    for i, (interpolator, interp_msd) in enumerate(results):
        msd = interpolator.msd
        obs_approx = interpolator(msd.arrays.x, compute_err=False)
        for j, band in enumerate(bands):
            df[band][i] = msd.odict[band].x.size
            deriv.iloc[i][j] = np.sum(np.square(msd.odict[band].y - obs_approx.odict[band].y))
            weight_deriv.iloc[i][j] = np.sum(np.square(msd.odict[band].y - obs_approx.odict[band].y)
                                             / msd.odict[band].err)
        logl[i] = interpolator.regressor.log_marginal_likelihood()
        theta.iloc[i] = interpolator.regressor.kernel_.theta
        curves.iloc[i] = np.hstack(interp_msd.odict[band].y for band in table_bands)

    df = pandas.concat((df, deriv, weight_deriv, logl, theta, curves), axis=1)
    csv_name = 'extrapol_{}_{}_{}.csv'.format(rng.min(), rng.max(), ','.join(b.replace("'", '_pr') for b in bands))
    df.to_csv(os.path.join(DATA_ROOT, csv_name), sep=',', index=False)

if __name__ == '__main__':
    import os
    import sys
    import multiprocessing
    from functools import partial
    from snad import BRI_to_gri

    band_sets = ('B,R,I', 'g,r,i', "g',r',i'",)
    if len(sys.argv) > 1:
        band_sets = sys.argv[1:]

    rng = np.r_[-20:100:121j]

    for bands in band_sets:
        bands = bands.split(',')
        basename = ','.join(band.replace("'", '_pr') for band in bands)
        sne_csv = os.path.join(DATA_ROOT, 'min3obs_{}.csv'.format(basename))
        sn_files = SNFiles(sne_csv, update=False, path=SNE_PATH)
        fig_dir = os.path.join(FIG_ROOT, basename)
        os.makedirs(fig_dir, exist_ok=True)
        transform = None
        table_bands = bands
        if set(bands) == {'B', 'R', 'I'}:
            transform = BRI_to_gri
            table_bands = ('g', 'r', 'i')
        interp = partial(interpolate,
                         rng=rng, bands=bands, peak_band=bands[1],
                         fig_dir=fig_dir, plot=True, with_bazin=False, transform=transform)
        with multiprocessing.Pool() as p:
            results = p.map(interp, sn_files.filepaths)
        results_to_table(results, sne_csv, bands, table_bands, rng)


from django.test import TestCase

from hc.api.models import Check

class StatusTestCase(TestCase):

    def test_it_works(self):
        check = Check()
        check.save()

        r = self.client.get("/status/%s/" % check.code)
        self.assertContains(r, "last_ping", status_code=200)

    def test_it_handles_bad_uuid(self):
        r = self.client.get("/status/not-uuid/")
        assert r.status_code == 400


class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:

        nums_dict = dict()

        for idx in range(len(nums)):
            temp_target = target - nums[idx]

            if nums[idx] in nums_dict.keys():
                return [nums_dict[nums[idx]], idx ]
            else:
                nums_dict[temp_target] = idx


# importing libraries and functions
from fastapi import APIRouter, Request
import re
import json
import skops.io as sio
import pandas as pd

from utils import sklearn

# instantiating the router
router = APIRouter(prefix='/api')

# index test route
@router.get('/')
async def get_index():
    return 'OK'

# student analysis route
@router.post('/analyze_student')
async def post_analyze_student(request: Request):
    request_content = await request.json()
    X = pd.DataFrame.from_dict(request_content).T

    X_transformed = sklearn.PREPROCESSOR.transform(X)
    X_transformed = pd.DataFrame(X_transformed, columns=[re.sub(r'.+__', '', item) for item in sklearn.PREPROCESSOR.get_feature_names_out()], index=X.index)
    X_transformed = X_transformed.drop(columns=['PARTICIPANTE_TP_SEXO_M'])

    preds = {
        'knn_classifier': sklearn.KNN_CLASSIFIER.predict(X_transformed),
        'knn_regressor': sklearn.KNN_REGRESSOR.predict(X_transformed),
        'linear_regression': sklearn.LINEAR_REGRESSION.predict(X_transformed),
        'logistic_regression': sklearn.LOGISTIC_REGRESSION.predict(X_transformed),
        'naive_bayes': sklearn.NAIVE_BAYES.predict(X_transformed),
        'svm_classifier': sklearn.SVM_CLASSIFIER.predict(X_transformed),
        'svm_regressor': sklearn.SVM_REGRESSOR.predict(X_transformed),
        'randomforest_classifier': sklearn.RANDOMFOREST_CLASSIFIER.predict(X_transformed),
        'randomforest_regressor': sklearn.RANDOMFOREST_REGRESSOR.predict(X_transformed),
    }
    preds = pd.DataFrame(preds, index=X_transformed.index)

    classifiers = ['knn_classifier', 'logistic_regression', 'naive_bayes', 'svm_classifier', 'randomforest_classifier']
    regressors = ['knn_regressor', 'linear_regression', 'svm_regressor', 'randomforest_regressor']

    preds = preds.apply(lambda column: round(column, 2), axis=0)

    preds['classifiers_summary'] = preds.apply(lambda row: int(pd.Series([row[classifier] for classifier in classifiers]).mode()), axis=1)
    preds['regressors_summary'] = preds.apply(lambda row: round(pd.Series([row[regressor] for regressor in regressors]).mean(), 2), axis=1)

    return json.loads(preds.to_json(orient='index'))


from tkinter import *
root=Tk()
root.title("Calculator")
temp=""
equation=StringVar()
equation.set("Enter your expression:")
calculation=Label(root,textvariable=equation)
calculation.grid(columnspan=3)

def press(num):
    global temp
    temp=temp+str(num)
    equation.set(temp)

def EqualPress():
    global temp
    total=str(eval(temp))
    equation.set(total)
    temp=""

def clear():
    global temp
    temp=""
    equation.set("")

b0=Button(root,text="0",command=lambda:press(0))
b0.grid(row=4,column=1)
b1=Button(root,text="1",fg="dark green",command=lambda:press(1))
b1.grid(row=1,column=0)
b2=Button(root,text="2",fg="dark green",command=lambda:press(2))
b2.grid(row=1,column=1)
b3=Button(root,text="3",fg="dark green",command=lambda:press(3))
b3.grid(row=1,column=2)
b4=Button(root,text="4",fg="dark green",command=lambda:press(4))
b4.grid(row=2,column=0)
b5=Button(root,text="5",fg="dark green",command=lambda:press(5))
b5.grid(row=2,column=1)
b6=Button(root,text="6",fg="dark green",command=lambda:press(6))
b6.grid(row=2,column=2)
b7=Button(root,text="7",fg="dark green",command=lambda:press(7))
b7.grid(row=3,column=0)
b8=Button(root,text="8",fg="dark green",command=lambda:press(8))
b8.grid(row=3,column=1)
b9=Button(root,text="9",fg="dark green",command=lambda:press(9))
b9.grid(row=3,column=2)
Plus=Button(root,text="+",fg="orange",command=lambda:press("+"))
Plus.grid(row=1,column=3)
Minus=Button(root,text="-",fg="orange",command=lambda:press("-"))
Minus.grid(row=2,column=3)
Multiply=Button(root,text="*",fg="orange",command=lambda:press("*"))
Multiply.grid(row=3,column=3)
Divide=Button(root,text="/",fg="orange",command=lambda:press("/"))
Divide.grid(row=4,column=3)
Equal=Button(root,text="=",fg="red",command=EqualPress)
Equal.grid(row=4,column=2)
Clear=Button(root,text="C",fg="brown",bg="light blue",command=clear)
Clear.grid(row=4,column=0)

root.mainloop()


"""added PHU capacity

Revision ID: 4408c7b44980
Revises: e46ca5f12457
Create Date: 2020-03-24 09:28:12.921258

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '4408c7b44980'
down_revision = 'e46ca5f12457'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('phucapacity',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('name', sa.String(), nullable=True),
    sa.Column('icu', sa.Integer(), nullable=True),
    sa.Column('acute', sa.Integer(), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_phucapacity_name'), 'phucapacity', ['name'], unique=False)
    op.drop_column('comparison', 'hundred')
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('comparison', sa.Column('hundred', sa.INTEGER(), autoincrement=False, nullable=True))
    op.drop_index(op.f('ix_phucapacity_name'), table_name='phucapacity')
    op.drop_table('phucapacity')
    # ### end Alembic commands ###


import unittest
import matplotlib.pyplot as plt
import numpy as np
import cv2
import modulos.Datos as dt

class Plt(unittest.TestCase):
    def setUp(self) -> None:
        print('--> Iniciando test')
        datosx = [1, 2, 3, 4, 5, 6]
        datosy = [2, 4, 6, 7, 9, 2]
        self.imagen = cv2.imread(r'C:\Google Drive\Cursos\Python_OpenCV\Deskew\Docs\Texto.png', 1)
        self.datos = dt.Datos()

    def tearDown(self) -> None:
        print('--> Test terminado')

    def test_figura(self):
        fig = plt.Figure(figsize=(5, 5), dpi=100)
        plt_axes = fig.add_subplot(111)
        plt_axes.plot([1, 2, 3, 4, 5, 6], [2, 4, 6, 7, 9, 2])
        plt.show()
        y = np.random.rand(100)
        x = range(0, 100, 1)
        plt_axes.plot(x, y)
        plt.show()
        cv2.imshow('Ventana', self.imagen)
        cv2.waitKey()

    def test_matrices(self):
        self.datos.actualizar_figura_plt()

class FFT(unittest.TestCase):

    def setUp(self) -> None:
        print('--> Iniciando test')

    def tearDown(self) -> None:
        print('--> Test terminado')

    def test_fft(self):
        dti = 0.001
        t = np.arange(0, 1, dti)
        f = np.sin(2 * np.pi * 50 * t) + np.sin(2 * np.pi * 120 * t)
        f_clean = f
        f = f + 2.5 * np.random.randn(len(t))
        # plt.plot(t, f)
        # plt.plot(t, f_clean)
        # plt.show()

        n = len(t)
        fhat = np.fft.fft(f, n)
        PSD = fhat * np.conj(fhat) / n
        plt.plot(PSD[:n // 2])
        plt.show()

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


#! /usr/bin/env python
#
# find the optimal parameters in the exchange and correlation parts of M05 functional
#
import os,sys,string,math,time
import numpy as np
import re
import praxis
import pdb
#import scipy.optimize.optimize
#
###################################################
def prep_par(param):
#
#
# prepare the dat files with the parameters for M05
	paramx=[param[0],1.0,param[1],0.0,0.0,0.0,1.0,param[2],param[3],param[4],param[5]]
	paramcp= [1.0,param[6],param[7],0.0,0.0,param[8]]
	paramcap=[1.0,param[9],param[10],0.0,0.0]
#
# the parameters as in the original M05
#
#	 at1=	 0.08151
#	 at2=	 -0.43956
#	 at3=	 -3.22422
#	 at4=	 2.01819
#	 at5=	 8.79431
#	 at6=	 -0.00295
#	 at7=	 9.82029
#	 at8=	 -4.82351
#	 at9=	 -48.17574
#	 at10=	 3.64802
#	 at11=	 34.02248
#	 hfx =	 0.28
#	 C1 =	 3.36116E-03
#	 C2=	 4.49267E-03
#
	coefs=[0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.]
	for i in range(len(paramx)):
		coefs[i]=paramx[i]
#	coefs[12]=param[8]
#
# coefs for revPBE
#
#	coefs[13]=0.00336116
#	coefs[14]=0.00290129
#
	s=""
	for i in range(11):
		s+=str(coefs[i])+" "
	s+="\n"
	f=open('ParamM05X.dat','w')
	f.write(s)
#	line=f.readline()
	f.close()
#	f=open('ParamM05X.dat','r')
#	a=f.readline()
#	f.close()
#	fs=open('atta.dat','w')
#	fs.write(str(a))
#
# the parameters for the parallel part of corr in M05
#  3.77344 -26.04463 30.69913 -9.22695
#
	coefs=[0.,0.,0.,0.,0.,0.]
	for i in range(len(paramcp)):
		coefs[i]=paramcp[i]
	s=""
	for i in range(6):
		s+=str(coefs[i])+" "
	s+="\n"
	f=open('ParamM05CP.dat','w')
	f.write(s)
#	line=f.readline()
	f.close()
#	f=open('ParamM05CP.dat','r')
#	b=f.readline()
#	f.close
#	fs=open('atta.dat','w')
#	fs.write("str(b)\n")
#
# the parameters for the antiparallel part of corr in M05
# 3.78569 -14.15261 -7.46589 17.94491
#
	coefs=[0.,0.,0.,0.,0.]
	for i in range(len(paramcap)):
		coefs[i]=paramcap[i]
	s=""
	for i in range(5):
		s+=str(coefs[i])+" "
	s+="\n"
	f=open('ParamM05CAP.dat','w')
	f.write(s)
#	line=f.readline()
	f.close()
#	f=open('ParamM05CAP.dat','r')
#	c=f.readline()
#	f.close
#	fs=open('atta.dat','w')
#	fs.write(str(a))
#	fs.write(str(b))
#	fs.write(str(c)+'\n')
#	fs.close
#
	return
##################################################
def prep_run(name):
	f=open("run",'r')
	s=f.read()
	f.close()
	s=s.replace("name",name)
	f=open(prefix+"run"+name,'w')
	f.write(s)
	f.close()
	return
###################################################
def prep_inputs():
#
# prepare the inputs
#
# herer!!!
	s0="%Mem=6GB"
	s0+="\n%NProcShared=16"
	s0+="\n#T M05/Gen test Massage SCF=(tight,maxcyc=20)"
# Guess=TCheck "
# herer!!!

#	s0+="integral=(grid=ultrafine)\n\nM05 opt"
	s0+="\n\nM05 opt"
#
	basis="\n@aug-cc-pVTZ.gbs/N\n\n"
#	count=0
#	for R in RAr:
#		count+=1
#		name="ArA_"+str(count)
#		f=open(name+".com",'w')
#		f.write("%Chk="+name+"\n")
#		f.write(s0)
#		f.write("\n\n0 1\nAr 0.0 0.0 0.0\nAr-Bq 0.0 0.0 R\n\n")
#		f.write("R="+str(R))
#		f.write("\n"+basis)
#		f.close()
#		prep_run(name)
#
# Ar2
#
#	count=0
#	for R in RAr:
#		count+=1
#		name="Ar_"+str(count)
#		f=open(name+".com",'w')
#		f.write("%Chk="+name+"\n")
#		f.write(s0)
#		f.write("\n\n0 1\nAr 0.0 0.0 0.0\nAr 0.0 0.0 R\n\n")
#		f.write("R="+str(R))
#		f.write("\n"+basis)
#		f.close()
#		prep_run(name)
#
# H2OA, H2OB, H2O
#
	os.system('cp geoparmH2O.d geoparm.d')
	os.system('cp dimerH2O.cnf dimer.cnf')
	f=open('geoparm.d','r')
	geo=[]
	for line in f:
		geo.append(line[0:74])
	f.close()
#
	count=0
	for p in pH2O:
		count+=1
		ft=open('temp','w')
		ft.write(geo[p-1]+'DOR6')
		ft.close()
		os.system('./getgeoG03.exe < temp')
#
		name="H2OA_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geoA.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
#
		name="H2OB_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geoB.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
#
		name="H2O_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geo.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
#
# CH4A,CH4B,CH4
#
	os.system('cp geoparmCH4.d geoparm.d')
	os.system('cp dimerCH4.cnf dimer.cnf')
	f=open('geoparm.d','r')
	geo=[]
	for line in f:
		geo.append(line[0:74])
	f.close()
#
	count=0
	for p in pCH4:
		count+=1
		ft=open('temp','w')
		ft.write(geo[p-1]+'DOR6')
		ft.close()
		os.system('./getgeoG03.exe < temp')
#
		name="CH4A_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geoA.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
#
		name="CH4B_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geoB.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
#
		name="CH4_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geo.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
#
# C2H4A,C2H4B,C2H4
#
	os.system('cp geoparmC2H4.d geoparm.d')
	os.system('cp dimerC2H4.cnf dimer.cnf')
	f=open('geoparm.d','r')
	geo=[]
	for line in f:
		geo.append(line[0:74])
	f.close()
#
	count=0
	for p in pC2H4:
		count+=1
		ft=open('temp','w')
		ft.write(geo[p-1]+'DOR6')
		ft.close()
		os.system('./getgeoG03.exe < temp')
#
		name="C2H4A_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write("Density=Checkpoint\n")
#		f.write("%OldChk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geoA.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
#
		name="C2H4B_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write("Density=Checkpoint\n")
#		f.write("%OldChk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geoB.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
#
		name="C2H4_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write("Density=Checkpoint\n")
#		f.write("%OldChk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geo.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
#
# C2H2ClFA, C2H2ClFB, C2H2ClF
#
	os.system('cp geoparmC2H2ClF.d geoparm.d')
	os.system('cp dimerC2H2ClF.cnf dimer.cnf')
	f=open('geoparm.d','r')
	geo=[]
	for line in f:
		geo.append(line[0:74])
	f.close()
#
	count=0
	for p in pC2H2ClF:
		count+=1
		ft=open('temp','w')
		ft.write(geo[p-1]+'DOR6')
		ft.close()
		os.system('./getgeoG03.exe < temp')
#
		name="C2H2ClFA_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geoA.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
#
		name="C2H2ClFB_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geoB.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
#
		name="C2H2ClF_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geo.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
#
# NH3_ClFA, NH3_ClFB, NH3_ClF
#
	os.system('cp geoparmNH3_ClF.d geoparm.d')
	os.system('cp dimerNH3_ClF.cnf dimer.cnf')
	f=open('geoparm.d','r')
	geo=[]
	for line in f:
		geo.append(line[0:74])
	f.close()
#
	count=0
	for p in pNH3_ClF:
		count+=1
		ft=open('temp','w')
		ft.write(geo[p-1]+'DOR6')
		ft.close()
		os.system('./getgeoG03.exe < temp')
#
		name="NH3_ClFA_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geoA.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
#
		name="NH3_ClFB_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geoB.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
#
		name="NH3_ClF_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geo.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
#
# C2H4_ArA, C2H4_ArB, C2H4_Ar
#
	os.system('cp geoparmC2H4_Ar.d geoparm.d')
	os.system('cp dimerC2H4_Ar.cnf dimer.cnf')
	f=open('geoparm.d','r')
	geo=[]
	for line in f:
		geo.append(line[0:74])
	f.close()
#
	count=0
	for p in pC2H4_Ar:
		count+=1
		ft=open('temp','w')
		ft.write(geo[p-1]+'DOR6')
		ft.close()
		os.system('./getgeoG03.exe < temp')
#
		name="C2H4_ArA_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geoA.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
#
		name="C2H4_ArB_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geoB.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
#
		name="C2H4_Ar_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geo.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
#
# C2H4_F2A, C2H4_F2B, C2H4_F2
#
#	os.system('cp geoparmC2H4_F2.d geoparm.d')
#	os.system('cp dimerC2H4_F2.cnf dimer.cnf')
#	f=open('geoparm.d','r')
#	geo=[]
#	for line in f:
#		geo.append(line[0:74])
#	f.close()
#
#	count=0
#	for p in pC2H4_F2:
#		count+=1
#		ft=open('temp','w')
#		ft.write(geo[p-1]+'DOR6')
#		ft.close()
#		os.system('./getgeoG03.exe < temp')
#
#		name="C2H4_F2A_"+str(count)
#		f=open(name+".com",'w')
#		f.write("%Chk="+name+"\n")
#		f.write(s0)
#		f.write("\n\n0 1\n")
#		fgeo=open('geoA.d','r')
#		s=fgeo.read()
#		fgeo.close()
#		f.write(s)
#		f.write(basis)
#		f.close()
#		prep_run(name)
#
#		name="C2H4_F2B_"+str(count)
#		f=open(name+".com",'w')
#		f.write("%Chk="+name+"\n")
#		f.write(s0)
#		f.write("\n\n0 1\n")
#		fgeo=open('geoB.d','r')
#		s=fgeo.read()
#		fgeo.close()
#		f.write(s)
#		f.write(basis)
#		f.close()
#		prep_run(name)
#
#		name="C2H4_F2_"+str(count)
#		f=open(name+".com",'w')
#		f.write("%Chk="+name+"\n")
#		f.write(s0)
#		f.write("\n\n0 1\n")
#		fgeo=open('geo.d','r')
#		s=fgeo.read()
#		fgeo.close()
#		f.write(s)
#		f.write(basis)
#		f.close()
#		prep_run(name)
#
# NH3A, NH3B, NH3
#
	os.system('cp geoparmNH3.d geoparm.d')
	os.system('cp dimerNH3.cnf dimer.cnf')
	f=open('geoparm.d','r')
	geo=[]
	for line in f:
		geo.append(line[0:74])
	f.close()
#
	count=0
	for p in pNH3:
		count+=1
		ft=open('temp','w')
		ft.write(geo[p-1]+'DOR6')
		ft.close()
		os.system('./getgeoG03.exe < temp')
#
		name="NH3A_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geoA.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
#
		name="NH3B_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geoB.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
#
		name="NH3_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geo.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
#
# ArHFA, ArHFB, ArHF
#
	os.system('cp geoparmArHF.d geoparm.d')
	os.system('cp dimerArHF.cnf dimer.cnf')
	f=open('geoparm.d','r')
	geo=[]
	for line in f:
		geo.append(line[0:74])
	f.close()
#
	count=0
	for p in pArHF:
		count+=1
		ft=open('temp','w')
		ft.write(geo[p-1]+'DOR6')
		ft.close()
		os.system('./getgeoG03.exe < temp')
#
		name="ArHFA_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geoA.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
#
		name="ArHFB_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geoB.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
#
		name="ArHF_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geo.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
#
# N2_HFA, N2_HFB, N2_HF
#
	os.system('cp geoparmN2_HF.d geoparm.d')
	os.system('cp dimerN2_HF.cnf dimer.cnf')
	f=open('geoparm.d','r')
	geo=[]
	for line in f:
		geo.append(line[0:74])
	f.close()
#
	count=0
	for p in pN2_HF:
		count+=1
		ft=open('temp','w')
		ft.write(geo[p-1]+'DOR6')
		ft.close()
		os.system('./getgeoG03.exe < temp')
#
		name="N2_HFA_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geoA.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
#
		name="N2_HFB_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geoB.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
#
		name="N2_HF_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geo.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
		prep_run(name)
#
# change the basis set to aDZ
#
	basis="\n@aug-cc-pVDZ.gbs/N\n\n"
#
# H2ODZA, H2ODZB, H2ODZ
#
	os.system('cp geoparmH2OZ.d geoparm.d')
	os.system('cp dimerH2OZ.cnf dimer.cnf')
	f=open('geoparm.d','r')
	geo=[]
	for line in f:
		geo.append(line[0:74])
	f.close()
#
	count=0
	for p in pH2ODZ:
		count+=1
		ft=open('temp','w')
		ft.write(geo[p-1]+'DOR6')
		ft.close()
		os.system('./getgeoG03.exe < temp')
#
		name="H2ODZA_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geoA.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
#
		name="H2ODZB_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geoB.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
#
		name="H2ODZ_"+str(count)
		f=open(name+".com",'w')
		f.write("%Chk="+name+"\n")
		f.write(s0)
		f.write("\n\n0 1\n")
		fgeo=open('geo.d','r')
		s=fgeo.read()
		fgeo.close()
		f.write(s)
		f.write(basis)
		f.close()
		prep_run(name)
#
	os.system("rm temp")
#
	return
###################################################
def en_int(monomerA,monomerB,dimer):
#
	conv=627.509474
# get the energy of a monomer in DCBS
#
	Conv1=0
	f=open(monomerA,'r')
	for line in f:
		if line[:10]==" SCF Done:":
			Conv1=1
			for l in range(len(line)) :
				if line[l]=="=":
					ini=l+1
				if line[l]=="A":
					fin=l-2
			en_monoA=float(line[ini:fin])
#			print "en_monoA", en_monoA
	f.close()
	if Conv1==0:
		en_monoA=0.0
		print("No convergence in"),monomerA
#		print "No convergence in",monomerA
#
	Conv1=0
	f=open(monomerB,'r')
	for line in f:
		if line[:10]==" SCF Done:":
			Conv1=1
			for l in range(len(line)) :
				if line[l]=="=":
					ini=l+1
				if line[l]=="A":
					fin=l-2
			en_monoB=float(line[ini:fin])
#			print "en_monoB", en_monoB
	f.close()
	if Conv1==0:
		en_monoB=0.0
		print("No convergence in"),monomerB
#		print "No convergence in",monomerB
#
#
# obtain the energy of dimer
#
	Conv2=0
	f=open(dimer,'r')
	for line in f:
		if line[:10]==" SCF Done:":
			Conv2=1
			for l in range(len(line)) :
				if line[l]=="=":
					ini=l+1
				if line[l]=="A":
					fin=l-2
			en_dim=float(line[ini:fin])
	f.close()
	if Conv2==0:
		en_dim=0.0
		print("No convergence in"),dimer
#		print "No convergence in",dimer
#
#	Dispersion part:
#
#	file='/data/szalewicgrp/atta/dldf-praxis-opt/Disp/'+monoA
#	f=open('/data/szalewicgrp/atta/dldf-test-praxis-opt/monomers/'+monoA,'r')
#	lineA=f.read()
#	f3=open('fileA.dat','w')
#	f3.write(str(lineA))
#	f3.close()
#	f.close()
#	file='/data/szalewicgrp/atta/dldf-praxis-opt/Disp/'+monoB
#	f=open('/data/szalewicgrp/atta/dldf-test-praxis-opt/monomers/'+monoB,'r')
#	lineB=f.read()
#	f4=open('fileB.dat','w')
#	f4.write(lineB)
#	f4.close()
#	f.close()
#	os.system('./disp.exe')
#	with open('aaa','r') as f:
#		d_e=f.readline()
#	disp_en=float(d_e)
#	fd=open('/data/szalewicgrp/atta/dldf-test-praxis-opt/monomers/disp.data','a')
#	fd.write(monoA+'\n')
#	fd.write(monoB+'\n')
#	fd.write(str(disp_en)+'\n')
#	fd.close()
	dlDF=round((en_dim-en_monoA-en_monoB)*conv,8)
	return dlDF
###################################################
def exist(name):
	f=os.popen("ls "+name+" 2>sss")
	s=f.read()
	f.close()
	os.system("rm sss")
	return s==name+"\n"
###################################################
def get_queue():
	listq=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]
	qno=-1
	while qno==-1:
		for q in listq:
			f=os.popen("qstat -f")
			s=f.read()
			f.close()
			ind=s.find("all.q@compute-0-"+str(q))
			used=float(s[ind+37:ind+38])
			f=os.popen("qstat -q all.q@compute-0-"+str(q)+".local | grep '	qw  '")
			waiting=f.read()
			f.close()
			f=os.popen("qstat -q all.q@compute-0-"+str(q)+".local | grep '	t  '")
			t=f.read()
			f.close()
#
			if q==14:
				used+=1
#
			if used<2 and len(waiting)==0 and len(t)==0:
				qno=q
				break
	return qno
###################################################
def jobs_running(m):
	run=0
	while run==0:
		f=os.popen("squeue -u connornm | grep 'connornm'")
		count=0
		for line in f:
			count+=1
		f.close()
		if count<=m:
			run=1
	return
###################################################
def get_err(param,n):
	global x
	x= param
#	param=x[0]
#	conv=627.509474
	n=11
#get_err(param,names,ERef,RRef,no_pts)
#	conv=3.157733E5
#
	prep_par(param)
#
# prepare a list of jobs
# here range(3) means 3 molecules, change for more molecules
	list=[]
	for m in range(10):
		count=0
		for i in range(no_pts[m]):
			count+=1
			name="run"+names[m]+"A_"+str(count)
			list.append(prefix+name)
			name="run"+names[m]+"B_"+str(count)
			if exist(prefix+name):
				list.append(prefix+name)
			name="run"+names[m]+"_"+str(count)
			list.append(prefix+name)
#
	for job in list:
#		jobs_running(5)
#		print job
#		q=get_queue()
#		os.system("qsub -q all.q@compute-0-"+str(q)+".local "+job+" >sss")
		os.system("sbatch "+job+" >sss")
	os.system("rm sss")
#
	running=1
	while running:
		f=os.popen("squeue -u connornm")
		s=f.read()
		f.close()
		ind=s.find(prefix+"run")
		if ind==-1:
			running=0
# collect the results
#
	eDFT=[]
	molec=[]
#
# add the errors from the interaction energies
#
	for n in range(len(names)):
		count=0
		for i in range(no_pts[n]):
			count+=1
			monomerA=names[n]+"A_"+str(count)+".log"
			monomerB=names[n]+"B_"+str(count)+".log"
#			monoA=names[n]+"_"+str(count)+"_monomerA.com"
#			monoB=names[n]+"_"+str(count)+"_monomerB.com"
			if not exist(monomerB):
				monomerB=monomerA
			dimer= names[n]+"_"+str(count)+".log"
			eDFT.append(en_int(monomerA,monomerB,dimer))
			molec.append(names[n])
#
	print("Dispersionless energies")
#	print "Dispersionless energies"
	print("{0:7}     {1:14}  {2:14}   {3:14}   {4:14}".format('Molecule','R[a.u.]','E_DFT[K]','E_Ref[K]','Err'))
#	print "R[a.u.], E_DFT[K], E_Ref[K], Err"
	err=0
	error=0
	fe=open('energy.dat','a')
	fe.write("{0:10}  {1:14}  {2:14}   {3:14}   {4:14}   {5:14}\n".format('Molecule','R[a.u.]','E_DFT[Kcal/mol]','E_Ref[Kcal/mol]','Abs_Err[Kcal/mol]','SQ_Rel_Err'))
	for i in range(len(ERef)):
#		print(eDFT[i])
		e_ref=ERef[i]
		e_dft=round(eDFT[i],8)
		R=RRef[i]
		if (e_ref!=0):
#
#			err+=((e_dft-e_ref)/min(abs(e_ref),abs(e_dft)))**2
			err+=((e_dft-e_ref)/e_ref)**2
			error+=((e_dft-e_ref)/e_ref)**2
		if (e_ref!=0):
#			print( molec[i],R,e_dft,e_ref,((e_dft-e_ref)/min(abs(e_ref),abs(e_dft)))**2)
#			print( molec[i],R,e_dft,e_ref,((e_dft-e_ref)/e_ref)**2)
			print("{0:7} {1:14} {2:14} {3:14} {4:14}".format(molec[i],round(R,5),e_dft,e_ref,round(((e_dft-e_ref)/e_ref)**2,8)))
			fe.write("{0:7} {1:14} {2:14} {3:18} {4:18} {5:18}\n".format(molec[i],round(R,5),e_dft,e_ref,round(abs(e_dft-e_ref),6),round(((e_dft-e_ref)/e_ref)**2,8)))
		else:
			print( molec[i],R,e_dft,e_ref)
#	fe.write("*****************************NEW Iteration*****************************" + '\n')
#	fe.close()
#
# add the errors from the dipole moments
#
	print("Dipole Moments")
	print("Dipole_DFT, Dipole_Ref, Err")
	fe.write("{0:10}   {1:14} {2:14} {3:14}\n".format('Molecule','Dipole_DFT', 'Dipole_Ref', 'Err'))
#
	weightDip=100.
#
# from H2OA_3

# S in the text with the whole file in it
#
	Conv1=0
	f=open("H2OA_3.log","r")
	s=f.read()
	f.close()
	f=open("H2OA_3.log","r")
	for line in f:
		if line[:20]==" Convergence failure":
			Conv1=1
#		if line[:10]==" SCF Done:":
#			Conv1=2
	f.close()
	if Conv1==1:
		err+=10
#       Don't understand this part of the code -- Connor vvvvvvv
#	if Conv1==2:
	else:
	#  Find X from log file from Gaussian
		ind=s.find("    X=")
		dip_dft=float(s[ind+19:ind+26])
		# Find difference in measured dipole and dipole reference value
		err+=((dip_dft-DipRef[0])/DipRef[0])**2*weightDip
		error+=((dip_dft-DipRef[0])/DipRef[0])**2
		print( "H2O_X",dip_dft,DipRef[0],((dip_dft-DipRef[0])/DipRef[0])**2*weightDip)
		fe.write("{0:7} {1:14} {2:14} {3:14}\n".format('H2O_X',dip_dft,DipRef[0],round(((dip_dft-DipRef[0])/DipRef[0])**2*weightDip,8)))
#
		ind=s.find("Z=")
		dip_dft=float(s[ind+13:ind+22])
		err+=((dip_dft-DipRef[1])/DipRef[1])**2*weightDip
		error+=((dip_dft-DipRef[1])/DipRef[1])**2
		print( "H2O_Z",dip_dft,DipRef[1],((dip_dft-DipRef[1])/DipRef[1])**2*weightDip)
		fe.write("{0:7} {1:14} {2:14} {3:14}\n".format('H2O_Z',dip_dft,DipRef[1],round(((dip_dft-DipRef[1])/DipRef[1])**2*weightDip,8)))
#
#	else:
#		print ("No convergence in H2OA_3.log")
#		err+=100000
#
	Conv1=0
	f=open("NH3A_3.log","r")
	s=f.read()
	f.close()
#
	f=open("NH3A_3.log","r")
	for line in f:
		if line[:20]==" Convergence failure":
			Conv1=1
#		if line[:10]==" SCF Done:":
#			Conv1=1
#
	f.close()
	if Conv1==1:
		err+=10
	else:
		ind=s.find("Y=")
		dip_dft=float(s[ind+13:ind+24])
		err+=((dip_dft-DipRef[2])/DipRef[2])**2*weightDip
		error+=((dip_dft-DipRef[2])/DipRef[2])**2
		print( "NH3_Y",dip_dft,DipRef[2],((dip_dft-DipRef[2])/DipRef[2])**2*weightDip)
		fe.write("{0:7} {1:14} {2:14} {3:14}\n".format('NH3_Y',dip_dft,DipRef[2],round(((dip_dft-DipRef[2])/DipRef[2])**2*weightDip,8)))
#
		ind=s.find("Z=")
		dip_dft=float(s[ind+13:ind+22])
		err+=((dip_dft-DipRef[3])/DipRef[3])**2*weightDip
		error+=((dip_dft-DipRef[3])/DipRef[3])**2
		print( "NH3_Z",dip_dft,DipRef[3],((dip_dft-DipRef[3])/DipRef[3])**2*weightDip)
		fe.write("{0:7} {1:14} {2:14} {3:14}\n".format('NH3_Z',dip_dft,DipRef[3],round(((dip_dft-DipRef[3])/DipRef[3])**2*weightDip,8)))
#	else:
#		print ("No convergence in H2OA_3.log")
#		err+=100000
#	fe.write("*****************************New Loop*****************************" + '\n')
#	fe.close()
	error=math.sqrt(error/33)*(100)
	err=math.sqrt(err/33)*(100)
	fe.write("{0:10} {1:10} {2:10} {3:10}\n".format("Error_Weight%=",err,"Error_NO_Weight%=",error))
	fe.write("*****************************New Loop*****************************" + '\n')
	fe.close()
#	get_err=err
#	time.sleep(30)
	print(error)
	print(param,'Percent Error:',err)
	f=open('param.dat','a')
#	f.write(str(error) + '\n')
	f.write("{0:14} {1:14} {2:14} {3:14} {4:14} {5:14} {6:14}\n".format(str(param[0]),str(param[1]),str(param[2]),str(param[3]),str(param[4]),\
	str(param[5]),str(param[6]),str(param[7]),str(param[8]),str(param[9]),str(param[10]),'% Error_weight:',round(err,8),'% Error:',round(error,8)))
	f.close()
#	for i in param:
#		print(i)
#
	if err < 11:
		sys.exit(0)
	return err
####################################################
def prep_data():
#
# conversion factor from Hartree to K
#       conv_fac=3.157733E5
	conv_fac=1
	print( "R[a.u.]  Eint[Kcal/mol]")
#
# All R in [A], energies in [Hartree] from SAPT(DFT)_dispersionless
#
# H2O
	R_All=[2.5, 3.1, 4.0]
	ERef_All=[5.297988310, -3.023071530, -1.766518960]
	if len(pH2O)>0:
		print("H2O")
	for i in pH2O:
		RH2O.append(R_All[i-1])
		RRef.append(R_All[i-1])
		ERefH2O.append(ERef_All[i-1])
		ERef.append(ERef_All[i-1])
		print(R_All[i-1]/0.529177208,ERef_All[i-1]*conv_fac)
#
# for aDZ basis set
#
# H2ODZ
#
#	R_All=[2.5, 3.1, 4.0]
#	ERef_All=[5.457619510, -3.035855110, -1.776455210]
	R_All=[3.1, 4.0]
	ERef_All=[-3.035855110, -1.776455210]
	if len(pH2ODZ)>0:
		print("H2ODZ")
	for i in pH2ODZ:
		RH2ODZ.append(R_All[i-1])
		RRef.append(R_All[i-1])
		ERefH2ODZ.append(ERef_All[i-1])
		ERef.append(ERef_All[i-1])
		print(R_All[i-1]/0.529177208,ERef_All[i-1]*conv_fac)
#
#
# Reference dipole moments in [Debye] from CCSD(T) aDZ
#
# for H2OA_3
	DipRef.append(-1.61256588)
	DipRef.append(0.89657227)
#
# for NH3A_3
	DipRef.append(1.41009079)
	DipRef.append(-0.57028608)
#
	return
#########################################
#     BEGINNING OF THE MAIN PART	#
#########################################
#
# input the initial parameters
#
# set prefix for job names
prefix="S"
#
# the parameters come from the Genetic Algorithm Opt
# he 9th parameter corresponds to xhf!
#restart("mn_opt_chimera.py")
#param=[-7.83343246615, 15.26130438, 1.38517538]
#param=[-7.84391049533, 15.26130438, 1.36517538]
#param=[-7.83343247, 15.26130438, 3.38517538]
#param=[-7.31481632, 15.57423523, 5.35533886]    #76%
#param=[-1.16011578, 19.0666469, 2.20063832]
#param=[1.851851, 17.33, 0.163]
param=[1.18328602E-03, 4.8827323, -0.163757125, -0.188002773, -0.449060892, -0.00823585719, 5.9515308, \
	-11.1602877, 0.614413, -2.59608972, 2.22337926]
#param=[1.38303837e-03, 4.09322728e+00, -3.32922779e-01, -2.44905609e-01, -3.91247752e-01, -4.95542667e-02, \
#	4.56238314e+00, -1.08236169e+01, 5.72471781e-01, -2.96133418e+00, 2.04022220e+00]
#param=[1.18328602E-03, 3.8827323E+00, -1.63757125E-01, -1.88002773E-01, -3.49060892E-01, -7.23585719E-03, \
#	3.95153080E+00, -1.01602877E+01, 0.56, -2.59608972E+00, 2.22337926E+00]
#param=[ 0.00891661528259, 3.93680079715, -0.10684221087, -0.35860210887, -0.524278554611, -0.56236347868, \
#	5.52213013587, -9.58968836413, 0.775493832148, -3.06668905587, 1.75277992413]
#param=[ 0.05281973, 0.54037798, -0.69588941, -0.19629029, -2.62045642, -4.95992745, \
#	-1.91062223, 1.21189836, 0.12786006, 4.23421, -8.24132]
#param=[ 1.81917515, 0.0864756, -3.6452664000000001, -1.65665967,  \
#	0.095848550000000005, -2.66675168, -0.35652831000000001, -2.82758398, 5.5, -10.2]
#
# reference points pxxx=[] means exluding xxx form the optimization set
#
pC2H4=[1,2,3]
pC2H2ClF=[1,2,3]
pNH3_ClF=[1,2,3]
pC2H4_Ar=[1,2]
pH2O=[1,2,3]
pCH4=[1,2,3]
pNH3=[1,2,3]
pArHF=[1,2,3]
pN2_HF=[1,2,3]
# for aDZ basis set
pH2ODZ=[1,2]
#pHe=[]
#pHe=[2,6,10]
#pAr=[8,12,17]
#pAr=[]
#pH2O=[]
#pH2O=[2,4,6]
#pH2O=[]
#pCH4=[]
#pCH4=[1,4,6]
#pCH4=[]
#pC2H4=[]
#pC2H4=[2,4,7]
#pC2H4=[]
#pC2H4_F2=[3,5,7]
#pC2H4_F2=[]
#pNH3=[]
#pNH3=[2,3,6]
#pArHF=[]
#pArHF=[2,3,5]
#pN2_HF=[]
#pN2_HF=[2,4,7]
# for aDZ basis set
#pH2ODZ=[2,4,6]
names=["C2H4","C2H2ClF","NH3_ClF","C2H4_Ar","H2O","CH4","NH3","ArHF","N2_HF","H2ODZ"]
no_pts=[len(pC2H4),len(pC2H2ClF),len(pNH3_ClF),len(pC2H4_Ar),len(pH2O),len(pCH4),len(pNH3), \
	len(pArHF),len(pN2_HF),len(pH2ODZ)]
#########################################
#
n=11
ERef=[]
RRef=[]
RC2H4=[]
ERefC2H4=[]
RC2H2ClF=[]
ERefC2H2ClF=[]
RNH3_ClF=[]
ERefNH3_ClF=[]
RC2H4_Ar=[]
ERefC2H4_Ar=[]
RH2O=[]
ERefH2O=[]
RCH4=[]
ERefCH4=[]
RNH3=[]
ERefNH3=[]
RArHF=[]
ERefArHF=[]
RN2_HF=[]
ERefN2_HF=[]
RH2ODZ=[]
ERefH2ODZ=[]
#
DipRef=[]
#
prep_data()
prep_inputs()
#
os.system("rm *.chk")
#
# optimize the parametres
#
x=praxis.praxis(0.00001,0.00001,11,4,param,get_err)
#time.sleep(30)
print(x)
param=x
#f=open('res1.data','w')
#f.write(str(x[0]))
#f.close()
#sys.exit()
#
# print the interaction energies for all distances
#
os.system("rm *.chk")
#pHe=range(1,15)
#pAr=range(1,24)
pC2H4=range(1,4)
pC2H2ClF=range(1,4)
pNH3_ClF=range(1,4)
pC2H4_Ar=range(1,3)
pH2O=range(1,4)
pCH4=range(1,4)
pNH3=range(1,4)
pArHF=range(1,4)
pN2_HF=range(1,4)
# for aDZ basis set
pH2ODZ=range(1,3)
#
#pC2H4=[]
#pC2H2ClF=[]
#pNH3_ClF=[]
#pC2H4_Ar=[]
#pH2O=[]
#pCH4=[]
#pNH3=[]
#pArHF=[]
#pN2_HF=[]
# for aDZ basis set
#pH2ODZ=[]
#
names=["C2H4","C2H2ClF","NH3_ClF","C2H4_Ar","H2O","CH4","NH3","ArHF","N2_HF","H2ODZ"]
no_pts=[len(pC2H4),len(pC2H2ClF),len(pNH3_ClF),len(pC2H4_Ar),len(pH2O),len(pCH4),len(pNH3), \
	len(pArHF),len(pN2_HF),len(pH2ODZ)]
#
ERef=[]
RRef=[]
RC2H4=[]
ERefC2H4=[]
RC2H2ClF=[]
ERefC2H2ClF=[]
RNH3_ClF=[]
ERefNH3_ClF=[]
RC2H4_Ar=[]
ERefC2H4_Ar=[]
RH2O=[]
ERefH2O=[]
RCH4=[]
ERefCH4=[]
RNH3=[]
ERefNH3=[]
RArHF=[]
ERefArHF=[]
RN2_HF=[]
ERefN2_HF=[]
RH2ODZ=[]
ERefH2ODZ=[]
#
DipRef=[]
#
prep_data()
prep_inputs()
#
print( "FINAL RESULTS")
err=get_err(param,n)
#
#sys.exit()


# 기본값 매개변수(Default Argument Variable)

# 기본값 매개변수 cnt = 1로 정의
def str(text, cnt = 1):
    for i in range(cnt):
        print(text)

# 함수 호출
# 함수를 호출할때 2번째 매개변수를 생략하면, 기본값 매개변수 cnt=1이 사용됨
str('안녕 하세요?')
str('안녕히 가세요?', 3)

#만약 뒤에 숫자가 할당되지 않으면 사전에 설정한 기본값 cnt=1이 자동으로 적용됨. 즉 한번만 루프가 돌려짐
#기본값이 있더라도 함수를 호출할 때 두번 째 값 즉 위에 예시로는 3이 할당됐으니 우선으로 적용되서 cnt가 3으로 지정