def visitExpressionAdditive(self,
                                ctx: LanguageParser.ExpressionAdditiveContext):
        if ctx.ADD_OP() or ctx.SUB_OP():
            operand_one = self.visitExpressionAdditive(
                ctx.expressionAdditive())
            operand_two = self.visitExpressionMultiplicative(
                ctx.expressionMultiplicative())

            if operand_one.type != operand_two.type:
                raise exceptions.TypeMismatchException(
                    "The additive operators must be applied to values of the same types.",
                    None, operand_one.type, operand_two.type)

            # Numbers
            if operand_one.type is Type.NUMBER:
                if ctx.ADD_OP():
                    return Value(Type.NUMBER,
                                 operand_one.value + operand_two.value)
                else:  # SUB
                    return Value(Type.NUMBER,
                                 operand_one.value - operand_two.value)

            if operand_one.type is Type.STRING:
                if ctx.ADD_OP():
                    return Value(Type.STRING,
                                 operand_one.value + operand_two.value)
                else:
                    raise Exception("Unsupported string - string")

        return self.visitExpressionMultiplicative(
            ctx.expressionMultiplicative())
Example #2
0
def genNe(resultLoc, src1Loc, src2Loc):
    resultLoc = resultLoc.withType(BoolType())
    assert (resultLoc.getIndirLevel() == 1)
    if src1Loc.getType() != src2Loc.getType():
        raise SemanticError(
            src1Loc.getPosition(),
            "Incompatible types: {} and {}".format(src1Loc.getType(),
                                                   src2Loc.getType()))
    t = src1Loc.getType()
    s1 = src1Loc.getSource()
    s2 = src2Loc.getSource()
    rs = resultLoc.getSource()
    l1 = src1Loc.getIndirLevel()
    l2 = src2Loc.getIndirLevel()
    isWord = t.getSize() == 2
    result = '; {} == {}\n'.format(src1Loc, src2Loc)
    if l1 == 0 and l2 == 0:
        # const == const
        pos = src1Loc.getPosition() - src2Loc.getPosition()
        if s1.isNumber() and s2.isNumber():
            return Value(pos, BoolType(), 0, int(int(s1) != int(s2)),
                         True), result
        else:
            return Value(pos, BoolType(), 0,
                         "int(({}) != ({}))".format(s1, s2), True), result
    else:
        result += _genEqNeCmp(src1Loc, src2Loc)
        result += '''
            dec b
            ldi a, 1
            sbb a, 0
        '''
        return Value.register(src1Loc.getPosition() - src2Loc.getPosition(),
                              BoolType()), result
Example #3
0
 def read_parameter_values(self):
     '''
     Read the possible values of all parameters.
     '''
     param_df = pd.read_excel(cfg.p_values, header=0)
     param_df = param_df.dropna(axis=0, how="all")
     params = param_df['Parameters']
     default_values = param_df['Default']
     alternatives = param_df['Alternative']
     good_as_param = param_df['Good']
     param_values = {}
     for index, row in param_df.iterrows():
         # row head: Parameters, Default,Alternative, Note, Good
         # if str(good_as_param[index]).lower().strip() == 'n':
         #     continue
         param = params[index].strip()
         v = Value(param, str(default_values[index]).strip())
         all_values = [v]
         # all_values = [] # do not include default values
         for altV in str(alternatives[index]).split(','):
             if altV == 'nan' or altV.lower().strip() == '':
                 continue
             all_values.append(Value(param, altV.strip()))
         # param_values[param.strip().lower()] = all_values
         param_values[param.strip()] = all_values
     # print '========== test parameter exists =============='
     # print 'yarn.resourcemanager.scheduler.class' in param_values
     # print 'yarn.resourcemanager.store.class' in param_values
     # print 'mapred.child.java.opts' in param_values
     return param_values
