Esempio n. 1
0
 def compileClassVarDec(self):
     """
     compiles a classVerDec
     """
     type, token = self.get_current()
     var_kind = token
     self.terminal(type, token)  # get 'static' or 'field'
     type, token = self.get_next()
     var_type = token
     self.terminal(type, token)  # get var type
     type, token = self.get_next()
     var_name = token
     self.terminal(type, token)  # get var name
     self._class_table.append(
         Symbol(var_name, var_type, var_kind, self.counters[var_kind]))
     self.counters[var_kind] += 1
     type, token = self.get_next()
     while token == ",":
         self.terminal(type, token)  # get ',' symbol
         type, token = self.get_next()
         self.terminal(type, token)  # get var name
         var_name = token
         self._class_table.append(
             Symbol(var_name, var_type, var_kind, self.counters[var_kind]))
         self.counters[var_kind] += 1
         type, token = self.get_next()
     self.terminal(type, token)  # get ';' symbol
    def parseMapFile(self):
        """Returns a list of Symbols instances extracted from the map file which
		path is filePath (should have been generalted by gold.ld -Map <file>
		"""
        filePath = self.getMapFile()
        res = []

        # The symbols described in the parsed file can mostly have 2 forms:
        # - 1 line description: "<name> <addr> <size> <alignment> <object file>"
        # - 2 lines description:
        #   "<name>
        #                 <addr> <size> <alignment> <object file>"
        # So here I have 1 regexp for the single line scenario and 2 for the
        # double lines one. This filters out a lot of uneeded stuff, but we
        # still need to only keep symbols related to text/data/rodata/bss so
        # an additional check is performed on the extracted symbosl before
        # adding it to the result set
        twoLinesRe1 = "^[\s]+(\.[texrodalcbs\.]+[\S]*)$"
        twoLinesRe2 = ("^[\s]+(0x[0-9a-f]+)[\s]+(0x[0-9a-f]+)[\s]+" +
                       "(0x[0-9a-f]+)[\s]+(.*)$")
        oneLineRe = ("^[\s]+(\.[texrodalcbs\.]+[\S]+)[\s]+(0x[0-9a-f]+)[\s]+" +
                     "(0x[0-9a-f]+)[\s]+(0x[0-9a-f]+)[\s]+(.*)$")

        with open(filePath, "r") as mapfile:
            lines = mapfile.readlines()
            for index, line in enumerate(lines):
                s = None
                matchResult = re.match(twoLinesRe1, line)
                if matchResult:  # probably a 2-lines symbol description
                    nextLine = lines[index + 1]
                    matchResult2 = re.match(twoLinesRe2, nextLine)
                    if matchResult2:
                        name = matchResult.group(1)
                        address = int(matchResult2.group(1), 0)
                        size = int(matchResult2.group(2), 0)
                        alignment = int(matchResult2.group(3), 0)
                        objectFile = matchResult2.group(4)
                        s = Symbol.Symbol(name, address, size, alignment,
                                          objectFile, self.getArch())
                    else:
                        er("missed a two lines symbol while parsing	mapfile:\n"
                           )
                        er("line1: " + line + "\n")
                        er("line2: " + nextLine + "\n")
                        sys.exit(-1)
                else:
                    matchResult3 = re.match(oneLineRe, line)
                    if matchResult3:  # one line symbol description
                        name = matchResult3.group(1)
                        address = int(matchResult3.group(2), 0)
                        size = int(matchResult3.group(3), 0)
                        alignment = int(matchResult3.group(4), 0)
                        objectFile = matchResult3.group(5)
                        s = Symbol.Symbol(name, address, size, alignment,
                                          objectFile, self.getArch())

                if s:
                    res.append(s)

        return res
Esempio n. 3
0
 def compileVarDec(self):
     """
     compiles a varDec.
     """
     type, token = self.get_current()
     self.terminal(type, token)  # get 'var' keyword
     type, token = self.get_next()
     var_type = token
     self.terminal(type, token)  # get var type
     type, token = self.get_next()
     var_name = token
     self._subroutine_table.add_symbol(
         Symbol(var_name, var_type, "local",
                self._subroutine_table.get_counters()["local"]))
     self._subroutine_table.get_counters()["local"] += 1
     self.terminal(type, token)  # get var name
     type, token = self.get_next()
     while token == ",":
         self.terminal(type, token)  # get ',' symbol
         type, token = self.get_next()
         var_name = token
         self._subroutine_table.add_symbol(
             Symbol(var_name, var_type, "local",
                    self._subroutine_table.get_counters()["local"]))
         self._subroutine_table.get_counters()["local"] += 1
         self.terminal(type, token)  # get var name
         type, token = self.get_next()
     self.terminal(type, token)  # get ';' symbol
