示例#1
0
 def setLocationAndRotation(self, location, *args):
     if len(args) == 3:
         self._matrix = MathUtil.buildTransformMatrix(location, *args)
     else:
         self._matrix = MathUtil.buildTransformMatrixQ(location, *args)
     if hasattr(self, "body") and self.body is not None:
         self.body.SetMatrix(self._matrix.toList())
def removeVarWithLowPotency(scenario, allCEVarList):
    hataSRD = MathUtil.HataSRDModel()

    maxDistanceCEAndClients = []

    for ce in scenario.cm.ceList:
        clientDistanceList = []

        for ceClient in ce.clientList:
            distanceBetween = MathUtil.calculateDistanceBetweenGeoPoints(
                ce.geoPoint, ceClient.geoPoint)
            clientDistanceList.append(distanceBetween)

        maxClientDistance = max(clientDistanceList)
        maxDistanceCEAndClients.append(maxClientDistance)

    newCEVarList = []

    for ceVar in allCEVarList:
        ceVarNameSplit = ceVar.name.split('_')

        ceId = int(ceVarNameSplit[1])
        cePotency = int(ceVarNameSplit[3])

        ceAntenna = scenario.cm.ceList[ceId].antenna
        channelFrequency = next(c.frequency for c in scenario.channels
                                if (c.channelNumber == ce.channel))

        ceSignalDistance = hataSRD.getDistance(ceAntenna, channelFrequency,
                                               cePotency, -60)

        if (ceSignalDistance >= maxDistanceCEAndClients[ceId]):
            newCEVarList.append(ceVar)

    return newCEVarList
示例#3
0
def analyze(stock_code, date, period):
    score = 0.0
    signal = ""
    RSI = getRSI(stock_code, date)
    if 90 > RSI > 80:
        score -= 1
        signal += "[-1]当六日指标上升到达80时,表示股市已有超买现象;"
    if RSI > 90:
        score -= -1
        signal += "[-1]超过90以上时,则表示已到严重超买的警戒区,股价已形成头部,极可能在短期内反转回转;"
    if 10 < RSI < 20:
        score += 1
        signal += "[1]六日强弱指标下降至20时,表示股市有超卖现象;"
    if RSI < 10:
        score += 1
        signal += "[1]一旦继续下降至10以下时则表示已到严重超卖区域,股价极可能有止跌回升的机会;"

    close_in_period = bd.getBasicDataInPeriod("CLOSE_TODAY", stock_code, date, period)
    RSI_in_period = bd.getTechDataInPeriod("CCI", stock_code, date, period)
    close_k = mu.getPoly(close_in_period, 1)[0]
    RSI_k = mu.getPoly(RSI_in_period, 1)[0]

    if close_k > 0 and RSI_k < 0:
        signal += "强弱指标下降而股价反趋上涨,产生的背离现象;"
    if close_k < 0 and RSI_k > 0:
        signal += "强弱指标上升而股价反而下跌, 产生的背离现象;"
    print score
    print signal.decode("utf-8").encode("gbk")
    bd.updateAnalysisData("RSI", str(score) + ";" + signal, stock_code, date)
    return [score, signal]
示例#4
0
def analyze(stock_code, date, period):
    signal = ""
    score = 0.0
    BR = getBR(stock_code, date)
    AR = getAR(stock_code, date)

    if (BR < AR) and (BR < 100):
        score += 1
        signal += "[1]BR<AR,且BR<100,可考虑逢低买进;"

    if (BR < AR) and (AR < 50):
        score += 1
        signal += "[1]BR<AR,而AR<50时,是买进信号;"

    BRs = getBRs(stock_code, date, period)
    ARs = getARs(stock_code, date, period)
    BR_K = mu.getPoly(BRs, 1)[0]
    AR_K = mu.getPoly(ARs, 1)[0]

    if (BR_K >= UP_RATIO_THREHOLD) and (AR_K >= UP_RATIO_THREHOLD):
        score -= 1
        signal += "[-1]AR和BR同时急速上升,意味着股价已近顶部,持股者应逢高卖出;"

    print score
    print signal.decode("utf-8").encode("gbk")
    bd.updateAnalysisData("BRAR", str(score) + ";" + signal, stock_code, date)
    return [score, signal]
示例#5
0
	def getInterpolatedHeight( self, fx, fy ):
		x, y = self.correctXY( fx, fy )
		t = self.getTriangleAtPosition( x, y )

		#calculate the triangle's plane
		plane = MathUtil.getTrianglePlane( t[0], t[1], t[2] )
		return MathUtil.intersectRayWithPlane( plane, vec3( x,0,y), vec3(0,1,0 ) )
示例#6
0
文件: Ents.py 项目: fathat/game-src
 def setLocationAndRotation(self, location, *args ):
     if len(args) == 3:
         self._matrix = MathUtil.buildTransformMatrix(location, *args)
     else:
         self._matrix = MathUtil.buildTransformMatrixQ(location, *args)
     if hasattr(self, "body") and self.body is not None:
         self.body.SetMatrix( self._matrix.toList() )
示例#7
0
    def is_possible_a_to_b(self, boundary_point, point_a, point_b):
        """
        This function checks whether it is possible to go from point_a to point_b by
        straight line. It first calculate the angle between point_a and point_b, then
        checks the boundary_point  for that angle and also check the boundary for that
        angle. If the boundary distance is greater then the distance between point_a
        and point_b then it is considered that we can go straightly from point_a to
        point_b.

        @param boundary_point: Boundary point of a sweep calculated using given data.
        @param point_a: Current position of drone/lidar.
        @param point_b: Next position of drone/lidar.
        @Return: return 1 if there is no obstacle from point point_a to point_b when it is
                 considered as straight line otherwise return 0
        """
        angle = MathUtil.angle_anti_clockwise(point_a, point_b)
        # print(angle)
        temp_boundary_point = boundary_point[:]
        precision = 360.0 / len(temp_boundary_point)

        distance_between_point = MathUtil.distance_a_to_b(point_a,
                                                          point_b) * 1000
        #print(angle, 'log', dis, precision)
        for point in range(len(temp_boundary_point)):
            #print(temp_boundary_point[i][0], angle, temp_boundary_point[i][1], dis)
            if precision > abs(
                    temp_boundary_point[point][0] - angle
            ) and distance_between_point > temp_boundary_point[point][1]:
                return 0
        return 1
示例#8
0
    def getInterpolatedHeight(self, fx, fy):
        x, y = self.correctXY(fx, fy)
        t = self.getTriangleAtPosition(x, y)

        #calculate the triangle's plane
        plane = MathUtil.getTrianglePlane(t[0], t[1], t[2])
        return MathUtil.intersectRayWithPlane(plane, vec3(x, 0, y),
                                              vec3(0, 1, 0))
示例#9
0
文件: Actor.py 项目: fathat/game-src
 def setLocationAndRotation(self, location, *args):
     self.location = location
     if len(args) == 3:
         self.yaw, self.pitch, self.roll = args
     else:
         self.yaw, self.pitch, self.roll = MathUtil.quaternionToEulerYawPitchRoll(*args)
     self.construction.setLocation(location, self.yaw, self.pitch, self.roll)
     self._matrix = MathUtil.buildTransformMatrix(self.location, self.yaw, self.pitch, self.roll)
示例#10
0
文件: Actor.py 项目: fathat/game-src
 def faceTowards(self, direction_vector):
     if direction_vector.length():
         # figure out the current direction
         current_direction = MathUtil.rotateVectorAroundAxis(vec3(0, 0, 1), self.yaw, vec3(0, 1, 0))
         direction_vector = direction_vector.normalize()
         # interpolate between current direction and desired direction
         d = MathUtil.interpolateVectors(current_direction, direction_vector, 0.1)
         self.yaw = MathUtil.yawAngle(d)
