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 _callback (self, params): args = [] list = List.from_pointer (ctypes.c_void_p (params)) for val in list: args.append (val.get()) # class method if self._self_object is not None: ret = self._callback_func (self._self_object(), *args) else: ret = self._callback_func (*args) if isinstance (ret, Value): _lib.myelin_value_ref (ret) return ret._ptr else: val = Value() if ret is not None: val.set (ret) _lib.myelin_value_ref (val) return val._ptr
def __init__(self, number): # Name this constant automatically based on it's number. Value.__init__(self, "CONST_0x%x" % (number)) self.constant = True self.volatile = False self.number = number
def __on_screen_saver_active_changed(self, connection: Gio.DBusConnection, sender_name: str, object_path: str, interface_name: str, signal_name: str, parameters: GLib.Variant) -> None: is_activated, = parameters self.is_lock_screen_activated = is_activated now = datetime.now() if self.is_lock_screen_activated: current_activity = Value.get_or_raise(self.current_activity, 'current_activity') self.previous_wm_class = current_activity.wm_class self.previous_active_window_name = current_activity.window_name wm_class = SpecialWmClass.LOCK_SCREEN.value window_name = '' else: if self.is_work_time: self.last_lock_screen_time = now wm_class = Value.get_or_raise(self.previous_wm_class, 'previous_wm_class') window_name = Value.get_or_raise(self.previous_active_window_name, 'previous_active_window_name') self.on_open_window(wm_class, window_name, now)
def __init__(self, name, location): Value.__init__(self, "VOLATILE_%s" % (name)) self.constant = False self.volatile = True self.location = location
def __init__(self, name, initial_number=0): Value.__init__(self, "GLOBAL_%s" % (name)) self.constant = False self.volatile = False self.initial_number = initial_number
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 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
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))
class PySenseThing(Thing): def __init__(self): Thing.__init__(self, 'urn:dev:ops:my-pysense', 'My PySense', [ 'Temperature', 'Humidity', 'Pressure', 'Luminance', 'Accelerometer' ], 'A Sensor Shield') self.seconds = 0 self.temperature = Value(0.0) self.humidity = Value(0.0) self.light = lt.light()[0] self.accelaration_0 = li.acceleration()[0] self.accelaration_1 = li.acceleration()[1] self.accelaration_2 = li.acceleration()[2] self.roll = li.roll() self.pitch = li.pitch() 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, 'temperature', self.temperature, #, self.updateTemperature), metadata={ '@type': 'Temperature', 'title': 'Temperature', 'type': 'number', 'description': 'The temperature sensor value', })) self.add_property( Property(self, 'humidity', self.humidity, metadata={ '@type': 'Humidity', 'title': 'Humidity', 'type': 'number', 'description': 'The humidity sensor value', })) def updateTemperature(self): self.temperature = si.temperature() print('temperature', self.temperature) def updateHumidity(self): self.humidity = si.humidity() print('humidity', self.humidity) #TODO : should not need to run timer to get temperature value! def _seconds_handler(self, alarm): self.seconds += 1 new_temperature = si.temperature() new_humidity = si.humidity() self.temperature.notify_of_external_update(new_temperature) self.humidity.notify_of_external_update(new_humidity) #print("%02d iterations" % self.seconds) #print(si.temperature()) if self.seconds < 0: alarm.cancel() # never stop
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' ]
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
def __init__(self, name, initial_number = 0): Value.__init__(self, "GLOBAL_%s"%(name)) self.constant = False self.volatile = False self.initial_number = initial_number
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
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())
def __init__(self, name, location): Value.__init__(self, "VOLATILE_%s"%(name)) self.constant = False self.volatile = True self.location = location
def load(self, filename): """ Load data from either XML or TSV file """ with open(filename, 'r') as f: _,ext = os.path.splitext(filename); if ext=='.xml': # Parse the XML file dom = parse(f) f.close() self.name = dom.documentElement.tagName xmlrows = dom.getElementsByTagName('row') for xmlrow in xmlrows: attr = xmlrow.attributes for i in range(attr.length): name = attr.item(i).name if not name in self.attrs(): # Add column to the table elt = Value(attr.item(i).value) index = self.attrStore.addAttr(name,elt.getType()) self.columns.append(index) for r in self.data: r.append(Value()) row = [unicode(xmlrow.getAttribute(name)) for name in self.attrs()] self.addrow(row) else: # Assume the input is a TSV file data = csv.reader(f,delimiter='\t') if len(data): for i in range(len(data[0])): self.attrStore('<untitled>'+str(i),None) for row in data: self.addrow([cell.decode('unicode-escape') for cell in row])
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', }))
class Button(Thing): def __init__(self, pin): Thing.__init__(self, 'Button 0', ['BinarySensor'], 'Button 0 on SparkFun ESP32 Thing') self.pin = machine.Pin(pin, machine.Pin.IN) self.button = Value(False) self.add_property( Property(self, 'on', self.button, metadata={ 'type': 'boolean', 'description': 'Button 0 pressed', 'readOnly': True, })) self.prev_pressed = self.is_pressed() def is_pressed(self): return self.pin.value() == 0 def process(self): pressed = self.is_pressed() if pressed != self.prev_pressed: self.prev_pressed = pressed log.debug('pressed = ' + str(pressed)) self.button.notify_of_external_update(pressed)
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 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"
def __init__(self, number): # Name this constant automatically based on it's number. Value.__init__(self, "CONST_0x%x"%(number)) self.constant = True self.volatile = False self.number = number
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
def genBNot(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())) assert (resultLoc.getIndirLevel() == 1) assert (srcLoc.getIndirLevel() == 1 or srcLoc.getIndirLevel() == 0) t = srcLoc.getType() result = '; {} = ~{}\n'.format(resultLoc, srcLoc) if srcLoc.getIndirLevel() == 0: # constant c = srcLoc.getSource() c = ~c return Value(srcLoc.getPosition(), t, 0, c, True), result # var s = srcLoc.getSource() rs = resultLoc.getSource() if t.getSize() == 1: result += loadByte('a', srcLoc, 0) result += 'not a\n' return Value.register(srcLoc.getPosition(), t), result else: # size > 1 for offset in range(0, t.getSize(), 2): rest = t.getSize() - offset result += f''' ldi pl, lo({s} + {offset}) ldi ph, hi({s} + {offset}) ld b ''' if rest > 1: result += incP(srcLoc.isAligned()) result += 'ld a\n' result += f''' ldi pl, lo({rs} + {offset}) ldi ph, hi({rs} + {offset}) not b st b ''' if rest > 1: if resultLoc.isAligned: result += ''' inc pl not a st a ''' else: result += ''' mov b, a inc pl mov a, 0 adc ph, a not b st b ''' return resultLoc, result
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
def genDeref(resultLoc, srcLoc, offset=0): if resultLoc.getType().isUnknown(): resultLoc = resultLoc.removeUnknown(srcLoc.getType().deref()) if srcLoc.getType().deref() != resultLoc.getType() and not srcLoc.getType( ).deref().isStruct(): raise SemanticError( srcLoc.getPosition(), "Incompatible types for deref: {} and {}".format( srcLoc.getType().deref(), resultLoc.getType())) assert (srcLoc.getIndirLevel() <= 1) t = resultLoc.getType() if srcLoc.getIndirLevel() == 0: return Value.withOffset(srcLoc.getPosition(), resultLoc.getType(), 1, srcLoc.getSource(), True, offset), "" result = '; {} = deref {} + {}\n'.format(resultLoc, srcLoc, offset) result += '; result is {}aligned, srcLoc is {}aligned'.format( "" if resultLoc.isAligned() else "not ", "" if srcLoc.isAligned() else "not ") rs = resultLoc.getSource() if t.getSize() == 1: result += loadP(srcLoc, offset) result += 'ld a\n' return Value.register(srcLoc.getPosition(), t), result else: # t.getSize() > 1 for byteOffset in reversed(range(0, t.getSize(), 2)): rest = min(2, t.getSize() - byteOffset) result += loadP(srcLoc, byteOffset + offset) result += 'ld b\n' if rest > 1: result += ''' mov a, 0 inc pl adc ph, a ld a ''' result += f''' ldi pl, lo({rs} + {byteOffset}) ldi ph, hi({rs} + {byteOffset}) st b ''' if rest > 1: if resultLoc.isAligned(): result += ''' inc pl st a ''' else: result += f''' ldi pl, lo({rs} + {byteOffset + 1}) ldi ph, hi({rs} + {byteOffset + 1}) st a ''' return resultLoc, result
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
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)
def _genMulVC(resultLoc, v, c): if c == 0: return Value(resultLoc.getPosition(), v.getType(), 0, 0, True), "" elif c == 1: return v, "" t = resultLoc.getType() if t.getSize() == 1: return Value.register(v.getPosition(), t), _genMulVCByte(resultLoc.getSource(), v, c) elif t.getSize() == 2: return resultLoc, _genMulVCWord(resultLoc, v, c) elif t.getSize() == 4: return resultLoc, _genMulVCDword(resultLoc, v, c)
def __init__(self, width=1920, height=1080): # Create Screen with the provided resolution self.width = width #1920 self.height = height #1080 self.screen = Screen(width, height) self.logo = self.screen.load_image("logo.png") #self.logo = self.screen.scale(self.logo, 500,100) #self.screen.set_fps(10) # NOTE: Remove comment on next line to add Full screen #self.screen.set_full_screen() size = self.screen.get_size() self.border = 10 b = self.border # Just to make the next line more readable self.battery = Battery(self.screen, x=20, y=self.height - 355, width=140, height=300) # Creates a wyndow with a margin to make it pritty <3 self.window = Window(self.screen, b + 180, b + 130, size[0] - (b * 2 + 270), size[1] - (b * 2 + 180)) self.window.set_all_colors((100, 100, 100)) self.window.set_border_color((200, 200, 200)) self.window.set_border_width(10) self.chart_og = Chart() self.chart_og.set_width(8) self.chart_og.set_color((255, 150, 0)) self.chart_og.add_point([1, 0]) self.chart_og.add_point([2, 0]) self.window.add_chart(self.chart_og) self.chart_optimised = Chart() self.chart_optimised.set_width(8) self.chart_optimised.set_color((0, 150, 255)) self.chart_optimised.add_point([1, 0]) self.chart_optimised.add_point([2, 0]) self.window.add_chart(self.chart_optimised) # Next we add a function that converts the X values to # something the window class can work with, simple numbers # the window class does not know how to handle dates # so they need to be converted to intigers. These X values # are still used as labels in the x axis so format them # wisely. # NOTE: Remove comment on the fallowing line to add convertion function #self.chart.set_conv_funct(self.convert) self.data = Value(self.screen, 22, 150)
def __init__(self, address=0, width=32, name=""): self.__address = Value(address) self.__token = Value("") self.__name = Value(name) self.__description = Value("") self.__width = Value(width) self.__nocode = Value(False) self.__dont_test = Value(False) self.__hide = Value(False) self.__bit_fields = {} self.__ram_size = Value(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
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])
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"
def generateFunctionCall(self, position, name, args, curFn): if name not in self.nameInfo.functions: raise SemanticError(position, "Undefined function: {}".format(name)) f = self.nameInfo.functions[name] if len(args) != len(f.args): raise SemanticError(position, "Incorrect argument count for {}".format(name)) result = "" isRecursive = self.callgraph.isRecursive(curFn, name) if not self.useStack: if isRecursive: sys.stderr.write("Warning: {}: recursion\n".format( position)) # TODO warning function in a different module if isRecursive: result += self.backend.genPushLocals(curFn) for n, expr in enumerate(args): result += self.generateAssignment( Value.variable(Position.fromAny(expr), labelname.getArgumentName(name, n, True), f.args[n]), expr, curFn) result += self.backend.genCall(name) if not self.useStack: if isRecursive: result += self.backend.genPopLocals(curFn) return result
def __init__(self, pin): Thing.__init__(self, 'Button 0', ['BinarySensor'], 'Button 0 on SparkFun ESP32 Thing') self.pin = machine.Pin(pin, machine.Pin.IN) self.button = Value(False) self.add_property( Property(self, 'on', self.button, metadata={ 'type': 'boolean', 'description': 'Button 0 pressed', 'readOnly': True, })) self.prev_pressed = self.is_pressed()
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
def __getitem__ (self, index): if not isinstance (index, int): raise TypeError ("The index must be a non-negative integer") if index < 0 or index >= _lib.myelin_list_size (self): raise IndexError val = _lib.myelin_list_index (self, index) return Value.from_pointer (val)
def addrow(self, strrow): assert len(strrow) == len(self.columns) row = [] for i in range(len(strrow)): val = Value(strrow[i]) #print str(val.getType())+' et '+str(self.types[i]) if self.getType(i) is type(None): # Initialize type self.setType(i,val.getType()) row.append(val) elif val.getType() == self.getType(i) or val.getType() is type(None): row.append(val) else: row.append(Value(val=strrow[i])) if self.getType(i) != unicode: # Convert all other values in the column back to string # TODO : handle more fine-grained fallback (eg Float to Int) for r in self.data: if not r[i].getType() is type(None): r[i] = Value(val=unicode(r[i])) self.setType(i,unicode) self.data.append(row)
def compute_integral(self, where=None, as_value=True): ocaml.lam_get_field(self.lam, self.master, self.get_lam_name()) dof_stem = "" if where != None: if type(where) == str: where = [where] dof_stem = ["%s_%s" % (self.name, mat_name) for mat_name in where] raw_result = nfem.integrate_field(self.master, dof_stem) if not as_value: return raw_result u = self.unit * self.volume_unit if self.def_on_mat: v = Value() for mat_name, data in raw_result: v.set(mat_name, data, u) return v else: assert len(raw_result) == 1 name, data = raw_result[0] return Value(data, u)
def get_value (self, index): val = _lib.myelin_list_index (self, index) return Value.from_pointer (val)
class Register(object): """ Defines a hardware register. """ def __init__(self, address=0, width=32, name=""): self.__address = Value(address) self.__token = Value("") self.__name = Value(name) self.__description = Value("") self.__width = Value(width) self.__nocode = Value(False) self.__dont_test = Value(False) self.__hide = Value(False) self.__bit_fields = {} self.__ram_size = Value(0) def find_first_unused_bit(self): """ Finds the first unused bit in a the register. """ bit = [0] * self.width for field in self.__bit_fields.values(): for val in range(field.start_position, field.stop_position + 1): bit[val] = 1 for pos in range(0, self.width): if bit[pos] == 0: return pos bit = set([]) for field in self.__bit_fields.values(): for val in range(field.start_position, field.stop_position + 1): bit.add(val) all_bits = set(range(0, self.width)) l = sorted(list(bit.difference(all_bits))) if l: return l[0] else: return 0 def find_next_unused_bit(self): """ Finds the first unused bit in a the register. """ bit = set([]) for field in self.__bit_fields.values(): for val in range(field.start_position, field.stop_position + 1): bit.add(val) lbits = sorted(list(bit)) if lbits: if lbits[-1] == self.width - 1: return self.find_first_unused_bit() else: return lbits[-1] + 1 else: return 0 def __set_dont_test(self, val): """ Sets the __dont_test flag. This cannot be accessed directly, but only via the propery 'do_not_test'. """ self.__dont_test.set(val) def __get_dont_test(self): """ Returns the value of the __dont_test flag. This cannot be accessed directly, but only via the property 'do_not_test' """ return self.__dont_test.get() def get_dont_test_obj(self): """ Returns the actual lower level __dont_test object. This is needed to set the modified flag and the last modified time stamp. """ return self.__dont_test do_not_test = property(__get_dont_test, __set_dont_test, None, "Indicates if the register should not be tested " "by automatic tests") def __set_ram_size(self, val): """ Sets __ram_size. This cannot be accessed directly, but only via the propery 'ram_size'. """ self.__ram_size.set(val) def __get_ram_size(self): """ Returns the value of __ram_size. This cannot be accessed directly, but only via the property 'ram_size' """ return self.__ram_size.get() def get_ram_size_obj(self): """ Returns the actual lower level __ram_size object. This is needed to set the modified flag and the last modified time stamp. """ return self.__ram_size ram_size = property(__get_ram_size, __set_ram_size, None, "Indicates if the register is a RAM, and what its" "length is") def __set_hide(self, val): """ Sets the __hide flag . This cannot be accessed directly, but only via the propery 'hide'. """ self.__hide.set(val) def __get_hide(self): """ Returns the value of the __hide flag. This cannot be accessed directly, but only via the property 'hide' """ return self.__hide.get() def get_hide_obj(self): """ Returns the actual lower level __hide object. This is needed to set the modified flag and the last modified time stamp. """ return self.__dont_test hide = property(__get_hide, __set_hide, None, "Indicates if the register should be hidden " "from documentation") def __set_no_code(self, val): """ Sets the __nocode flag. This cannot be accessed directly, but only via the propery 'do_not_generate_code' """ self.__nocode.set(bool(val)) def __get_no_code(self): """ Returns the value of the __nocode flag. This cannot be accessed directly, but only via the property 'do_not_generate_code' """ return self.__nocode.get() def get_no_code_obj(self): """ Returns the actual lower level __nocode object. This is needed to set the modified flag and the last modified time stamp. """ return self.__nocode do_not_generate_code = property(__get_no_code, __set_no_code, None, "Indicates if code generation should be " "suppressed") def __set_token(self, val): """ Sets the __token flag. This cannot be accessed directly, but only via the propery 'token' """ self.__token.set(val.strip().upper()) def __get_token(self): """ Returns the value of the __token flag. This cannot be accessed directly, but only via the property 'token' """ return self.__token.get() def get_token_obj(self): """ Returns the actual lower level __token object. This is needed to set the modified flag and the last modified time stamp. """ return self.__token token = property(__get_token, __set_token, None, "token name of the register") def __set_name(self, name): """ Sets the __name flag. This cannot be accessed directly, but only via the propery 'register_name' """ self.__name.set(name.strip()) def __get_name(self): """ Returns the value of the __name flag. This cannot be accessed directly, but only via the property 'register_name' """ return self.__name.get() def get_name_obj(self): """ Returns the actual lower level __name object. This is needed to set the modified flag and the last modified time stamp. """ return self.__name register_name = property(__get_name, __set_name, None, "Name of the register") def __set_address(self, addr): """ Sets the __address flag. This cannot be accessed directly, but only via the propery 'address' """ self.__address.set(addr) def __get_address(self): """ Returns the value of the __address flag. This cannot be accessed directly, but only via the property 'address' """ return self.__address.get() def get_address_obj(self): """ Returns the actual lower level __address object. This is needed to set the modified flag and the last modified time stamp. """ return self.__address address = property(__get_address, __set_address, None, "Address of the register") def __set_description(self, description): """ Sets the __description flag. This cannot be accessed directly, but only via the propery 'Description' """ self.__description.set(description) def __get_description(self): """ Returns the value of the __description flag. This cannot be accessed directly, but only via the property 'description' """ return self.__description.get() def get_description_obj(self): """ Returns the actual lower level __description object. This is needed to set the modified flag and the last modified time stamp. """ return self.__description description = property(__get_description, __set_description, None, "description of the register") def __set_width(self, width): """ Sets the __width flag. This cannot be accessed directly, but only via the propery 'width' """ self.__width.set(width) def __get_width(self): """ Returns the value of the __width flag. This cannot be accessed directly, but only via the property 'width' """ return self.__width.get() def get_width_obj(self): """ Returns the actual lower level __width object. This is needed to set the modified flag and the last modified time stamp. """ return self.__width width = property(__get_width, __set_width, None, "Width of the register") def get_bit_fields(self): """ Returns a dictionary of bit fields. The key is stop_position of the bit field. """ return self.__bit_fields.values() def get_bit_field(self, key): """ Returns the bit field associated with the specified key. """ return self.__bit_fields.get(key) def get_bit_field_keys(self): """ Returns the list of keys associated with the bit fields """ return sorted(self.__bit_fields.keys()) def add_bit_field(self, field): """ Adds a bit field to the set of bit fields. """ self.__bit_fields[field.stop_position] = field def delete_bit_field(self, field): """ Removes the specified bit field from the dictionary. We cannot use the stop_position, since it may have changed. """ for key in self.__bit_fields.keys(): if self.__bit_fields[key] == field: del self.__bit_fields[key]
def call (self, name, params): val = _lib.myelin_object_call (self, name, params) return Value.from_pointer (val)
def get_instance (self): instance = _lib.myelin_object_get_instance (self) return Value.from_pointer (instance)
def __init__(self, end_node, prec, tree_index, linear_index, val): Value.__init__(self, end_node, prec, tree_index, linear_index) self._value = val
def convert_value(self, value): val = _lib.myelin_converter_convert_value(self, value) return Value.from_pointer(val)
def test_Value_instantiate(): objs = dict() v = Value('type', 'value') assert isinstance(v, Value) assert v.type(objs) == 'type' assert v.value(objs) == 'value'
def __init__(self, *args, **kwargs): Value.__init__(self, *args, **kwargs) self.constant = False self.volatile = False self.number = None
def call (self, params): # check_param_types (self.get_param_types(), params) val = _lib.myelin_constructor_call (self, params) return Value.from_pointer (val)
def call (self, params): # check_param_types (self.get_type().get_param_types(), params) val = _lib.myelin_function_call (self, params) return Value.from_pointer (val)
def __init__(self, end_node, prec, tree_index, linear_index): Value.__init__(self, end_node, prec, tree_index, linear_index)
def __init__(self, name): Value.__init__(self, "LOCAL_%s"%(name)) self.constant = False self.volatile = False
def call (self, params): val = _lib.myelin_custom_function_type_call (self, params) return Value.from_pointer (val)
def create_instance (self, params): instance = _lib.myelin_class_create_instance (self, params) return Value.from_pointer (instance)