Esempio n. 1
0
def get_angle_from_frame(vector, frame, type):
    """
    Calculates pitch or yaw angle of a vector in a given reference frame.
       
    :param vector: XYZ vector 
    :param frame: 3x3 matrix of unit basis vectors given row-wise in the
        following order:
            * local "up" (direction of zero pitch)
            * local "north" (direction of 90 degree yaw)
            * local "east" (direction of zero yaw)
    :param type: string, either 'pitch' or 'yaw'
    :return: requested angle in degrees
    """

    vector = unit(vector)
    if type == 'pitch':
        angle = safe_acosd(np.vdot(vector, frame[0]))
    elif type == 'yaw':
        inplane = vector - frame[0] * np.vdot(vector, frame[0])
        inplane = unit(inplane)
        angle = safe_acosd(np.vdot(inplane, frame[2]))
        # correct for direction of the angle
        tangential = np.cross(frame[0], frame[2])
        if np.vdot(inplane, tangential) < 0:
            angle = -angle
    else:
        print('Unknown parameter (get_angle_from_frame).\n')
        angle = 0

    if abs(np.imag(angle)) > 0:
        print('-')
    return angle
Esempio n. 2
0
def gen_clock(bus_params):
    '''Returns a string that uses params to specify a clock signal'''

    logging.info('Generating clock signal')

    bittime = unit(bus_params['bittime'])

    if bus_params['clockrisefall']:
        clockrisefall = unit(bus_params['clockrisefall'])
    else:
        clockrisefall = unit(bus_params['risefall'])

    # Write these values back into params to ease string formatting
    bus_params['clockhigh'] = D('0.5') * (bittime - clockrisefall)
    bus_params['clockperiod'] = bittime + 2 * clockrisefall

    if bus_params['clockdelay']:
        clockdelay = bus_params['clockdelay']
    else:
        # No clockdelay specified - set the clock such that input changes will
        # occur in the middle of the clock bit
        clockdelay = D('0.25') * bittime

    if bus_params['edge'] == 'rising':
        logging.debug('Generating clock for rising active edge')
        clk = 'Vclock clock 0 PULSE(%(bitlow)s %(bithigh)s %(clockdelay)s %(clockrisefall)s %(clockrisefall)s %(clockhigh)s %(clockperiod)s)\n' % bus_params
    elif bus_params['edge'] == 'falling':
        logging.debug('Generating clock for falling active edge')
        clk = 'Vclock clock 0 PULSE(%(bithigh)s %(bitlow)s %(clockdelay)s %(clockrisefall)s %(clockrisefall)s %(clockhigh)s %(clockperiod)s)\n' % bus_params
    else:
        raise ValueError('Invalid clock edge specified: {}'.\
                format(params['edge']))
    return clk
Esempio n. 3
0
    def __init__(self,id=None,name=None,brand=None,model=None,
            operating_cost=0,width=None,length=None,
            uses_media_roll=True,
            margin_top=0,margin_right=0,margin_bottom=0,margin_left=0,
            blade_offset=unit(.25,'mm'),
            blade_overcut=unit(2,'mm'),
            calibration_x=1,calibration_y=1,command_language='HPGL',
            command_buffer=8,command_method=None,command_port=None,
            command_baudrate=9600,command_parity='None',
            command_stopbits=1,command_bytesize=8,command_xonxoff=False,
            command_rtscts=False,command_dsrdtr=False,
            command_use_software=False,velocity_min=None,
            velocity_max=None,velocity=None,force_min=None,
            force_max=None,force=None,
        ):
        """
        Create a device instance with it's properties.
        """
        self.id = id
        self.name = name
        self.brand = brand
        self.model = model
        self.operating_cost = operating_cost

        self.width = width
        self.length = length
        self.uses_media_roll = uses_media_roll
        self.margin_top = margin_top
        self.margin_right = margin_right
        self.margin_bottom = margin_bottom
        self.margin_left = margin_left
        self.blade_offset = blade_offset
        self.blade_overcut = blade_overcut
        self.calibration_x = calibration_x
        self.calibration_y = calibration_y

        self.command_language = command_language
        self.command_buffer = command_buffer
        self.command_method = command_method

        self.command_port = command_port
        self.command_baudrate = command_baudrate
        self.command_parity = command_parity
        self.command_stopbits = command_stopbits
        self.command_bytesize = command_bytesize
        self.command_xonxoff = command_xonxoff
        self.command_rtscts = command_rtscts
        self.command_dsrdtr = command_dsrdtr

        self.command_use_software = command_use_software
        self.velocity_min = velocity_min
        self.velocity_max = velocity_max
        self.velocity = velocity
        self.force_min = force_min
        self.force_max = force_max
        self.force = force
Esempio n. 4
0
 def from_state(cls, mu, state, target, theta):
     rd = target.radius * unit(
         rodrigues(state.radius, -target.normal, theta)
     )  # The idea here is that we want to be in orbit after rotating 20 degrees about the planet
     rgrav = -0.5 * mu * unit(state.radius) / np.linalg.norm(
         state.radius)**3
     vgo = target.velocity * unit(np.cross(-target.normal,
                                           rd)) - state.velocity
     return UPEGState(CSERState(0, 0, 0, 0, 0), np.array([0, 0, 0]), rd,
                      rgrav, 0, state.time, 0, state.velocity, vgo)
Esempio n. 5
0
def get_navball_frame(r):
    # pass current position under r (1x3)
    up = unit(r)  # true Up direction (radial away from Earth)
    east = np.cross(np.array([0, 0, 1]), up)  # true East direction
    north = np.cross(up, east)  # true North direction (completes frame)
    f = [None] * 3
    # return a right-handed coordinate system base
    f[0] = up
    f[1] = unit(north)
    f[2] = unit(east)
    return f
Esempio n. 6
0
def get_circum_frame(r, v):
    # pass current position under r (1x3)
    # current velocity under v (1x3)
    radial = unit(r)  # Up direction (radial away from Earth)
    normal = unit(np.cross(
        r, v))  # Normal direction (perpendicular to orbital plane)
    circum = np.cross(
        normal, radial
    )  # Circumferential direction (tangential to sphere, in motion plane)
    f = [None] * 3
    # return a left(?)-handed coordinate system base
    f[0] = radial
    f[1] = normal
    f[2] = circum
    return f
Esempio n. 7
0
    def __init__(self):
        random.seed(None)

        self.window_size = WINDOW_SIZE
        self.map_size = MAP_SIZE
        self.size = coord.Coord(x=1.0 / self.map_size.x,
                                y=1.0 / self.map_size.y)

        #self.tiles = {}
        #for y in range(self.map_size.y):
        #	for x in range(self.map_size.x):
        #		ttex = 0
        #		tx = x if TILE_TYPE == tile.RECT else (x + (0.5 if y%2 == 0 else 0.0))
        #		ty = y
        #		tloc = coord.Coord(x=tx, y=ty)
        #		tweight = random.randint(RANDRANGE[0], RANDRANGE[1])
        #		#self.tiles.append(tile.tile(tx, ty, ttex, TILE_TYPE, tweight))
        #		self.tiles[tloc] = tile.tile(tx, ty, ttex, TILE_TYPE, tweight)

        coordFactory = map.RectCoordFactory(MAP_SIZE)
        dataFactory = map.RandDataFactory(RANDRANGE)
        self.map = map.Map(coordFactory, dataFactory)

        self.init_window()
        self.init_callback()
        tex.init()
        self.units = {
            coord.Coord(x=0, y=0):
            unit.unit(coord.Coord(x=0, y=0), g_texnames.index("unit"),
                      2),  # * sum(RANDRANGE)/2),
            coord.Coord(x=4, y=6):
            unit.unit(coord.Coord(x=4, y=6), g_texnames.index("unit"),
                      4),  # * sum(RANDRANGE)/2),
            coord.Coord(x=3, y=6):
            unit.unit(coord.Coord(x=3, y=6), g_texnames.index("unit"),
                      1),  # * sum(RANDRANGE)/2),
            coord.Coord(x=3, y=5):
            unit.unit(coord.Coord(x=3, y=5), g_texnames.index("unit"),
                      0),  # * sum(RANDRANGE)/2)
        }
        self.selected = None
        self.mouseloc = None
        self.wmouseloc = None
        self.tooltip = tooltips.tooltip(1.0)
        self.tooltip.start()
        self.path = None
        self.pathtex = None
        self.myfps = fps.fps()