Example #4
0
def test_simplify_quantities():
    print "Testing simplification of quantities"
    from quantity import Constant, SpaceField, Quantities
    zero = Constant("zero", subfields=False, value=Value(0.0))
    C = Constant("C",
                 subfields=True,
                 value=Value("mat1", -1.25).set("mat2", -2.5))

    a = SpaceField("a", [3], subfields=True)
    b = SpaceField("b", [3])
    H_exch = SpaceField("H_exch", [3], subfields=True)
    rho = SpaceField("rho", [])
    M_sat = Constant("M_sat", [],
                     subfields=True,
                     value=Value("mat1", 1e6).set("mat2", 0.5e6))
    m = SpaceField("m", [3], subfields=True)
    qs = [C, a, b, H_exch, m, rho, M_sat]
    context = OpSimplifyContext(quantities=Quantities(qs),
                                material=["mat1", "mat2"],
                                is_periodic=True)

    # Testing the 'periodic' amendment
    pbc_in = \
        "C*<d/dxj H_exch(k)||d/dxj m(k)>; periodic:H_exch(k), j:1, k:3"
    # Expected result if context.is_periodic = True
    pbc_out_if_pbc = \
        ("  (-1.25)*<d/dxj H_exch_mat1(k)||d/dxj m_mat1(k)> "
         "+ (-2.5)*<d/dxj H_exch_mat2(k)||d/dxj m_mat2(k)>; "
         "periodic: H_exch_mat1(k); periodic: H_exch_mat2(k),"
         "j:1, k:3")
    # Expected result if context.is_periodic = False
    pbc_out_ifnot_pbc = \
        ("  (-1.25)*<d/dxj H_exch_mat1(k)||d/dxj m_mat1(k)> "
         "+ (-2.5)*<d/dxj H_exch_mat2(k)||d/dxj m_mat2(k)>, "
         "j:1, k:3")

    strings = {}
    strings[True] = \
        [("<a||b>", "<a_mat1||b> + <a_mat2||b>"),
         ("C*<d/dxj H_exch(k)||d/dxj m(k)>, j:1, k:3",
          "  (-1.25)*<d/dxj H_exch_mat1(k)||d/dxj m_mat1(k)> "
          "+ (-2.5)*<d/dxj H_exch_mat2(k)||d/dxj m_mat2(k)>,j:1, k:3"),
         ("M_sat*<rho||d/dxj m(j)> + M_sat*<rho||D/Dxj m(j)>, j:3",
          " 1000000.0*<rho||d/dxj m_mat1(j)> + "
          "1000000.0*<rho||D/Dxj m_mat1(j)> + "
          "500000.0*<rho||d/dxj m_mat2(j)> + "
          "500000.0*<rho||D/Dxj m_mat2(j)>, j:3"),
         (pbc_in, pbc_out_if_pbc)]

    strings[False] = [(pbc_in, pbc_out_ifnot_pbc)]

    for is_periodic in (False, True):
        context.is_periodic = is_periodic
        for string, result in strings[is_periodic]:
            parse_tree = parse(string).simplify(context=context)
            my_result = str(parse_tree)
            assert compare_strings(my_result, result), \
                ("Simplified of '%s' is '%s', but '%s' is expected."
                 % (string, my_result, result))
            print "passed"
Example #5
0
    def codegenIndex(self, ex):
        arr = self.codegenExpr(ex.op)
        print(ex)
        print(arr)
        print(arr.type)
        print(arr.type[1])
        if arr.type[0] != 'array':
            raise ValueError(f"no indexing non-array variables in {ex}")
        indexName = "%" + self.e.getName()
        #arrays types generally corrospond to array ptrs in llvm
        #actually will get  a element_type* which can be stored in directly
        ptrType = arr.lltype
        arrType = arr.lltype[:-1]
        #should be elem type...
        elemType = self.e.typeToLLType(arr.type[1][1])
        elemTypePtr = elemType + "*"
        self.e.emit(
            f"{indexName} = getelementptr {arrType}, {ptrType} {arr.val}, i64 0, i64 {ex.index.val}"
        )

        loadName = "%" + self.e.getName()

        #TODO meaningful alignment
        self.e.emit(
            f"{loadName} = load {elemType}, {elemTypePtr} {indexName}, align 1"
        )

        #FIXME idk if cateogry is *actually* maintained
        return Value(loadName,
                     elemType,
                     arr.category,
                     arr.type[1][1],
                     lvalue=Value(indexName, elemTypePtr, arr.category,
                                  arr.type[1][1], False))
    def __init__(self, ledPin):
        Thing.__init__(self, 'urn:dev:ops:blue-led-1234', 'Blue LED',
                       ['OnOffSwitch', 'Light'],
                       'Blue LED on SparkFun ESP32 Thing')
        self.pinLed = machine.Pin(ledPin, machine.Pin.OUT)
        self.pwmLed = machine.PWM(self.pinLed)
        self.ledBrightness = 50
        self.on = False
        self.updateLed()

        self.add_property(
            Property(self,
                     'on',
                     Value(self.on, self.setOnOff),
                     metadata={
                         '@type': 'OnOffProperty',
                         'title': 'On/Off',
                         'type': 'boolean',
                         'description': 'Whether the LED is turned on',
                     }))
        self.add_property(
            Property(self,
                     'brightness',
                     Value(self.ledBrightness, self.setBrightness),
                     metadata={
                         '@type': 'BrightnessProperty',
                         'title': 'Brightness',
                         'type': 'number',
                         'minimum': 0,
                         'maximum': 100,
                         'unit': 'percent',
                         'description': 'The brightness of the LED',
                     }))