Esempio n. 4
0
def p_PrimeList(t):
  '''PrimeList : PrimeList PRIME
               | PRIME'''

  if len(t) == 2:
    t[0] = [Symbol(Symbol.PRIME)]

  else:
    t[0] = t[1] + [Symbol(Symbol.PRIME)]
Esempio n. 5
0
def p_DifferentialVariable2(t):
  '''DifferentialVariable : ID CARET LBRACE LPAREN NUMBER RPAREN RBRACE LPAREN ExpressionList RPAREN
                          | ID CARET LBRACE LPAREN NUMBER RPAREN RBRACE'''

  isOrder = False

  try:
    order = int(t[5].getNumber())
    isOrder = True
  except Exception as msg:
    order = t[5]

  if isOrder:

    if order > 0:
      primeList = [Symbol(Symbol.PRIME)]*int(order)
    else:
      primeList = []

    if len(t) > 8:
      t[0] = DifferentialVariable(Identifier(ID(t[1])), primeList, t[9])

    else:
      t[0] = DifferentialVariable(Identifier(ID(t[1])), primeList)

  else:
    if len(t) > 8:
      raise SyntaxException(t.slice[5].lineno, t.slice[5].lexpos, t.slice[5].value, t.slice[5])

    else:
      t[0] = ExpressionWithBinaryOperation(BinaryOperator(BinaryOperator.POW), Identifier(ID(t[1])), t[5])
    def get_symbol_test(self, soup, trace_obj_dict):
        flag = True  # to ignore the first tracegroup
        symbols = [
        ]  # This will store the objects for every symbol in the file.
        # pdb.set_trace()
        for trace_g in soup.findAll('tracegroup'):
            if flag == True:
                flag = False
                continue
            else:
                #  symbol_class = trace_g.annotation.text   # No ground truth available
                # Get symbol id
                try:
                    symbol_id = int(trace_g.attrs[0][1])
                except:
                    #Conversion to int nit possible
                    symbol_id = int(trace_g.attrs[0][1].split(":")[0])

                symbol_list = []
                #print ("Symbol_id: %d" ) % (symbol_id)
                trace_view = trace_g.findAll('traceview')
                #pdb.set_trace()
                for i in xrange(len(trace_view)):
                    trace_id = int(trace_view[i]['tracedataref'])
                    symbol_list.append(trace_obj_dict[trace_id])

                symbol_obj = Symbol(symbol_id, symbol_list, symbol_class)

            symbols.append(symbol_obj)

        return symbols
Esempio n. 7
0
class TestBot:
    #symbols = Symbol.Symbol("ES\H20.CM", "symbol")
    symbols = Symbol.Symbol("Earnings_2020-02-04.csv", "file")
    Register.Register(
        "TOS",
        "5555",
    )
Esempio n. 8
0
def addLabelwithLocation(Label, location):

    if (str(-1) != str(Opcode_Table.CheckOpcode(Label)[1])):
        return -6

    symbol = Symbol.Symbol(Label, "Label")

    if symbol.name not in Symbol_Table:

        Symbol_Table[symbol.name] = [location, symbol.Type]
        return 0

    else:

        Type = Symbol_Table[symbol.name][1]

        if (Type == ("Variable")):
            return -3

        if (Type == ("Label")):

            address = Symbol_Table[symbol.name][0]

            if (address == -1):

                Symbol_Table[symbol.name][0] = location
                return 0

            return -4
Esempio n. 9
0
 def __new__(cls):
     if ComplexRationals.__instance == None:
         obj = object.__new__(cls)
         obj._polyRing = PolynomialDomain(Rationals(), Symbol.Symbol('i'))
         obj._poly = obj._polyRing([1, 0, 1])
         obj._ideal = BAS.PrincipalIdeal(obj._polyRing, obj._poly)
         obj._ideal.isMaximal = lambda: True
         super(ComplexRationals, obj).__init__(obj._polyRing, obj._ideal)
         ComplexRationals.__instance = obj
     return ComplexRationals.__instance
Esempio n. 10
0
def addVariable(Variable):
    if (str(-1) != str(Opcode_Table.CheckOpcode(Variable)[1])):
        return -7

    symbol = Symbol.Symbol(Variable, "Variable")
    if symbol.name in Symbol_Table:
        if (symbol.Type == ("Label")):
            return -5
    else:
        Symbol_Table[symbol.name] = [-1, "Variable"]
    return 0