Esempio n. 8
0
    def check_collision(self, target_unit):
        # 返回相遇对象,否则返回None
        # 注:这里最好只检查面前,以减少计算量并且避免BUG
        # 方向可以通过 unit.flag 判断
        pos = target_unit.pos
        game_statue = 'running'
        rag = target_unit.range if target_unit.flag == 'left' else -target_unit.range

        def is_in_range(a, b, c):
            if a < b:
                return a < c < b
            else:
                return b < c < a

        for i in self.unit_list:
            # 判定碰撞
            if i.flag != target_unit.flag and i.pos[1] == pos[1] \
                    and is_in_range(pos[0], pos[0] + rag, i.pos[0]):
                return i, game_statue

        base_flag = 'left' if 'right' == target_unit.flag else 'right'
        # 与基地发生碰撞
        if is_in_range(pos[0], pos[0] + rag, self.base[base_flag].pos):
            # 游戏状态 right_win, left_win
            if target_unit.now_interval == target_unit.attack_interval:
                game_statue = self.base[base_flag].loss_HP(target_unit)
            return unit(100, 10, (0, 0), -1, 10, base_flag), game_statue

        return None, game_statue
Esempio n. 9
0
    def __init__(self):
        const.__init__(self,'physical');

        self.unit = unit.unit('physical.')
        self.units = self.unit

        self.constant = constant.constant('physical.', self.units)
        self.constants = self.constant

        self.element = element.element('physical.', self.constants, self.units)
        self.elements = self.element


        # do some trickery to get modules set to instantiated classes
        self.unit.__name__ = unit.__name__
        sys.modules[unit.__name__]=self.unit
        sys.modules[units.__name__]=self.unit

        self.constant.__name__ = constant.__name__
        sys.modules[constant.__name__]=self.constant
        sys.modules[constants.__name__]=self.constant

        self.element.__name__ = element.__name__
        sys.modules[element.__name__]=self.element
        sys.modules[elements.__name__]=self.element

        # add in the license file
        self.license = license

        # copy over the Quantity module so that the user can reference it.
        self.base = Quantity
Esempio n. 10
0
    def __init__(self):
        const.__init__(self, "physical")

        self.unit = unit.unit("physical.")
        self.units = self.unit

        self.constant = constant.constant("physical.", self.units)
        self.constants = self.constant

        self.element = element.element("physical.", self.constants, self.units)
        self.elements = self.element

        # do some trickery to get modules set to instantiated classes
        self.unit.__name__ = unit.__name__
        sys.modules[unit.__name__] = self.unit
        sys.modules[units.__name__] = self.unit

        self.constant.__name__ = constant.__name__
        sys.modules[constant.__name__] = self.constant
        sys.modules[constants.__name__] = self.constant

        self.element.__name__ = element.__name__
        sys.modules[element.__name__] = self.element
        sys.modules[elements.__name__] = self.element

        # add in the license file
        self.license = license

        # copy over the Quantity module so that the user can reference it.
        self.base = Quantity

        # also provide a direct reference to the Quantity class
        self.Quantity = Quantity.Quantity
Esempio n. 11
0
def gen_signal(bus_params, signal, vector):
    '''Returns a string specifying signal using params in bus_params

    Arguments:
        bus_params: the 'params' dict from the dict returned by parse_bus
        signal: the name of the signal
        vector: a string of 1s and 0s
    '''

    pwl = 'V%s %s 0 PWL\n' % (signal, signal)

    hi = unit(bus_params['bithigh'])
    lo = unit(bus_params['bitlow'])
    trf = unit(bus_params['risefall'])
    bittime = unit(bus_params['bittime'])
    # Calculate a bittime that accounts for differences in rise/fall times
    # between the clock signal and the data signal
    clockrisefall = unit(bus_params['clockrisefall'])
    bittime += (clockrisefall + (clockrisefall - trf))

    # Lambda to get bit voltage from a '1' or '0'
    vbit = lambda bit: D(hi) if bit == '1' else D(lo)

    # Calculate the initial value of the PWL
    t = D('0.0')
    lastbit = vector[0]
    v_lastbit = vbit(lastbit)
    pwl += '+ 0 %s\n' % v_lastbit

    for bit in vector[1:]:
        t += bittime
        # only output a point when there is a change
        if bit != lastbit:
            # Mimic behavior of SPICE pulse source
            # Total period = 2*t_bit + 2*trf
            t_trans = t + trf
            v_nextbit = vbit(bit)
            pwl += '+ %s %s\n' % (t, v_lastbit)
            pwl += '+ %s %s\n' % (t_trans, v_nextbit)
            # Our new time reference is now the start of this 'bit' instead of
            # the start of the transition to this bit. If we didn't do this,
            # bits would get cut short by trf.
            t += trf
            lastbit = bit
            v_lastbit = v_nextbit

    return pwl
Esempio n. 12
0
def bus2pwl(busfile, out=None):
    '''Translates inputs specified by a busfile into SPICE PWL sources

    Outputs the result of this translation to a .pwl file at the path specified
    by 'out'
    '''

    if out:
        assert os.path.isdir(os.path.dirname(out))
    # If the user specified an outpath, use it. Otherwise, use busfile name
    pwl_name = out if out else busfile.replace('.bus', '.pwl')

    bus_parsed = busparse.parse_busfile(busfile)
    bus_params = bus_parsed['params']

    with open(pwl_name, 'w') as f:
        # Write a newline at the beginning of the file. Most SPICE interpreters
        # skip the first line of a file. While the user is actually supposed
        # to import this pwl, not run it standalone, this shouldn't matter, but
        # we'll write a blank line just in case.
        f.write('\n')

        # Generate a clock signal if the user has requested one
        if bus_params['edge'] != 'none':
            f.write(gen_clock(bus_params))
            f.write('\n')

        # Output each input source
        for signal, vector in bus_parsed['signals'].items():
            f.write(gen_signal(bus_params, signal, vector))
            f.write('\n')

        logging.info('Busfile translated. Output file: {}'.format(pwl_name))

    # Calculate the length of transient simulation required in order to capture
    # all inputs
    signal = list(bus_parsed['signals'].keys())[0]
    n_vectors = len(bus_parsed['signals'][signal])
    clock_period = unit(bus_params['bittime']) \
            + 2*unit(bus_params['clockrisefall'])
    sim_length = n_vectors * clock_period + unit(bus_params['clockdelay'])
    print('Simulate for {:e} seconds to simulate entire waveform'\
            .format(sim_length))

    return pwl_name
Esempio n. 13
0
    def creat_unit(self, no, pos, flag):
        if self.now_cool_down[no] != self.cool_down[no]:
            return None
        else:
            self.now_cool_down[no] = 0
        hp_list = [i for i in UNIT_MAX_HP]
        if no == 0:
            return unit(hp_list[0], 10, pos, no, 10, flag, 6, 50)
        elif no == 1:
            return unit(hp_list[1], 15, pos, no, 12, flag, 4, 90)
        elif no == 2:
            return unit(hp_list[2], 30, pos, no, 15, flag, 3, 60)
        elif no == 3:
            return unit(hp_list[3], 20, pos, no, 10, flag, 2, 50)
        elif no == 4:
            return unit(hp_list[4], 10, pos, no, 10, flag, 3, 120)

        return None
Esempio n. 14
0
def main(entity, entity_code):
    if entity == 'chapters':
        return chapter(entity_code)
    if entity == 'units':
        return unit(entity_code)
    if entity == 'concepts':
        return concept(entity_code)
    if entity == 'subjects':
        return subject(entity_code)
