当前位置: 首页>>代码示例>>Python>>正文


Python Units类代码示例

本文整理汇总了Python中Units的典型用法代码示例。如果您正苦于以下问题:Python Units类的具体用法?Python Units怎么用?Python Units使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Units类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: getMoment

    def getMoment(self, fp):
        """Compute the mass of the object, already taking into account the
        type of subentities.

        Position arguments:
        fp -- Part::FeaturePython object affected.

        Returned value:
        List of moments toward x, y and z
        """
        m = [Units.parseQuantity('0 kg*m'),
             Units.parseQuantity('0 kg*m'),
             Units.parseQuantity('0 kg*m')]
        for s in fp.Shape.Solids:
            mom = self._getVolumetricMoment(fp, s)
            for i in range(len(m)):
                m[i] = m[i] + mom[i]
        for f in fp.Shape.Faces:
            mom = self._getAreaMoment(fp, f)
            for i in range(len(m)):
                m[i] = m[i] + mom[i]
        for e in fp.Shape.Edges:
            mom = self._getLinearMoment(fp, e)
            for i in range(len(m)):
                m[i] = m[i] + mom[i]
        for v in fp.Shape.Vertexes:
            mom = self._getPuntualMoment(fp, v)
            for i in range(len(m)):
                m[i] = m[i] + mom[i]
        return m
开发者ID:3DPrinterGuy,项目名称:FreeCAD,代码行数:30,代码来源:WeightInstance.py

示例2: accept

    def accept(self):
        if not self.ship:
            return False
        self.save()
        # Plot data
        mw = self.getMainWindow()
        form = mw.findChild(QtGui.QWidget, "TaskPanel")
        form.draft = self.widget(QtGui.QLineEdit, "Draft")
        form.trim = self.widget(QtGui.QLineEdit, "Trim")
        form.num = self.widget(QtGui.QSpinBox, "Num")
        draft = Units.parseQuantity(Locale.fromString(form.draft.text()))
        trim = Units.parseQuantity(Locale.fromString(form.trim.text()))
        num = form.num.value()

        disp, B, _ = Hydrostatics.displacement(self.ship,
                                               draft,
                                               Units.parseQuantity("0 deg"),
                                               trim)
        xcb = Units.Quantity(B.x, Units.Length)
        data = Hydrostatics.areas(self.ship,
                                  num,
                                  draft=draft,
                                  trim=trim)
        x = []
        y = []
        for i in range(0, len(data)):
            x.append(data[i][0].getValueAs("m").Value)
            y.append(data[i][1].getValueAs("m^2").Value)
        PlotAux.Plot(x, y, disp, xcb, self.ship)
        self.preview.clean()
        return True
开发者ID:3DPrinterGuy,项目名称:FreeCAD,代码行数:31,代码来源:TaskPanel.py

示例3: moment

def moment(ship, draft=None,
                 roll=Units.parseQuantity("0 deg"), 
                 trim=Units.parseQuantity("0 deg")):
    """Compute the moment required to trim the ship 1cm

    Position arguments:
    ship -- Ship object (see createShip)

    Keyword arguments:
    draft -- Ship draft (Design ship draft by default)
    roll -- Roll angle (0 degrees by default)
    trim -- Trim angle (0 degrees by default)

    Returned value:
    Moment required to trim the ship 1cm. Such moment is positive if it cause a
    positive trim angle. The moment is expressed as a mass by a distance, not as
    a force by a distance
    """
    disp_orig, B_orig, _ = displacement(ship, draft, roll, trim)
    xcb_orig = Units.Quantity(B_orig.x, Units.Length)

    factor = 10.0
    x = 0.5 * ship.Length.getValueAs('cm').Value
    y = 1.0
    angle = math.atan2(y, x) * Units.Radian
    trim_new = trim + factor * angle
    disp_new, B_new, _ = displacement(ship, draft, roll, trim_new)
    xcb_new = Units.Quantity(B_new.x, Units.Length)

    mom0 = -disp_orig * xcb_orig
    mom1 = -disp_new * xcb_new
    return (mom1 - mom0) / factor
开发者ID:3DPrinterGuy,项目名称:FreeCAD,代码行数:32,代码来源:Tools.py

示例4: tankCapacityCurve