Esempio n. 11
0
    def get_parse_layout(self, adj_matrix, dict_mapping_Symbol_index,
                         index_to_symbol, rel_classifier_obj):
        '''
        The function returns a dictionary of relation corresponding to two symbols, which is later used for writing it to a lg files.
        '''

        symbol_obj = Symbol()
        dict_map_rel_to_syms = {}

        tree = minimum_spanning_tree(adj_matrix)
        mst = tree.toarray()

        for i in xrange(mst.shape[0]):
            eye_obj = index_to_symbol[i]
            arr = np.where(mst[i] > 0)[0]
            if arr.shape[0] == 0:
                continue
            else:
                trace_list = []
                points_eye = []
                for k in xrange(len(eye_obj.symbol_list)):
                    points_eye += eye_obj.symbol_list[k].original_points

                for j in xrange(arr.shape[0]):

                    other_obj = index_to_symbol[arr[j]]
                    total_points = []
                    for l in xrange(len(other_obj.symbol_list)):
                        total_points += other_obj.symbol_list[
                            l].original_points

                    total_points = points_eye + total_points
                    trace_obj = Trace(points_float=total_points)
                    trace_obj.normalization()
                    trace_list.append(trace_obj)

                    symbol_obj.symbol_list = trace_list
                    features = symbol_obj.get_features()
                    X_test = np.asarray(features)
                    label = rel_classifier_obj.predict(X_test.reshape(1, -1))

                    if label[0] not in dict_map_rel_to_syms:
                        dict_map_rel_to_syms[label[0]] = []
                        dict_map_rel_to_syms[label[0]].append(
                            (eye_obj, other_obj))
                    else:
                        dict_map_rel_to_syms[label[0]].append(
                            (eye_obj, other_obj))

                    trace_list.remove(trace_obj)

        return dict_map_rel_to_syms,
Esempio n. 12
0
 def test_Matrix(self):
     Z5 = AS.IntegerResidueClassField(5)
     m = Matrix.Matrix(2,2,Z5,[[2,1],[0,2]])
     n = Matrix.Matrix(2,2,Z5,[[3,1],[0,3]])
     self.assertEqual(str(m), "[2|1]\n[0|2]")
     self.assertEqual(m.invert(),n)
     polys = AS.PolynomialDomain(Z5,Symbol.Symbol('t'))
     self.assertEqual(m.charPoly(), polys([4,1,1]))
     self.assertEqual(m.determinant(), Z5.elementFromValue(4))
     m2 = Matrix.Matrix(2,2,Z5,[[1,3],[2,6]])
     with self.assertRaises(Matrix.MatrixInversionError):
         m2.invert()
     self.assertEqual(m2.determinant(), Z5(0))
     
     k = Matrix.getUnitMatrix(2, Z5)
     self.assertTrue(k.isDiagonalizable())
     (p,d) = k.getDiagonalizerMatrix()
     self.assertEqual(p, d)
     self.assertEqual(p, k)
     
     m = Matrix.Matrix(2,2,Z5,[[1,1],[1,1]])
     self.assertTrue(m.isDiagonalizable())
     (p,d) = m.getDiagonalizerMatrix()
     self.assertEqual(p,Matrix.Matrix(2,2,Z5,[[4,1],[1,1]]))
     
     Q = AS.F_Q
     m = Matrix.Matrix(3,3,Q,[[1,1,0],[2,0,2],[-1,1,1]])
     n = Matrix.Matrix(3,3,Q,[[2,1,-2],[4,-1,2],[-2,2,2]]).scalarMultiplication(Q(1,6))
     self.assertEqual(n, m.invert())
     self.assertEqual(n.invert(), m)
     
     self.assertEqual(m.determinant(),Q(-6))
     polys = AS.PolynomialDomain(Q,Symbol.Symbol("t"))
     self.assertEqual(m.charPoly(), polys([6,-3,-2,1]))
     
     
     m = Matrix.Matrix(3,3,Q,[[1,1,0],[0,0,1],[0,0,0]])
     self.assertEqual(m.nullity(), 1)
Esempio n. 13
0
 def compileParameter(self):
     """
     compiles a parameter
     """
     type, token = self.get_current()
     argument_type = token
     self.terminal(type, token)  # get parameter type
     type, token = self.get_next()
     argument_name = token
     self._subroutine_table.add_symbol(
         Symbol(argument_name, argument_type, "argument",
                self._subroutine_table.get_counters()["argument"]))
     self._subroutine_table.get_counters()["argument"] += 1
     self.terminal(type, token)  # get parameter name
Esempio n. 14
0
	def _declare(self, enclosing_scope, is_key = False):
		self._scope = enclosing_scope
		token_name = self._token.value
		token_type = self._token.type.name
		symbol_type = self._scope.resolve(token_type)

		if is_key:
			self._symbol = self._scope.resolve(token_name)

			if self._symbol != None:
				raise ValueError('Symbol Already Defined')

		self._symbol = Symbol(token_name, symbol_type)

		return self._symbol