Esempio n. 15
0
    def get_preview_svg(self):
        """
        Returns a svg preview of the job.
        """
        w = self.material.get_width()
        l = self.material.get_length()

        # create the base svg (simulate the material)
        svg = structure.svg(width=unit(2,'cm')+w,height=unit(2,'cm')+l)

        # add the material layer
        layer = structure.g()
        layer.set_id('material_layer')
        layer.setAttribute('inkscape:label','Material Layer')
        layer.setAttribute('inkscape:groupmode','layer')
        material = builders.ShapeBuilder().createRect(
                x=unit(1,'cm'),y=unit(1,'cm'),width=w,height=l,
                fill=self.material.get_color()
            )
        layer.addElement(material)
        svg.addElement(layer)

        # add the data layer
        layer = structure.g()
        layer.set_id('data_layer')
        layer.setAttribute('inkscape:label','Data Layer')
        layer.setAttribute('inkscape:groupmode','layer')
        data = parser.parse_string(self.data)
        data.set_x(unit(1,'cm'))
        data.set_y(unit(1,'cm'))
        for path in data.getElementsByType(shape.path):
            layer.addElement(path)
        svg.addElement(layer)
        return svg.getXML()
Esempio n. 16
0
    def __init__(self,id=None,name=None,brand=None,model=None,
            operating_cost=0,width=None,length=None,
            uses_media_roll=True,
            margin=[0,0,0,0],
            blade_offset=unit(.25,'mm'),
            blade_overcut=unit(2,'mm'),
            calibration_scale=(1,1),command_language='HPGL',
            velocity_enable=False,velocity_min=None,
            velocity_max=None,velocity=None,
            force_enable=False,force_min=None,
            force_max=None,force=None,
        ):
        """
        Create a device instance with it's properties.
        """
        self.id = id
        self.name = name
        self.brand = brand
        self.model = model
        self.operating_cost = operating_cost

        self.width = width
        self.length = length
        self.uses_media_roll = uses_media_roll
        self.margin = margin
        self.blade_offset = blade_offset
        self.blade_overcut = blade_overcut
        self.calibration = calibration_scale

        self.command_language = command_language
        self.velocity_enable = velocity_enable
        self.velocity_min = velocity_min
        self.velocity_max = velocity_max
        self.velocity = velocity

        self.force_enable = force_enable
        self.force_min = force_min
        self.force_max = force_max
        self.force = force
Esempio n. 17
0
def rodrigues(vector, axis, angle):
    """
    Rotates a given vector about a given axis by a given angle using Rodrigues
    rotation formula:
    https://en.wikipedia.org/wiki/Rodrigues'_rotation_formula

    :param vector: XYZ vector to be rotated.
    :param axis: XYZ vector representing the axis of rotation (will be
        normalized so its magnitude does not matter).
    :param angle: Angle of rotation (degrees).
    :return: Rotated XYZ vector.
    """
    axis = unit(axis)
    rotated = vector * np.cos(np.deg2rad(angle))
    rotated = rotated + np.cross(axis, vector) * np.sin(np.deg2rad(angle))
    rotated = rotated + axis * np.vdot(
        axis, vector) * (1 - np.cos(np.deg2rad(angle)))
    return rotated
Esempio n. 18
0
def building(name, pid):
    #返回栋数
    page = 1
    url = "http://zjj.sz.gov.cn/ris/bol/szfdc/"+pid
    #print(url)
    headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36',
               'Content-Type': 'application/x-www-form-urlencoded'}
    req = urllib.request.Request(url=url, headers=headers)
    response = urllib.request.urlopen(req)
    result = response.read().decode('utf-8')
    selector=etree.HTML(result, parser=None, base_url=None)
    items = selector.xpath('//tr/td/a/@href')
    #print(items)
    res = []
    for i in range(len(items)):
        #print(items[i])
        res+=unit.unit(items[i])
    outline = ''.join(res)
    with open("property/%s.csv" % name, "w") as myfile:
        myfile.write(outline)
Esempio n. 19
0
File: game.py Progetto: queppl/sq
    def create_unit(self, unit_type = -1, group = None, pos = None, country_id = 0):
        if unit_type == -1 : return None
        u = unit.unit(unit_type)
        self.last_created_unit = u
        
        if group <> None :
            group.add_unit(u)
            
        elif pos <> None :
            if country_id <> 0 :
                group = self.create_group(country_id)
                group.add_unit(u)
                group.set_area(self.map.get_at_area(pos))
            else :
                country_id = self.map.get_at_area(pos).get_owner_id()
                if country_id == None : return None
                group = self.create_group(country_id)
                group.add_unit(u)
                group.set_area(self.map.get_at_area(pos))
                
                
        
        else :
            if country_id <> 0 : pass #warning
            if self.focus == None : return None
            if self.focus.__class__.__name__ == 'group' :
                group = self.focus
                group.add_unit(u)
            else :
                return None
            
        self.units.append(u)
        
        for i in self.modules :
            if hasattr(i,'unit_created') : i.unit_created(u)

        return u
Esempio n. 20
0
    def get_preview_svg(self):
        """
        Returns a svg preview of the job.
        """
        w = self.material.get_width()
        l = self.material.get_length()

        # create the base svg (simulate the material)
        svg = structure.svg(width=unit(2, 'cm') + w, height=unit(2, 'cm') + l)

        # add the material layer
        layer = structure.g()
        layer.set_id('material_layer')
        layer.setAttribute('inkscape:label', 'Material Layer')
        layer.setAttribute('inkscape:groupmode', 'layer')
        material = builders.ShapeBuilder().createRect(
            x=unit(1, 'cm'),
            y=unit(1, 'cm'),
            width=w,
            height=l,
            fill=self.material.get_color())
        layer.addElement(material)
        svg.addElement(layer)

        # add the data layer
        layer = structure.g()
        layer.set_id('data_layer')
        layer.setAttribute('inkscape:label', 'Data Layer')
        layer.setAttribute('inkscape:groupmode', 'layer')
        data = parser.parse_string(self.data)
        data.set_x(unit(1, 'cm'))
        data.set_y(unit(1, 'cm'))
        for path in data.getElementsByType(shape.path):
            layer.addElement(path)
        svg.addElement(layer)
        return svg.getXML()
Esempio n. 21
0
from unit import unit 
from mat import creator,matrix
from usr import press,Printer
brd = matrix(15,7,' ')
def move(brd,block,d):
    if d == 'r':
        block.right(brd)
    elif d == 'l':
        block.left(brd)
    elif d == 'd':
        block.down(brd)
    elif d == 'e':
        block.clock(brd)
    elif d == 'q':
        block.cclock(brd)
piece2 = unit()
def clearer(brd):
    for row_n in range(len(brd.mat)):
        if row_empty(brd.mat[row_n]):
            brd.mat.pop(row_n)
            brd.addrow()
def row_empty(row):
    if ' ' in row:
        return False
    return True
###warning i'm changing the way this game works 
#the matrix, is now a variable in an object matrix brd to access the board itself brd.mat with some other basic funcitons 
while True:
    clearer(brd)
    brd.Print(piece2)
    piece = piece2
Esempio n. 22
0
# Revision 1.1.1.1  2000/01/21 22:59:51  dgg
# dgg Cantera
#
# Revision 1.1  1999/11/27 17:27:35  dgg
# initial import to Cantera repository
#
# Revision 1.1  1999/11/25 19:50:58  aivazis
# Original source
#

from unit import unit, dimensionless

#
# The basic SI units
#
meter = unit(1.0, (1, 0, 0, 0, 0, 0, 0))
kilogram = unit(1.0, (0, 1, 0, 0, 0, 0, 0))
second = unit(1.0, (0, 0, 1, 0, 0, 0, 0))
ampere = unit(1.0, (0, 0, 0, 1, 0, 0, 0))
kelvin = unit(1.0, (0, 0, 0, 0, 1, 0, 0))
mole = unit(1.0, (0, 0, 0, 0, 0, 1, 0))
candela = unit(1.0, (0, 0, 0, 0, 0, 0, 1))

#
# The 21 derived SI units with special names
#
radian = dimensionless  #  plane angle
steradian = dimensionless  #  solid angle

