Exemple #1
0
def child(i, step, totalimage, prefs, kind, finalData, monitor, nOutstart):

    Start = i*step;
    End = (i+1)*step;
    if(Start >= totalimage):
        return 0
    if(End > totalimage):
        End = totalimage;

    for iproj in range(Start,End):
        nOut = nOutstart+iproj
        # outfilename = "%s/%s_%s.hdf" % (prefs['out']['filePath'], prefs['projection']['Prefix'], Transform.paddingZero(nOut, int(prefs['out']['numberDigit'])))
        dataArray = []

        for i in prefs['series']:
            i = i -1
            filename = "%s/%s%s.%s" % ( prefs['filePath'], prefs[kind]['Prefix'][0], Transform.paddingZero(int(prefs[kind]['Num'][i][iproj]), prefs['numberDigit'] ), prefs[kind]['extension'] )
            im = Image.open(filename)
            imarray = np.array(im)
            dataArray.append(0)
            dataArray[i] = imarray[(prefs['ROIy'][i][0]-1):prefs['ROIy'][i][-1] , (prefs['ROIx'][i][0]-1):prefs['ROIx'][i][-1]] # corp the array
            # if prefs['slits']['shouldCorr']: #comment out for this momoent, if need corr, need to initialize in the initialize script
            # dataAve[iavg] = slitposcorr(dataAve[iavg], prefs, j, kind, iavg)
            dataArray[i], _, _, aveint = Transform.preprocess(dataArray[i], prefs, i)
            if prefs['vis']['intMonitor']:
                monitor[iproj][i]=array('d', [aveint, prefs[kind]['Num'][i][iproj], nOut])

        dataResutArray, sminx, smaxx = Transform.stitching(dataArray, prefs)
        finalData[iproj] = dataResutArray

    return 1
Exemple #2
0
    def redraw(self, rotation_x, rotation_y):
        resize_width = 0
        resize_height = 0
        if (rotation_x + self.originalRotationX > 360):
            resize_width = (rotation_x + self.originalRotationX * 1.0) % 90.0
            resize_width = int(resize_width * 100)

        Surface.__init__(self, self.get_size(), pygame.SRCALPHA)
        Transform.skew_surface(self.originalImage, 0, -rotation_y), (0, 0)
        self.blit(pygame.transform.scale(Transform.skew_surface(self.originalImage, 0, -rotation_y), (resize_width, self.get_size()[1])), (-rotation_x,0))
Exemple #3
0
 def transformFunc(self):
     import Image as i, Transform
     self.pic = i.Image("Resources/test.jpg")
     if(self.radioButton.isChecked()):
         self.pic.set_img(Transform.crop(self.pic.get_img(),self.spinBox_2.value(),self.spinBox_3.value()))
     if(self.radioButton_9.isChecked()):
         self.pic.set_img(Transform.rotate(self.pic.get_img(),self.spinBox.value()))
     if(self.radioButton_10.isChecked()):
         if(self.checkBox.isChecked()):
             self.pic.set_img(Transform.flip(self.pic.get_img(),1))
         if(self.checkBox_2.isChecked()):
             self.pic.set_img(Transform.flip(self.pic.get_img(),2))
     from scipy.misc import imsave
     imsave("Resources/test2.jpg",self.pic.get_img())
     self.imageUpdate("Resources/test2.jpg")
    def savePeakListToFile(self,filename,initialGuess,qData,
            numberOfChi,maskedPixelInfo,stddev):
        peakList = Fit.getPeakList(self.theDiffractionData.data,qData,
                initialGuess,numberOfChi,stddev)

        # now, save to file
        file = open(filename,"w")
        file.write("# A list of diffraction peaks found.\n")
        file.write("# Diffraction Data: %s\n" % self.theDiffractionData.filename)
        file.write("# Calculated on "+time.asctime()+"\n")
        file.write("# Calibration data used to find peaks:\n")
        initialGuess.writeCommentString(file)
        file.write("# Q data used to find peaks:\n")
        file.write("# Peaks:\n")
        qData.writeCommentString(file)

        if maskedPixelInfo.doPolygonMask and maskedPixelInfo.numPolygons() > 0:
            file.write("# All peaks inside of polygon mask(s) were ignored.\n")
            file.write(maskedPixelInfo.writePolygonCommentString())

        file.write("#%16s%21s%21s%21s%21s%21s%21s%21s\n" % \
                ("x","y","Real Q","Fit Q","chi","width","intensity","2theta"))
        for peak in peakList.getMaskedPeakList(maskedPixelInfo):
            x,y,realQ,fitQ,chi,width = peak
            
            intensity=self.getPixelValueBilinearInterpolation(x,y)
            twoTheta = Transform.convertQToTwoTheta(fitQ,initialGuess)
            file.write("%17.10f    %17.10f    %17.10f    %17.10f    %17.10f    %17.10f    %17.10f    %17.10f\n" % \
                    (x,y,realQ,fitQ,chi,width,intensity,twoTheta) )
        file.close()
        return peakList
def addConstantQLineCakeImage(image,Q,qOrTwoThetaLower,
        qOrTwoThetaUpper,numQOrTwoTheta,chiLower,
        chiUpper,numChi,color,calibrationData,type):

    draw = ImageDraw.Draw(image)

    if type == "Q":
        if Q < qOrTwoThetaLower or Q > qOrTwoThetaUpper:
            return

        qIndex = (numQOrTwoTheta-1)*(Q-qOrTwoThetaLower)/ \
                (qOrTwoThetaUpper-qOrTwoThetaLower)

        draw.line( (qIndex,0)+(qIndex,numChi-1),fill=color)
    
    elif type == "2theta":
        twoTheta = Transform.convertQToTwoTheta(Q,calibrationData)
        if twoTheta < qOrTwoThetaLower or \
                twoTheta > qOrTwoThetaUpper:
            return

        twoThetaIndex = (numQOrTwoTheta-1)* \
                (twoTheta-qOrTwoThetaLower)/ \
                (qOrTwoThetaUpper-qOrTwoThetaLower)

        draw.line( (twoThetaIndex,0)+(twoThetaIndex,numChi-1),
                fill=color)
        
    else:
        raise Exception("Unable to add constant Q \
lines to the cake image. The function must be passed \
for the parameter type either 'Q', or '2theta'")
Exemple #6
0
    def _paint_block(self, position):
        """ Creates vertexes for the block.

        Parameters
        ----------
        position : tuple of len 3
            The (x, y, z) position of the block to show.
        """
        x, y, z = position
        try:
            block = self.world.getBlock(position)
            
            if block.getVertex():
                return
            
            vertex_data = Transform.cube_vertices(x, y, z, 0.5)
            texture_data = list(block.getTexture())

            # create vertex list
            # FIXME Maybe `add_indexed()` should be used instead
            block.setVertex(self.batch.add(24, GL_QUADS, self._materialFactory.getMaterial(block.getMaterial()).textureGroup,
                ('v3f/static', vertex_data),
                ('t2f/static', texture_data)))
            
            #self.log.debug('Block at %s made visible' % (position,))
        except Exception, e:
            self.log.error("Painting block at %s failed: %s" % (position, e))