Esempio n. 15
0
    def sym_parsing(self, rel_classifier_obj, file_path_till_traininkml,
                    str_opt):
        '''
        The function calls methods from MinimumSpanningTree class to segment and classify symbols and then parses the symbols, finally
        writing it to an lg files.
        '''
        load_obj = loadData()
        e = Graph()
        symbol_obj = Symbol()
        lg_folder_name = "parsing_" + str_opt
        file_write_obj = FileWrite(lg_folder_name)
        flag = False

        with open('split_files.txt', 'r') as f:
            for line in f:
                if flag:
                    files = line
                    files = files.strip("Set([")
                    files = files.strip("])\n")
                    list_files = files.split(', ')
                    break

                elif line.startswith(str_opt):
                    flag = True
                    continue

        count = 0

        for fileName in list_files:
            count = count + 1
            fileName = fileName.strip("'")
            print "count= %d" % (count)
            fileName = fileName.replace(
                "/home/sbp3624/PatternRecog/TrainINKML_v3/",
                file_path_till_traininkml)
            root_obj, trace_obj_dict = load_obj.loadInkml(fileName)
            symbols = load_obj.get_symbol(root_obj, trace_obj_dict)
            adj_matrix, dict_mapping_Symbol_index, index_to_symbol = e.LineOfSight(
                symbols, rel_classifier_obj)
            dict_map_rel_to_syms = self.get_parse_layout(
                adj_matrix, dict_mapping_Symbol_index, index_to_symbol,
                rel_classifier_obj)
            dict_map_rel_to_syms = dict_map_rel_to_syms[
                0]  # because the funtion returns a tuple
            self.write_to_lg(fileName, symbols, dict_map_rel_to_syms,
                             lg_folder_name)
Esempio n. 16
0
    def sym_segmentation(self, classifier_obj, file_path_till_traininkml,
                         str_opt, rel_classifier_obj):
        '''
        The function calls methods from MinimumSpanningTree to segment,classify and parse symbols
        Input 
        classifier_obj - Classifier pretrained model
        file_path_till_traininkml - path to inkml file
        str_opt - Train or Test
        rel_classifier_obj - Realationship classifier pretrained model.   
        '''
        load_obj = loadData()
        m = MinimumSpanningTree()
        symbol_obj = Symbol()

        lg_folder_name = "parsing_" + str_opt
        file_write_obj = FileWrite(lg_folder_name)

        flag = False

        with open('split_files.txt', 'r') as f:
            for line in f:
                if flag:
                    files = line
                    files = files.strip("Set([")
                    files = files.strip("])\n")
                    list_files = files.split(', ')
                    break

                elif line.startswith(str_opt):
                    flag = True
                    continue

        count = 0

        for fileName in list_files:
            count = count + 1
            fileName = fileName.strip("'")
            print "count= %d" % (count)
            fileName = fileName.replace(
                "/home/sbp3624/PatternRecog/TrainINKML_v3/",
                file_path_till_traininkml)
            root_obj, trace_obj_dict = load_obj.loadInkml(fileName)

            m.get_segmentation(trace_obj_dict, classifier_obj, symbol_obj,
                               file_write_obj, fileName, lg_folder_name,
                               rel_classifier_obj)
Esempio n. 17
0
def addLabel(Label):

    if (str(-1) != str(Opcode_Table.CheckOpcode(Label)[1])):
        return -6

    symbol = Symbol.Symbol(Label, "Label")

    if symbol.name not in Symbol_Table:

        Symbol_Table[symbol.name] = [-1, symbol.Type]
        return 0

    else:

        Type = Symbol_Table[symbol.name][1]

        if (Type == ("Variable")):
            return -3

        return 0
Esempio n. 18
0
 def test_rootsOverFiniteFields(self):
     Z7 = AS.IntegerResidueClassField(7)
     Z7x = AS.PolynomialDomain(Z7,Symbol.Symbol('x'))
     poly = Z7x([1,0,1])
     self.assertEqual(polyTools.rootsOverFiniteField(poly), [])
     poly = Z7x([-1,0,1])
     self.assertEqual(polyTools.rootsOverFiniteField(poly), [[Z7(6),1],[Z7(1),1]])
     
     Z5 = AS.IntegerResidueClassRing(5)
     Z5x,x = AS.polyRing(Z5,'x')
     f = x*(x+4)**3*(x**4+4)**4
     #print(polyTools.SFF(f))
     
     f = 3+2*x+3*x**2+3*x**3+3*x**4+3*x**5
     print(polyTools.getBerlekampMatrix(f,5))
     print(polyTools.BerlekampFactorization(f/3))
     
     Z3x,x = AS.polyRing(AS.IntegerResidueClassField(3),'x')
     
     f = x**11+2*x**9+2*x**8+x**6+x**5+2*x**3+2*x**2+1