def getInterferenceList(scenario, allCEVarList):
    hataSRD = MathUtil.HataSRDModel()
    interferenceList = []

    for ceVar in allCEVarList:
        ceVarNameSplit = ceVar.name.split('_')

        ceId = int(ceVarNameSplit[1])
        ceChannel = int(ceVarNameSplit[2])
        cePotency = int(ceVarNameSplit[3])

        ce = scenario.cm.ceList[ceId]
        channel = next(c for c in scenario.channels
                       if c.channelNumber == ceChannel)
        ceSignalDistance = hataSRD.getDistance(ce.antenna, channel.frequency,
                                               cePotency, -60)

        ceTotalInterference = 0.0
        ceInterferenceList = []

        for otherCEVar in allCEVarList:
            otherCEVarNameSplit = otherCEVar.name.split('_')

            otherCEId = int(otherCEVarNameSplit[1])
            otherCEChannel = int(otherCEVarNameSplit[2])

            if (otherCEId != ceId):
                otherCE = scenario.cm.ceList[otherCEId]
                distanceBetweenCEs = MathUtil.calculateDistanceBetweenGeoPoints(
                    ce.geoPoint, otherCE.geoPoint)
                signalLevel = MathUtil.dbm2Double(
                    hataSRD.getSignalLevel(ce.antenna, channel.frequency,
                                           cePotency, distanceBetweenCEs))

                if (ceSignalDistance >= distanceBetweenCEs):
                    if (otherCEChannel == ceChannel):
                        signalLevel = 1.0 * signalLevel
                        ceTotalInterference += signalLevel
                        ceInterferenceList.append(signalLevel)
                    elif (otherCEChannel
                          == (ceChannel - 1)) or (otherCEChannel
                                                  == (ceChannel + 1)):
                        signalLevel = 0.7 * signalLevel
                        ceTotalInterference += signalLevel
                        ceInterferenceList.append(signalLevel)
                    elif (otherCEChannel
                          == (ceChannel - 2)) or (otherCEChannel
                                                  == (ceChannel + 2)):
                        signalLevel = 0.3 * signalLevel
                        ceTotalInterference += signalLevel
                        ceInterferenceList.append(signalLevel)

        interferenceList.append(
            (ceVar, ceTotalInterference, ceInterferenceList))

    return interferenceList
示例#12
0
文件: Actor.py 项目: ylyking/game-src
 def faceTowards(self, direction_vector):
     if direction_vector.length():
         #figure out the current direction
         current_direction = MathUtil.rotateVectorAroundAxis(
             vec3(0, 0, 1), self.yaw, vec3(0, 1, 0))
         direction_vector = direction_vector.normalize()
         # interpolate between current direction and desired direction
         d = MathUtil.interpolateVectors(current_direction,
                                         direction_vector, 0.1)
         self.yaw = MathUtil.yawAngle(d)
示例#13
0
文件: Actor.py 项目: ylyking/game-src
 def setLocationAndRotation(self, location, *args):
     self.location = location
     if len(args) == 3:
         self.yaw, self.pitch, self.roll = args
     else:
         self.yaw, self.pitch, self.roll = MathUtil.quaternionToEulerYawPitchRoll(
             *args)
     self.construction.setLocation(location, self.yaw, self.pitch,
                                   self.roll)
     self._matrix = MathUtil.buildTransformMatrix(self.location, self.yaw,
                                                  self.pitch, self.roll)
示例#14
0
 def get_inbd_track(self, wp):
     """Returns the inbound track to the given waypoint"""
     i = self.get_waypoint_index(wp)
     if i >= 0 and i < len(self) and self[i].inbd_track:
         return self[i].inbd_track
     # else
     if i < 1: i = 1
     if i > (len(self) - 1): i = len(self) - 1
     (distance,
      bearing) = MathUtil.rp(MathUtil.r(self[i].pos(), self[i - 1].pos()))
     self[i].inbd_track = bearing
     return bearing
示例#15
0
def analyze(stock_code, date, period):
    score = 0.0
    signal = ""
    pday = bd.getStockDate(stock_code, date, 1)

    CCI = getCCI(stock_code, date)
    CCI_pday = getCCI(stock_code, pday)
    CCIs = getCCIs(stock_code, date, period)
    CCI_K1 = mu.getPoly(CCIs, 1)[0]
    CCI_K2 = mu.getPoly(CCIs, 2)[0]

    print CCI
    print CCI_pday
    print CCIs
    print CCI_K1
    print CCI_K2


    if CCI > 100:
        score -= 0.5
        signal += "[-0.5]当CCI>﹢100时,表明股价已经进入非常态区间—超买区间;"
        if CCI_K1 > 0:
            score += 1
            signal += "[1]CCI曲线向上突破﹢100线而进入非常态区间后,只要CCI曲线一直朝上运行,就表明股价强势依旧,中短线应及时买入,如果有比较大的成交量配合,买入信号则更为可靠;"
        if CCI_K2 < 0 and (CCI -100) >= CCI_THREHOLD:
            score -= 1
            signal += "[-1]当CCI曲线在﹢100线以上的非常态区间,在远离﹢100线的地方开始掉头向下时,表明股价的强势状态将难以维持,是股价比较强的转势信号。如果前期的短期涨幅过高时,更可确认。此时,投资者应及时逢高卖出股票;"

    if CCI < -100:
        score += 0.5
        signal += "[0.5]当CCI<﹣100时,表明股价已经进入另一个非常态区间—超卖区间;"
        if CCI_K1 < 0:
            score -= 1
            signal += "[-1]当CCI曲线向下突破﹣100线而进入另一个非常态区间后,只要CCI曲线一路朝下运行,就表明股价弱势依旧,投资者可一路观望;"
        if CCI_K2 > 0:
            score += 0.5
            signal += "[0.5]当CCI曲线向下突破﹣100线而进入另一个非常态区间,如果CCI曲线在超卖区运行了相当长的一段时间后开始掉头向上,表明股价的短期底部初步找到,投资者可少量建仓。CCI曲线在超卖区运行的时间越长,越可以确认短期的底部;"

    if CCI_pday >= 100 and CCI < 100:
        score -= 1
        signal += "[-1]当CCI指标从上向下突破﹢100线而重新进入常态区间时,表明股价的上涨阶段可能结束,将进入一个比较长时间的盘整阶段。投资者应及时逢高卖出股票;"

    if CCI_pday <= -100 and CCI > -100:
        score += 0.5
        signal += "[0.5]当CCI指标从下向上突破﹣100线而重新进入常态区间时,表明股价的探底阶段可能结束,又将进入一个盘整阶段。投资者可以逢低少量买入股票;"

    print score
    print signal.decode("utf-8").encode("gbk")
    bd.updateAnalysisData("CCI", str(score) + ";" + signal, stock_code, date)
    return [score, signal]
示例#16
0
    def __init__(self, dir_path, slices):
        ##### CT IMAGE DATA #####
        self.dir_path = dir_path
        self.dicom_slices = slices

        # The ID of the patient from whom the cross sectional image was scanned
        self.patient_id = self.dicom_slices[0].__getattr__("PatientID")

        # The shape of an individual slice in the cross sectional image in 2D NumPy form
        self.slice_shape = self.dicom_slices[0].pixel_array.shape

        # The number of slices in the cross sectional image
        self.slice_count = len(self.dicom_slices)

        # The shape the cross sectional image in (y, x, z) form; NOT NumPy shape format
        self.shape = [
            self.slice_shape[0], self.slice_shape[1], self.slice_count
        ]

        # The second lowest pixel value of all slices in the cross sectional image (the lowest is padding and should
        # not be counted)
        self.global_min = MathUtil.second_min(
            min(self.dicom_slices,
                key=lambda slice: MathUtil.second_min(slice.pixel_array)).
            pixel_array)

        # The highest pixel value of all slices in the cross sectional image
        self.global_max = max(
            self.dicom_slices,
            key=lambda slice: slice.pixel_array.max()).pixel_array.max()

        ##### ANNOTATIONS #######

        # The superior crop boundary slice of the cross sectional image; when cropping, this will be the topmost slice
        # included in the cropped data
        self.superior_slice = 0

        # The inferior crop boundary slice of the cross sectional image; when cropping, this will be the bottommost
        # slice included in the cropped data
        self.inferior_slice = self.slice_count - 1

        # The scale factor used to scale XY crop boundaries for individual slices; when this is 1, the crop boundaries
        # at the superior and inferior slices will be exactly at the heart landmarks for those respective slices
        self.landmark_scale_factor = 1.6

        # The HeartLandmarks object that stores the eight annotated heart landmarks for the cross sectional image
        self.heart_landmarks = HeartLandmarks()

        self.set_default_landmarks()