hertz = 1 / second  #  frequency
Esempio n. 23
0
def busverify(bus, raw):
    '''Checks that SPICE waveforms conform to the ouput spec in a bus file'''

    assert os.path.isfile(bus)
    assert os.path.isfile(raw)

    bus_parsed = busparse.parse_busfile(bus)
    try:
        bus_outputs = bus_parsed['outputs']
    except KeyError:
        logging.critical('No output spec found in {}'.format(bus))
        raise
    # Get the names of the signals we are checking
    output_signals = bus_outputs.keys()
    logging.debug('The following outputs were specified in the busfile: {}'\
            .format(output_signals))
    # Convert output signals to voltage net names
    output_netnames = [
        ''.join(('V(', signal, ')')) for signal in output_signals
    ]
    logging.debug('Finding the following netnames in the rawfile: {}'\
            .format(output_netnames))
    # Unpack output signals into a list of strings passed to LTSpiceRawRead
    raw_parsed = rawparse.LTSpiceRawRead(raw, ' '.join(output_netnames))
    # Verify that all signals in output specification are in our rawfile. If
    # we find that any are missing, this is likely because the netname in the
    # BUS file does no match the one in the raw file.
    logging.debug('Ensuring that all specified outputs are in the rawfile...')
    for net in output_netnames:
        assert net in raw_parsed.get_trace_names(), \
                'Specified output signal {} was not found in the rawfile'\
                .format(net)
    logging.info('All specified outputs were found in the rawfile')

    time_array = raw_parsed.axis.data

    clockparams = bus_parsed['params']
    bittime = unit(clockparams['bittime'])
    tsu = unit(clockparams['tsu'])
    th = unit(clockparams['th'])
    clockdelay = unit(clockparams['clockdelay'])
    clockrisefall = unit(clockparams['clockrisefall'])
    logging.debug('Params:\n\tBit time: {}\n\tSetup time: {}\n\tHold time: {}\
            \n\tClock delay: {}\n\tClockrisefall: {}'\
            .format(bittime, tsu, th, clockdelay, clockrisefall))

    # First edge starts at the clock delay - subsequent edges are found at
    # last_edge + clockperiod
    first_edge_time = clockdelay
    clockperiod = bittime + 2 * clockrisefall

    logic_hi = D(clockparams['bithigh'])
    logic_lo = D(clockparams['bitlow'])
    logic_thresh = (logic_hi - logic_lo) * D(0.75)
    logging.debug('Threshold voltage for logic 1: {}'.format(logic_thresh))

    all_passed = True

    # Verify waveforms
    for signal, net in zip(output_signals, output_netnames):
        logging.debug('Testing signal: {}'.format(signal))
        loop_edge_time = first_edge_time
        su_index = 0
        hold_index = 0
        bit_count = 0
        trace = raw_parsed.get_trace(net).data
        simulation_results = ''
        for bit in bus_outputs[signal]:
            logging.debug(' - Testing bit {}'.format(bit_count))
            bit_count += 1
            logging.debug('Looking for logic {} at t={}'\
                    .format(bit, loop_edge_time))
            # Find the array indices of the setup and hold times associated
            # with a given clock edge
            edge_su_time = loop_edge_time - tsu
            edge_hold_time = loop_edge_time + th + clockrisefall
            # Start searching for su_index after last hold index
            next_su = clockedge_index(time_array[hold_index:], edge_su_time)
            su_index = hold_index + next_su
            # Start searching for next hold index after the su_index
            next_h = clockedge_index(time_array[su_index:], edge_hold_time)
            hold_index = su_index + next_h
            logging.debug('su_index: {}'.format(su_index))
            logging.debug('hold_index: {}'.format(hold_index))

            # Determine whether simulation yielded a '1' or '0' after clk edge
            if hold_index - su_index != 0:
                # We use hold_index+1 for the slice because we want hold_index
                # to be included in the slice
                logging.debug(time_array[su_index:(hold_index + 1)])
                logging.debug(trace[su_index:(hold_index + 1)])
                v_avg = sum(trace[su_index:(hold_index + 1)])
                logging.debug('Sum of voltages over points: {}'.format(v_avg))
                npoints = hold_index - su_index + 1
                v_avg /= (hold_index - su_index + 1)
                logging.debug('Dividing sum by {}'.format(npoints))
            else:
                v_avg = trace[su_index]

            logging.debug('Average voltage found: {}'.format(v_avg))
            simulated_bit = '1' if v_avg > logic_thresh else '0'
            simulation_results += simulated_bit

            # Get time of next clock edge
            loop_edge_time += clockperiod

        if simulation_results == bus_outputs[signal]:
            logging.info('{} passed - outputs were: {}'\
                    .format(signal, simulation_results))
        else:
            all_passed = False
            logging.error("{} failed.\nActual: {}\nSpec'd: {}"\
                    .format(signal, simulation_results, bus_outputs[signal]))
    return all_passed
Esempio n. 24
0
 def f**k(self, parent_1, parent_2):
     """ This method mixes the genes of the parents by a certain rule. """
     newGenes = None  # yet
     # TODO implement f**k
     child = unit(newGenes)
     return child
Esempio n. 25
0
def main():

    clock = pygame.time.Clock()
    IMAGES_DIR = os.getcwd() + "\\images\\"
    icon = pygame.image.load(IMAGES_DIR + "icon.png")
    pygame.display.set_icon(icon)
    reso = (640,480)
    screen = pygame.display.set_mode(reso)
    pygame.display.set_caption(".::TEAL CONCRETE::.")
    Mouse = mouse.mouse()
    
    ronnie = unit.unit("ronnie", IMAGES_DIR + "ronnie")
    rob    = unit.unit("rob", IMAGES_DIR + "rob")
    alyssa = unit.unit("alyssa", IMAGES_DIR + "alyssa")
    zoe    = unit.unit("zoe", IMAGES_DIR + "zoe")

    player = alyssa
    
    robsHouse = scene.scene(IMAGES_DIR + "background.png")
    tv = pygame.image.load(IMAGES_DIR + "tvback.png")
    counter = 0
   
    
    while 1:
        msElapse = clock.tick(30)
        Mouse.update()
        useList = player.idleList
        key = pygame.key.get_pressed()
        
        robsHouse.update(screen)
        robsHouse.checkIfMsg(player)
        
        
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
                pygame.quit()
            if event.type == pygame.KEYDOWN:
                    
                if event.key == pygame.K_z and robsHouse.pressed == False and robsHouse.msgAvail == True:
                    robsHouse.pressed = True
                elif event.key == pygame.K_z and robsHouse.pressed == True:
                    robsHouse.pressed = False
                
        
            
                    
        
             
        #If "z" isnt pressed down, then move.. if not you cant move
        if robsHouse.pressed == False:     
            if key[pygame.K_RIGHT]:
                if player.x < (reso[0] - 128):
                    player.isFlipped = False
                    useList = player.walkList
                    player.x += 10
            elif key[pygame.K_LEFT]:
                if player.x > 0:
                    player.isFlipped = True
                    useList = player.walkList
                    player.x -= 10
                
            if key[pygame.K_UP]:
                if player.y > 205:
                    useList = player.walkList
                    player.y -= 5
            elif key[pygame.K_DOWN]:
                if player.y < 355:
                    useList = player.walkList
                    player.y += 5
      
        
        
        
            
        print player.x,  player.y
        
        
        #TODO: IF THERE IS NO MSG AVAILABLE DONT PRINT THE TEXT BOX..
            
       

        
                
                
        player.update(screen, useList)
        screen.blit(tv, (380,305))
        if robsHouse.pressed == True:
            robsHouse.printText(screen, player)
        
        
        
        
        
        
        pygame.display.flip()
Esempio n. 26
0
 def parse(self, mc):
     super(DiskMetadata_1_1, self).parse(mc)
     self.partition_size = unit.unit(self.partition_size)
     self.partition_max_nr = int(self.partition_max_nr)
     self.rqr_reserved_ratio = float(self.rqr_reserved_ratio)