Example #7
0
    def __init__(self):
        Thing.__init__(self, 'My Humidity Sensor', 'multiLevelSensor',
                       'A web connected humidity sensor')

        self.add_property(
            Property(self,
                     'on',
                     Value(True),
                     metadata={
                         'type': 'boolean',
                         'description': 'Whether the sensor is on',
                     }))

        self.level = Value(0.0)
        self.add_property(
            Property(self,
                     'level',
                     self.level,
                     metadata={
                         'type': 'number',
                         'description': 'The current humidity in %',
                         'unit': '%',
                     }))

        log.debug('starting the sensor update looping task')
    def visitExpressionNew(self, ctx: LanguageParser.ExpressionNewContext):
        class_name = ctx.IDENTIFIER().getText()
        class_instance = self._symbols.get_declared_class(class_name)
        if class_instance is None:
            raise exceptions.UnknownClassException(class_name)

        arguments = map(lambda expression: self.visitExpression(expression),
                        ctx.arguments().expression())

        # init null values
        field_values = {}
        for k, field in class_instance.fields.items():
            if field.default_expression is None:
                field_values[k] = Value(Type.NULL, None)
            else:
                field_values[k] = self.visitExpression(
                    field.default_expression)

        instance = Value(Type.CUSTOM_OBJECT, None, class_instance.methods,
                         field_values)

        # execute constructor
        if class_instance.constructor is not None:
            new_frame = Frame()
            new_frame.set_variables(
                zip(class_instance.constructor.parameters, arguments))
            new_frame.set_variable("this", instance)
            self._stack.push(new_frame)
            self.visitCodeBlock(class_instance.constructor.code)
            self._stack.pop()

        return instance
Example #9
0
def make_thing():
    thing = Thing('My Lamp', 'dimmableLight', 'A web connected lamp')

    def noop(_):
        pass

    thing.add_property(
        Property(thing,
                 'on',
                 Value(True, noop),
                 metadata={
                     'type': 'boolean',
                     'description': 'Whether the lamp is turned on',
                 }))
    thing.add_property(
        Property(thing,
                 'level',
                 Value(50, noop),
                 metadata={
                     'type': 'number',
                     'description': 'The level of light from 0-100',
                     'minimum': 0,
                     'maximum': 100,
                 }))

    thing.add_available_action(
        'fade', {
            'description': 'Fade the lamp to a given level',
            'input': {
                'type': 'object',
                'required': [
                    'level',
                    'duration',
                ],
                'properties': {
                    'level': {
                        'type': 'number',
                        'minimum': 0,
                        'maximum': 100,
                    },
                    'duration': {
                        'type': 'number',
                        'unit': 'milliseconds',
                    },
                },
            }
        }, FadeAction)

    thing.add_available_event(
        'overheated', {
            'description':
            'The lamp has exceeded its safe operating temperature',
            'type': 'number',
            'unit': 'celsius'
        })

    return thing
Example #10
0
    def from_buffer(cls, data):
        values = cls.fmt.unpack(data)
        page = MXLogPagePacket()

        # Parse the mess of binary values
        page.bat_max = ((values[1] & 0xFC) >> 2) | ((values[2] & 0x0F) << 6)
        page.bat_min = ((values[9] & 0xC0) >> 6) | (values[10] << 2) | ((values[11] & 0x03) << 10)
        page.kilowatt_hours = ((values[2] & 0xF0) >> 4) | (values[3] << 4)
        page.amp_hours = values[8] | ((values[9] & 0x3F) << 8)
        page.volts_peak = values[4]
        page.amps_peak = values[0] | ((values[1] & 0x03) << 8)
        page.absorb_time = values[5] | ((values[6] & 0x0F) << 8)
        page.float_time = ((values[6] & 0xF0) >> 4) | (values[7] << 4)
        page.kilowatts_peak = ((values[12] & 0xFC) >> 2) | (values[11] << 6)
        page.day = values[13]

        # Convert to human-readable values
        page.bat_max = Value(page.bat_max / 10.0, units='V', resolution=1)
        page.bat_min = Value(page.bat_min / 10.0, units='V', resolution=1)
        page.volts_peak = Value(page.volts_peak, units='Vpk')
        page.amps_peak = Value(page.amps_peak / 10.0, units='Apk', resolution=1)
        page.kilowatts_peak = Value(page.kilowatts_peak / 1000.0, units='kWpk', resolution=3)
        page.amp_hours = Value(page.amp_hours, units='Ah')
        page.kilowatt_hours = Value(page.kilowatt_hours / 10.0, units='kWh', resolution=1)
        page.absorb_time = Value(page.absorb_time, units='min')
        page.float_time = Value(page.float_time, units='min')

        # Also add the raw packet
        page.raw = data

        return page