示例#17
0
def fit_sphere(p1, n1, p2, n2, eps=0.005, alpha=np.deg2rad(30.0)):
  ''' 
    fit a sphere to the two point/normal pairs 
    eps: distance thres for determining if the fit is a valid sphere
          both points must be < eps from the sphere
    alpha: angle thres for determining if the fit is a valid sphere
          both normals must be < alpha from the sphere normals

    return (valid, center, radius);
      valid is a bool indicating if the fit was valid based on the points and normals
  '''
  p1 = np.asarray(p1);
  n1 = np.asarray(n1);
  p2 = np.asarray(p2);
  n2 = np.asarray(n2);

  # find closes points on the lines
  (pc0, pc1) = mu.line_line_closest_point(p1, n1, p2, n2);
  # center of the sphere
  c = (pc0 + pc1) / 2.0;
  # compute radius
  r = (np.linalg.norm(p1-c) + np.linalg.norm(p2-c))/2.0;

  # check if the fit is valid
  if ((np.abs(r - np.linalg.norm(p1 - c)) > eps)
      or (np.abs(r - np.linalg.norm(p2 - c)) > eps)):
    return (False, c, r);

  sa = np.sin(alpha);
  if ((np.sin(np.abs(ru.angle_between(n1, p1-c))) > sa)
      or (np.sin(np.abs(ru.angle_between(n2, p2-c))) > sa)):
    return (False, c, r);
  
  return (True, c, r);
示例#18
0
    def reduce(self, uid, values):
        values = [eval(text_dict) for text_dict in values]
        c = Cluster()
        c.uid = uid
        c_total = len(values)
        sqdist = 0.0

        # set cluster center to sum of members
        for doc in values:
            for tokenid in doc:
                if c.tfidf.has_key(tokenid):
                    c.tfidf[tokenid] += doc[tokenid]
                else:
                    c.tfidf[tokenid] = doc[tokenid]


        # set cluster center, currently the sum, to the mean
        for tokenid in c.tfidf:
            c.tfidf[tokenid] = c.tfidf[tokenid] / float(c_total)

        # set sqdist to the squared sum of deviations from mean
        for doc in values:
            sqdist += MathUtil.compute_distance(c.tfidf, doc, squared=True)

        # Output the cluster center into file: clusteri
        self.emit("cluster" + str(c.uid), str(c))
        # Output the within distance into file: distancei
        self.emit("distance" + str(c.uid), str(c.uid) + "|" + str(sqdist))
示例#19
0
    def _markWalkableAreas(self):
        self.walkableMask   = [True]*self.size*self.size
        index = 0
        for tz in xrange(self.size):
            for tx in xrange(self.size):
                v1,v2,v3,v4,v5,v6 = self.heightmap.getTrianglesAt( tx, tz )
                normal1 = MathUtil.getTriangleNormal( v1, v3, v2  )
                normal2 = MathUtil.getTriangleNormal( v4, v6, v5  )

                #mix the two normals to get an average
                normal = ((normal1 + normal2)/2.0).normalize()
                height = self.heightmap.getHeight(tx, tz)
                if height < self.world.seaLevel or normal.y < 0.1:
                    self.walkableMask[index] = False
                index += 1
        self.astarMap = AStar.AStarMap( self.walkableMask, self.size, self.size )
示例#20
0
    def reduce(self, uid, values):
        # values is a list of dictionaries
        c = Cluster()
        c.uid = int(uid)
        sqdist = 0.0

        # Compute new center
        count = 0
        for value in values:
            count += 1
            doc = Document(value)
            for key, v in doc.tfidf.items():
                c.tfidf[key] = c.tfidf.get(key, 0.0) + v

        for key in c.tfidf:
            c.tfidf[key] /= count

        # Get within cluster distance
        for value in values:
            doc = Document(value)
            sqdist += MathUtil.compute_distance(c.tfidf, doc.tfidf)

        # Output the cluster center into file: clusteri
        self.emit("cluster" + str(c.uid), str(c))
        # Output the within distance into file: distancei
        self.emit("distance" + str(c.uid), str(c.uid) + "|" + str(sqdist))
示例#21
0
def analyze(stock_code, date, period1, period2):
    signal = ""
    score = 0.0
    recent_high_price = bd.getHighPriceInPeriod("CLOSE_TODAY", stock_code, date, period1)
    recent_low_price = bd.getLowPriceInPeriod("CLOSE_TODAY", stock_code, date, period1)
    close_today = bd.getBasicData("CLOSE_TODAY", stock_code, date)
    BBI = getBBI(stock_code, date)

    if (abs(close_today - recent_high_price) / recent_high_price <= HIGH_OFFSET / 100) and (BBI > close_today):
        score = score - 1
        signal = signal + "[-1]股价在高价区以收市价跌破多空线为卖出信号;"

    if (abs(close_today - recent_low_price) / recent_low_price <= LOW_OFFSET / 100) and (BBI < close_today):
        score = score + 1
        signal = signal + "[1]股价在低价区以收市价突破多空线为买入信号;"

    BBIs = getBBIs(stock_code, date, period2)
    K = mu.getPoly(BBIs, 1)[0]

    if (K > 0) and (BBI > close_today):
        score += 1
        signal += "[1]多空指数由下向上递增,股价在多空线上方,表明多头势强,可以继续持股;"

    if (K < 0) and (BBI < close_today):
        score -= 1
        signal += "[-1]多空指数由上向下递减,股价在多空线下方,表明空头势强,一般不宜买入;"

    print score
    print signal.decode("utf-8").encode("gbk")
    bd.updateAnalysisData("BBI", str(score) + ";" + signal, stock_code, date)
    return [score, signal]
示例#22
0
文件: WR.py 项目: A1eXFei/StockMarket
def analyze(stock_code, date, period):
    score = 0
    signal = ""
    WR = getWR(stock_code, date)
    if WR >= 80:
        score += 1
        signal += "[1]当%R线达到80时,市场处于超卖状况,股价走势随时可能见底。因此,80的横线一般称为买进线,投资者在此可以伺机买入;"
    if WR <= 20:
        score -= 1
        signal += "[-1]当%R线达到20时,市场处于超买状况,走势可能即将见顶,20的横线被称为卖出线;"

    WRs = bd.getTechDataInPeriod("WR", stock_code, date, period)
    WR_K = mu.getPoly(WRs, 1)[0]

    if WR > 50 and WR_K > 0:
        score += 1
        signal += "[1]当%R向下跌破50中轴线时,市场由弱转强,是买进信号;"

    if WR < 50 and WR_K < 0:
        score -= 1
        signal += "[-1]当%R从超买区向上爬升,突破50中轴线后,可以确认强势转弱,是卖出信号;"

    print score
    print signal.decode("utf-8").encode("gbk")
    bd.updateAnalysisData("WR", str(score) + ";" + signal, stock_code, date)
    return [score, signal]
示例#23
0
    def reduce(self, uid, values):
        values = [eval(text_dict) for text_dict in values]
        c = Cluster()
        c.uid = uid
        c_total = len(values)
        sqdist = 0.0

        # set cluster center to sum of members
        for doc in values:
            for tokenid in doc:
                if c.tfidf.has_key(tokenid):
                    c.tfidf[tokenid] += doc[tokenid]
                else:
                    c.tfidf[tokenid] = doc[tokenid]

        # set cluster center, currently the sum, to the mean
        for tokenid in c.tfidf:
            c.tfidf[tokenid] = c.tfidf[tokenid] / float(c_total)

        # set sqdist to the squared sum of deviations from mean
        for doc in values:
            sqdist += MathUtil.compute_distance(c.tfidf, doc, squared=True)

        # Output the cluster center into file: clusteri
        self.emit("cluster" + str(c.uid), str(c))
        # Output the within distance into file: distancei
        self.emit("distance" + str(c.uid), str(c.uid) + "|" + str(sqdist))
