示例#1
0
文件: base.py 项目: Sharkkii/shaDL
 def grad(self, *douts):
     """
     grad: Variables -> tuple(Variables)
     """
     tmp_douts = tuple([dout.data for dout in douts])
     tmp_dins = self.backward(*tmp_douts)
     dins = tuple([Variable(din) for din in tmp_dins]) if isinstance(
         tmp_dins, tuple) else Variable(tmp_dins)
     return dins
示例#2
0
def neural_network_test():
    '''
    Classifier test
    '''
    x = Placeholder()
    w = Variable([1, 1])
    b = Variable(-5)
    z = add(matmul(w, x), b)
    a = Sigmoid(z)
    sess = Session()
    assert sess.run(operation=a, feed_dict={x: [8, 10]}) > 0.9
    assert sess.run(operation=a, feed_dict={x: [4, -10]}) < 0.1
示例#3
0
def basic_test():
    '''
    basic test for z = Ax + b
    '''
    g = Graph()
    A = Variable(10, default_graph=g)
    b = Variable(1, default_graph=g)
    x = Placeholder(default_graph=g)
    y = multiply(A, x)
    z = add(y, b)
    sess = Session()
    result = sess.run(operation=z, feed_dict={x: 10})
    print(result)
    assert result == 101
示例#4
0
    def test_get_func_for_pde(self):
        integration_steps = 10

        t = sympy.Symbol("t")
        x = sympy.Symbol("x")
        var_name = x.name
        f = sympy.Function("f")(x)
        g = sympy.Function("g")(t, x)

        g.subs({x: x + 2, t: t - 1}).atoms()

        sym_x_expression = x
        func = get_func_for_pde(sym_x_expression, f.diff(x, 1))
        dom = Domain(lower_limits_dict={var_name: 1},
                     upper_limits_dict={var_name: 1},
                     step_width_dict={var_name: 0.1})
        var = Variable(data=[1],
                       domain=dom,
                       domain2axis={var_name: 0},
                       variable_name='f')
        res_var = func(data0=var,
                       boundary=[],
                       integration_steps=integration_steps)
        assert res_var.data == dom.step_width[var_name] * np.arange(
            integration_steps) + dom.lower_limits[var_name]
示例#5
0
def matrix_multiplication_test():
    '''
    test for matrix multiplication
    '''
    A = Variable([[10, 20], [30, 40]])
    b = Variable([1, 2])
    x = Placeholder()
    y = matmul(A, x)
    z = add(y, b)
    sess = Session()
    result = sess.run(operation=z, feed_dict={x: 10})
    assert len(result) == 2
    assert len(result[0]) == 2
    assert result[0][0] == 101
    assert result[0][1] == 202
    assert result[1][0] == 301
    assert result[1][1] == 402