Esempio n. 27
0
def unified_powered_flight_guidance(vehicle, target, state, previous):
    """
    Implementation of Unified Powered Flight Guidance in Standard Ascent Mode
    as described by Brand, Brown and Higgins in Space Shuttle GN&C Equation
    Document 24.

    :param vehicle: (Array of) struct defining vehicle performance stage by
        stage. First element of the array should be the currently
        flown stage.
    :param target: Struct defining desired insertion conditions.
    :param state: Struct defining current vehicle physical state.
    :param previous: UPFG internal struct containing results of previous iteration.
    :return: (current, guidance, debug)
        current    UPFG internal struct containing results of this iteration.
        guidance   Struct containing calculated guidance parameters.
        debug      Currently just returns None
    """
    global g0

    # Block 0
    gamma = target.angle  # Desired inertial flight path angle at terminal (cutoff) position
    iy = target.normal  # Unit vectors relative to desired trajectory plane: iy is normal to desired trajectory plane.
    rdval = target.radius  # Desired radius magnitude at terminal (cutoff) position
    vdval = target.velocity  # Desired velocity magnitude at terminal (cutoff) position

    t = state.time  # Time associated with r, v
    m = state.mass  # Current estimated vehicle mass
    r = state.radius  # Vehicle position vector
    v = state.velocity  # Vehicle velocity vector

    cser = previous.cser
    rbias = previous.rbias  # A position bias to account for effects of a rotating thrust vector
    rd = previous.rd  # Desired terminal (cutoff) position
    rgrav = previous.rgrav  # Second integral of central force field gravitational acceleration over thrusting maneuver
    tp = previous.time  # t of previous guidance cycle
    vprev = previous.v
    vgo = previous.vgo

    # Block 1
    n = len(vehicle)  # total number of stages
    SM = [1] * n  # thrust mode (1=const thrust, 2=const acc)
    aL = [0] * n  # acceleration limit for const acceleration mode
    md = [0] * n  # mass flow rate
    ve = [0] * n  # Effective exhaust velocity for phase i
    fT = [0] * n  # thrust
    aT = [0] * n  # acceleration at the beginning of stage
    tu = [0] * n  # "time to burn as if the whole stage was fuel"
    tb = [0] * n  # Estimated burn time remaining in phase i

    for i in range(n):
        SM[i] = vehicle[i].mode
        aL[i] = vehicle[i].gLim * g0
        fT[i], md[i], ve[i] = get_thrust(vehicle[i].engines, 0, 0)
        ve[i] = ve[i] * g0
        aT[i] = fT[i] / vehicle[i].m0
        tu[i] = ve[i] / aT[i]
        tb[i] = vehicle[i].maxT

    # Block 2
    # We need to store dt in order to keep track on maneuver time.
    dt = t - tp  # Guidance cycle time step

    # In the paper, this block assumes the only known thing about vehicle's
    # state change since the last iteration is vector of velocity change
    # (delta-v_sensed) and time interval (delta t). In this implementation
    # however we assume the state is perfectly known and hence the call to
    # Powered Flight Navigation Routine is not necessary.
    # However, we still decrement vgo here!
    dvsensed = v - vprev  # Total velocity change accumulated on accelerometers since last reading
    vgo = vgo - dvsensed  # Velocity to be gained including bias. (vthrust reflects true velocity-to-be-gained)
    vgo1 = vgo

    # Calculation of 'remaining time to burn in stage k' (which here means
    # current stage) is done differently than in the paper. There, t_b,k is
    # decremented by dt every iteration; here this variable is not
    # persistent, but re-read from vehicle data at each iteration, and
    # instead we remember the current burn time tb, so we simply subtract
    # this time from original time-to-burn, obtaining the remaining time.
    tb[0] = tb[0] - previous.tb

    # Block 3
    # Current vehicle parameters have already been obtained in block 1, the
    # only thing different is a_T,k which should be calculated from current
    # mass instead of initial, and subsequently tu,k.
    # This is done according to theory on pages 33-34 and block diagrams on
    # 56-57, although with a small change: original document for the Space
    # Shuttle assumed that standard ascent will be finalized with a
    # predetermined OMS burn (Orbiter's SSMEs burning fuel from ET will only
    # take it so far, then the ET is jettisoned and vehicle coasts for a
    # predetermined amount of time (tc), after which the last burn phase
    # circularizes). Therefore, active guidance did not calculate the
    # integral Li(n). Stages 1..n-2 were assumed to burn out completely
    # (hence the logarithmic expression for them), and stage n-1 has burn
    # time set accordingly, so the total delta-v expended equals vgo.
    # In this application however, there is no such thing as a predetermined
    # final stage velocity. Therefore, stages n-1 are assumed to burn out
    # completely, and the last one is adjusted, so it burns out only as long
    # as needed.

    if SM[0] == 1:
        aT[0] = fT[0] / m
    elif SM[0] == 2:
        aT[0] = aL[0]

    tu[0] = ve[0] / aT[0]
    L = 0
    Li = [0] * n
    for i in range(n - 1):
        if SM[i] == 1:
            Li[i] = ve[i] * np.log(tu[i] / (tu[i] - tb[i]))
        elif SM[i] == 2:
            Li[i] = aL[i] * tb[i]

        L = L + Li[i]
        # If we have more stages than we need to get to orbit, redo the
        # whole calculation but skip the last stage.
        if L > np.linalg.norm(vgo):
            return unified_powered_flight_guidance(vehicle[0:n - 1], target,
                                                   state, previous)
    Li[n - 1] = np.linalg.norm(vgo) - L
    # Now for each stage its remaining time of burn is calculated (tbi) and
    # in the same pass accumulated into a total time-to-go of the maneuver.
    tgoi = [0] * n  # Time-to-go until end of ith phase
    for i in range(n):
        if SM[i] == 1:
            tb[i] = tu[i] * (1 - np.exp(-Li[i] / ve[i]))
        elif SM[i] == 2:
            tb[i] = Li[i] / aL[i]
        if i == 0:
            tgoi[i] = tb[i]
        else:
            tgoi[i] = tgoi[i - 1] + tb[i]
    L1 = Li[0]
    tgo = tgoi[n - 1]

    # Block 4
    L = 0
    J = 0
    Ji = [0] * n
    S = 0
    Si = [0] * n
    Q = 0
    Qi = [0] * n
    H = 0
    P = 0
    Pi = [0] * n
    # Major loop of the whole block, almost exactly as in the block diagrams.
    for i in range(n):
        # Variable tgoi1 represents t_go,i-1 only is determined in a safe
        # way (as to not exceed the array).
        if i == 0:
            tgoi1 = 0
        else:
            tgoi1 = tgoi[i - 1]

        # Constant thrust vs constant acceleration mode
        if SM[i] == 1:
            Ji[i] = tu[i] * Li[i] - ve[i] * tb[i]
            Si[i] = -Ji[i] + tb[i] * Li[i]
            Qi[i] = Si[i] * (tu[i] + tgoi1) - 0.5 * ve[i] * tb[i]**2
            Pi[i] = Qi[i] * (tu[i] + tgoi1) - 0.5 * ve[i] * tb[i]**2 * (
                (1.0 / 3) * tb[i] + tgoi1)
        elif SM[i] == 2:
            Ji[i] = 0.5 * Li[i] * tb[i]
            Si[i] = Ji[i]
            Qi[i] = Si[i] * ((1.0 / 3) * tb[i] + tgoi1)
            Pi[i] = (1.0 / 6) * Si[i] * (tgoi[i]**2 + 2 * tgoi[i] * tgoi1 +
                                         3 * tgoi1**2)

        # Common for both modes
        Ji[i] = Ji[i] + Li[i] * tgoi1
        Si[i] = Si[i] + L * tb[i]
        Qi[i] = Qi[i] + J * tb[i]
        Pi[i] = Pi[i] + H * tb[i]

        # No coast period before the last stage.

        L = L + Li[i]
        J = J + Ji[i]
        S = S + Si[i]
        Q = Q + Qi[i]
        P = P + Pi[i]
        H = J * tgoi[i] - Q

    # Block 5
    lambda_vec = unit(vgo)  # Unit vector in direction of vgo
    # print('lambda %s; vgo = %s' % (lambda_vec, vgo))
    rgrav1 = rgrav
    if not np.isclose(previous.tgo, 0):
        rgrav = (tgo / previous.tgo)**2 * rgrav
    rgo = rd - (r + v * tgo + rgrav)
    rgo1 = rgo
    iz = unit(np.cross(rd, iy))
    # print('iz = %s; rd = %s; iy = %s' % (iz, rd, iy))
    iz1 = iz
    rgoxy = rgo - np.vdot(iz, rgo) * iz
    rgoz = (S - np.vdot(lambda_vec, rgoxy)) / np.vdot(lambda_vec, iz)
    rgo = rgoxy + rgoz * iz + rbias
    lambdade = Q - S * J / L
    lambdadot = (
        rgo - S * lambda_vec
    ) / lambdade  # Time derivative of unit vector coincident with lambda_vec, but rotating with desired thrust vector turning rate omega_f
    iF = unit(lambda_vec - lambdadot * J / L)  # Unit thrust vector
    phi = np.arccos(np.vdot(iF, lambda_vec))
    phidot = -phi * L / J
    vthrust = (
        L - 0.5 * L * phi**2 - J * phi * phidot - 0.5 * H * phidot**2
    ) * lambda_vec  # First integral of thrust acceleration vector over thrusting maneuver
    vthrust = vthrust - (L * phi + J * phidot) * unit(lambdadot)
    # print("vthrust = %s" % vthrust)
    rthrust = (
        S - 0.5 * S * phi**2 - Q * phi * phidot - 0.5 * P * phidot**2
    ) * lambda_vec  # Second integral of thrust acceleration vector over thrusting maneuver
    rthrust = rthrust - (S * phi + Q * phidot) * unit(lambdadot)
    vbias = vgo - vthrust  # A velocity bias to account for the effects of a rotating thrust vector (vbias = vgo - vthrust)
    rbias = rgo - rthrust  # A position bias to account for the effects of a rotating thrust vector (rbias = rgo - rthrust)

    # Block 6 - original document does not contain any implementation
    # TODO - pitch and yaw RATES
    UP = unit(r)
    NORTH = np.array([0, 0, 1])
    EAST = unit(np.cross(NORTH, UP))
    frame = [UP, NORTH, EAST]
    # print('Frame: %s; iF = %s' % (frame, iF))
    pitch = get_angle_from_frame(iF, frame, 'pitch')
    yaw = get_angle_from_frame(iF, frame, 'yaw')

    # Block 7 - this calls the Conic State Extrapolation Routine
    rc1 = r - 0.1 * rthrust - (
        1.0 / 30
    ) * vthrust * tgo  # Vehicle position vector at beginning of gravity computation coast segment
    vc1 = v + 1.2 * rthrust / tgo - 0.1 * vthrust  # Vehicle velocity vector at beginning of gravity computation coast segment
    # Vehicle velocity vector at end of gravity computation coast segment
    # Vehicle position vector at end of gravity computation coast segment
    rc2, vc2, cser = conic_state_extrapolation_routine(rc1, vc1, tgo, cser)
    vgrav = vc2 - vc1  # First integral of central force field gravity acceleration over thrusting maneuver
    rgrav = rc2 - rc1 - vc1 * tgo  # Second integral of central force field gravitational acceleration over thrusting maneuver

    # Block 8
    rho = 0  # Damping factor used in determining the change in dvgo - see 4-20 for a proper definition
    rp = r + v * tgo + rgrav + rthrust
    rp = rp - np.vdot(rp, iy) * iy
    rd = rdval * unit(rp)
    ix = unit(rd)
    iz = np.cross(ix, iy)
    vd = vdval * np.matmul(np.transpose([ix, iy, iz]),
                           [np.sin(gamma), 0, np.cos(gamma)])
    vgop = vd - v - vgrav + vbias
    dvgo = rho * (
        vgop - vgo
    )  # big values (0.8+) cause bananas; standard ascent uses 0 (?)
    # print('vd = %s; gamma = %f; vgop = %s; v = %s; vgrav = %s; vbias = %s' % (vd, gamma, vgop, v, vgrav, vbias))
    vgo = vgop + dvgo  # 5-15 shows vgo + dvgo, but 4-21 shows vgop + dvgo

    current = previous
    current.cser = cser
    current.rbias = rbias
    current.rd = rd
    current.rgrav = rgrav
    current.tb = current.tb + dt
    current.time = t
    current.tgo = tgo
    current.v = v
    current.vgo = vgo

    guidance = Guidance(pitch, yaw, 0, 0, tgo)

    debug = DebugState(0, t, r, v, m, dvsensed, vgo1, L1, tgo, L, J, S, Q, P,
                       H, lambda_vec, rgrav1, rgo1, iz1, rgoxy, rgoz, rgo,
                       lambdade, lambdadot, iF, phi, phidot, vthrust, rthrust,
                       vbias, rbias, pitch, EAST, yaw, rc1, vc1, rc2, vc2,
                       cser.dtcp, cser.xcp, cser.A, cser.D, cser.E, vgrav,
                       rgrav, rp, rd, ix, iz, vd, vgop, dvgo, vgo, 0)

    return current, guidance, debug