Example #11
0
    def __init__(self):
        Thing.__init__(self, 'urn:dev:ops:my-pycom-pysense', 'My Pycom',
                       ['RGBLed', 'memory'], 'A web connected Pycom')

        self.color = 0  #0 is no light, 20 is very light blue #0xff00 #green
        self.updateLeds()
        self.mempycom = Value(0.0)
        self.seconds = 0

        self.__alarm = Timer.Alarm(self._seconds_handler, s=10, periodic=True)
        #self._alarm = Timer.Alarm(updateMemPycom, 1, arg=None, periodic=True)

        self.add_property(
            Property(self,
                     'mempycom',
                     self.mempycom,
                     metadata={
                         '@type': 'SystemParameter',
                         'title': 'Memory',
                         'type': 'number',
                         'description': 'The free RAM of the system',
                     }))
        self.add_property(
            Property(self,
                     'color',
                     Value(self.color, self.setcolor),
                     metadata={
                         '@type': 'ColorProperty',
                         'title': 'Color',
                         'type': 'integar',
                         'description': 'The color of the LED',
                     }))

        self.add_available_action(
            'setrgbcolor',
            {
                'title': 'Change Color',
                'description': 'Change the color of LED',
                'input': {
                    'type': 'object',
                    'required': [
                        'color',
                    ],
                    'properties': {
                        'color': {
                            'type': 'integer',
                            'minimum': 0,
                            'maximum': 0xFFFFFF,
                            #'unit': 'percent',
                        },
                    },
                },
            },
            SetRGBColor)
Example #12
0
 def get_value(self, var_name, imposed_limits=None, latlon_limits=None):
     # initialize limits dictionary if its not there
     if imposed_limits is None:
         imposed_limits = {}
     # if var_name's dimensions do not include lat and lon, we need to translate latlon_limits to the limits of actual var_name's dimensions
     if latlon_limits is not None:
         imposed_limits.update(self._translate_latlon_limits(latlon_limits))
     else:
         latlon_limits = self._get_latlon_limits()
     value = Value()
     # get data from all the datasets
     for f, ds in zip(self._files, self._ds):
         # data variable (we might need to impose the limits on it later on)
         print 'Reading data from file ' + f
         data = ds.variables[var_name]
         limits = {}
         # dimension names and values
         dim_names = data.dimensions
         dims = [ds.variables[name] for name in dim_names]
         title = getattr(data, 'long_name', None)
         # units (must be according to standart)
         units = getattr(data, 'units', None)
         for idim, (name, dim) in enumerate(zip(dim_names, dims)):
             dim_data = dim[:]
             if name in imposed_limits.keys():
                 # treat time differently
                 if name == "time":
                     imposed_limits[name] = date2num(imposed_limits[name], units=dim.units, calendar=getattr(dim, 'calendar', 'gregorian'))
                 # impose a limit on the dimension
                 min_dim, max_dim = imposed_limits[name]
                 dim_idx = np.where((dim_data >= min_dim) & (dim_data <= max_dim))
                 dim_data = dim_data[dim_idx]
                 data = data[dim_idx]
                 limits[name] = imposed_limits[name]
             else:
                 data = data[:]
                 limits[name] = [np.min(dim_data), np.max(dim_data)]
             # treat time differently
             if name == 'time':
                 limits[name] = num2date(limits[name], units=dim.units, calendar=getattr(dim, 'calendar', 'gregorian'))
                 dims[idim] = num2date(dim_data, units=dim.units, calendar=getattr(dim, 'calendar', 'gregorian'))
             else:
                 dims[idim] = dim_data
             axes_tuple = tuple(range(1, len(dims)) + [0,])
             data = np.transpose(data, axes_tuple)
         latlon = self._get_latlon_within_limits(latlon_limits)
         value_i = Value(data, title, units, dims, dim_names, latlon, limits, latlon_limits)
         value.update(value_i)
     return value