def test_variable_scalar_pow():
    '''object.__pow__(), object.__ipow__()'''
    x = Variable('x',2)
    y = Variable('y',-5)
    z = Variable('z',0)

    # case 1:
    f1 = x**2
    assert (f1.val == 4)
    assert (f1.jacobian() == {'x':4})
    assert (f1.partial_der(x) == 4)
    assert (f1.partial_der(y) == 0)

    # case 2:
    f2 = x**0
    assert (f2.val==1)
    assert (f2.jacobian()=={'x':0})

    # notice 0**0 not define, should throws error
    with pytest.raises(ZeroDivisionError):
        f3 = z**0

    with pytest.raises(ZeroDivisionError):
        f4 = z**(-2)

    # case 3:
    #print(x.der)
    f3 = (2*x)**(1/2)
    assert (f3.val == 2)
    #print(f3.jacobian())
    assert (f3.jacobian() == {'x':0.5})
    assert (f3.partial_der(x) == 0.5)
    assert (f3.partial_der(y) == 0)

    # case 4:
    f4 = 2**x
    assert (f4.val == 4)
    assert (f4.jacobian() == {'x':4*np.log(2)})
    assert (f4.partial_der(x) == 4*np.log(2))
    assert (f4.partial_der(y) == 0)

    # case 5:
    '''
示例#7
0
def test_numpy_scalar_sin_cos():
    '''
    object.__add__(), object.__sub__(), object.__pos__(), object.__neg__(),
    object.__iadd__(), object.__isub__()
    '''
    # case 0: build variables
    x = Variable('x', np.pi/4)
    y = Variable('y', -np.pi/4)
    z = Variable('z', 0)
    a = Variable('a',np.pi/2)

    f1=anp.cos(a)
    assert(abs(f1.val-0)<=1e-16)
    assert(f1.jacobian()=={'a':-1})

    f2=anp.cos(x)
    assert(abs(f2.val-(np.sqrt(2)/2))<=1e-5)
    assert(abs(f2.partial_der(x) +np.sqrt(2)/2)<=1e-5)
    f3=anp.sin(y)
    assert(abs(f3.val+(np.sqrt(2)/2))<=1e-5)
    assert(abs(f3.partial_der(y) - np.sqrt(2)/2) <= 1e-5)
示例#8
0
def variable(c, m):
    """Variable or constant definition. For instance:
        byte little = 42
        short big = 1234

        byte[5] vector1
        byte[] vector2 = 1, 2, 3, 4, 5

        const VALUE = 7
    """
    # TODO Perform more checks to ensure the value is correct
    vartype = m.group(1)
    vector_size = m.group(2)
    name = m.group(3)
    value = m.group(4)
    if not value:
        value = '?'

    if vector_size is None:
        # Single item variable
        c.add_variable(Variable(name=name, vartype=vartype, value=value))
    else:
        # We have a vector, get the comma-separated values
        values = Operand.get_csv(value)

        # Determine its size (remove '[]' by slicing) if given
        vector_size = vector_size[1:-1].strip()
        if vector_size:
            vector_size = int(vector_size)
        else:
            if value == '?':
                raise ValueError('A list of values must be supplied when '
                                 'no vector size is specified')
            vector_size = len(values)

        c.add_variable(
            Variable(name=name,
                     vartype=vartype,
                     value=values,
                     vector_size=vector_size))
示例#9
0
def ETI_TEST():
    print("Staring ETL Test  Job !!!!")
    var = Variable()
    var.INPUT_DATA = "/input/employee.csv"
    csvParser = csv_parser(var.INPUT_DATA)

    if csvParser.file_exist(var.INPUT_DATA):
        TABLE_NAME = csvParser.get_table_name(
            var.INPUT_DATA)  # Takes Table name from Filename

        if var.CREATE_TABLE and not var.RELATION:
            ob = ETL(TABLE_NAME, var.INPUT_DATA)
            ob.etl_process(csvParser.check_header(), 20)
示例#10
0
def main():

    print("Staring ETL Job !!!!")
    var = Variable()
    csvParser = csv_parser(var.INPUT_DATA)

    if csvParser.file_exist(var.INPUT_DATA):
        TABLE_NAME = csvParser.get_table_name(
            var.INPUT_DATA)  # Takes Table name from Filename

        if var.CREATE_TABLE and not var.RELATION:
            ob = ETL(TABLE_NAME, var.INPUT_DATA)
            ob.etl_process(csvParser.check_header())
示例#11
0
def exp(x):
    """Returns exponential of x, can be used to calculate
    exponential of Variable instance

    INPUTS
    =======
    x: numeric or Variable, element-wise for lists, arrays, or similar structures

    RETURNS
    ========
    value: numeric or Variable, element-wise for lists, arrays, or similar structures

    NOTES
    =====
    PRE:
         - x is either numeric or Variable types

    POST:
         - x is not changed by this function
         - if x is Variable instance, returns a new Variable instance
         - if x is numeric, returns numeric
         - should return value greater than 0

    EXAMPLES
    =========
    >>> try:
    ...     from variables import Variable
    ... except:
    ...     from AutoDiff.variables import Variable
    >>> try:
    ...     import AD_numpy as np
    ... except:
    ...     import AutoDiff.AD_numpy as np
    >>> a = Variable('a', 0)
    >>> x = np.exp(a)
    >>> x.val
    1.0
    >>> x.der
    {'a': 1.0}
    >>> np.exp(0)
    1.0
    """
    try:
        return Variable(x.name, np.exp(x.val),
                        {k: v * np.exp(x.val)
                         for (k, v) in x.der.items()}, False)
    except AttributeError:
        return np.exp(x)
示例#12
0
def tanh(x):
    """Returns hyberbolic tanh of x, can be used to calculate tanh of
    Variable instance

    INPUTS
    =======
    x: numeric or Variable, element-wise for lists, arrays, or similar structures

    RETURNS
    ========
    value: numeric or Variable, element-wise for lists, arrays, or similar structures

    NOTES
    =====
    PRE:
         - x is either numeric or Variable types

    POST:
         - x is not changed by this function
         - if x is Variable instance, returns a new Variable instance
         - if x is numeric, returns numeric
         - should return value between -1 and 1

    EXAMPLES
    =========
    >>> try:
    ...     from variables import Variable
    ... except:
    ...     from AutoDiff.variables import Variable
    >>> try:
    ...     import AD_numpy as np
    ... except:
    ...     import AutoDiff.AD_numpy as np
    >>> a = Variable('a', 1)
    >>> x = np.tanh(a)
    >>> x.val
    0.7615941559557649
    >>> x.der
    {'a': 0.4199743416140261}
    >>> np.tanh(0)
    0.0
    """
    try:
        return Variable(x.name, np.tanh(
            x.val), {k: v / (np.cosh(x.val)**2)
                     for (k, v) in x.der.items()}, False)
    except AttributeError:
        return np.tanh(x)
示例#13
0
def cosh(x):
    """Returns hyberbolic cosh of x, can be used to calculate cosh of
    Variable instances

    INPUTS
    =======
    x: numeric or Variable, element-wise for lists, arrays, or similar structures

    RETURNS
    ========
    value: numeric or Variable, element-wise for lists, arrays, or similar structures

    NOTES
    =====
    PRE:
         - x is either numeric or Variable types

    POST:
         - x is not changed by this function
         - if x is Variable instance, returns a new Variable instance
         - if x is numeric, returns numeric
         - should return value greater than 1

    EXAMPLES
    =========
    >>> try:
    ...     from variables import Variable
    ... except:
    ...     from AutoDiff.variables import Variable
    >>> try:
    ...     import AD_numpy as np
    ... except:
    ...     import AutoDiff.AD_numpy as np
    >>> a = Variable('a', 1)
    >>> x = np.cosh(a)
    >>> x.val
    1.5430806348152437
    >>> x.der
    {'a': 1.1752011936438014}
    >>> np.cosh(0)
    1.0
    """
    try:
        return Variable(x.name, np.cosh(x.val),
                        {k: v * np.sinh(x.val)
                         for (k, v) in x.der.items()}, False)
    except AttributeError:
        return np.cosh(x)
示例#14
0
    def __init__(self, root_path, module_name, name):
        assert isinstance(module_name, str)
        assert isinstance(name, str)

        self.root_path = root_path
        self.module_name = module_name
        self.name = name
        self.artefacts = Variable()
        self.prerequisites = Variable()
        self.depends_on = Variable()
        self.run_before = Variable()
        self.run_after = Variable()
        self.resources = Variable()
        self.visible_in = Variable()
示例#15
0
def arcsinh(x):
    """Returns hyberbolic inverse arcsinh of x, can be used to calculate
    arcsinh of Variable instance

    INPUTS
    =======
    x: numeric or Variable, element-wise for lists, arrays, or similar structures

    RETURNS
    ========
    value: numeric or Variable, element-wise for lists, arrays, or similar structures

    NOTES
    =====
    PRE:
         - x is either numeric or Variable types

    POST:
         - x is not changed by this function
         - if x is Variable instance, returns a new Variable instance
         - if x is numeric, returns numeric

    EXAMPLES
    =========
    >>> try:
    ...     from variables import Variable
    ... except:
    ...     from AutoDiff.variables import Variable
    >>> try:
    ...     import AD_numpy as np
    ... except:
    ...     import AutoDiff.AD_numpy as np
    >>> a = Variable('a', 1)
    >>> x = np.arcsinh(a)
    >>> x.val
    0.881373587019543
    >>> x.der
    {'a': 0.7071067811865475}
    >>> np.arcsinh(0)
    0.0
    """
    try:
        return Variable(x.name, np.arcsinh(
            x.val), {k: v / np.sqrt(1 + x.val**2)
                     for (k, v) in x.der.items()}, False)
    except AttributeError:
        return np.arcsinh(x)
示例#16
0
def define_and_print(c, string):
    """Defines a new variable with an unique name
        for 'string', and prints it to the screen
    """
    if not string or not string.strip('"'):
        return

    # First try finding an existing string variable with the same content
    # that we wish, if it exists, don't waste memory creating yet another one
    enc, _ = Variable.escape_string(string)
    var = next((v for v in c.variables.values() if v.value == enc), None)
    if not var:
        # No luck, create a new variable TODO This will escape the string again!
        var = Variable(c.get_uid(), 'string', string)
        c.add_variable(var)

    # Now we have an existing variable with the content we want to show
    c.add_code([f'lea dx, {var.name}', f'int 21h'])
示例#17
0
文件: base.py 项目: Sharkkii/shaDL
    def __call__(self, *inputs):
        """
        __call__: Variables -> a Variable | tuple(Variables)
        """
        self.inputs = inputs
        for var in self.inputs:
            var.children = self

        tmp_inputs = tuple([x.data for x in self.inputs])
        tmp_outputs = self.forward(*tmp_inputs)
        tmp_outputs = tmp_outputs if isinstance(tmp_outputs,
                                                tuple) else (tmp_outputs, )

        self.outputs = tuple([Variable(x) for x in tmp_outputs])
        for var in self.outputs:
            var.parent = self
            var.generation = max([x.generation for x in inputs]) + 1
        outputs = self.outputs if (len(self.outputs) > 1) else self.outputs[0]

        return outputs
示例#18
0
def sqrt(x):
    """Returns square root of x, can be used to calculate
    square root of Variable instance

    INPUTS
    =======
    x: numeric or Variable, element-wise for lists, arrays, or similar structures

    RETURNS
    ========
    value: numeric or Variable, element-wise for lists, arrays, or similar structures

    NOTES
    =====
    PRE:
         - x is either numeric or Variable types
         - x should be greater than or equal to 0

    POST:
         - x is not changed by this function
         - if x is Variable instance, returns a new Variable instance
         - if x is numeric, returns numeric
         - should raise ValueError if x is less than 0

    EXAMPLES
    =========
    >>> try:
    ...     from variables import Variable
    ... except:
    ...     from AutoDiff.variables import Variable
    >>> try:
    ...     import AD_numpy as np
    ... except:
    ...     import AutoDiff.AD_numpy as np
    >>> a = Variable('a', 1)
    >>> x = np.sqrt(a)
    >>> x.val
    1.0
    >>> x.der
    {'a': 0.5}
    >>> b = Variable('b', -1)
    >>> try:
    ...     np.sqrt(b)
    ... except ValueError as e:
    ...     print(e)
    math domain error
    >>> np.sqrt(4)
    2.0
    >>> try:
    ...     np.sqrt(-1)
    ... except ValueError as e:
    ...     print(e)
    math domain error
    """
    try:
        if x.val < 0:
            raise ValueError('math domain error')
        return Variable(x.name, np.sqrt(
            x.val), {k: v * 0.5 / np.sqrt(x.val)
                     for (k, v) in x.der.items()}, False)
    except AttributeError:
        if x < 0:
            raise ValueError('math domain error')
        return np.sqrt(x)
示例#19
0
def define_integer_to_string(c):
    """Defines the 'integer_to_string' built-in function.
        AX is used to pass the input parameter, number to convert,
        and is lost in the progress. Caller is responsibe to save it.

        Returns the Function header.
    """
    vname = '_v_itos'
    fname = '_f_itos'
    function = Function(fname, params=['ax'], returns=vname, mangle=False)

    # Early exit if it's already defined
    if fname in c.functions:
        return function

    maxlen = len(f'-{0x7FFF}$')
    c.add_variable(Variable(vname, 'byte', '?', vector_size=maxlen))

    c.begin_function(function)
    c.add_code('''push bx
    push cx
    push dx
    push di

    xor cx, cx  ; Digit counter
    mov bx, 10  ; Cannot divide by inmediate
    lea di, _v_itos  ; Destination string index

    ; Special case, number is negative
    cmp ax, 0
    jge _f_itos_loop1

    mov [di], '-'
    inc di
    neg ax