Exemple #7
0
    def remove_block(self, position, immediate=True):
        """ Remove the block at the given `position`.

        Parameters
        ----------
        position : tuple of len 3
            The (x, y, z) position of the block to remove.
        immediate : bool
            Whether or not to immediately remove block from canvas.

        """
        
        # if block is dead hide it and remove it
        if not self.world.getBlock(position).isAlive():
            transparent = self._materialFactory.getMaterial(self.world.getBlock(position).getMaterial()).transparent
            if immediate:
                self.hide_block(position)
                
            self.world.removeBlock(position)
            self.sectors[Transform.sectorize(position, self.conf.getConfValue('sectorSize'))].remove(position)

            # show newly exposed blocks
            self.check_neighbors(position, transparent)

        else:
            self.world.getBlock(position).decreaseLife()
Exemple #8
0
    def hit_test(self, position, vector, max_distance=8):
        """ Line of sight search from current position. If a block is
        intersected it is returned, along with the block previously in the line
        of sight. If no block is found, return None, None.

        Parameters
        ----------
        position : tuple of len 3
            The (x, y, z) position to check visibility from.
        vector : tuple of len 3
            The line of sight vector.
        max_distance : int
            How many blocks away to search for a hit.

        """
        m = 8
        x, y, z = position
        dx, dy, dz = vector
        previous = None
        for _ in xrange(max_distance * m):
            key = Transform.normalize((x, y, z))
            if key != previous and self.world.existsBlockAt(key):
                return key, previous
            previous = key
            x, y, z = x + dx / m, y + dy / m, z + dz / m
        return None, None
Exemple #9
0
def get_bbox(pc, pose=None):
  '''
    get the bounding box for the point cloud
    if a pose is provided then it will find the bbox
      for the data aligned to that pose

    return: bbox array
        |xmin, xmax|
        |ymin, ymax|
        |zmin, zmax|
  '''
  pts = ru.to_array(pc);

  if pose != None:
    ps = ru.to_PoseStamped(pose);
    ps_wrtPC = ru.transformPose(ru.get_frame_id(pc), ps);

    T = tr.rospose2tr(ps_wrtPC.pose);
    pts = np.dot(np.linalg.inv(T), np.vstack((pts.T, np.ones(pts.shape[0])))).T; 

  pmin = np.min(pts[:,:3], axis=0);
  pmax = np.max(pts[:,:3], axis=0);
  bbox = np.array([pmin, pmax]).T;

  return bbox;
Exemple #10
0
    def __init__(self):

        self.log = l.getLogger('model')

        self.conf = EC.EngineConfig.Instance()

        # A Batch is a collection of vertex lists for batched rendering.
        self.batch = pyglet.graphics.Batch()

        # Mapping from sector to a list of positions inside that sector.
        self.sectors = {}

        # Simple function queue implementation. The queue is populated with
        # _show_block() and _hide_block() calls
        self.queue = deque()

        self._materialFactory = Materials.MaterialFactory.Instance()

        # all shown blocks.
        self.visibleWorld = {}

        # This defines all the blocks that are currently in the world.
        try:
            (self.world, self.player) = Savegame.Savegame.load()
            # make blocks visible after loading
            for position in self.world.getBlockPositions():
                # sectorize blocks
                self.sectors.setdefault(Transform.sectorize(position, self.conf.getConfValue('sectorSize')), []).append(position)
                self.show_sector(0)
        except Exception, e:
            self.log.debug("Couldn't load a savegame. Creating new world ...")
            self.world = World.World()
            self.player = Player.Player()
            self.visibleWorld = {}
            self._initialize()
Exemple #11
0
    def loadMaterials(self):
        """ This method crawles the ressources for diffrent materials
            and loads them for future use
        """
        self.log.debug('loading materials from %s' % (self._materialPath, ))

        textureFactory = TF.TextureFactory.Instance()

        for file in os.listdir(self._materialPath):
            absPath = os.path.join(self._materialPath, file)

            """ if found new material, load metadata and textures """
            if os.path.isdir(absPath):
                self.log.debug('material found: %s' % (file, ))

                # load json material definition
                try:
                    defFile = open(os.path.join(absPath, "material.json"), 'r')
                    definition = "".join(defFile.readlines())
                    jsonObj = json.loads(definition)
                except Exception, e:
                    self.log.error("Error loading material metadata %s: %s" %
                            (file, str(e)))

                # create new Material object
                self._materials[jsonObj['name']] = Material()

                # load texture
                try:
                    self._materials[jsonObj['name']].name = jsonObj['name']
                    self._materials[jsonObj['name']].sustain = int(jsonObj['sustain'])
                    self._materials[jsonObj['name']].clipping = bool(jsonObj['clipping'])
                    self._materials[jsonObj['name']].transparent = bool(jsonObj['transparent'])
                    self._materials[jsonObj['name']].texture['top'] = Transform.tex_coords(
                        tuple(jsonObj['texture']['mapping']['top']['top']),
                        tuple(jsonObj['texture']['mapping']['top']['bottom']),
                        tuple(jsonObj['texture']['mapping']['top']['sides']))
                    self._materials[jsonObj['name']].texture['middle'] = Transform.tex_coords(
                        tuple(jsonObj['texture']['mapping']['middle']['top']),
                        tuple(jsonObj['texture']['mapping']['middle']['bottom']),
                        tuple(jsonObj['texture']['mapping']['middle']['sides']))
                    # A TextureGroup manages an OpenGL texture.
                    self._materials[jsonObj['name']].textureGroup = textureFactory.loadTexture(
                        os.path.join(absPath,jsonObj['texture']['ressource']))

                except Exception, e:
                    self.log.debug("Error loading material textures: %s" % (str(e), ))
Exemple #12
0
def icp(data, model, thres=.001, maxIter=1000):
  '''
    compute icp on two point sets

    matrix: DxN

    return:
      qr - quaterion rotation
      qt - translation
  '''
  # augment if needed
  if data.shape[0] == 3:
    data = np.vstack((data, np.ones(data.shape[1])));
  if model.shape[0] == 3:
    model = np.vstack((model, np.ones(model.shape[1])));

  # initialize registration
  qr = np.array([1.0, 0.0, 0.0, 0.0]);
  qt = np.array([0.0, 0.0, 0.0]);
  dm = np.Inf;
  count = 0;

  # compute initial closest points
  di = np.arange(data.shape[1]);
  (imin, d) = closest_points(data, model);
  dk = np.sum(d[di, imin]);

  # loop until the change in error is below the threshold
  while (dm > thres and count < maxIter):
  
    # compute registration
    (qr, qt) = compute_registration(data, model[:,imin]);

    # transform data
    T = np.dot(tr.trans(qt), tr.quat2rot(qr));
    tdata = np.dot(T, data);

    # compute closest points
    (imin, d) = closest_points(tdata, model);
    dk1 = np.sum(d[di, imin]);

    dm = np.abs(dk1 - dk);
    dk = dk1;
    count += 1;

  return (qr, qt, dk);
    def getWavelength(self):
        if self.energy['val'] == None or self.energy['fixed'] == None:
            return UserInputException('Cannot get the wavelength because neither the wavelength nor the energy have been set.')

        val = Transform.convertEnergyToWavelength(self.energy['val'])
        lower,upper=None,None
        if self.energy['lower'] != None: lower = hc/self.energy['upper']
        if self.energy['upper'] != None: upper = hc/self.energy['lower']
        return {'val':val,'fixed':self.energy['fixed'],'lower':lower,'upper':upper}
