Ejemplo n.º 1
0
def make_function(inputs, outputs, updates=None, givens=None):
    if isinstance(outputs, list):
        return Function(inputs, outputs, updates, givens=givens)
    elif isinstance(outputs, (dict, collections.OrderedDict)):
        raise NotImplemented()
    else:
        f = Function(inputs, [outputs], updates, givens=givens)
        return lambda *args, **kwargs: f(*args, **kwargs)[0]
Ejemplo n.º 2
0
    def __init__(self):
        self.functions = {
            'EXP': Function(np.exp),
            'LOG': Function(np.log),
            'SIN': Function(np.sin),
            'COS': Function(np.cos),
            'SQRT': Function(np.sqrt)
        }

        self.operators = {
            'PLUSS': Operator(np.add, 0),
            'GANGE': Operator(np.multiply, 1),
            'DELE': Operator(np.divide, 1),
            'MINUS': Operator(np.subtract, 0)
        }
Ejemplo n.º 3
0
def enclose(function, variable, name=None):
    """Given a function f(x0, x1...), write a function f(x0, x1...) - variable.

    For example, if the argument function corresponds to 'x**2 + sin(y) + c',
    the return function will correspond to '(x**2 + sin(y) + c) - variable'.

    This is useful if, for instance, we have a model with a constraint
    or objective function g(x0, x1...) and need to introduce a new
    variable which is constrained to be equal to the value of g.

    If the argument function is linear (that is, an instance of
    functions.Linear,) so is the return function.

    Otherwise, the first and second derivative caches are preserved,
    and the first derivative wrt variable is filled in.

    """
    if isinstance(function, Linear):
        new_coefficients = {'variable': -1}
        new_coefficients.update(function.coefficients)
        return Linear(new_coefficients, name=name)

    new_expr = '(%s) - %s' % (function.math, variable)
    new_variables = function.variables.copy()
    new_variables.add(variable)
    new_function = Function(new_expr,
                            variables=new_variables,
                            first_derivatives=function._first_derivatives,
                            second_derivatives=function._second_derivatives,
                            name=name)
    new_function._first_derivatives[variable] = '-1.'
    return new_function
Ejemplo n.º 4
0
    def iter_test(self, func_name, dim_count):
        ''' Runs the PSO algorithm given the initialization
            parameters, outputting a list of the best values
            from the run
        '''

        bests = []
        func = Function(func_name)(dim_count)
        self.pop = self._generate_pop(self.size, func)
        p_min = min(self.pop)
        self.best = np.copy(p_min.position)
        self.best_val = p_min.val

        bests.append(self.best_val)
        for _ in xrange(self.gen):
            self.pop = [
                p.map_eval(self.best, self.alpha, self.beta) for p in self.pop
            ]
            p_min = min(self.pop)

            if p_min.val < self.best_val:
                self.best = np.copy(p_min.position)
                self.best_val = p_min.val

            bests.append(self.best_val)

        return np.array(bests)
Ejemplo n.º 5
0
    def set_objective(self, objective_id, expression):
        """ Set the objective function of the problem. 

        The existing objective function will be lost.

        """

        self.objective_function = Function(expression, name=objective_id)
Ejemplo n.º 6
0
    def iter_test(self, func_name, dim, iterations, style=BOLTZMANN):
        ''' initialize our simulated annealing machine
        '''

        objfunc = Function(func_name)(dim)
        schedule = self._get_schedule(style)
        prob = self._get_prob_distr(style)

        return self._test_anneal(objfunc, schedule, prob, iterations)
Ejemplo n.º 7
0
    def run(self, func_name, dim, style=BOLTZMANN):
        ''' initialize our simulated annealing machine
        '''

        objfunc = Function(func_name)(dim)
        schedule = self._get_schedule(style)
        prob = self._get_prob_distr(style)

        state_final = self._anneal(objfunc, schedule, prob)
        return state_final