_f_itos_loop1:
    ; DX is considered on division, reset it to zero
    xor dx, dx
    div bx
    add dl, '0'
    ; From less significant to most significant (use stack to reverse)
    push dx
    inc cx
    cmp ax, 0
    jg _f_itos_loop1

_f_itos_loop2:
    ; Reverse the stored digits back from the stack
    pop [di]
    inc di
    loop _f_itos_loop2

    ; Strings must end with the dollar sing
    mov [di], '$'

    pop di
    pop dx
    pop cx
    pop bx''')
    c.close_block()

    return function
示例#20
0
def log2(x):
    """Returns logarithm to the base 2 of x, can be used to calculate
    logarithm to the base 2 of Variable instance

    INPUTS
    =======
    x: numeric or Variable, element-wise for lists, arrays, or similar structures

    RETURNS
    ========
    value: numeric or Variable, element-wise for lists, arrays, or similar structures

    NOTES
    =====
    PRE:
         - x is either numeric or Variable types
         - x should be greater than 0

    POST:
         - x is not changed by this function
         - if x is Variable instance, returns a new Variable instance
         - if x is numeric, returns numeric
         - should raise ValueError if x less than 0
         - should raise ZeroDivisionErrorif x equals 0

    EXAMPLES
    =========
    >>> try:
    ...     from variables import Variable
    ... except:
    ...     from AutoDiff.variables import Variable
    >>> try:
    ...     import AD_numpy as np
    ... except:
    ...     import AutoDiff.AD_numpy as np
    >>> a = Variable('a', 1)
    >>> x = np.log2(a)
    >>> x.val
    0.0
    >>> x.der
    {'a': 1.4426950408889634}
    >>> b = Variable('b', -1)
    >>> try:
    ...     np.log2(b)
    ... except ValueError as e:
    ...     print(e)
    math domain error
    >>> np.log2(2)
    1.0
    >>> try:
    ...     np.log2(-1)
    ... except ValueError as e:
    ...     print(e)
    math domain error
    """
    try:
        if x.val <= 0:
            raise ValueError('math domain error')
        return Variable(
            x.name, np.log2(x.val),
            {k: v * np.log2(np.exp(1)) / x.val
             for (k, v) in x.der.items()}, False)
    except AttributeError:
        if x <= 0:
            raise ValueError('math domain error')
        return np.log2(x)
def test_variable_scalar_multiple_divide():
    '''
    object.__mul__(), object.__truediv__(), object.__imul__(), object.__idiv__()
    '''
    # case 0: build variables
    x = Variable('x',2)
    y = Variable('y',-5)
    z = Variable('z',0)

    # case 1: right multiple
    f1 = 2*x
    assert (f1.val == 4)
    assert (f1.jacobian() == {'x':2})
    assert (f1.partial_der(x) == 2)
    assert (f1.partial_der(y) == 0)

    # case 2: left add
    f2 = y*3
    assert (f2.val == -15)
    assert (f2.jacobian() == {'y':3})
    assert (f2.partial_der(x) == 0)
    assert (f2.partial_der(y) == 3)

    # case 3: variable+variable
    f3 = x*y
    assert (f3.val == -10)
    assert (f3.jacobian() == {'x':-5, 'y':2})
    assert (f3.partial_der(x) == -5)
    assert (f3.partial_der(y) == 2)

    # case 4: right divide
    f1 = x/2
    assert (f1.val == 1)
    assert (f1.jacobian() == {'x':1/2})
    assert (f1.partial_der(x) == 1/2)
    assert (f1.partial_der(y) == 0)

    # case 5: left divide
    f2 = 10+2*5/y
    assert (f2.val == 8)
    assert (f2.jacobian() == {'y':-0.4})
    assert (f2.partial_der(x) == 0)
    assert (f2.partial_der(y) == -0.4)

    # case 6: variable/variable
    f3 = x/y
    assert (f3.val == -0.4)
    assert (f3.jacobian() == {'x':-0.2, 'y':-0.08})
    assert (f3.partial_der(x) == -0.2)
    assert (f3.partial_der(y) == -0.08)

    # case 7: divide 0:
    with pytest.raises(ZeroDivisionError):
        f4 = x/0

    with pytest.raises(ZeroDivisionError):
        f5 = 2/z

    with pytest.raises(ZeroDivisionError):
        f6 = x/z

    with pytest.raises(ZeroDivisionError):
        f5 = 29/(0*x)

    # case8: imul
    # f3 was x/y
    '''