Exemple #14
0
    def draw(self, surface):
        self.fill((0,0,0))
        self.cubeSide.update(self.rotation, 0)
        self.cubeSide.redraw(self.rotation, 0)
        print ("Equation = %s" % (-33 + int(((self.rotation * 1.0) % 90)/ 90.0 * 66)))
        if self.rotation <= 90:
            self.blit(pygame.transform.scale(Transform.skew_surface(self.originalImage, 0, -33 + int(((self.rotation * 1.0) % 90)) ), (int((self.rotation%90.0)/90*100), 100)), self.imageLocation)
        else:
            self.blit(pygame.transform.scale(Transform.skew_surface(self.originalImage, 0, -33 + int(((self.rotation * 1.0) % 90))),
                                             (100 - int((self.rotation % 90.0) / 90 * 100), 100)), self.imageLocation)

        if (self.rotation == 90):
            self.rotation = 0
        self.rotation += 1

        self.imageLocation = (100 - int((self.rotation % 90.0) / 90 * 100), self.imageLocation[1])

        surface.blit(self, (200, 200))
def addConstantQLineDiffractionImage(image,Q,calibrationData,color):
    draw = ImageDraw.Draw(image)

    polygon = []
    for chi in frange(0,360,3):
        x,y = Transform.getXY(calibrationData,Q,chi)
        polygon += [x,y]

    draw.polygon(polygon, outline=color)
Exemple #16
0
    def __init__(self, size, images):
        Surface.__init__(self, images[0].get_size(), pygame.SRCALPHA)

        self.location = (0, 34)
        self.blit(images[0], (0, 0))
        self.xChange = 100

        self.rotationX = 45
        self.rotationY = 33

        self.surfaces = [CubeSide(images[x], images[0].get_size(), x) for x in range(6)]
        self.surfaces[0].blit(images[0], (0, 0))
        self.surfaces[1].blit(images[1], (0, 0))

        self.ORIGINAL_SURFACES = [pygame.Surface((100, 100), pygame.SRCALPHA) for _ in range(6)]
        self.ORIGINAL_SURFACES[0].blit(images[0], (0, 0))

        self.testingSurf = Transform.skew_surface(pygame.transform.scale(self.surfaces[0], (self.xChange, 100)), 0, 33)
        self.testingSurf2 = Transform.skew_surface(pygame.transform.scale(self.surfaces[4], (self.xChange, 100)), 0, -33)
Exemple #17
0
 def __init__(self):
     self.cairoContext = None
     self.RGB = "rgb"
     self.HSB = "hsb"
     self.CMYK = "cmyk"    
     self._colormode = self.RGB
     self._fillState = 1
     self._lineWidth = 1
     
     self._autoclosepath = True
     self._transform = Transform()
     self._fontsize = 10
Exemple #18
0
def child(i, procs, step, totalimage, prefs, kind, j, dataAve, monitor, nOut):

    Start = i*step;
    End = (i+1)*step;
    if(Start >= totalimage):
        return 0
    if(End > totalimage):
        End = totalimage;

    for iavg in range(Start, End ):
        filename = "%s/%s%s.%s" % ( prefs['filePath'], prefs[kind]['Prefix'][0], Transform.paddingZero(int(prefs[kind]['Num'][j][iavg]), prefs['numberDigit'] ), prefs[kind]['extension'] )
        im = Image.open(filename)
        imarray = np.array(im)
        dataAve[iavg] = imarray[(prefs['ROIy'][j][0]-1):prefs['ROIy'][j][-1] , (prefs['ROIx'][j][0]-1):prefs['ROIx'][j][-1]] # corp the array
        # if prefs['slits']['shouldCorr']: #comment out for this momoent, if need corr, need to initialize in the initialize script
        # dataAve[iavg] = slitposcorr(dataAve[iavg], prefs, j, kind, iavg)
        # print iavg
        if prefs['vis']['intMonitor']:
            _, _, _, aveint = Transform.preprocess(dataAve[iavg], prefs, j)
            monitor[iavg][j] = array('d', [aveint, prefs[kind]['Num'][j][iavg], nOut])

    return 1
Exemple #19
0
    def collide(self, position, height):
        """ Checks to see if the player at the given `position` and `height`
        is colliding with any blocks in the world.

        Parameters
        ----------
        position : tuple of len 3
            The (x, y, z) position to check for collisions at.
        height : int or float
            The height of the player.

        Returns
        -------
        position : tuple of len 3
            The new position of the player taking into account collisions.

        """
        # How much overlap with a dimension of a surrounding block you need to
        # have to count as a collision. If 0, touching terrain at all counts as
        # a collision. If .49, you sink into the ground, as if walking through
        # tall grass. If >= .5, you'll fall through the ground.
        pad = 0.25
        p = list(position)
        np = Transform.normalize(position)
        for face in Block.FACES:  # check all surrounding blocks
            for i in xrange(3):  # check each dimension independently
                if not face[i]:
                    continue
                # How much overlap you have with this dimension.
                d = (p[i] - np[i]) * face[i]
                if d < pad:
                    continue
                for dy in xrange(height):  # check each height
                    op = list(np)
                    op[1] -= dy
                    op[i] += face[i]
                    if not self.model.world.existsBlockAt(tuple(op)):
                        continue
                    # check for non resiting block (no colision)
                    if not self._materialFactory.getMaterial(
                            self.model.world.getBlock(tuple(op)).getMaterial()).clipping:
                        continue

                    p[i] -= (d - pad) * face[i]
                    if face == (0, -1, 0) or face == (0, 1, 0):
                        # You are colliding with the ground or ceiling, so stop
                        # falling / rising.
                        self.dy = 0
                    break
        return tuple(p)
Exemple #20
0
def createControl( name, args ):
        """
            Creates a default control
        """
        functArgs = {"shape":"circle", "size":1, "match":""}
        functArgs =  dict(functArgs.items() + args.items())
        
        #create control
        if(functArgs["shape"] == "circle"):
                ctl = circleCtl( name, functArgs["size"] )
        elif(functArgs["shape"] == "arrow"):
                ctl = arrowCtl( name, functArgs )
        elif(functArgs["shape"] == "locator"):
                ctl = locatorCtl( name, functArgs )
        else:
                print "Shape not supported...\n"
                return 0
        if cmds.objExists(functArgs["match"]):
            Transform.match(ctl[1],functArgs["match"],{"all":1})
        #create control variable
        """for c in ctl:
            storeString(c, "control", "")"""
        return ctl
    def setWavelength(self,val,fixed=0,lower=None,upper=None):
        if fixed != 0 and fixed != 1:
            raise UserInputException("Cannot set the wavelength because fixed must be set to 0 or 1.")
        if lower != None and lower >= val:
            raise UserInputException("Cannot set the wavelength because the lower bound on wavelength must be less then the value.")
        if upper != None and upper <= val:
            raise UserInputException("Cannot set the wavelength because the upper bound on wavelength must be greater then the value.")
        if val <= 0:
            raise UserInputException("Cannot set the wavelength because it must be a positive quantity.")

        val = Transform.convertWavelengthToEnergy(val)
        if lower != None: lower=hc/upper
        if upper != None: upper=hc/lower
        # note that a low wavelength is the same as a high energy and vice versa!
        self.energy = {'val':val,'fixed':fixed,'lower':upper,'upper':lower} 
Exemple #22
0
    def draw_focused_block(self):
        """ Draw black edges around the block that is currently under the
        crosshairs.

        """
        vector = self.get_sight_vector()
        block = self.model.hit_test(self._player.position, vector)[0]
        if block:
            x, y, z = block
            self.focusedBlock = block
            vertex_data = Transform.cube_vertices(x, y, z, 0.51)
            glColor3d(0, 0, 0)
            glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
            pyglet.graphics.draw(24, GL_QUADS, ('v3f/static', vertex_data))
            glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