def tankCapacityCurve(tank, n):
    """Create a tank capacity curve

    Position arguments:
    tank -- Tank object (see createTank)
    ship -- n Number of filling levels to test

    Returned value:
    List of computed points. Each point contains the filling level percentage
    (interval [0, 1]), the the filling level (0 for the bottom of the tank), and
    the volume.
    """
    bbox = tank.Shape.BoundBox
    dz = Units.Quantity(bbox.ZMax - bbox.ZMin, Units.Length)
    dlevel = 1.0 / (n - 1)
    out = [(0.0, Units.parseQuantity("0 m"), Units.parseQuantity("0 m^3"))]

    msg = QtGui.QApplication.translate(
        "ship_console",
        "Computing capacity curves",
        None)
    App.Console.PrintMessage(msg + '...\n')
    for i in range(1, n):
        App.Console.PrintMessage("\t{} / {}\n".format(i + 1, n))
        level = i * dlevel
        vol = tank.Proxy.getVolume(tank, level)
        out.append((level, level * dz, level * vol))
    return out
开发者ID:abdullahtahiriyo,项目名称:FreeCAD_sf_master,代码行数:28,代码来源:Tools.py

示例5: turn

def turn(gc, unit):
    Units.shoot_at_best_target(gc, unit)
    if gc.is_move_ready(unit.id):
        planet = unit.location.map_location().planet
        path = get_closest_fact(unit) if planet == bc.Planet.Earth else Globals.updatePathMars
        Navigation.path_with_bfs(gc, unit, path)
    return
开发者ID:trice07,项目名称:One-West-BC,代码行数:7,代码来源:Knight.py

示例6: onData

    def onData(self, value):
        """ Method called when the tool input data is touched.
        @param value Changed value.
        """
        if not self.ship:
            return

        mw = self.getMainWindow()
        form = mw.findChild(QtGui.QWidget, "TaskPanel")
        form.draft = self.widget(QtGui.QLineEdit, "Draft")
        form.trim = self.widget(QtGui.QLineEdit, "Trim")

        # Get the values (or fix them in bad setting case)
        try:
            draft = Units.parseQuantity(Locale.fromString(form.draft.text()))
        except:
            draft = self.ship.Draft
            form.draft.setText(draft.UserString)
        try:
            trim = Units.parseQuantity(Locale.fromString(form.trim.text()))
        except:
            trim = Units.parseQuantity("0 deg")
            form.trim.setText(trim.UserString)

        bbox = self.ship.Shape.BoundBox
        draft_min = Units.Quantity(bbox.ZMin, Units.Length)
        draft_max = Units.Quantity(bbox.ZMax, Units.Length)
        draft = self.clampValue(form.draft, draft_min, draft_max, draft)

        trim_min = Units.parseQuantity("-180 deg")
        trim_max = Units.parseQuantity("180 deg")
        trim = self.clampValue(form.trim, trim_min, trim_max, trim)

        self.onUpdate()
        self.preview.update(draft, trim, self.ship)
开发者ID:3DPrinterGuy,项目名称:FreeCAD,代码行数:35,代码来源:TaskPanel.py

示例7: save

    def save(self):
        """ Saves the data into ship instance. """
        mw = self.getMainWindow()
        form = mw.findChild(QtGui.QWidget, "TaskPanel")
        form.draft = self.widget(QtGui.QLineEdit, "Draft")
        form.trim = self.widget(QtGui.QLineEdit, "Trim")
        form.num = self.widget(QtGui.QSpinBox, "Num")

        draft = Units.parseQuantity(Locale.fromString(form.draft.text()))
        trim = Units.parseQuantity(Locale.fromString(form.trim.text()))
        num = form.num.value()

        props = self.ship.PropertiesList
        try:
            props.index("AreaCurveDraft")
        except ValueError:
            try:
                tooltip = str(QtGui.QApplication.translate(
                    "ship_areas",
                    "Areas curve tool draft selected [m]",
                    None))
            except:
                tooltip = "Areas curve tool draft selected [m]"
            self.ship.addProperty("App::PropertyLength",
                                  "AreaCurveDraft",
                                  "Ship",
                                  tooltip)
        self.ship.AreaCurveDraft = draft
        try:
            props.index("AreaCurveTrim")
        except ValueError:
            try:
                tooltip = str(QtGui.QApplication.translate(
                    "ship_areas",
                    "Areas curve tool trim selected [deg]",
                    None))
            except:
                tooltip = "Areas curve tool trim selected [deg]"
            self.ship.addProperty("App::PropertyAngle",
                                  "AreaCurveTrim",
                                  "Ship",
                                  tooltip)
        self.ship.AreaCurveTrim = trim
        try:
            props.index("AreaCurveNum")
        except ValueError:
            try:
                tooltip = str(QtGui.QApplication.translate(
                    "ship_areas",
                    "Areas curve tool number of points",
                    None))
            except:
                tooltip = "Areas curve tool number of points"
            self.ship.addProperty("App::PropertyInteger",
                                  "AreaCurveNum",
                                  "Ship",
                                  tooltip)
        self.ship.AreaCurveNum = num