def test_variable_scalar_add_minus():
    '''
    object.__add__(), object.__sub__(), object.__pos__(), object.__neg__(),
    object.__iadd__(), object.__isub__()
    '''
    # case 0: build variables
    x = Variable('x',2)
    y = Variable('y',-5)

    # case 1: right add
    f1 = x+2
    assert (f1.val == 4)
    assert (f1.jacobian() == {'x':1})
    assert (f1.partial_der(x) == 1)
    assert (f1.partial_der(y) == 0)

    # case 2: left add
    f2 = 10+2*8+y
    assert (f2.val == 21)
    assert (f2.jacobian() == {'y':1})
    assert (f2.partial_der(x) == 0)
    assert (f2.partial_der(y) == 1)

    # case 3: variable+variable
    f3 = 3+x+y-2
    assert (f3.val == -2)
    assert (f3.jacobian() == {'x':1, 'y':1})
    assert (f3.partial_der(x) == 1)
    assert (f3.partial_der(y) == 1)

    # case 4: right minus
    f1 = x-2
    assert (f1.val == 0)
    assert (f1.jacobian() == {'x':1})
    assert (f1.partial_der(x) == 1)
    assert (f1.partial_der(y) == 0)

    # case 5: left minus

    f2 = 10+2*8-y
    assert (f2.val == 31)
    assert (f2.jacobian() == {'y':-1})
    assert (f2.partial_der(x) == 0)
    assert (f2.partial_der(y) == -1)


    # case 6: variable+variable

    f3 = 3-x-y-2
    assert (f3.val == 4)
    assert (f3.jacobian() == {'x':-1, 'y':-1})
    assert (f3.partial_der(x) == -1)
    assert (f3.partial_der(y) == -1)



    # case 7: positive
    '''
    f4 = +y
    assert (f4.val == -5)
    assert (f4.jacobian() == [1])
    assert (f4.partial_der(x) == 0)
    assert (f4.partial_der(y) == 1)

    f4 = +x
    assert (f4.val == 2)
    assert (f4.jacobian() == [1])
    assert (f4.partial_der(x) == 1)
    assert (f4.partial_der(y) == 0)
    '''
    # case 8: negative
    f5 = -y
    assert (f5.val == 5)
    assert (f5.jacobian() == {'y':-1})
    assert (f5.partial_der(x) == 0)
    assert (f5.partial_der(y) == -1)

    f5 = -x
    assert (f5.val == -2)
    assert (f5.jacobian() == {'x':-1})
    assert (f5.partial_der(x) == -1)
    assert (f5.partial_der(y) == 0)