Ejemplo n.º 8
0
    def set_unitary(self, V):
        """Parse input and set the unitary operator attributes.
        This also sets up the potential function
        attributes in the process.
        """
        if isinstance(V, str):
            try:
                if V.strip().replace(".",
                                     "").replace("-",
                                                 "").replace("e",
                                                             "").isnumeric():
                    self.V_name = ""
                    self.V_latex = str(np.round(float(V), 2))
                    if float(V) == 0:
                        V = 1e-30
                        V_f = float(V) * np.ones([self.N])
                        self.U_t = UnitaryOperator1D(np.copy(V_f))
                        self.V_x = 0.0 * V_f
                    else:
                        V_f = scale(float(V) * np.ones([self.N]), 15)
                        self.V_x = V_f
                        self.U_t = UnitaryOperator1D(np.copy(V_f))
                        self.V_latex = "%sk" % (self.V_latex) if V_f[0] > 0\
                                       else " %sk" % (self.V_latex)
                    self.V_params = {}
                    self.V_base = None
                else:
                    V = V.replace("^", "**")
                    f = Function(V, "x")
                    self.V = lambda x: f(x, *f.get_tupled_default_values())
                    self.V_x = scale(self.V(self.x), 15)
                    self.V_name = str(f)
                    self.V_latex = "$" + f.multiply_latex_string("k") + "$"
                    self.U_t = UnitaryOperator1D(self.V)
                    self.V_base = f
                    self.V_params = f.get_enumerated_default_values()
            except (TypeError, AttributeError, SyntaxError, ValueError,
                    NameError) as E:
                print(E)
        elif isinstance(V, np.ndarray):
            self.V_params = {}
            self.V_base = None
            self.V = None
            self.V_x = scale(V, 15)
            self.V_name = "V(x)"
            self.V_latex = "$V(x)$"
            self.U_t = UnitaryOperator1D(V)
        else:
            print("Unable to parse input")

        if hasattr(self, "lines"):
            self.update_draw_potential()
Ejemplo n.º 9
0
    def add_constraint(self, function_id, expression, value=None):
        """ Add the expression to the problem as a constraint function. 

        Optionally, set the value to which the function is constrained,
        (a scalar, or (lower bound, upper bound) tuple of scalars or Nones.)

        """
        self.constraints.set(function_id, Function(expression,
                                                   name=function_id))
        if value is not None:
            if isinstance(value, tuple):
                self.set_inequality(function_id, *value)
            else:
                self.set_equality(function_id, value)
Ejemplo n.º 10
0
def functiondef(c, m):
    """Function definition. For instance:
        function myMethod(ax) returns dx {
            ; code
        }
    """
    f = Function(name=m.group(1), params=m.group(2), returns=m.group(3))
    # Ensure that the function doesn't have repeated parameters
    for i in range(len(f.params)):
        for j in range(i + 1, len(f.params)):
            if f.params[i] == f.params[j]:
                raise ValueError(f'Parameter "{f.params[i]}" used twice on '
                                 f'"{f.name}" definition (positions {i+1} '
                                 f'and {j+1})')
    c.begin_function(f)
Ejemplo n.º 11
0
    def run(self, func_name, dim_count):
        ''' runs the simulation given the function name
            and dimension count
        '''

        func = Function(func_name)(dim_count)
        self.pop = self._generate_pop(self.size, func)
        self.best = min(self.pop)

        for _ in xrange(self.gen):
            self.pop = [
                p.map_eval(self.best.position, self.alpha, self.beta)
                for p in self.pop
            ]
            self.best = min(self.pop)

        return self.best
