コード例 #1
0
def train(dataFile):
    ##    e = 15 # nb of example
    ##
    ##    n = 3 # nb of data analyze (weight, length, power)
    ##
    ##    n += 1 # pour le threshold
    ##
    ##    theta = [ 0 for i in range(n)]

    alpha = 0.000005

    ##    x = [[ random.random() for i in range(n)] for j in range(e)]
    ##    for i in range(len(x)):
    ##        x[i][0] = 1 # Threshold, only theta is taken into account
    ##    print x[0]
    ##    y = [ random.random() for j in range(e)]

    print "Debug : reading file"
    e, n, x, y = readData(dataFile)
    theta = [0 for i in range(n)]
    print theta
    print "Debug : reading done"

    # print "Debug"
    # print x
    # print y
    # print "Debug end"

    print "Debug : training..."
    # training theta
    for time in range(50):  #redo the train x times
        for i in range(e):  #each example
            for j in range(n):  #each data type

                # update the corresponding theta
                sumDerivated = 0

                for t in range(e):
                    sumDerivated += (MathHelper.arrayProduct(theta, x[t]) -
                                     y[t]) * x[t][j]

                theta[j] -= alpha * (float(1) / e) * sumDerivated

            # print theta
        print theta
    print "Debug : training done!"

    print "Debug : testing..."
    # print MathHelper.arrayProduct(theta, [1,49.94357,21.47114,73.07750,8.74861,-17.40628,-13.09905,-25.01202,-12.23257,7.83089,-2.46783,3.32136,-2.31521,10.20556,611.10913,951.08960,698.11428,408.98485,383.70912,326.51512,238.11327,251.42414,187.17351,100.42652,179.19498,-8.41558,-317.87038,95.86266,48.10259,-95.66303,-18.06215,1.96984,34.42438,11.72670,1.36790,7.79444,-0.36994,-133.67852,-83.26165,-37.29765,73.04667,-37.36684,-3.13853,-24.21531,-13.23066,15.93809,-18.60478,82.15479,240.57980,-10.29407,31.58431,-25.38187,-3.90772,13.29258,41.55060,-7.26272,-21.00863,105.50848,64.29856,26.08481,-44.59110,-8.30657,7.93706,-10.73660,-95.44766,-82.03307,-35.59194,4.69525,70.95626,28.09139,6.02015,-37.13767,-41.12450,-8.40816,7.19877,-8.60176,-5.90857,-12.32437,14.68734,-54.32125,40.14786,13.01620,-54.40548,58.99367,15.37344,1.11144,-23.08793,68.40795,-1.82223,-27.46348,2.26327])
    print MathHelper.arrayProduct(theta, [1, 626, 626])
    print "Debug : many wow!"

    #raw_input('Press Start \r\n')
    sys.exit("Bye !!")
コード例 #2
0
 def lerp(color1, color2, amount):
     if color1.a is not 0 and color2.a is not 0:
         return Color(MathHelper.lerp(color1.r, color2.r, amount), MathHelper.lerp(color1.g, color2.g, amount),
                      MathHelper.lerp(color1.b, color2.b, amount), MathHelper.lerp(color1.a, color2.a, amount))
     else:
         return Color(MathHelper.lerp(color1.r, color2.r, amount), MathHelper.lerp(color1.g, color2.g, amount),
                      MathHelper.lerp(color1.b, color2.b, amount))