Exemple #23
0
def get_blob_pose(pts):
  '''
    computes the pose of the point cloud
    arr is expected to be Nx3

    return Pose
  '''
  pts = ru.to_array(pts);
  
  cent = get_centroid(pts);
  (x, y, z) = get_ev(pts);
  
  pose = geometry_msgs.Pose();
  pose.position = geometry_msgs.Point(*cent);
  pose.orientation = tr.ev2rosq((x,y,z));

  return pose;
def addPeaksCakeImage(image,qLower,qUpper,numQ,chiLower,chiUpper,
        numChi,peakList,calibrationData,color,
        smallestRangeQLower,smallestRangeQUpper,smallestRangeChiLower,smallestRangeChiUpper):

    draw = ImageDraw.Draw(image)

    unZoomWidth = 2.5
    # scale the length of the xs. For example, zoomed in to 50% means will 
    # cause the xs to be drawn with double the length.
    numTimesZoomInQ = abs((smallestRangeQUpper-smallestRangeQLower)/ \
            (qUpper-qLower))

    numTimesZoomInChi = abs((smallestRangeChiUpper-smallestRangeChiLower)/ \
            (chiUpper-chiLower))

    scalingFactor = min(numTimesZoomInQ,numTimesZoomInChi)

    halflength = unZoomWidth*scalingFactor

    for x,y,qReal,qFit,chi,width in peakList:
        
        # for each peak, we want to take the true x,y value of
        # where the peak is on the image and figure out where
        # it belongs on the cake data.
        qTemp,chiTemp = Transform.getQChi(calibrationData,x,y)

        # if our chi range begins in the negative, we might have to place 
        # our chi values in their 360 degree rotated values. Note that
        # getQChi always returns chi between 0 and 360
        if (chiTemp-360) > chiLower and \
                (chiTemp-360) < chiUpper:
                chiTemp -= 360
            
        cakeX = (numQ-1)*(qTemp-qLower)/(qUpper-qLower)
        cakeY = (numChi-1)*(chiTemp-chiLower)/(chiUpper-chiLower)

        # add in new lines if they would be visible
        if cakeX >= 0 and cakeX < numQ and  \
                cakeY >= 0 and cakeY < numChi:

            draw.line( (cakeX-halflength,cakeY-halflength) +
                    (cakeX+halflength,cakeY+halflength),fill=color)

            draw.line( (cakeX+halflength,cakeY-halflength) +
                    (cakeX-halflength,cakeY+halflength),fill=color)
Exemple #25
0
def get_chessboard_pose(img, info, ncol=5, nrow=4, squareSize=0.045, useSubPix=True, publishDetection=True, isRect=True):
  ''' 
    compute the pose of the chessboard in the camera frame   
  '''
  (success, chessboard_wrtImage) =  find_chessboard(img, ncol=ncol, nrow=nrow, useSubPix=useSubPix);
  if (len(chessboard_wrtImage) == 0):
    rospy.logwarn(__name__ + ': no chessboard found');
    return None;

  if (publishDetection):
    chessboardCV = draw_chessboard(img, chessboard_wrtImage, ncol=ncol, nrow=nrow);
    chessboardMsg = cvmat2msg(chessboardCV, img.encoding, frame_id=img.header.frame_id, stamp=rospy.Time().now());
    chessboardDetectionPub.publish(chessboardMsg);

  # compute pose
  chessboard_wrtBoard = cv.CreateMat(ncol*nrow, 1, cv.CV_32FC3);
  for i in range(ncol*nrow):
    chessboard_wrtBoard[i,0] = ((i % ncol) * squareSize, (i / ncol) * squareSize, 0);

  # get camera intrinsics
  (cameraMatrix, distCoeffs, projectionMatrix, rotationMatrix) = info2cvmat(info);

  # extrinsic outputs 
  rot = cv.CreateMat(3, 1, cv.CV_32FC1)
  trans = cv.CreateMat(3, 1, cv.CV_32FC1)

  # find chessboard pose
  if isRect:
    distCoeffs = cv.CreateMat(1, 4, cv.CV_32FC1);
    distCoeffs[0,0] = 0; distCoeffs[0,1] = 0; distCoeffs[0,2] = 0; distCoeffs[0,3] = 0;
    cv.FindExtrinsicCameraParams2(chessboard_wrtBoard, chessboard_wrtImage, projectionMatrix[:,:3], distCoeffs, rot, trans);
  else:
    cv.FindExtrinsicCameraParams2(chessboard_wrtBoard, chessboard_wrtImage, cameraMatrix, distCoeffs, rot, trans);

  # get transform from rot, trans
  rot = np.asarray(rot);
  trans = np.asarray(trans);

  th = np.linalg.norm(rot);
  r = rot / th;
  R = np.cos(th)*np.eye(3) + (1 - np.cos(th))*np.dot(r, r.T) + np.sin(th)*np.array([[0, -r[2], r[1]], [r[2], 0, -r[0]], [-r[1], r[0], 0]]);

  if not isRect:
    Trect = tr.trans(-projectionMatrix[0,3]/cameraMatrix[0,0],-projectionMatrix[1,3]/cameraMatrix[1,1], 0)
    Rcam = tr.rot2tr(np.asarray(rotationMatrix));
    Tmodel2cam = np.dot(Trect, np.dot(Rcam, np.dot(tr.trans(trans), tr.rot2tr(R))));
  else:
    Tmodel2cam = np.dot(tr.trans(trans), tr.rot2tr(R));

  return ru.to_PoseStamped(Tmodel2cam, frame_id=info.header.frame_id, stamp=info.header.stamp); 
    def savePeakListToFile(self,filename,initialGuess,qData,numberOfChi,stddev):
        peakList = Fit.getPeakList(self.theDiffractionData.data,qData,
                initialGuess,numberOfChi,stddev)

        # now, save to file
        file = open(filename,'w')
        file.write("# A list of peaks found in the diffraction image.\n")
        file.write("# Calculated on "+time.asctime()+"\n")
        file.write("# Calibration data used to find peaks:\n")
        initialGuess.writeCommentString(file)
        file.write("#\tx\ty\tRealQ\tFitQ\tchi\twidth\tintensity\t2theta\n")
        for peak in peakList:
            x,y,realQ,fitQ,chi,width = peak
            
            intensity=self.getPixelValueBilinearInterpolation(x,y)
            twoTheta = Transform.convertQToTwoTheta(fitQ,initialGuess)
            file.write("%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\n" % \
                    (x,y,realQ,fitQ,chi,width,intensity,twoTheta) )
        file.close()
        return peakList
Exemple #27
0
def saveShapes(filePath, module, objects):
    """
        Will store shape data in file
    """
    # objects = self.getRegisteredObjects(module , regAttr)
    writeData = ""

    for object in objects:
        writeLine = object + " "
        # Get shape
        shape = Transform.getShape(object)
        # Get CV number
        cvNum = Curve.getCurveCVNumber(shape)
        for x in xrange(cvNum):
            pos = cmds.xform((object + ".cv[" + x + "]"), q=True, ws=True, t=True)
            writeLine += pos[0] + " " + pos[1] + " " + pos[2] + " "
        writeData += writeLine + "\n"
    FILE = open(filePath, "wb")
    blueprintData = FILE.write(writeData)
    FILE.close()
    print ("Saved shape data to : " + filePath)