示例#23
0
 def add_variable(self, variable_name, possible_values):
     self.variables[variable_name] = Variable(variable_name, possible_values)
示例#24
0
 def __init__(self):
     self.sources = Variable()
     self.include_dirs = Variable()
     self.compiler_flags = Variable()
     self.built_targets = Variable()
示例#25
0
def test_numpy_scalar_add_minus():
      # case 0: build variables
    x = Variable('x', 2)
    y = Variable('y', -5)

    # case 1: right add
    f1 = anp.add(x,2)
    assert (f1.val == 4)
    assert (f1.jacobian() == {'x': 1})
    assert (f1.partial_der(x) == 1)
    assert (f1.partial_der(y) == 0)

    # case 2: left add
    f2 = anp.add(10+2*8,y)
    assert (f2.val == 21)
    assert (f2.jacobian() == {'y': 1})
    assert (f2.partial_der(x) == 0)
    assert (f2.partial_der(y) == 1)

    # case 3: variable+variable
    f3 = anp.add(3+x,y-2)
    assert (f3.val == -2)
    assert (f3.jacobian() == {'x': 1, 'y': 1})
    assert (f3.partial_der(x) == 1)
    assert (f3.partial_der(y) == 1)

    # case 4: right minus
    f1 = anp.add(x,-2)
    assert (f1.val == 0)
    assert (f1.jacobian() == {'x': 1})
    assert (f1.partial_der(x) == 1)
    assert (f1.partial_der(y) == 0)

    # case 5: left minus

    f2 = anp.add(10+2*8,-y)
    assert (f2.val == 31)
    assert (f2.jacobian() == {'y': -1})
    assert (f2.partial_der(x) == 0)
    assert (f2.partial_der(y) == -1)

    # case 6: variable+variable
    '''
    f3 = anp.add(3-x,-y-2)
    assert (f3.val == 4)
    print(f3.jacobian())
    assert (f3.jacobian() == {'x': -1, 'y': -1})
    assert (f3.partial_der(x) == -1)
    assert (f3.partial_der(y) == -1)
    '''

    # case 7: positive
    '''
    f4 = anp.+y
    assert (f4.val == -5)
    assert (f4.jacobian() == [1])
    assert (f4.partial_der(x) == 0)
    assert (f4.partial_der(y) == 1)

    f4 = +x
    assert (f4.val == 2)
    assert (f4.jacobian() == [1])
    assert (f4.partial_der(x) == 1)
    assert (f4.partial_der(y) == 0)
    '''

    # case 8: negative
    '''
    f5 = anp.negative(y)
    assert (f5.val == 5)
    assert (f5.jacobian() == {'y':-1})
    assert (f5.partial_der(x) == 0)
    assert (f5.partial_der(y) == -1)
    '''
    f5 = anp.negative(x)
    assert (f5.val == -2)
    assert (f5.jacobian() == {'x':-1})
    assert (f5.partial_der(x) == -1)
    assert (f5.partial_der(y) == 0)