コード例 #3
0
    def train(self, dataFile):
        # self.e,self.n,self.x,self.y = self.readData()
        self.e,self.n,self.x,self.y = self.readDataThread(25)
        
        self.theta = [ 0 for i in range(n)]
        print self.theta

        print "Debug : training..."
        
        # training theta
        for time in range(50): #redo the train x times
            for i in range(self.e): #each example
                for j in range(self.n): #each data type

                    # update the corresponding theta
                    sumDerivated = 0

                    for t in range(self.e):
                        sumDerivated += (MathHelper.arrayProduct(self.theta, self.x[t]) - self.y[t]) * self.x[t][j]
                
                    self.theta[j] -= self.alpha * ( float(1) / self.e ) * sumDerivated

            print self.theta
            
        print "Debug : training done!"


        print "Debug : testing..."
        
        # print MathHelper.arrayProduct(theta, [1,49.94357,21.47114,73.07750,8.74861,-17.40628,-13.09905,-25.01202,-12.23257,7.83089,-2.46783,3.32136,-2.31521,10.20556,611.10913,951.08960,698.11428,408.98485,383.70912,326.51512,238.11327,251.42414,187.17351,100.42652,179.19498,-8.41558,-317.87038,95.86266,48.10259,-95.66303,-18.06215,1.96984,34.42438,11.72670,1.36790,7.79444,-0.36994,-133.67852,-83.26165,-37.29765,73.04667,-37.36684,-3.13853,-24.21531,-13.23066,15.93809,-18.60478,82.15479,240.57980,-10.29407,31.58431,-25.38187,-3.90772,13.29258,41.55060,-7.26272,-21.00863,105.50848,64.29856,26.08481,-44.59110,-8.30657,7.93706,-10.73660,-95.44766,-82.03307,-35.59194,4.69525,70.95626,28.09139,6.02015,-37.13767,-41.12450,-8.40816,7.19877,-8.60176,-5.90857,-12.32437,14.68734,-54.32125,40.14786,13.01620,-54.40548,58.99367,15.37344,1.11144,-23.08793,68.40795,-1.82223,-27.46348,2.26327])
        print MathHelper.arrayProduct(theta, [1, 626,626])
        
        print "Debug : many wow!"

        #raw_input('Press Start \r\n')
        sys.exit("Bye !!")
コード例 #4
0
    def run(self):
        # global theta, x, y, n, e, alpha
    
        # print "Starting " + self.name
        
        # update the corresponding theta
        sumDerivated = 0

        for j in range(self.min,self.max+1):
            for t in range(e):
                # print "%s => %d/%d" % (self.name,len(theta), len(x[t]))
                sumDerivated += (MathHelper.arrayProduct(theta, x[t]) - y[t]) * x[t][j]
                
            ThetaThreadClass.Lock.acquire(True)
            theta[j] -= alpha * ( float(1) / e ) * sumDerivated
            ThetaThreadClass.Lock.release()
コード例 #5
0
ファイル: validators.py プロジェクト: asmodat/Cosmos-RichList
print("Average: " + str(earningsSum / cnt) + "ATOM")
print("Median: " + str(statistics.median(arr)) + "ATOM")

print("----- ----- ----- ----- -----")
print("|    GINI COEFFICIENT       |")
print("----- ----- ----- ----- -----")

giniList = []
for r in range(1000):
    newArr = []
    for i in arr:
        if i < r:
            newArr.append(i + r)
        else:
            newArr.append(i)
    giniList.append(MathHelper.gini(newArr))

print(",".join(map(str, giniList)))

print("----- ----- ----- ----- -----")
print("|  DELEGATIONS DISTRIBUTION  |")
print("----- ----- ----- ----- -----")

delegationsCnt34 = []
delegationsCnt67 = []
delegationsCnt99 = []

for delegatorAddr in uniqueDelegators:
    sum = 0.0
    delegations = delegationsList[delegatorAddr]
    cnt = len(delegations)