开发者ID:AjinkyaDahale,项目名称:FreeCAD,代码行数:58,代码来源:TaskPanel.py

示例8: solve

def solve(ship, weights, tanks, rolls, var_trim=True):
    """Compute the ship GZ stability curve

    Position arguments:
    ship -- Ship object
    weights -- List of weights to consider
    tanks -- List of tanks to consider (each one should be a tuple with the
    tank instance, the density of the fluid inside, and the filling level ratio)
    rolls -- List of roll angles

    Keyword arguments:
    var_trim -- True if the equilibrium trim should be computed for each roll
    angle, False if null trim angle can be used instead.

    Returned value:
    List of GZ curve points. Each point contains the GZ stability length, the
    equilibrium draft, and the equilibrium trim angle (0 deg if var_trim is
    False)
    """
    # Get the unloaded weight (ignoring the tanks for the moment).
    W = Units.parseQuantity("0 kg")
    mom_x = Units.parseQuantity("0 kg*m")
    mom_y = Units.parseQuantity("0 kg*m")
    mom_z = Units.parseQuantity("0 kg*m")
    for w in weights:
        W += w.Proxy.getMass(w)
        m = w.Proxy.getMoment(w)
        mom_x += m[0]
        mom_y += m[1]
        mom_z += m[2]
    COG = Vector(mom_x / W, mom_y / W, mom_z / W)
    W = W * G

    # Get the tanks weight
    TW = Units.parseQuantity("0 kg")
    VOLS = []
    for t in tanks:
        # t[0] = tank object
        # t[1] = load density
        # t[2] = filling level
        vol = t[0].Proxy.getVolume(t[0], t[2])
        VOLS.append(vol)
        TW += vol * t[1]
    TW = TW * G

    points = []
    for i,roll in enumerate(rolls):
        App.Console.PrintMessage("{0} / {1}\n".format(i + 1, len(rolls)))
        point = solve_point(W, COG, TW, VOLS,
                            ship, tanks, roll, var_trim)
        if point is None:
            return []
        points.append(point)

    return points
开发者ID:abdullahtahiriyo,项目名称:FreeCAD_sf_master,代码行数:55,代码来源:Tools.py

示例9: __init__

        def __init__(self,game,f):
          self.dieties = dict([(i,Diety.Computer(game)) for i in Diety.RACE])
          self.game = game
          self.Units = Units # an ugly hack to avoid circular imports

          Units.generateUnits()
          self.U=self.Units.U
          self.L = [[None]*self.HEIGHT for dummy in xrange(self.WIDTH)]
          self.M = [(x,y) for y in xrange(self.HEIGHT) for x in xrange(self.WIDTH)]
          if f:
            self.load(f)
开发者ID:haitike,项目名称:berto-s-dimensional-wars,代码行数:11,代码来源:Map.py

示例10: floatingArea

def floatingArea(ship, draft=None,
                       roll=Units.parseQuantity("0 deg"), 
                       trim=Units.parseQuantity("0 deg")):
    """Compute the ship floating area

    Position arguments:
    ship -- Ship object (see createShip)

    Keyword arguments:
    draft -- Ship draft (Design ship draft by default)
    roll -- Roll angle (0 degrees by default)
    trim -- Trim angle (0 degrees by default)

    Returned values:
    area -- Ship floating area
    cf -- Floating area coefficient
    """
    if draft is None:
        draft = ship.Draft

    # We wanna intersect the whole ship with the free surface, so in this case
    # we must not use the underwater side (or the tool will fail)
    shape, _ = placeShipShape(ship.Shape.copy(), draft, roll, trim)

    try:
        f = Part.Face(shape.slice(Vector(0,0,1), 0.0))
        area = Units.Quantity(f.Area, Units.Area)
    except Part.OCCError:
        msg = QtGui.QApplication.translate(
            "ship_console",
            "Part.OCCError: Floating area cannot be computed",
            None,
            QtGui.QApplication.UnicodeUTF8)
        App.Console.PrintError(msg + '\n')
        area = Units.Quantity(0.0, Units.Area)

    bbox = shape.BoundBox
    Area = (bbox.XMax - bbox.XMin) * (bbox.YMax - bbox.YMin)
    try:
        cf = area.Value / Area
    except ZeroDivisionError:
        msg = QtGui.QApplication.translate(
            "ship_console",
            "ZeroDivisionError: Null area found during the floating area"
            " computation!",
            None,
            QtGui.QApplication.UnicodeUTF8)
        App.Console.PrintError(msg + '\n')
        cf = 0.0

    return area, cf