示例#26
0
def arccosh(x):
    """Returns hyberbolic inverse arccosh of x, can be used to calculate
    arccosh of Variable instance

    INPUTS
    =======
    x: numeric or Variable, element-wise for lists, arrays, or similar structures

    RETURNS
    ========
    value: numeric or Variable, element-wise for lists, arrays, or similar structures

    NOTES
    =====
    PRE:
         - x is either numeric or Variable types
         - x must be greater than 1

    POST:
         - x is not changed by this function
         - if x is Variable instance, returns a new Variable instance
         - if x is numeric, returns numeric
         - should return ValueError if x lesser than 1
         - should return value greater than 0

    EXAMPLES
    =========
    >>> try:
    ...     from variables import Variable
    ... except:
    ...     from AutoDiff.variables import Variable
    >>> try:
    ...     import AD_numpy as np
    ... except:
    ...     import AutoDiff.AD_numpy as np
    >>> a = Variable('a', 2)
    >>> x = np.arccosh(a)
    >>> x.val
    1.3169578969248166
    >>> x.der
    {'a': 0.5773502691896258}
    >>> b = Variable('b', 0)
    >>> try:
    ...     np.arccosh(b)
    ... except ValueError as e:
    ...     print(e)
    math domain error
    >>> np.arccosh(1)
    0.0
    >>> try:
    ...     np.arccosh(0)
    ... except ValueError as e:
    ...     print(e)
    math domain error
    """

    try:
        if x.val <= 1:
            raise ValueError('math domain error')
        return Variable(x.name, np.arccosh(
            x.val), {k: v / np.sqrt(x.val**2 - 1)
                     for (k, v) in x.der.items()}, False)
    except AttributeError:
        if x < 1:
            raise ValueError('math domain error')
        return np.arccosh(x)