コード例 #6
0
ファイル: Train.py プロジェクト: MehdiTheMedoc/IA_TripleM
def train(useThread=True):
    global x, y, theta, alpha, n, e, trainTime

    start = time.time()

    theta = [0 for i in range(n)]

    print "Debug : training..."

    # training theta
    for train in range(trainTime):  #redo the train trainTime times
        if (train % 200) == 0:
            print "train number %d/%d" % (train, trainTime)
            print theta
        for i in range(
                e
        ):  #each example => to put in some thread, each thread do some example
            #print theta
            if useThread:
                print "not implemented !!"
            else:
                for j in range(
                        n
                ):  #each data type => to put in n thread, each thread do one theta
                    print MathHelper.arrayProduct(theta, [
                        1, 49.94357, 21.47114, 73.07750, 8.74861, -17.40628,
                        -13.09905, -25.01202, -12.23257, 7.83089, -2.46783,
                        3.32136, -2.31521, 10.20556, 611.10913, 951.08960,
                        698.11428, 408.98485, 383.70912, 326.51512, 238.11327,
                        251.42414, 187.17351, 100.42652, 179.19498, -8.41558,
                        -317.87038, 95.86266, 48.10259, -95.66303, -18.06215,
                        1.96984, 34.42438, 11.72670, 1.36790, 7.79444,
                        -0.36994, -133.67852, -83.26165, -37.29765, 73.04667,
                        -37.36684, -3.13853, -24.21531, -13.23066, 15.93809,
                        -18.60478, 82.15479, 240.57980, -10.29407, 31.58431,
                        -25.38187, -3.90772, 13.29258, 41.55060, -7.26272,
                        -21.00863, 105.50848, 64.29856, 26.08481, -44.59110,
                        -8.30657, 7.93706, -10.73660, -95.44766, -82.03307,
                        -35.59194, 4.69525, 70.95626, 28.09139, 6.02015,
                        -37.13767, -41.12450, -8.40816, 7.19877, -8.60176,
                        -5.90857, -12.32437, 14.68734, -54.32125, 40.14786,
                        13.01620, -54.40548, 58.99367, 15.37344, 1.11144,
                        -23.08793, 68.40795, -1.82223, -27.46348, 2.26327
                    ])
                    # update the corresponding theta
                    sumDerivated = 0

                    for t in range(e):
                        sumDerivated += (MathHelper.arrayProduct(theta, x[t]) -
                                         y[t]) * x[t][j]

#sumDerivated += (MathHelper.arrayProductNP(theta, x[t]) - y[t]) * x[t][j]

                    theta[j] -= alpha * (float(1) / e) * sumDerivated
                    # if (j % 10 ) == 0:
                    # print "%s/%s" % (j,n)
            # print theta
            # print MathHelper.arrayProduct(theta, [1,49.94357,21.47114,73.07750,8.74861,-17.40628,-13.09905,-25.01202,-12.23257,7.83089,-2.46783,3.32136,-2.31521,10.20556,611.10913,951.08960,698.11428,408.98485,383.70912,326.51512,238.11327,251.42414,187.17351,100.42652,179.19498,-8.41558,-317.87038,95.86266,48.10259,-95.66303,-18.06215,1.96984,34.42438,11.72670,1.36790,7.79444,-0.36994,-133.67852,-83.26165,-37.29765,73.04667,-37.36684,-3.13853,-24.21531,-13.23066,15.93809,-18.60478,82.15479,240.57980,-10.29407,31.58431,-25.38187,-3.90772,13.29258,41.55060,-7.26272,-21.00863,105.50848,64.29856,26.08481,-44.59110,-8.30657,7.93706,-10.73660,-95.44766,-82.03307,-35.59194,4.69525,70.95626,28.09139,6.02015,-37.13767,-41.12450,-8.40816,7.19877,-8.60176,-5.90857,-12.32437,14.68734,-54.32125,40.14786,13.01620,-54.40548,58.99367,15.37344,1.11144,-23.08793,68.40795,-1.82223,-27.46348,2.26327])

    end = time.time()

    print "Debug : training done, Using Threads : %r in %ds" % (useThread,
                                                                end - start)

    print "=========================================="

    print "Debug : testing..."

    if n > 5:
        print "Congratz, you waited so long, you should be dead long ago :3 (2001 by the way ^^)"
        print MathHelper.arrayProduct(theta, [
            1, 49.94357, 21.47114, 73.07750, 8.74861, -17.40628, -13.09905,
            -25.01202, -12.23257, 7.83089, -2.46783, 3.32136, -2.31521,
            10.20556, 611.10913, 951.08960, 698.11428, 408.98485, 383.70912,
            326.51512, 238.11327, 251.42414, 187.17351, 100.42652, 179.19498,
            -8.41558, -317.87038, 95.86266, 48.10259, -95.66303, -18.06215,
            1.96984, 34.42438, 11.72670, 1.36790, 7.79444, -0.36994,
            -133.67852, -83.26165, -37.29765, 73.04667, -37.36684, -3.13853,
            -24.21531, -13.23066, 15.93809, -18.60478, 82.15479, 240.57980,
            -10.29407, 31.58431, -25.38187, -3.90772, 13.29258, 41.55060,
            -7.26272, -21.00863, 105.50848, 64.29856, 26.08481, -44.59110,
            -8.30657, 7.93706, -10.73660, -95.44766, -82.03307, -35.59194,
            4.69525, 70.95626, 28.09139, 6.02015, -37.13767, -41.12450,
            -8.40816, 7.19877, -8.60176, -5.90857, -12.32437, 14.68734,
            -54.32125, 40.14786, 13.01620, -54.40548, 58.99367, 15.37344,
            1.11144, -23.08793, 68.40795, -1.82223, -27.46348, 2.26327
        ])
    else:
        print "testing for 626, should be 1565"
        print MathHelper.arrayProduct(theta, [1, 626, 626])

    print "Debug : many wow!"