Exemple #28
0
    def update(self, dt):
        """ This method is scheduled to be called repeatedly by the pyglet
        clock.

        Parameters
        ----------
        dt : float
            The change in time since the last call.

        """
        self.model.process_queue()
        sector = Transform.sectorize(self._player.position, self.conf.getConfValue('sectorSize'))
        if sector != self.sector:
            self.model.change_sectors(self.sector, sector)
            if self.sector is None:
                self.model.process_entire_queue()
            self.sector = sector
        m = 8
        dt = min(dt, 0.2)
        for _ in xrange(m):
            self._update(dt / m)
Exemple #29
0
    def view_test(self, source, target):
        """ Check if plock at position has a line of sight to character.

        Parameters
        ----------
        source : tuple of len 3
            The (x, y, z) position to check visibility from.
        target :tuple of len 3
            The (x, y, z) position to check visibility to.
        """
        m = 8
        x, y, z = source
        dx, dy, dz = target
        previous = None
        for _ in xrange(max_distance * m):
            key = Transform.normalize((x, y, z))
            if key != previous and self.world.existsBlockAt(key):
                return key, previous
            previous = key
            x, y, z = x + dx / m, y + dy / m, z + dz / m
        return None, None
Exemple #30
0
def compute_registration(P, X):
  '''
    compute the registration between the two data sets
    Pi should correspond to Xi (distance)

    matrix: 4xN

    return:
      qr - quaterion rotation
      qt - translation
  '''

  # compute mean
  uP = np.array([np.sum(P, axis=1)/P.shape[1]]);
  uX = np.array([np.sum(X, axis=1)/X.shape[1]]);

  # cross-covariance matrix
  cc = np.dot(P[:3,:], X[:3,:].T)/P.shape[1] - np.dot(uP[:,:3].T, uX[:,:3]);

  A = cc - cc.T;
  delta = np.array([[A[1,2], A[2,0], A[0,1]]]).T;

  trace = np.trace(cc);
  t0 = np.hstack(([[trace]], delta.T));
  t1 = np.hstack((delta, cc + cc.T - trace * np.eye(3)));
  Q = np.vstack((t0, t1));

  # comute quaternion
  # main eigenvector of Q
  (U, s, Vh) = np.linalg.svd(Q);
  qr = Vh[0];

  # compute translation 
  R  = tr.quat2rot(qr);
  qt = uX - np.dot(R,uP.T).T;

  return (qr, qt[0,:3]);
Exemple #31
0
# - maskXRay (array) -
import Converter as C
import Connector as X
import Generator as G
import Geom as D
import Transform as T

surf = D.sphere((0,0,0), 0.5, 20)
surf = T.rotate(surf,(0.,0.,0.),(0.,1.,0.), 90.)
res = X.maskXRay__([surf])
C.convertArrays2File([res], "out.plt")
Exemple #32
0
# - projectAllDirs (array) -
import Geom as D
import Converter as C
import Generator as G
import Transform as T
import KCore.test as test

# Structure
a = D.sphere((0, 0, 0), 1., 20)
a = C.initVars(a, 'F', 1)
b = G.cart((1.1, -0.1, -0.1), (0.1, 0.1, 0.1), (1, 5, 5))
n = G.getNormalMap(b)
n = C.center2Node(n)
b = C.addVars([b, n])
b = C.initVars(b, 'F', 1)
c = T.projectAllDirs([b], [a], ['sx', 'sy', 'sz'])
test.testA(c, 1)

# Non structure
a = D.sphere((0, 0, 0), 1., 20)
a = C.initVars(a, 'F', 1)
b = G.cartTetra((1.1, -0.1, -0.1), (0.1, 0.1, 0.1), (1, 5, 5))
n = G.getNormalMap(b)
n = C.center2Node(n)
b = C.addVars([b, n])
b = C.initVars(b, 'F', 1)
c = T.projectAllDirs([b], [a], ['sx', 'sy', 'sz'])
test.testA(c, 2)

a = C.convertArray2Tetra(a)
b = G.cartTetra((1.1, -0.1, -0.1), (0.1, 0.1, 0.1), (1, 5, 5))
# - makeCartesian (array) -
import Generator as G
import Transform as T
import Converter as C
import KCore.test as test
a = G.cart((0.,0.,0.),(1.,1.,1.),(10,10,10))
a = T.reorder(a, (3,2,-1))
a = T.makeCartesianXYZ(a)
test.testA([a])
Exemple #34
0
def TFIHalfO__(a1, a2, weight, offset=0):
    import Transform as T
    import Geom as D

    Nt1 = a1[2]
    Nt2 = a2[2]
    if Nt1 > Nt2:
        ap = a2
        a2 = a1
        a1 = ap
        Np = Nt2
        Nt2 = Nt1
        Nt1 = Np
    # le plus long est toujours Nt2

    # Check
    P0 = (a1[1][0, 0], a1[1][1, 0], a1[1][2, 0])
    P00 = (a2[1][0, 0], a2[1][1, 0], a2[1][2, 0])
    if abs(P0[0] - P00[0]) > 1.e-6: a2 = T.reorder(a2, (-1, 2, 3))
    elif abs(P0[1] - P00[1]) > 1.e-6: a2 = T.reorder(a2, (-1, 2, 3))
    elif abs(P0[2] - P00[2]) > 1.e-6: a2 = T.reorder(a2, (-1, 2, 3))

    # Round
    w1 = C.array('weight', Nt1, 1, 1)
    w1 = C.initVars(w1, 'weight', 1.)
    w = C.array('weight', Nt2, 1, 1)
    w = C.initVars(w, 'weight', 1.)
    w[1][0, 0:Nt2 / 2 + 1] = weight
    P3 = G.barycenter([a2, a1], [w, w1])
    w = C.initVars(w, 'weight', 1.)
    w[1][0, Nt2 / 2:Nt2] = weight
    P4 = G.barycenter([a2, a1], [w, w1])

    # Projection
    b = C.convertArray2Hexa(a2)
    b = G.close(b)
    PP = C.array('x,y,z', 2, 1, 1)
    C.setValue(PP, 0, (P3[0], P3[1], P3[2]))
    C.setValue(PP, 1, (P4[0], P4[1], P4[2]))
    PPP = T.projectOrtho(PP, [b])
    PPP = PPP[1]

    PP3 = (PPP[0, 0], PPP[1, 0], PPP[2, 0])
    PP4 = (PPP[0, 1], PPP[1, 1], PPP[2, 1])

    indexPP3 = D.getNearestPointIndex(a2, PP3)[0] + offset
    if ((Nt1 - Nt2) / 2 - (Nt1 - Nt2) * 0.5 == 0
            and (indexPP3 + 1) / 2 - (indexPP3 + 1) * 0.5 != 0):
        indexPP3 += 1
    if ((Nt1 - Nt2) / 2 - (Nt1 - Nt2) * 0.5 != 0
            and (indexPP3 + 1) / 2 - (indexPP3 + 1) * 0.5 == 0):
        indexPP3 += 1
    #if (indexPP3 == 0): indexPP3 = 1
    #elif (indexPP3 == (Nt2-1)/2): indexPP3 += -1
    PP3 = (a2[1][0, indexPP3], a2[1][1, indexPP3], a2[1][2, indexPP3])
    N1 = indexPP3 + 1
    indexPP4 = Nt2 - N1
    PP4 = (a2[1][0, indexPP4], a2[1][1, indexPP4], a2[1][2, indexPP4])
    N2 = Nt2 - 2 * N1 + 2

    # Straight
    N3 = (Nt1 - N2 + 2) / 2

    ind = N3 - 1
    P1 = (a1[1][0, ind], a1[1][1, ind], a1[1][2, ind])
    P2 = (a1[1][0, Nt1 - ind - 1], a1[1][1,
                                         Nt1 - ind - 1], a1[1][2,
                                                               Nt1 - ind - 1])

    # Lines
    l1 = D.line(P1, P3, N=N1)
    l2 = D.line(P3, P4, N=N2)
    l3 = D.line(P4, P2, N=N1)

    p1 = D.line(P3, PP3, N=N3)
    p2 = D.line(P4, PP4, N=N3)

    # subzones
    s1 = T.subzone(a1, (1, 1, 1), (ind + 1, 1, 1))
    s2 = T.subzone(a1, (ind + 1, 1, 1), (Nt1 - ind, 1, 1))
    s3 = T.subzone(a1, (Nt1 - ind, 1, 1), (Nt1, 1, 1))

    s4 = T.subzone(a2, (1, 1, 1), (indexPP3 + 1, 1, 1))
    s5 = T.subzone(a2, (indexPP3 + 1, 1, 1), (indexPP4 + 1, 1, 1))
    s6 = T.subzone(a2, (indexPP4 + 1, 1, 1), (Nt2, 1, 1))

    #C.convertArrays2File([l1,l2,l3,p1,p2,s1,s2,s3,s4,s5,s6], 'lines.plt')

    # TFIs
    m = G.TFI([l1, l2, l3, s2])
    m1 = G.TFI([s1, s4, p1, l1])
    m2 = G.TFI([s5, p1, p2, l2])
    m3 = G.TFI([s6, p2, s3, l3])

    return [m, m1, m2, m3]