示例#24
0
    def reduce(self, uid, values):
        c = Cluster()
        c.uid = uid
        sqdist = 0.0
        # TODO: update the cluster center
        instances = []
        for value in values:
            doc = Document(value)
            instances.append(doc)
            for token in doc.tfidf.keys():
                bool = token in c.tfidf.keys()
                if bool:
                    c.tfidf[token] += doc.tfidf[token]
                else:
                    c.tfidf[token] = doc.tfidf[token]

        size = float(len(values))
        for token in c.tfidf.keys():
            c.tfidf[token] = c.tfidf[token] / size
        #compute the distance
        for instance in instances:
            sqdist += MathUtil.compute_distance(map1=c.tfidf,
                                                map2=instance.tfidf)

        # Output the cluster center into file: clusteri
        self.emit("cluster" + str(c.uid), str(c))
        # Output the within distance into file: distancei
        self.emit("distance" + str(c.uid), str(c.uid) + "|" + str(sqdist))
示例#25
0
    def _markWalkableAreas(self):
        self.walkableMask = [True] * self.size * self.size
        index = 0
        for tz in xrange(self.size):
            for tx in xrange(self.size):
                v1, v2, v3, v4, v5, v6 = self.heightmap.getTrianglesAt(tx, tz)
                normal1 = MathUtil.getTriangleNormal(v1, v3, v2)
                normal2 = MathUtil.getTriangleNormal(v4, v6, v5)

                #mix the two normals to get an average
                normal = ((normal1 + normal2) / 2.0).normalize()
                height = self.heightmap.getHeight(tx, tz)
                if height < self.world.seaLevel or normal.y < 0.1:
                    self.walkableMask[index] = False
                index += 1
        self.astarMap = AStar.AStarMap(self.walkableMask, self.size, self.size)
示例#26
0
    def reduce(self, uid, values):
        c = Cluster()
        c.uid = uid
        sqdist = 0.0
        # TODO: update the cluster center 
        instances = []
        for value in values:
            doc = Document(value)
            instances.append(doc)
            for token in doc.tfidf.keys():
                bool = token in c.tfidf.keys()
                if bool:
                    c.tfidf[token] += doc.tfidf[token]
                else:
                    c.tfidf[token] = doc.tfidf[token]
                
        size = float(len(values))
        for token in c.tfidf.keys():
            c.tfidf[token] = c.tfidf[token]/size
        #compute the distance    
        for instance in instances:
            sqdist += MathUtil.compute_distance(map1 = c.tfidf, map2 = instance.tfidf) 

        # Output the cluster center into file: clusteri
        self.emit("cluster" + str(c.uid), str(c))
        # Output the within distance into file: distancei
        self.emit("distance" + str(c.uid), str(c.uid) + "|" + str(sqdist))
示例#27
0
def normalize_slice_projection(slice_pixel_array, crop_bounds, desired_width,
                               desired_height):
    result = np.zeros((desired_height, desired_width))
    #Crop bounds must be converted from (x, y) points to (y, x) points
    source_bounds = np.asarray([[0, 0], [0, desired_width],
                                [desired_height, desired_width],
                                [desired_height, 0]])
    destination_bounds = np.asarray([[crop_bounds[0][1], crop_bounds[0][0]],
                                     [crop_bounds[1][1], crop_bounds[1][0]],
                                     [crop_bounds[2][1], crop_bounds[2][0]],
                                     [crop_bounds[3][1], crop_bounds[3][0]]])
    projective_transform = ProjectiveTransform()
    if not projective_transform.estimate(source_bounds, destination_bounds):
        print("Cannot project from crop bounds to desired image dimensions")
    else:
        for x in range(0, desired_width):
            for y in range(0, desired_height):
                normalized_point = [y, x]
                transform = projective_transform(normalized_point)
                slice_point = transform[0]
                value = MathUtil.sample_image_bilinear(slice_pixel_array,
                                                       slice_point[1],
                                                       slice_point[0])
                result[y][x] = value

    return result
示例#28
0
def fit_sphere(p1, n1, p2, n2, eps=0.005, alpha=np.deg2rad(30.0)):
    ''' 
    fit a sphere to the two point/normal pairs 
    eps: distance thres for determining if the fit is a valid sphere
          both points must be < eps from the sphere
    alpha: angle thres for determining if the fit is a valid sphere
          both normals must be < alpha from the sphere normals

    return (valid, center, radius);
      valid is a bool indicating if the fit was valid based on the points and normals
  '''
    p1 = np.asarray(p1)
    n1 = np.asarray(n1)
    p2 = np.asarray(p2)
    n2 = np.asarray(n2)

    # find closes points on the lines
    (pc0, pc1) = mu.line_line_closest_point(p1, n1, p2, n2)
    # center of the sphere
    c = (pc0 + pc1) / 2.0
    # compute radius
    r = (np.linalg.norm(p1 - c) + np.linalg.norm(p2 - c)) / 2.0

    # check if the fit is valid
    if ((np.abs(r - np.linalg.norm(p1 - c)) > eps)
            or (np.abs(r - np.linalg.norm(p2 - c)) > eps)):
        return (False, c, r)

    sa = np.sin(alpha)
    if ((np.sin(np.abs(ru.angle_between(n1, p1 - c))) > sa)
            or (np.sin(np.abs(ru.angle_between(n2, p2 - c))) > sa)):
        return (False, c, r)

    return (True, c, r)
示例#29
0
 def updateForces(self, timedelta, maxForce, yaw=0):
     #take moveVector, rotate it by yaw, and scale it
     strafe_force = -self.moveVector.x
     fwd_force = self.moveVector.z
     torque_vec = vec3( fwd_force, 0, strafe_force )
     self.moveForce = MathUtil.rotateVectorAroundAxis(torque_vec, yaw, vec3(0,1,0), True )
     self.moveForce = self.moveForce * 20
示例#30
0
 def updateForces(self, timedelta, maxForce, yaw=0):
     #take moveVector, rotate it by yaw, and scale it
     strafe_force = -self.moveVector.x
     fwd_force = self.moveVector.z
     torque_vec = vec3(fwd_force, 0, strafe_force)
     self.moveForce = MathUtil.rotateVectorAroundAxis(
         torque_vec, yaw, vec3(0, 1, 0), True)
     self.moveForce = self.moveForce * 20
示例#31
0
 def setDesiredVelocity(self, vector, yaw=0):
     """Sets the motion vector for the avatar to move in."""
     self.body.Unfreeze()
     if yaw:
         self.moveVector = MathUtil.rotateVectorAroundAxis(
             vector, yaw, vec3(0, 1, 0))
     else:
         self.moveVector = vector
示例#32
0
def InstanceDataFromPacket(packet):
    """Grab instance data from the packet"""
    typepath = Platform.asOSPath(packet.typepath)
    typestr = GetEntTypeInfoForTypePath(typepath).typeClass
    yaw, pitch, roll = MathUtil.quaternionToEulerYawPitchRoll(
        quat(packet.qw, packet.qx, packet.qy, packet.qz))
    return EntInstanceData(None, typestr, typepath, packet.scriptname,
                           packet.x, packet.y, packet.z, yaw, pitch, roll)
示例#33
0
 def setDesiredVelocity(self, vector, yaw=0):
     """Sets the motion vector for the avatar to move in."""
     self.body.Unfreeze()
     if yaw:
         self.moveVector = MathUtil.rotateVectorAroundAxis(vector,
                                                           yaw,
                                                           vec3(0,1,0))
     else:
         self.moveVector = vector