コード例 #7
0
    def test_two_intersections(self):
        sq = np.array([[1, 1], [1, -1], [-1, -1], [-1, 1]], dtype=np.float)
        line = np.array([[0.5, 2], [-0.5, -2]], dtype=np.float)
        dist = m.find_distance_to_polygon(sq, line)

        self.assertAlmostEqual(dist, np.linalg.norm(np.array([0.25, 1]), 2))
コード例 #8
0
    def test_orthogonal_edge(self):
        sq = np.array([[1, 1], [1, -1], [-1, -1], [-1, 1]], dtype=np.float)
        line = np.array([[-3, -3], [0.5, 0.5]], dtype=np.float)
        dist = m.find_distance_to_polygon(sq, line)

        self.assertAlmostEqual(dist, math.sqrt(8), 3)
コード例 #9
0
    def test_orthogonal_no_hit(self):
        sq = np.array([[1, 1], [1, -1], [-1, -1], [-1, 1]], dtype=np.float)
        line = np.array([[3, 0], [2, 0]], dtype=np.float)
        dist = m.find_distance_to_polygon(sq, line)

        self.assertIsNone(dist)
コード例 #10
0
    def test_orthogonal_hit(self):
        sq = np.array([[1, 1], [1, -1], [-1, -1], [-1, 1]], dtype=np.float)
        line = np.array([[3, 0], [0, 0]], dtype=np.float)
        dist = m.find_distance_to_polygon(sq, line)

        self.assertAlmostEqual(dist, 2, 3)
コード例 #11
0
#일종의 Lib 추가와 같이 Python의 기능을 묶은 단위의 Module을 Import(C의 include)하여 사용
#1) PyCharm기준 File/Settings(Alt + F7)/Project/ProjectInterpeter/Option Button/More/
#   Show path for the selected interpreter/Path Add
#
#2) sys.path.append(경로)
#
#3) PYTHONEPATH 환경변수 내 경로 입력

import MathHelper  #import ModuleName                 : Module을 포함하고 내부 기능 사용
from MathHelper import safe_mul  #from ModuleName import ModuleFunc : Module내 지정 기능을 ModuleName.Function 대신 바로 Fuction을 쓰기 위해 포함시킨다
#from MathHelper import *            #Module 내 모든 기능을 from ~ import 와 같이 사용하게 된다

print(MathHelper.sum(1, 2, 3, 4))
print(safe_mul(5, 3))

