id
int64
0
843k
repository_name
stringlengths
7
55
file_path
stringlengths
9
332
class_name
stringlengths
3
290
human_written_code
stringlengths
12
4.36M
class_skeleton
stringlengths
19
2.2M
total_program_units
int64
1
9.57k
total_doc_str
int64
0
4.2k
AvgCountLine
float64
0
7.89k
AvgCountLineBlank
float64
0
300
AvgCountLineCode
float64
0
7.89k
AvgCountLineComment
float64
0
7.89k
AvgCyclomatic
float64
0
130
CommentToCodeRatio
float64
0
176
CountClassBase
float64
0
48
CountClassCoupled
float64
0
589
CountClassCoupledModified
float64
0
581
CountClassDerived
float64
0
5.37k
CountDeclInstanceMethod
float64
0
4.2k
CountDeclInstanceVariable
float64
0
299
CountDeclMethod
float64
0
4.2k
CountDeclMethodAll
float64
0
4.2k
CountLine
float64
1
115k
CountLineBlank
float64
0
9.01k
CountLineCode
float64
0
94.4k
CountLineCodeDecl
float64
0
46.1k
CountLineCodeExe
float64
0
91.3k
CountLineComment
float64
0
27k
CountStmt
float64
1
93.2k
CountStmtDecl
float64
0
46.1k
CountStmtExe
float64
0
90.2k
MaxCyclomatic
float64
0
759
MaxInheritanceTree
float64
0
16
MaxNesting
float64
0
34
SumCyclomatic
float64
0
6k
147,748
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/adc.py
pymlab.sensors.adc.I2CADC01
class I2CADC01(Device): """ Driver for the LTC2485 Linear Technology I2C ADC device. """ def __init__(self, parent = None, address = 0x24, **kwargs): Device.__init__(self, parent, address, **kwargs) # reading internal temperature def readTemp(self): self.bus.write_byte(self.address, 0x08) # switch to internal thermometer, start conversion time.sleep(0.2) # wait for conversion value = self.bus.read_i2c_block(self.address, 4) # read converted value time.sleep(0.2) # wait for dummy conversion v = value[0]<<24 | value[1]<<16 | value[2]<<8 | value[3] v ^= 0x80000000 if (value[0] & 0x80)==0: v = v - 0xFFFFFFff voltage = float(v) voltage = voltage * 1.225 / (2147483648.0) # calculate voltage against vref and 24bit temperature = (voltage / 0.0014) - 273 # calculate temperature return temperature # reading ADC after conversion and start new conversion def readADC(self): self.bus.write_byte(self.address, 0x00) # switch to external input, start conversion time.sleep(0.2) # wait for conversion value = self.bus.read_i2c_block(self.address, 4) # read converted value time.sleep(0.2) # wait for dummy conversion v = value[0]<<24 | value[1]<<16 | value[2]<<8 | value[3] v ^= 0x80000000 if (value[0] & 0x80)==0: v = v - 0xFFFFFFff voltage = float(v) voltage = voltage * 1.225 / (2147483648.0) # calculate voltage against vref and 24bit return voltage
class I2CADC01(Device): ''' Driver for the LTC2485 Linear Technology I2C ADC device. ''' def __init__(self, parent = None, address = 0x24, **kwargs): pass def readTemp(self): pass def readADC(self): pass
4
1
9
0
9
4
2
0.57
1
1
0
0
3
0
3
11
37
4
28
11
24
16
28
11
24
2
2
1
5
147,749
MLAB-project/pymlab
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MLAB-project_pymlab/src/pymlab/utils.py
pymlab.utils.Enum2.Sequence
class Sequence(object): def __iter__(self): return self
class Sequence(object): def __iter__(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
1
3
0
3
2
1
0
3
2
1
1
1
0
1
147,750
MLAB-project/pymlab
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MLAB-project_pymlab/src/pymlab/utils.py
pymlab.utils.Enum2.range.IntegerSequence
class IntegerSequence(cls.Sequence): def __init__(self, start, step): self._next = start self._step = step def __iter__(self): return self def next(self): value = self._next self._next += self._step return value
class IntegerSequence(cls.Sequence): def __init__(self, start, step): pass def __iter__(self): pass def next(self): pass
4
0
3
0
3
0
1
0
1
0
0
0
3
2
3
3
12
2
10
7
6
0
10
7
6
1
1
0
3
147,751
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/adc.py
pymlab.sensors.adc.LTC2453
class LTC2453(Device): """ Driver for the LTC2453 Linear Technology I2C ADC device. """ def __init__(self, parent = None, address = 0x14, **kwargs): Device.__init__(self, parent, address, **kwargs) def readADC(self): value = self.bus.read_i2c_block(self.address, 2) # read converted value v = value[0]<<8 | value[1] v = v - 0x8000 return v
class LTC2453(Device): ''' Driver for the LTC2453 Linear Technology I2C ADC device. ''' def __init__(self, parent = None, address = 0x14, **kwargs): pass def readADC(self): pass
3
1
4
0
4
1
1
0.5
1
0
0
0
2
0
2
10
12
1
8
5
5
4
8
5
5
1
2
0
2
147,752
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/light.py
pymlab.sensors.light.ISL03
class ISL03(Device): """ Python library for ISL03A MLAB module with VEML 6030 I2C Light Sensor """ def __init__(self, parent = None, address = 0x10, fault_queue = 1, **kwargs): Device.__init__(self, parent, address, **kwargs) ## register definitions self.command = 0x00 self.Data_lsb = 0x04 ##self.Data_msb = 0x02 ## config parameters self.SHUTDOWN = (1 << 7) self.continuous_measurement = (1 << 6) self.IR_sense = (1 << 5) self.VIS_sense = (0 << 5) self.clock_INT_16bit = (0b000 << 4) self.clock_INT_12bit = (0b001 << 4) self.clock_INT_8bit = (0b010 << 4) self.clock_INT_4bit = (0b011 << 4) self.clock_EXT_ADC = (0b100 << 4) self.clock_EXT_Timer = (0b101 << 4) self.range_1kLUX = 0b00 self.range_4kLUX = 0b01 self.range_16kLUX = 0b10 self.range_64kLUX = 0b11 def initialize(self): self.config(self.continuous_measurement) def ADC_sync(self): """ Ends the current ADC-integration and starts another. Used only with External Timing Mode. """ self.bus.write_byte_data(self.address, 0xff, 0x01) LOGGER.debug("syncing ILS ADC",) return def config(self, config): self.bus.write_word_data(self.address, self.command, config) return def get_lux(self): DATA = self.bus.read_word_data(self.address, self.Data_lsb) Ecal = 1 * DATA return Ecal
class ISL03(Device): ''' Python library for ISL03A MLAB module with VEML 6030 I2C Light Sensor ''' def __init__(self, parent = None, address = 0x10, fault_queue = 1, **kwargs): pass def initialize(self): pass def ADC_sync(self): ''' Ends the current ADC-integration and starts another. Used only with External Timing Mode. ''' pass def config(self, config): pass def get_lux(self): pass
6
2
8
0
6
1
1
0.28
1
0
0
0
5
16
5
13
51
10
32
24
26
9
32
24
26
1
2
0
5
147,753
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/sht.py
pymlab.sensors.sht.SHT25
class SHT25(Device): 'Python library for SHT25v01A MLAB module with Sensirion SHT25 i2c humidity and temperature sensor.' def __init__(self, parent = None, address = 0x40, **kwargs): Device.__init__(self, parent, address, **kwargs) self.SHT25_HEATER_ON = 0x04 self.SHT25_HEATER_OFF = 0x00 self.SHT25_OTP_reload_off = 0x02 self.SHT25_RH12_T14 = 0x00 self.SHT25_RH8_T12 = 0x01 self.SHT25_RH10_T13 = 0x80 self.SHT25_RH11_T11 = 0x81 #self.address = 0x40 # SHT25 has only one device address (factory set) self.TRIG_T_HOLD = 0b11100011 self.TRIG_RH_HOLD = 0b11100101 self.TRIG_T_noHOLD = 0b11110011 self.TRIG_RH_noHOLD = 0b11110101 self.WRITE_USR_REG = 0b11100110 self.READ_USR_REG = 0b11100111 self.SOFT_RESET = 0b11111110 def soft_reset(self): self.bus.write_byte(self.address, self.SOFT_RESET); return def setup(self, setup_reg ): # writes to status register and returns its value reg=self.bus.read_byte_data(self.address, self.READ_USR_REG); # Read status actual status register reg = (reg & 0x3A) | setup_reg; # modify actual register status leave reserved bits without modification self.bus.write_byte_data(self.address, self.WRITE_USR_REG, reg); # write new status register return self.bus.read_byte_data(self.address, self.READ_USR_REG); # Return status actual status register for check purposes def get_temp(self): self.bus.write_byte(self.address, self.TRIG_T_noHOLD); # start temperature measurement time.sleep(0.1) data = self.bus.read_i2c_block(self.address, 2) # Sensirion digital sensors are pure I2C devices, therefore clear I2C trasfers must be used instead of SMBus trasfers. value = data[0]<<8 | data[1] value &= ~0b11 # trow out status bits return(-46.85 + 175.72/65536.0*value) def get_hum(self, raw = False): """ The physical value RH given above corresponds to the relative humidity above liquid water according to World Meteorological Organization (WMO) """ self.bus.write_byte(self.address, self.TRIG_RH_noHOLD); # start humidity measurement time.sleep(0.1) data = self.bus.read_i2c_block(self.address, 2) value = data[0]<<8 | data[1] value &= ~0b11 # trow out status bits humidity = (-6.0 + 125.0*(value/65536.0)) if raw: # raw sensor output, useful for getting an idea of sensor failure status return humidity else: if humidity > 100.0: # limit values to relevant physical variable (values out of that limit is sensor error state and are dependent on specific sensor piece) return 100.0 elif humidity < 0.0: return 0.0 else: return humidity
class SHT25(Device): '''Python library for SHT25v01A MLAB module with Sensirion SHT25 i2c humidity and temperature sensor.''' def __init__(self, parent = None, address = 0x40, **kwargs): pass def soft_reset(self): pass def setup(self, setup_reg ): pass def get_temp(self): pass def get_hum(self, raw = False): ''' The physical value RH given above corresponds to the relative humidity above liquid water according to World Meteorological Organization (WMO) ''' pass
6
2
13
2
9
4
2
0.4
1
0
0
0
5
14
5
13
70
15
48
26
42
19
45
26
39
4
2
2
8
147,754
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/sdp3x.py
pymlab.sensors.sdp3x.SDP3x
class SDP3x(Device): """ Driver for the SDP3x diff pressure sensor. """ def __init__(self, parent = None, address = 0x21, **kwargs): Device.__init__(self, parent, address, **kwargs) def initialize(self): self.reset() self.bus.write_byte(self.address, 0x00) # SDP3x device wakeup time.sleep(0.1) self.bus.write_byte_data(self.address, 0x36, 0x7C) self.bus.write_byte_data(self.address, 0xE1, 0x02) p_id = self.bus.read_i2c_block(self.address, 18) p_num = ((p_id[0] << 24) | (p_id[1] << 16) | (p_id[3] << 8) | p_id[4]) if (p_num == 0x03010101): sensor = "SDP31" elif (p_num == 0x03010201): sensor = "SDP32" elif (p_num == 0x03010384): sensor = "SDP33" else: sensor = "unknown" print("ID: %s - sensor: %s" % (hex(p_num), sensor)) self.bus.write_byte_data(self.address, 0x36, 0x15) def reset(self): self.bus.write_byte(self.address, 0x00) # SDP3x device wakeup time.sleep(0.1) self.bus.write_byte(0x00, 0x06) # SDP3x device soft reset time.sleep(0.1) def readData(self): raw_data = self.bus.read_i2c_block(self.address, 9) press_data = raw_data[0]<<8 | raw_data[1] temp_data = raw_data[3]<<8 | raw_data[4] if (press_data > 0x7fff): press_data -= 65536 if (temp_data > 0x7fff): temp_data -= 65536 dpsf = float(raw_data[6]<<8 | raw_data[7]) if(dpsf == 0): press_data = 0.0 else: press_data /= dpsf temp_data /= 200 return press_data, temp_data
class SDP3x(Device): ''' Driver for the SDP3x diff pressure sensor. ''' def __init__(self, parent = None, address = 0x21, **kwargs): pass def initialize(self): pass def reset(self): pass def readData(self): pass
5
1
12
2
10
1
3
0.15
1
1
0
0
4
0
4
12
57
13
41
12
36
6
37
12
32
4
2
1
10
147,755
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/rtc.py
pymlab.sensors.rtc.RTC01
class RTC01(Device): FUNCT_MODE_32 = 0b00000000 FUNCT_MODE_50 = 0b00010000 FUNCT_MODE_count = 0b00100000 FUNCT_MODE_test = 0b00110000 MAX_COUNT = 999999 def __init__(self, parent = None, address = 0x50, possible_adresses = [0x50, 0x51], **kwargs): Device.__init__(self, parent, address, **kwargs) ## register definitions self.CONTROL_STATUS = 0x00 def initialize(self): self.last_reset = time.time() LOGGER.debug("RTC01 sensor initialized. ",) return self.bus.read_byte_data(self.address,0x01); def get_status(self): status = self.bus.read_byte_data(self.address, self.CONTROL_STATUS) return status def set_config(self, config): self.bus.write_byte_data(self.address, self.CONTROL_STATUS, config) return config def set_datetime(self, dt = None): if not dt: dt = datetime.datetime.utcnow() # TODO def get_datetime(self): for reg in xrange(1,6): print (hex(self.bus.read_byte_data(self.address, reg))) #TODO def get_integration_time(self): return time.time()-self.last_reset def reset_counter(self): self.bus.write_byte_data(self.address,0x01,0x00) self.bus.write_byte_data(self.address,0x02,0x00) self.bus.write_byte_data(self.address,0x03,0x00) self.last_reset = time.time() def get_frequency(self): delta = time.time()-self.last_reset count = self.get_count() freq = 1.0*(count/delta) return freq def get_count(self): a = self.bus.read_byte_data(self.address, 0x01) b = self.bus.read_byte_data(self.address, 0x02) c = self.bus.read_byte_data(self.address, 0x03) return int((a&0x0f)*1 + ((a&0xf0)>>4)*10 + (b&0x0f)*100 + ((b&0xf0)>>4)*1000+ (c&0x0f)*10000 + ((c&0xf0)>>4)*1000000) def get_speed(self, **kwargs): diameter = kwargs.get('diameter', 1) reset = kwargs.get('reset', 0) time_reset = kwargs.get('time_reset', 60) if time.time() - self.last_reset > time_reset: self.reset_counter() freq = self.get_frequency() spd = math.pi*diameter/1000*freq #if reset: # self.reset_counter() return spd
class RTC01(Device): def __init__(self, parent = None, address = 0x50, possible_adresses = [0x50, 0x51], **kwargs): pass def initialize(self): pass def get_status(self): pass def set_config(self, config): pass def set_datetime(self, dt = None): pass def get_datetime(self): pass def get_integration_time(self): pass def reset_counter(self): pass def get_frequency(self): pass def get_count(self): pass def get_speed(self, **kwargs): pass
12
0
5
0
4
0
1
0.1
1
2
0
0
11
2
11
19
74
18
51
32
39
5
51
32
39
2
2
1
14
147,756
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/motor.py
pymlab.sensors.motor.MOTOR01
class MOTOR01(Device): """ Example: """ def __init__(self, parent = None, address = 0x51, **kwargs): Device.__init__(self, parent, address, **kwargs) def set_pwm(self,pwm): self.bus.write_byte_data(self.address, pwm & 0xFF, (pwm>>8) & 0xFF)
class MOTOR01(Device): ''' Example: ''' def __init__(self, parent = None, address = 0x51, **kwargs): pass def set_pwm(self,pwm): pass
3
1
2
0
2
0
1
0.6
1
0
0
0
2
0
2
10
13
5
5
3
2
3
5
3
2
1
2
0
2
147,757
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/mag.py
pymlab.sensors.mag.MAG01
class MAG01(Device): """ Example: """ SCALES = { 0.88: [0, 0.73], 1.30: [1, 0.92], 1.90: [2, 1.22], 2.50: [3, 1.52], 4.00: [4, 2.27], 4.70: [5, 2.56], 5.60: [6, 3.03], 8.10: [7, 4.35], } def __init__(self, parent = None, address = 0x1E, gauss = 4.0, **kwargs): Device.__init__(self, parent, address, **kwargs) self._gauss = gauss (reg, self._scale) = self.SCALES[gauss] self.HMC5883L_CRA =0x00 self.HMC5883L_CRB =0x01 self.HMC5883L_MR =0x02 self.HMC5883L_DXRA =0x03 self.HMC5883L_DXRB =0x04 self.HMC5883L_DYRA =0x05 self.HMC5883L_DYRB =0x06 self.HMC5883L_DZRA =0x07 self.HMC5883L_DZRB =0x08 self.HMC5883L_SR =0x09 self.HMC5883L_IRA =0x0A self.HMC5883L_IRB =0x0B self.HMC5883L_IRC =0x0C def initialize(self): reg, self._scale = self.SCALES[self._gauss] self.bus.read_byte(self.address) self.bus.write_byte_data(self.address, self.HMC5883L_CRA, 0x70) # 8 Average, 15 Hz, normal measurement self.bus.write_byte_data(self.address, self.HMC5883L_CRB, reg << 5) # Scale self.bus.write_byte_data(self.address, self.HMC5883L_MR, 0x00) # Continuous measurement LOGGER.debug("Byte data %s to register %s to address %s writen", bin(self.bus.read_byte_data(self.address, self.HMC5883L_MR)), hex(self.HMC5883L_MR), hex(self.address)) self.x = [0, 0, 0] # min, max, offset self.y = [0, 0, 0] self.z = [0, 0, 0] def axes(self, offset = False): """returns measured value in miligauss""" reg, self._scale = self.SCALES[self._gauss] x = self.bus.read_int16_data(self.address, self.HMC5883L_DXRA) if x == -4096: x = OVERFLOW y = self.bus.read_int16_data(self.address, self.HMC5883L_DYRA) if y == -4096: y = OVERFLOW z = self.bus.read_int16_data(self.address, self.HMC5883L_DZRA) if z == -4096: z = OVERFLOW x*=self._scale y*=self._scale z*=self._scale if offset: (x, y, z) = self.__offset((x,y,z)) return (x, y, z) def __str__(self): (x, y, z) = self.axes() return "Axis X: " + str(x) + "\n" \ "Axis Y: " + str(y) + "\n" \ "Axis Z: " + str(z) + "\n" \ def __offset(self, read): (x, y, z) = read if x < self.x[0]: self.x[0] = x if x > self.x[1]: self.x[1] = x if y < self.y[0]: self.y[0] = y if y > self.y[1]: self.y[1] = y if z < self.z[0]: self.z[0] = z if z > self.z[1]: self.z[1] = z x = x - (self.x[0]+self.x[1])/2 y = y - (self.y[0]+self.y[1])/2 z = z - (self.z[0]+self.z[1])/2 return (x, y, z) def get_azimuth(self, offset = -90): (x, y, z) = self.axes(offset = True) heading = math.atan2(y, x) if heading < 0: heading += 2*math.pi if heading > 2*math.pi: heading -= 2*math.pi heading = heading * 180/math.pi; heading += offset if heading > 360: heading -= 360 if heading < 0: heading += 360 return 360-heading
class MAG01(Device): ''' Example: ''' def __init__(self, parent = None, address = 0x1E, gauss = 4.0, **kwargs): pass def initialize(self): pass def axes(self, offset = False): '''returns measured value in miligauss''' pass def __str__(self): pass def __offset(self, read): pass def get_azimuth(self, offset = -90): pass
7
2
15
3
12
1
3
0.1
1
1
0
0
6
18
6
14
112
27
81
35
74
8
81
35
74
7
2
1
20
147,758
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/i2cio.py
pymlab.sensors.i2cio.I2CIO
class I2CIO(Device): 'Python library for I2CIO01A MLAB module with Texas Instruments TCA9535 I/O expander' def __init__(self, parent = None, address = 0x27, **kwargs): Device.__init__(self, parent, address, **kwargs) self.IO_INPUT0 = 0x00 self.IO_INPUT1 = 0x01 self.IO_OUTPUT0 = 0x02 self.IO_OUTPUT1 = 0x03 self.IO_POLARITY0 = 0x04 self.IO_POLARITY1 = 0x05 self.IO_CONFIGURATION0 = 0x06 self.IO_CONFIGURATION1 = 0x07 def get_port0(self): self.bus.read_byte_data(self.address, self.IO_INPUT0) def get_port1(self): self.bus.read_byte_data(self.address, self.IO_INPUT1) def set_output0(self, port0): self.bus.write_byte_data(self.address, self.IO_OUTPUT0, port0) def set_output1(self, port1): self.bus.write_byte_data(self.address, self.IO_OUTPUT1, port1) def set_polarity0(self, port0): self.bus.write_byte_data(self.address, self.IO_POLARITY0, port0) def set_polarity1(self, port1): self.bus.write_byte_data(self.address, self.IO_POLARITY1, port1) def set_config0(self, port0): self.bus.write_byte_data(self.address, self.IO_CONFIGURATION0, port0) def set_config1(self, port1): self.bus.write_byte_data(self.address, self.IO_CONFIGURATION1, port1)
class I2CIO(Device): '''Python library for I2CIO01A MLAB module with Texas Instruments TCA9535 I/O expander''' def __init__(self, parent = None, address = 0x27, **kwargs): pass def get_port0(self): pass def get_port1(self): pass def set_output0(self, port0): pass def set_output1(self, port1): pass def set_polarity0(self, port0): pass def set_polarity1(self, port1): pass def set_config0(self, port0): pass def set_config1(self, port1): pass
10
1
3
0
3
0
1
0.04
1
0
0
0
9
8
9
17
46
18
27
18
17
1
27
18
17
1
2
0
9
147,759
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/i2chub.py
pymlab.sensors.i2chub.I2CHub
class I2CHub(Device): """Python library for I2CHUB02A MLAB module with TCA9548A i2c bus expander. Example: .. code-block:: python #!/usr/bin/python # Python library for I2CHUB02A MLAB module with TCA9548A i2c bus expander. # Example code # Program takes two arguments import time import I2CHUB02 import sys # Example of example use: # sudo ./I2CHUB02_Example.py 5 hub = I2CHUB02.i2chub(int(sys.argv[1]),eval(sys.argv[2])) print "Get initial I2CHUB setup:" print "I2CHUB channel setup:", bin(hub.status()); #print "Setup I2CHUB to channel configuration: ", bin(hub.ch0 |hub.ch2 | hub.ch3 | hub.ch7); #hub.setup(hub.ch0 |hub.ch2 | hub.ch3 | hub.ch7); #this connect the channels O and 7 on the I2CHUB02A togeather with master bus. print "Setup I2CHUB to channel configuration: ", bin(eval(sys.argv[3])); hub.setup(eval(sys.argv[3])); time.sleep(0.1); print "final I2C hub channel status: ", bin(hub.status()); """ ch0 = 0b00000001 ch1 = 0b00000010 ch2 = 0b00000100 ch3 = 0b00001000 ch4 = 0b00010000 ch5 = 0b00100000 ch6 = 0b01000000 ch7 = 0b10000000 ALL_CHANNELS = 0b11111111 def __init__(self, parent = None, address=0x70, **kwargs): Device.__init__(self, parent, address, **kwargs) self.channels = {} for channel in range(8): self.channels[channel] = SimpleBus( self, None, channel = channel, ) self._status = None def __getitem__(self, key): return self.channels[key] @property def status(self): if self._status is None: self._status = self.get_status() return self._status def get_named_devices(self): if self.name is None: result = {} else: result = { self.name: self, } for channel in self.channels.values(): result.update(channel.get_named_devices()) return result def add_child(self, device): if device.channel is None: raise ValueError("Device doesn't have a channel.") self.channels[device.channel].add_child(device) def route(self, child = None): if self.routing_disabled: return False if child is None: return Device.route(self) LOGGER.debug("Routing multiplexer to %r" % (child, )) if child.channel is None: LOGGER.error("Child doesn't have a channel: %r" % (child, )) return False self.routing_disabled = True mask = 1 << child.channel if (self.status != mask): self.setup(mask) self.routing_disabled = False #self.setup(child.channel) return True def initialize(self): Device.initialize(self) for channel, bus in self.channels.items(): self.setup(1 << channel) bus.initialize() self.setup(self.ALL_CHANNELS) def setup(self, i2c_channel_setup): self._status = i2c_channel_setup if self.bus is None: raise Exception( "Cannot setup device %s, because it doesn't have a bus (none of its parents is a bus)." % ( self.name ) ) self.bus.write_byte(self.address, i2c_channel_setup) return -1 def get_status(self): self.route() self._status = self.bus.read_byte(self.address) return self._status
class I2CHub(Device): '''Python library for I2CHUB02A MLAB module with TCA9548A i2c bus expander. Example: .. code-block:: python #!/usr/bin/python # Python library for I2CHUB02A MLAB module with TCA9548A i2c bus expander. # Example code # Program takes two arguments import time import I2CHUB02 import sys # Example of example use: # sudo ./I2CHUB02_Example.py 5 hub = I2CHUB02.i2chub(int(sys.argv[1]),eval(sys.argv[2])) print "Get initial I2CHUB setup:" print "I2CHUB channel setup:", bin(hub.status()); #print "Setup I2CHUB to channel configuration: ", bin(hub.ch0 |hub.ch2 | hub.ch3 | hub.ch7); #hub.setup(hub.ch0 |hub.ch2 | hub.ch3 | hub.ch7); #this connect the channels O and 7 on the I2CHUB02A togeather with master bus. print "Setup I2CHUB to channel configuration: ", bin(eval(sys.argv[3])); hub.setup(eval(sys.argv[3])); time.sleep(0.1); print "final I2C hub channel status: ", bin(hub.status()); ''' def __init__(self, parent = None, address=0x70, **kwargs): pass def __getitem__(self, key): pass @property def status(self): pass def get_named_devices(self): pass def add_child(self, device): pass def route(self, child = None): pass def initialize(self): pass def setup(self, i2c_channel_setup): pass def get_status(self): pass
11
1
8
1
7
0
2
0.32
1
4
1
0
9
3
9
17
129
31
74
28
63
24
64
27
54
5
2
1
20
147,760
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/gpio.py
pymlab.sensors.gpio.USBI2C_GPIO
class USBI2C_GPIO(Gpio): IN = 0b0 OUT = 0b1 OPEN_DRAIN = 0b0 PUSH_PULL = 0b1 SPECIAL_ALL = 0b11100000 SPECIAL_LED = 0b11000000 SPECIAL_CLK = 0b00100000 SPECIAL_OFF = 0b00000000 PIN_COUNT = 8 def __init__(self, parent = None, **kwargs): Gpio.__init__(self, parent, None, **kwargs) def initialize(self): print(self.bus.driver.__class__) if not self.bus.driver.__class__.__name__ == 'HIDDriver': raise ValueError("This {!r} GPIO device requires a 'HIDdriver' driver.".format(self.name)) self.g_direction = self.bus.driver.gpio_direction self.g_pushpull = self.bus.driver.gpio_pushpull self.g_special = self.bus.driver.gpio_special self.g_clockdiv = self.bus.driver.gpio_clockdiv def update_gpio(self): return self.bus.driver.write_hid([0x02, self.g_direction, self.g_pushpull, self.g_special, self.g_clockdiv]) def setup(self, pin, direction = 0b0, push_pull = 0b0): if not (-1 < pin < self.PIN_COUNT): raise ValueError("GPIO pin (%i) is out or range [0,7]." %pin) if direction: self.g_direction = (self.g_direction | (1<<pin)) else: self.g_direction = (self.g_direction & ~(1<<pin)) if push_pull: self.g_pushpull = (self.g_pushpull | (1<<pin)) else: self.g_pushpull = (self.g_pushpull & ~(1<<pin)) self.update_gpio() def output(self, pin, value): #TODO: Overeni, jestli pin je nastaven jakou output a nasledne udelat chybu # a jestli se nezapisuje na 'special pin' if False: raise ValueError("Pin is not set as OUTput.") self.bus.driver.write_hid([0x04, (bool(value)<<pin), (1 << pin)]) def set_special(self, special = None, divider = None): if special: self.g_special = special if divider: self.g_clockdiv = divider self.update_gpio()
class USBI2C_GPIO(Gpio): def __init__(self, parent = None, **kwargs): pass def initialize(self): pass def update_gpio(self): pass def setup(self, pin, direction = 0b0, push_pull = 0b0): pass def output(self, pin, value): pass def set_special(self, special = None, divider = None): pass
7
0
6
1
5
0
2
0.05
1
2
0
0
6
4
6
19
52
12
38
20
31
2
42
20
35
4
3
1
13
147,761
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/gpio.py
pymlab.sensors.gpio.TCA6416A
class TCA6416A(Device): 'Python library for I2CIO01A MLAB module with Texas Instruments TCA6416A I/O expander' def __init__(self, parent = None, address = 0x21, **kwargs): Device.__init__(self, parent, address, **kwargs) self.STATUS_PORT0 = 0x00 self.STATUS_PORT1 = 0x01 self.OUTPUT_PORT0 = 0x02 self.OUTPUT_PORT1 = 0x03 self.POLARITY_PORT0 = 0x04 self.POLARITY_PORT1 = 0x05 self.CONTROL_PORT0 = 0x06 self.CONTROL_PORT1 = 0x07 def set_polarity(self, port0 = 0x00, port1 = 0x00): self.bus.write_byte_data(self.address, self.POLARITY_PORT0, port0) self.bus.write_byte_data(self.address, self.POLARITY_PORT1, port1) return #self.bus.read_byte_data(self.address, self.POLARITY_PORT0), self.bus.read_byte_data(self.address, self.PULLUP_PORT1) def config_ports(self, port0 = 0x00, port1 = 0x00): self.bus.write_byte_data(self.address, self.CONTROL_PORT0, port0) self.bus.write_byte_data(self.address, self.CONTROL_PORT1, port1) return def set_ports(self, port0 = 0x00, port1 = 0x00): self.bus.write_byte_data(self.address, self.OUTPUT_PORT0, port0) self.bus.write_byte_data(self.address, self.OUTPUT_PORT1, port1) return def get_ports(self): 'Reads logical values at pins.' return (self.bus.read_byte_data(self.address, self.STATUS_PORT0), self.bus.read_byte_data(self.address, self.STATUS_PORT1)); def get_config(self): 'Reads logical values at pins.' return (self.bus.read_byte_data(self.address, self.CONTROL_PORT0), self.bus.read_byte_data(self.address, self.CONTROL_PORT1));
class TCA6416A(Device): '''Python library for I2CIO01A MLAB module with Texas Instruments TCA6416A I/O expander''' def __init__(self, parent = None, address = 0x21, **kwargs): pass def set_polarity(self, port0 = 0x00, port1 = 0x00): pass def config_ports(self, port0 = 0x00, port1 = 0x00): pass def set_ports(self, port0 = 0x00, port1 = 0x00): pass def get_ports(self): '''Reads logical values at pins.''' pass def get_config(self): '''Reads logical values at pins.''' pass
7
3
5
1
4
1
1
0.15
1
0
0
0
6
8
6
14
40
10
27
15
20
4
27
15
20
1
2
0
6
147,762
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/gpio.py
pymlab.sensors.gpio.PCA9635
class PCA9635(Device): """ Python library for PCA9635 """ def __init__(self, parent = None, address = 0x01, fault_queue = 1, **kwargs): Device.__init__(self, parent, address, **kwargs) ## register definitions self.MODE1 = 0x00 self.MODE2 = 0x01 self.LEDOUT0 = 0x14 self.LEDOUT1 = 0x15 self.LEDOUT2 = 0x16 self.LEDOUT3 = 0x17 self.PWM00 = 0x02 self.PWM01 = 0x03 self.PWM02 = 0x04 self.PWM03 = 0x05 self.PWM04 = 0x06 self.PWM05 = 0x07 self.PWM06 = 0x08 self.PWM07 = 0x09 self.PWM08 = 0x0A self.PWM09 = 0x0B self.PWM10 = 0x0C self.PWM11 = 0x0D self.PWM12 = 0x0E self.PWM13 = 0x0F self.PWM14 = 0x10 self.PWM15 = 0x11 ## config parameters self.led00_config = (0xAA) self.led01_config = (0xAA) self.mode1_config = (0x00) self.mode2_config = (0x01) def get_mode1(self): DATA = self.bus.read_byte_data(self.address, self.MODE1) Ecal = 1 * DATA return Ecal def get_mode2(self): DATA = self.bus.read_byte_data(self.address, self.MODE2) Ecal = 1 * DATA return Ecal def get_pwm00 (self): DATA = self.bus.read_byte_data(self.address, self.PWM00 ) Ecal = 1 * DATA return Ecal def get_ledout0(self): DATA = self.bus.read_byte_data(self.address, self.LEDOUT0) Ecal = 1 * DATA return Ecal def config(self): self.bus.write_byte_data(self.address, self.LEDOUT0, self.led00_config) self.bus.write_byte_data(self.address, self.LEDOUT1, self.led01_config) self.bus.write_byte_data(self.address, self.MODE1, self.mode1_config) self.bus.write_byte_data(self.address, self.MODE2, self.mode2_config) return def pwm00_set(self, value): self.bus.write_byte_data(self.address, self.PWM00, value) return def pwm01_set(self, value): self.bus.write_byte_data(self.address, self.PWM01, value) return def pwm02_set(self, value): self.bus.write_byte_data(self.address, self.PWM02, value) return def pwm03_set(self, value): self.bus.write_byte_data(self.address, self.PWM03, value) return def pwm04_set(self, value): self.bus.write_byte_data(self.address, self.PWM04, value) return def pwm05_set(self, value): self.bus.write_byte_data(self.address, self.PWM05, value) return def pwm06_set(self, value): self.bus.write_byte_data(self.address, self.PWM06, value) return def pwm07_set(self, value): self.bus.write_byte_data(self.address, self.PWM07, value) return
class PCA9635(Device): ''' Python library for PCA9635 ''' def __init__(self, parent = None, address = 0x01, fault_queue = 1, **kwargs): pass def get_mode1(self): pass def get_mode2(self): pass def get_pwm00 (self): pass def get_ledout0(self): pass def config(self): pass def pwm00_set(self, value): pass def pwm01_set(self, value): pass def pwm02_set(self, value): pass def pwm03_set(self, value): pass def pwm04_set(self, value): pass def pwm05_set(self, value): pass def pwm06_set(self, value): pass def pwm07_set(self, value): pass
15
1
6
0
5
0
1
0.07
1
0
0
0
14
26
14
22
98
18
75
49
60
5
75
49
60
1
2
0
14
147,763
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/gpio.py
pymlab.sensors.gpio.I2CIO_TCA9535
class I2CIO_TCA9535(Device): 'Python library for I2CIO01A MLAB module with Texas Instruments TCA9535 I/O expander' def __init__(self, parent = None, address = 0x27, **kwargs): Device.__init__(self, parent, address, **kwargs) 'The Input Port registers (registers 0 and 1) reflect the incoming logic levels of the pins, regardless of whether thepin is defined as an input or an output by the Configuration Register. It only acts on read operation. Writes to these registers have no effect. The default value, X, is determined by the externally applied logic level. Before a read operation, a write transmission is sent with the command byte to let the I 2 C device know that the Input Port registers will be accessed next.' self.INPUT_PORT0 = 0x00 self.INPUT_PORT1 = 0x01 'The Output Port registers (registers 2 and 3) show the outgoing logic levels of the pins defined as outputs by the Configuration register. Bit values in this register have no effect on pins defined as inputs. In turn, reads from this register reflect the value that is in the flip-flop controlling the output selection, not the actual pin value.' self.OUTPUT_PORT0 = 0x02 self.OUTPUT_PORT1 = 0x03 'The Polarity Inversion registers (registers 4 and 5) allow polarity inversion of pins defined as inputs by the Configuration register. If a bit in this register is set (written with 1), the corresponding pins polarity is inverted. If a bit in this register is cleared (written with a 0), the corresponding pins original polarity is retained.' self.POLARITY_PORT0 = 0x04 self.POLARITY_PORT1 = 0x05 'The Configuration registers (registers 6 and 7) configure the directions of the I/O pins. If a bit in this register is set to 1, the corresponding port pin is enabled as an input with a high-impedance output driver. If a bit in this register is cleared to 0, the corresponding port pin is enabled as an output.' self.CONTROL_PORT0 = 0x06 self.CONTROL_PORT1 = 0x07 def set_polarity(self, port0 = 0x00, port1 = 0x00): self.bus.write_byte_data(self.address, self.POLARITY_PORT0, port0) self.bus.write_byte_data(self.address, self.POLARITY_PORT1, port1) return True #self.bus.read_byte_data(self.address, self.POLARITY_PORT0), self.bus.read_byte_data(self.address, self.PULLUP_PORT1) def config_ports(self, port0 = 0x00, port1 = 0x00): self.bus.write_byte_data(self.address, self.CONTROL_PORT0, port0) self.bus.write_byte_data(self.address, self.CONTROL_PORT1, port1) return True def set_ports(self, port0 = 0x00, port1 = 0x00): 'Writes specified value to the pins defined as output by config_ports() method. Writing to input pins has no effect.' self.bus.write_byte_data(self.address, self.OUTPUT_PORT0, port0) self.bus.write_byte_data(self.address, self.OUTPUT_PORT1, port1) return True def get_ports(self): 'Reads logical values at pins.' return (self.bus.read_byte_data(self.address, self.STATUS_PORT0), self.bus.read_byte_data(self.address, self.STATUS_PORT1));
class I2CIO_TCA9535(Device): '''Python library for I2CIO01A MLAB module with Texas Instruments TCA9535 I/O expander''' def __init__(self, parent = None, address = 0x27, **kwargs): pass def set_polarity(self, port0 = 0x00, port1 = 0x00): pass def config_ports(self, port0 = 0x00, port1 = 0x00): pass def set_ports(self, port0 = 0x00, port1 = 0x00): '''Writes specified value to the pins defined as output by config_ports() method. Writing to input pins has no effect.''' pass def get_ports(self): '''Reads logical values at pins.''' pass
6
3
7
1
5
1
1
0.32
1
0
0
0
5
8
5
13
40
8
25
14
19
8
25
14
19
1
2
0
5
147,764
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/gpio.py
pymlab.sensors.gpio.DS4520
class DS4520(Device): 'Python library for Dallas DS4520 I/O expander' def __init__(self, parent = None, address = 0x50, **kwargs): Device.__init__(self, parent, address, **kwargs) """ I/O control for I/O_0 to I/O_7. I/O_0 is the LSB and I/O_7 is the MSB. Clearing the corresponding bit of the register pulls the selected I/O pin low; setting the bit places the pulldown transistor into a high-impedance state. When the pulldown is high impedance, the output floats if no pullup/down is connected to the pin""" self.CONTROL_PORT0 = 0xF2 self.CONTROL_PORT1 = 0xF3 'Pullup enable for I/O_8. I/O_8 is the LSB. Only the LSB is used. Set the LSB bit to enable the pullup on I/O_8; clear the LSB to disable the pullup' self.PULLUP_PORT0 = 0xF0 self.PULLUP_PORT1 = 0xF1 'I/O status for I/O_0 to I/O_7. I/O_0 is the LSB and I/O_7 is the MSB. Writing to this register has no effect. Read this register to determine the state of the I/O_0 to I/O_7 pins.' self.STATUS_PORT0 = 0xF8 self.STATUS_PORT1 = 0xF9 def set_pullups(self, port0 = 0x00, port1 = 0x00): 'Sets INPUT (1) or OUTPUT (0) direction on pins. Inversion setting is applicable for input pins 1-inverted 0-noninverted input polarity.' self.bus.write_byte_data(self.address, self.PULLUP_PORT0, port0) self.bus.write_byte_data(self.address, self.PULLUP_PORT1, port1) return #self.bus.read_byte_data(self.address, self.PULLUP_PORT0), self.bus.read_byte_data(self.address, self.PULLUP_PORT1) def set_ports(self, port0 = 0x00, port1 = 0x00): 'Writes specified value to the pins defined as output by method. Writing to input pins has no effect.' self.bus.write_byte_data(self.address, self.CONTROL_PORT0, port0) self.bus.write_byte_data(self.address, self.CONTROL_PORT0, port1) return def get_ports(self): 'Reads logical values at pins.' return self.bus.read_byte_data(self.address, self.STATUS_PORT0), self.bus.read_byte_data(self.address, self.STATUS_PORT1);
class DS4520(Device): '''Python library for Dallas DS4520 I/O expander''' def __init__(self, parent = None, address = 0x50, **kwargs): pass def set_pullups(self, port0 = 0x00, port1 = 0x00): '''Sets INPUT (1) or OUTPUT (0) direction on pins. Inversion setting is applicable for input pins 1-inverted 0-noninverted input polarity.''' pass def set_ports(self, port0 = 0x00, port1 = 0x00): '''Writes specified value to the pins defined as output by method. Writing to input pins has no effect.''' pass def get_ports(self): '''Reads logical values at pins.''' pass
5
4
8
1
5
3
1
0.68
1
0
0
0
4
6
4
12
38
7
19
11
14
13
19
11
14
1
2
0
4
147,765
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/clkgen.py
pymlab.sensors.clkgen.CLKGEN01
class CLKGEN01(Device): """Lilbary for Si571 and Si570 clock generator ICs""" def __init__(self, parent = None, address = 0x55, **kwargs): Device.__init__(self, parent, address, **kwargs) self.R_HS = 7 self.R_RFREQ4 = 8 self.R_RFREQ3 = 9 self.R_RFREQ2 = 10 self.R_RFREQ1 = 11 self.R_RFREQ0 = 12 self.R_RFMC = 135 self.R_FDCO = 137 self.HS_DIV_MASK = 0xE0 self.N1_H_MASK = 0x1F self.N1_L_MASK = 0xC0 self.RFREQ4_MASK = 0x3F self.RFMC_RST = (1<<7) self.RFMC_NEW_FREQ = (1<<6) self.RFMC_FREEZE_M = (1<<5) self.RFMC_FREEZE_VCADC = (1<<4) self.RFMC_RECALL = (1<<0) self.FDCO_FREEZE_DCO = (1<<4) def get_rfreq(self): rfreq = self.bus.read_byte_data(self.address,self.R_RFREQ0) rfreq |= (self.bus.read_byte_data(self.address,self.R_RFREQ1)<<8) rfreq |= (self.bus.read_byte_data(self.address,self.R_RFREQ2)<<16) rfreq |= (self.bus.read_byte_data(self.address,self.R_RFREQ3)<<24) rfreq |= ((self.bus.read_byte_data(self.address,self.R_RFREQ4) & self.RFREQ4_MASK)<<32) return rfreq/2.0**28 def get_n1_div(self): n1 = ((self.bus.read_byte_data(self.address, self.R_HS) & self.N1_H_MASK)<<2) n1 |= self.bus.read_byte_data(self.address, self.R_RFREQ4)>>6 return n1+1 def get_hs_div(self): return (((self.bus.read_byte_data(self.address, self.R_HS))>>5) + 4) def set_rfreq(self, freq): freq_int = int(freq * (2.0**28)) reg = self.bus.read_byte_data(self.address, self.R_RFREQ4) self.bus.write_byte_data(self.address, self.R_RFREQ4, (((freq_int>>32) & self.RFREQ4_MASK) | (reg & self.N1_L_MASK))) self.bus.write_byte_data(self.address, self.R_RFREQ0, (freq_int & 0xFF)) self.bus.write_byte_data(self.address, self.R_RFREQ1, ((freq_int>>8) & 0xFF)) self.bus.write_byte_data(self.address, self.R_RFREQ2, ((freq_int>>16) & 0xFF)) self.bus.write_byte_data(self.address, self.R_RFREQ3, ((freq_int>>24) & 0xFF)) def set_hs_div(self, div): reg = self.bus.read_byte_data(self.address, self.R_HS) self.bus.write_byte_data(self.address, self.R_HS, (((div-4)<<5) | (reg & self.N1_H_MASK))) def set_n1_div(self, div): div = div - 1 reg = self.bus.read_byte_data(self.address, self.R_HS) self.bus.write_byte_data(self.address, self.R_HS, (((div>>2) & self.N1_H_MASK) | (reg & self.HS_DIV_MASK))) reg = self.bus.read_byte_data(self.address, self.R_RFREQ4) self.bus.write_byte_data(self.address, self.R_RFREQ4, (((div<<6) & self.N1_L_MASK) | (reg & self.RFREQ4_MASK))) def freeze_m(self): self.bus.write_byte_data(self.address, self.R_RFMC, self.RFMC_FREEZE_M) def unfreeze_m(self): self.bus.write_byte_data(self.address, self.R_RFMC, 0) def new_freq(self): self.bus.write_byte_data(self.address, self.R_RFMC, self.RFMC_NEW_FREQ) def reset(self): #Will interrupt I2C state machine. It is not reccomended for starting from initial conditions. reg = self.bus.read_byte_data(self.address, self.R_RFMC) | self.RFMC_RST self.bus.write_byte_data(self.address, self.R_RFMC, reg) def freeze_dco(self): self.bus.write_byte_data(self.address, self.R_FDCO, self.FDCO_FREEZE_DCO) def unfreeze_dco(self): self.bus.write_byte_data(self.address, self.R_FDCO, 0) def reset_reg(self): reg = self.bus.read_byte_data(self.address, self.R_RFMC) | self.RFMC_RST self.bus.write_byte_data(self.address, self.R_RFMC, reg) def recall_nvm(self): # reloads NVM data. It is recommended for starting from initial conditions. reg = self.bus.read_byte_data(self.address, self.R_RFMC) | self.RFMC_RECALL self.bus.write_byte_data(self.address, self.R_RFMC, reg) def set_freq(self, fout, freq): """ Sets new output frequency, required parameters are real current frequency at output and new required frequency. """ hsdiv_tuple = (4, 5, 6, 7, 9, 11) # possible dividers n1div_tuple = (1,) + tuple(range(2,129,2)) # fdco_min = 5670.0 # set maximum as minimum hsdiv = self.get_hs_div() # read curent dividers n1div = self.get_n1_div() # if abs((freq-fout)*1e6/fout) > 3500: # check if new requested frequency is withing 3500 ppm from last Center Frequency Configuration # Large change of frequency fdco = fout * hsdiv * n1div # calculate high frequency oscillator fxtal = fdco / self.get_rfreq() # should be fxtal = 114.285 for hsdiv_iter in hsdiv_tuple: # find dividers with minimal power consumption for n1div_iter in n1div_tuple: fdco_new = freq * hsdiv_iter * n1div_iter if (fdco_new >= 4850) and (fdco_new <= 5670): if (fdco_new <= fdco_min): fdco_min = fdco_new hsdiv = hsdiv_iter n1div = n1div_iter rfreq = fdco_min / fxtal self.freeze_dco() # write registers self.set_hs_div(hsdiv) self.set_n1_div(n1div) self.set_rfreq(rfreq) self.unfreeze_dco() self.new_freq() else: # Small change of frequency rfreq = self.get_rfreq() * (freq/fout) self.freeze_m() # write registers self.set_rfreq(rfreq) self.unfreeze_m() # For Si571 only ! def freeze_vcadc(self): reg = self.bus.read_byte_data(self.address, self.R_RFMC) | self.RFMC_FREEZE_VCADC self.bus.write_byte_data(self.address, self.R_RFMC, reg) def unfreeze_vcadc(self): reg = self.bus.read_byte_data(self.address, self.R_RFMC) & ~(self.RFMC_FREEZE_VCADC) self.bus.write_byte_data(self.address, self.R_RFMC, reg)
class CLKGEN01(Device): '''Lilbary for Si571 and Si570 clock generator ICs''' def __init__(self, parent = None, address = 0x55, **kwargs): pass def get_rfreq(self): pass def get_n1_div(self): pass def get_hs_div(self): pass def set_rfreq(self, freq): pass def set_hs_div(self, div): pass def set_n1_div(self, div): pass def freeze_m(self): pass def unfreeze_m(self): pass def new_freq(self): pass def reset(self): pass def freeze_dco(self): pass def unfreeze_dco(self): pass def reset_reg(self): pass def recall_nvm(self): pass def set_freq(self, fout, freq): ''' Sets new output frequency, required parameters are real current frequency at output and new required frequency. ''' pass def freeze_vcadc(self): pass def unfreeze_vcadc(self): pass
19
2
7
0
6
1
1
0.19
1
3
0
0
18
18
18
26
140
28
105
59
86
20
104
59
85
6
2
5
23
147,766
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/bus_translators.py
pymlab.sensors.bus_translators.I2CSPI
class I2CSPI(Device): 'Python library for SC18IS602B chip in I2CSPI MLAB bridge module.' def __init__(self, parent = None, address = 0x2E, **kwargs): Device.__init__(self, parent, address, **kwargs) self.I2CSPI_SS0 = 0b0001 self.I2CSPI_SS1 = 0b0010 self.I2CSPI_SS2 = 0b0100 self.I2CSPI_SS3 = 0b1000 self.SS0_BIDIRECT = 0b00 self.SS0_PUSHPULL = 0b01 self.SS0_INPUT = 0b10 self.SS0_OPENDRAIN = 0b11 self.SS1_BIDIRECT = 0b0000 self.SS1_PUSHPULL = 0b0100 self.SS1_INPUT = 0b1000 self.SS1_OPENDRAIN = 0b1100 self.SS2_BIDIRECT = 0b000000 self.SS2_PUSHPULL = 0b010000 self.SS2_INPUT = 0b100000 self.SS2_OPENDRAIN = 0b110000 self.SS3_BIDIRECT = 0b00000000 self.SS3_PUSHPULL = 0b01000000 self.SS3_INPUT = 0b10000000 self.SS3_OPENDRAIN = 0b11000000 self.I2CSPI_MSB_FIRST = 0b0 self.I2CSPI_LSB_FIRST = 0b100000 self.I2CSPI_MODE_CLK_IDLE_LOW_DATA_EDGE_LEADING = 0b0000 # SPICLK LOW when idle; data clocked in on leading edge (CPOL = 0, CPHA = 0) self.I2CSPI_MODE_CLK_IDLE_LOW_DATA_EDGE_TRAILING = 0b0100 # SPICLK LOW when idle; data clocked in on trailing edge (CPOL = 0, CPHA = 1) self.I2CSPI_MODE_CLK_IDLE_HIGH_DATA_EDGE_TRAILING = 0b1000 # SPICLK HIGH when idle; data clocked in on trailing edge (CPOL = 1, CPHA = 0) self.I2CSPI_MODE_CLK_IDLE_HIGH_DATA_EDGE_LEADING = 0b1100 # SPICLK HIGH when idle; data clocked in on leading edge (CPOL = 1, CPHA = 1) self.I2CSPI_CLK_1843kHz = 0b00 self.I2CSPI_CLK_461kHz = 0b01 self.I2CSPI_CLK_115kHz = 0b10 self.I2CSPI_CLK_58kHz = 0b11 def SPI_write_byte(self, chip_select, data): 'Writes a data to a SPI device selected by chipselect bit. ' self.bus.write_byte_data(self.address, chip_select, data) def SPI_read_byte(self): 'Reads a data from I2CSPI buffer. ' #return self.bus.read_i2c_block_data(self.address, 0xF1) # Clear interrupt and read data return self.bus.read_byte(self.address) def SPI_write(self, chip_select, data): 'Writes data to SPI device selected by chipselect bit. ' dat = list(data) dat.insert(0, chip_select) return self.bus.write_i2c_block(self.address, dat); # up to 8 bytes may be written. def SPI_read(self, length): 'Reads data from I2CSPI buffer. ' return self.bus.read_i2c_block(self.address, length) def SPI_config(self,config): 'Configure SPI interface parameters.' self.bus.write_byte_data(self.address, 0xF0, config) return self.bus.read_byte_data(self.address, 0xF0) def SPI_clear_INT(self): 'Clears an interrupt at INT pin generated after the SPI transmission has been completed. ' return self.bus.write_byte(self.address, 0xF1) def Idle_mode(self): 'Turns the bridge to low power idle mode.' return self.bus.write_byte(self.address, 0xF2) def GPIO_write(self, value): 'Write data to GPIO enabled slave-selects pins.' return self.bus.write_byte_data(self.address, 0xF4, value) def GPIO_read(self): 'Reads logic state on GPIO enabled slave-selects pins.' self.bus.write_byte_data(self.address, 0xF5, 0x0f) status = self.bus.read_byte(self.address) bits_values = dict([('SS0',status & 0x01 == 0x01),('SS1',status & 0x02 == 0x02),('SS2',status & 0x04 == 0x04),('SS3',status & 0x08 == 0x08)]) return bits_values def GPIO_config(self, gpio_enable, gpio_config): 'Enable or disable slave-select pins as gpio.' self.bus.write_byte_data(self.address, 0xF6, gpio_enable) self.bus.write_byte_data(self.address, 0xF7, gpio_config) return
class I2CSPI(Device): '''Python library for SC18IS602B chip in I2CSPI MLAB bridge module.''' def __init__(self, parent = None, address = 0x2E, **kwargs): pass def SPI_write_byte(self, chip_select, data): '''Writes a data to a SPI device selected by chipselect bit. ''' pass def SPI_read_byte(self): '''Reads a data from I2CSPI buffer. ''' pass def SPI_write_byte(self, chip_select, data): '''Writes data to SPI device selected by chipselect bit. ''' pass def SPI_read_byte(self): '''Reads data from I2CSPI buffer. ''' pass def SPI_config(self,config): '''Configure SPI interface parameters.''' pass def SPI_clear_INT(self): '''Clears an interrupt at INT pin generated after the SPI transmission has been completed. ''' pass def Idle_mode(self): '''Turns the bridge to low power idle mode.''' pass def GPIO_write(self, value): '''Write data to GPIO enabled slave-selects pins.''' pass def GPIO_read(self): '''Reads logic state on GPIO enabled slave-selects pins.''' pass def GPIO_config(self, gpio_enable, gpio_config): '''Enable or disable slave-select pins as gpio.''' pass
12
11
7
1
5
1
1
0.28
1
2
0
0
11
30
11
19
91
18
61
45
49
17
61
45
49
1
2
0
11
147,767
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/atmega.py
pymlab.sensors.atmega.ATMEGA
class ATMEGA(Device): 'Python library for ATmega MLAB module.' def __init__(self, parent = None, address = 0x04, **kwargs): Device.__init__(self, parent, address, **kwargs) def put(self,data): self.bus.write_byte(self.address, data); def get(self): data = self.bus.read_byte(self.address); return data
class ATMEGA(Device): '''Python library for ATmega MLAB module.''' def __init__(self, parent = None, address = 0x04, **kwargs): pass def put(self,data): pass def get(self): pass
4
1
2
0
2
0
1
0.13
1
0
0
0
3
0
3
11
12
3
8
5
4
1
8
5
4
1
2
0
3
147,768
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/altimet.py
pymlab.sensors.altimet.SDP6XX
class SDP6XX(Device): """ Python library for Sensirion SDP6XX/5xx differential preassure sensors. """ def __init__(self, parent = None, address = 0x40, **kwargs): Device.__init__(self, parent, address, **kwargs) self.TRIGGER_MEASUREMENT = 0xF1 # command: trigger differential pressure measurement self.SOFT_RESET = 0xFE # command: soft reset self.READ_USER_REGISTER = 0xE5 # command: read advanced user register self.WRITE_USER_REGISTER = 0xE4 # command: write advanced user register self.RESOLUTION_9BIT = 0x00 self.RESOLUTION_10BIT = 0x01 self.RESOLUTION_11BIT = 0x02 self.RESOLUTION_12BIT = 0x03 self.RESOLUTION_13BIT = 0x04 self.RESOLUTION_14BIT = 0x05 self.RESOLUTION_15BIT = 0x06 self.RESOLUTION_16BIT = 0x07 def get_p(self): self.bus.write_byte(self.address, self.TRIGGER_MEASUREMENT); # trigger measurement data = self.bus.read_i2c_block(self.address, 3) press_data = data[0]<<8 | data[1] if (press_data & 0x1000): press_data -= 65536 return (press_data/60.0) # bit; // bit mask # crc = 0x00; // calculated checksum # byteCtr; // byte counter # # calculates 8-Bit checksum with given polynomial # for(byteCtr = 0; byteCtr < nbrOfBytes; byteCtr++) # crc ^= (data[byteCtr]); # for(bit = 8; bit > 0; --bit) # if(crc & 0x80) crc = (crc << 1) ^ POLYNOMIAL; # else crc = (crc << 1); # verify checksum # if(crc != checksum) return CHECKSUM_ERROR; # else return NO_ERROR; def reset(self): ''' Calls the soft reset mechanism that forces the sensor into a well-defined state without removing the power supply. ''' self.bus.write_byte(self.address, 0xFE); # trigger measurement time.sleep(0.01)
class SDP6XX(Device): ''' Python library for Sensirion SDP6XX/5xx differential preassure sensors. ''' def __init__(self, parent = None, address = 0x40, **kwargs): pass def get_p(self): pass def reset(self): ''' Calls the soft reset mechanism that forces the sensor into a well-defined state without removing the power supply. ''' pass
4
2
12
2
8
3
1
1
1
0
0
0
3
12
3
11
58
14
25
18
21
25
25
18
21
2
2
1
4
147,769
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/altimet.py
pymlab.sensors.altimet.SDP3X
class SDP3X(Device): """ Python library for Sensirion SDP3X differential pressure sensors. """ def __init__(self, parent = None, address = 0x21, **kwargs): Device.__init__(self, parent, address, **kwargs) self.TRIGGER_MEASUREMENT = [0x36, 0x1E] # command: trigger differential pressure measurement self.SOFT_RESET = 0x06 # command: soft reset self.READ_PRODUCT_IDENTIFIER1 = [0x36, 0x7c] # command: read product idetifier register self.READ_PRODUCT_IDENTIFIER2 = [0xE1, 0x02] # self.dpsf = 60.0 # differential pressure sensor scaling factor (dpsf = 60 means resolution of 16.666 mPa / LSB) self.tsf = 200.0 #temperature scaling factor (same for all SDP3X sensors) def get_p(self): raw_data = self.bus.read_i2c_block(self.address, 9) press_data = raw_data[0]<<8 | raw_data[1] if (press_data & 0x1000): press_data -= 65536 dpsf = float(raw_data[6]<<8 | raw_data[7]) # SDP3X sensor scaling factor obtained from byte 6 and 7 of read message return(press_data/dpsf) def get_t(self): raw_data = self.bus.read_i2c_block(self.address, 5) temp_data = data[3]<<8 | data[4] return(temp_data/tsf) def get_tp(self): raw_data = self.bus.read_i2c_block(self.address, 9) press_data = raw_data[0]<<8 | raw_data[1] temp_data = raw_data[3]<<8 | raw_data[4] if (press_data > 0x7fff): press_data -= 65536 if (temp_data > 0x7fff): temp_data -= 65536 dpsf = float(raw_data[6]<<8 | raw_data[7]) # SDP3X sensor scaling factor obtained from byte 6 and 7 of read message return((press_data/dpsf), (temp_data/self.tsf)) # print(data) # self.bus.write_byte_data(self.address, self.READ_PRODUCT_IDENTIFIER1[0], self.READ_PRODUCT_IDENTIFIER1[1]); # trigger measurement # self.bus.write_byte_data(self.address, self.READ_PRODUCT_IDENTIFIER2[0], self.READ_PRODUCT_IDENTIFIER2[1]); # trigger measurement # id_data = self.bus.read_i2c_block_data(self.READ_PRODUCT_IDENTIFIER2[0], self.READ_PRODUCT_IDENTIFIER2[1], 18) # print(id_data) # data1 = self.bus.read_byte(self.address) # print(data1) # print(data) # data = self.bus.read_i2c_block(self.address, 9) # self.bus.write_i2c_block(self.address, self.READ_PRODUCT_IDENTIFIER1); # id_data = self.bus.read_i2c_block_data(self.address, self.READ_PRODUCT_IDENTIFIER2, 18); # id_data = self.bus.read_i2c_block(self.address, 18) # product_number = (id_data[0] << 24) | (id_data[1] << 16) | (id_data[3] << 8) | id_data [4] # print("product_number: ") # print(hex(product_number)) # return (press_data/20.0) def start_meas(self): self.bus.write_byte_data(self.address, self.TRIGGER_MEASUREMENT[0], self.TRIGGER_MEASUREMENT[1]); # trigger measurement time.sleep(0.1) def reset(self): self.bus.write_byte(0x00, self.SOFT_RESET); # soft reset of the sensor time.sleep(0.1)
class SDP3X(Device): ''' Python library for Sensirion SDP3X differential pressure sensors. ''' def __init__(self, parent = None, address = 0x21, **kwargs): pass def get_p(self): pass def get_t(self): pass def get_tp(self): pass def start_meas(self): pass def reset(self): pass
7
1
7
2
6
2
2
0.8
1
1
0
0
6
5
6
14
81
26
35
21
28
28
35
21
28
3
2
1
9
147,770
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/altimet.py
pymlab.sensors.altimet.ALTIMET01
class ALTIMET01(Device): """ Python library for ALTIMET01A MLAB module with MPL3115A2 Freescale Semiconductor i2c altimeter and barometer sensor. """ def __init__(self, parent = None, address = 0x60, **kwargs): Device.__init__(self, parent, address, **kwargs) #MPL3115A register address self.MPL3115_STATUS =0x00 self.MPL3115_PRESSURE_DATA =0x01 self.MPL3115_DR_STATUS =0x06 self.MPL3115_DELTA_DATA =0x07 self.MPL3115_WHO_AM_I =0x0c self.MPL3115_FIFO_STATUS =0x0d self.MPL3115_FIFO_DATA =0x0e self.MPL3115_FIFO_SETUP =0x0e self.MPL3115_TIME_DELAY =0x10 self.MPL3115_SYS_MODE =0x11 self.MPL3115_INT_SORCE =0x12 self.MPL3115_PT_DATA_CFG =0x13 self.MPL3115_BAR_IN_MSB =0x14 self.MPL3115_P_ARLARM_MSB =0x16 self.MPL3115_T_ARLARM =0x18 self.MPL3115_P_ARLARM_WND_MSB =0x19 self.MPL3115_T_ARLARM_WND =0x1b self.MPL3115_P_MIN_DATA =0x1c self.MPL3115_T_MIN_DATA =0x1f self.MPL3115_P_MAX_DATA =0x21 self.MPL3115_T_MAX_DATA =0x24 self.MPL3115_CTRL_REG1 =0x26 self.MPL3115_CTRL_REG2 =0x27 self.MPL3115_CTRL_REG3 =0x28 self.MPL3115_CTRL_REG4 =0x29 self.MPL3115_CTRL_REG5 =0x2a self.MPL3115_OFFSET_P =0x2b self.MPL3115_OFFSET_T =0x2c self.MPL3115_OFFSET_H =0x2d def initialize(self): # Set to Barometer self.bus.write_byte_data(self.address, self.MPL3115_CTRL_REG1, 0xB8); # Enable Data Flags in PT_DATA_CFG self.bus.write_byte_data(self.address, self.MPL3115_PT_DATA_CFG, 0x07) # Set Active, barometer mode with an OSR = 128 self.bus.write_byte_data(self.address, self.MPL3115_CTRL_REG1, 0x39) def get_tp(self): # Read STATUS Register #STA = self.bus.read_byte(MPL3115_STATUS) # check if pressure or temperature are ready (both) [STATUS, 0x00 register] #if (int(STA,16) & 0x04) == 4: # OUT_P p_MSB = self.bus.read_byte_data(self.address,0x01) p_CSB = self.bus.read_byte_data(self.address,0x02) p_LSB = self.bus.read_byte_data(self.address,0x03) t_MSB = self.bus.read_byte_data(self.address,0x04) t_LSB = self.bus.read_byte_data(self.address,0x05) # conversion of register values to measured values according to sensor datasheet #Determine sign and output if (t_MSB > 0x7F): t = float((t_MSB - 256) + (t_LSB >> 4)/16.0) else: t = float(t_MSB + (t_LSB >> 4)/16.0) p = float((p_MSB << 10)|(p_CSB << 2)|(p_LSB >> 6)) + float((p_LSB >> 4)/4.0) return (t, p); def get_press(self): p_MSB = self.bus.read_byte_data(self.address,0x01) p_CSB = self.bus.read_byte_data(self.address,0x02) p_LSB = self.bus.read_byte_data(self.address,0x03) p = float((p_MSB << 10)|(p_CSB << 2)|(p_LSB >> 6)) + float((p_LSB >> 4)/4.0) return p def get_temp(self): t_MSB = self.bus.read_byte_data(self.address,0x04) t_LSB = self.bus.read_byte_data(self.address,0x05) if (t_MSB > 0x7F): t = float((t_MSB - 256) + (t_LSB >> 4)/16.0) else: t = float(t_MSB + (t_LSB >> 4)/16.0) return t
class ALTIMET01(Device): ''' Python library for ALTIMET01A MLAB module with MPL3115A2 Freescale Semiconductor i2c altimeter and barometer sensor. ''' def __init__(self, parent = None, address = 0x60, **kwargs): pass def initialize(self): pass def get_tp(self): pass def get_press(self): pass def get_temp(self): pass
6
1
16
1
12
2
1
0.23
1
1
0
0
5
29
5
13
89
13
62
49
56
14
60
49
54
2
2
1
7
147,771
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/adc.py
pymlab.sensors.adc.VCAI2C01
class VCAI2C01(Device): """ Current loop transducer measurement module. """ def __init__(self, parent = None, address = 0x68 , gain = 1, sample_rate = 240, **kwargs): Device.__init__(self, parent, address, **kwargs) self.rate = sample_rate self.gain = gain self.address = address def initialize(self): self.setADC(sample_rate = self.rate) def setADC(self, channel = 1, gain = 1, continuous = True, sample_rate = 240 ): CHANNEL_CONFIG = { 1: 0b0000000, 2: 0b0100000, 3: 0b1000000, 4: 0b1100000, } RATE_CONFIG = { 240: 0b0000, 60: 0b0100, 15: 0b1000, 3.75: 0b1100, } GAIN_CONFIG = { 1: 0b00, 2: 0b01, 4: 0b10, 8: 0b11, } self.rate = sample_rate self.gain = gain config = int(CHANNEL_CONFIG[channel] + (continuous << 4) + RATE_CONFIG[sample_rate] + GAIN_CONFIG[gain]) self.bus.write_byte(self.address, config) def readADC(self): if self.rate == 240: data = self.bus.read_i2c_block(self.address, 3) # read converted value value = (data[0] & 0x0F) << 8 | data[1] self.config = data[2] elif self.rate == 60: data = self.bus.read_i2c_block(self.address, 3) # read converted value value = (data[0] & 0x3F) << 8 | data[1] self.config = data[2] elif self.rate == 15: data = self.bus.read_i2c_block(self.address, 3) # read converted value value = data[0] << 8 | data[1] self.config = data[2] elif self.rate == 3.75: data = self.bus.read_i2c_block(self.address, 4) # read converted value value = (data[0] & 0x03) << 16 | data[1] << 8 | data[2] self.config = data[3] return value def readVoltage(self): value = self.readADC() if self.rate == 240: value = float(value)/self.gain*3/550 elif self.rate == 60: value = float(value)/self.gain*3/2200 elif self.rate == 15: value = float(value)/self.gain*3/8800 elif self.rate == 3.75: value = float(value)/self.gain*3/35200 return value def readCurrent(self): value = float(self.readVoltage())*1000/249 return value
class VCAI2C01(Device): ''' Current loop transducer measurement module. ''' def __init__(self, parent = None, address = 0x68 , gain = 1, sample_rate = 240, **kwargs): pass def initialize(self): pass def setADC(self, channel = 1, gain = 1, continuous = True, sample_rate = 240 ): pass def readADC(self): pass def readVoltage(self): pass def readCurrent(self): pass
7
1
13
3
10
1
2
0.11
1
2
0
0
6
4
6
14
88
22
63
19
56
7
42
19
35
5
2
1
14
147,772
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/i2clcd.py
pymlab.sensors.i2clcd.I2CLCD
class I2CLCD(Device): """ Example: # Python library for I2C module with alpha-numeric LCD display """ def __init__(self, parent = None, address = 0x27, fault_queue = 1, **kwargs): Device.__init__(self, parent, address, **kwargs) ## register definitions self.backlight = 0b00000000 ## config parameters self.LCD_RS = 0b00000001 self.LCD_RW = 0b00000010 self.LCD_EN = 0b00000100 self.LCD_BL = 0b00001000 def initialize(self): LOGGER.debug("LCD initialized initialized. ") def reset(self): self.bus.write_byte(self.address, 0xFF) time.sleep(20/1000) self.bus.write_byte(self.address, 0x30+self.LCD_EN) self.bus.write_byte(self.address, 0x30) time.sleep(10/1000) self.bus.write_byte(self.address, 0x30+self.LCD_EN) self.bus.write_byte(self.address, 0x30) time.sleep(1/1000) self.bus.write_byte(self.address, 0x30+self.LCD_EN) self.bus.write_byte(self.address, 0x30) time.sleep(1/1000) self.bus.write_byte(self.address, 0x20+self.LCD_EN) self.bus.write_byte(self.address, 0x20) time.sleep(1/1000) def cmd(self, cmd): self.bus.write_byte(self.address, (cmd & 0xF0)|self.LCD_EN | self.LCD_BL ) self.bus.write_byte(self.address, (cmd & 0xF0) | self.LCD_BL) self.bus.write_byte(self.address, ((cmd << 4) & 0xF0)|self.LCD_EN | self.LCD_BL) self.bus.write_byte(self.address, ((cmd << 4) & 0xF0) | self.LCD_BL ) time.sleep(4/1000) def clear(self): self.cmd(0x01) time.sleep(4/1000) def init (self): self.reset() self.cmd(0x0c) self.cmd(0x06) self.cmd(0x80) self.clear() # Function to display single Character def lcd_data(self, dat): self.bus.write_byte(self.address, ( ord(dat) & 0xF0)| self.LCD_EN | self.LCD_RS | self.LCD_BL) self.bus.write_byte(self.address, ( ord(dat) & 0xF0)| self.LCD_RS | self.LCD_BL) self.bus.write_byte(self.address, (( ord(dat) << 4) & 0xF0)| self.LCD_EN | self.LCD_RS | (self.LCD_BL)) self.bus.write_byte(self.address, (( ord(dat) << 4) & 0xF0)| self.LCD_RS | self.LCD_BL) time.sleep(4/1000) #time.sleep(0.5) def puts(self, a): for i in list(str(a)): self.lcd_data(i) def putsFull(self, lineA = None, lineB = None): #self.clear() self.home() time.sleep(0.01) self.clear() if lineA: time.sleep(0.01) self.puts(lineA) if lineB: time.sleep(0.01) self.set_row2() time.sleep(0.01) self.puts(lineB) def set_row2(self): self.cmd(0xc0) def home(self): self.cmd(0x02) def light(self, on = 0): if on: self.LCD_BL = 0b00001000 self.bus.write_byte(self.address, (0 |(self.LCD_BL) )) else: self.LCD_BL = 0b00000000 self.bus.write_byte(self.address, (0 &(~self.LCD_BL) )) def lightToggle(self): if self.LCD_BL == 0b00001000: self.LCD_BL = 0b00000000 self.bus.write_byte(self.address, (0 | self.LCD_BL )) else: self.LCD_BL = 0b00001000 self.bus.write_byte(self.address, (0 | self.LCD_BL ))
class I2CLCD(Device): ''' Example: # Python library for I2C module with alpha-numeric LCD display ''' def __init__(self, parent = None, address = 0x27, fault_queue = 1, **kwargs): pass def initialize(self): pass def reset(self): pass def cmd(self, cmd): pass def clear(self): pass def initialize(self): pass def lcd_data(self, dat): pass def puts(self, a): pass def putsFull(self, lineA = None, lineB = None): pass def set_row2(self): pass def home(self): pass def light(self, on = 0): pass def lightToggle(self): pass
14
1
6
0
6
0
1
0.11
1
2
0
0
13
5
13
21
110
22
79
20
65
9
77
20
63
3
2
1
18
147,773
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/adc.py
pymlab.sensors.adc.LTC2487
class LTC2487(Device): """ Driver for the LTC2487 Linear Technology I2C ADC device. """ def __init__(self, parent = None, address = 0x14, configuration = [0b10111000,0b10011000], **kwargs): Device.__init__(self, parent, address, **kwargs) self.config = configuration def initialize(self): self.bus.write_i2c_block(self.address, self.config) def setADC(self, channel = 0 ): CHANNEL_CONFIG = { 1: 0b00000, 23: 0b00001, 10: 0b01000, 32: 0b01001, 0: 0b10000, 1: 0b11000, 2: 0b10001, 3: 0b11000, } self.config[0] = 0b10100000 + CHANNEL_CONFIG[channel] self.bus.write_i2c_block(self.address, self.config) def readADC(self): data = self.bus.read_i2c_block(self.address, 3) # read converted value value = (data[0] & 0x3F)<<10 | data[1] << 2 | data[2] >> 6 if (data[0] >> 6) == 0b11: value = "OVERFLOW" elif (data[0] >> 6) == 0b10: value elif (data[0] >> 6) == 0b01: value = value * -1 elif (data[0] >> 6) == 0b00: value = "UNDERFLOW" return value
class LTC2487(Device): ''' Driver for the LTC2487 Linear Technology I2C ADC device. ''' def __init__(self, parent = None, address = 0x14, configuration = [0b10111000,0b10011000], **kwargs): pass def initialize(self): pass def setADC(self, channel = 0 ): pass def readADC(self): pass
5
1
8
1
8
0
2
0.13
1
0
0
0
4
1
4
12
40
6
31
9
26
4
19
9
14
5
2
1
8
147,774
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/i2cpwm.py
pymlab.sensors.i2cpwm.I2CPWM
class I2CPWM(Device): 'Python library for I2CPWM01A MLAB module with NXP Semiconductors PCA9531 I2C-bus LED dimmer' MODES = { 'X': 0b00, 'LOW': 0b01, 'PWM0': 0b10, 'PWM1': 0b11, } def __init__(self, parent = None, address = 0b1100011, **kwargs): Device.__init__(self, parent, address, **kwargs) 'The INPUT register reflects the state of the device pins. Writes to this register will be acknowledged but will have no effect.' self.PWM_INPUT = 0x00 'PSC0 is used to program the period of the PWM output.' self.PWM_PSC0 = 0x01 'The PWM0 register determines the duty cycle of BLINK0. The outputs are LOW (LED on) when the count is less than the value in PWM0 and HIGH (LED off) when it is greater. If PWM0 is programmed with 00h, then the PWM0 output is always HIGH (LED off).' self.PWM_PWM0 = 0x02 'PSC1 is used to program the period of the PWM output.' self.PWM_PSC1 = 0x03 'The PWM1 register determines the duty cycle of BLINK1. The outputs are LOW (LED on) when the count is less than the value in PWM1 and HIGH (LED off) when it is greater. If PWM1 is programmed with 00h, then the PWM1 output is always HIGH (LED off).' self.PWM_PWM1 = 0x04 'The LSn LED select registers determine the source of the LED data.' self.PWM_LS0 = 0x05 self.PWM_LS1 = 0x06 def set_pwm0(self, frequency, duty): # frequency in Hz, Duty cycle in % (0-100) period = int((1.0/float(frequency))*152.0)-1 duty = int((float(duty)/100.0)*255.0) self.bus.write_byte_data(self.address, 0x01, period) self.bus.write_byte_data(self.address, self.PWM_PWM0, duty) def set_pwm1(self, frequency, duty): # frequency in Hz, Duty cycle in % (0-100) period = int((1.0/float(frequency))*152.0)-1 duty = int((float(duty)/100.0)*255.0) self.bus.write_byte_data(self.address, self.PWM_PSC1, period) self.bus.write_byte_data(self.address, self.PWM_PWM1, duty) def set_ls0(self, mode): self.bus.write_byte_data(self.address, self.PWM_LS0, mode) def set_ls1(self, mode): self.bus.write_byte_data(self.address, self.PWM_LS1, mode) def set_output_type(self, mode = ['X','X','X','X','X','X','X','X']): set_ls0((MODES[mode[0]] << 6) | (MODES[mode[1]] << 4) | (MODES[mode[2]] << 2) | MODES[mode[3]]) set_ls1((MODES[mode[4]] << 6) | (MODES[mode[5]] << 4) | (MODES[mode[6]] << 2) | MODES[mode[7]]) def get_input(self): return self.bus.read_byte_data(self.address, self.PWM_INPUT)
class I2CPWM(Device): '''Python library for I2CPWM01A MLAB module with NXP Semiconductors PCA9531 I2C-bus LED dimmer''' def __init__(self, parent = None, address = 0b1100011, **kwargs): pass def set_pwm0(self, frequency, duty): pass def set_pwm1(self, frequency, duty): pass def set_ls0(self, mode): pass def set_ls1(self, mode): pass def set_output_type(self, mode = ['X','X','X','X','X','X','X','X']): pass def get_input(self): pass
8
1
5
0
4
1
1
0.26
1
2
0
0
7
7
7
15
55
13
35
18
27
9
30
18
22
1
2
0
7
147,775
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/iic.py
pymlab.sensors.iic.SMBusDriver
class SMBusDriver(Driver): """ Key to symbols ============== S (1 bit) : Start bit P (1 bit) : Stop bit Rd/Wr (1 bit) : Read/Write bit. Rd equals 1, Wr equals 0. A, NA (1 bit) : Accept and reverse accept bit. Addr (7 bits): I2C 7 bit address. Note that this can be expanded as usual to get a 10 bit I2C address. Comm (8 bits): Command byte, a data byte which often selects a register on the device. Data (8 bits): A plain data byte. Sometimes, I write DataLow, DataHigh for 16 bit data. Count (8 bits): A data byte containing the length of a block operation. [..]: Data sent by I2C device, as opposed to data sent by the host adapter. More detail documentation is at https://www.kernel.org/doc/Documentation/i2c/smbus-protocol """ def __init__(self, port, smbus): self.port = port self.smbus = smbus self.driver_type = 'smbus' def write_byte(self, address, value): """ SMBus Send Byte: i2c_smbus_write_byte() ======================================== This operation is the reverse of Receive Byte: it sends a single byte to a device. See Receive Byte for more information. S Addr Wr [A] Data [A] P Functionality flag: I2C_FUNC_SMBUS_WRITE_BYTE """ return self.smbus.write_byte(address, value) def read_byte(self, address): """ SMBus Send Byte: i2c_smbus_write_byte() ======================================== This operation is the reverse of Receive Byte: it sends a single byte to a device. See Receive Byte for more information. S Addr Wr [A] Data [A] P Functionality flag: I2C_FUNC_SMBUS_WRITE_BYTE """ return self.smbus.read_byte(address) def write_byte_data(self, address, register, value): """ SMBus Read Byte: i2c_smbus_read_byte_data() ============================================ This reads a single byte from a device, from a designated register. The register is specified through the Comm byte. S Addr Wr [A] Comm [A] S Addr Rd [A] [Data] NA P Functionality flag: I2C_FUNC_SMBUS_READ_BYTE_DATA """ return self.smbus.write_byte_data(address, register, value) def read_byte_data(self, address, register): """ SMBus Read Byte: i2c_smbus_read_byte_data() ============================================ This reads a single byte from a device, from a designated register. The register is specified through the Comm byte. S Addr Wr [A] Comm [A] S Addr Rd [A] [Data] NA P Functionality flag: I2C_FUNC_SMBUS_READ_BYTE_DATA """ return self.smbus.read_byte_data(address, register) def write_word_data(self, address, register, value): """ SMBus Write Word: i2c_smbus_write_word_data() ============================================== This is the opposite of the Read Word operation. 16 bits of data is written to a device, to the designated register that is specified through the Comm byte. S Addr Wr [A] Comm [A] DataLow [A] DataHigh [A] P Functionality flag: I2C_FUNC_SMBUS_WRITE_WORD_DATA Note the convenience function i2c_smbus_write_word_swapped is available for writes where the two data bytes are the other way around (not SMBus compliant, but very popular.) """ return self.smbus.write_word_data(address, register, value) def read_word_data(self, address, register): """ SMBus Read Word: i2c_smbus_read_word_data() ============================================ This operation is very like Read Byte; again, data is read from a device, from a designated register that is specified through the Comm byte. But this time, the data is a complete word (16 bits). S Addr Wr [A] Comm [A] S Addr Rd [A] [DataLow] A [DataHigh] NA P Functionality flag: I2C_FUNC_SMBUS_READ_WORD_DATA Note the convenience function i2c_smbus_read_word_swapped is available for reads where the two data bytes are the other way around (not SMBus compliant, but very popular.) """ return self.smbus.read_word_data(address, register) def write_block_data(self, address, register, value): """ SMBus Block Write: i2c_smbus_write_block_data() ================================================ The opposite of the Block Read command, this writes up to 32 bytes to a device, to a designated register that is specified through the Comm byte. The amount of data is specified in the Count byte. S Addr Wr [A] Comm [A] Count [A] Data [A] Data [A] ... [A] Data [A] P Functionality flag: I2C_FUNC_SMBUS_WRITE_BLOCK_DATA """ return self.smbus.write_block_data(address, register, value) def read_block_data(self, address, register): """ SMBus Block Read: i2c_smbus_read_block_data() ============================================== This command reads a block of up to 32 bytes from a device, from a designated register that is specified through the Comm byte. The amount of data is specified by the device in the Count byte. S Addr Wr [A] Comm [A] S Addr Rd [A] [Count] A [Data] A [Data] A ... A [Data] NA P Functionality flag: I2C_FUNC_SMBUS_READ_BLOCK_DATA """ return self.smbus.read_block_data(address, register) def block_process_call(self, address, register, value): """ SMBus Block Write - Block Read Process Call =========================================== SMBus Block Write - Block Read Process Call was introduced in Revision 2.0 of the specification. This command selects a device register (through the Comm byte), sends 1 to 31 bytes of data to it, and reads 1 to 31 bytes of data in return. S Addr Wr [A] Comm [A] Count [A] Data [A] ... S Addr Rd [A] [Count] A [Data] ... A P Functionality flag: I2C_FUNC_SMBUS_BLOCK_PROC_CALL """ return self.smbus.block_process_call(address, register, value) ### I2C transactions not compatible with pure SMBus driver def write_i2c_block(self, address, value): """ Simple send transaction ====================== This corresponds to i2c_master_send. S Addr Wr [A] Data [A] Data [A] ... [A] Data [A] P More detail documentation is at: https://www.kernel.org/doc/Documentation/i2c/i2c-protocol """ return self.smbus.write_i2c_block(address, value) def read_i2c_block(self, address, length): """ Simple receive transaction =========================== This corresponds to i2c_master_recv S Addr Rd [A] [Data] A [Data] A ... A [Data] NA P More detail documentation is at: https://www.kernel.org/doc/Documentation/i2c/i2c-protocol """ return self.smbus.read_i2c_block(address, length) def write_i2c_block_data(self, address, register, value): """ I2C block transactions do not limit the number of bytes transferred but the SMBus layer places a limit of 32 bytes. I2C Block Write: i2c_smbus_write_i2c_block_data() ================================================== The opposite of the Block Read command, this writes bytes to a device, to a designated register that is specified through the Comm byte. Note that command lengths of 0, 2, or more bytes are seupported as they are indistinguishable from data. S Addr Wr [A] Comm [A] Data [A] Data [A] ... [A] Data [A] P Functionality flag: I2C_FUNC_SMBUS_WRITE_I2C_BLOCK """ return self.smbus.write_i2c_block_data(address, register, value) def read_i2c_block_data(self, address, register, length): """ I2C block transactions do not limit the number of bytes transferred but the SMBus layer places a limit of 32 bytes. I2C Block Read: i2c_smbus_read_i2c_block_data() ================================================ This command reads a block of bytes from a device, from a designated register that is specified through the Comm byte. S Addr Wr [A] Comm [A] S Addr Rd [A] [Data] A [Data] A ... A [Data] NA P Functionality flag: I2C_FUNC_SMBUS_READ_I2C_BLOCK """ return self.smbus.read_i2c_block_data(address, register, length) def scan_bus(self, verbose = False): devices = [] for addr in range(128): out = self.smbus.read_byte(addr) if out > 0: devices += [addr] if verbose: if addr % 0x0f == 0: print("", end = '') print(hex(addr)+":", end = '') if out > 0: print(hex(addr)) else: print(" -- ", end = '') print("") return devices
class SMBusDriver(Driver): ''' Key to symbols ============== S (1 bit) : Start bit P (1 bit) : Stop bit Rd/Wr (1 bit) : Read/Write bit. Rd equals 1, Wr equals 0. A, NA (1 bit) : Accept and reverse accept bit. Addr (7 bits): I2C 7 bit address. Note that this can be expanded as usual to get a 10 bit I2C address. Comm (8 bits): Command byte, a data byte which often selects a register on the device. Data (8 bits): A plain data byte. Sometimes, I write DataLow, DataHigh for 16 bit data. Count (8 bits): A data byte containing the length of a block operation. [..]: Data sent by I2C device, as opposed to data sent by the host adapter. More detail documentation is at https://www.kernel.org/doc/Documentation/i2c/smbus-protocol ''' def __init__(self, port, smbus): pass def write_byte(self, address, value): ''' SMBus Send Byte: i2c_smbus_write_byte() ======================================== This operation is the reverse of Receive Byte: it sends a single byte to a device. See Receive Byte for more information. S Addr Wr [A] Data [A] P Functionality flag: I2C_FUNC_SMBUS_WRITE_BYTE ''' pass def read_byte(self, address): ''' SMBus Send Byte: i2c_smbus_write_byte() ======================================== This operation is the reverse of Receive Byte: it sends a single byte to a device. See Receive Byte for more information. S Addr Wr [A] Data [A] P Functionality flag: I2C_FUNC_SMBUS_WRITE_BYTE ''' pass def write_byte_data(self, address, register, value): ''' SMBus Read Byte: i2c_smbus_read_byte_data() ============================================ This reads a single byte from a device, from a designated register. The register is specified through the Comm byte. S Addr Wr [A] Comm [A] S Addr Rd [A] [Data] NA P Functionality flag: I2C_FUNC_SMBUS_READ_BYTE_DATA ''' pass def read_byte_data(self, address, register): ''' SMBus Read Byte: i2c_smbus_read_byte_data() ============================================ This reads a single byte from a device, from a designated register. The register is specified through the Comm byte. S Addr Wr [A] Comm [A] S Addr Rd [A] [Data] NA P Functionality flag: I2C_FUNC_SMBUS_READ_BYTE_DATA ''' pass def write_word_data(self, address, register, value): ''' SMBus Write Word: i2c_smbus_write_word_data() ============================================== This is the opposite of the Read Word operation. 16 bits of data is written to a device, to the designated register that is specified through the Comm byte. S Addr Wr [A] Comm [A] DataLow [A] DataHigh [A] P Functionality flag: I2C_FUNC_SMBUS_WRITE_WORD_DATA Note the convenience function i2c_smbus_write_word_swapped is available for writes where the two data bytes are the other way around (not SMBus compliant, but very popular.) ''' pass def read_word_data(self, address, register): ''' SMBus Read Word: i2c_smbus_read_word_data() ============================================ This operation is very like Read Byte; again, data is read from a device, from a designated register that is specified through the Comm byte. But this time, the data is a complete word (16 bits). S Addr Wr [A] Comm [A] S Addr Rd [A] [DataLow] A [DataHigh] NA P Functionality flag: I2C_FUNC_SMBUS_READ_WORD_DATA Note the convenience function i2c_smbus_read_word_swapped is available for reads where the two data bytes are the other way around (not SMBus compliant, but very popular.) ''' pass def write_block_data(self, address, register, value): ''' SMBus Block Write: i2c_smbus_write_block_data() ================================================ The opposite of the Block Read command, this writes up to 32 bytes to a device, to a designated register that is specified through the Comm byte. The amount of data is specified in the Count byte. S Addr Wr [A] Comm [A] Count [A] Data [A] Data [A] ... [A] Data [A] P Functionality flag: I2C_FUNC_SMBUS_WRITE_BLOCK_DATA ''' pass def read_block_data(self, address, register): ''' SMBus Block Read: i2c_smbus_read_block_data() ============================================== This command reads a block of up to 32 bytes from a device, from a designated register that is specified through the Comm byte. The amount of data is specified by the device in the Count byte. S Addr Wr [A] Comm [A] S Addr Rd [A] [Count] A [Data] A [Data] A ... A [Data] NA P Functionality flag: I2C_FUNC_SMBUS_READ_BLOCK_DATA ''' pass def block_process_call(self, address, register, value): ''' SMBus Block Write - Block Read Process Call =========================================== SMBus Block Write - Block Read Process Call was introduced in Revision 2.0 of the specification. This command selects a device register (through the Comm byte), sends 1 to 31 bytes of data to it, and reads 1 to 31 bytes of data in return. S Addr Wr [A] Comm [A] Count [A] Data [A] ... S Addr Rd [A] [Count] A [Data] ... A P Functionality flag: I2C_FUNC_SMBUS_BLOCK_PROC_CALL ''' pass def write_i2c_block(self, address, value): ''' Simple send transaction ====================== This corresponds to i2c_master_send. S Addr Wr [A] Data [A] Data [A] ... [A] Data [A] P More detail documentation is at: https://www.kernel.org/doc/Documentation/i2c/i2c-protocol ''' pass def read_i2c_block(self, address, length): ''' Simple receive transaction =========================== This corresponds to i2c_master_recv S Addr Rd [A] [Data] A [Data] A ... A [Data] NA P More detail documentation is at: https://www.kernel.org/doc/Documentation/i2c/i2c-protocol ''' pass def write_i2c_block_data(self, address, register, value): ''' I2C block transactions do not limit the number of bytes transferred but the SMBus layer places a limit of 32 bytes. I2C Block Write: i2c_smbus_write_i2c_block_data() ================================================== The opposite of the Block Read command, this writes bytes to a device, to a designated register that is specified through the Comm byte. Note that command lengths of 0, 2, or more bytes are seupported as they are indistinguishable from data. S Addr Wr [A] Comm [A] Data [A] Data [A] ... [A] Data [A] P Functionality flag: I2C_FUNC_SMBUS_WRITE_I2C_BLOCK ''' pass def read_i2c_block_data(self, address, register, length): ''' I2C block transactions do not limit the number of bytes transferred but the SMBus layer places a limit of 32 bytes. I2C Block Read: i2c_smbus_read_i2c_block_data() ================================================ This command reads a block of bytes from a device, from a designated register that is specified through the Comm byte. S Addr Wr [A] Comm [A] S Addr Rd [A] [Data] A [Data] A ... A [Data] NA P Functionality flag: I2C_FUNC_SMBUS_READ_I2C_BLOCK ''' pass def scan_bus(self, verbose = False): pass
16
14
14
3
3
8
1
3
1
1
0
0
15
3
15
25
253
65
47
22
31
141
46
22
30
6
2
3
20
147,776
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/lightning.py
pymlab.sensors.lightning.AS3935
class AS3935(Device): 'Python library for LIGHTNING01A MLAB module with austria microsystems AS3935 I2C/SPI lighting detecor.' def __init__(self, parent = None, address = 0x02, TUN_CAP = 0, **kwargs): Device.__init__(self, parent, address, **kwargs) addresses = [0x02, 0x01, 0x03] if address not in addresses: raise ValueError("Unsupported sensor address") self._TUN_CAP = TUN_CAP def soft_reset(self): self.bus.write_byte_data(self.address, 0x3c, 0x96); return def reset(self): self.soft_reset() self.setTUN_CAP(self._TUN_CAP) def calib_rco(self): """calibrate RCO""" byte = self.bus.read_byte_data(self.address, 0x08) self.bus.write_byte_data(self.address, 0x3d, 0x96); print(bin(self.bus.read_byte_data(self.address, 0x3A))) print(bin(self.bus.read_byte_data(self.address, 0x3B))) return def antennatune_on(self, FDIV = 0,TUN_CAP=0): """Display antenna resonance at IRQ pin""" # set frequency division data = self.bus.read_byte_data(self.address, 0x03) data = (data & (~(3<<6))) | (FDIV<<6) self.bus.write_byte_data(self.address, 0x03, data) #print hex(self.bus.read_byte_data(self.address, 0x03)) self.setTUN_CAP(TUN_CAP) # Display LCO on IRQ pin reg = self.bus.read_byte_data(self.address, 0x08) reg = (reg & 0x8f) | 0x80; self.bus.write_byte_data(self.address, 0x08, reg) return def initialize(self): self.soft_reset() self.setTUN_CAP(self._TUN_CAP) def getDistance(self): data = self.bus.read_byte_data(self.address, 0x07) & 0b00111111 print(hex(data)) distance = {0b111111: 255, 0b101000: 40, 0b100101: 37, 0b100010: 34, 0b011111: 31, 0b011011: 27, 0b011000: 24, 0b010100: 20, 0b010001: 17, 0b001110: 14, 0b001100: 12, 0b001010: 10, 0b001000: 8, 0b000110: 6, 0b000101: 5, 0b000001: 0} return distance.get(data,data) # returns distance or distance data adirectly in case there is no distance code. def getIndoor(self): indoor = self.bus.read_byte_data(self.address, 0x00) & 0b00111110 values = { 0b100100: True, 0b011100: False} try: return values[indoor] except LookupError: print("Uknown register value {0:b}".format(indoor)) def setIndoor(self, state): byte = self.bus.read_byte_data(self.address, 0x00) if state: byte |= 0b100100 byte &=~0b011010 else: byte |= 0b011100 byte &=~0b100010 #print("{:08b}".format(byte)) self.bus.write_byte_data(self.address, 0x00, byte) return byte def getNoiseFloor(self): value = (self.bus.read_byte_data(self.address, 0x01) & 0b01110000) >> 4 indoor = self.getIndoor() matrix = [ [390, 28], [630, 45], [860, 62], [1100,78], [1140,95], [1570,112], [1800,130], [2000,146]] return matrix[value][int(indoor)] def setNoiseFloor(self, value): data = self.bus.read_byte_data(self.address, 0x01) data = (data & (~(7<<4))) | (value<<4) self.bus.write_byte_data(self.address, 0x01, data) def setTUN_CAP(self, value): # Display LCO on IRQ pin reg = self.bus.read_byte_data(self.address, 0x08) reg = (reg & 0x0f) | value; self.bus.write_byte_data(self.address, 0x08, reg) def getTUN_CAP(self): data = self.bus.read_byte_data(self.address, 0x08) data = data & 0x0f return data def setWDTH(self, value): data = self.bus.read_byte_data(self.address, 0x01) data = (data & (~(0x0f))) | (value) self.bus.write_byte_data(self.address, 0x01, data) def getWDTH(self): data = self.bus.read_byte_data(self.address, 0x01) return (data & 0x0f) def setNoiseFloorAdv(self, value): pass def getSpikeRejection(self): data = self.bus.read_byte_data(self.address, 0x02) & 0b1111 return data def setSpikeRejection(self, value): data = self.bus.read_byte_data(self.address, 0x02) & 0b1111 data = (data & (~(0b1111))) | (value) self.bus.write_byte_data(self.address, 0x02, data) def getPowerStatus(self): return not bool(self.bus.read_byte_data(self.address, 0x00) & 0b1) #returns true in Active state def getInterrupts(self): reg = self.bus.read_byte_data(self.address, 0x03) out = {} out['INT_NH'] = bool(reg & 0b00000001) out['INT_D'] = bool(reg & 0b00000100) out['INT_L'] = bool(reg & 0b00001000) return out def getSingleEnergy(self): lsb = self.bus.read_byte_data(self.address, 0x04) msb = self.bus.read_byte_data(self.address, 0x05) mmsb= self.bus.read_byte_data(self.address, 0x06) & 0b11111 return lsb | msb << 8 | mmsb << 16 def getMaskDist(self): return bool(self.bus.read_byte_data(self.address, 0x03) & 0b00100000) def setMaskDist(self, value): value = bool(value) data = self.bus.read_byte_data(self.address, 0x03) if value: self.bus.write_byte_data(self.address, 0x03, data | 0b00100000) else: self.bus.write_byte_data(self.address, 0x03, data & (~0b00100000))
class AS3935(Device): '''Python library for LIGHTNING01A MLAB module with austria microsystems AS3935 I2C/SPI lighting detecor.''' def __init__(self, parent = None, address = 0x02, TUN_CAP = 0, **kwargs): pass def soft_reset(self): pass def reset(self): pass def calib_rco(self): '''calibrate RCO''' pass def antennatune_on(self, FDIV = 0,TUN_CAP=0): '''Display antenna resonance at IRQ pin''' pass def initialize(self): pass def getDistance(self): pass def getIndoor(self): pass def setIndoor(self, state): pass def getNoiseFloor(self): pass def setNoiseFloor(self, value): pass def setTUN_CAP(self, value): pass def getTUN_CAP(self): pass def setWDTH(self, value): pass def getWDTH(self): pass def setNoiseFloorAdv(self, value): pass def getSpikeRejection(self): pass def setSpikeRejection(self, value): pass def getPowerStatus(self): pass def getInterrupts(self): pass def getSingleEnergy(self): pass def getMaskDist(self): pass def setMaskDist(self, value): pass
24
3
6
0
6
0
1
0.07
1
4
0
0
23
1
23
31
172
30
134
50
110
10
107
50
83
2
2
1
27
147,777
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/light.py
pymlab.sensors.light.RGBC01
class RGBC01(Device): """ Python library for RGBC01A MLAB module with TCS3771 I2C Light Sensor """ def __init__(self, parent = None, address = 0x29, **kwargs): Device.__init__(self, parent, address, **kwargs) self.TCS3771_ENABLE =0x00 self.TCS3771_ATIME =0x01 self.TCS3771_PTIME =0x02 self.TCS3771_WTIME =0x03 self.TCS3771_PDATA =0x1C self.TCS3771_PDATAH =0x1D def initialize(self): self.bus.write_byte_data(self.address, self.TCS3771_ENABLE, 0x0f) def get_prox(self): pass
class RGBC01(Device): ''' Python library for RGBC01A MLAB module with TCS3771 I2C Light Sensor ''' def __init__(self, parent = None, address = 0x29, **kwargs): pass def initialize(self): pass def get_prox(self): pass
4
1
4
0
4
0
1
0.23
1
0
0
0
3
6
3
11
20
4
13
10
9
3
13
10
9
1
2
0
3
147,778
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/light.py
pymlab.sensors.light.ISL01
class ISL01(Device): """ Python library for ISL2902001A MLAB module with ISL29020 I2C Light Sensor """ RANGE = { 1000: [0b00, 1/1000], 4000: [0b01, 1/4000], 16000: [0b10, 1/16000], 64000: [0b11, 1/64000], } def __init__(self, parent = None, address = 0x44, fault_queue = 1, **kwargs): Device.__init__(self, parent, address, **kwargs) ## register definitions self.command = 0x00 self.Data_lsb = 0x01 self.Data_msb = 0x02 ## config parameters self.SHUTDOWN = (1 << 7) self.continuous_measurement = (1 << 6) self.IR_sense = (1 << 5) self.VIS_sense = (0 << 5) self.clock_INT_16bit = (0b000 << 4) self.clock_INT_12bit = (0b001 << 4) self.clock_INT_8bit = (0b010 << 4) self.clock_INT_4bit = (0b011 << 4) self.clock_EXT_ADC = (0b100 << 4) self.clock_EXT_Timer = (0b101 << 4) self.range_1kLUX = 0b00 self.range_4kLUX = 0b01 self.range_16kLUX = 0b10 self.range_64kLUX = 0b11 def ADC_sync(self): """ Ends the current ADC-integration and starts another. Used only with External Timing Mode. """ self.bus.write_byte_data(self.address, 0xff, 0x01) LOGGER.debug("syncing ILS ADC",) return def config(self, config): self.bus.write_byte_data(self.address, self.command, config) return def get_lux(self): LSB = self.bus.read_byte_data(self.address, self.Data_lsb) MSB = self.bus.read_byte_data(self.address, self.Data_msb) DATA = (MSB << 8) + LSB Ecal = 1 * DATA return Ecal
class ISL01(Device): ''' Python library for ISL2902001A MLAB module with ISL29020 I2C Light Sensor ''' def __init__(self, parent = None, address = 0x44, fault_queue = 1, **kwargs): pass def ADC_sync(self): ''' Ends the current ADC-integration and starts another. Used only with External Timing Mode. ''' pass def config(self, config): pass def get_lux(self): pass
5
2
10
1
8
1
1
0.21
1
0
0
0
4
17
4
12
56
9
39
27
34
8
34
27
29
1
2
0
4
147,779
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/imu.py
pymlab.sensors.imu.WINDGAUGE03A
class WINDGAUGE03A(Device): def __init__(self, parent = None, address = 0x68, **kwargs): Device.__init__(self, parent, address, **kwargs) self.SDP33_i2c_address = 0x21 self.mag_i2c_address = 0x0C ## USER BANK 0 REGISTERS self.ICM20948_WHO_AM_I = 0x00 self.ICM20948_USER_CTRL = 0x03 self.ICM20948_LP_CONFIG = 0x05 self.ICM20948_PWR_MGMT_1 = 0x06 self.ICM20948_PWR_MGMT_2 = 0x07 self.ICM20948_INT_PIN_CFG = 0x0F self.ICM20948_INT_ENABLE = 0x10 self.ICM20948_I2C_MST_STATUS = 0x17 self.ICM20948_ACEL_XOUT_H = 0x2D self.ICM20948_ACEL_XOUT_L = 0x2E self.ICM20948_ACEL_YOUT_H = 0x2F self.ICM20948_ACEL_YOUT_L = 0x30 self.ICM20948_ACEL_ZOUT_H = 0x31 self.ICM20948_ACEL_XOUT_L = 0x32 self.ICM20948_GYRO_XOUT_H = 0x33 self.ICM20948_GYRO_XOUT_L = 0x34 self.ICM20948_GYRO_YOUT_H = 0x35 self.ICM20948_GYRO_YOUT_L = 0x36 self.ICM20948_GYRO_ZOUT_H = 0x37 self.ICM20948_GYRO_XOUT_L = 0x38 self.ICM20948_TEMP_OUT_H = 0x39 self.ICM20948_TEMP_OUT_L = 0x3A self.ICM20948_EXT_SLV_SENS_DATA_00 = 0x3B # USER BANK 2 REGISTERS self.ICM20948_GYRO_CONFIG = 0x01 self.ICM20948_ACEL_CONFIG = 0x14 ## USER BANK 3 REGISTERS self.ICM20948_I2C_SLV0_ADDR = 0x03 self.ICM20948_I2C_SLV0_REG = 0x04 # I2C slave 0 register address from where to begin data transfer. self.ICM20948_I2C_SLV0_CTRL = 0x05 self.ICM20948_I2C_SLV0_DO = 0x06 self.ICM20948_I2C_SLV1_ADDR = 0x07 self.ICM20948_I2C_SLV1_REG = 0x08 # I2C slave 1 register address from where to begin data transfer. self.ICM20948_I2C_SLV1_CTRL = 0x09 self.ICM20948_I2C_SLV1_DO = 0x0A ## USER BANK REGISTERS 0-3 self.ICM20948_REG_BANK_SEL = 0x7F # 0 def usr_bank_sel(self, usr_bank_reg): self.bus.write_byte_data(self.address, self.ICM20948_REG_BANK_SEL, usr_bank_reg << 4) def write_icm20948_reg_data(self, reg_address, reg_usr_bank, value): self.usr_bank_sel(reg_usr_bank) self.bus.write_byte_data(self.address, reg_address, value) def read_icm20948_reg_data(self, reg_address, reg_usr_bank, num_of_bytes): self.usr_bank_sel(reg_usr_bank) if num_of_bytes > 1: return(self.bus.read_i2c_block_data(self.address, reg_address, num_of_bytes)) else: return((self.bus.read_byte_data(self.address, reg_address))) def reset (self): self.write_icm20948_reg_data(self.ICM20948_PWR_MGMT_1, 0, 0x80) # reset device and register values time.sleep(1) def initialize (self): # self.bus.write_byte_data(self.address, self.ICM20948_PWR_MGMT_2, 0x3f) # gyro and accel off # self.write_icm20948_reg_data(self.ICM20948_PWR_MGMT_2, 0, 0x00) # gyro and accel on self.write_icm20948_reg_data(self.ICM20948_USER_CTRL, 0, 0x00) # I2C_MST_EN set to 0 self.write_icm20948_reg_data(self.ICM20948_INT_PIN_CFG, 0, 0x02) # BYPASS ENABLE # self.write_icm20948_reg_data(self.ICM20948_USER_CTRL, 0, 0x02) # I2C_MST_RST set to 1 (bit auto clears) self.write_icm20948_reg_data(self.ICM20948_PWR_MGMT_1, 0, 0x01) # clear sleep bit and wake up device time.sleep(0.1) def i2c_master_init (self): # self.write_icm20948_reg_data(self.ICM20948_INT_ENABLE, 0, 0xFF) # enable i2c master interrupt to propagate to interrupt pin1 # self.write_icm20948_reg_data(self.ICM20948_USER_CTRL, 0, 0x02) # I2C_MST_RST # time.sleep(0.1) # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_CTRL, 3, 0x20) # When bit 5 set (0x20), the transaction does not write a register value, it will only read data, or write data # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_ADDR, 3, self.SDP33_i2c_address) # self.write_icm20948_reg_data(self.ICM20948_LP_CONFIG, 0, 0x00) #disable master's duty cycled mode self.write_icm20948_reg_data(self.ICM20948_USER_CTRL, 0, 0x20) # I2C_MST_EN set to 1 def i2c_master_write (self, slv_id, slv_addr, data_out, slv_reg ): # self.write_icm20948_reg_data(self.ICM20948_USER_CTRL, 0, 0x20) # USER_CTRL[5] (I2C_MST_EN) = 1 self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_ADDR + (slv_id * 4), 3, slv_addr | (1 << 7)) # I2C_SLVX_ADDR[6:0] = (slv_addr | I2C_SLV0_RNW) - slave addres | R/W bit MSB (1) self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_DO + (slv_id * 4), 3, data_out) # I2C_SLVX_DO[7:0](0-15) = data_out if slv_reg is not None: self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_REG + (slv_id * 4), 3, slv_reg) # I2C_SLVX_REG[7:0] = slv_reg self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_CTRL + (slv_id * 4), 3, 0xA0) # I2C_SLVX_CTRL[7] (I2C_SLVX_EN) = 1, I2C_SLVX_CTRL[5] (I2C_SLVX_REG_EN) = 1 else: self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_CTRL + (slv_id * 4), 3, 0x80) # I2C_SLVX_CTRL[7] (I2C(0-15)_SLVX_EN) = 1, I2C_SLVX_CTRL[5] (I2C_SLVX_REG_EN) = 0 self.write_icm20948_reg_data(self.ICM20948_USER_CTRL, 0, 0x00) # USER_CTRL[5] (I2C_MST_EN) = 0 time.sleep(0.1) def i2c_master_read (self, slv_id, slv_addr, slv_rd_len, slv_reg ): # self.write_icm20948_reg_data(self.ICM20948_USER_CTRL, 0, 0x20) # USER_CTRL[5] (I2C_MST_EN) = 1 self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_ADDR + (slv_id * 4), 3, slv_addr | (1 << 7)) # I2C_SLVX_ADDR[6:0] = (slv_addr | I2C_SLV0_RNW) - slave addres | R/W bit MSB (0) if slv_reg is not None: self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_REG + (slv_id * 4), 3, slv_reg) # I2C_SLVX_REG[7:0] = slv_reg self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_CTRL + (slv_id * 4), 3, 0xA0 | slv_rd_len) # I2C_SLVX_CTRL[7] (I2C_SLVX_EN) = 1, I2C_SLVX_CTRL[5] (I2C_SLVX_REG_EN) = 1, I2C_SLVX_LENG[3:0] = slv_rd_len (number of bytes to be read from slave (0-15)) else: self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_CTRL + (slv_id * 4), 3, 0x80 | slv_rd_len) # I2C_SLVX_CTRL[7] (I2C_SLVX_EN) = 1, I2C_SLVX_CTRL[5] (I2C_SLVX_REG_EN) = 0, I2C_SLVX_LENG[3:0] = slv_rd_len (number of bytes to be read from slave (0-15)) time.sleep(0.1) def i2c_master_sdp33_init(self): self.write_icm20948_reg_data(self.ICM20948_USER_CTRL, 0, 0x20) # I2C_MST_EN set to 1 # time.sleep(0.01) # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV1_DO, 3, 0x04) # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV1_REG, 3, 0x31) # adress of the slave register master will write to # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV1_ADDR, 3, 0x0C) # R/W bit MSB - write operation # time.sleep(gi) # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV1_CTRL, 3, 0xA9) # I2C_SLV1_EN, I2C_SLV1_REG_DIS, I2C_SLV1_LENG[3:0] # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV1_CTRL, 3, 0x00) # I2C_SLV0_DIS self.write_icm20948_reg_data(self.ICM20948_I2C_SLV1_ADDR, 3, 0xA1) # SPD3X i2c address =0x21 | R/W bit MSB - read (1) self.write_icm20948_reg_data(self.ICM20948_I2C_SLV1_CTRL, 3, 0xA9) # I2C_SLV1_EN, I2C_SLV1_REG_EN, I2C_SLV1_LENG[3:0] time.sleep(0.1) # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV1_REG, 3, 0x00) # adress of the first slave register master will start reading from # print("reading", end = ' ') # print(self.read_icm20948_reg_data(self.ICM20948_I2C_SLV0_ADDR, 3, 1)) # time.sleep(gi) # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV1_CTRL, 3, 0x8f) def i2c_master_mag_init (self): # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_DO, 3, 0x01) # self.write_icm20948_reg_data(self.ICM20948_USER_CTRL, 0, 0x00) # I2C_MST_EN set to 0, I2C_MST_RST set to 1 # time.sleep(gi) self.write_icm20948_reg_data(self.ICM20948_USER_CTRL, 0, 0x20) # I2C_MST_EN set to 0, I2C_MST_RST set to 1 # time.sleep(gi) # self.write_icm20948_reg_data(self.ICM20948_USER_CTRL, 0, 0x02) # I2C_MST_EN set to 0, I2C_MST_RST set to 1 # time.sleep(0.1) ## MAGNETOMETER SOFT RESET # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_DO, 3, 0x01) # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_REG, 3, 0x32) # adress of the slave register master will write to # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_ADDR, 3, 0x0C) # R/W bit MSB - write operation # # time.sleep(gi) # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_CTRL, 3, 0x8a) # I2C_SLV0_EN, I2C_SLV0_REG_EN, I2C_SLV0_LENG[3:0] = 9 # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_CTRL, 3, 0x00) # I2C_SLV0_DIS # time.sleep(gi) self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_DO, 3, 0x04) self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_REG, 3, 0x31) # adress of the slave register master will write to self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_ADDR, 3, 0x0C) # R/W bit MSB - write operation # time.sleep(gi) self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_CTRL, 3, 0x8a) # I2C_SLV0_EN, I2C_SLV0_REG_EN, I2C_SLV0_LENG[3:0] = 9 self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_CTRL, 3, 0x00) # I2C_SLV0_DIS self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_ADDR, 3, 0x8C) # R/W bit MSB self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_REG, 3, 0x00) # adress of the first slave register master will start reading from # print("reading", end = ' ') # print(self.read_icm20948_reg_data(self.ICM20948_I2C_SLV0_ADDR, 3, 1)) # time.sleep(gi) self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_CTRL, 3, 0x8d) # I2C_SLV0_EN, I2C_SLV0_REG_EN, I2C_SLV0_LENG[3:0] = 9 # print(self.read_icm20948_reg_data(self.ICM20948_I2C_SLV0_ADDR, 3, 1)) # self.write_icm20948_reg_data(self.ICM20948_USER_CTRL, 0, 0x20) # I2C_MST_EN set to 1 time.sleep(0.1) # time.sleep(gi) def get_temp(self): room_temp_offset = 21.0 tem_sens = 333.87 temp_raw_data = self.read_icm20948_reg_data(self.ICM20948_TEMP_OUT_H, 0, 2) temp_raw = ((temp_raw_data[0] << 8) + temp_raw_data[1]) return(((temp_raw - room_temp_offset)/temp_sens) + room_temp_offset) def get_accel(self): accel_sens = float((1 << (3 - (self.read_icm20948_reg_data(self.ICM20948_ACEL_CONFIG, 2, 1) & 0x6))) * 2048) accel_raw = self.read_icm20948_reg_data(self.ICM20948_ACEL_XOUT_H, 0, 6) accel_x_raw = ((accel_raw[0] << 8) + accel_raw_[1]) accel_y_raw = ((accel_raw[2] << 8) + accel_raw_[3]) accel_z_raw = ((accel_raw[4] << 8) + accel_raw_[5]) if accel_x_raw > 0x7fff: accel_x_raw -= 65536 if accel_y_raw > 0x7fff: accel_y_raw -= 65536 if accel_z_raw > 0x7fff: accel_z_raw -= 65536 return((accel_x_raw / accel_sens), (accel_y_raw / accel_sens), (accel_z_raw / accel_sens) ) def get_gyro(self): gyro_sens = float((1 << (3 - (self.read_icm20948_reg_data(self.ICM20948_GYRO_CONFIG, 2, 1) & 0x6))) * 16.4) gyro_raw = self.read_icm20948_reg_data(self.ICM20948_GYRO_XOUT_H, 0, 6) gyro_x_raw = ((gyro_raw[0] << 8) + gyro_raw_[1]) gyro_y_raw = ((gyro_raw[2] << 8) + gyro_raw_[3]) gyro_z_raw = ((gyro_raw[4] << 8) + gyro_raw_[5]) if gyro_x_raw > 0x7fff: gyro_x_raw -= 65536 if gyro_y_raw > 0x7fff: gyro_y_raw -= 65536 if gyro_z_raw > 0x7fff: gyro_z_raw -= 65536 return((gyro_x_raw / gyro_sens), (gyro_y_raw / gyro_sens), (gyro_z_raw / gyro_sens)) def SDP33_write (self, SDP33_i2c_address, command): self.bus.write_i2c_block_data(self.SDP33_i2c_address, command) def SDP33_read (self, SDP33_i2c_address, command): # write = i2c_msg.write(SDP33_i2c_address, command) # read = i2c_msg.read(SDP33_i2c_address, 9) # raw_data = bus2.i2c_rdwr(write, read) self.bus2.write_i2c_block_data(self, self.SDP33_i2c_address, 0, [0x36, 0x24]) raw_data = self.bus2.read_i2c_block_data(self, self.SDP33_i2c_address, 9) return(raw_data) def get_mag(self, cal_available): if (cal_available): cal_file = open("ICM20948_mag_cal.txt", "r") cal_consts = cal_file.readline().split(",") offset_x = float(cal_consts[0]) offset_y = float(cal_consts[1]) offset_z = float(cal_consts[2]) scale_x = float(cal_consts[3]) scale_y = float(cal_consts[4]) scale_z = float(cal_consts[5]) # print(str(offset_x)+"\n") # print(str(offset_y)+"\n") # print(str(offset_z)+"\n") # print(str(scale_x)+"\n") # print(str(scale_y)+"\n") # print(str(scale_z)+"\n") else: offset_x, offset_y, offset_z = 0, 0, 0 scale_x, scale_y, scale_z = 1, 1, 1 mag_raw_data = self.read_icm20948_reg_data(self.ICM20948_EXT_SLV_SENS_DATA_00, 0, 13) magX = (mag_raw_data[6] << 8) + mag_raw_data[5] magY = (mag_raw_data[8] << 8) + mag_raw_data[7] magZ = (mag_raw_data[10] << 8) + mag_raw_data[9] if magX > 0x7fff: magX -= 65536 if magY > 0x7fff: magY -= 65536 if magZ > 0x7fff: magZ -= 65536 mag_scf = 4912/32752.0 # print(magX) # print(((magX*mag_scf) - offset_x) * scale_x) return(((magX*mag_scf) - offset_x) * scale_x, ((magY*mag_scf) - offset_y) * scale_y, ((magZ*mag_scf) - offset_z)*scale_z) def calib_mag(self, calib_time): try: decision = False print("\nDo you wish to perform new magnetometer calibration? Old calibration data will be lost!") while not decision: start_cal = raw_input("[Y/N]\n") if (start_cal == 'N') or (start_cal == 'n'): print("\nCalibration canceled, no new calibration values saved.\n\n") sys.exit(1) elif (start_cal == 'Y') or (start_cal == 'y'): decision = True self.i2c_master_mag_init() delay = 5 print("\nStarting calibration in %d seconds with duration of %d seconds!\n" % (delay,calib_time)) time.sleep(1) for i in range(delay): print(str(delay-i)) time.sleep(1) print("Calibration has started!\n") t_end = time.time() + calib_time mag_x = [] mag_y = [] mag_z = [] while time.time() < t_end: mag_x_i, mag_y_i, mag_z_i = self.get_mag(False) mag_x.append(mag_x_i) mag_y.append(mag_y_i) mag_z.append(mag_z_i) print("%f,%f,%f\n" % (mag_x_i, mag_y_i, mag_z_i)) ### HARDIRON COMPAS COMPENSATION offset_x = (max(mag_x) + min(mag_x)) / 2 offset_y = (max(mag_y) + min(mag_y)) / 2 offset_z = (max(mag_z) + min(mag_z)) / 2 ### SOFTIRON COMPASS COMPENSATION avg_delta_x = (max(mag_x) - min(mag_x)) / 2 avg_delta_y = (max(mag_y) - min(mag_y)) / 2 avg_delta_z = (max(mag_z) - min(mag_z)) / 2 avg_delta = (avg_delta_x + avg_delta_y + avg_delta_z) / 3 scale_x = avg_delta / avg_delta_x scale_y = avg_delta / avg_delta_y scale_z = avg_delta / avg_delta_z # sys.stdout.write(str(offset_x)+"\n") # sys.stdout.write(str(offset_y)+"\n") # sys.stdout.write(str(offset_z)+"\n") # sys.stdout.write(str(scale_x)+"\n") # sys.stdout.write(str(scale_y)+"\n") # sys.stdout.write(str(scale_z)+"\n") decision = False print("\nFinished. Do you wish to save calibration data?") while not decision: start_cal = raw_input("[Y/N]\n") if (start_cal == 'N') or (start_cal == 'n'): print("\nCalibration canceled, no new calibration values saved.\n\n") sys.exit(1) elif (start_cal == 'Y') or (start_cal == 'y'): decision = True except KeyboardInterrupt: print("\nCalibration canceled, no new calibration values saved.\n\n") sys.exit(0) cal_file = open("ICM20948_mag_cal.txt", "w") cal_file.write("%f,%f,%f,%f,%f,%f" % (offset_x, offset_y, offset_z, scale_x, scale_y, scale_z)) cal_file.close() sys.stdout.write("Calibration successful!\n\n")
class WINDGAUGE03A(Device): def __init__(self, parent = None, address = 0x68, **kwargs): pass def usr_bank_sel(self, usr_bank_reg): pass def write_icm20948_reg_data(self, reg_address, reg_usr_bank, value): pass def read_icm20948_reg_data(self, reg_address, reg_usr_bank, num_of_bytes): pass def reset (self): pass def initialize (self): pass def i2c_master_init (self): pass def i2c_master_write (self, slv_id, slv_addr, data_out, slv_reg ): pass def i2c_master_read (self, slv_id, slv_addr, slv_rd_len, slv_reg ): pass def i2c_master_sdp33_init(self): pass def i2c_master_mag_init (self): pass def get_temp(self): pass def get_accel(self): pass def get_gyro(self): pass def SDP33_write (self, SDP33_i2c_address, command): pass def SDP33_read (self, SDP33_i2c_address, command): pass def get_mag(self, cal_available): pass def calib_mag(self, calib_time): pass
19
0
18
3
12
5
2
0.46
1
4
0
0
18
34
18
26
358
79
214
101
195
98
208
101
189
10
2
3
40
147,780
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/imu.py
pymlab.sensors.imu.MPU6050
class MPU6050(Device): MPU6050_ACCEL_XOUT_H = 0x3B MPU6050_ACCEL_XOUT_L = 0x3C MPU6050_ACCEL_YOUT_H = 0x3D MPU6050_ACCEL_YOUT_L = 0x3E MPU6050_ACCEL_ZOUT_H = 0x3F MPU6050_ACCEL_ZOUT_L = 0x40 MPU6050_TEMP_OUT_H = 0x41 MPU6050_TEMP_OUT_L = 0x42 MPU6050_GYRO_XOUT_H = 0x43 MPU6050_GYRO_XOUT_L = 0x44 MPU6050_GYRO_YOUT_H = 0x45 MPU6050_GYRO_YOUT_L = 0x46 MPU6050_GYRO_ZOUT_H = 0x47 MPU6050_GYRO_ZOUT_L = 0x78 def __init__(self, parent = None, address = 0x68, possible_adresses = [0x68, 0x69], **kwargs): Device.__init__(self, parent, address, **kwargs) def initialize(self): self.bus.write_byte_data(self.address, 0x6b, 0x00) # power management 1 def get_accel(self): MSB = self.bus.read_byte_data(self.address, self.MPU6050_ACCEL_XOUT_H) LSB = self.bus.read_byte_data(self.address, self.MPU6050_ACCEL_XOUT_L) x = (MSB << 8) + LSB if (x >= 0x8000): x = -1*((65535 - x) + 1) MSB = self.bus.read_byte_data(self.address, self.MPU6050_ACCEL_YOUT_H) LSB = self.bus.read_byte_data(self.address, self.MPU6050_ACCEL_YOUT_L) y = (MSB << 8) + LSB if (y >= 0x8000): y = -1*((65535 - y) + 1) MSB = self.bus.read_byte_data(self.address, self.MPU6050_ACCEL_ZOUT_H) LSB = self.bus.read_byte_data(self.address, self.MPU6050_ACCEL_ZOUT_L) z = (MSB << 8) + LSB if (z >= 0x8000): z = -1*((65535 - z) + 1) return(x/16384.0,y/16384.0,z/16384.0) def get_temp(self): MSB = self.bus.read_byte_data(self.address, self.MPU6050_TEMP_OUT_H) LSB = self.bus.read_byte_data(self.address, self.MPU6050_TEMP_OUT_L) t = (MSB << 8) + LSB return(t/340+36.5) def get_gyro(self): MSB = self.bus.read_byte_data(self.address, self.MPU6050_GYRO_XOUT_H) LSB = self.bus.read_byte_data(self.address, self.MPU6050_GYRO_XOUT_L) x = (MSB << 8) + LSB MSB = self.bus.read_byte_data(self.address, self.MPU6050_GYRO_YOUT_H) LSB = self.bus.read_byte_data(self.address, self.MPU6050_GYRO_YOUT_L) y = (MSB << 8) + LSB MSB = self.bus.read_byte_data(self.address, self.MPU6050_GYRO_ZOUT_H) LSB = self.bus.read_byte_data(self.address, self.MPU6050_GYRO_ZOUT_L) z = (MSB << 8) + LSB return(x/131,y/131,z/131) def dist(self, a,b): return math.sqrt((a*a)+(b*b)) def get_rotation(self, position = None): if position: (x, y, z) = position else: (x, y, z) = self.get_accel() radians = math.atan2(y, self.dist(x,z)) rx = math.degrees(radians) radians = math.atan2(x, self.dist(y,z)) ry = -math.degrees(radians) return (rx, ry)
class MPU6050(Device): def __init__(self, parent = None, address = 0x68, possible_adresses = [0x68, 0x69], **kwargs): pass def initialize(self): pass def get_accel(self): pass def get_temp(self): pass def get_gyro(self): pass def dist(self, a,b): pass def get_rotation(self, position = None): pass
8
0
8
1
7
0
2
0.02
1
0
0
0
7
0
7
15
84
20
64
39
56
1
63
39
55
4
2
1
11
147,781
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/imu.py
pymlab.sensors.imu.IMU01_GYRO
class IMU01_GYRO(Device): """ A3G4250D Gyroscope sensor binding. Needs sensitivity calibration data. This gyroscope is factory calibrated to sensitivity range from 7.4 to 10.1 mdps/digit. The 8.75 mdps/digit is selected as default value. """ def __init__(self, parent = None, address = 0x68, sensitivity_corr = (8.75, 8.75, 8.75), datarate = 0b00, bandwidth = 0b00, FIFO = True, HPF = True, **kwargs): Device.__init__(self, parent, address, **kwargs) self.sensitivity = (sensitivity_corr[0]/1000 , sensitivity_corr[1]/1000, sensitivity_corr[2]/1000) self.data_rate = datarate self.band_width = bandwidth self.FIFO_EN = FIFO self.HPen = HPF self.A3G4250D_WHO_AM_I = 0x0F self.A3G4250D_CTRL_REG1 = 0x20 self.A3G4250D_CTRL_REG2 = 0x21 self.A3G4250D_CTRL_REG3 = 0x22 self.A3G4250D_CTRL_REG4 = 0x23 self.A3G4250D_CTRL_REG5 = 0x24 self.A3G4250D_REFERENCE = 0x25 self.A3G4250D_OUT_TEMP = 0x26 self.A3G4250D_STATUS_REG = 0x27 self.A3G4250D_OUT_X_L = 0x28 self.A3G4250D_OUT_X_H = 0x29 self.A3G4250D_OUT_Y_L = 0x2A self.A3G4250D_OUT_Y_H = 0x2B self.A3G4250D_OUT_Z_L = 0x2C self.A3G4250D_OUT_Z_H = 0x2D self.A3G4250D_FIFO_CTRL_REG = 0x2e self.A3G4250D_FIFO_SRC_REG = 0x2F self.A3G4250D_INT1_CFG = 0x30 self.A3G4250D_INT1_SRC = 0x31 self.A3G4250D_INT1_TSH_XH = 0x32 self.A3G4250D_INT1_TSH_XL = 0x33 self.A3G4250D_INT1_TSH_YH = 0x34 self.A3G4250D_INT1_TSH_YL = 0x35 self.A3G4250D_INT1_TSH_ZH = 0x36 self.A3G4250D_INT1_TSH_ZL = 0x37 self.A3G4250D_INT1_DURATION = 0x38 self.A3G4250D_FIFO_BYPASS_MODE = 0b000 self.A3G4250D_FIFO_MODE = 0b001 self.A3G4250D_FIFO_STREAM_MODE = 0b010 def initialize(self): self.bus.write_byte_data(self.address, self.A3G4250D_CTRL_REG1, ((self.data_rate << 6) | (self.band_width << 4) | 0x0f)) ## setup data rate and bandwidth. All axis are active self.bus.write_byte_data(self.address, self.A3G4250D_CTRL_REG5, ((self.FIFO_EN << 7) | (self.HPen << 4) | 0x0f)) ## setup data rate and bandwidth. All axis are active self.bus.write_byte_data(self.address, self.A3G4250D_FIFO_CTRL_REG, (self.A3G4250D_FIFO_BYPASS_MODE << 5)) if (self.bus.read_byte_data(self.address, self.A3G4250D_WHO_AM_I) != 0b11010011): raise NameError('Gyroscope device could not be identified') def axes(self): INT16 = struct.Struct("<h") self.bus.write_byte_data(self.address, self.A3G4250D_CTRL_REG1, ((self.data_rate << 6) | (self.band_width << 4) | 0b1000)) ## setup data rate and self.bus.read_byte_data(self.address, self.A3G4250D_OUT_X_L) # x = self.bus.read_int16(self.address) # y = self.bus.read_int16(self.address) # z = self.bus.read_int16(self.address) # YLSB = self.bus.read_byte(self.address) # YMSB = self.bus.read_byte(self.address) # ZLSB = self.bus.read_byte(self.address) # ZMSB = self.bus.read_byte(self.address) # XLSB = self.bus.read_byte(self.address) # XMSB = self.bus.read_byte(self.address) # y = self.bus.read_wdata(self.address, self.A3G4250D_OUT_Y_L) # z = self.bus.read_wdata(self.address, self.A3G4250D_OUT_Z_L) # x = self.bus.read_wdata(self.address, self.A3G4250D_OUT_X_L) # print hex(YLSB),hex(YMSB),hex(ZLSB),hex(ZMSB),hex(XLSB),hex(XMSB) # return (x*self.sensitivity[0], y*self.sensitivity[1], z*self.sensitivity[2]) LSB = self.bus.read_byte_data(self.address, self.A3G4250D_OUT_X_L) MSB = self.bus.read_byte_data(self.address, self.A3G4250D_OUT_X_H) x = (MSB << 8) + LSB if (x & 0x1000): x -= 65536 LSB = self.bus.read_byte_data(self.address, self.A3G4250D_OUT_Y_L) MSB = self.bus.read_byte_data(self.address, self.A3G4250D_OUT_Y_H) y = (MSB << 8) + LSB if (y & 0x1000): y -= 65536 LSB = self.bus.read_byte_data(self.address, self.A3G4250D_OUT_Z_L) MSB = self.bus.read_byte_data(self.address, self.A3G4250D_OUT_Z_H) z = (MSB << 8) + LSB if (z & 0x1000): z -= 65536 # print hex(YLSB),hex(YMSB),hex(ZLSB),hex(ZMSB),hex(XLSB),hex(XMSB) # return (hex(self.bus.read_byte_data(self.address, self.A3G4250D_OUT_X_L)), hex(self.bus.read_byte_data(self.address, self.A3G4250D_OUT_X_H))) # self.bus.write_byte_data(self.address, self.A3G4250D_CTRL_REG5, ((self.FIFO_EN << 7) | (self.HPen << 4) | 0x0f)) ## setup data rate and self.bus.write_byte_data(self.address, self.A3G4250D_CTRL_REG1, ((self.data_rate << 6) | (self.band_width << 4) | 0b1111)) ## setup data rate and self.bus.write_byte_data(self.address, self.A3G4250D_FIFO_CTRL_REG, (self.A3G4250D_FIFO_BYPASS_MODE << 5)) return (x, y, z) def temp(self): temp = self.bus.read_byte_data(self.address, self.A3G4250D_OUT_TEMP) return temp
class IMU01_GYRO(Device): ''' A3G4250D Gyroscope sensor binding. Needs sensitivity calibration data. This gyroscope is factory calibrated to sensitivity range from 7.4 to 10.1 mdps/digit. The 8.75 mdps/digit is selected as default value. ''' def __init__(self, parent = None, address = 0x68, sensitivity_corr = (8.75, 8.75, 8.75), datarate = 0b00, bandwidth = 0b00, FIFO = True, HPF = True, **kwargs): pass def initialize(self): pass def axes(self): pass def temp(self): pass
5
1
26
5
17
5
2
0.35
1
1
0
0
4
34
4
12
114
26
68
46
63
24
68
46
63
4
2
1
8
147,782
MLAB-project/pymlab
MLAB-project_pymlab/tools/si570_freqdial.py
si570_freqdial.FreqDialWidget
class FreqDialWidget(wx.Window): RedrawReqEvent, EVT_REDRAW_REQ = wx.lib.newevent.NewCommandEvent() NDIGITS = 7 MAX_VALUE = 9999999 DARK_GREY = wx.Colour(64, 64, 64) @classmethod def clamp(self, v, lo, hi): if v < lo: return lo if v > hi: return hi return v def __init__(self, parent, default=0): wx.Window.__init__(self, parent, size=(440, 80)) self.Bind(wx.EVT_PAINT, self.on_paint) self.Bind(wx.EVT_MOTION, self.on_mouse_moved) self.Bind(wx.EVT_MOUSEWHEEL, self.on_mouse_wheel_moved) self.Bind(wx.EVT_KEY_DOWN, self.on_key_pressed) self.Bind(self.EVT_REDRAW_REQ, self.on_redraw_req) self.mouse_pos = wx.Point(0, 0) self.focused_digit_no = -1 self.w, self.h = self.GetSize() self._value = default self._value_cv = threading.Condition() self._locked = False self._error = False self.fonts = [ wx.Font(size, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL) for size in (40, 20, 12) ] dc = wx.ClientDC(self) dc.SetFont(self.fonts[0]) self.border = 10 self.digitw, self.digith = dc.GetTextExtent("0") border, dw = self.border, self.digitw self.digit_rects = [ wx.Rect(border + dw*(8-i) - int(offset), border, dw, self.digith) for i, offset in enumerate([0, 0, 0, dw/2, dw/2, dw/2, dw]) ] dc.SetFont(self.fonts[1]) ulabelw, ulabelh = dc.GetTextExtent("kHz") self.khz_label_pos = (border + dw*9 + 5, border + 24) self.flag_label_pos = (border + dw*9 + ulabelw + 10, border + 15) def on_redraw_req(self, event): self.Refresh(); self.Update() @property def value(self): return self._value def set_flags(self, locked, error): if self._locked == locked and self._error == error: return self._locked, self._error = locked, error wx.PostEvent(self, self.RedrawReqEvent(0)) def _set_value(self, value): with self._value_cv: if self._value == value: return self._value = value self._value_cv.notify_all() self.Refresh(); self.Update() def add_to_value(self, delta): self._set_value(self.clamp(self._value + delta, 0, self.MAX_VALUE)) def on_paint(self, event): dc = wx.PaintDC(self) dc.SetBrush(wx.BLACK_BRUSH) dc.DrawRectangle(0, 0, self.w, self.h) dc.SetTextForeground(wx.WHITE) dc.SetFont(self.fonts[0]) v = int(self.value) self.focused_digit_no = -1 for i, rect in enumerate(self.digit_rects): if rect.Contains(self.mouse_pos): self.focused_digit_no = i dc.SetBrush(wx.LIGHT_GREY_BRUSH) dc.DrawRectangle(rect) if v != 0 or i == 0: dc.DrawText(str(v % 10), rect.GetX(), rect.GetY()) v = v // 10 dc.SetFont(self.fonts[1]) dc.SetTextForeground(wx.LIGHT_GREY) dc.DrawText("kHz", *self.khz_label_pos) dc.SetFont(self.fonts[2]) if self._locked: dc.SetTextForeground(wx.GREEN) else: dc.SetTextForeground(self.DARK_GREY) flag_x, flag_y = self.flag_label_pos dc.DrawText("LOCKED", flag_x, flag_y) if self._error: dc.SetTextForeground(wx.RED) else: dc.SetTextForeground(self.DARK_GREY) dc.DrawText("ERROR", flag_x, flag_y + 20) def on_mouse_moved(self, event): self.mouse_pos = event.GetPosition() self.Refresh(); self.Update(); def on_mouse_wheel_moved(self, event): if self.focused_digit_no != -1: dir_ = 1 if (event.GetWheelRotation() > 0) else -1 self.add_to_value(dir_ * 10**self.focused_digit_no) def move_mouse_to_digit(self, digit_no): dc = wx.ClientDC(self) rect = self.digit_rects[digit_no] x, y = rect.GetX()+rect.GetWidth()/2, rect.GetY()+rect.GetHeight()/2 self.WarpPointer(dc.LogicalToDeviceX(x), dc.LogicalToDeviceY(y)) def shift_focus(self, dir_): assert dir_ in (1, -1) if self.focused_digit_no == -1: return self.move_mouse_to_digit(self.clamp(self.focused_digit_no + dir_, 0, self.NDIGITS-1)) def on_key_pressed(self, event): if self.focused_digit_no == -1: return key = event.GetKeyCode() if key in [wx.WXK_LEFT, wx.WXK_RIGHT]: self.shift_focus(1 if key == wx.WXK_LEFT else -1) if key in [wx.WXK_UP, wx.WXK_DOWN]: dir_ = 1 if key == wx.WXK_UP else -1 self.add_to_value(dir_ * 10**self.focused_digit_no) if key in range(48, 58): num = key - 48 focused = 10**self.focused_digit_no new_val = self._value - (self._value // focused % 10) * focused new_val += focused * num self._set_value(new_val) self.shift_focus(-1)
class FreqDialWidget(wx.Window): @classmethod def clamp(self, v, lo, hi): pass def __init__(self, parent, default=0): pass def on_redraw_req(self, event): pass @property def value(self): pass def set_flags(self, locked, error): pass def _set_value(self, value): pass def add_to_value(self, delta): pass def on_paint(self, event): pass def on_mouse_moved(self, event): pass def on_mouse_wheel_moved(self, event): pass def move_mouse_to_digit(self, digit_no): pass def shift_focus(self, dir_): pass def on_key_pressed(self, event): pass
16
0
11
1
9
0
2
0
1
5
0
0
12
15
13
13
159
30
129
49
113
0
119
47
105
7
1
2
31
147,783
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/utils.py
pymlab.utils.UserException
class UserException(Exception): def __init__(self, message = None, *args, **kwargs): Exception.__init__(self, message, *args) self.message = str(message) self.underlying = kwargs.pop("underlying", None) self.kwargs = kwargs def __str__(self): return self.message def __repr__(self): if self.underlying is None: return obj_repr(self, self.message) return obj_repr(self, self.message, underlying = self.underlying) def __pprint__(self, printer, level = 0): printer.writef("Message: {}\n\n", self.message) printer.writeln("Keywords:") printer.indent() for key, value in self.kwargs.iteritems(): printer.writef("{}: ", key) printer.indent(printer.CURRENT) printer.format_inner(value, level + 1) printer.unindent() printer.unindent()
class UserException(Exception): def __init__(self, message = None, *args, **kwargs): pass def __str__(self): pass def __repr__(self): pass def __pprint__(self, printer, level = 0): pass
5
0
6
1
5
0
2
0
1
1
0
0
4
3
4
14
28
6
22
9
17
0
22
9
17
2
3
1
6
147,784
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/utils.py
pymlab.utils.PrettyPrinter
class PrettyPrinter(object): INDENT = object() CURRENT = object() def __init__(self, output = None): if output is None: output = sys.stdout self.output = output self._indent = [] self._current_indent = 0 self._mode_stack = [] self.new_line = True self.max_level = None @property def mode(self): if len(self._mode_stack) == 0: return None return self._mode_stack[-1] def push_mode(self, value): self._mode_stack.append(value) def pop_mode(self): return self._mode_stack.pop() def write(self, value): if value is self.INDENT: self.output.write("".join(self._indent)) self.new_line = False return if self.new_line: self.write(self.INDENT) self.new_line = False value = str(value) if "\n" in value: lines = value.splitlines() for line in lines: self.writeln(line) else: self._current_indent += len(value) self.output.write(value) def writeln(self, value = ""): self.write(value) self.output.write("\n") self.new_line = True self._current_indent = 0 def writef(self, value, *args, **kwargs): self.write(value.format(*args, **kwargs)) def flush(self): self.output.flush() def close(self): self.output.close() def indent(self, indent = " "): if indent is self.CURRENT: self._indent.append(" " * self._current_indent) self._current_indent = 0 return self._indent.append(indent) def unindent(self): self._indent.pop() def format_list(self, value, level = 0): if (self.max_level is not None) and (level >= self.max_level): self.write("[ ... ]") return if len(value) < 10: self.write("[ ") self.indent(self.CURRENT) for item in value: self.format_inner(item, level + 1) self.write(", ") self.unindent() self.write("]") return self.writeln("[") self.indent() for item in value: self.format_inner(item, level + 1) self.writeln(",") self.unindent() self.write("]") def format_inner(self, value, level = 0): if value in self.visited: self.write("<recursion>") return if self.mode is None: meth = getattr(value, "__pprint__", None) else: meth = getattr(value, "__pprint_%s__" % (self.mode, ), None) if meth is None: meth = getattr(value, "__pprint__", None) if meth: self.visited.append(value) meth(self, level) self.visited.pop() return if isinstance(value, list): self.format_list(value, level) return if isinstance(value, basestring): if "\n" in value: self.indent() lines = value.splitlines() for line in lines: self.format_inner(line, level + 1) self.unindent() return self.write(repr(value)) def format(self, value): self.visited = [] self.format_inner(value) self.visited = None
class PrettyPrinter(object): def __init__(self, output = None): pass @property def mode(self): pass def push_mode(self, value): pass def pop_mode(self): pass def write(self, value): pass def writeln(self, value = ""): pass def writef(self, value, *args, **kwargs): pass def flush(self): pass def close(self): pass def indent(self, indent = " "): pass def unindent(self): pass def format_list(self, value, level = 0): pass def format_inner(self, value, level = 0): pass def format_list(self, value, level = 0): pass
16
0
8
1
7
0
2
0
1
2
0
0
14
7
14
14
128
21
107
31
91
0
104
30
89
9
1
3
33
147,785
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/utils.py
pymlab.utils.Enum2
class Enum2(object): INDEX = object() class Sequence(object): def __iter__(self): return self @classmethod def range(cls, start = 0, step = 1): class IntegerSequence(cls.Sequence): def __init__(self, start, step): self._next = start self._step = step def __iter__(self): return self def next(self): value = self._next self._next += self._step return value return IntegerSequence(start, step) def __init__(self, attributes, defaults, items): self._attributes = attributes self._defaults = defaults self._item_class = collections.namedtuple("EnumItem", attributes) self._name_map = {} self._items = [] for item in items: if isinstance(item, basestring): item = (item, ) name = str(item[0]) attributes = [(a or b) for a, b in itertools.izip_longest(item, self._defaults)] attributes = [(a.next() if isinstance(a, self.Sequence) else a) for a in attributes] value = self._item_class(*attributes) setattr(self, name, value) self._name_map[name] = value self._items.append(value) def __len__(self): return len(self._items) def __iter__(self): return iter(self._items) def __getitem__(self, key): if isinstance(key, int): if key >= len(self._items): raise KeyError return self._items[key] if isinstance(key, basestring): return self._name_map[key] raise KeyError
class Enum2(object): class Sequence(object): def __iter__(self): pass @classmethod def range(cls, start = 0, step = 1): pass class IntegerSequence(cls.Sequence): def __init__(self, start, step): pass def __iter__(self): pass def next(self): pass def __init__(self, start, step): pass def __len__(self): pass def __iter__(self): pass def __getitem__(self, key): pass
13
0
7
1
6
0
2
0
1
5
2
0
4
5
5
5
61
15
46
25
33
0
45
24
33
4
1
2
15
147,786
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/utils.py
pymlab.utils.Enum
class Enum(object): def __init__(self, *args, **kwargs): self._names = {} self._indicies = {} self._items = [] self.max_value = 0 index = 0 for arg in args: if isinstance(arg, int): index = arg else: self.max_value = max(self.max_value, index) self._indicies[arg] = index self._names[index] = arg self._items.append(index) index += 1 def __len__(self): return len(self._indicies) def __setitem__(self, key, value): self._names[key] = value self._indicies[value] = key if isinstance(key, int): self.max_value = max(self.max_value, key) def __getattr__(self, name): try: return self._indicies[name] except KeyError: raise AttributeError def __in__(self, value): return value in self._indicies def __iter__(self): return iter(self._items) def to_string(self, value): try: return self._names[value] except KeyError: return "<undefined enum %r>" % (value, ) def get_name(self, value): try: return self._names[value] except KeyError: raise ValueError("%r is not a valid enum value." % (value, )) def from_name(self, name): try: return self._indicies[name] except KeyError: raise ValueError("Unknown enum name: %r." % (name, )) def decorate(self, name): def decorator(cls): self[name] = cls return cls return decorator
class Enum(object): def __init__(self, *args, **kwargs): pass def __len__(self): pass def __setitem__(self, key, value): pass def __getattr__(self, name): pass def __in__(self, value): pass def __iter__(self): pass def to_string(self, value): pass def get_name(self, value): pass def from_name(self, name): pass def decorate(self, name): pass def decorator(cls): pass
12
0
5
0
5
0
2
0
1
4
0
0
10
4
10
10
63
11
52
18
40
0
51
18
39
3
1
2
18
147,787
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/tests/sensors/config.py
pymlab.tests.sensors.config.ConfigTestCase
class ConfigTestCase(unittest.TestCase): def test_load_python_00(self): cfg = config.Config() cfg.load_python(""" i2c = { "port": 5, } bus = [ ] """) def test_load_python_01(self): cfg = config.Config() cfg.load_python(""" i2c = { "port": 5, } bus = [ { "type": "mag01", "address": 0x68 }, { "type": "sht25" } ] """) def test_load_python_02(self): cfg = config.Config() cfg.load_python(""" i2c = { "port": 5, } bus = [ { "type": "i2chub", "address": 0x70, "children": [ {"type": "mag01", "channel": 0}, {"type": "mag01", "channel": 1}, ] }, { "type": "mag01", "address": 0x68 } ] """) def test_load_python_03(self): cfg = config.Config() cfg.load_python(""" i2c = { "port": 5, } bus = [ { "type": "i2chub", "address": 0x72, "children": [ { "type": "i2chub", "address": 0x70, "channel": 1, "children": [ { "type": "sht25", "channel": 2, }, { "type": "mag01", "channel": 2, }, ], }, ], }, ] """) def test_load_python_04(self): cfg = config.Config() cfg.load_python(""" i2c = { "port": 1, } bus = [ { "type": "altimet01", "name": "alt", }, ] """)
class ConfigTestCase(unittest.TestCase): def test_load_python_00(self): pass def test_load_python_01(self): pass def test_load_python_02(self): pass def test_load_python_03(self): pass def test_load_python_04(self): pass
6
0
15
2
14
0
1
0
1
1
1
0
5
0
5
77
82
13
69
11
63
0
16
11
10
1
2
0
5
147,788
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/tests/remote.py
pymlab.tests.remote.RemoteDriverTestCase
class RemoteDriverTestCase(unittest.TestCase): def test_dummy_driver(self): d = load_driver( device="dummy" ) self.assertEqual(d.read_byte(0), 0xaa) def test_remote_driver(self): d = load_driver( device="remote", host=[], # will run the server locally remote_device={"device": "dummy"} ) self.assertEqual(d.read_byte(0), 0xaa) d.close()
class RemoteDriverTestCase(unittest.TestCase): def test_dummy_driver(self): pass def test_remote_driver(self): pass
3
0
7
0
7
1
1
0.07
1
0
0
0
2
0
2
74
15
1
14
5
11
1
8
5
5
1
2
0
2
147,789
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/windgauge.py
pymlab.sensors.windgauge.WINDGAUGE03A
class WINDGAUGE03A(Device): def __init__(self, parent = None, address = 0x68, sdp3x_address = 0x21, **kwargs): Device.__init__(self, parent, address, **kwargs) self.r_outer = 0.018 # outer venturi tube diameter [m] self.r_inner = 0.009 # inner venturi tube diameter [m] self.air_density = 1.029 # density of air [kg/m^3] self.mag_declination = 4.232 # magnetic declination in deg from true north self.sdp3x_i2c_address = sdp3x_address self.mag_i2c_address = 0x0C ## USER BANK 0 REGISTERS self.ICM20948_WHO_AM_I = 0x00 self.ICM20948_USER_CTRL = 0x03 self.ICM20948_LP_CONFIG = 0x05 self.ICM20948_PWR_MGMT_1 = 0x06 self.ICM20948_PWR_MGMT_2 = 0x07 self.ICM20948_INT_PIN_CFG = 0x0F self.ICM20948_INT_ENABLE = 0x10 self.ICM20948_I2C_MST_STATUS = 0x17 self.ICM20948_ACEL_XOUT_H = 0x2D self.ICM20948_ACEL_XOUT_L = 0x2E self.ICM20948_ACEL_YOUT_H = 0x2F self.ICM20948_ACEL_YOUT_L = 0x30 self.ICM20948_ACEL_ZOUT_H = 0x31 self.ICM20948_ACEL_XOUT_L = 0x32 self.ICM20948_GYRO_XOUT_H = 0x33 self.ICM20948_GYRO_XOUT_L = 0x34 self.ICM20948_GYRO_YOUT_H = 0x35 self.ICM20948_GYRO_YOUT_L = 0x36 self.ICM20948_GYRO_ZOUT_H = 0x37 self.ICM20948_GYRO_XOUT_L = 0x38 self.ICM20948_TEMP_OUT_H = 0x39 self.ICM20948_TEMP_OUT_L = 0x3A self.ICM20948_EXT_SLV_SENS_DATA_00 = 0x3B # self.ICM20948_EXT_SLV_SENS_DATA_01 = 0x3C # USER BANK 2 REGISTERS self.ICM20948_GYRO_CONFIG = 0x01 self.ICM20948_ODR_ALIGN_EN = 0x09 self.ICM20948_ACCEL_SMPLRT_DIV_1 = 0x10 self.ICM20948_ACCEL_SMPLRT_DIV_2 = 0x11 self.ICM20948_ACEL_CONFIG = 0x14 self.ICM20948_ACEL_CONFIG_2 = 0x15 ## USER BANK 3 REGISTERS self.ICM20948_I2C_SLV0_ADDR = 0x03 self.ICM20948_I2C_SLV0_REG = 0x04 # I2C slave 0 register address from where to begin data transfer. self.ICM20948_I2C_SLV0_CTRL = 0x05 self.ICM20948_I2C_SLV0_DO = 0x06 self.ICM20948_I2C_SLV1_ADDR = 0x07 self.ICM20948_I2C_SLV1_REG = 0x08 # I2C slave 1 register address from where to begin data transfer. self.ICM20948_I2C_SLV1_CTRL = 0x09 self.ICM20948_I2C_SLV1_DO = 0x0A ## USER BANK REGISTERS 0-3 self.ICM20948_REG_BANK_SEL = 0x7F # 0 ## MAGNETOMETER REGISTERS self.AK09916_WIA2 = 0x01 # WHO_AM_I[7:0] = 0x09 self.AK09916_ST1 = 0x10 # STATUS_1[1] = DOR (data overrun); STATUS_1[0] = DRDY (data ready) self.AK09916_HXL = 0x11 # HXL[7:0] = X-axis measurement data lower 8bit self.AK09916_HXH = 0x12 # HXH[15:8] = X-axis measurement data higher 8bit self.AK09916_HYL = 0x13 # HYL[7:0] = Y-axis measurement data lower 8bit self.AK09916_HYH = 0x14 # HYH[15:8] = Y-axis measurement data higher 8bit self.AK09916_HZL = 0x15 # HZL[7:0] = Z-axis measurement data lower 8bit self.AK09916_HZH = 0x16 # HZH[15:8] = Z-axis measurement data higher 8bit self.AK09916_ST2 = 0x18 # STATUS_2[3] = HOFL (magnetic sensor overflow) self.AK09916_CNTL2 = 0x31 # CONTROL_2[4:0] = """ “00000”: Power-down mode “00001”: Single measurement mode “00010”: Continuous measurement mode 1 (10Hz) “00100”: Continuous measurement mode 2 (20Hz) “00110”: Continuous measurement mode 3 (50Hz) “01000”: Continuous measurement mode 4 (100Hz) “10000”: Self-test mode """ self.AK09916_CNTL3 = 0x32 # CONTROL_3[0] = SRST (soft reset) self.TRIGGER_MEASUREMENT = [0x36, 0x1E] # SDP3x command: trigger continuos differential pressure measurement self.TRIGGER_MEASUREMENT_2 = [0x36, 0x15] # SDP3x command: trigger differential pressure measurement with averaging until read self.SOFT_RESET = 0x06 # SDP3x command: soft reset self.READ_PRODUCT_IDENTIFIER1 = [0x36, 0x7c] # SDP3x command: read product idetifier register self.READ_PRODUCT_IDENTIFIER2 = [0xE1, 0x02] self.SDP3x_tsf = 200.0 #temperature scaling factor (same for all SDP3X sensors) def usr_bank_sel(self, usr_bank_reg): self.bus.write_byte_data(self.address, self.ICM20948_REG_BANK_SEL, usr_bank_reg << 4) def write_icm20948_reg_data(self, reg_address, reg_usr_bank, value): self.usr_bank_sel(reg_usr_bank) self.bus.write_byte_data(self.address, reg_address, value) def read_icm20948_reg_data(self, reg_address, reg_usr_bank, num_of_bytes): self.usr_bank_sel(reg_usr_bank) if num_of_bytes > 1: return(self.bus.read_i2c_block_data(self.address, reg_address, num_of_bytes)) else: return((self.bus.read_byte_data(self.address, reg_address))) def reset (self): self.write_icm20948_reg_data(self.ICM20948_PWR_MGMT_1, 0, 0x01 | 1 << 7) # ICM20948 - reset device and register values time.sleep(0.1) self.write_icm20948_reg_data(self.ICM20948_PWR_MGMT_1, 0, 0x01) # PWR_MGMT_1[6] (SLEEP) set to 0 - !!!DEVICE WAKEUP!!!; PWR_MGMT_1[2:0] (CLKSEL) = "001" for optimal performance self.write_icm20948_reg_data(self.ICM20948_INT_PIN_CFG, 0, 0x02) # INT_PIN_CFG[1] (BYPASS_ENABLE) = 1 !ENABLE BYPASS OF ICM20948's I2C INTERFACE! (SDA and SCL connected directly to auxilary AUX_DA and AUX_CL) self.bus.write_byte(self.sdp3x_i2c_address, 0x00) # SDP3x device wakeup time.sleep(0.1) self.bus.write_byte(0x00, 0x06) # SDP3x device soft reset time.sleep(0.1) def initialize (self): self.write_icm20948_reg_data(self.ICM20948_PWR_MGMT_1, 0, 0x01) # PWR_MGMT_1[6] (SLEEP) set to 0 - !!!DEVICE WAKEUP!!!; PWR_MGMT_1[2:0] (CLKSEL) = "001" for optimal performance # time.sleep(0.1) ### ICM20948 accelerometer configuration # self.write_icm20948_reg_data(self.ICM20948_ODR_ALIGN_EN, 2, 0x01) # # self.write_icm20948_reg_data(self.ICM20948_ACCEL_SMPLRT_DIV_2, 2, 0x04) # # self.write_icm20948_reg_data(self.ICM20948_ACCEL_SMPLRT_DIV_2, 2, 0x65) # LSB for accel sample div. rate ( ODR = 1.125 kHz/(1+ACCEL_SMPLRT_DIV[11:0])) - set to 10 Hz # self.write_icm20948_reg_data(self.ICM20948_ACCEL_SMPLRT_DIV_2, 2, 0x0F) # self.write_icm20948_reg_data(self.ICM20948_ACCEL_SMPLRT_DIV_2, 2, 0xFF) # LSB for accel sample div. rate ( ODR = 1.125 kHz/(1+ACCEL_SMPLRT_DIV[11:0])) - set to 10 Hz # self.write_icm20948_reg_data(self.ICM20948_ACCEL_SMPLRT_DIV_2, 2, 0x70) # LSB for accel sample div. rate ( ODR = 1.125 kHz/(1+ACCEL_SMPLRT_DIV[11:0])) - set to 10 Hz # self.write_icm20948_reg_data(self.ICM20948_ACEL_CONFIG, 2, 0x09) # enable accel DPLF and set it to 23.9 Hz # self.write_icm20948_reg_data(self.ICM20948_ACEL_CONFIG_2, 2, 0x03) # ### SDP3X sensor configuration ##################### self.write_icm20948_reg_data(self.ICM20948_USER_CTRL, 0, 0x00) # USER_CTRL[5] (I2C_MST_EN) = 0 self.write_icm20948_reg_data(self.ICM20948_INT_PIN_CFG, 0, 0x02) # INT_PIN_CFG[1] (BYPASS_ENABLE) = 1 !ENABLE BYPASS OF ICM20948's I2C INTERFACE! (SDA and SCL connected directly to auxilary AUX_DA and AUX_CL) self.bus.write_byte(self.sdp3x_i2c_address, 0x00) # SDP3x device wakeup time.sleep(0.1) self.bus.write_byte_data(self.sdp3x_i2c_address, 0x36, 0x7C) self.bus.write_byte_data(self.sdp3x_i2c_address, 0xE1, 0x02) p_id = self.bus.read_i2c_block(self.sdp3x_i2c_address, 18) p_num = ((p_id[0] << 24) | (p_id[1] << 16) | (p_id[3] << 8) | p_id[4]) if (p_num == 0x03010101): sensor = "SDP31 500Pa" elif (p_num == 0x03010201): sensor = "SDP32 125Pa" elif (p_num == 0x03010384): sensor = "SDP33 1500Pa" else: sensor = "unknown" print("ID: %s - sensor: %s" % (hex(p_num), sensor)) if (os.path.isfile("ICM20948_mag_cal.txt")): print("Magnetometer calibrated.\n") else: print("Magnetometer not calibrated.\n") self.bus.write_byte_data(self.sdp3x_i2c_address, self.TRIGGER_MEASUREMENT[0], self.TRIGGER_MEASUREMENT[1] ) # send "trigger continuos measurement" command to SDP3X sensor to begin diff. pressure and temperature measurement time.sleep(0.1) self.i2c_master_read(0, self.sdp3x_i2c_address, 9, 0x00) # configure SDP3X as slave_0 of IMU's I2C master ### ICM-20948 magnetometer configuration ##################### self.i2c_master_write(1, self.mag_i2c_address, 0x08, self.AK09916_CNTL2) # configure magnetometer to begin magnetic flux measurement with frequency of 100 Hz (for measurement frequency options ref. to AK09916_CNTL2) self.i2c_master_read(1, self.mag_i2c_address, 9, 0x10) def stop(self): self.write_icm20948_reg_data(self.ICM20948_USER_CTRL, 0, 0x00) # USER_CTRL[5] (I2C_MST_EN) = 0 self.write_icm20948_reg_data(self.ICM20948_INT_PIN_CFG, 0, 0x02) # INT_PIN_CFG[1] (BYPASS_ENABLE) = 1 !ENABLE BYPASS OF ICM20948's I2C INTERFACE! (SDA and SCL connected directly to auxilary AUX_DA and AUX_CL) self.bus.write_byte_data(self.sdp3x_i2c_address, 0x3F, 0xF9) # SDP3x stop continuous measurement command self.bus.write_byte_data(self.sdp3x_i2c_address, 0x36, 0x77) # SDP3x enter sleep mode self.write_icm20948_reg_data(self.ICM20948_PWR_MGMT_1, 0, 0x21) # PWR_MGMT_1[6] (SLEEP) set to 1 - !!!DEVICE PUT IN SLEEP MODE!!!; PWR_MGMT_1[2:0] (CLKSEL) = "001" for optimal performance def i2c_master_write (self, slv_id, slv_addr, data_out, slv_reg ): # slv_reg_shift = 4 * slv_id self.write_icm20948_reg_data(self.ICM20948_USER_CTRL, 0, 0x20) # USER_CTRL[5] (I2C_MST_EN) = 1 self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_DO + slv_reg_shift, 3, data_out) # I2C_SLVX_DO[7:0] = data_out self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_ADDR + slv_reg_shift, 3, slv_addr) # I2C_SLVX_ADDR[6:0] = (slv_addr | I2C_SLV0_RNW) - slave addres | R/W bit MSB (W: 0) self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_REG + slv_reg_shift, 3, slv_reg) # I2C_SLVX_REG[7:0] = slv_reg self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_CTRL + slv_reg_shift, 3, 0x8a) # I2C_SLVX_CTRL[7] (I2C_SLVX_EN) = 1, I2C_SLVX_CTRL[5] (I2C_SLVX_REG_DIS) = 0 self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_CTRL + slv_reg_shift, 3, 0x00) # I2C_SLVX_CTRL[7] (I2C_SLVX_EN) = 0 self.write_icm20948_reg_data(self.ICM20948_USER_CTRL, 0, 0x00) # USER_CTRL[5] (I2C_MST_EN) = 0 def i2c_master_read (self, slv_id, slv_addr, slv_rd_len, slv_reg ): # slv_reg_shift = 4 * slv_id self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_ADDR + slv_reg_shift, 3, slv_addr | (1 << 7)) # I2C_SLVX_ADDR[6:0] = (slv_addr | I2C_SLV0_RNW) - slave addres | R/W bit MSB (R: 1) self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_REG + slv_reg_shift, 3, slv_reg) # I2C_SLVX_REG[7:0] = slv_reg self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_CTRL + slv_reg_shift, 3, 0x80 | slv_rd_len) # I2C_SLVX_CTRL[7] (I2C_SLVX_EN) = 1, I2C_SLVX_LENG[3:0] = slv_rd_len (number of bytes to be read from slave (0-15)) self.write_icm20948_reg_data(self.ICM20948_USER_CTRL, 0, 0x20) # USER_CTRL[5] (I2C_MST_EN) = 1 def get_temp(self): room_temp_offset = 21.0 temp_sens = 333.87 temp_raw_data = self.read_icm20948_reg_data(self.ICM20948_TEMP_OUT_H, 0, 2) temp_raw = ((temp_raw_data[0] << 8) + temp_raw_data[1]) return(((temp_raw - room_temp_offset)/temp_sens) + room_temp_offset) def get_accel(self): accel_sens = float((1 << (3 - (self.read_icm20948_reg_data(self.ICM20948_ACEL_CONFIG, 2, 1) & 0x6))) * 2048) accel_raw = self.read_icm20948_reg_data(self.ICM20948_ACEL_XOUT_H, 0, 6) accel_x_raw = ((accel_raw[0] << 8) + accel_raw[1]) accel_y_raw = ((accel_raw[2] << 8) + accel_raw[3]) accel_z_raw = ((accel_raw[4] << 8) + accel_raw[5]) if accel_x_raw > 0x7fff: accel_x_raw -= 65536 if accel_y_raw > 0x7fff: accel_y_raw -= 65536 if accel_z_raw > 0x7fff: accel_z_raw -= 65536 return((accel_x_raw / accel_sens), (accel_y_raw / accel_sens), (accel_z_raw / accel_sens) ) def get_gyro(self): gyro_sens = float((1 << (3 - (self.read_icm20948_reg_data(self.ICM20948_GYRO_CONFIG, 2, 1) & 0x6))) * 16.4) gyro_raw = self.read_icm20948_reg_data(self.ICM20948_GYRO_XOUT_H, 0, 6) gyro_x_raw = ((gyro_raw[0] << 8) + gyro_raw[1]) gyro_y_raw = ((gyro_raw[2] << 8) + gyro_raw[3]) gyro_z_raw = ((gyro_raw[4] << 8) + gyro_raw[5]) if gyro_x_raw > 0x7fff: gyro_x_raw -= 65536 if gyro_y_raw > 0x7fff: gyro_y_raw -= 65536 if gyro_z_raw > 0x7fff: gyro_z_raw -= 65536 return((gyro_x_raw / gyro_sens), (gyro_y_raw / gyro_sens), (gyro_z_raw / gyro_sens)) def get_mag_raw(self, *args): mag_raw_data = self.read_icm20948_reg_data(self.ICM20948_EXT_SLV_SENS_DATA_00 + 9, 0, 9) magX = (mag_raw_data[2] << 8) + mag_raw_data[1] magY = (mag_raw_data[4] << 8) + mag_raw_data[3] magZ = (mag_raw_data[6] << 8) + mag_raw_data[5] if magX > 0x7fff: magX -= 65536 if magY > 0x7fff: magY -= 65536 if magZ > 0x7fff: magZ -= 65536 mag_scf = 4912/32752.0 return(magX, magY, magZ) def get_mag(self, *args): offset_x, offset_y, offset_z = 0, 0, 0 scale_x, scale_y, scale_z = 1, 1, 1 if (not args) & (os.path.isfile("ICM20948_mag_cal.txt")): cal_file = open("ICM20948_mag_cal.txt", "r") cal_consts = cal_file.readline().split(",") offset_x = float(cal_consts[0]) offset_y = float(cal_consts[1]) offset_z = float(cal_consts[2]) scale_x = float(cal_consts[3]) scale_y = float(cal_consts[4]) scale_z = float(cal_consts[5]) mag_raw_data = self.read_icm20948_reg_data(self.ICM20948_EXT_SLV_SENS_DATA_00 + 9, 0, 9) magX = (mag_raw_data[2] << 8) + mag_raw_data[1] magY = (mag_raw_data[4] << 8) + mag_raw_data[3] magZ = (mag_raw_data[6] << 8) + mag_raw_data[5] if magX > 0x7fff: magX -= 65536 if magY > 0x7fff: magY -= 65536 if magZ > 0x7fff: magZ -= 65536 mag_scf = 4912/32752.0 return(((magX*mag_scf) - offset_x) * scale_x, ((magY*mag_scf) - offset_y) * scale_y, ((magZ*mag_scf) - offset_z)*scale_z) def calib_mag(self, calib_time): try: decision = False print("\nDo you wish to perform new magnetometer calibration? Old calibration data will be lost!") while not decision: start_cal = input("[Y/N]\n") if (start_cal == 'N') or (start_cal == 'n'): print("\nCalibration canceled, no new calibration values saved.\n\n") self.stop() sys.exit(1) elif (start_cal == 'Y') or (start_cal == 'y'): decision = True self.initialize() delay = 5 print("\nStarting calibration in %d seconds with duration of %d seconds! Please manually rotate by sensor to every direction\n" % (delay, calib_time)) time.sleep(1) for i in range(delay): print(str(delay-i)) time.sleep(1) print("Calibration has started!\n") t_end = time.time() + calib_time mag_x = [] mag_y = [] mag_z = [] while time.time() < t_end: mag_x_i, mag_y_i, mag_z_i = self.get_mag(True) mag_x.append(mag_x_i) mag_y.append(mag_y_i) mag_z.append(mag_z_i) print("%f,%f,%f\n" % (mag_x_i, mag_y_i, mag_z_i)) ### HARDIRON COMPAS COMPENSATION offset_x = (max(mag_x) + min(mag_x)) / 2 offset_y = (max(mag_y) + min(mag_y)) / 2 offset_z = (max(mag_z) + min(mag_z)) / 2 ### SOFTIRON COMPASS COMPENSATION avg_delta_x = (max(mag_x) - min(mag_x)) / 2 avg_delta_y = (max(mag_y) - min(mag_y)) / 2 avg_delta_z = (max(mag_z) - min(mag_z)) / 2 avg_delta = (avg_delta_x + avg_delta_y + avg_delta_z) / 3 scale_x = avg_delta / avg_delta_x scale_y = avg_delta / avg_delta_y scale_z = avg_delta / avg_delta_z decision = False print("\nFinished. Do you wish to save calibration data?") while not decision: start_cal = input("[Y/N]\n") if (start_cal == 'N') or (start_cal == 'n'): print("\nCalibration canceled, no new calibration values saved.\n\n") self.stop() sys.exit(1) elif (start_cal == 'Y') or (start_cal == 'y'): decision = True except KeyboardInterrupt: print("\nCalibration canceled, no new calibration values saved.\n\n") self.stop() sys.exit(0) cal_file = open("ICM20948_mag_cal.txt", "w") cal_file.write("%f,%f,%f,%f,%f,%f" % (offset_x, offset_y, offset_z, scale_x, scale_y, scale_z)) cal_file.close() sys.stdout.write("Calibration successful!\n\n") def get_dp(self): raw_data = self.read_icm20948_reg_data(self.ICM20948_EXT_SLV_SENS_DATA_00, 0x00, 9) press_data = raw_data[0]<<8 | raw_data[1] if (press_data > 0x7fff): press_data -= 65536 dpsf = float(raw_data[6]<<8 | raw_data[7]) # SDP3X sensor scaling factor obtained from byte 6 and 7 of read message if(dpsf == 0): return(0.0) else: return(press_data/dpsf) def get_t(self): raw_data = self.read_icm20948_reg_data(self.ICM20948_EXT_SLV_SENS_DATA_00, 0x00, 5) temp_data = raw_data[3]<<8 | raw_data[4] return(temp_data/self.SDP3x_tsf) def get_t_dp(self): raw_data = self.read_icm20948_reg_data(self.ICM20948_EXT_SLV_SENS_DATA_00, 0x00, 9) press_data = raw_data[0]<<8 | raw_data[1] temp_data = raw_data[3]<<8 | raw_data[4] if (press_data > 0x7fff): press_data -= 65536 if (temp_data > 0x7fff): temp_data -= 65536 dpsf = float(raw_data[6]<<8 | raw_data[7]) # SDP3X sensor scaling factor obtained from byte 6 and 7 of read message return((press_data/dpsf), (temp_data/self.SDP3x_tsf)) def get_dp_spd(self): # function for computation of air-flow speed from diff. pressure in venturi tube (given diff. pressure, outer diameter, inner diameter and air density) dp = self.get_dp() a_outer = math.pi*(self.r_outer**2) a_inner = math.pi*(self.r_inner**2) ratio = a_outer/a_inner if dp < 0: spd = math.sqrt(((2*-dp)/((ratio**2-1)*self.air_density))) elif dp == 0: spd = 0 else: spd = -math.sqrt(((2*(dp)/((ratio**2-1)*self.air_density)))) # positive speed from negative pressure is due to backwards mounting of SDP3x sensor in venturi tube return(dp, spd) def get_mag_hdg(self): mag_raw = list(self.get_mag()) accel_raw = list(self.get_accel()) if accel_raw[2] < 0: # switch X and Z axis sign in case the sensor is turned upside down mag_raw[0] = - mag_raw[0] mag_raw[2] = - mag_raw[2] accel_raw[0] = - accel_raw[0] accel_raw[2] = - accel_raw[2] # Normalize accelerometer raw values. if(sum(accel_raw) == 0): acc_x_norm = 0 acc_y_norm = 0 else: acc_x_norm = accel_raw[0]/math.sqrt(accel_raw[0]**2 + accel_raw[1]**2 + accel_raw[2]**2) acc_y_norm = accel_raw[1]/math.sqrt(accel_raw[0]**2 + accel_raw[1]**2 + accel_raw[2]**2) # Calculate pitch and roll pitch = math.asin(acc_y_norm); if abs(pitch) == math.pi: roll = 0 else: if (-acc_x_norm/math.cos(pitch)) > 1: roll = math.pi elif (-acc_x_norm/math.cos(pitch)) < -1: roll = -math.pi else: roll = math.asin(-acc_x_norm/math.cos(pitch)) # Calculate the new tilt compensated values mag_x_comp = -mag_raw[1]*math.cos(pitch) + mag_raw[2]*math.sin(pitch); mag_y_comp = (mag_raw[1]*math.sin(roll)*math.sin(pitch) + mag_raw[0]*math.cos(roll) - mag_raw[2]*math.sin(roll)*math.cos(pitch)) if mag_x_comp != 0: mag_hdg_comp = math.atan2(-mag_y_comp, mag_x_comp)*(180/math.pi) + self.mag_declination else: if mag_y_comp < 0: mag_hdg_comp = -90 elif mag_y_comp > 0: mag_hdg_comp = +90 else: mag_hdg_comp = 0 if(mag_hdg_comp < 0): mag_hdg_comp += 360 return(mag_hdg_comp)
class WINDGAUGE03A(Device): def __init__(self, parent = None, address = 0x68, sdp3x_address = 0x21, **kwargs): pass def usr_bank_sel(self, usr_bank_reg): pass def write_icm20948_reg_data(self, reg_address, reg_usr_bank, value): pass def read_icm20948_reg_data(self, reg_address, reg_usr_bank, num_of_bytes): pass def reset (self): pass def initialize (self): pass def stop(self): pass def i2c_master_write (self, slv_id, slv_addr, data_out, slv_reg ): pass def i2c_master_read (self, slv_id, slv_addr, slv_rd_len, slv_reg ): pass def get_temp(self): pass def get_accel(self): pass def get_gyro(self): pass def get_mag_raw(self, *args): pass def get_mag_raw(self, *args): pass def calib_mag(self, calib_time): pass def get_dp(self): pass def get_temp(self): pass def get_t_dp(self): pass def get_dp_spd(self): pass def get_mag_hdg(self): pass
21
0
22
4
17
5
3
0.27
1
5
0
0
20
59
20
28
461
95
334
156
313
90
317
156
296
10
2
3
62
147,790
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/thermopile.py
pymlab.sensors.thermopile.THERMOPILE01
class THERMOPILE01(Device): def __init__(self, parent = None, address = 0x5A, **kwargs): Device.__init__(self, parent, address, **kwargs) # Function for changing communication address if device does not use default address # Warning, the device address can not be changed through CP2112 def setAddress(self, address): self.address = address; # Reading temperature of device case in Celsius def getTambient(self): return self.bus.read_word_data(self.address, 0x06) * 0.02 - 273.15; # Reading of temperature of distant object from zone 1 in Celsius def getTobject1(self): return self.bus.read_word_data(self.address, 0x07) * 0.02 - 273.15; # Reading of temperature of distant object from zone 2 in Celsius def getTobject2(self): return self.bus.read_word_data(self.address, 0x08) * 0.02 - 273.15;
class THERMOPILE01(Device): def __init__(self, parent = None, address = 0x5A, **kwargs): pass def setAddress(self, address): pass def getTambient(self): pass def getTobject1(self): pass def getTobject2(self): pass
6
0
2
0
2
0
1
0.45
1
0
0
0
5
1
5
13
21
5
11
7
5
5
11
7
5
1
2
0
5
147,791
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/thermopile.py
pymlab.sensors.thermopile.Overflow
class Overflow(object): def __repr__(self): return "OVERFLOW" def __str__(self): return repr(self)
class Overflow(object): def __repr__(self): pass def __str__(self): pass
3
0
2
0
2
0
1
0
1
0
0
0
2
0
2
2
6
1
5
3
2
0
5
3
2
1
1
0
2
147,792
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/sht.py
pymlab.sensors.sht.SHT31
class SHT31(Device): 'Python library for SHT31v01A MLAB module with Sensirion SHT31 i2c humidity and temperature sensor.' def __init__(self, parent = None, address = 0x44, **kwargs): Device.__init__(self, parent, address, **kwargs) self.SOFT_RESET = [0x30, 0xA2] self.STATUS_REG = [0xF3, 0x2D] self.MEASURE_H_CLKSD = [0x24, 0x00] def soft_reset(self): self.bus.write_i2c_block(self.address, self.SOFT_RESET); return def get_status(self): self.bus.write_i2c_block(self.address, self.STATUS_REG) status = self.bus.read_i2c_block(self.address, 3) bits_values = dict([('Invalid_checksum',status[0] & 0x01 == 0x01), ('Invalid_command',status[0] & 0x02 == 0x02), ('System_reset',status[0] & 0x10 == 0x10), ('T_alert',status[1] & 0x04 == 0x04), ('RH_alert',status[1] & 0x08 == 0x08), ('Heater',status[1] & 0x20 == 0x02), ('Alert_pending',status[1] & 0x80 == 0x80), ('Checksum',status[2])]) return bits_values def get_TempHum(self): self.bus.write_i2c_block(self.address, self.MEASURE_H_CLKSD); # start temperature and humidity measurement time.sleep(0.05) data = self.bus.read_i2c_block(self.address, 6) temp_data = data[0]<<8 | data[1] hum_data = data[3]<<8 | data[4] humidity = 100.0*(hum_data/65535.0) temperature = -45.0 + 175.0*(temp_data/65535.0) return temperature, humidity def get_temp(self): #TODO: cist mene i2c bloku ... self.bus.write_i2c_block(self.address, self.MEASURE_H_CLKSD); # start temperature and humidity measurement time.sleep(0.05) data = self.bus.read_i2c_block(self.address, 6) temp_data = data[0]<<8 | data[1] temperature = -45.0 + 175.0*(temp_data/65535.0) return temperature def get_humi(self): #TODO: cist mene i2c bloku ... self.bus.write_i2c_block(self.address, self.MEASURE_H_CLKSD); # start temperature and humidity measurement time.sleep(0.05) data = self.bus.read_i2c_block(self.address, 6) hum_data = data[3]<<8 | data[4] humidity = 100.0*(hum_data/65535.0) return humidity @staticmethod def _calculate_checksum(value): """4.12 Checksum Calculation from an unsigned short input""" # CRC polynomial = 0x131 # //P(x)=x^8+x^5+x^4+1 = 100110001 crc = 0xFF # calculates 8-Bit checksum with given polynomial for byteCtr in [ord(x) for x in struct.pack(">H", value)]: crc ^= byteCtr for bit in range(8, 0, -1): if crc & 0x80: crc = (crc << 1) ^ polynomial else: crc = (crc << 1) return crc
class SHT31(Device): '''Python library for SHT31v01A MLAB module with Sensirion SHT31 i2c humidity and temperature sensor.''' def __init__(self, parent = None, address = 0x44, **kwargs): pass def soft_reset(self): pass def get_status(self): pass def get_TempHum(self): pass def get_temp(self): pass def get_humi(self): pass @staticmethod def _calculate_checksum(value): '''4.12 Checksum Calculation from an unsigned short input''' pass
9
2
10
2
8
1
1
0.18
1
2
0
0
6
3
7
15
81
21
56
29
47
10
47
28
39
4
2
3
10
147,793
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/imu.py
pymlab.sensors.imu.IMU01_ACC
class IMU01_ACC(Device): """ MMA8451Q Accelerometer sensor binding """ def __init__(self, parent = None, address = 0x1C, sensitivity = 4.0, highres = True, **kwargs): Device.__init__(self, parent, address, **kwargs) self.MMA_845XQ_STATUS = 0x00 self.MMA_845XQ_OUT_X_MSB = 0x1 self.MMA_845XQ_OUT_Y_MSB = 0x3 self.MMA_845XQ_OUT_Z_MSB = 0x5 self.MMA_845XQ_CTRL_REG1 = 0x2A self.MMA_845XQ_CTRL_REG1_VALUE_ACTIVE = 0x01 self.MMA_845XQ_CTRL_REG1_VALUE_F_READ = 0x02 self.MMA_845XQ_CTRL_REG2 = 0x2B self.MMA_845XQ_CTRL_REG2_RESET = 0x40 self.MMA_845XQ_CTRL_REG3 = 0x2C self.MMA_845XQ_CTRL_REG4 = 0x2D self.MMA_845XQ_CTRL_REG5 = 0x2E self.MMA_845XQ_WHO_AM_I = 0x0D self.MMA_845XQ_PL_STATUS = 0x10 self.MMA_845XQ_PL_CFG = 0x11 self.MMA_845XQ_PL_EN = 0x40 self.MMA_845XQ_XYZ_DATA_CFG = 0x0E self.MMA_845XQ_2G_MODE = 0x00 # Set Sensitivity to 2g self.MMA_845XQ_4G_MODE = 0x01 # Set Sensitivity to 4g self.MMA_845XQ_8G_MODE = 0x02 # Set Sensitivity to 8g self.MMA_845XQ_FF_MT_CFG = 0x15 self.MMA_845XQ_FF_MT_CFG_ELE = 0x80 self.MMA_845XQ_FF_MT_CFG_OAE = 0x40 self.MMA_845XQ_FF_MT_SRC = 0x16 self.MMA_845XQ_FF_MT_SRC_EA = 0x80 self.MMA_845XQ_PULSE_CFG = 0x21 self.MMA_845XQ_PULSE_CFG_ELE = 0x80 self.MMA_845XQ_PULSE_SRC = 0x22 self.MMA_845XQ_PULSE_SRC_EA = 0x80 ## Interrupts # Auto SLEEP/WAKE interrupt self.INT_ASLP = (1<<7) # Transient interrupt self.INT_TRANS = (1<<5) # Orientation = (landscape/portrait) interrupt self.INT_LNDPRT = (1<<4) # Pulse detection interrupt self.INT_PULSE = (1<<3) # Freefall/Motion interrupt self.INT_FF_MT = (1<<2) # Data ready interrupt self.INT_DRDY = (1<<0) SCALES = { 2.0: self.MMA_845XQ_2G_MODE, 4.0: self.MMA_845XQ_4G_MODE, 8.0: self.MMA_845XQ_8G_MODE, } self._sensitivity = sensitivity self._highres = highres self._scale = SCALES[sensitivity] def standby(self): reg1 = self.bus.read_byte_data(self.address, self.MMA_845XQ_CTRL_REG1) # Set to status reg self.bus.write_byte_data(self.address, self.MMA_845XQ_CTRL_REG1, (reg1 & ~self.MMA_845XQ_CTRL_REG1_VALUE_ACTIVE)) def active(self): reg1 = self.bus.read_byte_data(self.address, self.MMA_845XQ_CTRL_REG1) # Set to status reg self.bus.write_byte_data(self.address, self.MMA_845XQ_CTRL_REG1, (reg1 | self.MMA_845XQ_CTRL_REG1_VALUE_ACTIVE | (0 if (self._highres == True) else self.MMA_845XQ_CTRL_REG1_VALUE_F_READ) )) def initialize(self): if self._scale == self.MMA_845XQ_2G_MODE: self.step_factor = (0.0039 if (self._highres == True) else 0.0156) # Base value at 2g setting elif self._scale == self.MMA_845XQ_4G_MODE: self.step_factor = 2*(0.0039 if (self._highres == True) else 0.0156) elif self._scale == self.MMA_845XQ_8G_MODE: self.step_factor = 4*(0.0039 if (self._highres == True) else 0.0156) else: LOGGER.error("Uknown sensitivity value",) whoami = self.bus.read_byte_data(self.address, self.MMA_845XQ_WHO_AM_I); # Get Who Am I from the device. # return value for MMA8543Q is 0x3A self.bus.write_byte_data(self.address, self.MMA_845XQ_CTRL_REG2, self.MMA_845XQ_CTRL_REG2_RESET) # Reset time.sleep(0.5) # Give it time to do the reset self.standby() self.bus.write_byte_data(self.address, self.MMA_845XQ_PL_CFG, (0x80 | self.MMA_845XQ_PL_EN)) # Set Portrait/Landscape mode self.bus.write_byte_data(self.address, self.MMA_845XQ_XYZ_DATA_CFG, self._scale) #setup sensitivity self.active() def getPLStatus(self): return self.bus.read_byte_data(self.address, self.MMA_845XQ_PL_STATUS) def getPulse(self): self.bus.write_byte_data(self.address, self.MMA_845XQ_PULSE_CFG, self.MMA_845XQ_PULSE_CFG_ELE) return (self.bus.read_byte_data(self.address, self.MMA_845XQ_PULSE_SRC) & self.MMA_845XQ_PULSE_SRC_EA) def axes(self): self._stat = self.bus.read_byte_data(self.address, self.MMA_845XQ_STATUS) # read status register, data registers follows. if(self._highres): x = self.bus.read_int16_data(self.address, self.MMA_845XQ_OUT_X_MSB) / 64.0 * self.step_factor y = self.bus.read_int16_data(self.address, self.MMA_845XQ_OUT_Y_MSB) / 64.0 * self.step_factor z = self.bus.read_int16_data(self.address, self.MMA_845XQ_OUT_Z_MSB) / 64.0 * self.step_factor else: x = self.bus.read_byte(self.address) * self.step_factor y = self.bus.read_byte(self.address) * self.step_factor z = self.bus.read_byte(self.address) * self.step_factor return (x,y,z) def setInterrupt(self, interrupt_type, pin, on): current_value = self.bus.read_byte_data(self.address, self.MMA_845XQ_CTRL_REG4) if (on == True): current_value |= interrupt_type else: current_value &= ~(interrupt_type) self.bus.write_byte_data(self.address, self.MMA_845XQ_CTRL_REG4, current_value); current_routing_value = self.bus.read_byte_data(self.address, self.MMA_845XQ_CTRL_REG5); if (pin == 1): current_routing_value &= ~(type); elif (pin == 2): current_routing_value |= type; else: LOGGER.error("Uknown interrupt pin",) self.bus.write_byte_data(self.address, self.MMA_845XQ_CTRL_REG5, current_routing_value) def disableAllInterrupts(self): self.bus.write_byte_data(self.address, self.MMA_845XQ_CTRL_REG4, 0)
class IMU01_ACC(Device): ''' MMA8451Q Accelerometer sensor binding ''' def __init__(self, parent = None, address = 0x1C, sensitivity = 4.0, highres = True, **kwargs): pass def standby(self): pass def active(self): pass def initialize(self): pass def getPLStatus(self): pass def getPulse(self): pass def axes(self): pass def setInterrupt(self, interrupt_type, pin, on): pass def disableAllInterrupts(self): pass
10
1
15
3
11
2
2
0.23
1
1
0
0
9
40
9
17
146
34
101
59
91
23
90
59
80
7
2
1
20
147,794
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/imu.py
pymlab.sensors.imu.ICM20948
class ICM20948(Device): # def __init__(self): def __init__(self, parent = None, address = 0x68, **kwargs): Device.__init__(self, parent, address, **kwargs) self.SDP33_i2c_address = 0x21 self.mag_i2c_address = 0x0C ## USER BANK 0 REGISTERS self.ICM20948_WHO_AM_I = 0x00 self.ICM20948_USER_CTRL = 0x03 self.ICM20948_LP_CONFIG = 0x05 self.ICM20948_PWR_MGMT_1 = 0x06 self.ICM20948_PWR_MGMT_2 = 0x07 self.ICM20948_INT_PIN_CFG = 0x0F self.ICM20948_INT_ENABLE = 0x10 self.ICM20948_I2C_MST_STATUS = 0x17 self.ICM20948_ACEL_XOUT_H = 0x2D self.ICM20948_ACEL_XOUT_L = 0x2E self.ICM20948_ACEL_YOUT_H = 0x2F self.ICM20948_ACEL_YOUT_L = 0x30 self.ICM20948_ACEL_ZOUT_H = 0x31 self.ICM20948_ACEL_XOUT_L = 0x32 self.ICM20948_GYRO_XOUT_H = 0x33 self.ICM20948_GYRO_XOUT_L = 0x34 self.ICM20948_GYRO_YOUT_H = 0x35 self.ICM20948_GYRO_YOUT_L = 0x36 self.ICM20948_GYRO_ZOUT_H = 0x37 self.ICM20948_GYRO_XOUT_L = 0x38 self.ICM20948_TEMP_OUT_H = 0x39 self.ICM20948_TEMP_OUT_L = 0x3A self.ICM20948_EXT_SLV_SENS_DATA_00 = 0x3B # USER BANK 2 REGISTERS self.ICM20948_GYRO_CONFIG = 0x01 self.ICM20948_ACEL_CONFIG = 0x14 ## USER BANK 3 REGISTERS self.ICM20948_I2C_SLV0_ADDR = 0x03 self.ICM20948_I2C_SLV0_REG = 0x04 # I2C slave 0 register address from where to begin data transfer. self.ICM20948_I2C_SLV0_CTRL = 0x05 self.ICM20948_I2C_SLV0_DO = 0x06 self.ICM20948_I2C_SLV1_ADDR = 0x07 self.ICM20948_I2C_SLV1_REG = 0x08 # I2C slave 1 register address from where to begin data transfer. self.ICM20948_I2C_SLV1_CTRL = 0x09 self.ICM20948_I2C_SLV1_DO = 0x0A ## USER BANK REGISTERS 0-3 self.ICM20948_REG_BANK_SEL = 0x7F # 0 def usr_bank_sel(self, usr_bank_reg): self.bus.write_byte_data(self.address, self.ICM20948_REG_BANK_SEL, usr_bank_reg << 4) def write_icm20948_reg_data(self, reg_address, reg_usr_bank, value): self.usr_bank_sel(reg_usr_bank) self.bus.write_byte_data(self.address, reg_address, value) def read_icm20948_reg_data(self, reg_address, reg_usr_bank, num_of_bytes): self.usr_bank_sel(reg_usr_bank) if num_of_bytes > 1: return(self.bus.read_i2c_block_data(self.address, reg_address, num_of_bytes)) else: return((self.bus.read_byte_data(self.address, reg_address))) def reset (self): self.write_icm20948_reg_data(self.ICM20948_PWR_MGMT_1, 0, 0x80) # reset device and register values time.sleep(1) def initialize (self): # self.write_icm20948_reg_data( self.ICM20948_REG_BANK_SEL, 0, 0x00) # select user register bank 0 # self.bus.write_byte_data(self.address, self.ICM20948_PWR_MGMT_2, 0x3f) # gyro and accel off # self.write_icm20948_reg_data(self.ICM20948_PWR_MGMT_2, 0, 0x00) # gyro and accel on # self.write_icm20948_reg_data(self.ICM20948_USER_CTRL, 0, 0x20) # I2C_MST_EN set to 1 # time.sleep(0.1) self.write_icm20948_reg_data(self.ICM20948_USER_CTRL, 0, 0x00) # I2C_MST_EN set to 0 # time.sleep(0.01) self.write_icm20948_reg_data(self.ICM20948_INT_PIN_CFG, 0, 0x02) # BYPASS ENABLE # time.sleep(0.1) # self.write_icm20948_reg_data(self.ICM20948_USER_CTRL, 0, 0x00) # I2C_MST_EN set to 0 # self.write_icm20948_reg_data(self.ICM20948_USER_CTRL, 0, 0x02) # I2C_MST_RST set to 1 (bit auto clears) # time.sleep(0.1) self.write_icm20948_reg_data(self.ICM20948_PWR_MGMT_1, 0, 0x01) # clear sleep bit and wake up device time.sleep(0.1) def i2c_master_init (self): # self.write_icm20948_reg_data(self.ICM20948_INT_ENABLE, 0, 0xFF) # enable i2c master interrupt to propagate to interrupt pin1 # self.write_icm20948_reg_data(self.ICM20948_USER_CTRL, 0, 0x02) # I2C_MST_RST # time.sleep(0.1) # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_CTRL, 3, 0x20) # When bit 5 set (0x20), the transaction does not write a register value, it will only read data, or write data # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_ADDR, 3, self.SDP33_i2c_address) # self.write_icm20948_reg_data(self.ICM20948_LP_CONFIG, 0, 0x00) #disable master's duty cycled mode self.write_icm20948_reg_data(self.ICM20948_USER_CTRL, 0, 0x20) # I2C_MST_EN set to 1 def i2c_master_write (self, command): # THIS WILL NOT WORK BECAUSE IMU'S MASTER CAPABILITY CAN'T WRITE 2 BYTE COMMAND (ONLY ONE BYTE) self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_ADDR, 3, self.SDP33_i2c_address) self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_DO, 3, command >> 8) self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_ADDR, 3, self.SDP33_i2c_address) self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_DO, 3, command & 0xFF) self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_ADDR, 3, self.SDP33_i2c_address) # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_CTRL, 3, 0x87) # print(self.read_icm20948_reg_data(self.ICM20948_I2C_SLV0_ADDR, 3, 1)) def i2c_master_sdp33_init(self): self.write_icm20948_reg_data(self.ICM20948_USER_CTRL, 0, 0x20) # I2C_MST_EN set to 1 # time.sleep(0.01) # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV1_DO, 3, 0x04) # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV1_REG, 3, 0x31) # adress of the slave register master will write to # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV1_ADDR, 3, 0x0C) # R/W bit MSB - write operation # time.sleep(gi) # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV1_CTRL, 3, 0xA9) # I2C_SLV1_EN, I2C_SLV1_REG_DIS, I2C_SLV1_LENG[3:0] # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV1_CTRL, 3, 0x00) # I2C_SLV0_DIS self.write_icm20948_reg_data(self.ICM20948_I2C_SLV1_ADDR, 3, 0xA1) # SPD3X i2c address =0x21 | R/W bit MSB - read (1) self.write_icm20948_reg_data(self.ICM20948_I2C_SLV1_CTRL, 3, 0xA9) # I2C_SLV1_EN, I2C_SLV1_REG_DIS, I2C_SLV1_LENG[3:0] time.sleep(0.1) # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV1_REG, 3, 0x00) # adress of the first slave register master will start reading from # print("reading", end = ' ') # print(self.read_icm20948_reg_data(self.ICM20948_I2C_SLV0_ADDR, 3, 1)) # time.sleep(gi) # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV1_CTRL, 3, 0x8f) def i2c_master_mag_init (self): # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_DO, 3, 0x01) # self.write_icm20948_reg_data(self.ICM20948_USER_CTRL, 0, 0x00) # I2C_MST_EN set to 0, I2C_MST_RST set to 1 # time.sleep(gi) self.write_icm20948_reg_data(self.ICM20948_USER_CTRL, 0, 0x20) # I2C_MST_EN set to 0, I2C_MST_RST set to 1 # time.sleep(gi) # self.write_icm20948_reg_data(self.ICM20948_USER_CTRL, 0, 0x02) # I2C_MST_EN set to 0, I2C_MST_RST set to 1 # time.sleep(0.1) ## MAGNETOMETER SOFT RESET # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_DO, 3, 0x01) # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_REG, 3, 0x32) # adress of the slave register master will write to # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_ADDR, 3, 0x0C) # R/W bit MSB - write operation # # time.sleep(gi) # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_CTRL, 3, 0x8a) # I2C_SLV0_EN, I2C_SLV0_REG_EN, I2C_SLV0_LENG[3:0] = 9 # self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_CTRL, 3, 0x00) # I2C_SLV0_DIS # time.sleep(gi) self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_DO, 3, 0x04) self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_REG, 3, 0x31) # adress of the slave register master will write to self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_ADDR, 3, 0x0C) # R/W bit MSB - write operation # time.sleep(gi) self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_CTRL, 3, 0x8a) # I2C_SLV0_EN, I2C_SLV0_REG_DIS, I2C_SLV0_LENG[3:0] = 9 self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_CTRL, 3, 0x00) # I2C_SLV0_DIS self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_ADDR, 3, 0x8C) # R/W bit MSB self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_REG, 3, 0x00) # adress of the first slave register master will start reading from # print("reading", end = ' ') # print(self.read_icm20948_reg_data(self.ICM20948_I2C_SLV0_ADDR, 3, 1)) # time.sleep(gi) self.write_icm20948_reg_data(self.ICM20948_I2C_SLV0_CTRL, 3, 0x8d) # I2C_SLV0_EN, I2C_SLV0_REG_EN, I2C_SLV0_LENG[3:0] = 9 # print(self.read_icm20948_reg_data(self.ICM20948_I2C_SLV0_ADDR, 3, 1)) # self.write_icm20948_reg_data(self.ICM20948_USER_CTRL, 0, 0x20) # I2C_MST_EN set to 1 time.sleep(0.1) # time.sleep(gi) def get_temp(self): RoomTemp_Offset = 21 Temp_Sensitivity = 333.87 temp_raw_data = self.read_icm20948_reg_data(self.ICM20948_TEMP_OUT_H, 0, 2) MSB = temp_raw_data[0] LSB = temp_raw_data[1] t = (MSB << 8) + LSB TEMP_degC = ((t - RoomTemp_Offset)/Temp_Sensitivity) + 21 return(TEMP_degC) def get_accel_x(self): Accel_Sensitivity = float((1 << (3 - (self.read_icm20948_reg_data(self.ICM20948_ACEL_CONFIG, 2, 1) & 0x6))) * 2048) accelX_raw_data = self.read_icm20948_reg_data(self.ICM20948_ACEL_XOUT_H, 0, 2) accelX = ((accelX_raw_data[0] << 8) + accelX_raw_data[1]) if accelX > 0x7fff: accelX -= 65536 return(accelX / Accel_Sensitivity) def get_accel_y(self): Accel_Sensitivity = float((1 << (3 - (self.read_icm20948_reg_data(self.ICM20948_ACEL_CONFIG, 2, 1) & 0x6))) * 2048) accelY_raw_data = self.read_icm20948_reg_data(self.ICM20948_ACEL_YOUT_H, 0, 2) accelY = ((accelY_raw_data[0] << 8) + accelY_raw_data[1]) if accelY > 0x7fff: accelY -= 65536 return(accelY / Accel_Sensitivity) def get_accel_z(self): Accel_Sensitivity = float((1 << (3 - (self.read_icm20948_reg_data(self.ICM20948_ACEL_CONFIG, 2, 1) & 0x6))) * 2048) accelZ_raw_data = self.read_icm20948_reg_data(self.ICM20948_ACEL_ZOUT_H, 0, 2) accelZ = ((accelZ_raw_data[0] << 8) + accelZ_raw_data[1]) if accelZ > 0x7fff: accelZ -= 65536 return(accelZ / Accel_Sensitivity) ## 131; 65.5; 32,8; 16,4 def get_gyro_x(self): Gyro_Sensitivity = float((1 << (3 - (self.read_icm20948_reg_data(self.ICM20948_GYRO_CONFIG, 2, 1) & 0x6))) * 16.4) gyroX_raw_data = self.read_icm20948_reg_data(self.ICM20948_GYRO_XOUT_H, 0, 2) gyroX = ((gyroX_raw_data[0] << 8) + gyroX_raw_data[1]) if gyroX > 0x7fff: gyroX -= 65536 return(gyroX / Gyro_Sensitivity) def get_gyro_y(self): Gyro_Sensitivity = float((1 << (3 - (self.read_icm20948_reg_data(self.ICM20948_GYRO_CONFIG, 2, 1) & 0x6))) * 16.4) gyroY_raw_data = self.read_icm20948_reg_data(self.ICM20948_GYRO_YOUT_H, 0, 2) gyroY = ((gyroY_raw_data[0] << 8) + gyroY_raw_data[1]) if gyroY > 0x7fff: gyroY -= 65536 return(gyroY / Gyro_Sensitivity) def get_gyro_z(self): Gyro_Sensitivity = float((1 << (3 - (self.read_icm20948_reg_data(self.ICM20948_GYRO_CONFIG, 2, 1) & 0x6))) * 16.4) gyroZ_raw_data = self.read_icm20948_reg_data(self.ICM20948_GYRO_ZOUT_H, 0, 2) gyroZ = ((gyroZ_raw_data[0] << 8) + gyroZ_raw_data[1]) if gyroZ > 0x7fff: gyroZ -= 65536 return(gyroZ / Gyro_Sensitivity) def SDP33_write (self, SDP33_i2c_address, command): self.bus.write_i2c_block_data(self.SDP33_i2c_address, command) def SDP33_read (self, SDP33_i2c_address, command): # write = i2c_msg.write(SDP33_i2c_address, command) # read = i2c_msg.read(SDP33_i2c_address, 9) # raw_data = bus2.i2c_rdwr(write, read) self.bus2.write_i2c_block_data(self, self.SDP33_i2c_address, 0, [0x36, 0x24]) raw_data = self.bus2.read_i2c_block_data(self, self.SDP33_i2c_address, 9) return(raw_data) def get_mag(self, cal_available): if (cal_available): cal_file = open("ICM20948_mag_cal.txt", "r") cal_consts = cal_file.readline().split(",") offset_x = float(cal_consts[0]) offset_y = float(cal_consts[1]) offset_z = float(cal_consts[2]) scale_x = float(cal_consts[3]) scale_y = float(cal_consts[4]) scale_z = float(cal_consts[5]) # print(str(offset_x)+"\n") # print(str(offset_y)+"\n") # print(str(offset_z)+"\n") # print(str(scale_x)+"\n") # print(str(scale_y)+"\n") # print(str(scale_z)+"\n") else: offset_x, offset_y, offset_z = 0, 0, 0 scale_x, scale_y, scale_z = 1, 1, 1 mag_raw_data = self.read_icm20948_reg_data(self.ICM20948_EXT_SLV_SENS_DATA_00, 0, 13) magX = (mag_raw_data[6] << 8) + mag_raw_data[5] magY = (mag_raw_data[8] << 8) + mag_raw_data[7] magZ = (mag_raw_data[10] << 8) + mag_raw_data[9] if magX > 0x7fff: magX -= 65536 if magY > 0x7fff: magY -= 65536 if magZ > 0x7fff: magZ -= 65536 mag_scf = 4912/32752.0 # print(magX) # print(((magX*mag_scf) - offset_x) * scale_x) return(((magX*mag_scf) - offset_x) * scale_x, ((magY*mag_scf) - offset_y) * scale_y, ((magZ*mag_scf) - offset_z)*scale_z) def calib_mag(self, calib_time): try: decision = False print("\nDo you wish to perform new magnetometer calibration? Old calibration data will be lost!") while not decision: start_cal = raw_input("[Y/N]\n") if (start_cal == 'N') or (start_cal == 'n'): print("\nCalibration canceled, no new calibration values saved.\n\n") sys.exit(1) elif (start_cal == 'Y') or (start_cal == 'y'): decision = True self.i2c_master_mag_init() delay = 5 print("\nStarting calibration in %d seconds with duration of %d seconds!\n" % (delay,calib_time)) time.sleep(1) for i in range(delay): print(str(delay-i)) time.sleep(1) print("Calibration has started!\n") t_end = time.time() + calib_time mag_x = [] mag_y = [] mag_z = [] while time.time() < t_end: mag_x_i, mag_y_i, mag_z_i = self.get_mag(False) mag_x.append(mag_x_i) mag_y.append(mag_y_i) mag_z.append(mag_z_i) print("%f,%f,%f\n" % (mag_x_i, mag_y_i, mag_z_i)) ### HARDIRON COMPAS COMPENSATION offset_x = (max(mag_x) + min(mag_x)) / 2 offset_y = (max(mag_y) + min(mag_y)) / 2 offset_z = (max(mag_z) + min(mag_z)) / 2 ### SOFTIRON COMPASS COMPENSATION avg_delta_x = (max(mag_x) - min(mag_x)) / 2 avg_delta_y = (max(mag_y) - min(mag_y)) / 2 avg_delta_z = (max(mag_z) - min(mag_z)) / 2 avg_delta = (avg_delta_x + avg_delta_y + avg_delta_z) / 3 scale_x = avg_delta / avg_delta_x scale_y = avg_delta / avg_delta_y scale_z = avg_delta / avg_delta_z # sys.stdout.write(str(offset_x)+"\n") # sys.stdout.write(str(offset_y)+"\n") # sys.stdout.write(str(offset_z)+"\n") # sys.stdout.write(str(scale_x)+"\n") # sys.stdout.write(str(scale_y)+"\n") # sys.stdout.write(str(scale_z)+"\n") decision = False print("\nFinished. Do you wish to save calibration data?") while not decision: start_cal = raw_input("[Y/N]\n") if (start_cal == 'N') or (start_cal == 'n'): print("\nCalibration canceled, no new calibration values saved.\n\n") sys.exit(1) elif (start_cal == 'Y') or (start_cal == 'y'): decision = True except KeyboardInterrupt: print("\nCalibration canceled, no new calibration values saved.\n\n") sys.exit(0) cal_file = open("ICM20948_mag_cal.txt", "w") cal_file.write("%f,%f,%f,%f,%f,%f" % (offset_x, offset_y, offset_z, scale_x, scale_y, scale_z)) cal_file.close() sys.stdout.write("Calibration successful!\n\n")
class ICM20948(Device): def __init__(self, parent = None, address = 0x68, **kwargs): pass def usr_bank_sel(self, usr_bank_reg): pass def write_icm20948_reg_data(self, reg_address, reg_usr_bank, value): pass def read_icm20948_reg_data(self, reg_address, reg_usr_bank, num_of_bytes): pass def reset (self): pass def initialize (self): pass def i2c_master_init (self): pass def i2c_master_write (self, command): pass def i2c_master_sdp33_init(self): pass def i2c_master_mag_init (self): pass def get_temp(self): pass def get_accel_x(self): pass def get_accel_y(self): pass def get_accel_z(self): pass def get_gyro_x(self): pass def get_gyro_y(self): pass def get_gyro_z(self): pass def SDP33_write (self, SDP33_i2c_address, command): pass def SDP33_read (self, SDP33_i2c_address, command): pass def get_mag(self, cal_available): pass def calib_mag(self, calib_time): pass
22
0
16
3
10
4
2
0.44
1
4
0
0
21
34
21
29
378
83
219
115
197
96
215
115
193
10
2
3
41
147,795
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/iic.py
pymlab.sensors.iic.RemoteDriver
class RemoteDriver(Driver): def __init__(self, host, remote_device): import sys hosts = host if isinstance(host, list) else [host] self.host = hosts[-1] if len(hosts) > 0 else "local" cmd = [arg for h in hosts for arg in ["ssh", h]] \ + ["python3", "-m", "pymlab.iic_server"] self.sp = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) self._remote_call('load_driver', remote_device) def close(self): self.sp.stdin.close() self.sp.wait() def _remote_call(self, method, *args): #line, errs = self.sp.communicate(repr((method,) + args) + '\n') self.sp.stdin.write(repr((method,) + args) + '\n') self.sp.stdin.flush() line = self.sp.stdout.readline().strip() try: reply = ast.literal_eval(line) assert isinstance(reply, dict) and 'good' in reply except Exception as e: raise RuntimeError('%s sent invalid reply %r' % (self.host, line)) if reply.get('good', False): return reply.get('result', None) else: raise RuntimeError('%s raised exception: %s' \ % (self.host, reply.get('exception', '<missing>'))) def write_byte(self, address, value): return self._remote_call('write_byte', address, value) def read_byte(self, address): return self._remote_call('read_byte', address) def write_byte_data(self, address, register, value): return self._remote_call('write_byte_data', address, register, value) def read_byte_data(self, address, register): return self._remote_call('read_byte_data', address, register) def write_word_data(self, address, register, value): return self._remote_call('write_word_data', address, register, value) def read_word_data(self, address, register): return self._remote_call('read_word_data', address, register) def write_block_data(self, address, register, value): return self._remote_call('write_block_data', address, register, value) def read_block_data(self, address, register): return self._remote_call('read_block_data', address, register) def scan_bus(self): return self._remote_call('scan_bus')
class RemoteDriver(Driver): def __init__(self, host, remote_device): pass def close(self): pass def _remote_call(self, method, *args): pass def write_byte(self, address, value): pass def read_byte(self, address): pass def write_byte_data(self, address, register, value): pass def read_byte_data(self, address, register): pass def write_word_data(self, address, register, value): pass def read_word_data(self, address, register): pass def write_block_data(self, address, register, value): pass def read_block_data(self, address, register): pass def scan_bus(self): pass
13
0
4
0
4
0
1
0.02
1
5
0
0
12
2
12
22
64
17
46
21
32
1
41
20
27
3
2
1
16
147,796
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/lioncell.py
pymlab.sensors.lioncell.LIONCELL
class LIONCELL(Device): """ Battery Guage binding """ def __init__(self, parent = None, address = 0x55, **kwargs): Device.__init__(self, parent, address, **kwargs) # reset def reset(self): self.bus.write_byte_data(self.address, 0x00, 0x01) self.bus.write_byte_data(self.address, 0x00, 0x41) # deg C def getTemp(self): return (self.bus.read_byte_data(self.address, 0x0C) + self.bus.read_byte_data(self.address, 0x0D) * 256) * 0.1 - 273.15 # mAh def getRemainingCapacity(self): return (self.bus.read_byte_data(self.address, 0x04) + self.bus.read_byte_data(self.address, 0x05) * 256) # mAh def FullChargeCapacity(self): return (self.bus.read_byte_data(self.address, 0x06) + self.bus.read_byte_data(self.address, 0x07) * 256) # mAh def NominalAvailableCapacity(self): return (self.bus.read_byte_data(self.address, 0x14) + self.bus.read_byte_data(self.address, 0x15) * 256) # mAh def FullAvailabeCapacity(self): return (self.bus.read_byte_data(self.address, 0x16) + self.bus.read_byte_data(self.address, 0x17) * 256) # 10 mWhr def AvailableEnergy(self): return (self.bus.read_byte_data(self.address, 0x24) + self.bus.read_byte_data(self.address, 0x25) * 256) # mAh def DesignCapacity(self): return (self.bus.read_byte_data(self.address, 0x3c) + self.bus.read_byte_data(self.address, 0x3d) * 256) # V def Voltage(self): return (self.bus.read_byte_data(self.address, 0x08) + self.bus.read_byte_data(self.address, 0x09) * 256) # % def StateOfCharge(self): """ % of Full Charge """ return (self.bus.read_byte_data(self.address, 0x02) + self.bus.read_byte_data(self.address, 0x03) * 256) # mA def AverageCurrent(self): I = (self.bus.read_byte_data(self.address, 0x0A) + self.bus.read_byte_data(self.address, 0x0B) * 256) if (I & 0x8000): return -0x10000 + I else: return I # S.N. def SerialNumber(self): return (self.bus.read_byte_data(self.address, 0x7E) + self.bus.read_byte_data(self.address, 0x7F) * 256) # Pack Configuration def PackConfiguration(self): return (self.bus.read_byte_data(self.address, 0x3A) + self.bus.read_byte_data(self.address, 0x3B) * 256) def Chemistry(self): ''' Get cells chemistry ''' length = self.bus.read_byte_data(self.address, 0x79) chem = [] for n in range(length): chem.append(self.bus.read_byte_data(self.address, 0x7A + n)) return chem # Read Flash Block # return 32 bytes plus checksum def ReadFlashBlock(self, fclass, fblock): ret = [] self.bus.write_byte_data(self.address, 0x61, 0x00) time.sleep(0.1) self.bus.write_byte_data(self.address, 0x3E, fclass) time.sleep(0.1) self.bus.write_byte_data(self.address, 0x3F, fblock) time.sleep(0.1) fsum = 0 for addr in range(0,32): tmp = self.bus.read_byte_data(self.address, 0x40+addr) ret.append(tmp) fsum = (fsum + tmp) % 256 ret.append(self.bus.read_byte_data(self.address, 0x60)) return ret # Write Byte to Flash def WriteFlashByte(self, fclass, fblock, foffset, fbyte): self.bus.write_byte_data(self.address, 0x61, 0x00) time.sleep(0.1) self.bus.write_byte_data(self.address, 0x3E, fclass) time.sleep(0.1) self.bus.write_byte_data(self.address, 0x3F, fblock) time.sleep(0.1) self.bus.write_byte_data(self.address, 0x40+foffset, fbyte) time.sleep(0.1) fsum = 0 for addr in range(0,32): if(addr != foffset): tmp = self.bus.read_byte_data(self.address, 0x40+addr) fsum = (fsum + tmp) % 256 fsum = (fsum + fbyte) % 256 fsum = 0xFF-fsum time.sleep(0.1) self.bus.write_byte_data(self.address, 0x60, fsum) time.sleep(1)
class LIONCELL(Device): ''' Battery Guage binding ''' def __init__(self, parent = None, address = 0x55, **kwargs): pass def reset(self): pass def getTemp(self): pass def getRemainingCapacity(self): pass def FullChargeCapacity(self): pass def NominalAvailableCapacity(self): pass def FullAvailabeCapacity(self): pass def AvailableEnergy(self): pass def DesignCapacity(self): pass def Voltage(self): pass def StateOfCharge(self): ''' % of Full Charge ''' pass def AverageCurrent(self): pass def SerialNumber(self): pass def PackConfiguration(self): pass def Chemistry(self): ''' Get cells chemistry ''' pass def ReadFlashBlock(self, fclass, fblock): pass def WriteFlashByte(self, fclass, fblock, foffset, fbyte): pass
18
3
4
0
4
0
1
0.28
1
1
0
0
17
0
17
25
115
20
74
29
56
21
73
29
55
3
2
2
22
147,797
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/lts.py
pymlab.sensors.lts.LTS01
class LTS01(Device): """ Example: .. code-block:: python # Python library for LTS01A MLAB module with MAX31725 i2c Local Temperature Sensor """ FAULTS = { 1: [0b00], 2: [0b01], 4: [0b10], 6: [0b11], } def __init__(self, parent = None, address = 0x48, fault_queue = 1, **kwargs): Device.__init__(self, parent, address, **kwargs) ## register definitions self.Reg_temp = 0x00 self.Reg_conf = 0x01 self.Reg_Thys = 0x02 self.Reg_Tos = 0x03 ## config parameters self.SHUTDOWN = (1 << 0) self.INTERRUPT_Mode = (1 << 1) self.COMPARATOR_Mode = (0 << 1) self.OS_POLARITY_1 = (1 << 2) self.OS_POLARITY_0 = (0 << 2) # self.FQ_num = (int(self.FAULTS[fault_queue]) << 3) self.FORMAT_2complement = (0 << 5) self.FORMAT_extended = (1 << 5) self.Timeout_on = (0 << 6) self.Timeout_off = (1 << 6) def initialize(self): setup = 0x00 self.bus.write_byte_data(self.address, self.Reg_conf, setup) LOGGER.debug("LTS sensor initialized. ",) return self.bus.read_byte_data(self.address,0x01); def get_temp(self): # self.bus.write_byte(self.address,0x00) temp = self.bus.read_int16_data(self.address, self.Reg_temp) / 256.0 #temperature calculation register_value * 0.00390625; (Sensor is a big-endian but SMBus is little-endian by default) return temp
class LTS01(Device): ''' Example: .. code-block:: python # Python library for LTS01A MLAB module with MAX31725 i2c Local Temperature Sensor ''' def __init__(self, parent = None, address = 0x48, fault_queue = 1, **kwargs): pass def initialize(self): pass def get_temp(self): pass
4
1
10
1
8
2
1
0.33
1
0
0
0
3
13
3
11
50
10
30
20
26
10
25
20
21
1
2
0
3
147,798
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/adc.py
pymlab.sensors.adc.BRIDGEADC01
class BRIDGEADC01(Device): """ Driver for the AD7730/AD7730L bridge ADC device. """ def __init__(self, parent = None, **kwargs): Device.__init__(self, parent, address, **kwargs) #AD7730 register address self.AD7730_COMM_REG =0b000 self.AD7730_STATUS_REG =0b000 self.AD7730_DATA_REG =0b001 self.AD7730_MODE_REG =0b010 self.AD7730_FILTER_REG =0b011 self.AD7730_DAC_REG =0b100 self.AD7730_OFFSET_REG =0b101 self.AD7730_GAIN_REG =0b110 self.AD7730_TEST_REG =0b111 # do not change state of this register def reset(self): spi.SPI_write(spi.I2CSPI_SS0, [0xFF]) # wrinting least 32 serial clock with 1 at data input resets the device. spi.SPI_write(spi.I2CSPI_SS0, [0xFF]) spi.SPI_write(spi.I2CSPI_SS0, [0xFF]) spi.SPI_write(spi.I2CSPI_SS0, [0xFF]) def single_write(self, register, value): comm_reg = 0b00000 << 3 + register spi.SPI_write(spi.I2CSPI_SS0, [comm_reg]) spi.SPI_write(spi.I2CSPI_SS0, [value]) def single_read(self, register, value): comm_reg = 0b00010 << 3 + register if register == self.AD7730_STATUS_REG: bytes_num = 1 elif register == self.AD7730_DATA_REG: bytes_num = 2 elif register == self.AD7730_MODE_REG: bytes_num = 2 elif register == self.AD7730_FILTER_REG: bytes_num = 3 elif register == self.AD7730_DAC_REG: bytes_num = 1 elif register == self.AD7730_OFFSET_REG: bytes_num = 3 elif register == self.AD7730_GAIN_REG: bytes_num = 3 elif register == self.AD7730_TEST_REG: bytes_num = 3 spi.SPI_write(spi.I2CSPI_SS0, [comm_reg]) return spi.SPI_write(spi.I2CSPI_SS0, bytes_num)
class BRIDGEADC01(Device): ''' Driver for the AD7730/AD7730L bridge ADC device. ''' def __init__(self, parent = None, **kwargs): pass def reset(self): pass def single_write(self, register, value): pass def single_read(self, register, value): pass
5
1
11
1
10
1
3
0.15
1
0
0
0
4
9
4
12
53
8
41
17
36
6
34
17
29
9
2
1
12
147,799
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/acount.py
pymlab.sensors.acount.ACOUNTER02
class ACOUNTER02(Device): """ Frequency counting device driver. It counts number of pulses received from oscillator between two 0.1PPS pulses from GPS receiver. """ def __init__(self, parent = None, address = 0x51, **kwargs): Device.__init__(self, parent, address, **kwargs) def read_count(self): # read atomic counter b0 = self.bus.read_byte_data(self.address, 0x00) b1 = self.bus.read_byte_data(self.address, 0x01) b2 = self.bus.read_byte_data(self.address, 0x02) b3 = self.bus.read_byte_data(self.address, 0x03) count = bytes(bytearray([b3, b2, b1, b0])) return struct.unpack(">L", count)[0] def get_freq(self): # get frequency from counter count = self.read_count() return (count/(10.0 - 100.0e-6)) #convert ~10s of pulse counting to frequency def set_GPS(self): # set GPS mode by GPS configuration sentence self.bus.write_byte_data(self.address, 0x00, 0) # write configuration byte to GPS configuration sentence # First byte of configuration sentence is length of sentence. # Maximal length of configuration sentence is 50 bytes. def conf_GPS(self,addr, byte): self.bus.write_byte_data(self.address, addr, byte)
class ACOUNTER02(Device): ''' Frequency counting device driver. It counts number of pulses received from oscillator between two 0.1PPS pulses from GPS receiver. ''' def __init__(self, parent = None, address = 0x51, **kwargs): pass def read_count(self): pass def get_freq(self): pass def set_GPS(self): pass def conf_GPS(self,addr, byte): pass
6
1
3
0
3
1
1
0.59
1
2
0
0
5
0
5
13
29
6
17
12
11
10
17
12
11
1
2
0
5
147,800
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/__init__.py
pymlab.sensors.Device
class Device(object): """Base class for all MLAB sensors. .. attribute:: channel I2C hub channel number to which the device is connected. Channels are numbered from 0 (on a 8 channel hub, the channels have numbers 0-7). This attribute has no meaning if the device isn't connected to a I2C hub (see :class:`pymlab.sensors.i2chub02.I2CHub`). """ def __init__(self, parent = None, address = 0x70, **kwargs): self.parent = parent self.address = address self.possible_addresses = kwargs.get("possible_addresses", []) self.channel = kwargs.get("channel", None) self.name = kwargs.get("name", None) self.routing_disabled = False def __repr__(self): if self.name is not None: return obj_repr(self, address = self.address, name = self.name) return obj_repr(self, address = self.address) @property def bus(self): if self.parent is None: return None if isinstance(self.parent, Bus): return self.parent return self.parent.bus def get_named_devices(self): if self.name is None: return {} return { self.name: self, } def route(self, child = None): if self.routing_disabled: return False if child is None: path = [] node = self while not isinstance(node, Bus): path.insert(0, node) node = node.parent path.insert(0, node) for i in range(len(path) - 1): node = path[i] child = path[i + 1] if not node.route(child): return False return True return False def initialize(self): """This method does nothing, it is meant to be overriden in derived classes. Also, this method is not meant to be called directly by the user, normally a call to :meth:`pymlab.sensors.Bus.initialize` should be used. Perform any initialization of the device that may require communication. This is meant to be done after the configuration has been set up (after instantiating :class:`pymlab.config.Config` and setting it up).""" pass def write_byte(self, value): return self.bus.write_byte(self.address, value) def read_byte(self): return self.bus.read_byte(self.address)
class Device(object): '''Base class for all MLAB sensors. .. attribute:: channel I2C hub channel number to which the device is connected. Channels are numbered from 0 (on a 8 channel hub, the channels have numbers 0-7). This attribute has no meaning if the device isn't connected to a I2C hub (see :class:`pymlab.sensors.i2chub02.I2CHub`). ''' def __init__(self, parent = None, address = 0x70, **kwargs): pass def __repr__(self): pass @property def bus(self): pass def get_named_devices(self): pass def route(self, child = None): pass def initialize(self): '''This method does nothing, it is meant to be overriden in derived classes. Also, this method is not meant to be called directly by the user, normally a call to :meth:`pymlab.sensors.Bus.initialize` should be used. Perform any initialization of the device that may require communication. This is meant to be done after the configuration has been set up (after instantiating :class:`pymlab.config.Config` and setting it up).''' pass def write_byte(self, value): pass def read_byte(self): pass
10
2
7
1
6
1
2
0.35
1
2
1
42
8
6
8
8
78
16
46
19
36
16
45
18
36
6
1
3
17
147,801
MLAB-project/pymlab
MLAB-project_pymlab/examples/I2CSPI_HBSTEP.py
I2CSPI_HBSTEP.axis
class axis: def __init__(self, SPI_CS, Direction, StepsPerUnit): ' One axis of robot ' self.CS = SPI_CS self.Dir = Direction self.SPU = StepsPerUnit self.Reset() def Reset(self): ' Reset Axis and set default parameters for H-bridge ' spi.SPI_write_byte(self.CS, 0xC0) # reset # spi.SPI_write_byte(self.CS, 0x14) # Stall Treshold setup # spi.SPI_write_byte(self.CS, 0xFF) # spi.SPI_write_byte(self.CS, 0x13) # Over Current Treshold setup # spi.SPI_write_byte(self.CS, 0xFF) spi.SPI_write_byte(self.CS, 0x15) # Full Step speed spi.SPI_write_byte(self.CS, 0xFF) spi.SPI_write_byte(self.CS, 0xFF) spi.SPI_write_byte(self.CS, 0x05) # ACC spi.SPI_write_byte(self.CS, 0x00) spi.SPI_write_byte(self.CS, 0x20) spi.SPI_write_byte(self.CS, 0x06) # DEC spi.SPI_write_byte(self.CS, 0x00) spi.SPI_write_byte(self.CS, 0x20) spi.SPI_write_byte(self.CS, 0x0A) # KVAL_RUN spi.SPI_write_byte(self.CS, 0xd0) spi.SPI_write_byte(self.CS, 0x0B) # KVAL_ACC spi.SPI_write_byte(self.CS, 0xd0) spi.SPI_write_byte(self.CS, 0x0C) # KVAL_DEC spi.SPI_write_byte(self.CS, 0xd0) spi.SPI_write_byte(self.CS, 0x16) # STEPPER spi.SPI_write_byte(self.CS, 0b00000000) spi.SPI_write_byte(self.CS, 0x18) # CONFIG spi.SPI_write_byte(self.CS, 0b00111000) spi.SPI_write_byte(self.CS, 0b00000000) def MaxSpeed(self, speed): ' Setup of maximum speed ' spi.SPI_write_byte(self.CS, 0x07) # Max Speed setup spi.SPI_write_byte(self.CS, 0x00) spi.SPI_write_byte(self.CS, speed) def ReleaseSW(self): ' Go away from Limit Switch ' while self.ReadStatusBit(2) == 1: # is Limit Switch ON ? spi.SPI_write_byte(self.CS, 0x92 | (~self.Dir & 1)) # release SW while self.IsBusy(): pass self.MoveWait(10) # move 10 units away def GoZero(self, speed): ' Go to Zero position ' self.ReleaseSW() spi.SPI_write_byte(self.CS, 0x82 | (self.Dir & 1)) # Go to Zero spi.SPI_write_byte(self.CS, 0x00) spi.SPI_write_byte(self.CS, speed) while self.IsBusy(): pass time.sleep(0.3) self.ReleaseSW() def Move(self, units): ' Move some distance units from current position ' steps = units * self.SPU # translate units to steps if steps > 0: # look for direction spi.SPI_write_byte(self.CS, 0x40 | (~self.Dir & 1)) else: spi.SPI_write_byte(self.CS, 0x40 | (self.Dir & 1)) steps = int(abs(steps)) spi.SPI_write_byte(self.CS, (steps >> 16) & 0xFF) spi.SPI_write_byte(self.CS, (steps >> 8) & 0xFF) spi.SPI_write_byte(self.CS, steps & 0xFF) def MoveWait(self, units): ' Move some distance units from current position and wait for execution ' self.Move(units) while self.IsBusy(): pass def Float(self): ' switch H-bridge to High impedance state ' spi.SPI_write_byte(self.CS, 0xA0) def ReadStatusBit(self, bit): ' Report given status bit ' spi.SPI_write_byte(self.CS, 0x39) # Read from address 0x19 (STATUS) spi.SPI_write_byte(self.CS, 0x00) data0 = spi.SPI_read_byte() # 1st byte spi.SPI_write_byte(self.CS, 0x00) data1 = spi.SPI_read_byte() # 2nd byte #print hex(data0), hex(data1) if bit > 7: # extract requested bit OutputBit = (data0 >> (bit - 8)) & 1 else: OutputBit = (data1 >> bit) & 1 return OutputBit def IsBusy(self): """ Return True if tehre are motion """ if self.ReadStatusBit(1) == 1: return False else: return True
class axis: def __init__(self, SPI_CS, Direction, StepsPerUnit): ''' One axis of robot ''' pass def Reset(self): ''' Reset Axis and set default parameters for H-bridge ''' pass def MaxSpeed(self, speed): ''' Setup of maximum speed ''' pass def ReleaseSW(self): ''' Go away from Limit Switch ''' pass def GoZero(self, speed): ''' Go to Zero position ''' pass def Move(self, units): ''' Move some distance units from current position ''' pass def MoveWait(self, units): ''' Move some distance units from current position and wait for execution ''' pass def Float(self): ''' switch H-bridge to High impedance state ''' pass def ReadStatusBit(self, bit): ''' Report given status bit ''' pass def IsBusy(self): ''' Return True if tehre are motion ''' pass
11
10
9
0
8
4
2
0.44
0
1
0
0
10
3
10
10
105
11
79
18
68
35
76
18
65
3
0
2
17
147,802
MLAB-project/pymlab
MLAB-project_pymlab/examples/I2CSPI_HBSTEP_interactive.py
I2CSPI_HBSTEP_interactive.axis
class axis: def __init__(self, SPI_CS, Direction, StepsPerUnit): ' One axis of robot ' self.CS = SPI_CS self.Dir = Direction self.SPU = StepsPerUnit self.Reset() def Reset(self): ' Reset Axis and set default parameters for H-bridge ' spi.SPI_write(self.CS, [0xC0, 0x60]) # reset # spi.SPI_write(self.CS, [0x14, 0x14]) # Stall Treshold setup # spi.SPI_write(self.CS, [0xFF, 0xFF]) # spi.SPI_write(self.CS, [0x13, 0x13]) # Over Current Treshold setup # spi.SPI_write(self.CS, [0xFF, 0xFF]) spi.SPI_write(self.CS, [0x15, 0xFF]) # Full Step speed spi.SPI_write(self.CS, [0xFF, 0xFF]) spi.SPI_write(self.CS, [0xFF, 0xFF]) spi.SPI_write(self.CS, [0x05, 0x05]) # ACC spi.SPI_write(self.CS, [0x01, 0x01]) spi.SPI_write(self.CS, [0xF5, 0xF5]) spi.SPI_write(self.CS, [0x06, 0x06]) # DEC spi.SPI_write(self.CS, [0x01, 0x01]) spi.SPI_write(self.CS, [0xF5, 0xF5]) spi.SPI_write(self.CS, [0x0A, 0x0A]) # KVAL_RUN spi.SPI_write(self.CS, [0x30, 0x10]) spi.SPI_write(self.CS, [0x0B, 0x0B]) # KVAL_ACC spi.SPI_write(self.CS, [0x30, 0x20]) spi.SPI_write(self.CS, [0x0C, 0x0C]) # KVAL_DEC spi.SPI_write(self.CS, [0x30, 0x20]) spi.SPI_write(self.CS, [0x18, 0x18]) # CONFIG spi.SPI_write(self.CS, [0b00111000, 0b00111000]) spi.SPI_write(self.CS, [0b00000000, 0b00000000]) def MaxSpeed(self, speed): ' Setup of maximum speed ' spi.SPI_write_byte(self.CS, 0x07) # Max Speed setup spi.SPI_write_byte(self.CS, 0x00) spi.SPI_write_byte(self.CS, speed) def ReleaseSW(self): ' Go away from Limit Switch ' while self.ReadStatusBit(2) == 1: # is Limit Switch ON ? spi.SPI_write_byte(self.CS, 0x92 | (~self.Dir & 1)) # release SW while self.IsBusy(): pass self.MoveWait(10) # move 10 units away def GoZero(self, speed): ' Go to Zero position ' self.ReleaseSW() spi.SPI_write_byte(self.CS, 0x82 | (self.Dir & 1)) # Go to Zero spi.SPI_write_byte(self.CS, 0x00) spi.SPI_write_byte(self.CS, speed) while self.IsBusy(): pass time.sleep(0.3) self.ReleaseSW() def Move(self, units): ' Move some distance units from current position ' steps = units * self.SPU # translate units to steps if steps > 0: # look for direction spi.SPI_write_byte(self.CS, 0x40 | (~self.Dir & 1)) else: spi.SPI_write_byte(self.CS, 0x40 | (self.Dir & 1)) steps = int(abs(steps)) spi.SPI_write_byte(self.CS, (steps >> 16) & 0xFF) spi.SPI_write_byte(self.CS, (steps >> 8) & 0xFF) spi.SPI_write_byte(self.CS, steps & 0xFF) def MoveWait(self, units): # Move some distance units from current position and wait for execution self.Move(units) while self.IsBusy(): pass def Float(self): ' switch H-bridge to High impedance state ' spi.SPI_write_byte(self.CS, 0xA0) def ReadStatusBit(self, bit): ' Report given status bit ' spi.SPI_write_byte(self.CS, 0x39) # Read from address 0x19 (STATUS) spi.SPI_write_byte(self.CS, 0x00) data0 = spi.SPI_read_byte() # 1st byte spi.SPI_write_byte(self.CS, 0x00) data1 = spi.SPI_read_byte() # 2nd byte # print hex(data0), hex(data1) if bit > 7: # extract requested bit OutputBit = (data0 >> (bit - 8)) & 1 else: OutputBit = (data1 >> bit) & 1 return OutputBit def IsBusy(self): """ Return True if tehre are motion """ if self.ReadStatusBit(1) == 1: return False else: return True
class axis: def __init__(self, SPI_CS, Direction, StepsPerUnit): ''' One axis of robot ''' pass def Reset(self): ''' Reset Axis and set default parameters for H-bridge ''' pass def MaxSpeed(self, speed): ''' Setup of maximum speed ''' pass def ReleaseSW(self): ''' Go away from Limit Switch ''' pass def GoZero(self, speed): ''' Go to Zero position ''' pass def Move(self, units): ''' Move some distance units from current position ''' pass def MoveWait(self, units): pass def Float(self): ''' switch H-bridge to High impedance state ''' pass def ReadStatusBit(self, bit): ''' Report given status bit ''' pass def IsBusy(self): ''' Return True if tehre are motion ''' pass
11
9
9
0
8
3
2
0.44
0
1
0
0
10
3
10
10
102
10
77
18
66
34
74
18
63
3
0
2
17
147,803
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/__init__.py
pymlab.sensors.Overflow
class Overflow(object): def __repr__(self): return "OVERFLOW" def __str__(self): return repr(self) def __add__(self, other): return self def __sub__(self, other): return self def __mul__(self, other): return self
class Overflow(object): def __repr__(self): pass def __str__(self): pass def __add__(self, other): pass def __sub__(self, other): pass def __mul__(self, other): pass
6
0
2
0
2
0
1
0
1
0
0
0
5
0
5
5
15
4
11
6
5
0
11
6
5
1
1
0
5
147,804
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/config.py
pymlab.config.Node
class Node(object): def __init__(self, config, address, name = None): self.config = config self.parent = None self.channel = None self.address = address self.name = name config.add_node(self) def __repr__(self): return utils.obj_repr(self, self.address, self.name) def __pprint__(self, printer, level = 0): printer.write("%s %d %s" % (type(self).__name__, self.address, self.name, ))
class Node(object): def __init__(self, config, address, name = None): pass def __repr__(self): pass def __pprint__(self, printer, level = 0): pass
4
0
4
0
4
0
1
0
1
1
0
0
3
5
3
3
15
3
12
9
8
0
12
9
8
1
1
0
3
147,805
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/config.py
pymlab.config.Config
class Config(object): """ Example: >>> cfg = Config() >>> cfg.load_python("config_file.py") Contents of `config_file.py`: .. code-block:: python root = mult( address = 0x70, name = "Multiplexer 1", children = { 0x01: mult( address = 0x72, name = "Multiplexer 2", children = { 0x01: sens( address = 0x68, name = "Sensor 2", ), }, ), 0x03: sens( address = 0x68, name = "Sensor 1", ), }, ) """ def __init__(self, **kwargs): self.drivers = {} self.i2c_config = {} self._bus = None self.init_drivers() self.config(**kwargs) @property def bus(self): if self._bus is None: self._bus = Bus(**self.i2c_config) return self._bus def init_drivers(self): from pymlab.sensors import lts, mag, sht, i2chub, altimet, acount, clkgen,\ imu, motor, atmega, gpio, bus_translators, light, thermopile,\ rps, adc, i2cpwm, i2cio, i2clcd, lioncell, rtc, lightning,\ windgauge, sdp3x self.drivers = { "i2chub": i2chub.I2CHub, "lts01": lts.LTS01, "mag01": mag.MAG01, "rps01": rps.RPS01, "imu01_acc": imu.IMU01_ACC, "imu01_gyro": imu.IMU01_GYRO, "mpu6050": imu.MPU6050, "ICM20948" : imu.ICM20948, "sht25": sht.SHT25, "sht31": sht.SHT31, "altimet01": altimet.ALTIMET01, "SDP600": altimet.SDP6XX, "SDP610": altimet.SDP6XX, "SDP33": altimet.SDP3X, "acount02": acount.ACOUNTER02, "motor01": motor.MOTOR01, "clkgen01": clkgen.CLKGEN01, "atmega": atmega.ATMEGA, "I2CIO_TCA9535": gpio.I2CIO_TCA9535, "DS4520": gpio.DS4520, "TCA6416A": gpio.TCA6416A, "USBI2C_gpio": gpio.USBI2C_GPIO, "i2cspi": bus_translators.I2CSPI, "isl01": light.ISL01, "isl03": light.ISL03, "lioncell": lioncell.LIONCELL, #LION1CELL and LION2CELL "thermopile01": thermopile.THERMOPILE01, "i2cadc01": adc.I2CADC01, "vcai2c01": adc.VCAI2C01, "LTC2453": adc.LTC2453, "LTC2487": adc.LTC2487, "i2cpwm": i2cpwm.I2CPWM, "i2cio": i2cio.I2CIO, "i2clcd": i2clcd.I2CLCD, "rtc01": rtc.RTC01, "PCA9635": gpio.PCA9635, "LIGHTNING01A": lightning.AS3935, "WINDGAUGE03A": windgauge.WINDGAUGE03A, "SDP3x": sdp3x.SDP3x } def get_device(self, name): return self.bus.get_device(name) def build_device(self, value, parent = None): if isinstance(value, list) or isinstance(value, tuple): if parent is None: result = Bus(**self.i2c_config) else: result = SimpleBus(parent) for child in value: result.add_child(self.build_device(child, result)) return result if isinstance(value, dict): if "type" not in value: raise ValueError("Device dictionary doesn't have a \"type\" item.") try: fn = self.drivers[value["type"]] except KeyError: raise ValueError("Unknown device type: {!r}".format(value["type"])) kwargs = dict(value) kwargs.pop("type") children = kwargs.pop("children", []) result = fn(**kwargs) for child in children: result.add_child(self.build_device(child, result)) return result if isinstance(value, Device): return value raise ValueError("Cannot create a device from: {!r}!".format(value)) def config(self, **kwargs): self.i2c_config = kwargs.get("i2c", {}) self._bus = self.build_device(kwargs.get("bus", [])) def load_python(self, source): local_vars = { "cfg": self, #"mult": self._mult, #"sens": self._sens, #"mult": Multiplexer, #"sens": Sensor, } exec(source, globals(), local_vars) #self.port = local_vars.get("port", self.port) self.i2c_config = local_vars.get("i2c", {}) bus = self.build_device(local_vars.get("bus", [])) if not isinstance(bus, Bus): LOGGER.warning( "Top-level device in the configuration is a " "%s and not a bus as expected. Use python list to " "denote a bus.", "None" if bus is None else type(bus).__name__) self._bus = bus def load_file(self, file_name): if file_name.endswith(".py"): with open(file_name, "r") as f: return self.load_python(f.read()) raise ValueError("Unknown file type: {!r}".format(file_name)) def initialize(self): self.bus.initialize() return self._bus
class Config(object): ''' Example: >>> cfg = Config() >>> cfg.load_python("config_file.py") Contents of `config_file.py`: .. code-block:: python root = mult( address = 0x70, name = "Multiplexer 1", children = { 0x01: mult( address = 0x72, name = "Multiplexer 2", children = { 0x01: sens( address = 0x68, name = "Sensor 2", ), }, ), 0x03: sens( address = 0x68, name = "Sensor 1", ), }, ) ''' def __init__(self, **kwargs): pass @property def bus(self): pass def init_drivers(self): pass def get_device(self, name): pass def build_device(self, value, parent = None): pass def config(self, **kwargs): pass def load_python(self, source): pass def load_file(self, file_name): pass def initialize(self): pass
11
1
14
2
12
1
2
0.3
1
46
40
0
9
3
9
9
172
29
111
26
96
33
60
21
49
9
1
2
21
147,806
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/__init__.py
pymlab.sensors.Bus
class Bus(SimpleBus): INT8 = struct.Struct(">b") INT16 = struct.Struct(">h") UINT16 = struct.Struct(">H") port = None def __init__(self, **kwargs): SimpleBus.__init__(self, None) self._driver = kwargs.pop("driver", None) self._driver_config = dict(kwargs) self._named_devices = None def __repr__(self): return obj_repr(self, port = self.port) @property def driver(self): if self._driver is None: self._driver = iic.load_driver(**self._driver_config) return self._driver def get_device(self, name): if self._named_devices is None: self._named_devices = self.get_named_devices() return self._named_devices[name] def write_byte(self, address, value): """Writes the byte to unaddressed register in a device. """ LOGGER.debug("Writing byte %s to device %s!", bin(value), hex(address)) return self.driver.write_byte(address, value) def read_byte(self, address): """Reads unadressed byte from a device. """ LOGGER.debug("Reading byte from device %s!", hex(address)) return self.driver.read_byte(address) def write_byte_data(self, address, register, value): """Write a byte value to a device's register. """ LOGGER.debug("Writing byte data %s to register %s on device %s", bin(value), hex(register), hex(address)) return self.driver.write_byte_data(address, register, value) def read_byte_data(self, address, register): data = self.driver.read_byte_data(address, register) LOGGER.debug("Reading byte %s from register %s in device %s", hex(data), hex(register), hex(address)) return data def write_word_data(self, address, register, value): """Write a 16-bit value to a device's register. """ LOGGER.debug("Writing byte data %s to register %s on device %s", bin(value), hex(register), hex(address)) return self.driver.write_word_data(address, register, value) def read_word_data(self, address, register): data = self.driver.read_word_data(address, register) LOGGER.debug("Reading word %s from register %s in device %s", hex(data), hex(register), hex(address)) return data def write_block_data(self, address, register, value): return self.driver.write_block_data(address, register, value) def read_block_data(self, address, register): LOGGER.debug("Reading SMBus data block %s from register %s in device %s",value, hex(register), hex(address)) return self.driver.read_block_data(address, register) def write_i2c_block_data(self, address, register, value): LOGGER.debug("Writing I2C data block %s from register %s in device %s",value, hex(register), hex(address)) return self.driver.write_i2c_block_data(address, register, value) def read_i2c_block_data(self, address, register, length = 1): data = self.driver.read_i2c_block_data(address, register, length) LOGGER.debug("Reading I2C data block %s from register %s in device %s", data, hex(register), hex(address)) return data def write_i2c_block(self, address, value): LOGGER.debug("Writing I2C data block %s to device %s",value, hex(address)) return self.driver.write_i2c_block(address, value) def read_i2c_block(self, address, length): data = self.driver.read_i2c_block(address, length) LOGGER.debug("Reading I2C data block %s from device %s", data, hex(address)) return data def write_int16(self, address, register, value): value = struct.unpack("<H", struct.pack(">H", value))[0] return self.driver.write_word_data(address, register, value) def read_int16(self, address): ## Reads int16 as two separate bytes, suppose autoincrement of internal register pointer in I2C device. MSB = self.driver.read_byte(address) LSB = self.driver.read_byte(address) data = bytes(bytearray([MSB, LSB])) LOGGER.debug("MSB %s and LSB %s from device %s was read", hex(MSB), hex(LSB), hex(address)) return self.INT16.unpack(data)[0] def read_int16_data(self, address, register): ## Must be checked, possible bug in byte manipulation (LTS01A sensor sometimes returns wrong values) data = struct.pack("<H",self.driver.read_word_data(address, register)) LOGGER.debug("MSB and LSB %r was read from device %s", data, hex(address)) return self.INT16.unpack(data)[0] def read_uint16(self, address): ## Reads uint16 as two separate bytes, suppose autoincrement of internal register pointer in I2C device. MSB = self.driver.read_byte(address) LSB = self.driver.read_byte(address) data = bytes(bytearray([MSB, LSB])) LOGGER.debug("Read MSB %s and LSB %s from device %s", hex(MSB), hex(LSB), hex(address)) return self.UINT16.unpack(data)[0] def read_uint16_data(self, address, register): ## Must be checked, possible bug in byte manipulation (LTS01A sensor sometimes returns wrong values) data = struct.pack("<H",self.driver.read_word_data(address, register)) return self.UINT16.unpack(data)[0] def get_driver(self): return self.driver.get_driver() def write_wdata(self, address, register, value): """Write a word (two bytes) value to a device's register. """ warnings.warn("write_wdata() is deprecated and will be removed in future versions replace with write_word_data()", DeprecationWarning) LOGGER.debug("Writing word data %s to register %s on device %s", bin(value), hex(register), hex(address)) return self.driver.write_word_data(address, register, value) def read_wdata(self, address, register): warnings.warn("read_wdata() is deprecated and will be removed in future versions replace with read_word_data()", DeprecationWarning) data = self.driver.read_word_data(address, register) return data
class Bus(SimpleBus): def __init__(self, **kwargs): pass def __repr__(self): pass @property def driver(self): pass def get_device(self, name): pass def write_byte(self, address, value): '''Writes the byte to unaddressed register in a device. ''' pass def read_byte(self, address): '''Reads unadressed byte from a device. ''' pass def write_byte_data(self, address, register, value): '''Write a byte value to a device's register. ''' pass def read_byte_data(self, address, register): pass def write_word_data(self, address, register, value): '''Write a 16-bit value to a device's register. ''' pass def read_word_data(self, address, register): pass def write_block_data(self, address, register, value): pass def read_block_data(self, address, register): pass def write_i2c_block_data(self, address, register, value): pass def read_i2c_block_data(self, address, register, length = 1): pass def write_i2c_block_data(self, address, register, value): pass def read_i2c_block_data(self, address, register, length = 1): pass def write_int16(self, address, register, value): pass def read_int16(self, address): pass def read_int16_data(self, address, register): pass def read_uint16(self, address): pass def read_uint16_data(self, address, register): pass def get_driver(self): pass def write_wdata(self, address, register, value): '''Write a word (two bytes) value to a device's register. ''' pass def read_wdata(self, address, register): pass
26
5
4
0
4
0
1
0.09
1
4
0
0
24
3
24
39
129
29
95
46
69
9
91
45
66
2
3
1
26
147,807
MLAB-project/pymlab
MLAB-project_pymlab/src/pymlab/sensors/__init__.py
pymlab.sensors.SimpleBus
class SimpleBus(Device): def __init__(self, parent, children = None, **kwargs): Device.__init__(self, parent, None, **kwargs) self.children = {} children = children or [] for child in children: self.children[child.address] = child def __iter__(self): return iter(self.children.values()) def __getitem__(self, key): return self.children[key] def get_named_devices(self): result = {} for child in self: result.update(child.get_named_devices()) return result def route(self, child = None): if self.routing_disabled: return False if child is None: return Device.route(self) if child.address not in self.children: return False return True def add_child(self, device): if device.address in self.children: raise Exception("") self.children[device.address] = device device.parent = self def initialize(self): """See :meth:`pymlab.sensors.Device.initialize` for more information. Calls `initialize()` on all devices connected to the bus. """ Device.initialize(self) for child in iter(self.children.values()): child.initialize()
class SimpleBus(Device): def __init__(self, parent, children = None, **kwargs): pass def __iter__(self): pass def __getitem__(self, key): pass def get_named_devices(self): pass def route(self, child = None): pass def add_child(self, device): pass def initialize(self): '''See :meth:`pymlab.sensors.Device.initialize` for more information. Calls `initialize()` on all devices connected to the bus. ''' pass
8
1
6
1
5
0
2
0.09
1
1
0
1
7
1
7
15
47
11
33
13
25
3
33
13
25
4
2
1
14
147,808
MSchnei/pyprf_feature
MSchnei_pyprf_feature/pyprf_feature/analysis/utils_general.py
pyprf_feature.analysis.utils_general.cls_set_config
class cls_set_config(object): """ Set config parameters from dictionary into local namespace. Parameters ---------- dicCnfg : dict Dictionary containing parameter names (as keys) and parameter values (as values). For example, `dicCnfg['varTr']` contains a float, such as `2.94`. """ def __init__(self, dicCnfg): """Set config parameters from dictionary into local namespace.""" self.__dict__.update(dicCnfg)
class cls_set_config(object): ''' Set config parameters from dictionary into local namespace. Parameters ---------- dicCnfg : dict Dictionary containing parameter names (as keys) and parameter values (as values). For example, `dicCnfg['varTr']` contains a float, such as `2.94`. ''' def __init__(self, dicCnfg): '''Set config parameters from dictionary into local namespace.''' pass
2
2
3
0
2
1
1
3.33
1
0
0
0
1
0
1
1
15
2
3
2
1
10
3
2
1
1
1
0
1
147,809
MSchnei/pyprf_feature
MSchnei_pyprf_feature/pyprf_feature/analysis/old/pRF_classTest.py
pRF_classTest.Fit
class Fit(object): def __init__(self, betaSw, varNumMtnDrctns, varNumVoxChnk): # get objects self.betaSw = betaSw self.varNumMtnDrctns = varNumMtnDrctns self.varNumVoxChnk = varNumVoxChnk # prepare array for best residuals self.vecBstRes = np.zeros(varNumVoxChnk, dtype='float32') self.vecBstRes[:] = np.inf if type(self.betaSw) is np.ndarray and betaSw.dtype == 'bool': self.aryEstimMtnCrvTrn = np.zeros((varNumVoxChnk, varNumMtnDrctns), dtype='float32') self.aryEstimMtnCrvTst = np.zeros((varNumVoxChnk, varNumMtnDrctns), dtype='float32') self.resTrn = np.zeros((varNumVoxChnk), dtype='float32') self.resTst = np.zeros((varNumVoxChnk), dtype='float32') self.aryErrorTrn = np.zeros((varNumVoxChnk), dtype='float32') self.aryErrorTst = np.zeros((varNumVoxChnk), dtype='float32') self.contrast = np.eye(varNumMtnDrctns) self.denomTrn = np.zeros((varNumVoxChnk, len(self.contrast)), dtype='float32') self.denomTst = np.zeros((varNumVoxChnk, len(self.contrast)), dtype='float32') else: self.aryEstimMtnCrv = np.zeros((varNumVoxChnk, varNumMtnDrctns), dtype='float32') def fit(self, aryDsgnTmp, aryFuncChnk, lgcTemp=slice(None)): aryTmpPrmEst, aryTmpRes = np.linalg.lstsq( aryDsgnTmp, aryFuncChnk[:, lgcTemp])[0:2] return aryTmpPrmEst.T, aryTmpRes def predict(self, aryDsgnTmp, betas, lgcTemp): # calculate prediction return np.dot(aryDsgnTmp, betas[lgcTemp, :].T) def tstFit(self, aryDsgnTmp, aryFuncChnk, lgcTemp=slice(None)): # get beta weights for axis of motion tuning curves betas = self.fit(aryDsgnTmp, aryFuncChnk, lgcTemp)[0].T # calculate prediction aryPredTc = self.predict(self, aryDsgnTmp, betas, lgcTemp) # Sum of squares: vecBstRes[lgcTemp] = np.sum((aryFuncChnk[:, lgcTemp] - aryPredTc) ** 2, axis=0)
class Fit(object): def __init__(self, betaSw, varNumMtnDrctns, varNumVoxChnk): pass def fit(self, aryDsgnTmp, aryFuncChnk, lgcTemp=slice(None)): pass def predict(self, aryDsgnTmp, betas, lgcTemp): pass def tstFit(self, aryDsgnTmp, aryFuncChnk, lgcTemp=slice(None)): pass
5
0
11
0
9
2
1
0.17
1
2
0
0
4
14
4
4
46
4
36
22
31
6
27
22
22
2
1
1
5
147,810
MaT1g3R/option
option/types_.py
option.types_.SupportsDunderLE
class SupportsDunderLE(Protocol): def __le__(self, __other: object) -> bool: ...
class SupportsDunderLE(Protocol): def __le__(self, __other: object) -> bool: pass
2
0
1
0
1
0
1
0
1
1
0
0
1
0
1
25
2
0
2
2
1
0
3
2
1
1
5
0
1
147,811
MaT1g3R/option
option/result.py
option.result.Result
class Result(Generic[T, E]): """ :class:`Result` is a type that either success (:meth:`Result.Ok`) or failure (:meth:`Result.Err`). To create an Ok value, use :meth:`Result.Ok` or :func:`Ok`. To create a Err value, use :meth:`Result.Err` or :func:`Err`. Calling the :class:`Result` constructor directly will raise a ``TypeError``. Examples: >>> Result.Ok(1) Ok(1) >>> Result.Err('Fail!') Err('Fail!') """ __slots__ = ('_val', '_is_ok', '_type') def __init__(self, val: Union[T, E], is_ok: bool, *, _force: bool = False) -> None: if not _force: raise TypeError( 'Cannot directly initialize, ' 'please use one of the factory functions instead.' ) self._val = val self._is_ok = is_ok self._type = type(self) @classmethod def Ok(cls, val: T) -> 'Result[T, Any]': """ Contains the success value. Args: val: The success value. Returns: The :class:`Result` containing the success value. Examples: >>> res = Result.Ok(1) >>> res Ok(1) >>> res.is_ok True """ return cls(val, True, _force=True) @classmethod def Err(cls, err: E) -> 'Result[Any, E]': """ Contains the error value. Args: err: The error value. Returns: The :class:`Result` containing the error value. Examples: >>> res = Result.Err('Oh No') >>> res Err('Oh No') >>> res.is_err True """ return cls(err, False, _force=True) def __bool__(self) -> bool: return self._is_ok @property def is_ok(self) -> bool: """ Returns `True` if the result is :meth:`Result.Ok`. Examples: >>> Ok(1).is_ok True >>> Err(1).is_ok False """ return self._is_ok @property def is_err(self) -> bool: """ Returns `True` if the result is :meth:`Result.Err`. Examples: >>> Ok(1).is_err False >>> Err(1).is_err True """ return not self._is_ok def ok(self) -> Option[T]: """ Converts from :class:`Result` [T, E] to :class:`option.option_.Option` [T]. Returns: :class:`Option` containing the success value if `self` is :meth:`Result.Ok`, otherwise :data:`option.option_.NONE`. Examples: >>> Ok(1).ok() Some(1) >>> Err(1).ok() NONE """ return Option.Some(self._val) if self._is_ok else NONE # type: ignore def err(self) -> Option[E]: """ Converts from :class:`Result` [T, E] to :class:`option.option_.Option` [E]. Returns: :class:`Option` containing the error value if `self` is :meth:`Result.Err`, otherwise :data:`option.option_.NONE`. Examples: >>> Ok(1).err() NONE >>> Err(1).err() Some(1) """ return NONE if self._is_ok else Option.Some(self._val) # type: ignore def map(self, op: Callable[[T], U]) -> 'Union[Result[U, E], Result[T, E]]': """ Applies a function to the contained :meth:`Result.Ok` value. Args: op: The function to apply to the :meth:`Result.Ok` value. Returns: A :class:`Result` with its success value as the function result if `self` is an :meth:`Result.Ok` value, otherwise returns `self`. Examples: >>> Ok(1).map(lambda x: x * 2) Ok(2) >>> Err(1).map(lambda x: x * 2) Err(1) """ return self._type.Ok(op(self._val)) if self._is_ok else self # type: ignore def flatmap(self, op: 'Callable[[T], Result[U, E]]') -> 'Result[U, E]': """ Applies a function to the contained :meth:`Result.Ok` value. This is different than :meth:`Result.map` because the function result is not wrapped in a new :class:`Result`. Args: op: The function to apply to the contained :meth:`Result.Ok` value. Returns: The result of the function if `self` is an :meth:`Result.Ok` value, otherwise returns `self`. Examples: >>> def sq(x): return Ok(x * x) >>> def err(x): return Err(x) >>> Ok(2).flatmap(sq).flatmap(sq) Ok(16) >>> Ok(2).flatmap(sq).flatmap(err) Err(4) >>> Ok(2).flatmap(err).flatmap(sq) Err(2) >>> Err(3).flatmap(sq).flatmap(sq) Err(3) """ return op(self._val) if self._is_ok else self # type: ignore def map_err(self, op: Callable[[E], F]) -> 'Union[Result[T, F], Result[T, E]]': """ Applies a function to the contained :meth:`Result.Err` value. Args: op: The function to apply to the :meth:`Result.Err` value. Returns: A :class:`Result` with its error value as the function result if `self` is a :meth:`Result.Err` value, otherwise returns `self`. Examples: >>> Ok(1).map_err(lambda x: x * 2) Ok(1) >>> Err(1).map_err(lambda x: x * 2) Err(2) """ return self if self._is_ok else self._type.Err(op(self._val)) # type: ignore def unwrap(self) -> T: """ Returns the success value in the :class:`Result`. Returns: The success value in the :class:`Result`. Raises: ``ValueError`` with the message provided by the error value if the :class:`Result` is a :meth:`Result.Err` value. Examples: >>> Ok(1).unwrap() 1 >>> try: ... Err(1).unwrap() ... except ValueError as e: ... print(e) 1 """ if self._is_ok: return self._val # type: ignore raise ValueError(self._val) def unwrap_or(self, optb: T) -> T: """ Returns the success value in the :class:`Result` or ``optb``. Args: optb: The default return value. Returns: The success value in the :class:`Result` if it is a :meth:`Result.Ok` value, otherwise ``optb``. Notes: If you wish to use a result of a function call as the default, it is recommnded to use :meth:`unwrap_or_else` instead. Examples: >>> Ok(1).unwrap_or(2) 1 >>> Err(1).unwrap_or(2) 2 """ return self._val if self._is_ok else optb # type: ignore def unwrap_or_else(self, op: Callable[[E], U]) -> Union[T, U]: """ Returns the sucess value in the :class:`Result` or computes a default from the error value. Args: op: The function to computes default with. Returns: The success value in the :class:`Result` if it is a :meth:`Result.Ok` value, otherwise ``op(E)``. Examples: >>> Ok(1).unwrap_or_else(lambda e: e * 10) 1 >>> Err(1).unwrap_or_else(lambda e: e * 10) 10 """ return self._val if self._is_ok else op(self._val) # type: ignore def expect(self, msg: object) -> T: """ Returns the success value in the :class:`Result` or raises a ``ValueError`` with a provided message. Args: msg: The error message. Returns: The success value in the :class:`Result` if it is a :meth:`Result.Ok` value. Raises: ``ValueError`` with ``msg`` as the message if the :class:`Result` is a :meth:`Result.Err` value. Examples: >>> Ok(1).expect('no') 1 >>> try: ... Err(1).expect('no') ... except ValueError as e: ... print(e) no """ if self._is_ok: return self._val # type: ignore raise ValueError(msg) def unwrap_err(self) -> E: """ Returns the error value in a :class:`Result`. Returns: The error value in the :class:`Result` if it is a :meth:`Result.Err` value. Raises: ``ValueError`` with the message provided by the success value if the :class:`Result` is a :meth:`Result.Ok` value. Examples: >>> try: ... Ok(1).unwrap_err() ... except ValueError as e: ... print(e) 1 >>> Err('Oh No').unwrap_err() 'Oh No' """ if self._is_ok: raise ValueError(self._val) return self._val # type: ignore def expect_err(self, msg: object) -> E: """ Returns the error value in a :class:`Result`, or raises a ``ValueError`` with the provided message. Args: msg: The error message. Returns: The error value in the :class:`Result` if it is a :meth:`Result.Err` value. Raises: ``ValueError`` with the message provided by ``msg`` if the :class:`Result` is a :meth:`Result.Ok` value. Examples: >>> try: ... Ok(1).expect_err('Oh No') ... except ValueError as e: ... print(e) Oh No >>> Err(1).expect_err('Yes') 1 """ if self._is_ok: raise ValueError(msg) return self._val # type: ignore def __repr__(self) -> str: return f'Ok({self._val!r})' if self._is_ok else f'Err({self._val!r})' def __hash__(self) -> int: return hash((self._type, self._is_ok, self._val)) def __eq__(self, other: object) -> bool: return (isinstance(other, self._type) and self._is_ok == other._is_ok and self._val == other._val) def __ne__(self, other: object) -> bool: return (not isinstance(other, self._type) or self._is_ok != other._is_ok or self._val != other._val) def __lt__(self: 'Result[SupportsDunderLT, SupportsDunderLT]', other: object) -> bool: if isinstance(other, self._type): if self._is_ok == other._is_ok: return self._val < other._val return self._is_ok return NotImplemented def __le__(self: 'Result[SupportsDunderLE, SupportsDunderLE]', other: object) -> bool: if isinstance(other, self._type): if self._is_ok == other._is_ok: return self._val <= other._val return self._is_ok return NotImplemented def __gt__(self: 'Result[SupportsDunderGT, SupportsDunderGT]', other: object) -> bool: if isinstance(other, self._type): if self._is_ok == other._is_ok: return self._val > other._val return other._is_ok return NotImplemented def __ge__(self: 'Result[SupportsDunderGE, SupportsDunderGE]', other: object) -> bool: if isinstance(other, self._type): if self._is_ok == other._is_ok: return self._val >= other._val return other._is_ok return NotImplemented
class Result(Generic[T, E]): ''' :class:`Result` is a type that either success (:meth:`Result.Ok`) or failure (:meth:`Result.Err`). To create an Ok value, use :meth:`Result.Ok` or :func:`Ok`. To create a Err value, use :meth:`Result.Err` or :func:`Err`. Calling the :class:`Result` constructor directly will raise a ``TypeError``. Examples: >>> Result.Ok(1) Ok(1) >>> Result.Err('Fail!') Err('Fail!') ''' def __init__(self, val: Union[T, E], is_ok: bool, *, _force: bool = False) -> None: pass @classmethod def Ok(cls, val: T) -> 'Result[T, Any]': ''' Contains the success value. Args: val: The success value. Returns: The :class:`Result` containing the success value. Examples: >>> res = Result.Ok(1) >>> res Ok(1) >>> res.is_ok True ''' pass @classmethod def Err(cls, err: E) -> 'Result[Any, E]': ''' Contains the error value. Args: err: The error value. Returns: The :class:`Result` containing the error value. Examples: >>> res = Result.Err('Oh No') >>> res Err('Oh No') >>> res.is_err True ''' pass def __bool__(self) -> bool: pass @property def is_ok(self) -> bool: ''' Returns `True` if the result is :meth:`Result.Ok`. Examples: >>> Ok(1).is_ok True >>> Err(1).is_ok False ''' pass @property def is_err(self) -> bool: ''' Returns `True` if the result is :meth:`Result.Err`. Examples: >>> Ok(1).is_err False >>> Err(1).is_err True ''' pass def ok(self) -> Option[T]: ''' Converts from :class:`Result` [T, E] to :class:`option.option_.Option` [T]. Returns: :class:`Option` containing the success value if `self` is :meth:`Result.Ok`, otherwise :data:`option.option_.NONE`. Examples: >>> Ok(1).ok() Some(1) >>> Err(1).ok() NONE ''' pass def err(self) -> Option[E]: ''' Converts from :class:`Result` [T, E] to :class:`option.option_.Option` [E]. Returns: :class:`Option` containing the error value if `self` is :meth:`Result.Err`, otherwise :data:`option.option_.NONE`. Examples: >>> Ok(1).err() NONE >>> Err(1).err() Some(1) ''' pass def map(self, op: Callable[[T], U]) -> 'Union[Result[U, E], Result[T, E]]': ''' Applies a function to the contained :meth:`Result.Ok` value. Args: op: The function to apply to the :meth:`Result.Ok` value. Returns: A :class:`Result` with its success value as the function result if `self` is an :meth:`Result.Ok` value, otherwise returns `self`. Examples: >>> Ok(1).map(lambda x: x * 2) Ok(2) >>> Err(1).map(lambda x: x * 2) Err(1) ''' pass def flatmap(self, op: 'Callable[[T], Result[U, E]]') -> 'Result[U, E]': ''' Applies a function to the contained :meth:`Result.Ok` value. This is different than :meth:`Result.map` because the function result is not wrapped in a new :class:`Result`. Args: op: The function to apply to the contained :meth:`Result.Ok` value. Returns: The result of the function if `self` is an :meth:`Result.Ok` value, otherwise returns `self`. Examples: >>> def sq(x): return Ok(x * x) >>> def err(x): return Err(x) >>> Ok(2).flatmap(sq).flatmap(sq) Ok(16) >>> Ok(2).flatmap(sq).flatmap(err) Err(4) >>> Ok(2).flatmap(err).flatmap(sq) Err(2) >>> Err(3).flatmap(sq).flatmap(sq) Err(3) ''' pass def map_err(self, op: Callable[[E], F]) -> 'Union[Result[T, F], Result[T, E]]': ''' Applies a function to the contained :meth:`Result.Err` value. Args: op: The function to apply to the :meth:`Result.Err` value. Returns: A :class:`Result` with its error value as the function result if `self` is a :meth:`Result.Err` value, otherwise returns `self`. Examples: >>> Ok(1).map_err(lambda x: x * 2) Ok(1) >>> Err(1).map_err(lambda x: x * 2) Err(2) ''' pass def unwrap(self) -> T: ''' Returns the success value in the :class:`Result`. Returns: The success value in the :class:`Result`. Raises: ``ValueError`` with the message provided by the error value if the :class:`Result` is a :meth:`Result.Err` value. Examples: >>> Ok(1).unwrap() 1 >>> try: ... Err(1).unwrap() ... except ValueError as e: ... print(e) 1 ''' pass def unwrap_or(self, optb: T) -> T: ''' Returns the success value in the :class:`Result` or ``optb``. Args: optb: The default return value. Returns: The success value in the :class:`Result` if it is a :meth:`Result.Ok` value, otherwise ``optb``. Notes: If you wish to use a result of a function call as the default, it is recommnded to use :meth:`unwrap_or_else` instead. Examples: >>> Ok(1).unwrap_or(2) 1 >>> Err(1).unwrap_or(2) 2 ''' pass def unwrap_or_else(self, op: Callable[[E], U]) -> Union[T, U]: ''' Returns the sucess value in the :class:`Result` or computes a default from the error value. Args: op: The function to computes default with. Returns: The success value in the :class:`Result` if it is a :meth:`Result.Ok` value, otherwise ``op(E)``. Examples: >>> Ok(1).unwrap_or_else(lambda e: e * 10) 1 >>> Err(1).unwrap_or_else(lambda e: e * 10) 10 ''' pass def expect(self, msg: object) -> T: ''' Returns the success value in the :class:`Result` or raises a ``ValueError`` with a provided message. Args: msg: The error message. Returns: The success value in the :class:`Result` if it is a :meth:`Result.Ok` value. Raises: ``ValueError`` with ``msg`` as the message if the :class:`Result` is a :meth:`Result.Err` value. Examples: >>> Ok(1).expect('no') 1 >>> try: ... Err(1).expect('no') ... except ValueError as e: ... print(e) no ''' pass def unwrap_err(self) -> E: ''' Returns the error value in a :class:`Result`. Returns: The error value in the :class:`Result` if it is a :meth:`Result.Err` value. Raises: ``ValueError`` with the message provided by the success value if the :class:`Result` is a :meth:`Result.Ok` value. Examples: >>> try: ... Ok(1).unwrap_err() ... except ValueError as e: ... print(e) 1 >>> Err('Oh No').unwrap_err() 'Oh No' ''' pass def expect_err(self, msg: object) -> E: ''' Returns the error value in a :class:`Result`, or raises a ``ValueError`` with the provided message. Args: msg: The error message. Returns: The error value in the :class:`Result` if it is a :meth:`Result.Err` value. Raises: ``ValueError`` with the message provided by ``msg`` if the :class:`Result` is a :meth:`Result.Ok` value. Examples: >>> try: ... Ok(1).expect_err('Oh No') ... except ValueError as e: ... print(e) Oh No >>> Err(1).expect_err('Yes') 1 ''' pass def __repr__(self) -> str: pass def __hash__(self) -> int: pass def __eq__(self, other: object) -> bool: pass def __ne__(self, other: object) -> bool: pass def __lt__(self: 'Result[SupportsDunderLT, SupportsDunderLT]', other: object) -> bool: pass def __le__(self: 'Result[SupportsDunderLE, SupportsDunderLE]', other: object) -> bool: pass def __gt__(self: 'Result[SupportsDunderGT, SupportsDunderGT]', other: object) -> bool: pass def __ge__(self: 'Result[SupportsDunderGE, SupportsDunderGE]', other: object) -> bool: pass
30
16
14
2
3
9
2
2.63
1
8
1
0
23
3
25
27
391
72
91
34
61
239
80
30
54
3
1
2
46
147,812
MaT1g3R/option
option/types_.py
option.types_.SupportsDunderLT
class SupportsDunderLT(Protocol): def __lt__(self, __other: object) -> bool: ...
class SupportsDunderLT(Protocol): def __lt__(self, __other: object) -> bool: pass
2
0
1
0
1
0
1
0
1
1
0
0
1
0
1
25
2
0
2
2
1
0
3
2
1
1
5
0
1
147,813
MaT1g3R/option
option/types_.py
option.types_.SupportsDunderGT
class SupportsDunderGT(Protocol): def __gt__(self, __other: object) -> bool: ...
class SupportsDunderGT(Protocol): def __gt__(self, __other: object) -> bool: pass
2
0
1
0
1
0
1
0
1
1
0
0
1
0
1
25
2
0
2
2
1
0
3
2
1
1
5
0
1
147,814
MaT1g3R/option
option/types_.py
option.types_.SupportsDunderGE
class SupportsDunderGE(Protocol): def __ge__(self, __other: object) -> bool: ...
class SupportsDunderGE(Protocol): def __ge__(self, __other: object) -> bool: pass
2
0
1
0
1
0
1
0
1
1
0
0
1
0
1
25
2
0
2
2
1
0
3
2
1
1
5
0
1
147,815
MaT1g3R/option
option/option_.py
option.option_.Option
class Option(Generic[T]): """ :py:class:`Option` represents an optional value. Every :py:class:`Option` is either ``Some`` and contains a value, or :py:data:`NONE` and does not. To create a ``Some`` value, please use :py:meth:`Option.Some` or :py:func:`Some`. To create a :py:data:`NONE` value, please use :py:meth:`Option.NONE` or import the constant :py:data:`NONE` directly. To let :py:class:`Option` guess the type of :py:class:`Option` to create, please use :py:meth:`Option.maybe` or :py:func:`maybe`. Calling the ``__init__`` method directly will raise a ``TypeError``. Examples: >>> Option.Some(1) Some(1) >>> Option.NONE() NONE >>> Option.maybe(1) Some(1) >>> Option.maybe(None) NONE """ __slots__ = ('_val', '_is_some', '_type') def __init__(self, value: T, is_some: bool, *, _force: bool = False) -> None: if not _force: raise TypeError( 'Cannot directly initialize, ' 'please use one of the factory functions instead.' ) self._val = value self._is_some = is_some self._type = type(self) @classmethod def Some(cls, val: T) -> 'Option[T]': """Some value ``val``.""" return cls(val, True, _force=True) @classmethod def NONE(cls) -> 'Option[T]': """No Value.""" return NONE # type: ignore @classmethod def maybe(cls, val: Optional[T]) -> 'Option[T]': """ Shortcut method to return ``Some`` or :py:data:`NONE` based on ``val``. Args: val: Some value. Returns: ``Some(val)`` if the ``val`` is not None, otherwise :py:data:`NONE`. Examples: >>> Option.maybe(0) Some(0) >>> Option.maybe(None) NONE """ return NONE if val is None else cls.Some(val) # type: ignore def __bool__(self) -> bool: """ Returns the truth value of the :py:class:`Option` based on its value. Returns: True if the :py:class:`Option` is ``Some`` value, otherwise False. Examples: >>> bool(Some(False)) True >>> bool(NONE) False """ return self._is_some @property def is_some(self) -> bool: """ Returns ``True`` if the option is a ``Some`` value. Examples: >>> Some(0).is_some True >>> NONE.is_some False """ return self._is_some @property def is_none(self) -> bool: """ Returns ``True`` if the option is a :py:data:`NONE` value. Examples: >>> Some(0).is_none False >>> NONE.is_none True """ return not self._is_some def expect(self, msg: object) -> T: """ Unwraps the option. Raises an exception if the value is :py:data:`NONE`. Args: msg: The exception message. Returns: The wrapped value. Raises: ``ValueError`` with message provided by ``msg`` if the value is :py:data:`NONE`. Examples: >>> Some(0).expect('sd') 0 >>> try: ... NONE.expect('Oh No!') ... except ValueError as e: ... print(e) Oh No! """ if self._is_some: return self._val raise ValueError(msg) def unwrap(self) -> T: """ Returns the value in the :py:class:`Option` if it is ``Some``. Returns: The ```Some`` value of the :py:class:`Option`. Raises: ``ValueError`` if the value is :py:data:`NONE`. Examples: >>> Some(0).unwrap() 0 >>> try: ... NONE.unwrap() ... except ValueError as e: ... print(e) Value is NONE. """ return self.value @property def value(self) -> T: """Property version of :py:meth:`unwrap`.""" if self._is_some: return self._val raise ValueError('Value is NONE.') def unwrap_or(self, default: U) -> Union[T, U]: """ Returns the contained value or ``default``. Args: default: The default value. Returns: The contained value if the :py:class:`Option` is ``Some``, otherwise ``default``. Notes: If you wish to use a result of a function call as the default, it is recommnded to use :py:meth:`unwrap_or_else` instead. Examples: >>> Some(0).unwrap_or(3) 0 >>> NONE.unwrap_or(0) 0 """ return self.unwrap_or_else(lambda: default) def unwrap_or_else(self, callback: Callable[[], U]) -> Union[T, U]: """ Returns the contained value or computes it from ``callback``. Args: callback: The the default callback. Returns: The contained value if the :py:class:`Option` is ``Some``, otherwise ``callback()``. Examples: >>> Some(0).unwrap_or_else(lambda: 111) 0 >>> NONE.unwrap_or_else(lambda: 'ha') 'ha' """ return self._val if self._is_some else callback() def map(self, callback: Callable[[T], U]) -> 'Option[U]': """ Applies the ``callback`` with the contained value as its argument or returns :py:data:`NONE`. Args: callback: The callback to apply to the contained value. Returns: The ``callback`` result wrapped in an :class:`Option` if the contained value is ``Some``, otherwise :py:data:`NONE` Examples: >>> Some(10).map(lambda x: x * x) Some(100) >>> NONE.map(lambda x: x * x) NONE """ return self._type.Some(callback(self._val)) if self._is_some else NONE # type: ignore def map_or(self, callback: Callable[[T], U], default: A) -> Union[U, A]: """ Applies the ``callback`` to the contained value or returns ``default``. Args: callback: The callback to apply to the contained value. default: The default value. Returns: The ``callback`` result if the contained value is ``Some``, otherwise ``default``. Notes: If you wish to use the result of a function call as ``default``, it is recommended to use :py:meth:`map_or_else` instead. Examples: >>> Some(0).map_or(lambda x: x + 1, 1000) 1 >>> NONE.map_or(lambda x: x * x, 1) 1 """ return callback(self._val) if self._is_some else default def map_or_else(self, callback: Callable[[T], U], default: Callable[[], A]) -> Union[U, A]: """ Applies the ``callback`` to the contained value or computes a default with ``default``. Args: callback: The callback to apply to the contained value. default: The callback fot the default value. Returns: The ``callback`` result if the contained value is ``Some``, otherwise the result of ``default``. Examples: >>> Some(0).map_or_else(lambda x: x * x, lambda: 1) 0 >>> NONE.map_or_else(lambda x: x * x, lambda: 1) 1 """ return callback(self._val) if self._is_some else default() def flatmap(self, callback: 'Callable[[T], Option[U]]') -> 'Option[U]': """ Applies the callback to the contained value if the option is not :py:data:`NONE`. This is different than :py:meth:`Option.map` because the result of the callback isn't wrapped in a new :py:class:`Option` Args: callback: The callback to apply to the contained value. Returns: :py:data:`NONE` if the option is :py:data:`NONE`. otherwise calls `callback` with the contained value and returns the result. Examples: >>> def square(x): return Some(x * x) >>> def nope(x): return NONE >>> Some(2).flatmap(square).flatmap(square) Some(16) >>> Some(2).flatmap(square).flatmap(nope) NONE >>> Some(2).flatmap(nope).flatmap(square) NONE >>> NONE.flatmap(square).flatmap(square) NONE """ return callback(self._val) if self._is_some else NONE # type: ignore def filter(self, predicate: Callable[[T], bool]) -> 'Option[T]': """ Returns :py:data:`NONE` if the :py:class:`Option` is :py:data:`NONE`, otherwise filter the contained value by ``predicate``. Args: predicate: The fitler function. Returns: :py:data:`NONE` if the contained value is :py:data:`NONE`, otherwise: * The option itself if the predicate returns True * :py:data:`NONE` if the predicate returns False Examples: >>> Some(0).filter(lambda x: x % 2 == 1) NONE >>> Some(1).filter(lambda x: x % 2 == 1) Some(1) >>> NONE.filter(lambda x: True) NONE """ if self._is_some and predicate(self._val): return self return NONE # type: ignore def get( self: 'Option[Mapping[K,V]]', key: K, default: Union[V, None] = None ) -> 'Option[V]': """ Gets a mapping value by key in the contained value or returns ``default`` if the key doesn't exist. Args: key: The mapping key. default: The defauilt value. Returns: * ``Some`` variant of the mapping value if the key exists and the value is not None. * ``Some(default)`` if ``default`` is not None. * :py:data:`NONE` if ``default`` is None. Examples: >>> Some({'hi': 1}).get('hi') Some(1) >>> Some({}).get('hi', 12) Some(12) >>> NONE.get('hi', 12) Some(12) >>> NONE.get('hi') NONE """ if self._is_some: return self._type.maybe(self._val.get(key, default)) # type: ignore return self._type.maybe(default) # type: ignore def __hash__(self) -> int: return hash((self.__class__, self._is_some, self._val)) def __eq__(self, other: object) -> bool: return (isinstance(other, self._type) and self._is_some == other._is_some and self._val == other._val) def __ne__(self, other: object) -> bool: return (not isinstance(other, self._type) or self._is_some != other._is_some or self._val != other._val) def __lt__(self: 'Option[SupportsDunderLT]', other: object) -> bool: if isinstance(other, self._type): if self._is_some == other._is_some: return self._val < other._val if self._is_some else False else: return other._is_some return NotImplemented def __le__(self: 'Option[SupportsDunderLE]', other: object) -> bool: if isinstance(other, self._type): if self._is_some == other._is_some: return self._val <= other._val if self._is_some else True return other._is_some return NotImplemented def __gt__(self: 'Option[SupportsDunderGT]', other: object) -> bool: if isinstance(other, self._type): if self._is_some == other._is_some: return self._val > other._val if self._is_some else False else: return self._is_some return NotImplemented def __ge__(self: 'Option[SupportsDunderGE]', other: object) -> bool: if isinstance(other, self._type): if self._is_some == other._is_some: return self._val >= other._val if self._is_some else True return self._is_some return NotImplemented def __repr__(self) -> str: return 'NONE' if self.is_none else f'Some({self._val!r})'
class Option(Generic[T]): ''' :py:class:`Option` represents an optional value. Every :py:class:`Option` is either ``Some`` and contains a value, or :py:data:`NONE` and does not. To create a ``Some`` value, please use :py:meth:`Option.Some` or :py:func:`Some`. To create a :py:data:`NONE` value, please use :py:meth:`Option.NONE` or import the constant :py:data:`NONE` directly. To let :py:class:`Option` guess the type of :py:class:`Option` to create, please use :py:meth:`Option.maybe` or :py:func:`maybe`. Calling the ``__init__`` method directly will raise a ``TypeError``. Examples: >>> Option.Some(1) Some(1) >>> Option.NONE() NONE >>> Option.maybe(1) Some(1) >>> Option.maybe(None) NONE ''' def __init__(self, value: T, is_some: bool, *, _force: bool = False) -> None: pass @classmethod def Some(cls, val: T) -> 'Option[T]': '''Some value ``val``.''' pass @classmethod def NONE(cls) -> 'Option[T]': '''No Value.''' pass @classmethod def maybe(cls, val: Optional[T]) -> 'Option[T]': ''' Shortcut method to return ``Some`` or :py:data:`NONE` based on ``val``. Args: val: Some value. Returns: ``Some(val)`` if the ``val`` is not None, otherwise :py:data:`NONE`. Examples: >>> Option.maybe(0) Some(0) >>> Option.maybe(None) NONE ''' pass def __bool__(self) -> bool: ''' Returns the truth value of the :py:class:`Option` based on its value. Returns: True if the :py:class:`Option` is ``Some`` value, otherwise False. Examples: >>> bool(Some(False)) True >>> bool(NONE) False ''' pass @property def is_some(self) -> bool: ''' Returns ``True`` if the option is a ``Some`` value. Examples: >>> Some(0).is_some True >>> NONE.is_some False ''' pass @property def is_none(self) -> bool: ''' Returns ``True`` if the option is a :py:data:`NONE` value. Examples: >>> Some(0).is_none False >>> NONE.is_none True ''' pass def expect(self, msg: object) -> T: ''' Unwraps the option. Raises an exception if the value is :py:data:`NONE`. Args: msg: The exception message. Returns: The wrapped value. Raises: ``ValueError`` with message provided by ``msg`` if the value is :py:data:`NONE`. Examples: >>> Some(0).expect('sd') 0 >>> try: ... NONE.expect('Oh No!') ... except ValueError as e: ... print(e) Oh No! ''' pass def unwrap(self) -> T: ''' Returns the value in the :py:class:`Option` if it is ``Some``. Returns: The ```Some`` value of the :py:class:`Option`. Raises: ``ValueError`` if the value is :py:data:`NONE`. Examples: >>> Some(0).unwrap() 0 >>> try: ... NONE.unwrap() ... except ValueError as e: ... print(e) Value is NONE. ''' pass @property def value(self) -> T: '''Property version of :py:meth:`unwrap`.''' pass def unwrap_or(self, default: U) -> Union[T, U]: ''' Returns the contained value or ``default``. Args: default: The default value. Returns: The contained value if the :py:class:`Option` is ``Some``, otherwise ``default``. Notes: If you wish to use a result of a function call as the default, it is recommnded to use :py:meth:`unwrap_or_else` instead. Examples: >>> Some(0).unwrap_or(3) 0 >>> NONE.unwrap_or(0) 0 ''' pass def unwrap_or_else(self, callback: Callable[[], U]) -> Union[T, U]: ''' Returns the contained value or computes it from ``callback``. Args: callback: The the default callback. Returns: The contained value if the :py:class:`Option` is ``Some``, otherwise ``callback()``. Examples: >>> Some(0).unwrap_or_else(lambda: 111) 0 >>> NONE.unwrap_or_else(lambda: 'ha') 'ha' ''' pass def map(self, callback: Callable[[T], U]) -> 'Option[U]': ''' Applies the ``callback`` with the contained value as its argument or returns :py:data:`NONE`. Args: callback: The callback to apply to the contained value. Returns: The ``callback`` result wrapped in an :class:`Option` if the contained value is ``Some``, otherwise :py:data:`NONE` Examples: >>> Some(10).map(lambda x: x * x) Some(100) >>> NONE.map(lambda x: x * x) NONE ''' pass def map_or(self, callback: Callable[[T], U], default: A) -> Union[U, A]: ''' Applies the ``callback`` to the contained value or returns ``default``. Args: callback: The callback to apply to the contained value. default: The default value. Returns: The ``callback`` result if the contained value is ``Some``, otherwise ``default``. Notes: If you wish to use the result of a function call as ``default``, it is recommended to use :py:meth:`map_or_else` instead. Examples: >>> Some(0).map_or(lambda x: x + 1, 1000) 1 >>> NONE.map_or(lambda x: x * x, 1) 1 ''' pass def map_or_else(self, callback: Callable[[T], U], default: Callable[[], A]) -> Union[U, A]: ''' Applies the ``callback`` to the contained value or computes a default with ``default``. Args: callback: The callback to apply to the contained value. default: The callback fot the default value. Returns: The ``callback`` result if the contained value is ``Some``, otherwise the result of ``default``. Examples: >>> Some(0).map_or_else(lambda x: x * x, lambda: 1) 0 >>> NONE.map_or_else(lambda x: x * x, lambda: 1) 1 ''' pass def flatmap(self, callback: 'Callable[[T], Option[U]]') -> 'Option[U]': ''' Applies the callback to the contained value if the option is not :py:data:`NONE`. This is different than :py:meth:`Option.map` because the result of the callback isn't wrapped in a new :py:class:`Option` Args: callback: The callback to apply to the contained value. Returns: :py:data:`NONE` if the option is :py:data:`NONE`. otherwise calls `callback` with the contained value and returns the result. Examples: >>> def square(x): return Some(x * x) >>> def nope(x): return NONE >>> Some(2).flatmap(square).flatmap(square) Some(16) >>> Some(2).flatmap(square).flatmap(nope) NONE >>> Some(2).flatmap(nope).flatmap(square) NONE >>> NONE.flatmap(square).flatmap(square) NONE ''' pass def filter(self, predicate: Callable[[T], bool]) -> 'Option[T]': ''' Returns :py:data:`NONE` if the :py:class:`Option` is :py:data:`NONE`, otherwise filter the contained value by ``predicate``. Args: predicate: The fitler function. Returns: :py:data:`NONE` if the contained value is :py:data:`NONE`, otherwise: * The option itself if the predicate returns True * :py:data:`NONE` if the predicate returns False Examples: >>> Some(0).filter(lambda x: x % 2 == 1) NONE >>> Some(1).filter(lambda x: x % 2 == 1) Some(1) >>> NONE.filter(lambda x: True) NONE ''' pass def get( self: 'Option[Mapping[K,V]]', key: K, default: Union[V, None] = None ) -> 'Option[V]': ''' Gets a mapping value by key in the contained value or returns ``default`` if the key doesn't exist. Args: key: The mapping key. default: The defauilt value. Returns: * ``Some`` variant of the mapping value if the key exists and the value is not None. * ``Some(default)`` if ``default`` is not None. * :py:data:`NONE` if ``default`` is None. Examples: >>> Some({'hi': 1}).get('hi') Some(1) >>> Some({}).get('hi', 12) Some(12) >>> NONE.get('hi', 12) Some(12) >>> NONE.get('hi') NONE ''' pass def __hash__(self) -> int: pass def __eq__(self, other: object) -> bool: pass def __ne__(self, other: object) -> bool: pass def __lt__(self: 'Option[SupportsDunderLT]', other: object) -> bool: pass def __le__(self: 'Option[SupportsDunderLE]', other: object) -> bool: pass def __gt__(self: 'Option[SupportsDunderGT]', other: object) -> bool: pass def __ge__(self: 'Option[SupportsDunderGE]', other: object) -> bool: pass def __repr__(self) -> str: pass
33
18
13
2
4
8
2
2.34
1
7
0
0
23
3
26
28
403
73
101
41
64
236
82
31
55
4
1
2
50
147,816
MaayanLab/clustergrammer-py
MaayanLab_clustergrammer-py/clustergrammer/__init__.py
clustergrammer.Network
class Network(object): ''' version 1.13.6 Clustergrammer.py takes a matrix as input (either from a file of a Pandas DataFrame), normalizes/filters, hierarchically clusters, and produces the :ref:`visualization_json` for :ref:`clustergrammer_js`. Networks have two states: 1. the data state, where they are stored as a matrix and nodes 2. the viz state where they are stored as viz.links, viz.row_nodes, and viz.col_nodes. The goal is to start in a data-state and produce a viz-state of the network that will be used as input to clustergram.js. ''' def __init__(self, widget=None): initialize_net.main(self, widget) def reset(self): ''' This re-initializes the Network object. ''' initialize_net.main(self) def load_file(self, filename): ''' Load TSV file. ''' load_data.load_file(self, filename) def load_file_as_string(self, file_string, filename=''): ''' Load file as a string. ''' load_data.load_file_as_string(self, file_string, filename=filename) def load_stdin(self): ''' Load stdin TSV-formatted string. ''' load_data.load_stdin(self) def load_tsv_to_net(self, file_buffer, filename=None): ''' This will load a TSV matrix file buffer; this is exposed so that it will be possible to load data without having to read from a file. ''' load_data.load_tsv_to_net(self, file_buffer, filename) def load_vect_post_to_net(self, vect_post): ''' Load data in the vector format JSON. ''' load_vect_post.main(self, vect_post) def load_data_file_to_net(self, filename): ''' Load Clustergrammer's dat format (saved as JSON). ''' inst_dat = self.load_json_to_dict(filename) load_data.load_data_to_net(self, inst_dat) def cluster(self, dist_type='cosine', run_clustering=True, dendro=True, views=['N_row_sum', 'N_row_var'], linkage_type='average', sim_mat=False, filter_sim=0.1, calc_cat_pval=False, run_enrichr=None, enrichrgram=None): ''' The main function performs hierarchical clustering, optionally generates filtered views (e.g. row-filtered views), and generates the :``visualization_json``. ''' initialize_net.viz(self) make_clust_fun.make_clust(self, dist_type=dist_type, run_clustering=run_clustering, dendro=dendro, requested_views=views, linkage_type=linkage_type, sim_mat=sim_mat, filter_sim=filter_sim, calc_cat_pval=calc_cat_pval, run_enrichr=run_enrichr, enrichrgram=enrichrgram) def make_clust(self, dist_type='cosine', run_clustering=True, dendro=True, views=['N_row_sum', 'N_row_var'], linkage_type='average', sim_mat=False, filter_sim=0.1, calc_cat_pval=False, run_enrichr=None, enrichrgram=None): ''' ... Will be deprecated, renaming method cluster ... The main function performs hierarchical clustering, optionally generates filtered views (e.g. row-filtered views), and generates the :``visualization_json``. ''' print('make_clust method will be deprecated in next version, please use cluster method.') initialize_net.viz(self) make_clust_fun.make_clust(self, dist_type=dist_type, run_clustering=run_clustering, dendro=dendro, requested_views=views, linkage_type=linkage_type, sim_mat=sim_mat, filter_sim=filter_sim, calc_cat_pval=calc_cat_pval, run_enrichr=run_enrichr, enrichrgram=enrichrgram) def produce_view(self, requested_view=None): ''' This function is under development and will produce a single view on demand. ''' print('\tproduce a single view of a matrix, will be used for get requests') if requested_view != None: print('requested_view') print(requested_view) def swap_nan_for_zero(self): ''' Swaps all NaN (numpy NaN) instances for zero. ''' # # may re-instate this in some form # self.dat['mat_orig'] = deepcopy(self.dat['mat']) self.dat['mat'][np.isnan(self.dat['mat'])] = 0 def load_df(self, df): ''' Load Pandas DataFrame. ''' # self.__init__() self.reset() df_dict = {} df_dict['mat'] = deepcopy(df) # always define category colors if applicable when loading a df data_formats.df_to_dat(self, df_dict, define_cat_colors=True) def export_df(self): ''' Export Pandas DataFrame/ ''' df_dict = data_formats.dat_to_df(self) return df_dict['mat'] def df_to_dat(self, df, define_cat_colors=False): ''' Load Pandas DataFrame (will be deprecated). ''' data_formats.df_to_dat(self, df, define_cat_colors) def set_cat_color(self, axis, cat_index, cat_name, inst_color): if axis == 0: axis = 'row' if axis == 1: axis = 'col' try: # process cat_index cat_index = cat_index - 1 cat_index = 'cat-' + str(cat_index) self.viz['cat_colors'][axis][cat_index][cat_name] = inst_color except: print('there was an error setting the category color') def dat_to_df(self): ''' Export Pandas DataFrams (will be deprecated). ''' return data_formats.dat_to_df(self) def export_net_json(self, net_type='viz', indent='no-indent'): ''' Export dat or viz JSON. ''' return export_data.export_net_json(self, net_type, indent) def export_viz_to_widget(self, which_viz='viz'): ''' Export viz JSON, for use with clustergrammer_widget. Formerly method was named widget. ''' return export_data.export_net_json(self, which_viz, 'no-indent') def widget(self, which_viz='viz'): ''' Generate a widget visualization using the widget. The export_viz_to_widget method passes the visualization JSON to the instantiated widget, which is returned and visualized on the front-end. ''' if hasattr(self, 'widget_class') == True: self.widget_instance = self.widget_class(network = self.export_viz_to_widget(which_viz)) return self.widget_instance else: print('Can not make widget because Network has no attribute widget_class') print('Please instantiate Network with clustergrammer_widget using: Network(clustergrammer_widget)') def widget_df(self): ''' Export a DataFrame from the front-end visualization. For instance, a user can filter to show only a single cluster using the dendrogram and then get a dataframe of this cluster using the widget_df method. ''' if hasattr(self, 'widget_instance') == True: if self.widget_instance.mat_string != '': tmp_net = deepcopy(Network()) df_string = self.widget_instance.mat_string tmp_net.load_file_as_string(df_string) df = tmp_net.export_df() return df else: return self.export_df() else: if hasattr(self, 'widget_class') == True: print('Please make the widget before exporting the widget DataFrame.') print('Do this using the widget method: net.widget()') else: print('Can not make widget because Network has no attribute widget_class') print('Please instantiate Network with clustergrammer_widget using: Network(clustergrammer_widget)') def write_json_to_file(self, net_type, filename, indent='no-indent'): ''' Save dat or viz as a JSON to file. ''' export_data.write_json_to_file(self, net_type, filename, indent) def write_matrix_to_tsv(self, filename=None, df=None): ''' Export data-matrix to file. ''' return export_data.write_matrix_to_tsv(self, filename, df) def filter_sum(self, inst_rc, threshold, take_abs=True): ''' Filter a network's rows or columns based on the sum across rows or columns. ''' inst_df = self.dat_to_df() if inst_rc == 'row': inst_df = run_filter.df_filter_row_sum(inst_df, threshold, take_abs) elif inst_rc == 'col': inst_df = run_filter.df_filter_col_sum(inst_df, threshold, take_abs) self.df_to_dat(inst_df) def filter_N_top(self, inst_rc, N_top, rank_type='sum'): ''' Filter the matrix rows or columns based on sum/variance, and only keep the top N. ''' inst_df = self.dat_to_df() inst_df = run_filter.filter_N_top(inst_rc, inst_df, N_top, rank_type) self.df_to_dat(inst_df) def filter_threshold(self, inst_rc, threshold, num_occur=1): ''' Filter the matrix rows or columns based on num_occur values being above a threshold (in absolute value). ''' inst_df = self.dat_to_df() inst_df = run_filter.filter_threshold(inst_df, inst_rc, threshold, num_occur) self.df_to_dat(inst_df) def filter_cat(self, axis, cat_index, cat_name): ''' Filter the matrix based on their category. cat_index is the index of the category, the first category has index=1. ''' run_filter.filter_cat(self, axis, cat_index, cat_name) def filter_names(self, axis, names): ''' Filter the visualization using row/column names. The function takes, axis ('row'/'col') and names, a list of strings. ''' run_filter.filter_names(self, axis, names) def clip(self, lower=None, upper=None): ''' Trim values at input thresholds using pandas function ''' df = self.export_df() df = df.clip(lower=lower, upper=upper) self.load_df(df) def normalize(self, df=None, norm_type='zscore', axis='row', keep_orig=False): ''' Normalize the matrix rows or columns using Z-score (zscore) or Quantile Normalization (qn). Users can optionally pass in a DataFrame to be normalized (and this will be incorporated into the Network object). ''' normalize_fun.run_norm(self, df, norm_type, axis, keep_orig) def downsample(self, df=None, ds_type='kmeans', axis='row', num_samples=100, random_state=1000): ''' Downsample the matrix rows or columns (currently supporting kmeans only). Users can optionally pass in a DataFrame to be downsampled (and this will be incorporated into the network object). ''' return downsample_fun.main(self, df, ds_type, axis, num_samples, random_state) def random_sample(self, num_samples, df=None, replace=False, weights=None, random_state=100, axis='row'): ''' Return random sample of matrix. ''' if df is None: df = self.dat_to_df() if axis == 'row': axis = 0 if axis == 'col': axis = 1 df = self.export_df() df = df.sample(n=num_samples, replace=replace, weights=weights, random_state=random_state, axis=axis) self.load_df(df) def add_cats(self, axis, cat_data): ''' Add categories to rows or columns using cat_data array of objects. Each object in cat_data is a dictionary with one key (category title) and value (rows/column names) that have this category. Categories will be added onto the existing categories and will be added in the order of the objects in the array. Example ``cat_data``:: [ { "title": "First Category", "cats": { "true": [ "ROS1", "AAK1" ] } }, { "title": "Second Category", "cats": { "something": [ "PDK4" ] } } ] ''' for inst_data in cat_data: categories.add_cats(self, axis, inst_data) def dendro_cats(self, axis, dendro_level): ''' Generate categories from dendrogram groups/clusters. The dendrogram has 11 levels to choose from 0 -> 10. Dendro_level can be given as an integer or string. ''' categories.dendro_cats(self, axis, dendro_level) def Iframe_web_app(self, filename=None, width=1000, height=800): link = iframe_web_app.main(self, filename, width, height) return link def enrichrgram(self, lib, axis='row'): ''' Add Enrichr gene enrichment results to your visualization (where your rows are genes). Run enrichrgram before clustering to incldue enrichment results as row categories. Enrichrgram can also be run on the front-end using the Enrichr logo at the top left. Set lib to the Enrichr library that you want to use for enrichment analysis. Libraries included: * ChEA_2016 * KEA_2015 * ENCODE_TF_ChIP-seq_2015 * ENCODE_Histone_Modifications_2015 * Disease_Perturbations_from_GEO_up * Disease_Perturbations_from_GEO_down * GO_Molecular_Function_2015 * GO_Biological_Process_2015 * GO_Cellular_Component_2015 * Reactome_2016 * KEGG_2016 * MGI_Mammalian_Phenotype_Level_4 * LINCS_L1000_Chem_Pert_up * LINCS_L1000_Chem_Pert_down ''' df = self.export_df() df, bar_info = enr_fun.add_enrichr_cats(df, axis, lib) self.load_df(df) self.dat['enrichrgram_lib'] = lib self.dat['row_cat_bars'] = bar_info @staticmethod def load_gmt(filename): return load_data.load_gmt(filename) @staticmethod def load_json_to_dict(filename): return load_data.load_json_to_dict(filename) @staticmethod def save_dict_to_json(inst_dict, filename, indent='no-indent'): export_data.save_dict_to_json(inst_dict, filename, indent)
class Network(object): ''' version 1.13.6 Clustergrammer.py takes a matrix as input (either from a file of a Pandas DataFrame), normalizes/filters, hierarchically clusters, and produces the :ref:`visualization_json` for :ref:`clustergrammer_js`. Networks have two states: 1. the data state, where they are stored as a matrix and nodes 2. the viz state where they are stored as viz.links, viz.row_nodes, and viz.col_nodes. The goal is to start in a data-state and produce a viz-state of the network that will be used as input to clustergram.js. ''' def __init__(self, widget=None): pass def reset(self): ''' This re-initializes the Network object. ''' pass def load_file(self, filename): ''' Load TSV file. ''' pass def load_file_as_string(self, file_string, filename=''): ''' Load file as a string. ''' pass def load_stdin(self): ''' Load stdin TSV-formatted string. ''' pass def load_tsv_to_net(self, file_buffer, filename=None): ''' This will load a TSV matrix file buffer; this is exposed so that it will be possible to load data without having to read from a file. ''' pass def load_vect_post_to_net(self, vect_post): ''' Load data in the vector format JSON. ''' pass def load_data_file_to_net(self, filename): ''' Load Clustergrammer's dat format (saved as JSON). ''' pass def cluster(self, dist_type='cosine', run_clustering=True, dendro=True, views=['N_row_sum', 'N_row_var'], linkage_type='average', sim_mat=False, filter_sim=0.1, calc_cat_pval=False, run_enrichr=None, enrichrgram=None): ''' The main function performs hierarchical clustering, optionally generates filtered views (e.g. row-filtered views), and generates the :``visualization_json``. ''' pass def make_clust(self, dist_type='cosine', run_clustering=True, dendro=True, views=['N_row_sum', 'N_row_var'], linkage_type='average', sim_mat=False, filter_sim=0.1, calc_cat_pval=False, run_enrichr=None, enrichrgram=None): ''' ... Will be deprecated, renaming method cluster ... The main function performs hierarchical clustering, optionally generates filtered views (e.g. row-filtered views), and generates the :``visualization_json``. ''' pass def produce_view(self, requested_view=None): ''' This function is under development and will produce a single view on demand. ''' pass def swap_nan_for_zero(self): ''' Swaps all NaN (numpy NaN) instances for zero. ''' pass def load_df(self, df): ''' Load Pandas DataFrame. ''' pass def export_df(self): ''' Export Pandas DataFrame/ ''' pass def df_to_dat(self, df, define_cat_colors=False): ''' Load Pandas DataFrame (will be deprecated). ''' pass def set_cat_color(self, axis, cat_index, cat_name, inst_color): pass def dat_to_df(self): ''' Export Pandas DataFrams (will be deprecated). ''' pass def export_net_json(self, net_type='viz', indent='no-indent'): ''' Export dat or viz JSON. ''' pass def export_viz_to_widget(self, which_viz='viz'): ''' Export viz JSON, for use with clustergrammer_widget. Formerly method was named widget. ''' pass def widget(self, which_viz='viz'): ''' Generate a widget visualization using the widget. The export_viz_to_widget method passes the visualization JSON to the instantiated widget, which is returned and visualized on the front-end. ''' pass def widget_df(self): ''' Export a DataFrame from the front-end visualization. For instance, a user can filter to show only a single cluster using the dendrogram and then get a dataframe of this cluster using the widget_df method. ''' pass def write_json_to_file(self, net_type, filename, indent='no-indent'): ''' Save dat or viz as a JSON to file. ''' pass def write_matrix_to_tsv(self, filename=None, df=None): ''' Export data-matrix to file. ''' pass def filter_sum(self, inst_rc, threshold, take_abs=True): ''' Filter a network's rows or columns based on the sum across rows or columns. ''' pass def filter_N_top(self, inst_rc, N_top, rank_type='sum'): ''' Filter the matrix rows or columns based on sum/variance, and only keep the top N. ''' pass def filter_threshold(self, inst_rc, threshold, num_occur=1): ''' Filter the matrix rows or columns based on num_occur values being above a threshold (in absolute value). ''' pass def filter_cat(self, axis, cat_index, cat_name): ''' Filter the matrix based on their category. cat_index is the index of the category, the first category has index=1. ''' pass def filter_names(self, axis, names): ''' Filter the visualization using row/column names. The function takes, axis ('row'/'col') and names, a list of strings. ''' pass def clip(self, lower=None, upper=None): ''' Trim values at input thresholds using pandas function ''' pass def normalize(self, df=None, norm_type='zscore', axis='row', keep_orig=False): ''' Normalize the matrix rows or columns using Z-score (zscore) or Quantile Normalization (qn). Users can optionally pass in a DataFrame to be normalized (and this will be incorporated into the Network object). ''' pass def downsample(self, df=None, ds_type='kmeans', axis='row', num_samples=100, random_state=1000): ''' Downsample the matrix rows or columns (currently supporting kmeans only). Users can optionally pass in a DataFrame to be downsampled (and this will be incorporated into the network object). ''' pass def random_sample(self, num_samples, df=None, replace=False, weights=None, random_state=100, axis='row'): ''' Return random sample of matrix. ''' pass def add_cats(self, axis, cat_data): ''' Add categories to rows or columns using cat_data array of objects. Each object in cat_data is a dictionary with one key (category title) and value (rows/column names) that have this category. Categories will be added onto the existing categories and will be added in the order of the objects in the array. Example ``cat_data``:: [ { "title": "First Category", "cats": { "true": [ "ROS1", "AAK1" ] } }, { "title": "Second Category", "cats": { "something": [ "PDK4" ] } } ] ''' pass def dendro_cats(self, axis, dendro_level): ''' Generate categories from dendrogram groups/clusters. The dendrogram has 11 levels to choose from 0 -> 10. Dendro_level can be given as an integer or string. ''' pass def Iframe_web_app(self, filename=None, width=1000, height=800): pass def enrichrgram(self, lib, axis='row'): ''' Add Enrichr gene enrichment results to your visualization (where your rows are genes). Run enrichrgram before clustering to incldue enrichment results as row categories. Enrichrgram can also be run on the front-end using the Enrichr logo at the top left. Set lib to the Enrichr library that you want to use for enrichment analysis. Libraries included: * ChEA_2016 * KEA_2015 * ENCODE_TF_ChIP-seq_2015 * ENCODE_Histone_Modifications_2015 * Disease_Perturbations_from_GEO_up * Disease_Perturbations_from_GEO_down * GO_Molecular_Function_2015 * GO_Biological_Process_2015 * GO_Cellular_Component_2015 * Reactome_2016 * KEGG_2016 * MGI_Mammalian_Phenotype_Level_4 * LINCS_L1000_Chem_Pert_up * LINCS_L1000_Chem_Pert_down ''' pass @staticmethod def load_gmt(filename): pass @staticmethod def load_json_to_dict(filename): pass @staticmethod def save_dict_to_json(inst_dict, filename, indent='no-indent'): pass
43
34
9
1
4
4
1
0.96
1
1
0
0
36
1
39
39
420
87
170
64
121
163
139
55
99
4
1
2
53
147,817
MacHu-GWU/angora-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_angora-project/angora/text/strtemplate.py
angora.text.strtemplate.Unittest
class Unittest(unittest.TestCase): def test_straight_line(self): self.assertEqual( StrTemplate.straight_line("Hello world!", 20, "-", 1), "--- Hello world! ---", ) def test_indented(self): self.assertEqual( StrTemplate.indented("Hello world!", 1), "\tHello world!", ) def test_box(self): self.assertEqual( StrTemplate.box("Hello world!", 20, 5), ("+------------------+" "\n| |" "\n| Hello world! |" "\n| |" "\n+------------------+"), )
class Unittest(unittest.TestCase): def test_straight_line(self): pass def test_indented(self): pass def test_box(self): pass
4
0
6
0
6
0
1
0
1
1
1
0
3
0
3
75
22
2
20
4
16
0
7
4
3
1
2
0
3
147,818
MacHu-GWU/angora-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_angora-project/angora/text/rerecipe.py
angora.text.rerecipe.ReParserUnittest
class ReParserUnittest(unittest.TestCase): def test_extract_by_prefix_surfix(self): self.assertEqual( ReParser.extract_by_prefix_surfix( "<div>", "</div>", 100, "<a>中文<div>some text</div>英文</a>"), ["some text",] )
class ReParserUnittest(unittest.TestCase): def test_extract_by_prefix_surfix(self): pass
2
0
9
0
9
0
1
0
1
1
1
0
1
0
1
73
10
0
10
2
8
0
3
2
1
1
2
0
1
147,819
MacHu-GWU/angora-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_angora-project/angora/text/formatter.py
angora.text.formatter.Unittest
class Unittest(unittest.TestCase): def test_fmt_title(self): title = " google killing annoying browsing feature " self.assertEqual(fmt_title(title), "Google Killing Annoying Browsing Feature") def test_fmt_sentence(self): sentence = " do you want to build a snow man? " self.assertEqual(fmt_sentence(sentence), "Do you want to build a snow man?") def test_fmt_name(self): name = " michael jackson " self.assertEqual(fmt_name(name), "Michael Jackson")
class Unittest(unittest.TestCase): def test_fmt_title(self): pass def test_fmt_sentence(self): pass def test_fmt_name(self): pass
4
0
4
0
4
0
1
0
1
0
0
0
3
0
3
75
14
2
12
7
8
0
10
7
6
1
2
0
3
147,820
MacHu-GWU/angora-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_angora-project/angora/math/outlier.py
angora.math.outlier.Unittest
class Unittest(unittest.TestCase): def test_std_filter(self): good, bad = std_filter(array, n_std=2.0) def test_box_filter(self): good, bad = box_filter(array, n_iqr=1.5)
class Unittest(unittest.TestCase): def test_std_filter(self): pass def test_box_filter(self): pass
3
0
2
0
2
0
1
0
1
0
0
0
2
0
2
74
6
1
5
5
2
0
5
5
2
1
2
0
2
147,821
MacHu-GWU/angora-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_angora-project/angora/baseclass/nameddict.py
angora.baseclass.nameddict.Unittest
class Unittest(unittest.TestCase): def test_all(self): person = Person(id=1, name="Jack") self.assertEqual(str(person), "Person(id=1, name='Jack')") self.assertDictEqual(person.to_dict(), {"id": 1, "name": "Jack"}) person = Person._make({"id": 1, "name": "Jack"}) self.assertEqual(str(person), "Person(id=1, name='Jack')") self.assertDictEqual(person.to_dict(), {"id": 1, "name": "Jack"}) print(person.keys()) print(person.values())
class Unittest(unittest.TestCase): def test_all(self): pass
2
0
11
2
9
0
1
0
1
2
1
0
1
0
1
73
12
2
10
3
8
0
10
3
8
1
2
0
1
147,822
MacHu-GWU/angora-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_angora-project/angora/baseclass/nameddict.py
angora.baseclass.nameddict.Person
class Person(Base): def __init__(self, id, name): self.id = id self.name = name
class Person(Base): def __init__(self, id, name): pass
2
0
3
0
3
0
1
0
1
0
0
0
1
2
1
8
4
0
4
4
2
0
4
4
2
1
2
0
1
147,823
MacHu-GWU/angora-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_angora-project/angora/math/interp.py
angora.math.interp.LinearInterpolateUnittest
class LinearInterpolateUnittest(unittest.TestCase): def test_linear_interpolate(self): x = [1, 2, 3] y = [1, 2, 3] x_new1 = [1, 1.5, 2, 2.5, 3] y_new1 = linear_interpolate(x, y, x_new1) x_new2 = [0, 1, 2, 3, 4] y_new2 = linear_interpolate(x, y, x_new2) for i, j in zip(y_new1, [1, 1.5, 2, 2.5, 3]): self.assertAlmostEqual(i, j, 0.001) for i, j in zip(y_new2, [0, 1, 2, 3, 4]): self.assertAlmostEqual(i, j, 0.001) def test_linear_interpolate_by_datetime(self): x = [ datetime(2014, 1, 1, 0, 0, 10), datetime(2014, 1, 1, 0, 0, 20)] y = [1, 2] x_new1 = [datetime(2014, 1, 1, 0, 0, 5), datetime(2014, 1, 1, 0, 0, 15), datetime(2014, 1, 1, 0, 0, 25)] y_new1 = linear_interpolate_by_datetime(x, y, x_new1) for i, j in zip(y_new1, [0.5, 1.5, 2.5]): self.assertAlmostEqual(i, j, 0.001) def test_exam_reliability(self): x = [1, 2, 3, 4] x_new = [0.4, 0.6, 1.7, 2.5, 3.3, 4.4, 4.5] self.assertListEqual( exam_reliability(x, x_new, 0.4), [False, False, True, False, True, False, False], )
class LinearInterpolateUnittest(unittest.TestCase): def test_linear_interpolate(self): pass def test_linear_interpolate_by_datetime(self): pass def test_exam_reliability(self): pass
4
0
10
0
9
0
2
0
1
2
0
0
3
0
3
75
32
3
29
18
25
0
23
18
19
3
2
1
6
147,824
MacHu-GWU/angora-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_angora-project/angora/math/img2waveform.py
angora.math.img2waveform.ParseImageUnittest
class ParseImageUnittest(unittest.TestCase): def test_expand_window(self): self.assertListEqual(list(expand_window(3, 5, 20)), [0, 1, 2, 3, 4, 5, 6, 7, 8]) self.assertListEqual(list(expand_window(18, 5, 20)), [13, 14, 15, 16, 17, 18, 19]) self.assertListEqual(list(expand_window(10, 5, 20)), [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
class ParseImageUnittest(unittest.TestCase): def test_expand_window(self): pass
2
0
7
0
7
0
1
0
1
1
0
0
1
0
1
73
8
0
8
2
6
0
5
2
3
1
2
0
1
147,825
MacHu-GWU/angora-project
MacHu-GWU_angora-project/angora/text/rerecipe.py
angora.text.rerecipe.ReParser
class ReParser(object): """An re-parser extract text using many useful built-in patterns. """ @staticmethod def extract_by_prefix_surfix(prefix, surfix, maxlen, text): """Extract the text in between a prefix and surfix. :param prefix: the prefix :type prefix: str :param surfix: the surfix :type surfix: str :param maxlen: the max matched string length :type maxlen: int :param text: text body :type text: str """ pattern = r"""(?<=%s)[\s\S]{1,%s}(?=%s)""" % (prefix, maxlen, surfix) return re.findall(pattern, text)
class ReParser(object): '''An re-parser extract text using many useful built-in patterns. ''' @staticmethod def extract_by_prefix_surfix(prefix, surfix, maxlen, text): '''Extract the text in between a prefix and surfix. :param prefix: the prefix :type prefix: str :param surfix: the surfix :type surfix: str :param maxlen: the max matched string length :type maxlen: int :param text: text body :type text: str ''' pass
3
2
17
4
3
10
1
2.4
1
0
0
0
0
0
1
1
22
5
5
4
2
12
4
3
2
1
1
0
1
147,826
MacHu-GWU/angora-project
MacHu-GWU_angora-project/angora/text/strtemplate.py
angora.text.strtemplate.StrTemplate
class StrTemplate(): @staticmethod def straight_line(title, length=100, linestyle="=", pad=0): """Return a fixed-length straight line with some text at the center. Usage Example:: >>> StringTemplate.straight_line("Hello world!", 20, "-", 1) --- Hello world! --- """ text = "{:%s^%s}" % (linestyle, length) return text.format("%s%s%s" % (" "*pad, title, " "*pad)) @staticmethod def straight_line_show(title, length=100, linestyle="=", pad=0): """Print a formatted straight line. """ print(StrTemplate.straight_line( title=title, length=length, linestyle=linestyle, pad=pad)) @staticmethod def indented(text, howmany=1): """Return the text with ``howmany`` indent at begin. Usage Example:: >>> StringTemplate.indented("Hello world!", 1) Hello world! """ return "%s%s" % ("\t"*howmany, text) @staticmethod def indented_show(text, howmany=1): """Print a formatted indented text. """ print(StrTemplate.pad_indent(text=text, howmany=howmany)) @staticmethod def box(text, width=100, height=3, corner="+", horizontal="-", vertical="|"): """Return a ascii box, with your text center-aligned. Usage Example:: >>> StringTemplate.box("Hello world!", 20, 5) +------------------+ | | | Hello world! | | | +------------------+ """ if width <= len(text) - 4: print("width is not large enough! apply auto-adjust...") width = len(text) + 4 if height <= 2: print("height is too small! apply auto-adjust...") height = 3 if (height % 2) == 0: print("height has to be odd! apply auto-adjust...") height += 1 head = tail = corner + horizontal * (width - 2) + corner pad = "%s%s%s" % (vertical, " " * (width - 2), vertical) pad_number = (height - 3) // 2 pattern = "{: ^%s}" % (width - 2, ) body = vertical + pattern.format(text) + vertical return "\n".join([head,] + [pad,] * pad_number + [body,] + [pad,] * pad_number + [tail,]) @staticmethod def box_show(text, width=100, height=3, corner="+", horizontal="-", vertical="|"): """Print a formatted ascii text box. """ print(StrTemplate.box(text=text, width=width, height=height, corner=corner, horizontal=horizontal, vertical=vertical))
class StrTemplate(): @staticmethod def straight_line(title, length=100, linestyle="=", pad=0): '''Return a fixed-length straight line with some text at the center. Usage Example:: >>> StringTemplate.straight_line("Hello world!", 20, "-", 1) --- Hello world! --- ''' pass @staticmethod def straight_line_show(title, length=100, linestyle="=", pad=0): '''Print a formatted straight line. ''' pass @staticmethod def indented(text, howmany=1): '''Return the text with ``howmany`` indent at begin. Usage Example:: >>> StringTemplate.indented("Hello world!", 1) Hello world! ''' pass @staticmethod def indented_show(text, howmany=1): '''Print a formatted indented text. ''' pass @staticmethod def box(text, width=100, height=3, corner="+", horizontal="-", vertical="|"): '''Return a ascii box, with your text center-aligned. Usage Example:: >>> StringTemplate.box("Hello world!", 20, 5) +------------------+ | | | Hello world! | | | +------------------+ ''' pass @staticmethod def box_show(text, width=100, height=3, corner="+", horizontal="-", vertical="|"): '''Print a formatted ascii text box. ''' pass
13
6
11
2
5
4
2
0.69
0
0
0
0
0
0
6
6
75
14
36
19
23
25
28
13
21
4
0
1
9
147,827
MacHu-GWU/angora-project
MacHu-GWU_angora-project/angora/timelib/timewrapper.py
angora.timelib.timewrapper.ModeError
class ModeError(Exception): """Used in TimeWrapper.day_interval, TimeWrapper.month_interval, TimeWrapper.year_interval. For wrong mode argument. """ def __init__(self, mode_name): self.mode_name = mode_name def __str__(self): return ("mode has to be 'str' or 'datetime', default 'str'. " "You are using '%s'.") % self.mode_name
class ModeError(Exception): '''Used in TimeWrapper.day_interval, TimeWrapper.month_interval, TimeWrapper.year_interval. For wrong mode argument. ''' def __init__(self, mode_name): pass def __str__(self): pass
3
1
3
0
3
0
1
0.5
1
0
0
0
2
1
2
12
10
1
6
4
3
3
5
4
2
1
3
0
2
147,828
MacHu-GWU/angora-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_angora-project/angora/crawler/downloader.py
angora.crawler.downloader.DownloaderUnittest
class DownloaderUnittest(unittest.TestCase): def test_download_url(self): url = "https://www.python.org//static/img/python-logo.png" save_as = "python-logo.png" download_url(url, save_as, iter_size=1024, enable_verbose=True) try: os.remove(save_as) except: pass
class DownloaderUnittest(unittest.TestCase): def test_download_url(self): pass
2
0
8
0
8
0
2
0
1
0
0
0
1
0
1
73
9
0
9
4
7
0
9
4
7
2
2
1
2
147,829
MacHu-GWU/angora-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_angora-project/angora/gadget/configuration.py
angora.gadget.configuration.ConfigurationUnittest
class ConfigurationUnittest(unittest.TestCase): def setUp(self): """从config dump到本地文件, 以供检视 """ config = Configuration() config.DEFAULT["localhost"] = "192.168.0.1" config.DEFAULT["port"] = 8080 config.DEFAULT["connection_timeout"] = 60 # seconds config.add_section("TEST") config.TEST["key1"] = 100 # key1 = 100 config.TEST["key2"] = 123.456 # key2 = 123.456 config.TEST["key3"] = "True" # key3 = 'True' config.TEST["key4"] = "123" # key4 ='123' # key5 = C:\test\nope\red\中文\英文.jpg config.TEST["key5"] = r"C:\test\nope\red\中文\英文.jpg" config.TEST["key6"] = False # key6 = False config.TEST["key7"] = [1, -2, 3] # key7 = 1, -2, 3 config.TEST["key8"] = [1.1, -2.2, 3.3] # key8 = 1.1, -2.2, 3.3 # key9 = '1', '1.1', 'True', 'helloworld' config.TEST["key9"] = ["1", "1.1", "True", "helloworld"] # key10 = 'C:\windows', 'C:\中文' config.TEST["key10"] = ["C:\windows", r"C:\中文"] # key11 = True, False, True, False config.TEST["key11"] = [True, False, True, False] config.TEST["key12"] = [] # key12 = , config.dump("config.txt") # <=== Uncomment this to view the file def test_load(self): """测试Configuration.load()方法 """ config = Configuration() config.load(r"testdata\config.txt") # read test data self.assertListEqual(config.sections(), ["DEFAULT", "TEST"]) self.assertEqual(config.DEFAULT["localhost"], "192.168.0.1") self.assertEqual(config.DEFAULT["port"], 8080) self.assertEqual(config.DEFAULT["connection_timeout"], 60) self.assertEqual(config.TEST["key1"], 100) self.assertEqual(config.TEST["key2"], 123.456) self.assertEqual(config.TEST["key3"], "True") self.assertEqual(config.TEST["key4"], "123") self.assertEqual( config.TEST["key5"], r"C:\test\nope\red\中文\英文.jpg") self.assertEqual(config.TEST["key6"], False) self.assertListEqual(config.TEST["key7"], [1, -2, 3]) self.assertListEqual(config.TEST["key8"], [1.1, -2.2, 3.3]) self.assertListEqual( config.TEST["key9"], ["1", "1.1", "True", "helloworld"]) self.assertListEqual( config.TEST["key10"], ["C:\windows", r"C:\中文"]) self.assertListEqual( config.TEST["key11"], [True, False, True, False]) self.assertListEqual(config.TEST["key12"], [])
class ConfigurationUnittest(unittest.TestCase): def setUp(self): '''从config dump到本地文件, 以供检视 ''' pass def test_load(self): '''测试Configuration.load()方法 ''' pass
3
2
27
2
21
10
1
0.44
1
1
1
0
2
0
2
74
56
5
43
5
40
19
39
5
36
1
2
0
2
147,830
MacHu-GWU/angora-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_angora-project/angora/crawler/simplecrawler.py
angora.crawler.simplecrawler.Unittest
class Unittest(unittest.TestCase): def test_html(self): url = "http://www.ralphlauren.fr/home/index.jsp?locale=it_FR&ab=global_cs_italy_US" html = spider.html(url) self.assertEqual(type(html), str) url = "http://www.caribbeancom.com/moviepages/010103-304/index.html" html = spider.html(url) self.assertEqual(type(html), str) url = "https://pypi.python.org/pypi/requests/2.6.0" html = spider.html(url) self.assertEqual(type(html), str) url = "https://www.python.org/doc/" html = spider.html(url) self.assertEqual(type(html), str) self.assertEqual(spider.domain_encoding_map, { "https://pypi.python.org": "utf-8", "https://www.python.org": "ascii", "http://www.caribbeancom.com": "EUC-JP", "http://www.ralphlauren.fr": "ISO-8859-2", }, ) def test_binary(self): url = "https://www.python.org//static/img/python-logo.png" with open("python-logo.png", "wb") as f: f.write(spider.binary(url))
class Unittest(unittest.TestCase): def test_html(self): pass def test_binary(self): pass
3
0
15
2
13
0
1
0
1
2
0
0
2
0
2
74
31
5
26
7
23
0
19
6
16
1
2
1
2
147,831
MacHu-GWU/angora-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_angora-project/angora/dataIO/js.py
angora.dataIO.js.JSUnittest
class JSUnittest(unittest.TestCase): def test_write_and_read(self): data = {"a": [1, 2], "b": ["是", "否"], "c": datetime(2015, 1, 1, 6, 30), "d": [0.123456789, 3.1415926535]} safe_dump_js(data, "data.json", precision=2, enable_verbose=False) data = load_js("data.json") self.assertEqual(data["a"][0], 1) self.assertEqual(data["b"][0], "是") self.assertAlmostEqual(data["d"][0], 0.12, delta=0.000000001) self.assertAlmostEqual(data["d"][1], 3.14, delta=0.000000001) def test_js2str(self): data = {"a": [1, 2], "b": ["是", "否"]} prt_js(data) def test_compress(self): data = {"a": [1, 2], "b": ["是", "否"]} safe_dump_js(data, "data.gz", compress=True) prt_js(load_js("data.gz", compress=True)) def tearDown(self): for path in ["data.json", "data.gz"]: try: os.remove(path) except: pass
class JSUnittest(unittest.TestCase): def test_write_and_read(self): pass def test_js2str(self): pass def test_compress(self): pass def tearDown(self): pass
5
0
6
0
6
0
2
0
1
1
0
0
4
0
4
76
26
3
23
9
18
0
22
9
17
3
2
2
6
147,832
MacHu-GWU/angora-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_angora-project/angora/dataIO/pk.py
angora.dataIO.pk.PKUnittest
class PKUnittest(unittest.TestCase): def test_write_and_read(self): data = {1: [1, 2], 2: ["是", "否"]} safe_dump_pk(data, "data.pickle") data = load_pk("data.pickle") # should be a self.assertEqual(data[1][0], 1) self.assertEqual(data[2][0], "是") def test_handle_object(self): python_object = {"a": 1} self.assertEqual(str2obj(obj2str(python_object)), python_object) def test_obj2bytestr(self): """pickle.dumps的结果是bytes, 而在python2中的sqlite不支持bytes直接 插入数据库,必须使用base64.encode将bytes编码成字符串之后才能存入数据 库。而在python3中, 可以直接将pickle.dumps的bytestr存入数据库, 这样 就省去了base64编码的开销。 注: 在python2中也有通过设定 connect.text_factory 的方法解决该问题, 具体内容请google This test will not pass in Python2, because sqlite python2 API doens't support bytes. """ conn = sqlite3.connect(":memory:") c = conn.cursor() c.execute("CREATE TABLE test (dictionary BLOB) ") # BLOB is byte c.execute("INSERT INTO test VALUES (?)", (obj2bytestr({1: "a", 2: "你好"}),)) # see what stored in database print(c.execute("select * from test").fetchone()) # recovery object from byte str self.assertDictEqual( bytestr2obj(c.execute("select * from test").fetchone()[0]), {1: "a", 2: "你好"}, ) def test_obj2str(self): """如果将任意python对象dump成pickle bytestr, 再通过base64 encode转化 成ascii字符串, 就可以任意地存入数据库了。 """ conn = sqlite3.connect(":memory:") c = conn.cursor() c.execute("CREATE TABLE test (name TEXT) ") c.execute("INSERT INTO test VALUES (?)", (obj2str({1: "a", 2: "你好"}),)) # see what stored in database print(c.execute("select * from test").fetchone()) # recovery object from text str self.assertDictEqual( str2obj(c.execute("select * from test").fetchone()[0]), {1: "a", 2: "你好"}, ) def test_compress(self): data = {"a": list(range(32)), "b": list(range(32)), } safe_dump_pk(data, "data.gz", compress=True) print(load_pk("data.gz", compress=True)) def tearDown(self): for path in ["data.pickle", "data.gz"]: try: os.remove(path) except: pass
class PKUnittest(unittest.TestCase): def test_write_and_read(self): pass def test_handle_object(self): pass def test_obj2bytestr(self): '''pickle.dumps的结果是bytes, 而在python2中的sqlite不支持bytes直接 插入数据库,必须使用base64.encode将bytes编码成字符串之后才能存入数据 库。而在python3中, 可以直接将pickle.dumps的bytestr存入数据库, 这样 就省去了base64编码的开销。 注: 在python2中也有通过设定 connect.text_factory 的方法解决该问题, 具体内容请google This test will not pass in Python2, because sqlite python2 API doens't support bytes. ''' pass def test_obj2str(self): '''如果将任意python对象dump成pickle bytestr, 再通过base64 encode转化 成ascii字符串, 就可以任意地存入数据库了。 ''' pass def test_compress(self): pass def tearDown(self): pass
7
2
11
1
7
3
1
0.42
1
2
0
0
6
0
6
78
69
10
43
15
36
18
34
15
27
3
2
2
8
147,833
MacHu-GWU/angora-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_angora-project/angora/dataIO/textfile.py
angora.dataIO.textfile.textfileIOUnittest
class textfileIOUnittest(unittest.TestCase): def test_read(self): print(read(r"testdata\multilanguage.txt")) def test_write(self): text = r"中\文, 台/湾, グー\グル, eng/lish" write(text, "test.txt") self.assertEqual(read("test.txt"), text) def tearDown(self): try: os.remove("test.txt") except: pass
class textfileIOUnittest(unittest.TestCase): def test_read(self): pass def test_write(self): pass def tearDown(self): pass
4
0
4
0
4
0
1
0
1
0
0
0
3
0
3
75
14
2
12
5
8
0
12
5
8
2
2
1
4
147,834
MacHu-GWU/angora-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_angora-project/angora/dtypes/dicttree.py
angora.dtypes.dicttree.DictTreeUnittest
class DictTreeUnittest(unittest.TestCase): def test_iter_method(self): self.assertSetEqual(set(DictTree.k(d)), set(["VA", "MD"])) def test_iter_on_depth_method(self): self.assertSetEqual(set(DictTree.k_depth(d, 0)), set(["US"])) self.assertSetEqual(set(DictTree.k_depth(d, 1)), set(["VA", "MD"])) self.assertSetEqual(set(DictTree.k_depth(d, 2)), set(["arlington", "vienna", "bethesta", "germentown"])) self.assertSetEqual(set(DictTree.k_depth(d, 3)), set(["riverhouse", "crystal plaza", "loft"])) def test_length_method(self): self.assertEqual(DictTree.length(d), 2) self.assertEqual(DictTree.length(d["VA"]), 2) self.assertEqual(DictTree.length(d["MD"]), 2) self.assertEqual(DictTree.length(d["VA"]["arlington"]), 3) self.assertEqual(DictTree.length(d["MD"]["bethesta"]), 0) self.assertEqual(DictTree.len_on_depth(d, 0), 0) self.assertEqual(DictTree.len_on_depth(d, 1), 2) self.assertEqual(DictTree.len_on_depth(d, 2), 4) self.assertEqual(DictTree.len_on_depth(d, 3), 3) self.assertEqual(DictTree.len_on_depth(d, 4), 0) def test_del_depth(self): d1 = copy.deepcopy(d) DictTree.del_depth(d1, 2) self.assertEqual(DictTree.len_on_depth(d1, 1), 2) self.assertEqual(DictTree.len_on_depth(d1, 2), 0) self.assertEqual(DictTree.len_on_depth(d1, 3), 0) def test_status_on_depth(self): DictTree.stats_on_depth(d, 0) DictTree.stats_on_depth(d, 1) DictTree.stats_on_depth(d, 2) DictTree.stats_on_depth(d, 3) DictTree.stats_on_depth(d, 4)
class DictTreeUnittest(unittest.TestCase): def test_iter_method(self): pass def test_iter_on_depth_method(self): pass def test_length_method(self): pass def test_del_depth(self): pass def test_status_on_depth(self): pass
6
0
7
0
7
0
1
0
1
2
1
0
5
0
5
77
38
4
34
7
28
0
31
7
25
1
2
0
5
147,835
MacHu-GWU/angora-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_angora-project/angora/dtypes/orderedset.py
angora.dtypes.orderedset.OrderedSetUnittest
class OrderedSetUnittest(unittest.TestCase): def test_add_pop_and_discard(self): """test, add(item), pop(last=True/False), discard(item) method """ s = OrderedSet("abcde") self.assertListEqual(list(s), ["a", "b", "c", "d", "e"]) s.pop() self.assertListEqual(list(s), ["a", "b", "c", "d"]) s.pop(last=False) self.assertListEqual(list(s), ["b", "c", "d"]) s.discard("c") self.assertListEqual(list(s), ["b", "d"]) def test_union_intersect_and_difference(self): """test union, intersect, difference operation """ s = OrderedSet("abracadaba") # {"a", "b", "r", "c", "d"} # {"s", "i", "m", "c", "a", "l", "b"} t = OrderedSet("simcsalabim") self.assertListEqual(list(s | t), # s union t ["a", "b", "r", "c", "d", "s", "i", "m", "l"]) self.assertListEqual(list(s & t), # s intersect t ["c", "a", "b"]) self.assertListEqual(list(s - t), # s different t ["r", "d"]) def test_staticmethod(self): """test customized batch union and intersect static method """ r = OrderedSet("buag") # {"b", "u", "a", "g"} s = OrderedSet("abracadaba") # {"a", "b", "r", "c", "d"} # {"s", "i", "m", "c", "a", "l", "b"} t = OrderedSet("simcsalabim") # r union s union t self.assertListEqual(list(OrderedSet.union(r, s, t)), ["b", "u", "a", "g", "r", "c", "d", "s", "i", "m", "l"]) # r intsect s and t self.assertListEqual(list(OrderedSet.intersection(r, s, t)), ["b", "a"])
class OrderedSetUnittest(unittest.TestCase): def test_add_pop_and_discard(self): '''test, add(item), pop(last=True/False), discard(item) method ''' pass def test_union_intersect_and_difference(self): '''test union, intersect, difference operation ''' pass def test_staticmethod(self): '''test customized batch union and intersect static method ''' pass
4
3
13
2
9
5
1
0.59
1
2
1
0
3
0
3
75
42
7
27
10
23
16
22
10
18
1
2
0
3
147,836
MacHu-GWU/angora-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_angora-project/angora/filesystem/filesystem.py
angora.filesystem.filesystem.WinDirUnittest
class WinDirUnittest(unittest.TestCase): def test_detail(self): windir = WinDir("testdir")
class WinDirUnittest(unittest.TestCase): def test_detail(self): pass
2
0
2
0
2
0
1
0
1
1
1
0
1
0
1
73
3
0
3
3
1
0
3
3
1
1
2
0
1
147,837
MacHu-GWU/angora-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_angora-project/angora/baseclass/defaultExc.py
angora.baseclass.defaultExc.DataError
class DataError(declare_base(erroName=False)): default = "This is DEFAULT message"
class DataError(declare_base(erroName=False)): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
1
0
0
147,838
MacHu-GWU/angora-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_angora-project/angora/gadget/configuration.py
angora.gadget.configuration.SectionUnittest
class SectionUnittest(unittest.TestCase): def test_str(self): """测试__str__()方法是否能返回正确的字符串 """ section = Section("DEFAULT") section["key1"] = 100 # key1 = 100 section["key2"] = 123.456 # key2 = 123.456 section["key3"] = "True" # key3 = 'True' section["key4"] = "123" # key4 ='123' # key5 = C:\test\nope\red\中文\英文.jpg section["key5"] = r"C:\test\nope\red\中文\英文.jpg" section["key6"] = False # key6 = False section["key7"] = [1, -2, 3] # key7 = 1, -2, 3 section["key8"] = [1.1, -2.2, 3.3] # key8 = 1.1, -2.2, 3.3 # key9 = '1', '1.1', 'True', 'helloworld' section["key9"] = ["1", "1.1", "True", "helloworld"] # key10 = 'C:\windows', 'C:\中文' section["key10"] = ["C:\windows", r"C:\中文"] # key11 = True, False, True, False section["key11"] = [True, False, True, False] section["key12"] = [] # key12 = , right_result = "\n".join([ "[DEFAULT]", "key1 = 100", "key2 = 123.456", "key3 = 'True'", "key4 = '123'", r"key5 = C:\test\nope\red\中文\英文.jpg", "key6 = False", "key7 = 1, -2, 3", "key8 = 1.1, -2.2, 3.3", "key9 = '1', '1.1', 'True', 'helloworld'", r"key10 = 'C:\windows', 'C:\中文'", "key11 = True, False, True, False", "key12 = ,", ]) self.assertEqual(str(section), right_result) def test_from_text(self): """测试from_text()方法能否将字符串解析成section """ text = r""" [DEFAULT] localhost = 192.168.0.1 # IP地址, 默认 192.168.0.1 port = 8080 # 端口号 ### 下面的是尝试连接的最长时间 connection_timeout = 60 # 单位是秒, 默认60 # Test是用来测试各种数据类型是否能被成功解析的 # 用Configuration.load()看看会不会成功吧 """.strip() section = Section.from_text(text) self.assertEqual(section["localhost"], "192.168.0.1") self.assertEqual(section["port"], 8080) self.assertEqual(section["connection_timeout"], 60) text = r""" [TEST] key1 = 100 key2 = 123.456 key3 = 'True' key4 = '123' key5 = C:\test\nope\red\中文\英文.jpg key6 = False key7 = 1, -2, 3 key8 = 1.1, -2.2, 3.3 key9 = '1', '1.1', 'True', 'helloworld' key10 = 'C:\windows', 'C:\中文' key11 = True, False, True, False key12 = , """.strip() section = Section.from_text(text) self.assertEqual(section["key1"], 100) self.assertEqual(section["key2"], 123.456) self.assertEqual(section["key3"], "True") self.assertEqual(section["key4"], "123") self.assertEqual(section["key5"], r"C:\test\nope\red\中文\英文.jpg") self.assertEqual(section["key6"], False) self.assertListEqual(section["key7"], [1, -2, 3]) self.assertListEqual(section["key8"], [1.1, -2.2, 3.3]) self.assertListEqual( section["key9"], ["1", "1.1", "True", "helloworld"]) self.assertListEqual(section["key10"], ["C:\windows", r"C:\中文"]) self.assertListEqual(section["key11"], [True, False, True, False]) self.assertListEqual(section["key12"], [])
class SectionUnittest(unittest.TestCase): def test_str(self): '''测试__str__()方法是否能返回正确的字符串 ''' pass def test_from_text(self): '''测试from_text()方法能否将字符串解析成section ''' pass
3
2
43
3
35
11
1
0.31
1
2
1
0
2
0
2
74
88
6
71
7
68
22
37
7
34
1
2
0
2
147,839
MacHu-GWU/angora-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_angora-project/angora/gadget/messenger.py
angora.gadget.messenger.MessengerUnittest
class MessengerUnittest(unittest.TestCase): def test_all(self): messenger = Messenger() messenger.show("hello world 1") messenger.off() messenger.show("hello world 2") messenger.on() messenger.show("hello world 3")
class MessengerUnittest(unittest.TestCase): def test_all(self): pass
2
0
7
0
7
0
1
0
1
1
1
0
1
0
1
73
8
0
8
3
6
0
8
3
6
1
2
0
1
147,840
MacHu-GWU/angora-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_angora-project/angora/hashes/fingerprint.py
angora.hashes.fingerprint.FingerPrintUnittest
class FingerPrintUnittest(unittest.TestCase): def test_hash_anything(self): for algorithm in ["md5", "sha1", "sha224", "sha256", "sha384", "sha512"]: print("\n===%s hash value===" % algorithm) fingerprint.use(algorithm) print(fingerprint.of_bytes(bytes(123))) print(fingerprint.of_text("message")) print(fingerprint.of_pyobj({"key": "value"})) print(fingerprint.of_file("fingerprint.py")) fingerprint.set_return_int(True) for algorithm in ["md5", "sha1", "sha224", "sha256", "sha384", "sha512"]: print("\n===%s hash value===" % algorithm) fingerprint.use(algorithm) print(fingerprint.of_bytes(bytes(123))) print(fingerprint.of_text("message")) print(fingerprint.of_pyobj({"key": "value"})) print(fingerprint.of_file("fingerprint.py"))
class FingerPrintUnittest(unittest.TestCase): def test_hash_anything(self): pass
2
0
19
1
18
0
3
0
1
1
0
0
1
0
1
73
20
1
19
3
17
0
17
3
15
3
2
1
3
147,841
MacHu-GWU/angora-project
MacHu-GWU_angora-project/angora/timelib/timewrapper.py
angora.timelib.timewrapper.TimeWrapper
class TimeWrapper(object): """A time related utility class. **中文文档** "时间包装器"提供了对时间, 日期相关的许多计算操作的函数。能智能的从各种其他 格式的时间中解析出Python datetime.datetime/datetime.date 对象。更多功能请 参考API文档。 """ def __init__(self): self.date_templates = list(_DATE_TEMPLATE.keys()) self.datetime_templates = list(_DATETIME_TEMPLATE.keys()) self.default_date_template = "%Y-%m-%d" # 日期默认模板 self.std_dateformat = "%Y-%m-%d" # 简单标准模板 self.default_datetime_templates = "%Y-%m-%d %H:%M:%S" # 日期时间默认模板 self.std_datetimeformat = "%Y-%m-%d %H:%M:%S" # 简单标准模板 def add_date_template(self, template): """Manually add a date format template so TimeWrapper can recognize it. A better way is to edit the ``_DATETIME_TEMPLATE`` in source code. """ self.date_templates.append(template) def add_datetime_template(self, template): """Manually add a datetime format template. A better way is to edit the ``_DATE_TEMPLATE`` and add it. """ self.datetime_templates.append(template) ########## # Parser # ########## def reformat(self, dtstring, before, after): """Edit the time string format. See https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior for all format string options. **中文文档** 将datetime string从一种格式转换成另一种格式。 """ a_datetime = datetime.strptime(dtstring, before) return datetime.strftime(a_datetime, after) def str2date(self, datestr): """Try parse date from string. If None template matching this datestr, raise Error. :param datestr: a string represent a date :type datestr: str :return: a datetime.date object Usage:: >>> from weatherlab.lib.timelib.timewrapper import timewrapper >>> timewrapper.str2date("12/15/2014") datetime.date(2014, 12, 15) **中文文档** 尝试从字符串中解析出datetime.date对象。每次解析时, 先尝试默认模板, 如果 失败了, 再重新对所有模板进行尝试; 一旦尝试成功, 这将当前成功的模板保存 为默认模板。这样使得尝试的策略最优化。 """ try: return datetime.strptime( datestr, self.default_date_template).date() except: # 如果默认的模板不匹配, 则重新尝试所有的模板 pass # try all date_templates # 对每个template进行尝试, 如果都不成功, 抛出异常 for template in self.date_templates: try: a_datetime = datetime.strptime(datestr, template) # 如果成功了 self.default_date_template = template # 保存为default return a_datetime.date() except: pass raise NoMatchingTemplateError(datestr) def str2datetime(self, datetimestr): """Try parse datetime from string. If None template matching this datestr, raise Error. :param datetimestr: a string represent a datetime :type datetimestr: str :return: a datetime.datetime object Usage:: >>> from weatherlab.lib.timelib.timewrapper import timewrapper >>> timewrapper.str2date("12/15/2014 06:30:00 PM") datetime.datetime(2014, 12, 15, 18, 30) **中文文档** 尝试从字符串中解析出datetime.date对象。每次解析时, 先尝试默认模板, 如果 失败了, 再重新对所有模板进行尝试; 一旦尝试成功, 这将当前成功的模板保存 为默认模板。这样使得尝试的策略最优化。 """ try: return datetime.strptime( datetimestr, self.default_datetime_templates) except: # 如果默认的模板不匹配, 则重新尝试所有的模板 pass # try all datetime_templates # 对每个template进行尝试, 如果都不成功, 抛出异常 for template in self.datetime_templates: try: a_datetime = datetime.strptime( datetimestr, template) # 如果成功了 self.default_datetime_templates = template # 保存为default return a_datetime except: pass raise NoMatchingTemplateError(datetimestr) def std_datestr(self, datestr): """Reformat a date string to standard format. """ return date.strftime( self.str2date(datestr), self.std_dateformat) def std_datetimestr(self, datetimestr): """Reformat a datetime string to standard format. """ return datetime.strftime( self.str2datetime(datetimestr), self.std_datetimeformat) ########################################## # timestamp, toordinary method extension # ########################################## def toordinal(self, date_object): """Calculate number of days from 0000-00-00. """ return date_object.toordinal() def fromordinal(self, days): """Create a date object that number ``days`` of days after 0000-00-00. """ return date.fromordinal(days) def totimestamp(self, datetime_object): """Calculate number of seconds from unix timestamp start point "1969-12-31 19:00:00" Because in python2, datetime module doesn't have timestamp() method, so we have to implement in a python2,3 compatible way. """ return (datetime_object - datetime(1969, 12, 31, 19, 0)).total_seconds() def fromtimestamp(self, timestamp): """Create a datetime object that number ``timestamp`` of seconds after unix timestamp start point "1969-12-31 19:00:00". Because python doesn't support negative timestamp to datetime so we have to implement my own method. """ if timestamp >= 0: return datetime.fromtimestamp(timestamp) else: return datetime(1969, 12, 31, 19, 0) + timedelta(seconds=timestamp) def parse_date(self, value): """A lazy method to parse anything to date. Usage:: >>> from weatherlab.lib.timelib.timewrapper import timewrapper >>> from datetime import datetime >>> timewrapper.parse_date("12/25/1985") datetime.date(1985, 12, 25) >>> timewrapper.parse_date(725000) datetime.date(1985, 12, 25) >>> timewrapper.parse_date(datetime(1985, 12, 25, 8, 30)) datetime.date(1985, 12, 25) """ if isinstance(value, date) and not isinstance(value, datetime): return value elif isinstance(value, str): return self.str2date(value) elif isinstance(value, int): return date.fromordinal(value) elif isinstance(value, datetime): return value.date() else: raise Exception("Unable to parse date from: %s, type<%s>." % ( value, type(value))) def parse_datetime(self, value): """A lazy method to parse anything to datetime. Usage:: >>> from weatherlab.lib.timelib.timewrapper import timewrapper >>> from datetime import date >>> timewrapper.parse_datetime("2001-09-11 10:07:00 AM") datetime.datetime(2001, 9, 11, 10, 7) >>> timewrapper.parse_datetime(1000217220.0) datetime.datetime(2001, 9, 11, 10, 7) >>> timewrapper.parse_datetime(date(2001, 9, 11)) datetime.datetime(2001, 9, 11, 0, 0) """ if isinstance(value, datetime): return value elif isinstance(value, str): return self.str2datetime(value) elif isinstance(value, int): return self.fromtimestamp(value) elif isinstance(value, float): return self.fromtimestamp(value) elif isinstance(value, date): return datetime(value.year, value.month, value.day) else: raise Exception("Unable to parse datetime from: %s, type<%s>." % ( value, type(value))) ############################# # datetime object generator # ############################# def _freq_parser(self, freq): """ day, hour, min, sec, """ freq = freq.lower().strip() try: if "day" in freq: freq = freq.replace("day", "") return timedelta(days=int(freq)) elif "hour" in freq: freq = freq.replace("hour", "") return timedelta(hours=int(freq)) elif "min" in freq: freq = freq.replace("min", "") return timedelta(minutes=int(freq)) elif "sec" in freq: freq = freq.replace("sec", "") return timedelta(seconds=int(freq)) else: raise Exception("%s is invalid format. use day, hour, min, sec." % freq) except: raise Exception("%s is invalid format. use day, hour, min, sec." % freq) def dtime_range(self, start=None, end=None, periods=None, freq="1day", normalize=False, return_date=False): """A pure Python implementation of pandas.date_range(). Given 2 of start, end, periods and freq, generate a series of datetime object. :param start: Left bound for generating dates :type start: str or datetime.datetime (default None) :param end: Right bound for generating dates :type end: str or datetime.datetime (default None) :param periods: Number of date points. If None, must specify start and end :type periods: integer (default None) :param freq: string, default '1day' (calendar daily) Available mode are day, hour, min, sec Frequency strings can have multiples. e.g. '7day', '6hour', '5min', '4sec' :type freq: string (default '1day' calendar daily) :param normalize: Trigger that normalize start/end dates to midnight :type normalize: boolean (default False) :return: A list of datetime.datetime object. An evenly sampled time series. Usage:: >>> from __future__ print_function >>> from weatherlab.lib.timelib.timewrapper import timewrapper >>> for dt in timewrapper.dtime_range("2014-1-1", "2014-1-7"): ... print(dt) 2014-01-01 00:00:00 2014-01-02 00:00:00 2014-01-03 00:00:00 2014-01-04 00:00:00 2014-01-05 00:00:00 2014-01-06 00:00:00 2014-01-07 00:00:00 **中文文档** 生成等间隔的时间序列。 需要给出, "起始", "结束", "数量"中的任意两个。以及指定"频率"。以此唯一 确定一个等间隔时间序列。"频率"项所支持的命令字符有"7day", "6hour", "5min", "4sec" (可以改变数字). """ def normalize_datetime_to_midnight(dtime): """normalize a datetime %Y-%m-%d %H:%M:%S to %Y-%m-%d 00:00:00 """ return datetime(dtime.year, dtime.month, dtime.day) def not_normalize(dtime): """do not normalize """ return dtime time_series = list() # if two of start, end, or periods exist if (bool(start) + bool(end) + bool(periods)) == 2: if normalize: converter = normalize_datetime_to_midnight else: converter = not_normalize interval = self._freq_parser(freq) if (bool(start) & bool(end)): # start and end start = self.parse_datetime(start) end = self.parse_datetime(end) if start > end: # if start time later than end time, raise error raise Exception("start time has to be eariler and equal " "than end time") start = start - interval while 1: start += interval if start <= end: time_series.append( converter(start) ) else: break elif (bool(start) & bool(periods)): # start and periods start = self.parse_datetime(start) start = start - interval for _ in range(periods): start += interval time_series.append( converter(start) ) elif (bool(end) & bool(periods)): # end and periods end = self.parse_datetime(end) start = end - interval * periods for _ in range(periods): start += interval time_series.append( converter(start) ) else: raise Exception("Must specify two of start, end, or periods") if return_date: time_series = [i.date() for i in time_series] return time_series def weekday_series(self, start, end, weekday): """Generate a datetime series with same weekday number. ISO weekday number: Mon = 1, Sun = 7 Usage:: >>> timewrapper.weekday_series( # All Tuesday >>> "2014-01-01 06:30:25", "2014-02-01 06:30:25", weekday=2), [ datetime(2014, 1, 7, 6, 30, 25), datetime(2014, 1, 14, 6, 30, 25), datetime(2014, 1, 21, 6, 30, 25), datetime(2014, 1, 28, 6, 30, 25), ] **中文文档** 生成星期数一致的时间序列。 """ startdatetime = self.parse_datetime(start) enddatetime = self.parse_datetime(end) series = list() for i in self.dtime_range(startdatetime, enddatetime, freq="1day"): if i.isoweekday() == weekday: series.append(i) return series """ 在数据库中, 我们经常需要使用: SELECT * FROM tablename WHERE create_datetime BETWEEN 'start' and 'end'; 为了方便, 我们提供了day_interval, month_interval, year_interval三个函数能够 方便地生成start和end日期字符串。例如: >>> timewrapper.month_interval(2014, 3, return_str=True) ("2014-03-01 00:00:00", "2014-03-31 23:59:59") """ @staticmethod def day_interval(year, month, day, return_str=False): """ Usage Example:: >>> timewrapper.day_interval(2014, 3, 1) (datetime(2014, 3, 1, 0, 0, 0), datetime(2014, 3, 1, 23, 59, 59)) """ start, end = datetime(year, month, day), datetime(year, month, day) + timedelta(days=1) - timedelta(seconds=1) if not return_str: return start, end else: return str(start), str(end) @staticmethod def month_interval(year, month, return_str=False): """ Usage Example:: >>> timewrapper.day_interval(2014, 12) (datetime(2014, 12, 1, 0, 0, 0), datetime(2014, 12, 31, 23, 59, 59)) """ if month == 12: start, end = datetime(year, month, 1), datetime(year+1, 1, 1) - timedelta(seconds=1) else: start, end = datetime(year, month, 1), datetime(year, month+1, 1) - timedelta(seconds=1) if not return_str: return start, end else: return str(start), str(end) @staticmethod def year_interval(year, return_str=False): """ Usage Example:: >>> timewrapper.day_interval(2014) (datetime(2014, 1, 1, 0, 0, 0), datetime(2014, 12, 31, 23, 59, 59)) """ start, end = datetime(year, 1, 1), datetime(year+1, 1, 1) - timedelta(seconds=1) if not return_str: return start, end else: return str(start), str(end) ################################### # random datetime, date generator # ################################### def randdate(self, start=date(1970, 1, 1), end=date.today()): """Generate a random date between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.date, (default date(1970, 1, 1)) :param end: Right bound :type end: string or datetime.date, (default date.today()) :return: a datetime.date object **中文文档** 随机生成一个位于 ``start`` 和 ``end`` 之间的日期。 """ if isinstance(start, str): start = self.str2date(start) if isinstance(end, str): end = self.str2date(end) if start > end: raise Exception("start must be smaller than end! " "your start=%s, end=%s" % (start, end)) return date.fromordinal(random.randint(start.toordinal(), end.toordinal())) def randdatetime(self, start=datetime(1970,1,1), end=datetime.now()): """Generate a random datetime between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.datetime, (default datetime(1970, 1, 1)) :param end: Right bound :type end: string or datetime.datetime, (default datetime.now()) :return: a datetime.datetime object **中文文档** 随机生成一个位于 ``start`` 和 ``end`` 之间的时间。 """ if isinstance(start, str): start = self.str2datetime(start) if isinstance(end, str): end = self.str2datetime(end) if start > end: raise Exception("start must be smaller than end! your start=%s, end=%s" % (start, end)) return datetime.fromtimestamp(random.randint(self.totimestamp(start), self.totimestamp(end))) def add_seconds(self, datetimestr, n): """Returns a time that n seconds after a time. :param datetimestr: a datetime object or a datetime str :param n: number of seconds, value can be negative **中文文档** 返回给定日期N秒之后的时间。 """ a_datetime = self.parse_datetime(datetimestr) return a_datetime + timedelta(seconds=n) def add_minutes(self, datetimestr, n): """Returns a time that n minutes after a time. :param datetimestr: a datetime object or a datetime str :param n: number of minutes, value can be negative **中文文档** 返回给定日期N分钟之后的时间。 """ a_datetime = self.parse_datetime(datetimestr) return a_datetime + timedelta(seconds=60*n) def add_hours(self, datetimestr, n): """Returns a time that n hours after a time. :param datetimestr: a datetime object or a datetime str :param n: number of hours, value can be negative **中文文档** 返回给定日期N小时之后的时间。 """ a_datetime = self.parse_datetime(datetimestr) return a_datetime + timedelta(seconds=3600*n) def add_days(self, datetimestr, n, return_date=False): """Returns a time that n days after a time. :param datetimestr: a datetime object or a datetime str :param n: number of days, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N天之后的时间。 """ a_datetime = self.parse_datetime(datetimestr) a_datetime += timedelta(days=n) if return_date: return a_datetime.date() else: return a_datetime def add_weeks(self, datetimestr, n, return_date=False): """Returns a time that n weeks after a time. :param datetimestr: a datetime object or a datetime str :param n: number of weeks, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N周之后的时间。 """ a_datetime = self.parse_datetime(datetimestr) a_datetime += timedelta(days=7*n) if return_date: return a_datetime.date() else: return a_datetime def add_months(self, datetimestr, n, return_date=False): """Returns a time that n months after a time. Notice: for example, the date that one month after 2015-01-31 supposed to be 2015-02-31. But there's no 31th in Feb, so we fix that value to 2015-02-28. :param datetimestr: a datetime object or a datetime str :param n: number of months, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N月之后的时间。 """ a_datetime = self.parse_datetime(datetimestr) month_from_ordinary = a_datetime.year * 12 + a_datetime.month month_from_ordinary += n year, month = divmod(month_from_ordinary, 12) try: a_datetime = datetime(year, month, a_datetime.day, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond) except ValueError: a_datetime = datetime(year, month+1, 1, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond) a_datetime = self.add_days(a_datetime, -1) if return_date: return a_datetime.date() else: return a_datetime def add_years(self, datetimestr, n, return_date=False): """Returns a time that n years after a time. :param datetimestr: a datetime object or a datetime str :param n: number of years, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N年之后的时间。 """ a_datetime = self.parse_datetime(datetimestr) try: a_datetime = datetime( a_datetime.year + n, a_datetime.month, a_datetime.day, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond) except: a_datetime = datetime( a_datetime.year + n, 2, 28, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond) if return_date: return a_datetime.date() else: return a_datetime def round_to_specified_time(self, a_datetime, hour, minute, second, mode="lower"): """Round the given datetime to specified hour, minute and second. :param mode: if 'lower', floor to. if 'upper', ceiling to. **中文文档** 将给定时间对齐到最近的一个指定了小时, 分钟, 秒的时间上。 """ mode = mode.lower() new_datetime = datetime(a_datetime.year, a_datetime.month, a_datetime.day, hour, minute, second) if mode == "lower": if new_datetime <= a_datetime: return new_datetime else: return timewrapper.add_days(new_datetime, -1) elif mode == "upper": if new_datetime >= a_datetime: return new_datetime else: return timewrapper.add_days(new_datetime, 1) else: raise ValueError("'mode' has to be lower or upper!")
class TimeWrapper(object): '''A time related utility class. **中文文档** "时间包装器"提供了对时间, 日期相关的许多计算操作的函数。能智能的从各种其他 格式的时间中解析出Python datetime.datetime/datetime.date 对象。更多功能请 参考API文档。 ''' def __init__(self): pass def add_date_template(self, template): '''Manually add a date format template so TimeWrapper can recognize it. A better way is to edit the ``_DATETIME_TEMPLATE`` in source code. ''' pass def add_datetime_template(self, template): '''Manually add a datetime format template. A better way is to edit the ``_DATE_TEMPLATE`` and add it. ''' pass def reformat(self, dtstring, before, after): '''Edit the time string format. See https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior for all format string options. **中文文档** 将datetime string从一种格式转换成另一种格式。 ''' pass def str2date(self, datestr): '''Try parse date from string. If None template matching this datestr, raise Error. :param datestr: a string represent a date :type datestr: str :return: a datetime.date object Usage:: >>> from weatherlab.lib.timelib.timewrapper import timewrapper >>> timewrapper.str2date("12/15/2014") datetime.date(2014, 12, 15) **中文文档** 尝试从字符串中解析出datetime.date对象。每次解析时, 先尝试默认模板, 如果 失败了, 再重新对所有模板进行尝试; 一旦尝试成功, 这将当前成功的模板保存 为默认模板。这样使得尝试的策略最优化。 ''' pass def str2datetime(self, datetimestr): '''Try parse datetime from string. If None template matching this datestr, raise Error. :param datetimestr: a string represent a datetime :type datetimestr: str :return: a datetime.datetime object Usage:: >>> from weatherlab.lib.timelib.timewrapper import timewrapper >>> timewrapper.str2date("12/15/2014 06:30:00 PM") datetime.datetime(2014, 12, 15, 18, 30) **中文文档** 尝试从字符串中解析出datetime.date对象。每次解析时, 先尝试默认模板, 如果 失败了, 再重新对所有模板进行尝试; 一旦尝试成功, 这将当前成功的模板保存 为默认模板。这样使得尝试的策略最优化。 ''' pass def std_datestr(self, datestr): '''Reformat a date string to standard format. ''' pass def std_datetimestr(self, datetimestr): '''Reformat a datetime string to standard format. ''' pass def toordinal(self, date_object): '''Calculate number of days from 0000-00-00. ''' pass def fromordinal(self, days): '''Create a date object that number ``days`` of days after 0000-00-00. ''' pass def totimestamp(self, datetime_object): '''Calculate number of seconds from unix timestamp start point "1969-12-31 19:00:00" Because in python2, datetime module doesn't have timestamp() method, so we have to implement in a python2,3 compatible way. ''' pass def fromtimestamp(self, timestamp): '''Create a datetime object that number ``timestamp`` of seconds after unix timestamp start point "1969-12-31 19:00:00". Because python doesn't support negative timestamp to datetime so we have to implement my own method. ''' pass def parse_date(self, value): '''A lazy method to parse anything to date. Usage:: >>> from weatherlab.lib.timelib.timewrapper import timewrapper >>> from datetime import datetime >>> timewrapper.parse_date("12/25/1985") datetime.date(1985, 12, 25) >>> timewrapper.parse_date(725000) datetime.date(1985, 12, 25) >>> timewrapper.parse_date(datetime(1985, 12, 25, 8, 30)) datetime.date(1985, 12, 25) ''' pass def parse_datetime(self, value): '''A lazy method to parse anything to datetime. Usage:: >>> from weatherlab.lib.timelib.timewrapper import timewrapper >>> from datetime import date >>> timewrapper.parse_datetime("2001-09-11 10:07:00 AM") datetime.datetime(2001, 9, 11, 10, 7) >>> timewrapper.parse_datetime(1000217220.0) datetime.datetime(2001, 9, 11, 10, 7) >>> timewrapper.parse_datetime(date(2001, 9, 11)) datetime.datetime(2001, 9, 11, 0, 0) ''' pass def _freq_parser(self, freq): ''' day, hour, min, sec, ''' pass def dtime_range(self, start=None, end=None, periods=None, freq="1day", normalize=False, return_date=False): '''A pure Python implementation of pandas.date_range(). Given 2 of start, end, periods and freq, generate a series of datetime object. :param start: Left bound for generating dates :type start: str or datetime.datetime (default None) :param end: Right bound for generating dates :type end: str or datetime.datetime (default None) :param periods: Number of date points. If None, must specify start and end :type periods: integer (default None) :param freq: string, default '1day' (calendar daily) Available mode are day, hour, min, sec Frequency strings can have multiples. e.g. '7day', '6hour', '5min', '4sec' :type freq: string (default '1day' calendar daily) :param normalize: Trigger that normalize start/end dates to midnight :type normalize: boolean (default False) :return: A list of datetime.datetime object. An evenly sampled time series. Usage:: >>> from __future__ print_function >>> from weatherlab.lib.timelib.timewrapper import timewrapper >>> for dt in timewrapper.dtime_range("2014-1-1", "2014-1-7"): ... print(dt) 2014-01-01 00:00:00 2014-01-02 00:00:00 2014-01-03 00:00:00 2014-01-04 00:00:00 2014-01-05 00:00:00 2014-01-06 00:00:00 2014-01-07 00:00:00 **中文文档** 生成等间隔的时间序列。 需要给出, "起始", "结束", "数量"中的任意两个。以及指定"频率"。以此唯一 确定一个等间隔时间序列。"频率"项所支持的命令字符有"7day", "6hour", "5min", "4sec" (可以改变数字). ''' pass def normalize_datetime_to_midnight(dtime): '''normalize a datetime %Y-%m-%d %H:%M:%S to %Y-%m-%d 00:00:00 ''' pass def not_normalize(dtime): '''do not normalize ''' pass def weekday_series(self, start, end, weekday): '''Generate a datetime series with same weekday number. ISO weekday number: Mon = 1, Sun = 7 Usage:: >>> timewrapper.weekday_series( # All Tuesday >>> "2014-01-01 06:30:25", "2014-02-01 06:30:25", weekday=2), [ datetime(2014, 1, 7, 6, 30, 25), datetime(2014, 1, 14, 6, 30, 25), datetime(2014, 1, 21, 6, 30, 25), datetime(2014, 1, 28, 6, 30, 25), ] **中文文档** 生成星期数一致的时间序列。 ''' pass @staticmethod def day_interval(year, month, day, return_str=False): ''' Usage Example:: >>> timewrapper.day_interval(2014, 3, 1) (datetime(2014, 3, 1, 0, 0, 0), datetime(2014, 3, 1, 23, 59, 59)) ''' pass @staticmethod def month_interval(year, month, return_str=False): ''' Usage Example:: >>> timewrapper.day_interval(2014, 12) (datetime(2014, 12, 1, 0, 0, 0), datetime(2014, 12, 31, 23, 59, 59)) ''' pass @staticmethod def year_interval(year, return_str=False): ''' Usage Example:: >>> timewrapper.day_interval(2014) (datetime(2014, 1, 1, 0, 0, 0), datetime(2014, 12, 31, 23, 59, 59)) ''' pass def randdate(self, start=date(1970, 1, 1), end=date.today()): '''Generate a random date between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.date, (default date(1970, 1, 1)) :param end: Right bound :type end: string or datetime.date, (default date.today()) :return: a datetime.date object **中文文档** 随机生成一个位于 ``start`` 和 ``end`` 之间的日期。 ''' pass def randdatetime(self, start=datetime(1970,1,1), end=datetime.now()): '''Generate a random datetime between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.datetime, (default datetime(1970, 1, 1)) :param end: Right bound :type end: string or datetime.datetime, (default datetime.now()) :return: a datetime.datetime object **中文文档** 随机生成一个位于 ``start`` 和 ``end`` 之间的时间。 ''' pass def add_seconds(self, datetimestr, n): '''Returns a time that n seconds after a time. :param datetimestr: a datetime object or a datetime str :param n: number of seconds, value can be negative **中文文档** 返回给定日期N秒之后的时间。 ''' pass def add_minutes(self, datetimestr, n): '''Returns a time that n minutes after a time. :param datetimestr: a datetime object or a datetime str :param n: number of minutes, value can be negative **中文文档** 返回给定日期N分钟之后的时间。 ''' pass def add_hours(self, datetimestr, n): '''Returns a time that n hours after a time. :param datetimestr: a datetime object or a datetime str :param n: number of hours, value can be negative **中文文档** 返回给定日期N小时之后的时间。 ''' pass def add_days(self, datetimestr, n, return_date=False): '''Returns a time that n days after a time. :param datetimestr: a datetime object or a datetime str :param n: number of days, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N天之后的时间。 ''' pass def add_weeks(self, datetimestr, n, return_date=False): '''Returns a time that n weeks after a time. :param datetimestr: a datetime object or a datetime str :param n: number of weeks, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N周之后的时间。 ''' pass def add_months(self, datetimestr, n, return_date=False): '''Returns a time that n months after a time. Notice: for example, the date that one month after 2015-01-31 supposed to be 2015-02-31. But there's no 31th in Feb, so we fix that value to 2015-02-28. :param datetimestr: a datetime object or a datetime str :param n: number of months, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N月之后的时间。 ''' pass def add_years(self, datetimestr, n, return_date=False): '''Returns a time that n years after a time. :param datetimestr: a datetime object or a datetime str :param n: number of years, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N年之后的时间。 ''' pass def round_to_specified_time(self, a_datetime, hour, minute, second, mode="lower"): '''Round the given datetime to specified hour, minute and second. :param mode: if 'lower', floor to. if 'upper', ceiling to. **中文文档** 将给定时间对齐到最近的一个指定了小时, 分钟, 秒的时间上。 ''' pass
36
32
19
3
8
8
3
1
1
13
1
0
27
6
30
30
660
133
271
69
234
270
216
65
183
12
1
4
86
147,842
MacHu-GWU/angora-project
MacHu-GWU_angora-project/angora/timelib/timewrapper.py
angora.timelib.timewrapper.NoMatchingTemplateError
class NoMatchingTemplateError(Exception): """Used in TimeWrapper.str2date, TimeWrapper.str2datetime. Raised when no template matched the string we want to parse. """ def __init__(self, pattern): self.pattern = pattern def __str__(self): return "None template matching '%s'" % self.pattern
class NoMatchingTemplateError(Exception): '''Used in TimeWrapper.str2date, TimeWrapper.str2datetime. Raised when no template matched the string we want to parse. ''' def __init__(self, pattern): pass def __str__(self): pass
3
1
2
0
2
0
1
0.6
1
0
0
0
2
1
2
12
9
1
5
4
2
3
5
4
2
1
3
0
2
147,843
MacHu-GWU/angora-project
MacHu-GWU_angora-project/angora/markup/rst.py
angora.markup.rst.RstConstructor
class RstConstructor(object): """reConstructed Text snippet constructor. """ def header(self, title, level, key, width=80): """Example:: .. _header_2: Header 2 ------------------------------------------------------------------- **中文文档** """ linestyle_code = {1: "=", 2: "-", 3: "~"} if level not in linestyle_code: raise Exception("'level' argument has to be 1, 2 or 3") else: linestyle = linestyle_code[level] if key: return "\n".join([".. _%s" % key, "", title, linestyle * width]) else: return "\n".join([title, "=" * width]) def reference(self, text, key): """Example:: `Go to section 2 <section_2_>`_ """ return "`{text} <{key}_>`_".format(text=text, key=key) def urllink(self, text, url): """Example:: `Google Homepage <https://www.google.com/>`_ """ return "`{text} <{url}>`_".format(text=text, url=url) def bullet_list(self, text): """Example:: - item """ return "- {text}".format(text=text) def enumerated_list(self, nth, text): """Example:: 1. item """ if not isinstance(nth, int): raise Exception("'nth' argument has to be an integer!") return "{nth}. {text}".format(nth=nth, text=text) def code_block(self, code, language, indent=0): """Example:: .. code-block:: python from __future__ import print_function import math print(math.sqrt(10.0)) """ if language not in [None, "console", "python", "ruby", "c"]: raise prefix = "\t" * indent code_prefix = "\t" * (indent + 1) lines = list() lines.append(prefix + ".. code-block:: %s" % language) lines.append(prefix) for line in code.split("\n"): lines.append(code_prefix + line.strip()) return "\n".join(lines) def table(self, data, header=None): """Example:: +----------+------------+ | CityName | Population | +----------+------------+ | Adelaide | 1158259 | +----------+------------+ | Darwin | 120900 | +----------+------------+ """ if header: x = PrettyTable(header) else: x = PrettyTable() # construct ascii text table, split header and body for row in data: x.add_row(row) s = x.get_string(border=True) lines = s.split("\n") header_ = lines[:2] body = lines[2:] n_body = len(body) ruler = body[0] # add more rulers between each rows new_body = list() counter = 0 for line in body: counter += 1 new_body.append(line) if (2 <= counter) and (counter < (n_body - 1)): new_body.append(ruler) if header: return "\n".join(header_ + new_body) else: return "\n".join(new_body)
class RstConstructor(object): '''reConstructed Text snippet constructor. ''' def header(self, title, level, key, width=80): '''Example:: .. _header_2: Header 2 ------------------------------------------------------------------- **中文文档** ''' pass def reference(self, text, key): '''Example:: `Go to section 2 <section_2_>`_ ''' pass def urllink(self, text, url): '''Example:: `Google Homepage <https://www.google.com/>`_ ''' pass def bullet_list(self, text): '''Example:: - item ''' pass def enumerated_list(self, nth, text): '''Example:: 1. item ''' pass def code_block(self, code, language, indent=0): '''Example:: .. code-block:: python from __future__ import print_function import math print(math.sqrt(10.0)) ''' pass def table(self, data, header=None): '''Example:: +----------+------------+ | CityName | Population | +----------+------------+ | Adelaide | 1158259 | +----------+------------+ | Darwin | 120900 | +----------+------------+ ''' pass
8
8
15
2
8
5
2
0.66
1
3
0
0
7
0
7
7
115
22
56
25
48
37
52
25
44
6
1
2
17
147,844
MacHu-GWU/angora-project
MacHu-GWU_angora-project/angora/hashes/fingerprint.py
angora.hashes.fingerprint.WrongHashAlgorithmError
class WrongHashAlgorithmError(Exception): pass
class WrongHashAlgorithmError(Exception): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
1
1
0
2
1
1
0
3
0
0
147,845
MacHu-GWU/angora-project
MacHu-GWU_angora-project/angora/baseclass/classtree.py
angora.baseclass.classtree.Base
class Base(nameddict.Base): """ """ def _getattr_by_key_value(self, key): def getattr_by_key_value(value): return getattr(self, "%s____%s" % (key, value)) return getattr_by_key_value def __getattr__(self, attr): if attr.startswith("getattr_by_"): key = attr.replace("getattr_by_", "") return self._getattr_by_key_value(key) else: return object.__getattribute__(self, attr) def keys(self): return [key for key, value in self.items()] def values(self): return [value for key, value in self.items()] def items(self): items = list() for attr, value in self.__dict__.items(): if "____" not in attr: items.append((attr, value)) return sorted(items, key=lambda x: x[0]) def to_dict(self): return self.__dict__ def serialize(self): d = {"classname": self.__class__.__name__, "metadata": dict()} uuid_set = set() for attr, value in self.items(): if "____" not in attr: d["metadata"][attr] = value else: _id = id(value) if _id not in uuid_set: try: d["subclass"].append(value.serialize()) except: d["subclass"] = [value.serialize(),] uuid_set.add(_id) return d
class Base(nameddict.Base): ''' ''' def _getattr_by_key_value(self, key): pass def getattr_by_key_value(value): pass def __getattr__(self, attr): pass def keys(self): pass def values(self): pass def items(self): pass def to_dict(self): pass def serialize(self): pass
9
1
5
0
5
0
2
0.05
1
3
0
0
7
0
7
14
46
6
38
18
29
2
36
16
27
5
2
4
15
147,846
MacHu-GWU/angora-project
MacHu-GWU_angora-project/angora/markup/html.py
angora.markup.html.HtmlConstructor
class HtmlConstructor(object): tab = " " def input_text(self, name, size=30): """ """ return '<input type="text" name="%s" size="%s" value="{{%s}}" />' % (name, size, name) def input_number(self, name, size=30): return '<input type="number" name="%s" size="%s" value="{{%s}}" />' % (name, size, name) def input_float(self, name, precision=2, size=30): if precision == 0: step = 1 else: step = "0.%s1" % ("0" * (precision - 1)) return '<input type="number" step="%s" name="%s" size="%s" value="{{%s}}" />' % (step, name, size, name) def input_date(self, name, size=30): return '<input type="date" name="%s" size="%s" value="{{%s}}" />' % (name, size, name) def input_time(self, name, size=30): return '<input type="time" name="%s" size="%s" value="{{%s}}" />' % (name, size, name) def input_ratio(self, name, choices, labels, multi_line=False): """ {% for value, label in [('choice1', '选项1'), ('choice2', '选项2')] %} {% if ratio == value %} {% set checked = "checked" %} {% else %} {% set checked = "" %} {% endif %} <input type="radio" name="ratio" value="{{value}}" {{checked}} /> {{label}} {% endfor %} """ if len(choices) != len(labels): raise ValueError("The size of 'choices' and 'labels' doesn't match!") choice_label = list(zip(choices, labels)) lines = list() lines.append('{%% for value, label in %s %%}' % repr(choice_label)) lines.append(self.tab + '{%% if %s == value %%}' % name) lines.append(self.tab * 2 + '{% set checked = "checked" %}') lines.append(self.tab + '{% else %}') lines.append(self.tab * 2 + '{% set checked = "" %}') lines.append(self.tab + '{% endif %}') if multi_line: line_break = "<br>" else: line_break = "" lines.append(self.tab + '<input type="radio" name="%s" value="{{value}}" {{checked}} /> {{label}} %s' % (name, line_break)) lines.append('{% endfor %}') return "\n".join(lines) def input_check(self, name, label, multi_line=False): """ {% if multiple_choice_1 %} {% set checked = "checked" %} {% else %} {% set checked = "" %} {% endif %} <input type="checkbox" name="multiple_choice_1" value="multiple_choice_1" {{checked}}> multiple_choice_1 """ lines = list() lines.append('{%% if %s %%}' % name) lines.append(self.tab + '{% set checked = "checked" %}') lines.append('{% else %}') lines.append(self.tab + '{% set checked = "" %}') lines.append('{% endif %}') if multi_line: line_break = "<br>" else: line_break = "" lines.append('<input type="checkbox" name="%s" value="%s" {{checked}}> %s %s' % (name, name, label, line_break)) return "\n".join(lines) def input_textarea(self, name, form_id, rows=4, cols=50): return '<textarea name="%s" rows="%s" cols="%s" form="%s">{{%s}}</textarea>' % ( name, rows, cols, form_id, name)
class HtmlConstructor(object): def input_text(self, name, size=30): ''' ''' pass def input_number(self, name, size=30): pass def input_float(self, name, precision=2, size=30): pass def input_date(self, name, size=30): pass def input_time(self, name, size=30): pass def input_ratio(self, name, choices, labels, multi_line=False): ''' {% for value, label in [('choice1', '选项1'), ('choice2', '选项2')] %} {% if ratio == value %} {% set checked = "checked" %} {% else %} {% set checked = "" %} {% endif %} <input type="radio" name="ratio" value="{{value}}" {{checked}} /> {{label}} {% endfor %} ''' pass def input_check(self, name, label, multi_line=False): ''' {% if multiple_choice_1 %} {% set checked = "checked" %} {% else %} {% set checked = "" %} {% endif %} <input type="checkbox" name="multiple_choice_1" value="multiple_choice_1" {{checked}}> multiple_choice_1 ''' pass def input_textarea(self, name, form_id, rows=4, cols=50): pass
9
3
9
0
6
3
2
0.4
1
3
0
0
8
0
8
8
80
10
50
16
41
20
46
16
37
3
1
1
12
147,847
MacHu-GWU/angora-project
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/MacHu-GWU_angora-project/angora/baseclass/classtree.py
angora.baseclass.classtree.Unittest.test_all.Person
class Person(classtree.Base): def __init__(self, name=None, person_id=None): self.name = name self.person_id = person_id
class Person(classtree.Base): def __init__(self, name=None, person_id=None): pass
2
0
3
0
3
0
1
0
1
0
0
0
1
2
1
1
4
0
4
4
2
0
4
4
2
1
1
0
1