示例#34
0
文件: AI.py 项目: ylyking/game-src
 def draw(self):
     #find camera's transform matrix
     m = MathUtil.buildTransformMatrix(self.ent.headLocation,
                                       self.ent.yaw + math.pi,
                                       self.ent.pitch, self.ent.roll)
     glPushMatrix()
     glMultMatrixf(m.toList())
     Graphics.drawPyramid(30, 10, 100.0)
     Graphics.drawWirePyramid(30, 10, 100.0)
     glPopMatrix()
示例#35
0
    def pixel_array_to_qimage(self, pixel_array, global_min, global_max):
        normalized_image = MathUtil.scale_matrix(pixel_array, 0, 255,
                                                 global_min, global_max)
        normalized_image = cv2.cvtColor(normalized_image, cv2.COLOR_GRAY2RGB)

        qt_image = QImage(normalized_image.data, normalized_image.shape[1],
                          normalized_image.shape[0],
                          3 * normalized_image.shape[1], QImage.Format_RGB888)

        return qt_image
示例#36
0
文件: TLPV.py 项目: op07n/crujisim
def sector_intersections(route):
    """Given a fp, add waypoints in the intersections of the route with
    the FIR sectors"""
    rte_orig = route[:]

    # Remove previous TLPV waypoints
    for wp in (wp for wp in rte_orig[:] if wp.type == Route.TLPV):
        rte_orig.remove(wp)

    n_added = 0  # Number of added intersections
    for i in range(len(rte_orig) - 1):
        xpoints = []
        for name, boundary in fir.boundaries.items():
            xp_list = MathUtil.get_entry_exit_points(rte_orig[i].pos(),
                                                     rte_orig[i + 1].pos(),
                                                     boundary)
            for xp in xp_list:
                xp.append(name)
            xpoints += xp_list
        xpoints.sort(lambda x, y: cmp(x[2], y[2])
                     )  # Sort according to distance to the first waypoint
        for xp in xpoints:
            wp = Route.WayPoint("X%fY%f" % (xp[1][0], xp[1][1]),
                                type=Route.TLPV)
            if xp[0] == MathUtil.ENTRY:
                wp.sector_entry = xp[3]
            else:
                wp.sector_exit = xp[3]
            route = route[:i + 1 + n_added] + Route.Route(
                [wp]) + route[i + 1 + n_added:]
            n_added += 1

    # If the first point in the route is within a known sector, make sure we note it.
    for sector, boundary in fir.boundaries.items():
        if MathUtil.point_within_polygon(route[0].pos(), boundary):
            route[0].sector_entry = sector
            n_added += 1

    if not n_added:
        logging.warning("No sector entry points found in %s" % str(route))

    return route  # Eliminates redundancy
示例#37
0
def InstanceDataFromPacket( packet ):
    """Grab instance data from the packet"""
    typepath = Platform.asOSPath(packet.typepath)
    typestr = GetEntTypeInfoForTypePath(typepath).typeClass
    yaw, pitch, roll = MathUtil.quaternionToEulerYawPitchRoll( quat( packet.qw, packet.qx, packet.qy, packet.qz) )
    return EntInstanceData(None,
                           typestr,
                           typepath,
                           packet.scriptname,
                           packet.x, packet.y, packet.z,
                           yaw, pitch, roll)
示例#38
0
 def map(self, line):
     # TODO: call `self.emit(key, value)`
     instance = Document(line)
     min_dist = sys.maxsize
     key = -1
     for cluster in self.clusters:
         dist = MathUtil.compute_distance(map1 = cluster.tfidf, map2 = instance.tfidf) 
         if dist < min_dist:
             key = cluster.uid
             min_dist = dist
     self.emit(key, line) #instance.__str__() 
示例#39
0
文件: AI.py 项目: fathat/game-src
	def draw(self):
		#find camera's transform matrix
		m = MathUtil.buildTransformMatrix(self.ent.headLocation,
										  self.ent.yaw + math.pi,
										  self.ent.pitch,
										  self.ent.roll)
		glPushMatrix()
		glMultMatrixf( m.toList() )
		Graphics.drawPyramid(30, 10, 100.0)
		Graphics.drawWirePyramid(30, 10, 100.0)
		glPopMatrix()
示例#40
0
 def __eq__(self, other):
     """Check whether two waypoints may be considered the same (within 0.1 nm)"""
     if not isinstance(other, WayPoint): return False
     try:
         if MathUtil.get_distance(self.pos(), other.pos()) < 0.1:
             return True
         else:
             return False
     except:
         # The previous test may fail for unknown points
         return False
示例#41
0
文件: Actor.py 项目: ylyking/game-src
 def grab(self, thing):
     self.holding = thing
     thing.owner = self
     location = self.location + vec3(0, 9, 0)
     m = MathUtil.buildTransformMatrix(location, 0, 0, 0)
     thing.body.SetMatrix(m.toList())
     thing.body.SetVelocity(self.body.GetVelocity())
     self.slider = self.world.solver.makeSliderJoint(
         (location.x, location.y, location.z), (0, 1, 0), self.body,
         thing.body)
     self.slider.SetMinLimit(7.5)
     self.slider.SetMaxLimit(10)
示例#42
0
 def map(self, line):
     #find cluster assignment by brute force
     doc = Document(line)
     cluster_uid = None
     sqdist_to_nearest = float('inf')
     for cluster_k in self.clusters:
         sqdist_k = MathUtil.compute_distance(map1 = cluster_k.tfidf, map2 = doc.tfidf, squared=True)
         if sqdist_k <= sqdist_to_nearest:
             cluster_uid = cluster_k.uid
     #dutifully emit.
     self.emit(key = cluster_uid, value = doc)
     return
示例#43
0
文件: Actor.py 项目: fathat/game-src
 def grab(self, thing):
     self.holding = thing
     thing.owner = self
     location = self.location + vec3(0, 9, 0)
     m = MathUtil.buildTransformMatrix(location, 0, 0, 0)
     thing.body.SetMatrix(m.toList())
     thing.body.SetVelocity(self.body.GetVelocity())
     self.slider = self.world.solver.makeSliderJoint(
         (location.x, location.y, location.z), (0, 1, 0), self.body, thing.body
     )
     self.slider.SetMinLimit(7.5)
     self.slider.SetMaxLimit(10)
示例#44
0
def DetermineMoveForceForVelocity( velocity, maxForce, body, timedelta, yaw=0):
    """Returns the amount of force to apply to the body to move it at the desired velocity"""
    assert timedelta > 0
    mass, ix, iy, iz = body.GetMassMatrix()
    fx, fy, fz = velocity.x, velocity.y, velocity.z
    vx, vy, vz = body.GetVelocity()

    #figure out neccessary force to move player at desired velocity
    move_force = MathUtil.playerMoveForce(vec3(vx, 0, vz), -yaw, fz, fx,
                                          mass, timedelta, maxForce)
    move_force.y = fy
    return move_force
示例#45
0
 def map(self, line):
     # TODO: call `self.emit(key, value)`
     instance = Document(line)
     min_dist = sys.maxsize
     key = -1
     for cluster in self.clusters:
         dist = MathUtil.compute_distance(map1=cluster.tfidf,
                                          map2=instance.tfidf)
         if dist < min_dist:
             key = cluster.uid
             min_dist = dist
     self.emit(key, line)  #instance.__str__()
示例#46
0
def DetermineMoveForceForVelocity(velocity, maxForce, body, timedelta, yaw=0):
    """Returns the amount of force to apply to the body to move it at the desired velocity"""
    assert timedelta > 0
    mass, ix, iy, iz = body.GetMassMatrix()
    fx, fy, fz = velocity.x, velocity.y, velocity.z
    vx, vy, vz = body.GetVelocity()

    #figure out neccessary force to move player at desired velocity
    move_force = MathUtil.playerMoveForce(vec3(vx, 0, vz), -yaw, fz, fx, mass,
                                          timedelta, maxForce)
    move_force.y = fy
    return move_force