# - refine (array) -
import Geom as D
import Transform as T
import Converter as C
import KCore.test as test

# broken line (STRUCT)
a = D.line((0,0,0), (1,0,0), N=10)
b = D.line((1,0,0), (2,1,0), N=30)
a = T.join([a,b])
a = D.refine(a, N=30)
test.testA([a], 1)
#C.convertArrays2File(a, 'out.plt')

# fourche (BAR)
a = D.line((0,0,0), (1,0,0), N=10)
b = D.line((1,0,0), (2,1,0), N=50)
c = D.line((1,0,0), (2,-1,0), N=100)
A = [a,b,c]
A = C.convertArray2Hexa(A)
a = T.join(A)
a = D.refine(a, N=50)
test.testA([a], 2)
#C.convertArrays2File(a, 'out.plt')

# Circle (STRUCT)
a = D.circle((0,0,0), 1, N=120)
a = D.refine(a, N=120)
test.testA([a], 3)
#C.convertArrays2File(a, 'out.plt')
Exemple #36
0
# - send (array) -
import Converter as C
import Generator as G
import Transform as T

a = G.cart((0,0,0), (1,1,1), (100,100,300))
C.send(a, 'localhost')

for i in range(30):
    a = T.rotate(a, (0,0,0), (0,0,1), 10.)
    C.send(a, 'localhost')
# - display (array) -
import Generator as G
import CPlot
import Transform as T

a = G.cart((0, 0, 0), (1, 1, 1), (18, 28, 3))
CPlot.display(a, mode='mesh')

for i in range(360):
    a = T.rotate(a, (9, 14, 3.5), (0, 0, 1), 1.)
    CPlot.display(a)
Exemple #38
0
# - blankIntersectingCells (array)
import Converter as C
import Generator as G
import Transform as T
import Connector as X
a1 = G.cart((0., 0., 0.), (1., 1., 1.), (11, 11, 11))
a2 = T.rotate(a1, (0., 0., 0.), (0., 0., 1.), 10.)
a2 = T.translate(a2, (7., 5., 5.))
A = [a1, a2]
Ac = C.node2Center(A)
Ac = C.initVars(Ac, 'cellN', 1.)
Ac = X.blankIntersectingCells(A, Ac, tol=1.e-10)
C.convertArrays2File(Ac, "out.plt")
Exemple #39
0
# - getSmoothNormalMap (array) -
import Converter as C
import Generator as G
import Transform as T

a = G.cart((0.,0.,0.),(1.,1.,1.),(10,10,1))
b = G.cart((0.,0.,0.),(1.,1.,1.),(1,10,10))
b = T.rotate(b,(0.,0.,0.),(0.,1.,0.),45.)
c = C.convertArray2Hexa([a,b])
c = T.join(c); c = T.reorder(c,(1,))
c = T.rotate(c,(0.,0.,0.),(0.,1.,0.),15.)
s = G.getSmoothNormalMap(c, niter=4)
c = C.addVars([c,s])
C.convertArrays2File(c, "out.plt")
# - CEBBIntersection (array) -
import Generator as G
import Converter as C
import Transform as T
ni = 11
nj = 3
nk = 11
a1 = G.cart((0., 0., 0.), (0.1, 0.1, 0.2), (ni, nj, nk))
a2 = G.cart((1., 0., 0.), (0.1, 0.1, 0.2), (ni, nj, nk))
a2 = T.rotate(a2, (0, 0, 0), (0, 0, 1), 12.)
print G.CEBBIntersection(a1, a2)
# - addkplane (array) -
import Geom as D
import Transform as T
import Converter as C

a = D.naca(12., 501)
a = T.addkplane(a)
C.convertArrays2File(a, "out.plt")
Exemple #42
0
# - stack (array) -
import Generator as G
import Converter as C
import Transform as T
import KCore.test as test

a = G.cylinder((0, 0, 0), 1, 1.3, 360, 0, 1., (50, 10, 1))
b = T.rotate(a, (0, 0, 0), (1, 0, 0), 5.)
b = T.translate(b, (0, 0, 0.5))
c = G.stack(a, b)
test.testA([c], 1)
Exemple #43
0
# - plot (array) -
import Generator as G
import Transform as T
import Converter as C

# Create a cartesian grid
a = G.cart((0, 0, 0), (1, 1, 1), (10, 10, 10))

# plot mesh
C.plot(a)

a = T.translate(a, (0.5 * 1, 0, 0))
C.plot(a)

a = T.translate(a, (0.5 * 1, 0, 0))
C.plot(a)
# - snapFront (array) -
import Generator as G
import Converter as C
import Geom as D
import Connector as X
import Transform as T

s = D.circle((0, 0, 0), 1., N=100)
s = T.addkplane(s)

# Grille cartesienne (reguliere)
BB = G.bbox([s])
ni = 100
nj = 100
nk = 3

xmin = BB[0]
ymin = BB[1]
zmin = BB[2] - 0.5

xmax = BB[3]
ymax = BB[4]
zmax = BB[5] + 0.5

hi = (xmax - xmin) / (ni - 1)
hj = (ymax - ymin) / (nj - 1)
h = min(hi, hj)
ni = int((xmax - xmin) / h) + 7
nj = int((ymax - ymin) / h) + 7
b = G.cart((xmin - 3 * h, ymin - 3 * h, zmin), (h, h, 1.), (ni, nj, nk))
celln = C.array('cellN', ni, nj, nk)
Exemple #45
0
# - oneovern (array) -
import Transform as T
import Converter as C
import Generator as G

