Skip to content

Extend Model

Flavio Lionel Rita edited this page Apr 25, 2021 · 2 revisions

It allows to extend the model by adding or overwriting enums, functions and operators

Add Enum

To add an enum to the model the method addEnum is used, this method can add an enum from a dictionary or from a class derived from Enum

Parameters:

  • name: name of enum
  • source: dictionary or class derived from Enum

Add enum from dictionary

Example:

from py_expression.core import Exp
exp = Exp()

exp.addEnum('ColorConversion',{"BGR2GRAY":6
                             ,"BGR2HSV":40
                             ,"BGR2RGB":4
                             ,"GRAY2BGR":8
                             ,"HSV2BGR":54
                             ,"HSV2RGB":55
                             ,"RGB2GRAY":7
                             ,"RGB2HSV":41})

Use

print(exp.solve('ColorConversion.GRAY2BGR'))                             
example result
'ColorConversion.GRAY2BGR' 8

Add enum from enum derived class

Example:

from py_expression.core import Exp
from enum import Enum
exp = Exp()

class Color(Enum):
        RED = 1
        GREEN = 2
        BLUE = 3        

exp.addEnum('Color',Color)

Use

print(exp.solve('Color.GREEN'))
example result
'Color.GREEN' 2

Add Function

To add a function to the model, the addFunction method is used, this method adds a function from one created.

Parameters:

  • name : name of function
  • source: reference of def
  • types (optional) :types associated with the function

Example:

from py_expression.core import Exp
exp = Exp()

def cvCanny(image,threshold1,threshold2):
    color = False
    if len(image.shape) >= 3:
        image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
        color = True
    output = cv.Canny(image,threshold1,threshold2)
    return cv.cvtColor(output, cv.COLOR_GRAY2BGR) if color else output

exp.addFunction('cvImread',cv.imread)
exp.addFunction('cvImwrite',cv.imwrite)
exp.addFunction('cvtColor',cv.cvtColor)
exp.addFunction('cvCanny',cvCanny)

Add or override Operator

To add or overwrite an operator to the model, the addOperator method is used, this method adds an Operator from a class derived from Operator.

Parameters:

  • key : symbol representing the operator
  • category: category to which the operator belongs
  • source: reference to the class, this class must derive from Operator
  • priority (optional) : is the priority that this operator has over others when it is evaluated (Example: the addition operator has higher priority than the sum operator)

Example:

from py_expression.core import Exp,Operator
exp = Exp()

class Assigment(Operator):
    @property
    def value(self):
        self._operands[0].value = self._operands[1].value
        return self._operands[0].value

class Addition(Operator):
    def solve(self,a,b):
        return a+b 

exp.addOperator('+','arithmetic',Addition,4)
exp.addOperator('=','assignment',Assigment,1)
Clone this wiki locally