Example #13
0
def test_llg():
    print "Testing LLG single material"
    from quantity import Constant, SpaceField, Quantities
    C1 = Constant("C1", subfields=False, value=Value(-0.125))
    C2 = Constant("C2", subfields=False, value=Value(-0.0625))
    C3 = Constant("C3", subfields=False, value=Value(0.25))
    C4 = Constant("C4", subfields=False, value=Value(0.0))
    C5 = Constant("C5", subfields=False, value=Value(0.0))
    m = SpaceField("m", [3], subfields=True)
    dmdt = SpaceField("dmdt", [3], subfields=True)
    dm_dcurrent = SpaceField("dm_dcurrent", [3], subfields=False)
    pin = SpaceField("pin", subfields=False)
    H_total = SpaceField("H_total", [3], subfields=True)
    quantities = Quantities([C1, C2, C3, C4, C5, m, dmdt, dm_dcurrent, pin,
                             H_total])

    eq_rhs = """
      %range i:3;
      (dmdt(i) <-
         (  C1 * (eps(i,j,k) * m(j) * H_total(k))_(j:3,k:3)
          + C2 * (  eps(i,j,k) * m(j)
                  * eps(k,p,q) * m(p) * H_total(q))_(j:3,k:3,p:3,q:3)
          + C3 * (1.0 - (m(j)*m(j))_(j:3)) * m(i)
          + C4 * (  eps(i,j,k) * m(j)
                  * eps(k,p,q) * m(p) * dm_dcurrent(q))_(j:3,k:3,p:3,q:3)
          + C5 * (eps(i,j,k) * m(j) * dm_dcurrent(k))_(j:3,k:3))*pin)_(i:3);"""

    #eq_rhs = """dmdt(0) <- (-m(i))_(i:3);"""

    eq_ccode = """
    if (have_dmdt_a) {
      dmdt_a(0) = (-0.125*(m_a(1)*H_total_a(2) + -1.0*m_a(2)*H_total_a(1)) + -0.0625*(m_a(1)*m_a(0)*H_total_a(1) + -1.0*m_a(1)*m_a(1)*H_total_a(0) + m_a(2)*m_a(0)*H_total_a(2) + -1.0*m_a(2)*m_a(2)*H_total_a(0)) + 0.25*(1.0 - (m_a(0)*m_a(0) + m_a(1)*m_a(1) + m_a(2)*m_a(2)))*m_a(0))*pin;
    };
    if (have_dmdt_a) {
      dmdt_a(1) = (-0.125*(-1.0*m_a(0)*H_total_a(2) + m_a(2)*H_total_a(0)) + -0.0625*(-1.0*m_a(0)*m_a(0)*H_total_a(1) + m_a(0)*m_a(1)*H_total_a(0) + m_a(2)*m_a(1)*H_total_a(2) + -1.0*m_a(2)*m_a(2)*H_total_a(1)) + 0.25*(1.0 - (m_a(0)*m_a(0) + m_a(1)*m_a(1) + m_a(2)*m_a(2)))*m_a(1))*pin;
    };
    if (have_dmdt_a) {
      dmdt_a(2) = (-0.125*(m_a(0)*H_total_a(1) + -1.0*m_a(1)*H_total_a(0)) + -0.0625*(-1.0*m_a(0)*m_a(0)*H_total_a(2) + m_a(0)*m_a(2)*H_total_a(0) + -1.0*m_a(1)*m_a(1)*H_total_a(2) + m_a(1)*m_a(2)*H_total_a(1)) + 0.25*(1.0 - (m_a(0)*m_a(0) + m_a(1)*m_a(1) + m_a(2)*m_a(2)))*m_a(2))*pin;
    };"""

    context = EqSimplifyContext(quantities=quantities, material='a')
    context.expand_indices = True
    parse_tree = parse(eq_rhs).simplify(context=context)
    my_result = parse_tree.get_ccode() #.replace("\n", "")
    assert compare_strings(my_result, eq_ccode), \
     ("Simplified of '%s' is '%s', but '%s' is expected."
      % (eq_rhs, my_result, eq_ccode))
    print "passed"
Example #14
0
def test_add_value(value):
    value = Value()
    value.add_value('Joker')
    assert value.value == [
        'ACE', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'JACK', 'QUEEN',
        'KING', 'JOKER'
    ]