Esempio n. 28
0
 def get_width(self, in_unit='cm'):
     return unit(self.width, in_unit)
Esempio n. 29
0
    def __init__(self,
            id=None,
            copies=1,
            scale=1,
            start_x=0,
            start_y=0,
            center_x=False,
            center_y=False,
            invert_axis_x=True,
            invert_axis_y=False,
            plot_margin_top=0,
            plot_margin_right=0,
            plot_margin_bottom=0,
            plot_margin_left=0,
            copy_spacing_x=unit(.25,'cm'), # TODO: load from config
            copy_spacing_y=unit(.25,'cm'), # TODO: load from config
            copy_rotation=0,
            path_smoothness=0.2,
            path_sort_order=0,
            weed_plot=False,
            weed_plot_margin=0,
            weed_copy=False,
            weed_copy_margin=0,
            plot_selected_nodes=None
        ):
        # Job requirements
        self.copies = copies
        self.scale = scale
        self.start_x = start_x
        self.start_y = start_y
        self.center_x = center_x
        self.center_y = center_y
        self.invert_axis_x = invert_axis_x
        self.invert_axis_y = invert_axis_y
        self.plot_margin_top = plot_margin_top
        self.plot_margin_right = plot_margin_right
        self.plot_margin_bottom = plot_margin_bottom
        self.plot_margin_left = plot_margin_left
        self.copy_spacing_x = copy_spacing_x
        self.copy_spacing_y = copy_spacing_y
        self.copy_rotation = copy_rotation
        self.path_smoothness = path_smoothness
        self.path_sort_order = path_sort_order
        self.weed_plot = weed_plot
        self.weed_plot_margin = weed_plot_margin
        self.weed_copy = weed_copy
        self.weed_copy_margin = weed_copy_margin
        self.plot_selected_nodes = plot_selected_nodes

        # Job status flags
        self.changed = True

        # Setting Requirements
        def set_copies(self,n):
            assert n >= 1
            self.copies = n

        def set_scale(self,r):
            assert r > 0
            self.scale = r

        def set_start_position(self,x,y):
            assert x > 0
            assert y > 0
            self.start_x = x
            self.start_y = y

        def set_auto_center(self,enable_x,enable_y):
            assert bool == type(enable_x)
            assert bool == type(enable_y)
            self.center_x = enable_x
            self.center_y = enable_y

        def set_invert_axis(self,enable_x,enable_y):
            assert bool == type(enable_x)
            assert bool == type(enable_y)
            self.invert_axis_x = enable_x
            self.invert_axis_y = enable_y

        def set_plot_margin(self,top,right,bottom,left):
            assert top >= 0
            assert right >= 0
            assert bottom >= 0
            assert left >= 0
            self.plot_margin_top = top
            self.plot_margin_right = right
            self.plot_margin_bottom = bottom
            self.plot_margin_left = left

        def set_copy_spacing(self,x,y):
            self.copy_spacing_x = x
            self.copy_spacing_y = y

        def set_path_smoothness(self,s):
            assert s >= .01
            self.path_smoothness = s

        def set_path_sort_order(self,order):
            #assert order in ['One copy at a time']
            self.path_sort_order = order

        def set_weed_plot(self,enabled,margin):
            assert bool == type(enabled)
            assert min([self.plot_margin_top,self.plot_margin_right,self.plot_margin_bottom,self.plot_margin_left]) > margin > 0
            self.weed_plot = enabled
            self.weed_plot_margin = margin

        def set_weed_copy(self,enabled,margin):
            assert bool == type(enabled)
            assert min([self.plot_margin_top,self.plot_margin_right,self.plot_margin_bottom,self.plot_margin_left]) > margin > 0
            self.weed_copy = enabled
            self.weed_copy_margin = margin
Esempio n. 30
0
 def set_width(self,value,convert_to='cm'):
     self.width = unit(value,convert_to)
Esempio n. 31
0
 def get_length(self,in_unit='cm'):
     return unit(self.length,in_unit)