Ejemplo n.º 12
0
def test(func_name, dimension_count, iteration_count, sample_count, cpu_count):
    ''' this function will run all metaheurstic algorithms against
        the given function for the specified amount of samples.
        the mean value will be output in a file for each algorithm
        for each iteration, showcasing the convergence over time
    '''

    fun = Function(func_name)(dimension_count)
    xstar = fun.eval(fun.xstar)

    f_n = Population(iteration_count, 40, 0.1, 1.0, 1.0)
    f_b = Population(iteration_count, 40, 0.5, 1.0, 1.0)
    f_c = Population(iteration_count, 40, 1.0, 1.0, 1.0)
    pso = PSO(iteration_count, 40, 2.0, 2.0)
    sma = SA(1000, 0.01)
    samples = [[], [], [], [], []]

    calc_mean = lambda a: np.mean(np.array(a), axis=0)

    with open('./data/' + func_name + '.dat', 'w') as out_file:
        try:
            out_file.write('iters   xstar   fa  faboltz facauchy    pso sa\n')
            for _ in range(sample_count):
                samples[0].append(
                    f_n.iter_test(func_name, dimension_count, Population.NONE,
                                  cpu_count))
                samples[1].append(
                    f_b.iter_test(func_name, dimension_count,
                                  Population.BOLTZMANN, cpu_count))
                samples[2].append(
                    f_c.iter_test(func_name, dimension_count,
                                  Population.CAUCHY, cpu_count))
                samples[3].append(pso.iter_test(func_name, dimension_count))
                samples[4].append(
                    sma.iter_test(func_name, dimension_count, iteration_count,
                                  SA.CAUCHY))

            # we add 1 to count for the initial case
            final = np.array([np.arange(iteration_count + 1)] +
                             [np.array([xstar] * (iteration_count + 1))] +
                             [calc_mean(data) for data in samples])
            for line in final.T:
                line.toout_file(file, sep='\t')
                out_file.write('\n')
        except Exception as exc:
            out_file.write(str(exc))
Ejemplo n.º 13
0
 def set_wavefunction(self, psi, normalize=True):
     """Parse input to set the wavefunction attributes.
     """
     if isinstance(psi, str):
         try:
             if psi.strip().replace(".",
                                    "").replace("-",
                                                "").replace("e",
                                                            "").isnumeric():
                 psi_x = float(psi) * np.ones([self.N])
                 self.psi_name = psi
                 self.psi_latex = "$%s$" % psi
                 self.psi = Wavefunction1D(psi_x)
                 self._msg = "$\psi(x, 0) =$ %s" % self.psi_latex
                 self._msg_i = 45
                 if normalize:
                     self.psi.normalize()
                 self.psi_base = None
                 self.psi_params = {}
             else:
                 psi = psi.replace("^", "**")
                 f = Function(psi, "x")
                 self.psi_base = f
                 psi_func = lambda x: f(x, *f.get_tupled_default_values())
                 self.psi_name = str(f)
                 self.psi_latex = "$" + f.latex_repr + "$"
                 self.psi = Wavefunction1D(psi_func)
                 self.psi_params = f.get_enumerated_default_values()
                 self._msg = r"$\psi(x, 0) =$ %s" % self.psi_latex
                 self._msg_i = 45
                 if normalize:
                     self.psi.normalize()
         except (TypeError, AttributeError, SyntaxError, ValueError,
                 NameError) as E:
             print(E)
     elif isinstance(psi, np.ndarray):
         # self.psi_base = None
         # self.psi_params = {}
         self.psi = Wavefunction1D(psi)
         self.psi_name = "wavefunction"
         self.psi_latex = "$\psi(x)$"
         if normalize:
             self.psi.normalize()
     else:
         print("Unable to parse input")
Ejemplo n.º 14
0
    def _prepare_run(self, func_name, dimension_count, style):
        ''' this prepares the environment before we begin
            a simulation run
        '''

        # get the objective function
        func = Function(func_name)(dimension_count)

        # create our populations
        self.pop = self._generate_pop(self.size, func)
        self.oldpop = self._generate_pop(self.size, func)

        # scale our gamma
        self.gamma = self.gamma0 / ((func.maxs[0] - func.mins[0])**self.m)

        # create our schedule for alpha
        update = self._get_schedule(style)

        # return coords and schedule function
        return update