Example #15
0
def genSubscript(resultLoc, baseLoc, indexLoc):
    if not indexLoc.getType().isInteger():
        raise ValueError("Index must be an integer, got {}".format(
            indexLoc.getType()))
    if not baseLoc.getType().isPointer():
        raise ValueError("Subscript base must be a pointer, got {}".format(
            baseLoc.getType()))
    resultType = baseLoc.getType().deref()
    if baseLoc.getIndirLevel() == 0:
        if indexLoc.getIndirLevel() == 0:
            return Value(
                resultType, 1, "{} + {} * {}".format(baseLoc.getSource(),
                                                     indexLoc.getSource(),
                                                     resultType.getSize())), ""
        else:
            return resultLoc.removeUnknown(
                resultType), "{} = deref({} + [{}] * {})\n".format(
                    resultLoc, baseLoc, indexLoc, resultType.getSize())
    else:
        if indexLoc.getIndirLevel() == 0:
            return resultLoc.removeUnknown(
                resultType), "{} = deref([{}] + {} * {}\n".format(
                    resultLoc, baseLoc, indexLoc, resultType.getSize())
        else:
            return resultLoc.removeUnknown(
                resultType), "{} = deref([{}] + [{}] * {}\n".format(
                    resultLoc, baseLoc, indexLoc, resultType.getSize())
    def visitExpressionRelational(
            self, ctx: LanguageParser.ExpressionRelationalContext):

        expression_additive = ctx.expressionAdditive()

        if ctx.LT_OP() or ctx.GT_OP() or ctx.LTOE_OP() or ctx.GTOE_OP():
            operand_one = self.visitExpressionRelational(
                ctx.expressionRelational())
            operand_two = self.visitExpressionAdditive(expression_additive)

            if operand_one.type is not Type.NUMBER or operand_two.type is not Type.NUMBER:
                raise exceptions.TypeMismatchException(
                    "The relational operators can only be applied to values of type NUMBER."
                )

            if ctx.LT_OP():
                result = operand_one.value < operand_two.value
            elif ctx.GT_OP():
                result = operand_one.value > operand_two.value
            elif ctx.LTOE_OP():
                result = operand_one.value <= operand_two.value
            elif ctx.GTOE_OP():
                result = operand_one.value >= operand_two.value
            else:
                raise Exception()

            return Value(Type.BOOL, result)

        return self.visitExpressionAdditive(expression_additive)
Example #17
0
def genLNot(resultLoc, srcLoc):
    if resultLoc.getType().isUnknown():
        resultLoc = resultLoc.removeUnknown(srcLoc.getType())
    if resultLoc.getType() != srcLoc.getType():
        raise SemanticError(
            srcLoc.getPosition(),
            "Incompatible types: {} and {}".format(resultLoc.getType(),
                                                   srcLoc.getType()))
    if srcLoc.getType().getSize() != 1 or srcLoc.getType().getSign():
        raise SemanticError(srcLoc.getPosition(),
                            "Argument for `!' should be of type u8")
    assert (resultLoc.getIndirLevel() == 1)
    assert (srcLoc.getIndirLevel() == 1 or srcLoc.getIndirLevel() == 0)

    result = '; {} = !{}\n'.format(resultLoc, srcLoc)
    if srcLoc.getIndirLevel() == 0:
        # constant
        c = srcLoc.getSource()
        if c.isNumber():
            c = int(not bool(c))
        else:
            c = 'int(not bool({}))'.format(c)  # Warning
        return Value(srcLoc.getPosition(), BoolType(), 0, c, True), result
    else:
        # var
        result += loadByte('a', srcLoc, 0)
        result += '''
            dec a ; c = a == 0
            mov a, 0
            adc a, 0
        '''.format(srcLoc.getSource())
        return Value.register(srcLoc.getPosition(), BoolType()), result
    return resultLoc, result
    def visitExpressionMultiplicative(
            self, ctx: LanguageParser.ExpressionMultiplicativeContext):
        if ctx.MUL_OP() or ctx.DIV_OP() or ctx.MOD_OP() or ctx.EXP_OP():
            operand_one = self.visitExpressionMultiplicative(
                ctx.expressionMultiplicative())
            operand_two = self.visitExpressionUnary(ctx.expressionUnary())

            if operand_one.type is not Type.NUMBER or operand_two.type is not Type.NUMBER:
                raise exceptions.TypeMismatchException(
                    "The multiplicative operators can only be applied to values of type NUMBER."
                )

            if ctx.MUL_OP():
                result = operand_one.value * operand_two.value
            elif ctx.DIV_OP():
                result = operand_one.value / operand_two.value
            elif ctx.MOD_OP():
                result = operand_one.value % operand_two.value
            elif ctx.EXP_OP():
                result = operand_one.value**operand_two.value
            else:
                raise Exception()

            return Value(Type.NUMBER, result)

        return self.visitExpressionUnary(ctx.expressionUnary())
Example #19
0
    def codgenCall(self, ex):
        argExprs = []
        for arg in ex.args:
            argExprs.append(self.codegenExpr(arg))
        try:
            func = self.e.getLLVariable(ex.name)
        except ValueError:
            raise ValueError(f"uknown function {ex.name} in function call")
        argStr = ""
        for index, arg in enumerate(argExprs):
            #func.type[0] is the arg types
            if arg.lltype != func.lltype[0][index]:
                if arg.isLit:
                    if not canConvert(arg, func.lltype[0][index]):
                        raise ValueError(
                            f"type mismatch between argument {index + 1} {arg} and function {func} in call {s}: expected {func.lltype[0][index]}, saw {arg.lltype}"
                        )
                else:
                    raise ValueError(
                        f"type mismatch between argument {index + 1} {arg} and function {func} in call {s}: expected {func.lltype[0][index]}, saw {arg.lltype}"
                    )
            if index == 0:
                argStr += f"{arg.lltype} {arg.val}"
            else:
                argStr += f",{arg.lltype} {arg.val}"

        llName = "%" + self.e.getName()
        self.e.emit(f"{llName} = call {func.lltype[1]} {func.val}({argStr})")
        return Value(llName, func.lltype[1], "unnamed", False)