Esempio n. 32
0
 def set_length(self,value,convert_to='cm'):
     self.length = unit(value,convert_to)
Esempio n. 33
0
    def __init__(
        self,
        id=None,
        name=None,
        brand=None,
        model=None,
        operating_cost=0,
        width=None,
        length=None,
        uses_media_roll=True,
        margin_top=0,
        margin_right=0,
        margin_bottom=0,
        margin_left=0,
        blade_offset=unit(.25, 'mm'),
        blade_overcut=unit(2, 'mm'),
        calibration_x=1,
        calibration_y=1,
        command_language='HPGL',
        command_buffer=8,
        command_method=None,
        command_port=None,
        command_baudrate=9600,
        command_parity='None',
        command_stopbits=1,
        command_bytesize=8,
        command_xonxoff=False,
        command_rtscts=False,
        command_dsrdtr=False,
        command_use_software=False,
        velocity_min=None,
        velocity_max=None,
        velocity=None,
        force_min=None,
        force_max=None,
        force=None,
    ):
        """
        Create a device instance with it's properties.
        """
        self.id = id
        self.name = name
        self.brand = brand
        self.model = model
        self.operating_cost = operating_cost

        self.width = width
        self.length = length
        self.uses_media_roll = uses_media_roll
        self.margin_top = margin_top
        self.margin_right = margin_right
        self.margin_bottom = margin_bottom
        self.margin_left = margin_left
        self.blade_offset = blade_offset
        self.blade_overcut = blade_overcut
        self.calibration_x = calibration_x
        self.calibration_y = calibration_y

        self.command_language = command_language
        self.command_buffer = command_buffer
        self.command_method = command_method

        self.command_port = command_port
        self.command_baudrate = command_baudrate
        self.command_parity = command_parity
        self.command_stopbits = command_stopbits
        self.command_bytesize = command_bytesize
        self.command_xonxoff = command_xonxoff
        self.command_rtscts = command_rtscts
        self.command_dsrdtr = command_dsrdtr

        self.command_use_software = command_use_software
        self.velocity_min = velocity_min
        self.velocity_max = velocity_max
        self.velocity = velocity
        self.force_min = force_min
        self.force_max = force_max
        self.force = force
Esempio n. 34
0
 def get_width(self,in_unit='cm'):
     return unit(self.width,in_unit)
Esempio n. 35
0
File: SI.py Progetto: Alex-Song/vmaf
#
#                               Michael A.G. Aivazis
#                        California Institute of Technology
#                        (C) 1998-2005  All Rights Reserved
#
# <LicenseText>
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#

from unit import unit, dimensionless


# basic SI units

meter = unit(1.0, (1, 0, 0, 0, 0, 0, 0))
kilogram = unit(1.0, (0, 1, 0, 0, 0, 0, 0))
second = unit(1.0, (0, 0, 1, 0, 0, 0, 0))
ampere = unit(1.0, (0, 0, 0, 1, 0, 0, 0))
kelvin = unit(1.0, (0, 0, 0, 0, 1, 0, 0))
mole = unit(1.0, (0, 0, 0, 0, 0, 1, 0))
candela = unit(1.0, (0, 0, 0, 0, 0, 0, 1))

# the 22 derived SI units with special names

radian = dimensionless                 #  plane angle                                
steradian = dimensionless              #  solid angle                                
                                                                                     
hertz = 1/second                       #  frequency                                  
                                                                                     
newton = meter*kilogram/second**2      #  force                                      
Esempio n. 36
0
 def set_width(self, value, convert_to='cm'):
     self.width = unit(value, convert_to)
Esempio n. 37
0
def main():

    clock = pygame.time.Clock()
    IMAGES_DIR = os.getcwd() + "\\images\\"
    icon = pygame.image.load(IMAGES_DIR + "icon.png")
    pygame.display.set_icon(icon)
    reso = (640, 480)
    screen = pygame.display.set_mode(reso)
    pygame.display.set_caption(".::TEAL CONCRETE::.")
    Mouse = mouse.mouse()

    ronnie = unit.unit("ronnie", IMAGES_DIR + "ronnie", 10)
    rob = unit.unit("rob", IMAGES_DIR + "rob", 10)
    alyssa = unit.unit("alyssa", IMAGES_DIR + "alyssa", 10)
    zoe = unit.unit("zoe", IMAGES_DIR + "zoe", 10)
    monster = unit.unit("monster", IMAGES_DIR + "monster", 5)
    monster.x = 340
    charSelected = False

    garage = scene.scene(IMAGES_DIR + "garage.png")
    robsHouse = scene.scene(IMAGES_DIR + "background.png")
    tv = pygame.image.load(IMAGES_DIR + "tvback.png")
    arrow = pygame.image.load(IMAGES_DIR + "arrow.png")

    counter = 0

    def resetStats():
        player.currentHP = player.maxHP
        player.x = 0
        player.y = 205
        player.hitCounter = 16
        player.bounceCounter = 10

        robsHouse.sysEvent = False
        robsHouse.userEvent = False

    def charSelection():

        fontType = pygame.font.SysFont("Pixelated Regular", 55)
        textbox = pygame.image.load(IMAGES_DIR + "textbox.png")

        garage.update(screen)
        ronnie.isFlipped = True

        ronnie.update(screen, ronnie.idleList, 475, 300)

        rob.update(screen, rob.idleList, 100, 280)

        alyssa.update(screen, alyssa.idleList, 380, 260)

        zoe.update(screen, zoe.idleList, 260, 240)

        screen.blit(textbox, (25, 5))
        screen.blit(fontType.render("SELECT YOUR CHARACTER", 0, (0, 0, 0)), (55, 45))

    arrowCoord = [(130, 210), (290, 170), (410, 190), (480, 230)]
    arrowIndex = 0

    while 1:
        msElapse = clock.tick(30)
        Mouse.update()

        key = pygame.key.get_pressed()

        # Character Selection Screen
        if charSelected == False:

            charSelection()

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                    pygame.quit()
                if event.type == pygame.KEYDOWN:

                    if event.key == pygame.K_RIGHT:
                        if arrowIndex < 3:
                            arrowIndex += 1
                    elif event.key == pygame.K_LEFT:
                        if arrowIndex > 0:
                            arrowIndex -= 1

                    if event.key == pygame.K_z:
                        if arrowIndex == 0:
                            player = rob
                        elif arrowIndex == 1:
                            player = zoe
                        elif arrowIndex == 2:
                            player = alyssa
                        elif arrowIndex == 3:
                            player = ronnie

                        # player.maxHP = 10
                        resetStats()
                        charSelected = True

            screen.blit(arrow, arrowCoord[arrowIndex])

        # Main Game
        else:

            useList = player.idleList
            robsHouse.update(screen)
            robsHouse.checkIfMsg(player)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                    pygame.quit()
                if event.type == pygame.KEYDOWN:

                    if event.key == pygame.K_z and robsHouse.userEvent == False and robsHouse.msgAvail == True:
                        robsHouse.userEvent = True
                    elif event.key == pygame.K_z and robsHouse.userEvent == True:
                        robsHouse.list1 = []
                        robsHouse.list2 = []
                        # robsHouse.text = ""
                        robsHouse.textCounter = 0
                        robsHouse.userEvent = False

                    elif event.key == pygame.K_ESCAPE:
                        charSelected = False
                    elif event.key == pygame.K_f:
                        player.currentHP -= 5

            if robsHouse.userEvent == False and robsHouse.sysEvent == False:
                if key[pygame.K_RIGHT]:
                    if player.x < (reso[0] - 128):
                        player.isFlipped = False
                        useList = player.walkList
                        player.x += 10
                elif key[pygame.K_LEFT]:
                    if player.x > 0:
                        player.isFlipped = True
                        useList = player.walkList
                        player.x -= 10

                if key[pygame.K_UP]:
                    if player.y > 205:
                        useList = player.walkList
                        player.y -= 5
                elif key[pygame.K_DOWN]:
                    if player.y < 355:
                        useList = player.walkList
                        player.y += 5

            if player.currentHP <= 0:
                charSelected = False
                # player.currentHP = player.maxHP

            if player.rect.colliderect(monster.rect) and player.isHit == False:
                player.immuneCount()
                player.currentHP -= 1

            elif player.isHit:
                player.immuneCount()

            if player.hitCounter >= 3 and player.hitCounter < 16:  # Countdown while being in "hit state".
                robsHouse.sysEvent = True
                if player.bounceCounter > 0:
                    player.bounceBack()
            else:
                robsHouse.sysEvent = False
                player.bounceBounce = 10
            monster.update(screen, monster.idleList, monster.x, monster.y)

            if player.hitCounter % 2 == 0:  # Flashing effect when damaged.
                player.update(screen, useList, player.x, player.y)

            screen.blit(tv, (380, 305))

            if robsHouse.userEvent == True:
                robsHouse.printText(screen, player)

            print "HP: " + str(player.currentHP) + "/" + str(player.maxHP)
            print "sys: " + str(robsHouse.sysEvent)
            print "user: " + str(robsHouse.userEvent)
            print player.bounceCounter
            # print player.rect
            # print monster.rect

        pygame.display.flip()