Esempio n. 19
0
    def charPoly(self):
        """
        returns the characteristic polynomial p of self=A, p = det(tI-A)
        """
        if self.columns != self.rows:
            raise MatrixInversionError("no square matrix")
        polyDomain = AS.PolynomialDomain(self.basedomain, Symbol.Symbol("t"))
        rationalsDomain = AS.RationalFunctionsDomain(polyDomain)
        charMatrix = Matrix(self.rows, self.columns, rationalsDomain)
        t = polyDomain(
            [self.basedomain.zero, self.basedomain.one]
        )  #rationalsDomain(polyDomain([self.basedomain.zero, self.basedomain.one]),polyDomain.one)
        for i in range(self.rows):
            for j in range(self.columns):
                charMatrix[i, j] = polyDomain([
                    -self[i, j]
                ])  #rationalsDomain(polyDomain([-self[i,j]]),polyDomain.one)
                if i == j:
                    charMatrix[i, j] += t

        return charMatrix.determinant().asBaseRingElement()
    def get_relation_probability(self, eye_obj, other_obj,
                                 relation_classfier_obj):
        #pdb.set_trace()
        sym_obj = Symbol()
        trace_list = []
        total_points = []
        #First get all the points together
        for i in xrange(len(eye_obj.symbol_list)):
            #trace_list.append(eye_obj.symbol_list[i])
            total_points += eye_obj.symbol_list[i].original_points
        for i in xrange(len(other_obj.symbol_list)):
            total_points += other_obj.symbol_list[i].original_points
            #trace_list.append(other_obj.symbol_list[i])

        trace_obj = Trace(points_float=total_points)
        trace_obj.normalization()
        trace_list.append(trace_obj)
        sym_obj.symbol_list = trace_list
        X = sym_obj.get_features()
        X = np.asarray(X)
        prob = np.max(relation_classfier_obj.predict_proba(X.reshape(1, -1)))
        #(1-prob) this is to get the minimum spanning tree.
        trace_list.remove(trace_obj)
        return (1 - prob)
Esempio n. 21
0
 def compileSubroutineDec(self):
     """
     compiles a subroutineDec
     """
     type, token = self.get_current()
     self._subroutine_table = SymbolTable(self._class_table)
     self._cur_func_type = token
     self.terminal(type, token)  # get subroutine
     type, token = self.get_next()
     if self._cur_func_type == "method":
         self._subroutine_table.add_symbol(
             Symbol("this", self._cur_class, "argument", 0))
         self._subroutine_table.get_counters()["argument"] += 1
     self.terminal(type, token)  # get subroutine return type
     type, token = self.get_next()
     self._cur_func = token
     self.terminal(type, token)  # get subroutine name
     type, token = self.get_next()
     self.terminal(type, token)  # get '(' symbol
     type, token = self.get_next()
     self.compileParameterList()
     type, token = self.get_current()
     self.terminal(type, token)  # get ')' symbol
     self.compileSubroutineBody()
Esempio n. 22
0
	def _declare(self, enclosing_scope):
		self._scope = enclosing_scope
		value = self._token.value
		type = self._scope.resolve(self._token.type.name)
		self._symbol = Symbol(value, type)
		return self._symbol
Esempio n. 23
0
    def get_relationship_data(self, file_path_till_traininkml, str_opt,
                              file_path_lg_train):
        '''
        The method extracts the data required for training relationship classifier.
        '''

        load_obj = loadData()
        symbol_obj = Symbol()
        X_rel_train = []
        y_rel_train = []
        flag = False
        with open('split_files.txt', 'r') as f:
            for line in f:
                if flag:
                    files = line
                    files = files.strip("Set([")
                    files = files.strip("])\n")
                    list_files = files.split(', ')
                    break

                elif line.startswith(str_opt):
                    flag = True
                    continue

        count = 0
        for fileName in list_files:

            count = count + 1
            fileName = fileName.strip("'")
            print "count= %d" % (count)
            fileName = fileName.replace(
                "/home/sbp3624/PatternRecog/TrainINKML_v3/",
                file_path_till_traininkml)
            fileName_lg = basename(fileName)
            pos = fileName_lg.find(".")
            fileName_sub = fileName_lg[:pos] + ".lg"
            fileName_lg = file_path_lg_train + fileName_sub
            root_obj, trace_obj_dict = load_obj.loadInkml(fileName)
            dict_sym = {}
            list_Obj = []
            list_R = []

            with open(fileName_lg, "r") as f_read:
                for line in f_read:
                    line = line.strip("\n")
                    line = line.replace(" ", "")
                    if line.startswith("O"):
                        list_obj = line.split(",")
                        dict_sym[list_obj[1]] = list_obj[4:]
                    elif line.startswith("R"):
                        list_R = line.split(",")
                        list_1 = dict_sym[list_R[1]]
                        list_1 += dict_sym[list_R[2]]
                        rel_label = list_R[3]
                        list_traceobj_rel = []
                        total_points = []
                        for trace_id in list_1:
                            #list_traceobj_rel.append(trace_obj_dict[int(trace_id)])
                            total_points += trace_obj_dict[int(
                                trace_id)].original_points
                        #First get the original points then normalize
                        trace_obj = Trace(points_float=total_points)
                        trace_obj.normalization()
                        list_traceobj_rel.append(trace_obj)
                        symbol_obj.symbol_list = list_traceobj_rel
                        features = symbol_obj.get_features()
                        X_rel_train.append(features)
                        y_rel_train.append(rel_label)
                        list_traceobj_rel.remove(trace_obj)

        return X_rel_train, y_rel_train