Ejemplo n.º 15
0
def define_set_cursor(c):
    """Defines the 'setcursor' built-in function.
        DH contains the row and DL contains the column.

        Returns the Function header.
    """
    fname = '_f_setc'
    function = Function(fname, params=['dx'], mangle=False)

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

    c.begin_function(function)
    c.add_code('''push ax
    push bx
    mov ah, 2
    mov bh, 0
    int 10h
    pop bx
    pop ax''')
    c.close_block()

    return function
Ejemplo n.º 16
0
import numpy as np
from functions import Function
from dataset.mnist import load_mnist
from layers import Affine, SoftmaxWithLoss, Relu
import matplotlib.pyplot as plt
from collections import OrderedDict  # 有序字典

fun = Function()


class DeepLearn:
    def __init__(self):
        (self.x_train,
         self.t_train), (self.x_test,
                         self.t_test) = load_mnist(flatten=True,
                                                   normalize=True,
                                                   one_hot_label=True)
        self.train_acc_list = []
        self.test_acc_list = []

    def predict(self, x):
        raise NotImplemented

    def cross_entropy_loss(self, x, t):
        y = self.predict(x)
        return fun.cross_entropy_error(y, t)

    def accuracy(self, x, t):
        y = np.argmax(self.predict(x), axis=1)
        t = np.argmax(t, axis=1)
        return np.sum(y == t) / float(x.shape[0])
Ejemplo n.º 17
0
 def visit_fnstmt(self, stmt: FnStmt) -> None:
     """Define a function!
     """
     self.environment[Variable(stmt.name)] = Function(
         stmt.params, stmt.body)
Ejemplo n.º 18
0
pygame.display.set_caption("River Crossing")

# FONTS
TEXT_FONT = pygame.font.SysFont('comics san', 30)
ANNOUNCE_FONT = pygame.font.SysFont('comics san', 200)

RIVER = pygame.rect.Rect(gm_set.RIVER_X, gm_set.RIVER_Y, gm_set.RIVER_WIDTH,
                         gm_set.RIVER_HEIGHT)
AI_BUTTON = pygame.rect.Rect(gm_set.WIDTH - gm_set.OBJECT_WIDTH, 0,
                             gm_set.OBJECT_WIDTH, gm_set.OBJECT_HEIGHT)

# NAMES
names = {"F": "Farmer", "W": "Wolf", "G": "Goat", "C": "Cabbage", "R": "River"}

# GAME
func = Function()

forbidden_states = ({'W', 'G'}, {'G', 'C'}, {'W', 'G', 'C'})
goal = {'F', 'G', 'C', 'W'}

left_bank = {'F', 'G', 'C', 'W'}
right_bank = set()

answer = ''  # ANSWER GET FROM COLLIDE POINT

# AI MODE
AI_MODE = False
AI_DRAW = True