示例#47
0
def analyze(stock_code, date, period):
    score = 0
    signal = ""
    pday = bd.getStockDate(stock_code, date, 1)

    ROC = getROC(stock_code, date)
    ROCMA = calcROCMA(stock_code, date, ROCMA_PARAM)
    ROCEMA = calcROCEMA(stock_code, date, ROCEMA_PARAM)

    ROC_pday = getROC(stock_code, pday)
    ROCMA_pday = calcROCMA(stock_code, pday, ROCMA_PARAM)
    ROCEMA_pday = calcROCEMA(stock_code, pday, ROCEMA_PARAM)

    ROCs = getROCs(stock_code, date, period)
    ROCMAs = getROCMAs(stock_code, date, period)
    ROCEMAs = getROCEMAs(stock_code, date, period)

    ROC_K = mu.getPoly(ROCs, 1)[0]
    ROCMA_K = mu.getPoly(ROCMAs, 1)[0]
    ROCEMA_K = mu.getPoly(ROCEMAs, 1)[0]

    if ROC < 0 and ROCEMA < 0 and ROCMA < 0:
        if ROC > ROC_pday:
            if ROC > ROCEMA and ROC > ROCEMA and ROC_pday < ROCEMA_pday and ROC_pday < ROCMA_pday:
                if (ROC - ROC_pday)/ROC_pday >= ROC_RAISE_RATE and (ROCMA - ROCMA_pday)/ROCMA_pday >= ROCMA_RAISE_RATE \
                        and (ROCEMA - ROCEMA_pday)/ROCEMA_pday >= ROCEMA_RAISE_RATE:
                    score += 1
                    signal += "[1]当ROC,ROCMA,ROCEMA三条线均小于零轴时,ROC迅速同时上穿ROCMA和ROCEMA两条线,而且ROCMA和ROCEMA两条线也处于缓缓上行中,为短线黑马买入信号;"

    if ROC > ROCMA > ROCEMA and ROC_K > ROCMA_K > ROCEMA_K:
        score += 1
        signal += "[1]当ROC,ROCMA,ROCEMA三条线是处于多头排列中,成交量处于间隙式放大或温和放大过程时,表明股价正运行于上升趋势中,仍有继续上涨趋势;"

    if ROC < ROCMA < ROCEMA and ROC_K < ROCMA_K < ROCEMA_K:
        score -= 1
        signal += "[-1]当ROC,ROCMA,ROCEMA三条线是处于空头排列中,表明股价正运行于下行趋势中,仍有继续下跌趋势;"
    print score
    print signal.decode("utf-8").encode("gbk")
    bd.updateAnalysisData("ROC", str(score) + ";" + signal, stock_code, date)
    return [score, signal]
示例#48
0
def analyze(stock_code, date, period):
    score = 0
    signal = ""
    OBVs = bd.getTechDataInPeriod("OBV", stock_code, date, period)
    close_in_period = bd.getBasicDataInPeriod("CLOSE_TODAY", stock_code, date, period)
    OBV_K = mu.getPoly(OBVs, 1)[0]
    CLOSE_K = mu.getPoly(close_in_period, 1)[0]

    # 1.OBV线下降,而此时股价上升,是卖出股票的信号。
    if OBV_K < 0 and CLOSE_K > 0:
        score -= 1
        signal += "[-1]OBV线下降,而此时股价上升,是卖出股票的信号;"
    # 2.OBV线上升,而此时股价下跌,是买进股票的信号。
    if OBV_K > 0 and CLOSE_K < 0:
        score += 1
        signal += "[1]OBV线上升,而此时股价下跌,是买进股票的信号;"

    # 3.OBV线从正的累积数转为负数时,为下跌趋势,应该卖出持有股票;反之,OBV线从负的累积数转为正数,应该买进股票。
    OBV_today = OBVs[0]
    OBV_pday = OBVs[1]
    if OBV_today > 0 and OBV_pday < 0:
        score += 1
        signal += "[1]OBV线从负的累积数转为正数,应该买进股票;"
    if OBV_today < 0 and OBV_pday > 0:
        score -= 1
        signal += "[-1]OBV线从正的累积数转为负数时,为下跌趋势,应该卖出持有股票;"

    # 4.OBV线呈缓慢上升时,为买进信号,但是若OBV线急速上升,隐含着能量不可能长久维持大成交量,非但不是买进信号,尚是卖出时机。
    if OBV_K > 0:
        if OBV_K > UP_RATIO_THREHOLD:
            score -= 1
            signal += "[-1]若OBV线急速上升,隐含着能量不可能长久维持大成交量,非但不是买进信号,尚是卖出时机;"
        else:
            score += 1
            signal += "[1]OBV线呈缓慢上升时,为买进信号;"
    print score
    print signal.decode("utf-8").encode("gbk")
    bd.updateAnalysisData("OBV", str(score) + ";" + signal, stock_code, date)
    return [score, signal]
示例#49
0
    def map(self, line):
        # Key is cluster id - clusters stored in self.clusters
        # Value is the line
        dist = float("inf")
        temp_dist = float("inf")
        doc = Document(line)
        key = doc.uid
        for c in self.clusters:
            temp_dist = MathUtil.compute_distance(doc.tfidf,c.tfidf)
            if temp_dist < dist:
                dist = temp_dist
                key = c.uid

        self.emit(str(key),str(doc))
示例#50
0
    def get_slice_bounds_from_interpolant(self, interpolant):
        bounds = [(0, 0)] * 4
        if 0.0 <= interpolant <= 1.0:
            scaled_superior_landmarks = self.heart_landmarks.get_scaled_superior(
                self.landmark_scale_factor)
            scaled_inferior_landmarks = self.heart_landmarks.get_scaled_inferior(
                self.landmark_scale_factor)

            bounds[0] = MathUtil.linear_interpolate_2d(
                scaled_superior_landmarks[0], scaled_inferior_landmarks[0],
                interpolant)
            bounds[1] = MathUtil.linear_interpolate_2d(
                scaled_superior_landmarks[1], scaled_inferior_landmarks[1],
                interpolant)
            bounds[2] = MathUtil.linear_interpolate_2d(
                scaled_superior_landmarks[2], scaled_inferior_landmarks[2],
                interpolant)
            bounds[3] = MathUtil.linear_interpolate_2d(
                scaled_superior_landmarks[3], scaled_inferior_landmarks[3],
                interpolant)

            bounds[0] = [max(bounds[0][0], 0), max(bounds[0][1], 0)]
            bounds[1] = [
                min(bounds[1][0], self.shape[1] - 1),
                max(bounds[1][1], 0)
            ]
            bounds[2] = [
                min(bounds[2][0], self.shape[1] - 1),
                min(bounds[2][1], self.shape[0] - 1)
            ]
            bounds[3] = [
                max(bounds[3][0], 0),
                min(bounds[3][1], self.shape[0] - 1)
            ]

        return bounds
示例#51
0
def normalize_cross_sectional_image_affine(cross_sectional_image,
                                           desired_width, desired_height,
                                           desired_depth):
    print(
        f"exporting normalized 3d image (affine) for {cross_sectional_image.patient_id}"
    )
    num_crop_slices = cross_sectional_image.inferior_slice + 1 - cross_sectional_image.superior_slice
    slice_stack = np.zeros((num_crop_slices, cross_sectional_image.shape[0],
                            cross_sectional_image.shape[1]), np.int16)
    result = np.zeros((desired_depth, desired_height, desired_width), np.int16)
    landmark_bounds = cross_sectional_image.get_landmark_bounds()

    for slice_idx in range(cross_sectional_image.superior_slice,
                           cross_sectional_image.inferior_slice + 1):
        slice = cross_sectional_image.get_slice(slice_idx)
        slice_pixels = slice_to_hu_pixels(slice)
        slice_stack[slice_idx -
                    cross_sectional_image.superior_slice] = slice_pixels

    print("z resizing")
    z_resize = float(desired_depth) / float(num_crop_slices)
    slice_stack_resized = zoom(slice_stack, (z_resize, 1.0, 1.0))
    print("z resize done")

    print("normalizing slices")
    for depth in range(0, desired_depth):
        interpolant = MathUtil.point_interpolant_1d(depth, 0,
                                                    desired_depth - 1)
        slice_pixels = slice_stack_resized[depth]
        slice_bounds = cross_sectional_image.get_slice_bounds_from_interpolant(
            interpolant)
        normalized_slice = normalize_slice_affine(slice_pixels, slice_bounds,
                                                  landmark_bounds,
                                                  desired_width,
                                                  desired_height)
        result[depth] = normalized_slice.astype(np.int16)
        print(f"{depth + 1}/{desired_depth}")
    print("slice normalization done")
    print("normalization done")
    return result