Esempio n. 38
0
 def get_length(self, in_unit='cm'):
     return unit(self.length, in_unit)
Esempio n. 39
0
from convert import chuyendoi
from unit import unit
nhietdo=float(input("nhap vao nhiet do :"))
donvi=str(input("nhap vao don vi nhiet do :"))
print("nhiet do da duoc chuyen doi thanh:  ")
print(chuyendoi(nhietdo,donvi),unit(donvi))
Esempio n. 40
0
 def set_length(self, value, convert_to='cm'):
     self.length = unit(value, convert_to)
Esempio n. 41
0
 def initFirstGen(self, size):
     """ Initialize first generation. """
     self.generations.append([
         unit([random.randint(-10, 10) for x in range(4)])
         for x in range(size)
     ])
Esempio n. 42
0
 def add_unit(self, x, y):
     self.units.append(unit(x, y))
     return 0
Esempio n. 43
0
def main():

    clock = pygame.time.Clock()
    IMAGES_DIR = os.getcwd() + "\\images\\"
    icon = pygame.image.load(IMAGES_DIR + "icon.png")
    pygame.display.set_icon(icon)
    reso = (640, 480)
    screen = pygame.display.set_mode(reso)
    pygame.display.set_caption(".::TEAL CONCRETE::.")
    Mouse = mouse.mouse()

    ronnie = unit.unit("ronnie", IMAGES_DIR + "ronnie", 10)
    rob = unit.unit("rob", IMAGES_DIR + "rob", 10)
    alyssa = unit.unit("alyssa", IMAGES_DIR + "alyssa", 10)
    zoe = unit.unit("zoe", IMAGES_DIR + "zoe", 10)
    monster = unit.unit("monster", IMAGES_DIR + "monster", 5)
    monster.x = 340
    charSelected = False

    garage = scene.scene(IMAGES_DIR + "garage.png")
    robsHouse = scene.scene(IMAGES_DIR + "background.png")
    tv = pygame.image.load(IMAGES_DIR + "tvback.png")
    arrow = pygame.image.load(IMAGES_DIR + "arrow.png")

    counter = 0

    def resetStats():
        player.currentHP = player.maxHP
        player.x = 0
        player.y = 205
        player.hitCounter = 16
        player.bounceCounter = 10

        robsHouse.sysEvent = False
        robsHouse.userEvent = False

    def charSelection():

        fontType = pygame.font.SysFont("Pixelated Regular", 55)
        textbox = pygame.image.load(IMAGES_DIR + "textbox.png")

        garage.update(screen)
        ronnie.isFlipped = True

        ronnie.update(screen, ronnie.idleList, 475, 300)

        rob.update(screen, rob.idleList, 100, 280)

        alyssa.update(screen, alyssa.idleList, 380, 260)

        zoe.update(screen, zoe.idleList, 260, 240)

        screen.blit(textbox, (25, 5))
        screen.blit(fontType.render("SELECT YOUR CHARACTER", 0, (
            0,
            0,
            0,
        )), (55, 45))

    arrowCoord = [(130, 210), (290, 170), (410, 190), (480, 230)]
    arrowIndex = 0

    while 1:
        msElapse = clock.tick(30)
        Mouse.update()

        key = pygame.key.get_pressed()

        #Character Selection Screen
        if charSelected == False:

            charSelection()

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                    pygame.quit()
                if event.type == pygame.KEYDOWN:

                    if event.key == pygame.K_RIGHT:
                        if arrowIndex < 3:
                            arrowIndex += 1
                    elif event.key == pygame.K_LEFT:
                        if arrowIndex > 0:
                            arrowIndex -= 1

                    if event.key == pygame.K_z:
                        if arrowIndex == 0:
                            player = rob
                        elif arrowIndex == 1:
                            player = zoe
                        elif arrowIndex == 2:
                            player = alyssa
                        elif arrowIndex == 3:
                            player = ronnie

                        #player.maxHP = 10
                        resetStats()
                        charSelected = True

            screen.blit(arrow, arrowCoord[arrowIndex])

        #Main Game
        else:

            useList = player.idleList
            robsHouse.update(screen)
            robsHouse.checkIfMsg(player)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                    pygame.quit()
                if event.type == pygame.KEYDOWN:

                    if event.key == pygame.K_z and robsHouse.userEvent == False and robsHouse.msgAvail == True:
                        robsHouse.userEvent = True
                    elif event.key == pygame.K_z and robsHouse.userEvent == True:
                        robsHouse.list1 = []
                        robsHouse.list2 = []
                        #robsHouse.text = ""
                        robsHouse.textCounter = 0
                        robsHouse.userEvent = False

                    elif event.key == pygame.K_ESCAPE:
                        charSelected = False
                    elif event.key == pygame.K_f:
                        player.currentHP -= 5

            if robsHouse.userEvent == False and robsHouse.sysEvent == False:
                if key[pygame.K_RIGHT]:
                    if player.x < (reso[0] - 128):
                        player.isFlipped = False
                        useList = player.walkList
                        player.x += 10
                elif key[pygame.K_LEFT]:
                    if player.x > 0:
                        player.isFlipped = True
                        useList = player.walkList
                        player.x -= 10

                if key[pygame.K_UP]:
                    if player.y > 205:
                        useList = player.walkList
                        player.y -= 5
                elif key[pygame.K_DOWN]:
                    if player.y < 355:
                        useList = player.walkList
                        player.y += 5

            if player.currentHP <= 0:
                charSelected = False
                #player.currentHP = player.maxHP

            if player.rect.colliderect(monster.rect) and player.isHit == False:
                player.immuneCount()
                player.currentHP -= 1

            elif player.isHit:
                player.immuneCount()

            if player.hitCounter >= 3 and player.hitCounter < 16:  #Countdown while being in "hit state".
                robsHouse.sysEvent = True
                if player.bounceCounter > 0:
                    player.bounceBack()
            else:
                robsHouse.sysEvent = False
                player.bounceBounce = 10
            monster.update(screen, monster.idleList, monster.x, monster.y)

            if player.hitCounter % 2 == 0:  #Flashing effect when damaged.
                player.update(screen, useList, player.x, player.y)

            screen.blit(tv, (380, 305))

            if robsHouse.userEvent == True:
                robsHouse.printText(screen, player)

            print "HP: " + str(player.currentHP) + "/" + str(player.maxHP)
            print "sys: " + str(robsHouse.sysEvent)
            print "user: " + str(robsHouse.userEvent)
            print player.bounceCounter
            #print player.rect
            #print monster.rect

        pygame.display.flip()
Esempio n. 44
0
                    else:
                        self.initCond = self.rungeKutta4(dt, demand)
                        self.timeHist.append([self.initCond, n * dt])

                        if (abs(self.initCond[0] - demand[0]) <= abs(
                                tolerance[0])
                                and abs(self.initCond[2] - demand[2]) <= abs(
                                    tolerance[2])):
                            n += 1
                            eqcounter += 1
                        elif abs(self.initCond[2]) >= pi:
                            return float('nan')
                            break
                        else:
                            n += 1


if __name__ == '__main__':

    from unit import unit

    u = unit([0.7, 0.5, 0.3, 0.3])
    ic = np.array([0, 0, 0.5, 0])
    params = [1, 1, 9.81]
    dt = 0.01
    steps = 5

    p = physicsHandler(ic, params, u, dt, steps)

    p.run()