示例#27
0
def arccos(x):
    """Returns trigonometric arccos of x, can be used to calculate arccos of
    Variable instance

    INPUTS
    =======
    x: numeric or Variable, element-wise for lists, arrays, or similar structures

    RETURNS
    ========
    value: numeric or Variable, element-wise for lists, arrays, or similar structures

    NOTES
    =====
    PRE:
         - x is either numeric or Variable types
         - x should be between -1 and 1

    POST:
         - x is not changed by this function
         - if x is Variable instance, returns a new Variable instance
         - if x is numeric, returns numeri
         - raises RuntimeWarning if x is not between -1 and 1
         - should return value between 0 and pi

    EXAMPLES
    =========
    >>> try:
    ...     from variables import Variable
    ... except:
    ...     from AutoDiff.variables import Variable
    >>> try:
    ...     import AD_numpy as np
    ... except:
    ...     import AutoDiff.AD_numpy as np
    >>> a = Variable('a', 0)
    >>> x = np.arccos(a)
    >>> x.val
    1.5707963267948966
    >>> x.der
    {'a': -1.0}
    >>> b = Variable('b', 2)
    >>> try:
    ...     np.arccos(b)
    ... except ValueError as e:
    ...     print(e)
    math domain error
    >>> np.arccos(1)
    0.0
    >>> try:
    ...     np.arccos(2)
    ... except ValueError as e:
    ...     print(e)
    math domain error
    """
    try:
        if x.val < -1 or x.val > 1:
            raise ValueError('math domain error')
        return Variable(
            x.name, np.arccos(x.val),
            {k: -v / np.sqrt(1 - x.val**2)
             for (k, v) in x.der.items()}, False)
    except AttributeError:
        if x < -1 or x > 1:
            raise ValueError('math domain error')
        return np.arccos(x)