示例#52
0
def fit_cone(p1, n1, p2, n2, p3, n3, eps=0.005, alpha=np.deg2rad(10.0)):
    ''' 
    fit a cone to the three point/normal pairs 
    eps: distance thres for determining if the fit is a valid cylinder
          both points must be < eps from the cylinder
    alpha: angle thres for determining if the fit is a valid cylinder
          both normals must be < alpha from the cylinder normals

    return (valid, apex, axis, opening angle);
      valid is a bool indicating if the fit was valid based on the points and normals
  '''
    p1 = np.asarray(p1)
    n1 = np.asarray(n1)
    p2 = np.asarray(p2)
    n2 = np.asarray(n2)
    p3 = np.asarray(p3)
    n3 = np.asarray(n3)

    # find cone apex (intersection of the 3 planes formed by the point/normal pairs)
    # line normal from plane 1/2 intersection
    (lp, ln) = mu.plane_plane_intersection(p1, n1, p2, n2)
    c = mu.line_plane_intersection(lp, ln, p3, n3)

    # find the axis from the normal of the plane formed by the three points
    pc1 = c + (p1 - c) / np.linalg.norm(p1 - c)
    pc2 = c + (p2 - c) / np.linalg.norm(p2 - c)
    pc3 = c + (p3 - c) / np.linalg.norm(p3 - c)
    a = np.cross(pc2 - pc1, pc3 - pc1)
    a /= np.linalg.norm(a)

    # find opening anlge
    ac = np.array(map(lambda p: ru.angle_between(p - c, a), [p1, p2, p3]))
    w = np.sum(ac) / 3.0

    # check validity

    # project each point onto the axis
    p1_proj_a = np.dot(p1 - c, a) * a
    p2_proj_a = np.dot(p2 - c, a) * a
    p3_proj_a = np.dot(p3 - c, a) * a
    # and rejections
    p1_rej_a = (p1 - c) - p1_proj_a
    p2_rej_a = (p2 - c) - p2_proj_a
    p3_rej_a = (p3 - c) - p3_proj_a

    # projection mag
    d1 = np.linalg.norm(p1_proj_a)
    d2 = np.linalg.norm(p2_proj_a)
    d3 = np.linalg.norm(p3_proj_a)
    # mag of vector from axis to cone edge
    r1 = d1 * np.tan(w)
    r2 = d2 * np.tan(w)
    r3 = d3 * np.tan(w)

    # scale rejections to find the cone point
    c1 = c + p1_proj_a + (r1 / np.linalg.norm(p1_rej_a)) * p1_rej_a
    c2 = c + p2_proj_a + (r2 / np.linalg.norm(p2_rej_a)) * p2_rej_a
    c3 = c + p3_proj_a + (r3 / np.linalg.norm(p3_rej_a)) * p3_rej_a

    # is the point within distance thres?
    distToCone = np.array([
        np.linalg.norm(p1 - c1),
        np.linalg.norm(p2 - c2),
        np.linalg.norm(p3 - c3)
    ])
    if np.any(distToCone > eps):
        return (False, c, a, w)

    # compute cone normals
    cn1 = np.cross(np.cross(a, (c1 - c)), (c1 - c))
    cn2 = np.cross(np.cross(a, (c2 - c)), (c2 - c))
    cn3 = np.cross(np.cross(a, (c3 - c)), (c3 - c))
    cn1 /= np.linalg.norm(cn1)
    cn2 /= np.linalg.norm(cn2)
    cn3 /= np.linalg.norm(cn3)

    # are the normals close?
    sa = np.sin(alpha)
    if ((np.sin(np.abs(ru.angle_between(cn1, n1))) > sa)
            or (np.sin(np.abs(ru.angle_between(cn2, n2))) > sa)
            or (np.sin(np.abs(ru.angle_between(cn3, n3))) > sa)):
        return (False, c, a, w)

    return (True, c, a, w)
示例#53
0
def fit_cylinder(p1, n1, p2, n2, eps=0.005, alpha=np.deg2rad(10.0)):
  ''' 
    fit a cylinder to the two point/normal pairs 
    eps: distance thres for determining if the fit is a valid cylinder
          both points must be < eps from the cylinder
    alpha: angle thres for determining if the fit is a valid cylinder
          both normals must be < alpha from the cylinder normals

    return (valid, center, axis, radius);
      valid is a bool indicating if the fit was valid based on the points and normals
  '''
  p1 = np.asarray(p1);
  n1 = np.asarray(n1);
  p2 = np.asarray(p2);
  n2 = np.asarray(n2);

  # find cylinder axis
  a = np.cross(n1, n2);
  a /= np.linalg.norm(a);

  # project lines (defined by the point/normal) onto the plane defined by a.x = 0
  pp1 = p1 - a * np.dot(a, p1);
  pn1 = n1 - a * np.dot(a, n1);
  pp2 = p2 - a * np.dot(a, p2);
  pn2 = n2 - a * np.dot(a, n2);
  
  # find intersection
  (c, c1) = mu.line_line_closest_point(pp1, pn1, pp2, pn2);

  # cylinder radius
  r = np.linalg.norm(pp1 - c);

  # check if the fit is valid
  
  # find rejections of the points from the cylinder axis
  cp1 = pp1 - c;
  cp2 = pp2 - c;
  ca = c + a;
  rej1 = cp1 - np.dot(cp1, ca)*ca; 
  rej2 = cp2 - np.dot(cp2, ca)*ca; 

  pa = create_normals_pose_array(np.array([p1,p2]), np.array([rej1,rej2]));
  #Debug.pa1Pub.publish(pa);
  print rej1
  print rej2
  print np.sin(np.abs(ru.angle_between(rej1, n1)))
  print np.sin(np.abs(ru.angle_between(rej2, n2)))
  print np.abs(r - np.linalg.norm(rej1))
  print np.abs(r - np.linalg.norm(rej2))


  sa = np.sin(alpha);
  if (((np.sin(np.abs(ru.angle_between(rej1, n1)))) > sa)
      or (np.sin(np.abs(ru.angle_between(rej2, n2))) > sa)):
    return (False, c, a, r);

  if ((np.abs(r - np.linalg.norm(rej1)) > eps)
      or (np.abs(r - np.linalg.norm(rej2)) > eps)):
    return (False, c, a, r);

  sa = np.sin(alpha);
  if (((np.sin(np.abs(ru.angle_between(rej1, n1)))) > sa)
      or (np.sin(np.abs(ru.angle_between(rej2, n2))) > sa)):
    return (False, c, a, r);
  
  return (True, c, a, r);
示例#54
0
文件: Camera.py 项目: fathat/game-src
 def getTransformMatrix(self):
     return MathUtil.buildTransformMatrix(self.position,
                                          self.yaw,
                                          self.pitch,
                                          self.roll)