cm = MathHelper.CircleMath()
print(cm.PI)
コード例 #12
0
ファイル: BuiltIns.py プロジェクト: YuvalLot/pyLocal
def builtin(interpreter, query_name, query_pat, depth, found):
    """
    Builtin predicates (many different libraries).

    :param interpreter: Interpreter
    :param query_name: str
    :param query_pat: str
    :param depth: Counter
    :param found: "pointer" bool
    :return: Generator
    """

    found[0] = True

    # checks for terminal match
    if query_name == "GuaranteeUnify":
        comps = splitWithoutParen(query_pat)
        if len(comps) != 2:
            return
        comp1, comp2 = comps
        m = MatchDictionary.match(interpreter, comp1, comp2)
        if m and not m[2]:
            yield {}
        return

    # Can be unified
    if query_name == "CanUnify":
        comps = splitWithoutParen(query_pat)
        if len(comps) != 2:
            return
        comp1, comp2 = comps
        m = MatchDictionary.match(interpreter, comp1, comp2)
        if m:
            yield {}
        return

    # Exact copy of a pattern
    if query_name == "ExactCopy":
        comps = splitWithoutParen(query_pat)
        if len(comps) != 2:
            return
        comp1, comp2 = comps
        bs = get_all_basics(comp1)
        copy = MatchDictionary.transform(comp1, bs, {})
        m = MatchDictionary.match(interpreter, comp2, copy)
        if m:
            print(m[1])
            yield m[1]
        return

    # Online Request
    if query_name == "Request":
        parts = splitWithoutParen(query_pat)
        if len(parts) != 2:
            return
        try:
            inLcl = url_opener(parts[0][1:-1])
            if inLcl is None:
                return
            m = MatchDictionary.match(interpreter, parts[1], inLcl)
            if m:
                yield m[1]
        except Exception as e:
            print(e)
        finally:
            return

    # Ref.new - Create reference
    if query_name == "Ref.new":
        comps = splitWithoutParen(query_pat)
        if len(comps) != 1:
            return
        comp1, = comps
        if match_type(comp1) != "var":
            return
        rand = hex(randint(10000, 10000000))
        while rand in interpreter.references:
            rand = hex(randint(100, 100000))
        interpreter.references[rand] = "nil"
        yield {comp1: rand}
        return

    # Ref.del - delete a reference
    if query_name == "Ref.del":
        comps = splitWithoutParen(query_pat)
        if len(comps) != 1:
            return
        comp1, = comps
        if comp1 not in interpreter.references:
            return
        del interpreter.references[comp1]
        yield {}
        return

    if query_name == "SecIns":
        print(">> ", end="")
        inspect = input()
        try:
            print(eval(inspect))
            yield {}
        except Exception as e:
            print(e)
        return

    # Break predicate
    if query_name == 'hBreak' and (interpreter.list_added
                                   or interpreter.types_added):
        parts = splitWithoutParen(query_pat)
        if len(parts) != 2 or "[" in parts[0] or "?" in parts[0]:
            return
        broken = list(parts[0])
        if len(broken) == 0:
            return
        inLcl = '['
        for broke in broken:
            inLcl += broke + ","
        inLcl = inLcl[:-1] + "]"
        m = MatchDictionary.match(interpreter, parts[1], inLcl)
        if m:
            yield m[1]
        return

    # domain generator
    if query_name == "Domain-Generator":
        parts = splitWithoutParen(query_pat)
        if len(parts) != 4 or any(
                match_type(part) != "list" for part in parts):
            return
        variables = splitWithoutParen(parts[0][1:-1])
        if any(match_type(pattern) != "var" for pattern in variables):
            return
        ranges = splitWithoutParen(parts[1][1:-1])
        if len(ranges) != len(variables):
            return
        constraints = splitWithoutParen(parts[2][1:-1])
        elims = splitWithoutParen(parts[3][1:-1])
        D = Domain(interpreter, "~~Anon")
        D.variables = variables
        D.raw_vars = parts[0][1:-1]
        for i, var in enumerate(variables):
            D.range_searches[var] = ranges[i]
        for const in constraints:
            D.insert_constraint(const, "", -1)
        for elim in elims:
            D.insert_elimination(elim, "", -1)
        yield from D.search(depth, parts[0][1:-1])

    # Input
    if query_name == "hInput" and interpreter.strings_added:
        parts = splitWithoutParen(query_pat)
        if len(parts) != 1:
            return
        if parts[0][0] != "?":
            return
        yield "Request"
        inp = interpreter.received_input
        interpreter.received_input = False
        yield {parts[0]: '"' + inp + '"'}

    # isList predicate (checks if list)
    if query_name == 'isList' and interpreter.types_added:
        parts = splitWithoutParen(query_pat)
        if len(parts) != 1:
            return
        if parts[0][0] == "[":
            yield {}
        return

    # isVar predicate (checks if variable)
    if query_name == 'isVar' and interpreter.types_added:
        parts = splitWithoutParen(query_pat)
        if len(parts) != 1:
            return
        if '?' == parts[0][0]:
            yield {}
        return

    # Title predicate (checks if title)
    if query_name == 'isTitle' and interpreter.types_added:
        parts = splitWithoutParen(query_pat)
        if len(parts) != 1:
            return
        try:
            T_name, _, T_pat = parts[0].partition("(")
            if T_name in interpreter.titles:
                yield {}
        except IndexError:
            pass
        except ValueError:
            pass
        return

    # Integer predicate (checks if integer)
    if query_name == 'isInteger' and interpreter.types_added:
        parts = splitWithoutParen(query_pat)
        if len(parts) != 1:
            return
        try:
            a = int(parts[0])
            yield {}
        except IndexError:
            pass
        except ValueError:
            pass
        return

    # Floating predicate (checks if float)
    if query_name == 'isFloating' and interpreter.types_added:
        parts = splitWithoutParen(query_pat)
        if len(parts) != 1:
            return
        try:
            a = float(parts[0])
            yield {}
        except IndexError:
            pass
        except ValueError:
            pass
        return

    # Known Predicate (checks if variables in predicate)
    if query_name == 'isKnown' and interpreter.types_added:
        parts = splitWithoutParen(query_pat)
        if len(parts) != 1:
            return
        if outString(parts[0], "?"):
            return
        yield {}

    # Predicate predicate (is it a predicate)
    if query_name == 'isPredicate' and interpreter.types_added:
        parts = splitWithoutParen(query_pat)
        if len(parts) != 1:
            return
        if parts[0] in interpreter.predicates or \
                (parts[0] in ['Add', 'Sub', 'Mul', 'Div', 'Mod', 'Floor', 'Ceil', 'Power', 'Log', 'Sin', 'Cos', 'Tan',
                              'LT'] and interpreter.math_added) \
                or parts[0] == 'Print' or parts[0] == 'Predicate' or (parts[0] == 'Break' and interpreter.list_added):
            yield {}
        return

    # isPackage predicate (is it a package)
    if query_name == 'isPackage' and interpreter.types_added:
        parts = splitWithoutParen(query_pat)
        if len(parts) != 1:
            return
        if parts[0] in interpreter.packages:
            yield {}
        return

    # Math Predicates
    if query_name in [
            'hAdd', 'hSub', 'hMul', 'hDiv', 'hMod', 'hFloor', 'hCeil',
            'hPower', 'hLog', 'hSin', 'hCos', 'hTan', 'hLT', 'hE'
    ] and interpreter.math_added:
        yield from MathHelper.Reader(query_name, query_pat)
        return

    # Print 'predicate'
    if query_name == 'Print':
        parts = splitWithoutParen(query_pat)
        printible = []
        for part in parts:
            printible.append(formatPrint(part))
        printed = joinPrint(printible)
        interpreter.message(printed)
        yield "Print"
        if len(query_pat) != 0 and query_pat[-1] == ",":
            interpreter.newline = True
        else:
            interpreter.newline = False
        yield {}

    # AllSolutions predicate
    if query_name == 'hAllSolutions' and interpreter.predicates_added:
        parts = splitWithoutParen(query_pat)
        if len(parts) != 3:
            return
        if parts[0][0] == "?":
            return
        try:
            n = int(parts[1])
        except ValueError:
            return
        sols = []
        pattern = ",".join([f"?x{j}" for j in range(n)])
        q = f"{parts[0]}({pattern})"
        for sol in interpreter.mixed_query(q, 0, depth.count, True):
            sols.append(smart_replace(f"[{pattern}]", sol))
        final = "[" + ",".join(sols) + "]"
        m = MatchDictionary.match(interpreter, parts[2], final)
        if m:
            yield m[1]
        return

    # Save predicate
    if query_name == 'hSave' and interpreter.save_added:
        parts = splitWithoutParen(query_pat)
        if len(parts) != 1:
            return
        if outString(parts[0], "?"):
            return
        to_save = parts[0]
        interpreter.saved.insert(0, to_save)
        yield {}
        return

    # helper Load predicate
    if query_name == 'hLoad' and interpreter.save_added:
        parts = splitWithoutParen(query_pat)
        if len(parts) == 1:
            if len(interpreter.saved) == 0:
                return
            else:
                to_load = interpreter.saved.popleft()
                t = MatchDictionary.match(interpreter, parts[0], to_load)
                if t:
                    yield t[1]
        return

    # Chars predicate
    if query_name == 'ToChars' and interpreter.strings_added:

        parts = splitWithoutParen(query_pat)
        if len(parts) != 2 or outString("[", parts[0]) or outString(
                parts[0], "?") or parts[0][0] != '"' or parts[0][-1] != '"':
            return
        broken = list(parts[0][1:-1])
        inLcl = '[' + ",".join(list(map(lambda c: f'"{c}"', broken))) + "]"
        m = MatchDictionary.match(interpreter, parts[1], inLcl)
        if m:
            yield m[1]
        return

    # Chars to String
    if query_name == 'ToString' and interpreter.strings_added:
        parts = splitWithoutParen(query_pat)
        if len(parts) != 2 or outString(
                parts[0], "?") or "[" != parts[0][0] or "]" != parts[0][-1]:
            return

        broken = splitWithoutParen(parts[0][1:-1])
        inLcl = '"'
        for broke in broken:
            if broke[0] != '"' or broke[-1] != '"':
                return
            inLcl += broke[1:-1]
        inLcl += '"'
        m = MatchDictionary.match(interpreter, parts[1], inLcl)
        if m:
            yield m[1]
        return

    # open file
    if query_name == 'hOpen' and interpreter.filestream_added:
        parts = splitWithoutParen(query_pat)
        if len(parts) != 3:
            return
        file_name, file_type, file_var = parts
        if match_type(file_var) != "var":
            return
        file_name = file_name[1:-1]
        print(file_name)
        if file_type not in ["r", "w", "a", "rp"]:
            if file_type == "rp":
                file_type = "r+"
            interpreter.raiseError(f"Error: Illegal file type '{file_type}'")
            return
        if ":" not in file_name:
            try:
                f = open(interpreter.filepath + "/" + file_name, file_type)
            except FileNotFoundError:
                interpreter.raiseError(f"Error: File not found, '{file_name}'")
                return
        else:
            try:
                f = open(file_name, file_type)
            except FileNotFoundError:
                interpreter.raiseError(f"Error: File not found, '{file_name}'")
                return
        file_hash = hashlib.md5(
            (random().as_integer_ratio()[0] +
             random().as_integer_ratio()[1]).__str__().encode()).hexdigest()
        interpreter.files[file_hash] = f
        yield {file_var: file_hash}
        return

    # read file
    if query_name == 'hRead' and interpreter.filestream_added:
        parts = splitWithoutParen(query_pat)
        if len(parts) != 2:
            return
        file_name, char_to = parts
        if match_type(char_to) != 'var':
            return False
        if file_name not in interpreter.files:
            interpreter.raiseError(f"Error: File '{file_name}' not opened.")
            return
        file_read = interpreter.files[file_name]
        try:
            c = file_read.read(1)
        except UnsupportedOperation:
            interpreter.raiseError(f"Error: File '{file_name}' not readable.")
            return

        yield {char_to: '"' + c + '"'}
        return

    # write in file
    if query_name == 'hWrite' and interpreter.filestream_added:
        parts = splitWithoutParen(query_pat)
        if len(parts) != 2:
            return
        file_name, write = parts
        if write[0] == '"':
            write = write[1:-1]
        if file_name not in interpreter.files:
            interpreter.raiseError(f"Error: File '{file_name}' not opened.")
            return

        try:
            interpreter.files[file_name].write(write)
        except UnsupportedOperation:
            interpreter.raiseError(f"Error: File '{file_name}' not writable.")
            return

        yield {}

    # close file
    if query_name == 'hClose' and interpreter.filestream_added:
        parts = splitWithoutParen(query_pat)
        if len(parts) != 1:
            return

        file_name = parts[0]
        if file_name in interpreter.files:
            interpreter.files[file_name].close()
            interpreter.files.pop(file_name)
            yield {}
            return
        else:
            interpreter.raiseError(f"Error: file '{file_name}' not found.")
            return

    # Tracing searching algorithm
    if query_name == "Trace" and interpreter.inspect_added:
        if query_pat == "On":
            interpreter.trace_on = True
        elif query_pat == "Off":
            interpreter.trace_on = False
        elif query_pat == "OnOn":
            interpreter.console_trace_on = True
        elif query_pat == "OffOff":
            interpreter.console_trace_on = False
        else:
            return
        yield {}
        return

    # Show Memory
    if query_name == "ShowMem" and interpreter.inspect_added:
        interpreter.message(
            f"{interpreter.memory}\n{interpreter.references}\n")
        yield "Print"
        yield {}
        return

    # Listing - list all cases of predicate
    if query_name == "Listing" and interpreter.inspect_added:
        p_name = query_pat

        if p_name == "ALL":
            for predicate in interpreter.predicates.values():
                interpreter.message(predicate.__str__())
            yield 'Print'
            yield {}
            return

        if p_name not in interpreter.predicates:
            return
        else:
            predicate_match = interpreter.predicates[p_name]
            interpreter.message(predicate_match.__str__())
            yield "Print"
            yield {}
            return

        return

    if interpreter.dynamic_added and query_name in {"AssertF", "AssertFE", "AssertN", "AssertNE", "AssertC", "AssertCE", "DeleteF",
                                                    "DeleteN", "DeleteC", "Create", "SwitchRecursive", "SwitchRandom", 'Clear', 'Delete'} \
            :

        parts = splitWithoutParen(query_pat)
        if len(parts) != 1:
            return

        if query_name == "Create":
            if re.fullmatch(r'[a-zA-Z_0-9\-\.]+',
                            query_pat) and query_pat not in Lexer.reserved:
                new_pred = Predicate(interpreter, query_pat, False, False)
                interpreter.predicates[new_pred.name] = new_pred
                yield {}
            return
        if query_name == "SwitchRecursive":
            if query_pat in interpreter.predicates:
                pred = interpreter.predicates[query_pat]
                pred.recursive = not pred.recursive
                yield {}
            return
        if query_name == "SwitchRandom":
            if query_pat in interpreter.predicates:
                pred = interpreter.predicates[query_pat]
                pred.random = not pred.random
                yield {}
            return
        if query_name == 'Delete':
            if query_pat in interpreter.predicates:
                del interpreter.predicates[query_pat]
                yield {}
            return

        predicate_changed, _, body = query_pat.partition("(")
        body = "(" + body
        body = remove_whitespace(body)

        if predicate_changed not in interpreter.predicates:
            return

        predicate_changed = interpreter.predicates[predicate_changed]

        if query_name == "AssertFE":
            basic = processParen(body)
            if basic:
                predicate_changed.addBasic(basic)
                yield {}
                return
            else:
                return
        if query_name == "AssertF":
            basic = processParen(body)
            if basic:
                predicate_changed.addBasic(basic, insert=True)
                yield {}
                return
            else:
                return

        if query_name == "AssertNE":
            basic = processParen(body)
            if basic:
                predicate_changed.addNot(basic)
                yield {}
                return
            else:
                return
        if query_name == "AssertN":
            basic = processParen(body)
            if basic:
                predicate_changed.addNot(basic, insert=True)
                yield {}
                return
            else:
                return

        if query_name == "AssertCE":
            to_match, _, then = body.partition(">")
            to_match, then = processParen(to_match), processParen(then)
            if not to_match or not then:
                return
            predicate_changed.addCase(to_match, then)
            yield {}
            return
        if query_name == "AssertC":
            to_match, _, then = body.partition(">")
            to_match, then = processParen(to_match), processParen(then)
            if not to_match or not then:
                return
            predicate_changed.addCase(to_match, then, insert=True)
            yield {}
            return

        if query_name == "DeleteF":
            body = processParen(body)
            if body in predicate_changed.basic:
                predicate_changed.basic.remove(body)
                yield {}
                return
            else:
                return
        if query_name == "DeleteN":
            body = processParen(body)
            if body in predicate_changed.nope:
                predicate_changed.nope.remove(body)
                yield {}
                return
            else:
                return
        if query_name == 'DeleteC':
            to_match, _, then = body.partition(">")
            to_match, then = processParen(to_match), processParen(then)
            if to_match in predicate_changed.cases:
                index = predicate_changed.cases.index(to_match)
                if then != predicate_changed.then[index]:
                    return
                predicate_changed.cases.remove(to_match)
                predicate_changed.then.remove(then)
                predicate_changed.count -= 1
                yield {}
                return
            else:
                return

        if query_name == 'Clear':
            predicate_changed.cases = []
            predicate_changed.then = []
            predicate_changed.count = 0
            predicate_changed.basic = []
            predicate_changed.nope = []
            yield {}
            return

        return

    found[0] = False