Esempio n. 24
0
def p_DivisorFunction(t):
  '''DivisorFunction : SIGMA_LOWER UNDERLINE LBRACE NUMBER RBRACE LPAREN ExpressionList RPAREN'''
  t[0] = ExpressionWithFunction(Symbol(Symbol.SIGMA_LOWER), t[7], t[4])
Esempio n. 25
0
 def append(self, symIdx):
     if not GL.symbols[symIdx].isValid():
         return
     s = Symbol(GL.gscore)
     s.setSym(symIdx)
     self.append1(s, qApp.translate("symbol", GL.symbols[symIdx].name()))
    def get_segmentation(self,trace_obj_dict,classifier_obj,symbol_obj,File_write_obj,fileName,lg_folder_name,rel_classifier_obj):
        '''
        The function is calls optimal segmenattation and then call method to write lg files
        Input
        trace_obj_dict: trace objects for that file
        classifier_obj: classifier object
        symbol_obj: Symbol class object
        File_write_obj:File write object
        lg_folder_name: Foldername to store lg files
        '''
        min_span_tree=self.get_spanning_tree(trace_obj_dict)
        demo_min_span_tree=min_span_tree
        temp=np.zeros(demo_min_span_tree.shape[0])
        temp=temp.reshape(temp.shape[0],1)
        demo_min_span_tree=np.hstack((temp,demo_min_span_tree))
        temp=np.zeros(demo_min_span_tree.shape[1])
        demo_min_span_tree=np.vstack((temp,demo_min_span_tree))
        demo_min_span_tree_bool=demo_min_span_tree>0
        # Now get best probability distribution for set of strokes  
        dict_trace_map={}
        count=0
        s=[]
        # This will help in mapping which index belong to which trace
        for i in xrange(1,len(trace_obj_dict)+1):
            dict_trace_map[i]=trace_obj_dict[i-1]

        n=len(trace_obj_dict)+1
        r,s = self.memoized_initialization(n)
        dict_mapping_strokes={}
        r,s,dict_mapping_strokes=self.optimal_segmentation(n,1,r,s,classifier_obj,trace_obj_dict,demo_min_span_tree_bool,dict_mapping_strokes,symbol_obj)
        index=n-1
        list_predict_symbol=[]
        symbol_list=[]
        count_traces=0

        #Back Track and get the list of strokes
        while index>0:
            
            x=s[index]
            list_strokes=dict_mapping_strokes[index]
            symbol_object=Symbol()
            symbol_list.append(symbol_object)  # List of symbol object , which will be used to extract features            
            strokes_symbol=[]    
            for k in list_strokes:
                trace_obj=dict_trace_map[k]
                strokes_symbol.append(trace_obj)
                count_traces=count_traces+1
                
            symbol_object.symbol_list=strokes_symbol
            index=index-int(x)

        stroke_to_pixel=[]
        X_test=[]
        
        for symbol in symbol_list:
            features=symbol.get_features()
            X_test.append(features)          
            
        X_test_final=np.asarray(X_test)
        
        predict_labels=classifier_obj.predict(X_test_final)
       
        e=Graph()
        r=RelationShipClassifier()
     

        adj_matrix,dict_mapping_Symbol_index,index_to_symbol=e.LineOfSight(symbol_list,rel_classifier_obj)
       
        dict_map_rel_to_syms=r.get_parse_layout(adj_matrix,dict_mapping_Symbol_index,index_to_symbol,rel_classifier_obj)
        dict_map_rel_to_syms=dict_map_rel_to_syms[0]
       
        File_write_obj.write_to_lg(predict_labels,fileName,symbol_list,dict_map_rel_to_syms,count_traces,lg_folder_name)     