示例#28
0
def arctanh(x):
    """Returns hyberbolic inverse arccosh of x, can be used to calculate
    arccosh of Variable instance

    INPUTS
    =======
    x: numeric or Variable, element-wise for lists, arrays, or similar structures

    RETURNS
    ========
    value: numeric or Variable, element-wise for lists, arrays, or similar structures

    NOTES
    =====
    PRE:
         - x is either numeric or Variable types
         - x must be between -1 and 1

    POST:
         - x is not changed by this function
         - if x is Variable instance, returns a new Variable instance
         - if x is numeric, returns numeric
         - should return ValueError if x not within domain

    EXAMPLES
    =========
    >>> try:
    ...     from variables import Variable
    ... except:
    ...     from AutoDiff.variables import Variable
    >>> try:
    ...     import AD_numpy as np
    ... except:
    ...     import AutoDiff.AD_numpy as np
    >>> a = Variable('a', 0)
    >>> x = np.arctanh(a)
    >>> x.val
    0.0
    >>> x.der
    {'a': 1.0}
    >>> b = Variable('b', 2)
    >>> try:
    ...     np.arctanh(b)
    ... except ValueError as e:
    ...     print(e)
    math domain error
    >>> np.arctanh(0)
    0.0
    >>> try:
    ...     np.arctanh(2)
    ... except ValueError as e:
    ...     print(e)
    math domain error
    """
    try:
        if x.val <= -1 or x.val >= 1:
            raise ValueError('math domain error')
        return Variable(x.name, np.arctanh(x.val),
                        {k: v / (1 - x.val**2)
                         for (k, v) in x.der.items()}, False)
    except AttributeError:
        if x <= -1 or x >= 1:
            raise ValueError('math domain error')
        return np.arctanh(x)
示例#29
0
                       bg="cadetblue",
                       font=("arial", 15, "bold"),
                       width=11,
                       pady=25,
                       bd=3,
                       relief=SUNKEN).grid(row=0, column=1, padx=5, pady=5)
        total = Button(f7,
                       text="Clear",
                       fg="white",
                       bg="cadetblue",
                       font=("arial", 15, "bold"),
                       width=10,
                       pady=25,
                       bd=3,
                       relief=SUNKEN).grid(row=0, column=2, padx=5, pady=5)
        total = Button(f7,
                       text="Exit",
                       fg="white",
                       bg="cadetblue",
                       font=("arial", 15, "bold"),
                       width=10,
                       pady=25,
                       bd=3,
                       relief=SUNKEN).grid(row=0, column=3, padx=5, pady=5)


root = Tk()
var = Variable()
obj = Bill_APP(root, var)
root.mainloop()
示例#30
0
def test_numpy_scalar_multiple_divide():
    '''
    object.__mul__(), object.__truediv__(), object.__imul__(), object.__idiv__()
    '''
    # case 0: build variables
    x = Variable('x', 2)
    y = Variable('y', -5)
    z = Variable('z', 0)

    # case 1: right multiple
    f1 = anp.multiply(2,x)
    assert (f1.val == 4)
    assert (f1.jacobian() == {'x': 2})
    assert (f1.partial_der(x) == 2)
    assert (f1.partial_der(y) == 0)

    # case 2: left add
    f2 = anp.multiply(y,3)
    assert (f2.val == -15)
    assert (f2.jacobian() == {'y': 3})
    assert (f2.partial_der(x) == 0)
    assert (f2.partial_der(y) == 3)

    # case 3: variable+variable
    f3 = anp.multiply(x,y)
    assert (f3.val == -10)
    assert (f3.jacobian() == {'x': -5, 'y': 2})
    assert (f3.partial_der(x) == -5)
    assert (f3.partial_der(y) == 2)

    # case 4: right divide
    f1 = anp.divide(x,2)
    assert (f1.val == 1)
    assert (f1.jacobian() == {'x': 1/2})
    assert (f1.partial_der(x) == 1/2)
    assert (f1.partial_der(y) == 0)


    # case 6: variable/variable
    f3 = anp.divide(x,y)
    assert (f3.val == -0.4)
    assert (f3.jacobian() == {'x': -0.2, 'y': -0.08})
    assert (f3.partial_der(x) == -0.2)
    assert (f3.partial_der(y) == -0.08)

    # case 7: divide 0:
    with pytest.raises(ZeroDivisionError):
        f4 = anp.divide(x,0)

    with pytest.raises(ZeroDivisionError):
        f5 = anp.divide(2,z)

    with pytest.raises(ZeroDivisionError):
        f6 = anp.divide(x,z)

    with pytest.raises(ZeroDivisionError):
        f5 = anp.divide(29,0*x)

    # case8: imul
    # f3 was x/y
    '''