Ejemplo n.º 1
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.º 2
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.º 3
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.º 4
0
 def takeFactor(self, tokens):
     now = tokens.front()
     if now == '(':
         try:
             tokens.popFront()
             exp = self.takeExpression(tokens)
             tokens.popFront()
         except IndexError:
             raise InvalidFormula()
         return Paranthesis(exp)
     elif Function.isSingleParamFunction(now) == True:
         try:
             self.functions.add(now)
             tokens.popFront()
             lparan = tokens.popFront()
             exp = self.takeExpression(tokens)
             rparan = tokens.popFront()
             if (lparan == '(' and rparan == ')') == False:
                 raise InvalidFormula()
         except IndexError:
             raise InvalidFormula()
         return Function.determine(now, param=exp)
     elif Function.isDoubleParamFunction(now) == True:
         try:
             self.functions.add(now)
             tokens.popFront()
             lparan = tokens.popFront()
             exp1 = self.takeExpression(tokens)
             tokens.popFront()
             exp2 = self.takeExpression(tokens)
             rparan = tokens.popFront()
             if (lparan == '(' and rparan == ')') == False:
                 raise InvalidFormula()
         except IndexError:
             raise InvalidFormula()
         return Function.determine(now, base=exp1, exponential=exp2)
     elif Number.isNumber(now) == True:
         tokens.popFront()
         return Number.determine(now)
     elif now == '-':
         try:
             tokens.popFront()
             fac = self.takeFactor(tokens)
             term = Term([Number(-1), fac], ['*'])
             expr = Expression([term], [])
         except IndexError:
             raise InvalidFormula()
         return Paranthesis(expr)
     elif Variable.isVariable(now) == True:
         tokens.popFront()
         return Variable(now)
     else:
         raise InvalidFormula()
Ejemplo n.º 5
0
	def takeFactor(self, tokens):
		now = tokens.front()
		if now == '(':
			try:
				tokens.popFront()
				exp = self.takeExpression(tokens)
				tokens.popFront()
			except IndexError:
				raise InvalidFormula()
			return Paranthesis(exp)
		elif Function.isSingleParamFunction(now)==True:
			try:
				self.functions.add(now)
				tokens.popFront()
				lparan=tokens.popFront()
				exp = self.takeExpression(tokens)
				rparan=tokens.popFront()
				if (lparan=='(' and rparan==')')==False:
					raise InvalidFormula()
			except IndexError:
				raise InvalidFormula()
			return Function.determine(now, param=exp)
		elif Function.isDoubleParamFunction(now)==True:
			try:
				self.functions.add(now)
				tokens.popFront()
				lparan=tokens.popFront()	
				exp1 = self.takeExpression(tokens)
				tokens.popFront()
				exp2 = self.takeExpression(tokens)
				rparan=tokens.popFront()
				if (lparan=='(' and rparan==')')==False:
					raise InvalidFormula()
			except IndexError:
				raise InvalidFormula()
			return Function.determine(now, base=exp1, exponential=exp2)
		elif Number.isNumber(now)==True:
			tokens.popFront()
			return Number.determine(now)
		elif now == '-':
			try:
				tokens.popFront()
				fac = self.takeFactor(tokens)
				term=Term([Number(-1),fac],['*'])
				expr=Expression([term],[])
			except IndexError:
				raise InvalidFormula()
			return Paranthesis(expr)
		elif Variable.isVariable(now)==True:
			tokens.popFront()
			return Variable(now)
		else:
			raise InvalidFormula()
Ejemplo n.º 6
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.º 7
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.º 8
0
class Layout_Aesthetics(object):

    layout_theme = {
        "margin": 0,
        "border_width": 1 if Function.screen_count() > 1 else 2,
        "border_focus": Colors.yellow[0],
        "border_normal": Colors.grey[0],
        "fontsize": 12 if Function.screen_count() > 1 else 22,
        "section_fontsize": 12 if Function.screen_count() > 1 else 22,
    }

    floating_layout = Floating(
        border_width=1 if Function.screen_count() > 1 else 2,
        border_focus=Colors.yellow[0],
        border_normal=Colors.black[0],
    )
Ejemplo n.º 9
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.º 10
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.º 11
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.º 12
0
class Widget_Aesthetics(object):

    widget_defaults = dict(
        font=Fonts.base,
        fontsize=12 if Function.screen_count() > 1 else 22,
        padding=0,
        foreground=Colors.white,
        background=Colors.black,
    )