示例#55
0
def fit_cone(p1, n1, p2, n2, p3, n3, eps=0.005, alpha=np.deg2rad(10.0)):
  ''' 
    fit a cone to the three point/normal pairs 
    eps: distance thres for determining if the fit is a valid cylinder
          both points must be < eps from the cylinder
    alpha: angle thres for determining if the fit is a valid cylinder
          both normals must be < alpha from the cylinder normals

    return (valid, apex, axis, opening angle);
      valid is a bool indicating if the fit was valid based on the points and normals
  '''
  p1 = np.asarray(p1);
  n1 = np.asarray(n1);
  p2 = np.asarray(p2);
  n2 = np.asarray(n2);
  p3 = np.asarray(p3);
  n3 = np.asarray(n3);

  # find cone apex (intersection of the 3 planes formed by the point/normal pairs)
  # line normal from plane 1/2 intersection
  (lp, ln) = mu.plane_plane_intersection(p1, n1, p2, n2);
  c = mu.line_plane_intersection(lp, ln, p3, n3);

  # find the axis from the normal of the plane formed by the three points
  pc1 = c + (p1 - c)/np.linalg.norm(p1 - c);
  pc2 = c + (p2 - c)/np.linalg.norm(p2 - c);
  pc3 = c + (p3 - c)/np.linalg.norm(p3 - c);
  a = np.cross(pc2 - pc1, pc3 - pc1);
  a /= np.linalg.norm(a);

  # find opening anlge
  ac = np.array(map(lambda p: ru.angle_between(p - c, a), [p1, p2, p3]));
  w = np.sum(ac)/3.0;

  # check validity

  # project each point onto the axis
  p1_proj_a = np.dot(p1 - c, a) * a;
  p2_proj_a = np.dot(p2 - c, a) * a;
  p3_proj_a = np.dot(p3 - c, a) * a;
  # and rejections
  p1_rej_a = (p1 - c) - p1_proj_a;
  p2_rej_a = (p2 - c) - p2_proj_a;
  p3_rej_a = (p3 - c) - p3_proj_a;

  # projection mag
  d1 = np.linalg.norm(p1_proj_a);
  d2 = np.linalg.norm(p2_proj_a);
  d3 = np.linalg.norm(p3_proj_a);
  # mag of vector from axis to cone edge
  r1 = d1 * np.tan(w);
  r2 = d2 * np.tan(w);
  r3 = d3 * np.tan(w);

  # scale rejections to find the cone point 
  c1 = c + p1_proj_a + (r1/np.linalg.norm(p1_rej_a))*p1_rej_a;
  c2 = c + p2_proj_a + (r2/np.linalg.norm(p2_rej_a))*p2_rej_a;
  c3 = c + p3_proj_a + (r3/np.linalg.norm(p3_rej_a))*p3_rej_a;
  

  # is the point within distance thres?
  distToCone = np.array([np.linalg.norm(p1 - c1), np.linalg.norm(p2 - c2), np.linalg.norm(p3 - c3)]);
  if np.any(distToCone > eps):
    return (False, c, a, w);

  # compute cone normals
  cn1 = np.cross(np.cross(a, (c1 - c)), (c1 - c));
  cn2 = np.cross(np.cross(a, (c2 - c)), (c2 - c));
  cn3 = np.cross(np.cross(a, (c3 - c)), (c3 - c));
  cn1 /= np.linalg.norm(cn1);
  cn2 /= np.linalg.norm(cn2);
  cn3 /= np.linalg.norm(cn3);

  # are the normals close?
  sa = np.sin(alpha);
  if ((np.sin(np.abs(ru.angle_between(cn1, n1))) > sa)
      or (np.sin(np.abs(ru.angle_between(cn2, n2))) > sa)
      or (np.sin(np.abs(ru.angle_between(cn3, n3))) > sa)):
    return (False, c, a, w);

  return (True, c, a, w);
示例#56
0
文件: Ents.py 项目: fathat/game-src
 def setGraphicsTransform( self ):
     if Settings.DebugTransforms:
         m = MathUtil.buildTransformMatrixQ( self.location, self.q4)
         GraphicsCard.multMatrix( m.toList() )
     else:
         GraphicsCard.multMatrix( self.body.GetMatrix() )
示例#57
0
文件: sense.py 项目: jgrossmann/iot
  def dataCallback(self, v):
    global start_time
    # clear first ten recordings because BT timing needs to settle
    # garbageiterations = 10
    if self.inittime > self.garbageiterations-1:

      if self.starttimer == 0:
        self.starttimer = 1

      else: # the garbage iterations have passed
        if len(self.timestamp) == 0:
          start_time = current_milli_time()
          self.timestamp.append(elapsed_time())
          print "Python timestamp (in s): " + str(self.timestamp[-1])
        else:
          self.timestamp.append( elapsed_time() )
          print "Python timestamp (in s): " + str(self.timestamp[-1])

        bytelen = len(v) # v is the handle data

        vx1 = int( str(v[2]*256 + v[1]) )
        vy1 = int( str(v[4]*256 + v[3]) )
        vz1 = int( str(v[6]*256 + v[5]) )
        gx1 = int( str(v[8]*256 + v[7]) )
        gy1 = int( str(v[10]*256 + v[9]) )
        gz1 = int( str(v[12]*256 + v[11]) )

        if(self.calibrateMagnet == True):
          (Mxyz, Mmag) = MathUtil.convertData(mx1, my1, mz1, 1.0)
          self.magX.append(Mxyz[0])
          self.magY.append(Mxyz[1])
          self.magZ.append(Mxyz[2])
        elif(self.calibrate == True):
            (Gxyz, Gmag) = MathUtil.convertData(gx1, gy1, gz1, 1.0) # FS = 500dps
            (Axyz, Amag) = MathUtil.convertData( vx1,vy1,vz1, 1.0)#(8192.0/9.80665))
            self.gyroX.append(Gxyz[0])
            self.gyroY.append(Gxyz[1])
            self.gyroZ.append(Gxyz[2])
            self.ax.append( Axyz[0] )
            self.ay.append( Axyz[1] )
            self.az.append( Axyz[2] )
            print str(Gxyz[0]) +", "+str(Gxyz[1])+", "+str(Gxyz[2]) + ", " + "{0:.5f}".format(Axyz[0]) + ", " + "{0:.5f}".format(Axyz[1]) + ", " + "{0:.5f}".format(Axyz[2])
        else:
          (Gxyz, Gmag) = MathUtil.convertData(gx1 + int(float(self.gyroCal[0])), gy1 + int(float(self.gyroCal[1])), gz1 + int(float(self.gyroCal[2])), 1.0/.00762939)
          (Axyz, Amag) = MathUtil.convertData(vx1 + int(float(self.accelCal[0])), vy1 + int(float(self.accelCal[1])), vz1 + int(float(self.accelCal[2])), 16384.0/9.80665)
          #(Mxyz, Mmag) = MathUtil.convertData(mx1 + int(float(self.magCal[0])), my1 + int(float(self.magCal[1])), mz1 + int(float(self.magCal[2])), 16384.0)
                    
          print str(Gxyz[0]) +", "+str(Gxyz[1])+", "+str(Gxyz[2]) + ", " + "{0:.5f}".format(Axyz[0]) + ", " + "{0:.5f}".format(Axyz[1]) + ", " + "{0:.5f}".format(Axyz[2])# + ", " + "{0:.5f}".format(Mxyz[0]) + ", " + "{0:.5f}".format(Mxyz[1]) + ", " + "{0:.5f}".format(Mxyz[2])

          self.gyroX.append(Gxyz[0])
          self.gyroY.append(Gxyz[1])
          self.gyroZ.append(Gxyz[2])

         # self.magX.append(Mxyz[0])
         # self.magY.append(Mxyz[1])
         # self.magZ.append(Mxyz[2])

          self.magnitude.append( Amag )

          self.ax.append( Axyz[0] )
          self.ay.append( Axyz[1] )
          self.az.append( Axyz[2] )
   
    else:
      self.inittime += 1  # increment 10 times before evaluating values      
示例#58
0
 def setLocation(self, location, yaw, pitch, roll):
     self.location = location
     self.matrix = MathUtil.buildTransformMatrix(self.location, yaw, pitch, roll)
     self.body.SetMatrix( self.matrix.toList() )
示例#59
0
 def setLocation(self, location):
     self.location = location
     self.matrix = MathUtil.buildTransformMatrix(self.location, 0, 0, 0)
     self.body.SetMatrix( self.matrix.toList() )