Example #20
0
    def compute_average(self, where=None):
        """Similar to 'compute_integral', but - for each material region -
        divide the result of the integral by the volume of the material region
        thus obtaining the spatial average."""
        integrals = self.compute_integral(where=where, as_value=False)
        if self.def_on_mat:
            v = Value()
            for subfield_name, value in integrals:
                v.set(subfield_name, value,
                      self.unit / self.volumes[subfield_name])
            return v

        else:
            assert len(integrals) == 1
            subfield_name, value = integrals[0]
            return Value(value, self.unit / self.volumes[subfield_name])
Example #21
0
 def group(self, attrIdx, count=False, aggrAttrIdx=[], aggrFunc=[]):
     #TODO: remove attributes of intermediary tables in attribute store
     attrIdx, aggrAttrIdx, aggrFunc = util.makelist(attrIdx, aggrAttrIdx,
                                                    aggrFunc)
     assert len(aggrAttrIdx) == len(aggrFunc)
     tmptable, idxmap = self.copy()
     aggrAttrIdx = util.mapIdx(aggrAttrIdx, idxmap)
     if count:
         cntIdx = tmptable.addAttr(gsql.WEIGHT_ATTR_NAME, val=Value(val=1))
         aggrAttrIdx.append(cntIdx)
         aggrFunc.append('cnt')
     # Find values for aggregation
     agg = aggregator.Aggregator(aggrFunc)
     aggCols = [tmptable.getColumn(idx) for idx in aggrAttrIdx]
     # Find groups of rows, and corresponding list of aggregation attributes
     tproj, _ = tmptable.project(attrIdx)
     groups = {}
     for i, row in enumerate(tproj.data):
         key = tuple(row)
         if not key in groups:
             groups[key] = []
         groups[key].append([col[i] for col in aggCols])
         # groups[key] is a list of lists: each inner list is the list of
         # aggregation values corresponding to this row
     # Create final table
     tfinal, _ = tmptable.project(attrIdx + aggrAttrIdx)
     for key in groups:
         aggvals = agg.calc(groups[key])
         newrow = list(key) + aggvals
         tfinal.data.append(newrow)
     idxmap = dict(zip(attrIdx + aggrAttrIdx, tfinal.columns))
     return tfinal, idxmap
Example #22
0
    def __init__(
        self,
        thing,
        name,
        initial_value=None,
        writeproperty=None,
        readproperty=None,
        metadata=None,
    ):
        """
        Initialize the object.

        thing -- the Thing this property belongs to
        name -- name of the property
        writeproperty -- Callable to pass value updates to
        readproperty -- Callable to obtain the property value
        metadata -- property metadata, i.e. type, description, unit, etc.,
                    as a dict
        """
        self.value = Value(
            initial_value=initial_value,
            read_forwarder=readproperty,
            write_forwarder=writeproperty,
        )

        self.thing = thing
        self.name = name
        self.href_prefix = ""
        self.href = "/properties/{}".format(self.name)
        self.metadata = metadata if metadata is not None else {}

        # Add the property change observer to notify the Thing about a property
        # change.
        self.value.on("update", lambda _: self.thing.property_notify(self))
    def __init__(self):
        Thing.__init__(
            self,
            'urn:dev:ops:my-humidity-sensor-1234',
            'My Humidity Sensor',
            ['MultiLevelSensor'],
            'A web connected humidity sensor'
        )

        self.level = Value(0.0)
        self.add_property(
            Property(self,
                     'level',
                     self.level,
                     metadata={
                         '@type': 'LevelProperty',
                         'title': 'Humidity',
                         'type': 'number',
                         'description': 'The current humidity in %',
                         'minimum': 0,
                         'maximum': 100,
                         'unit': 'percent',
                         'readOnly': True,
                     }))

        log.debug('starting the sensor update looping task')
Example #24
0
 def Evaluate(self, SymbolTable, whileFlag=0):
     value_obj = self.children[0].Evaluate(SymbolTable, whileFlag)
     value = value_obj.getValue()
     if (self.value == "-"):
         result = Value("int")
         result.setValue(value * -1)
         return result
     elif (self.value == "not"):
         if value_obj.type == "boolean":
             result = Value("boolean")
             result.setValue(not value)
             return result
         else:
             raise ValueError("Operand must be a boolean")
     else:
         return