Esempio n. 27
0
    def dropEvent(self, event):
        data = event.mimeData()
        if data.hasUrls():
            ul = event.mimeData().urls()
            u = ul.front()
            if u.scheme() == "file":
                fi = QFileInfo(u.path())
                s = Image(None)
                suffix = QString(fi.suffix().toLower())
                if suffix == "svg":
                    s = SvgImage(GL.gscore)
                elif suffix == "jpg" or suffix == "png" or suffix == "xpm":
                    s = RasterImage(GL.gscore)
                else:
                    return
                mag = PALETTE_SPATIUM * self.extraMag / GL.gscore.spatium()
                s.setPath(u.toLocalFile())
                s.setSize(QSizeF(self.hgrid / mag, self.hgrid / mag))
                e = s
                name = s.path()
        elif data.hasFormat(mimeSymbolFormat):
            data = QByteArray(event.mimeData().data(mimeSymbolFormat))
            doc = QDomDocument()
            (ok, err, line, column) = doc.setContent(data)
            if not ok:
                print "error reading drag data\n"
                return
            docName = "--"
            el = doc.documentElement()
            (type, dragOffset, duration) = Element.readType(el)

            if type == ElementType.IMAGE:
                path = QString()
                ee = el.firstChildElement()
                while not ee.isNull():
                    tag = QString(ee.tagName())
                    if tag == "path":
                        path = ee.text()
                        break
                    ee = ee.nextSiblingElement()
                image = 0
                s = QString(path.toLower())
                if s.endsWith(".svg"):
                    image = SvgImage(GL.gscore)
                elif s.endsWith(".jpg") or s.endsWith(".png") or s.endsWith(
                        ".xpm"):
                    image = RasterImage(GL.gscore)
                else:
                    print "unknown image format <%s>\n" % path.toLatin1().data(
                    )
                if image:
                    image.read(el)
                    e = image
            elif type == ElementType.SYMBOL:
                s = Symbol(GL.gscore)
                s.read(el)
                e = s
            else:
                e = Element.create(type, GL.gscore)
                if e:
                    e.read(el)
                if e.type() == ElementType.TEXTLINE:
                    tl = e
                    tl.setLen(GL.gscore.spatium() * 7)
                    tl.setTrack(0)
        if e:
            e.setSelected(False)
            ok = False
            if event.source() == self:
                i = self.idx(event.pos())
                if i == -1:
                    self.cells.append(self.cells[self.dragSrcIdx])
                    self.cells[self.dragSrcIdx] = 0
                    ok = True
                elif self.dragSrcIdx != i:
                    c = self.cells[self.dragSrcIdx]
                    self.cells[self.dragSrcIdx] = self.cells[i]
                    self.cells[i] = c
                    del e
                    ok = True
                event.setDropAction(Qt.MoveAction)
            else:
                self.append(e, name)
                ok = True
            if ok:
                event.acceptProposedAction()
                self.update()
                self.changed.emit()
Esempio n. 28
0
def polyRing(domain, var):
    p = PolynomialDomain(domain, Symbol.Symbol(var))
    return p, p([domain.zero, domain.one])