a = G.cart((0, 0, 0), (1, 1, 1), (10, 10, 1))
a2 = T.oneovern(a, (2, 2, 2))
C.convertArrays2File([a2], "out.plt")
# - projectDir (array) -
import Geom as D
import Converter as C
import Generator as G
import Transform as T
a = D.sphere((0, 0, 0), 1., 20)
b = G.cart((1.1, -0.1, -0.1), (0.03, 0.03, 0.03), (1, 50, 50))
c = T.projectDir(b, [a], (1., 0, 0))
d = T.projectDir([b], [a], (1., 0, 0), smooth=1)
C.convertArrays2File([a, b, c] + d, 'out.plt')
Exemple #47
0
def TFITri(a1, a2, a3):
    import Transform as T
    import Generator as G
    import Geom as D
    N1 = a1[2]
    N2 = a2[2]
    N3 = a3[2]

    # Verif de N
    Nt = N3 - N2 + N1 + 1
    if (Nt / 2 - Nt * 0.5 != 0):
        raise ValueError("TFITri: N3-N2+N1 must be odd.")
    N = Nt / 2
    if (N < 2):
        raise ValueError(
            "TFITri: invalid number of points for this operation.")
    if (N > N1 - 1):
        raise ValueError(
            "TFITri: invalid number of points for this operation.")
    if (N > N2 - 1):
        raise ValueError(
            "TFITri: invalid number of points for this operation.")

    # Assure la continuite
    P0 = (a1[1][0, N1 - 1], a1[1][1, N1 - 1], a1[1][2, N1 - 1])
    P00 = (a2[1][0, 0], a2[1][1, 0], a2[1][2, 0])
    P01 = (a2[1][0, N2 - 1], a2[1][1, N2 - 1], a2[1][2, N2 - 1])
    if (abs(P0[0] - P00[0]) + abs(P0[1] - P00[1]) + abs(P0[2] - P00[2]) > 1.e-6
            and abs(P0[0] - P01[0]) + abs(P0[1] - P01[1]) + abs(P0[2] - P01[2])
            > 1.e-6):
        t = a2
        a2 = a3
        a3 = t
        N2 = a2[2]
        N3 = a3[2]
        P00 = (a2[1][0, 0], a2[1][1, 0], a2[1][2, 0])

    if abs(P0[0] - P00[0]) > 1.e-6: a2 = T.reorder(a2, (-1, 2, 3))
    elif abs(P0[1] - P00[1]) > 1.e-6: a2 = T.reorder(a2, (-1, 2, 3))
    elif abs(P0[2] - P00[2]) > 1.e-6: a2 = T.reorder(a2, (-1, 2, 3))
    P0 = (a2[1][0, N2 - 1], a2[1][1, N2 - 1], a2[1][2, N2 - 1])
    P00 = (a3[1][0, 0], a3[1][1, 0], a3[1][2, 0])
    if abs(P0[0] - P00[0]) > 1.e-6: a3 = T.reorder(a3, (-1, 2, 3))
    elif abs(P0[1] - P00[1]) > 1.e-6: a3 = T.reorder(a3, (-1, 2, 3))
    elif abs(P0[2] - P00[2]) > 1.e-6: a3 = T.reorder(a3, (-1, 2, 3))
    #C.convertArrays2File([a1,a2,a3], 'order.plt')

    # Center
    w1 = C.array('weight', N1, 1, 1)
    w1 = C.initVars(w1, 'weight', 1)
    w2 = C.array('weight', N2, 1, 1)
    w2 = C.initVars(w2, 'weight', 1)
    w3 = C.array('weight', N3, 1, 1)
    w3 = C.initVars(w3, 'weight', 1)
    CC = G.barycenter([a1, a2, a3], [w1, w2, w3])

    # Subzones
    s1 = T.subzone(a1, (1, 1, 1), (N1 - N + 1, 1, 1))
    s2 = T.subzone(a1, (N1 - N + 1, 1, 1), (N1, 1, 1))
    s3 = T.subzone(a2, (1, 1, 1), (N2 - N1 + N, 1, 1))
    s4 = T.subzone(a2, (N2 - N1 + N, 1, 1), (N2, 1, 1))
    s5 = T.subzone(a3, (1, 1, 1), (N, 1, 1))
    s6 = T.subzone(a3, (N, 1, 1), (N3, 1, 1))

    # Lines
    index = N1 - N
    P01 = (a1[1][0, index], a1[1][1, index], a1[1][2, index])
    index = N2 - N1 + N - 1
    P12 = (a2[1][0, index], a2[1][1, index], a2[1][2, index])
    index = N - 1
    P23 = (a3[1][0, index], a3[1][1, index], a3[1][2, index])
    l1 = D.line(CC, P01, N=N2 - N1 + N)
    l2 = D.line(CC, P12, N=N)
    l3 = D.line(CC, P23, N=N1 - N + 1)

    # TFIs
    m1 = G.TFI([s1, l1, l3, s6])
    m2 = G.TFI([l1, s2, s3, l2])
    m3 = G.TFI([l2, s4, s5, l3])

    #return [l1,l2,l3,s1,s2,s3,s4,s5,s6]
    #return [s1,l1,l3,s6,m1]
    return [m1, m2, m3]
Exemple #48
0
        return x*x + 2.*y*y + 3*z
    elif deg == 3 :
        return x*x*y + 2.*y*y*y + 3*z
    elif deg == 4 :
        return x*x*x*x + 2.*y*y*y*y +z*z
    elif deg == 5 :
        return 2*x*x*x*x*x + 2.*y*y*z + z*z
    else :
        print 'Error : unknown degree of polynomials'
        import sys
        sys.exit()
        
# Maillage en noeuds
ni = 101; nj = 101; nk = 11
m = G.cylinder((0,0,0), 1., 10.,45., 145., 1., (ni,nj,nk))
m = T.reorder(m, (-1,2,3))
#
as=[]
as.append(m)
# init by function
m = C.addVars(m, 'F')
m = C.initVars(m, 'F', F, ['x','y','z'])