开发者ID:3DPrinterGuy,项目名称:FreeCAD,代码行数:51,代码来源:Tools.py

示例11: mainFrameCoeff

def mainFrameCoeff(ship, draft=None):
    """Compute the main frame coefficient

    Position arguments:
    ship -- Ship object (see createShip)

    Keyword arguments:
    draft -- Ship draft (Design ship draft by default)

    Returned value:
    Ship main frame area coefficient
    """
    if draft is None:
        draft = ship.Draft

    shape, _ = placeShipShape(ship.Shape.copy(), draft,
                              Units.parseQuantity("0 deg"),
                              Units.parseQuantity("0 deg"))
    shape = getUnderwaterSide(shape)

    try:
        f = Part.Face(shape.slice(Vector(1,0,0), 0.0))
        area = f.Area
    except Part.OCCError:
        msg = QtGui.QApplication.translate(
            "ship_console",
            "Part.OCCError: Main frame area cannot be computed",
            None,
            QtGui.QApplication.UnicodeUTF8)
        App.Console.PrintError(msg + '\n')
        area = 0.0

    bbox = shape.BoundBox
    Area = (bbox.YMax - bbox.YMin) * (bbox.ZMax - bbox.ZMin)

    try:
        cm = area / Area
    except ZeroDivisionError:
        msg = QtGui.QApplication.translate(
            "ship_console",
            "ZeroDivisionError: Null area found during the main frame area"
            " coefficient computation!",
            None,
            QtGui.QApplication.UnicodeUTF8)
        App.Console.PrintError(msg + '\n')
        cm = 0.0

    return cm
开发者ID:3DPrinterGuy,项目名称:FreeCAD,代码行数:48,代码来源:Tools.py

示例12: turn

def turn(gc, unit):
    # t = time.time()
    result = Units.shoot_at_best_target(gc, unit)
    # Globals.ranger_find_time += time.time() - t
    # print("find target time", Globals.ranger_find_time)
    if isinstance(result, bc.Unit):
        return
    elif isinstance(result, bc.VecUnit):
        nearby_enemies = result
    else:
        nearby_enemies = send_radar_info(unit, gc)
    # t = time.time()
    if gc.is_move_ready(unit.id):
        e, should_retreat = ranger_retreat(unit, nearby_enemies)
        if should_retreat:
            moved = Navigation.retreatFromKnownEnemy(gc, unit, Globals.radar.get_enemy_center(unit.location.map_location().planet))
            if moved:
                return
        if gc.is_attack_ready(unit.id):
            planet = unit.location.map_location().planet
            path = Globals.updatePath if planet == bc.Planet.Earth else Globals.updatePathMars
            Navigation.path_with_bfs(gc, unit, path)
    # Globals.ranger_else_time += time.time() - t
    # print("other ranger time", Globals.ranger_else_time)
    return
开发者ID:trice07,项目名称:One-West-BC,代码行数:25,代码来源:Ranger.py