Esempio n. 29
0
def p_Symbol(t):
  '''Symbol : PI
            | XI_LOWER
            | CHI_LOWER
            | PHI_LOWER
            | PSI_LOWER
            | SIGMA_LOWER
            | ZETA_LOWER
            | ETA_LOWER
            | DELTA_LOWER
            | THETA_LOWER
            | LAMBDA_LOWER
            | EPSILON_LOWER
            | TAU_LOWER
            | KAPPA_LOWER
            | OMEGA_LOWER
            | ALPHA_LOWER
            | NU_LOWER
            | RHO_LOWER
            | OMICRON_LOWER
            | UPSILON_LOWER
            | IOTA_LOWER
            | BETA_LOWER
            | GAMMA_LOWER
            | MU_LOWER
            | PI_UPPER
            | BETA
            | GAMMA
            | KAPPA
            | OMICRON
            | OMEGA
            | LAMBDA
            | IOTA
            | PSI
            | MU
            | PHI
            | SIGMA
            | ETA
            | ZETA
            | THETA
            | EPSILON
            | TAU
            | ALPHA
            | XI
            | CHI
            | NU
            | RHO
            | UPSILON'''

  if t.slice[1].type == "PI":
    t[0] = Symbol(Symbol.PI)

  elif t.slice[1].type == "PI_UPPER":
    t[0] = Symbol(Symbol.PI_UPPER)

  elif t.slice[1].type == "ALPHA_LOWER":
    t[0] = Symbol(Symbol.ALPHA_LOWER)

  elif t.slice[1].type == "CHI_LOWER":
    t[0] = Symbol(Symbol.CHI_LOWER)

  elif t.slice[1].type == "XI_LOWER":
    t[0] = Symbol(Symbol.XI_LOWER)

  elif t.slice[1].type == "PHI_LOWER":
    t[0] = Symbol(Symbol.PHI_LOWER)

  elif t.slice[1].type == "PSI_LOWER":
    t[0] = Symbol(Symbol.PSI_LOWER)

  elif t.slice[1].type == "SIGMA_LOWER":
    t[0] = Symbol(Symbol.SIGMA_LOWER)

  elif t.slice[1].type == "ZETA_LOWER":
    t[0] = Symbol(Symbol.ZETA_LOWER)

  elif t.slice[1].type == "ETA_LOWER":
    t[0] = Symbol(Symbol.ETA_LOWER)

  elif t.slice[1].type == "DELTA_LOWER":
    t[0] = Symbol(Symbol.DELTA_LOWER)

  elif t.slice[1].type == "THETA_LOWER":
    t[0] = Symbol(Symbol.THETA_LOWER)

  elif t.slice[1].type == "LAMBDA_LOWER":
    t[0] = Symbol(Symbol.LAMBDA_LOWER)

  elif t.slice[1].type == "EPSILON_LOWER":
    t[0] = Symbol(Symbol.EPSILON_LOWER)

  elif t.slice[1].type == "TAU_LOWER":
    t[0] = Symbol(Symbol.TAU_LOWER)

  elif t.slice[1].type == "KAPPA_LOWER":
    t[0] = Symbol(Symbol.KAPPA_LOWER)

  elif t.slice[1].type == "OMEGA_LOWER":
    t[0] = Symbol(Symbol.OMEGA_LOWER)

  elif t.slice[1].type == "NU_LOWER":
    t[0] = Symbol(Symbol.NU_LOWER)

  elif t.slice[1].type == "RHO_LOWER":
    t[0] = Symbol(Symbol.RHO_LOWER)

  elif t.slice[1].type == "OMICRON_LOWER":
    t[0] = Symbol(Symbol.OMICRON_LOWER)

  elif t.slice[1].type == "UPSILON_LOWER":
    t[0] = Symbol(Symbol.UPSILON_LOWER)

  elif t.slice[1].type == "IOTA_LOWER":
    t[0] = Symbol(Symbol.IOTA_LOWER)

  elif t.slice[1].type == "BETA_LOWER":
    t[0] = Symbol(Symbol.BETA_LOWER)

  elif t.slice[1].type == "GAMMA_LOWER":
    t[0] = Symbol(Symbol.GAMMA_LOWER)

  elif t.slice[1].type == "BETA":
    t[0] = Symbol(Symbol.BETA)

  elif t.slice[1].type == "GAMMA":
    t[0] = Symbol(Symbol.GAMMA)

  elif t.slice[1].type == "MU":
    t[0] = Symbol(Symbol.MU)

  elif t.slice[1].type == "KAPPA":
    t[0] = Symbol(Symbol.KAPPA)

  elif t.slice[1].type == "OMICRON":
    t[0] = Symbol(Symbol.OMICRON)

  elif t.slice[1].type == "OMEGA":
    t[0] = Symbol(Symbol.OMEGA)

  elif t.slice[1].type == "LAMBDA":
    t[0] = Symbol(Symbol.LAMBDA)

  elif t.slice[1].type == "IOTA":
    t[0] = Symbol(Symbol.IOTA)

  elif t.slice[1].type == "PSI":
    t[0] = Symbol(Symbol.PSI)

  elif t.slice[1].type == "PHI":
    t[0] = Symbol(Symbol.PHI)
  
  elif t.slice[1].type == "SIGMA":
    t[0] = Symbol(Symbol.SIGMA)
  
  elif t.slice[1].type == "ETA":
    t[0] = Symbol(Symbol.ETA)
  
  elif t.slice[1].type == "ZETA":
    t[0] = Symbol(Symbol.ZETA)
  
  elif t.slice[1].type == "THETA":
    t[0] = Symbol(Symbol.THETA)
  
  elif t.slice[1].type == "EPSILON":
    t[0] = Symbol(Symbol.EPSILON)
  
  elif t.slice[1].type == "TAU":
    t[0] = Symbol(Symbol.TAU)
  
  elif t.slice[1].type == "ALPHA":
    t[0] = Symbol(Symbol.ALPHA)
  
  elif t.slice[1].type == "XI":
    t[0] = Symbol(Symbol.XI)
  
  elif t.slice[1].type == "CHI":
    t[0] = Symbol(Symbol.CHI)
  
  elif t.slice[1].type == "NU":
    t[0] = Symbol(Symbol.NU)
  
  elif t.slice[1].type == "RHO":
    t[0] = Symbol(Symbol.RHO)
  
  elif t.slice[1].type == "UPSILON":
    t[0] = Symbol(Symbol.UPSILON)
  
  else:
    t[0] = Symbol(Symbol.MU_LOWER)
Esempio n. 30
0
 def boxes2symbols(boxes):
     symbols = []
     for x, y, w, h in boxes:
         symbols.append(Symbol(SymbolType.UNKNOWN, x, y, w, h))
     return symbols