Ejemplo n.º 13
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.º 14
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.º 15
0
    def find_matching_function(self, name, param_count, must_return):
        """Finds and returns the function definition which
            matches with the given 'name' and parameter count.

            If 'must_return' is True, then the function must also
            return some value to be valid
        """
        f = self.functions.get(Function.mangle(name, param_count))
        if f and (not must_return or f.returns is not None):
            return f

        return None
Ejemplo n.º 16
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.º 17
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.º 18
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.º 19
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.º 20
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.º 21
0
    def runTest(self):
        script = kScript(r'E:\packages\file.txt',
                         'myscript',
                         max_line_length=70,
                         compact=True)
        with self.assertRaises(RuntimeError):
            script._generate_code()

        def foo():
            kLog(kLog.array,
                 path=r'E:\packages\pyksp\LogFileReader-master/mylog.nka')
            mw = kMainWindow()
            buttons_area = kWidget(parent=mw)
            buttons_area.place_pct(20, 10, 50, 80)
            ba_bg = kLabel(parent=buttons_area)
            ba_bg.pack(sticky='nswe')
            ba_bg.text <<= ''
            lvl = kLevelMeter(parent=ba_bg, width=20)
            lvl.pack(sticky='nse')
            buttons_area.add_grid(3, 2, 20, 20, 20, 20)
            buttons = [kButton(parent=buttons_area) for b in range(3 * 2)]

            def b_callback(control):
                self.switch(kButton.ids, control.id)
                message(control.id)

            for idx, b in enumerate(buttons):
                b.grid(idx % 3, idx // 3)
                b.bound_callback(b_callback)
            with For(arr=kButton.ids) as seq:
                for item in seq:
                    set_control_par_str(item, 'text', 'mybutton')

        script.main = foo
        localtime = time.asctime(time.localtime(time.time()))
        init_line = '{ Compiled on %s }' % localtime
        self.maxDiff = None
        self.assertEqual(
            unpack_lines(script._generate_code()),
            generated_code.format(init_line=init_line,
                                  fname=Function.get_func_name(self.switch)))
Ejemplo n.º 22
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.º 23
0
 def functions(self, funcObjects):
     fos = (f if hasattr(f, 'isFunction') else Function.fromCppDictionary(f)
            for f in funcObjects)
     self.values['functions'] = OrderedDict()
     for f in fos:
         self.values['functions'].update(f.values)
Ejemplo n.º 24
0
 def __init__(self, name, abbrev=()):
     Function.__init__(self, name)
     self.abbrev = abbrev
Ejemplo n.º 25
0
 def __init__(self, name, abbrev=()):
     Function.__init__(self, name)
     self.abbrev = abbrev
Ejemplo n.º 26
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.º 27
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.º 28
0
 def __init__(self, f):
     Function.__init__(self, None, ["other"], BinaryPyExpr(f))
Ejemplo n.º 29
0
AUDIOAPP = TERM + " -e pulsemixer"  # spawn audio control app
TODOLIST = "dtodo"  # show a list of todos
SPAWNTERM = "via"  # spawn term in specfic wd
NETWORKSELECT = ""
BRIGHUP = "brightnessctl set +5%"
BRIGHDOWN = "brightnessctl set 5%-"
#

# Keys Config {{{
keymap = {
    # ~: System Control: ------------------------------------------------------
    "M-C-r": lazy.restart(),  # Restart Qtile
    "M-C-x": lazy.shutdown(),  # Exit Qtile
    "M-C-d": lazy.spawn("displayselect"),  # Configure Display
    "M-C-a": lazy.spawn(AUDIOAPP),  # Audio controler
    "M-<equal>": Function.volume_ctl(10),  # Audio (+10)
    "M-<minus>": Function.volume_ctl(-10),  # Audio (-10)
    "M-<F2>": lazy.spawn(BRIGHUP),  # brightness (+5)
    "M-<F1>": lazy.spawn(BRIGHDOWN),  # brightness (-5)

    # ~: Windows, Groups and Layout Contol : ----------------------------------
    "M-j": lazy.group.prev_window(),  # Window Focus up
    "M-k": lazy.group.next_window(),  # Window Focus Down
    "M-C-j": lazy.layout.shuffle_up(),  # Window Move up
    "M-C-k": lazy.layout.shuffle_down(),  # Window Move Down
    "M-C-q": lazy.window.kill(),  # Quit Force
    "M-q": lazy.window.kill(),  # Quit Normal
    "M-f": lazy.window.toggle_fullscreen(),  # Window Fullscreen
    "M-i": lazy.layout.shrink(),  # Window Shrink
    "M-o": lazy.layout.grow(),  # Window Grow
    "M-n": lazy.layout.normalize(),
Ejemplo n.º 30
0
 def my_function(self, vector):
     self.fcount += 1
     tmp = Function(self.name)(dim)
     return tmp.eval(list(vector))
Ejemplo n.º 31
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.º 32
0
    def init_keys(self, my_term, script_path, mod):

        return [
            # Window manager controls
            Key([mod, 'control'], 'r', lazy.restart()),
            # Key([mod, 'control'], 'q', lazy.shutdown()),
            Key([mod], 'r', lazy.spawn(script_path + 'dmenu_recent.sh')),
            Key([mod, "mod1"], 'r',
                lazy.spawn(script_path + 'dmenu_removeRecent.sh')),
            Key([mod], 'Return', lazy.spawn(my_term)),
            Key([mod], 'q', lazy.window.kill()),
            Key([mod], 'Tab', lazy.layout.next()),
            #Key([mod], 'Left', lazy.screen.prev_group()),
            #Key([mod], 'Right', lazy.screen.next_group()),
            Key([mod], "Left", lazy.prev_screen()),
            Key([mod], "Right", lazy.next_screen()),
            Key([mod, "shift"], "Left", Function.window_to_prev_screen()),
            Key([mod, "shift"], "Right", Function.window_to_next_screen()),

            # Layout modification
            Key([mod, 'control'], 'f', lazy.window.toggle_floating()),

            # Switch between windows in current stack pane
            Key([mod], 'k', lazy.layout.down()),
            Key([mod], 'j', lazy.layout.up()),

            # Move windows up or down in current stack
            Key([mod, 'shift'], 'k', lazy.layout.shuffle_down()),
            Key([mod, 'shift'], 'j', lazy.layout.shuffle_up()),

            # Switch window focus to other pane(s) of stack
            # Key([mod], 'space', lazy.layout.next()),
            Key([mod], 'space', lazy.spawn(script_path + 'dmenu_recent.sh')),

            # Toggle between different layouts as defined below
            Key([mod], 'Tab', lazy.next_layout()),

            #############################################################################
            # Own shortcuts                                                             #
            #############################################################################
            # # emacs
            Key(['control', 'mod1'], 'e', lazy.spawn('emacs')),
            # pcmanfm
            Key([mod], 'e', lazy.spawn(script_path + 'dmenu_filemanager.sh')),
            # firefox
            Key([mod, 'control'], 'Return', lazy.spawn('firefox')),
            # logout
            Key([mod, 'shift'], 'q',
                lazy.spawn(script_path + 'dmenu_exit.sh')),
            Key([mod], 'l', lazy.spawn(script_path + 'lockscreen.sh')),
            # brightness control
            Key([], 'XF86MonBrightnessDown',
                lazy.spawn(script_path + 'brightness.sh -')),
            Key([], 'XF86MonBrightnessUp',
                lazy.spawn(script_path + 'brightness.sh +')),
            # volume control
            Key([], 'XF86AudioRaiseVolume',
                lazy.spawn(script_path + 'adjust_volume.sh +')),
            Key([], 'XF86AudioLowerVolume',
                lazy.spawn(script_path + 'adjust_volume.sh -')),
            Key([], 'XF86AudioMute',
                lazy.spawn(script_path + 'adjust_volume.sh m')),
            # screenshots
            Key([mod], 's', lazy.spawn(script_path + 'screenshot_full.sh')),
            Key([mod, 'shift'], 's',
                lazy.spawn(script_path + 'screenshot_region.sh')),
            Key([], 'XF86AudioPlay',
                lazy.spawn(script_path + 'mpc_playpause.sh')),
            Key([], 'XF86AudioNext', lazy.spawn('mpc next')),
            Key([], 'XF86AudioPrev', lazy.spawn('mpc prev')),
            # screens and monitors
            Key([mod], 'p',
                lazy.spawn(script_path + 'dmenu_displayselect.sh')),
        ]
Ejemplo n.º 33
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.º 34
0
 def eval(self, env, memory):
     passedFunc = Function(self.paramID, self.expr)
     return env.putFunc(self.funcID, passedFunc)
Ejemplo n.º 35
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))