Example #25
0
 def buy_power(self):
     """
     AC_INPUT -> BATTERIES + AC_OUTPUT
     """
     if self.buy_current is not None and self.input_voltage is not None:
         return Value((float(self.buy_current) * float(self.input_voltage)) / 1000.0, units='kW', resolution=2)
     return None
Example #26
0
    def __init__(self):
        self.read_locations = [
            Value("money", (170, 14, 215, 35)),
            Value("manpower", (254, 17, 300, 31)),
            #Value("stability", (420, 17, 446, 30)),
            Value("admin", (522, 58, 550, 70)),
            Value("diplo", (584, 58, 610, 70)),
            Value("mil", (641, 58, 666, 70))
        ]

        #pg init
        pg.init()
        self.screen = pg.display.set_mode((960, 540))
        self.clock = pg.time.Clock()
        pg.font.init()
        self.font = pg.font.Font('freesansbold.ttf', 8)
        self.frame_count = 0

        # EU4 init
        self.provinces = [""]
        provinces_txt = np.loadtxt('map/provinces.txt',
                                   dtype=str,
                                   delimiter=",")
        for p in provinces_txt:
            id = int(p[0])
            name = str(p[4])
            color_rgb = (int(p[1]), int(p[2]), int(p[3]))
            position = (int(p[5]), int(p[6]))
            self.provinces.append(Province(id, name, color_rgb, position))
        print(len(self.provinces))

        self.ongoing = True
        self.capital_id = 65
        while self.ongoing:
            if (self.frame_count % 10000 == 0):
                #self.get_values(self.read_locations)
                #self.draw_game(self.read_locations)

                pass
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    self.ongoing = False
            key = pg.key.get_pressed()
            if key[pg.K_q]:
                self.move_troops(134, 73)

            self.frame_count += 1
Example #27
0
def genNeg(resultLoc, srcLoc):
    if resultLoc.getType().isUnknown():
        resultLoc = resultLoc.removeUnknown(srcLoc.getType())
    if resultLoc.getType() != srcLoc.getType():
        raise SemanticError(
            srcLoc.getPosition(),
            "Incompatible types: {} and {}".format(resultLoc.getType(),
                                                   srcLoc.getType()))
    if not srcLoc.getType().getSign():
        raise SemanticError(
            srcLoc.getPosition(),
            "Argument for unary `-' should be of a signed type")
    assert (resultLoc.getIndirLevel() == 1)
    assert (srcLoc.getIndirLevel() == 1 or srcLoc.getIndirLevel() == 0)

    t = srcLoc.getType()
    if t.getSize() > 2:
        raise NatrixNotImplementedError(
            srcLoc.getPosition(),
            "Negation of ints wider than s16 is not implemented")
    result = '; {} = -{}\n'.format(resultLoc, srcLoc)
    if srcLoc.getIndirLevel() == 0:
        # constant
        c = srcLoc.getSource()
        if c.isNumber():
            c = -int(c) & (0xff if t.getSize() == 1 else 0xffff)
        else:
            c = '-({})'.format(c)  # Warning
        return Value(srcLoc.getPosition(), t, 0, c, True), result
    else:
        # var
        if t.getSize() == 1:
            result += loadByte('a', srcLoc, 0)
            result += 'neg a\n'
            return Value.register(srcLoc.getPosition(), t), result
        else:
            result += f'''
                ldi pl, lo({srcLoc.getSource()})
                ldi ph, hi({srcLoc.getSource()})
                ld b
            '''
            result += incP(srcLoc.isAligned())
            result += '''
                ld a
                not a
                not b
                inc b
                adc a, 0
            '''
        result += f'''
            ldi pl, lo({resultLoc.getSource()})
            ldi ph, hi({resultLoc.getSource()})
            st b
        '''
        result += incP(resultLoc.isAligned())
        result += '''
            st a
        '''
        return resultLoc, result
Example #28
0
 def __missing__(self, name):
     val = find_var_in_frame(self.sbframe, name)
     if val.IsValid():
         val = Value(val)
         self.__setitem__(name, val)
         return val
     else:
         raise KeyError(name)
Example #29
0
 def chg_power(self):
     """
     AC_INPUT -> BATTERIES
     Power consumed by the inverter from the AC input to charge the battery bank
     """
     if self.chg_current is not None and self.input_voltage is not None:
         return Value((float(self.chg_current) * float(self.input_voltage)) / 1000.0, units='kW', resolution=2)
     return None
Example #30
0
 def sell_power(self):
     """
     BATTERIES -> AC_INPUT
     Power produced by the inverter from the batteries, sold back to the grid (AC input)
     """
     if self.sell_current is not None and self.output_voltage is not None:
         return Value((float(self.sell_current) * float(self.output_voltage)) / 1000.0, units='kW', resolution=2)
     return None