COUNT = 0
Ejemplo n.º 19
0
def generate_one(target):
    SYSCALL_NAMES = [c for c in dir(constants) if c.startswith('SYS_')]

    for syscall in SYSCALL_NAMES:
        name = syscall[4:]

        # Skip anything with uppercase
        if name.lower() != name:
            print 'Skipping %s' % name
            continue

        # Skip anything that starts with 'unused' or 'sys' after stripping
        if name.startswith('unused'):
            print 'Skipping %s' % name
            continue

        function = functions.get(name, None)

        if name.startswith('rt_'):
            name = name[3:]

        # If we can't find a function, just stub it out with something
        # that has a vararg argument.
        if function is None:
            print 'Stubbing out %s' % name
            args = [Argument('int', 0, 'vararg')]
            function = Function('long', 0, name, args)

        # Some syscalls have different names on different architectures,
        # or are superceded.  We try to do the "best" thing at runtime.
        syscalls = fix_syscall_names(syscall)

        # Set up the argument string for Mako
        argument_names = []
        argument_defaults = []

        #

        for arg in function.args:
            argname = fix_bad_arg_names(function, arg)
            default = get_arg_default(arg)

            # Mako is unable to use *vararg and *kwarg, so we just stub in
            # a whole bunch of additional arguments.
            if argname == 'vararg':
                for j in range(5):
                    argname = 'vararg_%i' % j
                    argument_names.append(argname)
                    argument_defaults.append('%s=%s' % (argname, None))
                break

            argument_names.append(argname)
            argument_defaults.append('%s=%s' % (argname, default))

        arguments_default_values = ', '.join(argument_defaults)
        arguments_comma_separated = ', '.join(argument_names)

        string_arguments = []
        array_arguments = []
        arg_docs = []

        for arg in function.args:

            if can_be_array(arg):
                array_arguments.append(arg.name)

            if can_be_string(arg):
                string_arguments.append(arg.name)

            argname = arg.name
            argtype = str(arg.type) + ('*' * arg.derefcnt)
            arg_docs.append('    {argname}({argtype}): {argname}'.format(
                argname=argname, argtype=argtype))

        return_type = str(function.type) + ('*' * function.derefcnt)
        arg_docs = '\n'.join(arg_docs)

        template_variables = {
            'name': name,
            'arg_docs': arg_docs,
            'syscalls': syscalls,
            'arguments_default_values': arguments_default_values,
            'arguments_comma_separated': arguments_comma_separated,
            'return_type': return_type,
            'string_arguments': string_arguments,
            'array_arguments': array_arguments,
            'argument_names': argument_names,
        }

        lines = [
            HEADER,
            DOCSTRING.format(**template_variables),
            ARGUMENTS.format(**template_variables),
            CALL.format(**template_variables)
        ]

        with open(os.path.join(target, name + '.asm'), 'wt+') as f:
            f.write('\n'.join(map(str.strip, lines)))
Ejemplo n.º 20
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
Ejemplo n.º 21
0
 def eval(self, env, memory):
     passedFunc = Function(self.paramID, self.expr)
     return env.putFunc(self.funcID, passedFunc)
Ejemplo n.º 22
0
 def test_RPN_solve(self):
     r = RPN_solver()
     value = r.solve([1, 2, 3, Operator(np.multiply,1), Operator(np.add,0), Function(np.exp)])
     self.assertEqual(value, np.exp(7))
Ejemplo n.º 23
0
WEBHOOK_SSL_CERT = './ssl_cert//webhook_cert.pem'  # Path to the ssl certificate
WEBHOOK_SSL_PRIV = './ssl_cert/webhook_pkey.pem'  # Path to the ssl private key

# Quick'n'dirty SSL certificate generation:
#
# openssl genrsa -out webhook_pkey.pem 2048
# openssl req -new -x509 -days 3650 -key webhook_pkey.pem -out webhook_cert.pem
#
# When asked for "Common Name (e.g. server FQDN or YOUR name)" you should reply
# with the same value in you put in WEBHOOK_HOST

WEBHOOK_URL_BASE = "https://%s:%s" % (WEBHOOK_HOST, WEBHOOK_PORT)
WEBHOOK_URL_PATH = "/%s/" % (API_TOKEN)

bot = telebot.TeleBot(API_TOKEN)
function = Function(bot)


# WebhookServer, process webhook calls
class WebhookServer(object):
    @cherrypy.expose
    def index(self):
        if 'content-length' in cherrypy.request.headers and \
                'content-type' in cherrypy.request.headers and \
                cherrypy.request.headers['content-type'] == 'application/json':
            length = int(cherrypy.request.headers['content-length'])
            json_string = cherrypy.request.body.read(length).decode("utf-8")
            update = telebot.types.Update.de_json(json_string)
            bot.process_new_updates([update])
            return ''
        else:
Ejemplo n.º 24
0
from functions import Function
f = Function(str(input('y = ')))
print('y =',f.factorize())
 def my_function(self, vector):
     self.fcount += 1
     tmp = Function(self.name)(dim)
     return tmp.eval(list(vector))
 def function(self, vector):
     self.fcount += 1
     return Function(self.name)(dim).eval(vector)