# Cree un maillage d'extraction
ni2 = 30; nj2 = 30
a = G.cart( (-1.,2.,0.4), (1./(ni2-1),1./(nj2-1),0.1), (ni2,nj2,2))
as.append(a)
C.convertArrays2File(as,"out.plt","bin_tp")
#
# Extrait la solution sur le maillage d'extraction
ordret = [2,3,5]
Exemple #49
0
def TFIO__(a, weight, offset=0):
    import Transform as T
    import Geom as D

    Nt = a[2]

    # Calcul des points P1, P2, P3, P4
    w = C.array('weight', Nt, 1, 1)
    w = C.initVars(w, 'weight', 1.)
    w[1][0, 0:Nt / 4 + 1] = weight
    P1 = G.barycenter(a, w)
    w = C.initVars(w, 'weight', 1.)
    w[1][0, Nt / 4:Nt / 2 + 1] = weight
    P2 = G.barycenter(a, w)
    w = C.initVars(w, 'weight', 1.)
    w[1][0, Nt / 2:3 * Nt / 4 + 1] = weight
    P3 = G.barycenter(a, w)
    w = C.initVars(w, 'weight', 1.)
    w[1][0, 3 * Nt / 4:Nt] = weight
    P4 = G.barycenter(a, w)

    # Calcul de P'1: projete de P1 sur le cercle
    b = C.convertArray2Hexa(a)
    b = G.close(b)
    PP = C.array('x,y,z', 4, 1, 1)
    C.setValue(PP, 0, (P1[0], P1[1], P1[2]))
    C.setValue(PP, 1, (P2[0], P2[1], P2[2]))
    C.setValue(PP, 2, (P3[0], P3[1], P3[2]))
    C.setValue(PP, 3, (P4[0], P4[1], P4[2]))

    PPP = T.projectOrtho(PP, [b])
    PPP = PPP[1]

    PP1 = (PPP[0, 0], PPP[1, 0], PPP[2, 0])
    PP2 = (PPP[0, 1], PPP[1, 1], PPP[2, 1])

    indexPP1 = D.getNearestPointIndex(a, PP1)[0] + offset
    if (indexPP1 < 0): indexPP1 = Nt + indexPP1 - 1
    if (indexPP1 > Nt - 1): indexPP1 = indexPP1 - Nt - 1

    # Renumerote a a partir de PP1
    b = T.subzone(a, (1, 1, 1), (indexPP1 + 1, 1, 1))
    c = T.subzone(a, (indexPP1 + 1, 1, 1), (Nt, 1, 1))
    a = T.join(c, b)
    indexPP1 = 0
    PP1 = (a[1][0, indexPP1], a[1][1, indexPP1], a[1][2, indexPP1])

    indexPP2 = D.getNearestPointIndex(a, PP2)[0] - offset
    PP2 = (a[1][0, indexPP2], a[1][1, indexPP2], a[1][2, indexPP2])

    indexPP3 = indexPP1 + Nt / 2
    PP3 = (a[1][0, indexPP3], a[1][1, indexPP3], a[1][2, indexPP3])

    N1 = indexPP2 - indexPP1 + 1
    N2 = Nt / 2 - N1 + 2
    indexPP4 = indexPP3 + N1 - 1
    PP4 = (a[1][0, indexPP4], a[1][1, indexPP4], a[1][2, indexPP4])

    # Lines
    l1 = D.line(P1, P2, N=N1)
    l2 = D.line(P2, P3, N=N2)
    l3 = D.line(P3, P4, N=N1)
    l4 = D.line(P4, P1, N=N2)

    dist1 = D.getLength(l1)
    p1 = D.line(P1, PP1, N=10)
    dist2 = D.getLength(p1)
    Np = int(dist2 / dist1 * N1) + 1

    p1 = D.line(P1, PP1, N=Np)
    p2 = D.line(P2, PP2, N=Np)
    p3 = D.line(P3, PP3, N=Np)
    p4 = D.line(P4, PP4, N=Np)

    # subzones
    s1 = T.subzone(a, (indexPP1 + 1, 1, 1), (indexPP2 + 1, 1, 1))
    s2 = T.subzone(a, (indexPP2 + 1, 1, 1), (indexPP3 + 1, 1, 1))
    s3 = T.subzone(a, (indexPP3 + 1, 1, 1), (indexPP4 + 1, 1, 1))
    s4 = T.subzone(a, (indexPP4 + 1, 1, 1), (Nt, 1, 1))

    # TFIs
    m = G.TFI([l1, l2, l3, l4])
    m1 = G.TFI([s1, p1, p2, l1])
    m2 = G.TFI([s2, p2, p3, l2])
    m3 = G.TFI([s3, p3, p4, l3])
    m4 = G.TFI([s4, p4, p1, l4])
    return [m, m1, m2, m3, m4]
Exemple #50
0
# - conformizeNGon (array) -
import Generator as G
import Converter as C
import Transform as T
a = G.cartNGon((0, 0, 0), (0.1, 0.1, 1), (11, 11, 1))
b = G.cartNGon((1., 0, 0), (0.1, 0.2, 1), (11, 6, 1))
a = G.cartNGon((0, 0, 0), (1, 1, 1), (3, 3, 1))
b = G.cartNGon((2., 0, 0), (2, 2, 1), (2, 2, 1))
res = T.join(a, b)
res2 = C.conformizeNGon(res)
C.convertArrays2File(res2, 'out.plt')
    def update(self, dt):
        for ent, (transform, motion, mcontrol,
                  bcontrol) in self.world.get_components(
                      Transform, Motion, MovementControl, BoostControl):
            particles = self.world.get_entity_component(ent, Particles)

            if bcontrol.ic.get_amt(
            ) > 0 and bcontrol.recovery_time_left == 0 and bcontrol.disabled == 0:
                if mcontrol.is_moving and (motion.velocity.x != 0
                                           or motion.velocity.y != 0):
                    bcontrol.recovery_time_left = bcontrol.recovery_time
                    bcontrol.boost_time_left = bcontrol.boost_time
                    bcontrol.accel_time_left = bcontrol.accel_time
                    mcontrol.disabled += 1

                    target_accel = motion.velocity.with_length(
                        bcontrol.accel_speed)
                    diff = mathutils.rot_diff(motion.velocity.to_rot(),
                                              mcontrol.rot)
                    if diff > bcontrol.back_boost_rot_diff or diff < -bcontrol.back_boost_rot_diff:
                        target_accel.mul_scalar(-1)
                    motion.acceleration = target_accel

                    if particles:
                        # calculations
                        d = motion.acceleration.normalized()
                        offset = d.rotated(mathutils.HALF_PI).mul_scalar(
                            bcontrol.particle_offset)

                        # paramaters
                        name = "boost_particle"
                        pos = transform.pos  #.added_to(d.multed_by_scalar(bcontrol.particle_offset))
                        rot = mathutils.HALF_PI - d.to_rot()
                        vel = d.mul_scalar(-bcontrol.particle_speed)
                        lifetime = bcontrol.particle_lifetime
                        opacity_func = lambda x: x

                        # creation
                        particles.add(name,
                                      Transform(pos.added_to(offset),
                                                rot + 0.1),
                                      lifetime=lifetime,
                                      velocity=vel.rotated(-0.2),
                                      opacity_func=opacity_func)
                        particles.add(name,
                                      Transform(pos.subbed_by(offset),
                                                rot - 0.1),
                                      lifetime=lifetime,
                                      velocity=vel.rotated(0.2),
                                      opacity_func=opacity_func)

            if bcontrol.recovery_time_left > 0:
                bcontrol.recovery_time_left = max(
                    0, bcontrol.recovery_time_left - dt)

            if bcontrol.boost_time_left > 0:
                bcontrol.boost_time_left = max(0,
                                               bcontrol.boost_time_left - dt)

                if bcontrol.boost_time_left == 0:
                    mcontrol.disabled -= 1

            if bcontrol.accel_time_left > 0:
                bcontrol.accel_time_left = max(0,
                                               bcontrol.accel_time_left - dt)
                motion.velocity.set_max_length(bcontrol.max_speed)
Exemple #52
0
# - integNormProduct (array) -
import Generator as G
import Converter as C
import Transform as T
import Post as P
from numpy import *
import math

res1 = math.pi*10.
res1c = (math.pi-math.pi/25.)*10.
res2 = 2.
res2c = 1.62
# Lit le fichier et le met dans arrays
a = G.cylinder((0.,0.,0.), 0.5, 1., 360., 0., 10., (50,2,30))
a2 = T.subzone(a, (1,1,1), (50,1,30))
#C.convertArrays2File([a], "new.plt", "bin_tp")

# integNormProd node2center, nj = 1
ni = a[2]-1
nj = a[3]-1
nk = a[4]-1
dens = C.array('tx,ty,tz', ni, nj, nk)
densa = C.initVars(dens,'tx', 0.)
densa = C.initVars(densa,'ty', 1.)
densa = C.initVars(densa,'tz', 0.)
res = P.integNormProduct([a2],[densa],[])
if math.fabs(res) > 1.e-1:
    print "pb in integNormProdNodeCenter, nj=1"

# integNormProd, nj = 1
ni = a[2]