示例13: drawHUD

	def drawHUD(self, unitOn, camera):
		HEALTHSIZE = 100
		unit = PTRS["UNITS"].alliedUnits[unitOn]
		if unit:
			if unit.getTargetHealth() > 0 or unit.getHealth() > 0:
				healthBarRect = [[10, camera.Height() - 20], [HEALTHSIZE, 12]]
				expBarRect = [[10, camera.Height() - 40], [HEALTHSIZE, 12]]
				self.drawStatusBar(unit, camera, unit.getHealth(), unit.getTargetHealth(), unit.getMaxHealth(), healthBarRect,
																				[255, 0, 0], [0, 255, 0], [155, 0, 0])
				self.drawStatusBar(unit, camera, unit.guilds.getActiveGuild().experience, unit.guilds.getActiveGuild().targetExperience,
																				unit.guilds.getActiveGuild().getExperienceRequirement(), expBarRect,
																				EXPERIENCECOLOUR, DARKEXPERIENCECOLOUR, [255, 255, 255])

			for i in range(ABILITYSLOTS):
				abil = unit.getSelectedAbil(i)
				if abil:
					icon = abil.icon
					if i == unit.selectedAbil:
						frameIcon = "SelectedFrame"
					else:
						frameIcon = "BattleFrame"
					
					pos = (5 + i * 45, 5)
					if abil.cooldown[0] > 0:
						drawAbilIcon(camera.getSurface(), pos, icon, frameIcon, abil.cooldown[0] / float(abil.cooldown[1]))
					else:
						drawAbilIcon(camera.getSurface(), pos, icon, frameIcon)
			
			if unit.lastHitTargets:
				on = len(unit.lastHitTargets)
				done = 0
				for u in unit.lastHitTargets:
					if not u.isTrainingDummy():
						pos = [camera.Width() - HEALTHSIZE - 10, camera.Height() - 20 - done * 15]
						hPct = u.getHealth() / float(u.getMaxHealth())
						hAmt = min(max(int(HEALTHSIZE * hPct), 1), HEALTHSIZE)
						clr = [150, 0, 0]
						if u == unit.target:
							clr = [255, 0, 0]
						pygame.draw.rect(camera.getSurface(), clr, [pos, [hAmt, 10]]) #Bright red health
						pygame.draw.rect(camera.getSurface(), [255] * 3, [pos, [HEALTHSIZE, 10]], 1)
						if unit.team == 1:
							Units.drawEnemyPic(camera.getSurface(), u.picture, [pos[0] - 15, pos[1]], int(u.animationFrames[int(u.frame)]))
						on -= 1
						done += 1
						if done > 5:
							break
开发者ID:TheOneTrueGod,项目名称:DunGen,代码行数:47,代码来源:Game.py

示例14: _getPuntualMass

    def _getPuntualMass(self, fp, shape):
        """Compute the mass of a puntual element.

        Position arguments:
        fp -- Part::FeaturePython object affected.
        shape -- Vertex shape object.
        """
        return Units.parseQuantity('{0} kg'.format(fp.Mass))
开发者ID:3DPrinterGuy,项目名称:FreeCAD,代码行数:8,代码来源:WeightInstance.py

示例15: onUpdate

    def onUpdate(self):
        """ Method called when the data update is requested. """
        if not self.ship:
            return
        mw = self.getMainWindow()
        form = mw.findChild(QtGui.QWidget, "TaskPanel")
        form.draft = self.widget(QtGui.QLineEdit, "Draft")
        form.trim = self.widget(QtGui.QLineEdit, "Trim")
        form.output = self.widget(QtGui.QTextEdit, "OutputData")

        draft = Units.parseQuantity(Locale.fromString(form.draft.text()))
        trim = Units.parseQuantity(Locale.fromString(form.trim.text()))

        # Calculate the drafts at each perpendicular
        angle = trim.getValueAs("rad").Value
        L = self.ship.Length.getValueAs('m').Value
        B = self.ship.Breadth.getValueAs('m').Value
        draftAP = draft + 0.5 * self.ship.Length * math.tan(angle)
        if draftAP < 0.0:
            draftAP = 0.0
        draftFP = draft - 0.5 * self.ship.Length * math.tan(angle)
        if draftFP < 0.0:
            draftFP = 0.0
        # Calculate the involved hydrostatics
        disp, B, _ = Hydrostatics.displacement(self.ship,
                                               draft,
                                               Units.parseQuantity("0 deg"),
                                               trim)
        xcb = Units.Quantity(B.x, Units.Length)
        # Setup the html string
        string = u'L = {0}<BR>'.format(self.ship.Length.UserString)
        string += u'B = {0}<BR>'.format(self.ship.Breadth.UserString)
        string += u'T = {0}<HR>'.format(draft.UserString)
        string += u'Trim = {0}<BR>'.format(trim.UserString)
        string += u'T<sub>AP</sub> = {0}<BR>'.format(draftAP.UserString)
        string += u'T<sub>FP</sub> = {0}<HR>'.format(draftFP.UserString)
        dispText = QtGui.QApplication.translate(
            "ship_areas",
            'Displacement',
            None,
            QtGui.QApplication.UnicodeUTF8)
        string += dispText + u' = {0}<BR>'.format(disp.UserString)
        string += u'XCB = {0}'.format(xcb.UserString)
        form.output.setHtml(string)
开发者ID:3DPrinterGuy,项目名称:FreeCAD,代码行数:44,代码来源:TaskPanel.py


注:本文中的Units类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。