Example #1
0
def create_bounding_region(pixels, skin_regions, width, height):
    bounding_region = Region()
    topmost_points_list = []
    bottommost_points_list = []
    rightmost_points_list = []
    leftmost_points_list = []
    for i in xrange(0, 3):
        topmost_points_list.append(skin_regions[i].topmost_pixel())
        bottommost_points_list.append(skin_regions[i].bottommost_pixel())
        leftmost_points_list.append(skin_regions[i].leftmost_pixel())
        rightmost_points_list.append(skin_regions[i].rightmost_pixel())

    topmost_points_list.sort(key = operator.attrgetter('x'), reverse=False)
    bottommost_points_list.sort(key = operator.attrgetter('x'), reverse=True)
    rightmost_points_list.sort(key = operator.attrgetter('y'), reverse=False)
    leftmost_points_list.sort(key = operator.attrgetter('y'), reverse=True)

    topmost_pixel = topmost_points_list[0]
    bottommost_pixel = bottommost_points_list[0]
    rightmost_pixel = rightmost_points_list[0]
    leftmost_pixel = leftmost_points_list[0]

    for i in xrange(0, width):
        for j in xrange(0, height):
            pixel = pixels[i][j]
            if inside_bounding_region(topmost_pixel, bottommost_pixel, rightmost_pixel, leftmost_pixel, pixel):
                bounding_region.add_pixel(pixel)
    return bounding_region
Example #2
0
def create_bounding_region(pixels, skin_regions, width, height):
    bounding_region = Region()
    topmost_points_list = []
    bottommost_points_list = []
    rightmost_points_list = []
    leftmost_points_list = []
    for i in xrange(0, 3):
        topmost_points_list.append(skin_regions[i].get_topmost_pixel())
        bottommost_points_list.append(skin_regions[i].get_bottommost_pixel())
        leftmost_points_list.append(skin_regions[i].get_leftmost_pixel())
        rightmost_points_list.append(skin_regions[i].get_rightmost_pixel())

    topmost_points_list.sort(key=operator.attrgetter("x"), reverse=False)
    bottommost_points_list.sort(key=operator.attrgetter("x"), reverse=True)
    rightmost_points_list.sort(key=operator.attrgetter("y"), reverse=False)
    leftmost_points_list.sort(key=operator.attrgetter("y"), reverse=True)

    topmost_pixel = topmost_points_list[0]
    bottommost_pixel = bottommost_points_list[0]
    rightmost_pixel = rightmost_points_list[0]
    leftmost_pixel = leftmost_points_list[0]

    for i in xrange(0, width):
        for j in xrange(0, height):
            pixel = pixels[i][j]
            if inside_bounding_region(topmost_pixel, bottommost_pixel, rightmost_pixel, leftmost_pixel, pixel):
                bounding_region.add_pixel(pixel)
    return bounding_region
Example #3
0
def main():
    trumpRace = {
        'white': .5,
        'African American': 0.01,
        'Hispanic': 0.01,
        'Asian': 0.1,
        'Other': 0.2
    }
    HillRace = {
        'white': .2,
        'African American': 0.5,
        'Hispanic': 0.5,
        'Asian': 0.1,
        'Other': 0.2
    }
    c = Candidate.Candidate("Trump", .7, trumpRace)
    d = Candidate.Candidate("Hilary", .4, HillRace)
    ##vp=VotingProfile.VotingProfile([c,d], [.3,.7], [.1, .2], [.4,.6],[.1, .1], .2)
    ##print vp.__reNorm__([1,2,3])
    reg = Region.Region("Region 1", 30, [.3, .3, .2, .1, .1], 45.0, 8.0, .5,
                        .05, [c, d], [.3, .7], [.1, .1], [.4, .6], [.1, .1],
                        .2, [.8, .2])
    voter = Voter(reg, "white", 45, .8, .5, .6, [.3, .7], .8, False)
    print voter
    print(str(voter.vote()))
    print(str(voter.likelyVoter()))
Example #4
0
    def getRegiones(self):
        titlesX = True
        valorunidad = self.congeladorestotal()
        print("Valor: %i " % valorunidad)

        for row in self.hoja.rows:
            if (titlesX):
                for item in row:
                    self.titulos.append(
                        item.value.replace("(En cientos de miles)",
                                           "").replace("(En miles)", ""))
                titlesX = False
                # print(self.titulos)
            else:
                regionX = rg.Region(self.editarNombre(row[0].value),
                                    row[0].value, row[1].value, row[2].value,
                                    self.congeladorestotal(), row[3].value,
                                    row[4].value, row[5].value)
                self.listaRegiones.append(regionX)
                print(self.listaRegiones)

        self.titulos.append("Proporcion\n(Congeladores/Total Congeladores)")
        self.titulos.append("Escala de valoración\ndel beneficio")

        self.calcularEscalaValoracion()

        return self.listaRegiones
Example #5
0
    def __init__(self, name, startup_event, shutdown_event, event_q, reply_q,
                 PopulationParameters, DiseaseParameters, endTime,
                 RegionalLocations, RegionInteractionMatrixList,
                 RegionListGuide, modelPopNames, HospitalTransitionMatrix,
                 mprandomseed, eventqueues, *args):
        self.name = name
        #self.log = functools.partial(_logger, f'{self.name} Worker')
        self.startup_event = startup_event
        self.shutdown_event = shutdown_event
        self.event_q = event_q
        self.reply_q = reply_q
        self.terminate_called = 0
        self.modelPopNames = modelPopNames

        self.eventqueues = eventqueues

        self.R0StatsList = {}
        self.AgeStatsList = {}
        self.CurrentHospOccList = {}
        self.RegionStats = {}

        self.RegionReconciliationEvents = []

        self.ProcRegion = Region.Region(RegionalLocations,
                                        RegionInteractionMatrixList, name,
                                        RegionListGuide,
                                        HospitalTransitionMatrix,
                                        PopulationParameters,
                                        DiseaseParameters, endTime)

        random.seed(mprandomseed + int(self.name))
        np.random.seed(seed=mprandomseed + int(self.name))
Example #6
0
 def generateData(self):
     for i in range(58):
         tempRegion = Region.Region(self.temps[i], self.humidity[i], self.winds[i])
         tempRegion.castVariables()
         tempRegion.calcEquilMoisture()
         tempRegion.calcMoistureDampening()
         self.CalculatedData.append(tempRegion.calcFinal())
Example #7
0
    def __init__(self):
        # initial parameters
        self.feature_queue = []
        self.root = Tk()
        self.gui = GUI.GUI(self.feature_queue, self.root)
        self.gui.recordMaster(self)
        self.gui.MODE = self.MODE

        self.log = loginfo.log(self.gui)
        self.log.info('GUI has been initialized.')
        self.gui.setLog(self.log)

        # setup connection with APP
        tksupport.install(self.root)
        self.comm = Communicate.communication()
        self.comm.setLog(self.log)
        self.listenBegin()

        self.region = Region.region(position=[-1.0, 1.0, -1.0], log=self.log)
        self.camera = Camera.camera(angle=[0.0, 0.0])
        # initialize region center and camera center

        # thread control center
        self.threadStart()

        self.log.info('Three Mode could be started!')
        self.log.info('Current Mode is ' + self.MODE + ' Mode.')
        self.log.info('Please INIT the coordinate system!')

        self.periodicCall()

        reactor.run()
Example #8
0
 def __init__(self, name='Default name', num_threads=3, log=None):
     self.ret.name = name
     self.num_threads = 2
     self.log = log
     feature.__init__(num_threads, Region([0.0, 0.0, 0.0], 1.0),
                      Camera([0.0, 0.0]), name)
     # define your variables
     pass
Example #9
0
 def callbackFunc(self,event):#지역 검색
     i = self.combo.current()
     sregion = self.region[i].regionCd
     tree = ElementTree.fromstring(self.text)
     self.dregions = []
     self.dregions.append(Region(sregion, '전체'))
     for wanted in tree.findall('oneDepth'):
         if(wanted.find('regionCd').text == sregion):
             for aregion in wanted.findall('twoDepth'):
                 regionCd = aregion.find('regionCd').text
                 regionNm = aregion.find('regionNm').text
                 self.dregions.append(Region(regionCd, regionNm))
     comboregion = []
     for i in self.dregions:
         comboregion.append(i.regionNm)
     self.combo2['value'] = comboregion
     self.combo2.current(0)
Example #10
0
 def selectRegion(self, msg=None):
     if msg:
         r = self.getScreen().selectRegion(msg)
     else:
         r = self.getScreen().selectRegion()
     if r:
         return Region(r)
     else:
         return None
Example #11
0
def selectRegion(msg=None):
    if msg:
        r = ScreenUnion().selectRegion(msg)
    else:
        r = ScreenUnion().selectRegion()
    if r:
        return Region(r)
    else:
        return None
Example #12
0
def extractXmlRegionData(strXml): #지역 파싱
    tree = ElementTree.fromstring(strXml)
    regions = []
    for wanted in tree.findall('oneDepth'):
        regionCd = wanted.find('regionCd').text
        regionNm = wanted.find('regionNm').text

        regions.append(Region(regionCd,regionNm))
    return regions
Example #13
0
def create_skin_regions(pixels, skin_pixels, skin_regions, width, height):
    for i in xrange(0, width):
        for j in xrange(0, height):
            pixel = pixels[i][j]
            if pixel.is_skin() and not pixel.in_region():
                region = Region()
                skin_regions.append(region)
                pixel_queue = deque()
                pixel_queue.append(pixel)
                breadth_first_skin_search(pixels, skin_pixels, region, pixel_queue, width, height)
Example #14
0
 def __init__(self,name='plate',num_threads=3,position=[0.0,0.0,0.0], log=None):
     feature.__init__(self, num_threads, \
                      Region.region(position=position, tar_pos=[SR_LENGTH/2+0.3,1.0,SR_WIDTH/2+0.5], radius=[0.1,0.1,0.1]), \
                      Camera.camera(angle=[-25.0,0.0]), name, log)
     self.ret.name=name
     self.num_threads=1
     self.log=log
     self.phase = 1
     # define your variables
     pass
Example #15
0
 def init(self):
     credentials = pika.PlainCredentials(Config.get("Amqp","user"),Config.get("Amqp","pass"))
     parameters = pika.ConnectionParameters('localhost',int(Config.get("Amqp","port")),Config.get("Amqp","virt"), credentials)
     self.connection = pika.BlockingConnection(parameters);
     self.channel = self.connection.channel()
     self.channel.basic_qos(prefetch_count=1)        
     self.channel.basic_consume(self.on_request, queue="monitor")
     
     self.reg=Region.Region(Config.get("Amqp","user"),Config.get("Amqp","pass"),Config.get("Amqp","virt"),Config.get("couchDB","user"),Config.get("couchDB","pass")) 
     self.controller_name= Config.get("General","Gateway_Name")
 def __init__(self, name='Ancheck', num_threads=3, log=None):
     feature.__init__(
         self, num_threads,
         Region.region(position=[0.0, 0.0, 0.0], radius=[0.1, 0.1, 0.1]),
         Camera.camera(angle=[0.0, 0.0]), name, log)
     self.ret.name = name
     self.num_threads = 2
     self.log = log
     # define your variables
     pass
Example #17
0
 def __init__(self,
              name='plate',
              num_threads=3,
              position=[0.0, 0.0, 0.0],
              log=None):
     feature.__init__(self, num_threads, \
                      Region.region(position=position, tar_pos=[-0.7,3.0,-0.0], radius=[0.1,0.1,0.1]), \
                      Camera.camera(angle=[70.0,0.0]), name, log)
     self.ret.name = name
     self.num_threads = 3
     self.log = log
     # define your variables
     pass
 def init_places(self):
     """
     Creates Regions and places them in the dictionary 'regions'.
     :return:
     """
     i = 0
     for x in range(4):
         for y in range(4):
             # New dictionary of names to regions.
             self.regions[self.place_names[i]] = Region.Region(
                 self.place_names[i], x, y, self)
             # Dictionary of x y position to regions.
             self.positions[x, y] = self.regions[self.place_names[i]]
             i += 1
Example #19
0
def LoadState(sliceCallback, orientationCallback):
    """ loads all the concerned variables
    and restores the state of an application """

    # open file for reading
    handle = tkFileDialog.askopenfile(filetypes=[('SAVE files', '*.save')])
    if not handle: return

    ### 1. read the rendered properties
    Globals.renderProps = pickle.load(handle)

    # 2. load the slice index and the orientation
    pipelineSliceIndex = pickle.load(handle)
    pipelineOrientation = pickle.load(handle)

    # 3. load the region set
    Globals.objectSet.dic.clear()
    # load the number of regions
    numberOfRegions = pickle.load(handle)
    # load each region
    for i in range(numberOfRegions):
        regionIndex = pickle.load(handle)
        sliceIndex = pickle.load(handle)
        orientation = pickle.load(handle)
        ptsZero = pickle.load(handle)
        ptsOne = pickle.load(handle)
        numberOfProfiles = pickle.load(handle)
        profiles = []
        for j in range(numberOfProfiles):
            p = pickle.load(handle)
            s = Spline.PlaneSpline(p)
            profiles.append(s)
        # commit each region
        zero = Spline.PlaneSpline(ptsZero)
        one = Spline.PlaneSpline(ptsOne)
        region = Region.Region()
        region.SetZeroPoints(zero)
        region.SetOnePoints(one)
        region.sliceIndex = sliceIndex
        region.orientation = orientation
        region.profiles = profiles
        region.rendering.UpdateProfiles(region.profiles)
        Globals.objectSet.AddRegion(region, regionIndex)
        region.Hide()

    handle.close()
    orientationCallback(pipelineOrientation)
    sliceCallback(pipelineSliceIndex)
    Globals.renWin.Render()
Example #20
0
def create_skin_regions(pixels, skin_pixels, skin_regions, width, height):
    for i in xrange(0, width):
        for j in xrange(0, height):
            pixel = pixels[i][j]
            # Pixel is skin and is not of any other region
            # Create a new skin region. Perform a BFS on pixels
            # starting from current pixel, to all connected pixels
            # that are skin
            if pixel.is_skin() and not pixel.in_region():
                region = Region()
                skin_regions.append(region)
                pixel_queue = deque()
                pixel_queue.append(pixel)
                breadth_first_skin_search(pixels, skin_pixels, region,
                                          pixel_queue, width, height)
Example #21
0
def main():

    #List to store regions
    region_list = []
    #The number of regions we want can be changed by user input
    number_of_regions = 20

    #Get user input for number of regions from GUI

    #Generate regions and populate the list
    for x in range(number_of_regions):

        #Get the regions name from GUI
        name = "temp"
        new_region = Region(name)
Example #22
0
def analizeItems(items):
    class1 = conf.get('ItemSelector', 'Class1')
    class2 = conf.get('ItemSelector', 'Class2')

    curr_province = None
    curr_city = None

    resultList = []

    for i in range(0, len(items)):
        item = items[i]
        codename = item.findAll(name='td', attrs={'class': class1})
        if len(codename) == 0:
            codename = item.findAll(
                name='td', attrs={'class': class2})

        code = codename[0].get_text()
        name = codename[1].get_text()

        firstcode = code[:2]

        secondType = SecondType.GetType(code[2:4])
        thirdType = ThirdType.GetType(code[-2:])

        region = None
        if name.startswith('\xa0\xa0'):
            name = name.lstrip()
            region = Region(code, name, RegionLevel.County)
            region.Parent = curr_city if curr_city != None else curr_province

        elif name.startswith('\xa0'):
            name = name.lstrip()
            region = Region(code, name, RegionLevel.City)
            curr_city = region
            curr_city.Parent = curr_province
        else:
            region = Region(code, name, RegionLevel.Province)
            curr_province = region
            curr_city = None
        seq = (code,
               name,
               (region.Parent.Code if region.Parent != None else ''),
               (region.Parent.Name if region.Parent != None else ''),
               str(region.Level.value),
               str(secondType.value) if secondType != None else '',
               str(thirdType.value) if thirdType != None else '')
        s = ','.join(seq)
        resultList.append(s)

    return resultList
Example #23
0
 def __init__(self,
              name='Ancheck',
              num_threads=3,
              position=[0.0, 0.0, 0.0],
              log=None):
     feature.__init__(
         self, num_threads,
         Region.region(position=position,
                       tar_pos=[2.0, 4.0, 0.0],
                       radius=[0.1, 0.1, 0.1]),
         Camera.camera(angle=[65.0, -80.0]), name, log)
     self.ret.name = name
     self.num_threads = 1
     self.log = log
     imgRs = []
     # define your variables
     pass
Example #24
0
    def __init__(self, root, w=600, h=600):
        self.root = root

        # VTK setup
        Globals.ren = vtk.vtkRenderer()
        Globals.renWin = vtk.vtkRenderWindow()
        Globals.renWin.AddRenderer(Globals.ren)

        # setup main actor
        Globals.imagePipeline = ImagePipeline(Globals.ren)

        def SetReferenceSpacing():
            spacing = Globals.imagePipeline.GetSpacing()
            if spacing[2] > 0: Globals.referenceSize = min(spacing)
            else: Globals.referenceSize = min(spacing[0:2])

        SetReferenceSpacing()
        Globals.ren.AddActor(Globals.imagePipeline.actor)

        Globals.SetDefaultRenderProps()
        Globals.SetDefaultPreferences()
        Globals.crossHair = CrossHair.CrossHairWidget()
        # setup observer chain for main events
        Globals.objectSet = Region.RegionSet()
        self.imageObservers = [Globals.objectSet.UpdateFromGUI]

        self.InitializeGUI(w, h)

        # initialize the interactor
        iren = self.renderWidget.GetRenderWindow().GetInteractor()
        Globals.ren.SetBackground(.5, .5, .5)

        Globals.ren.ResetCamera()

        iren.Initialize()
        self.mode = Mode.Navigation()
        self.mode.Start()  # set the interactor style
        Globals.renWin.Render()
        iren.Start()

        # set the initial position of the pointer in the center
        bounds = Globals.imagePipeline.slicer.GetOutput().GetBounds()
        centerX = .5 * (bounds[0] + bounds[1])
        centerY = .5 * (bounds[2] + bounds[3])
        Globals.crossHair.SetPosition(centerX, centerY)
Example #25
0
 def __init__(self, name, startup_event, shutdown_event, event_q,reply_q,PopulationParameters,
                 DiseaseParameters,endTime,RegionalLocations,RegionInteractionMatrixList,
                 RegionListGuide,modelPopNames,HospitalTransitionMatrix,mprandomseed,eventqueues,historyData,SavedRegionFolder,GlobalLocations, *args):
     self.name = name
     #self.log = functools.partial(_logger, f'{self.name} Worker')
     self.startup_event = startup_event
     self.shutdown_event = shutdown_event
     self.event_q = event_q
     self.reply_q = reply_q
     self.terminate_called = 0
     self.modelPopNames = modelPopNames
     
     self.eventqueues = eventqueues
     
     self.R0StatsList = {}
     self.AgeStatsList = {}
     self.CurrentHospOccList = {}
     self.RegionStats = {}
     self.historyData = historyData
     
     self.RegionReconciliationEvents = []
     
     
     if ParameterSet.UseSavedRegion:
         if os.path.exists(os.path.join(SavedRegionFolder,"Region"+str(self.name)+".pickle")):
             self.ProcRegion = Utils.PickleFileRead(os.path.join(SavedRegionFolder,"Region"+str(self.name)+".pickle"))
             print("Getting Region"+str(self.name)+".pickle")
             self.RegionStats = copy.deepcopy(self.ProcRegion.savedStats)
             self.CurrentHospOccList = copy.deepcopy(self.ProcRegion.savedOcc)
             self.ProcRegion.resetParameters(GlobalLocations,PopulationParameters,DiseaseParameters,endTime)
         else:            
             print("Prior data for Region"+str(self.name)+" is missing")
         ##### need to update here based on new version
         #print(self.RegionStats)
         
     else:
         self.ProcRegion = Region.Region(RegionalLocations, RegionInteractionMatrixList, name, RegionListGuide,HospitalTransitionMatrix,PopulationParameters,DiseaseParameters,endTime)
         
     random.seed(mprandomseed+int(self.name))
     np.random.seed(seed=mprandomseed+int(self.name))
Example #26
0
    def __init__(self, regionsArray):
        super(World, self).__init__()
        self.regionsArray = regionsArray
        self.position = Vector2f(0, 0)
        self.size = 16 * World.REGION_TILES * Vector2f(regionsArray.x,
                                                       regionsArray.y)
        self.regionSize = 16 * Vector2f(World.REGION_TILES, World.REGION_TILES)
        self.regions = []

        o = Vector2f(-self.size.x / 2, -self.size.y / 2)
        for i in range(self.regionsArray.x):
            for j in range(self.regionsArray.y):
                self.regions.append(
                    Region(
                        o +
                        Vector2f(i * self.regionSize.x, j * self.regionSize.y),
                        self.regionSize, random.randint(0, 2147483647)))

        self.terrainBank = None
        self.terrainTransparency = -1
        self.factory = None
        self.dynamicEntities = set()
        self.scriptedEntities = set()
        self.loadingJobs = []
Example #27
0
    def GenFd (self):
        if self.FdUiName.upper() + 'fd' in GenFds.ImageBinDict.keys():
            return GenFds.ImageBinDict[self.FdUiName.upper() + 'fd']

        #
        # Print Information
        #
        GenFdsGlobalVariable.InfLogger("Fd File Name:%s" %self.FdUiName)
        Offset = 0x00
        for item in self.BlockSizeList:
            Offset = Offset + item[0]  * item[1]
        if Offset != self.Size:
            EdkLogger.error("GenFds", GENFDS_ERROR, 'FD %s Size not consistent with block array' % self.FdUiName)
        GenFdsGlobalVariable.VerboseLogger('Following Fv will be add to Fd !!!')
        for FvObj in GenFdsGlobalVariable.FdfParser.Profile.FvDict:
            GenFdsGlobalVariable.VerboseLogger(FvObj)

        GenFdsGlobalVariable.VerboseLogger('################### Gen VTF ####################')
        self.GenVtfFile()

        TempFdBuffer = StringIO.StringIO('')
        PreviousRegionStart = -1
        PreviousRegionSize = 1
        
        for RegionObj in self.RegionList :
            if RegionObj.RegionType == 'CAPSULE':
                continue
            if RegionObj.Offset + RegionObj.Size <= PreviousRegionStart:
                pass
            elif RegionObj.Offset <= PreviousRegionStart or (RegionObj.Offset >=PreviousRegionStart and RegionObj.Offset < PreviousRegionStart + PreviousRegionSize):
                pass
            elif RegionObj.Offset > PreviousRegionStart + PreviousRegionSize:
                GenFdsGlobalVariable.InfLogger('Padding region starting from offset 0x%X, with size 0x%X' %(PreviousRegionStart + PreviousRegionSize, RegionObj.Offset - (PreviousRegionStart + PreviousRegionSize)))
                PadRegion = Region.Region()
                PadRegion.Offset = PreviousRegionStart + PreviousRegionSize
                PadRegion.Size = RegionObj.Offset - PadRegion.Offset
                PadRegion.AddToBuffer(TempFdBuffer, self.BaseAddress, self.BlockSizeList, self.ErasePolarity, GenFds.ImageBinDict, self.vtfRawDict, self.DefineVarDict)
            PreviousRegionStart = RegionObj.Offset
            PreviousRegionSize = RegionObj.Size
            #
            # Call each region's AddToBuffer function
            #
            if PreviousRegionSize > self.Size:
                pass
            GenFdsGlobalVariable.VerboseLogger('Call each region\'s AddToBuffer function')
            RegionObj.AddToBuffer (TempFdBuffer, self.BaseAddress, self.BlockSizeList, self.ErasePolarity, GenFds.ImageBinDict, self.vtfRawDict, self.DefineVarDict)
        
        FdBuffer = StringIO.StringIO('')
        PreviousRegionStart = -1
        PreviousRegionSize = 1
        for RegionObj in self.RegionList :
            if RegionObj.Offset + RegionObj.Size <= PreviousRegionStart:
                EdkLogger.error("GenFds", GENFDS_ERROR,
                                'Region offset 0x%X in wrong order with Region starting from 0x%X, size 0x%X\nRegions in FDF must have offsets appear in ascending order.'\
                                % (RegionObj.Offset, PreviousRegionStart, PreviousRegionSize))
            elif RegionObj.Offset <= PreviousRegionStart or (RegionObj.Offset >=PreviousRegionStart and RegionObj.Offset < PreviousRegionStart + PreviousRegionSize):
                EdkLogger.error("GenFds", GENFDS_ERROR,
                                'Region offset 0x%X overlaps with Region starting from 0x%X, size 0x%X' \
                                % (RegionObj.Offset, PreviousRegionStart, PreviousRegionSize))
            elif RegionObj.Offset > PreviousRegionStart + PreviousRegionSize:
                GenFdsGlobalVariable.InfLogger('Padding region starting from offset 0x%X, with size 0x%X' %(PreviousRegionStart + PreviousRegionSize, RegionObj.Offset - (PreviousRegionStart + PreviousRegionSize)))
                PadRegion = Region.Region()
                PadRegion.Offset = PreviousRegionStart + PreviousRegionSize
                PadRegion.Size = RegionObj.Offset - PadRegion.Offset
                PadRegion.AddToBuffer(FdBuffer, self.BaseAddress, self.BlockSizeList, self.ErasePolarity, GenFds.ImageBinDict, self.vtfRawDict, self.DefineVarDict)
            PreviousRegionStart = RegionObj.Offset
            PreviousRegionSize = RegionObj.Size
            #
            # Verify current region fits within allocated FD section Size
            #
            if PreviousRegionStart + PreviousRegionSize > self.Size:
                EdkLogger.error("GenFds", GENFDS_ERROR,
                                'FD %s size too small to fit region with offset 0x%X and size 0x%X'
                                % (self.FdUiName, PreviousRegionStart, PreviousRegionSize))
            #
            # Call each region's AddToBuffer function
            #
            GenFdsGlobalVariable.VerboseLogger('Call each region\'s AddToBuffer function')
            RegionObj.AddToBuffer (FdBuffer, self.BaseAddress, self.BlockSizeList, self.ErasePolarity, GenFds.ImageBinDict, self.vtfRawDict, self.DefineVarDict)
        #
        # Create a empty Fd file
        #
        GenFdsGlobalVariable.VerboseLogger ('Create an empty Fd file')
        FdFileName = os.path.join(GenFdsGlobalVariable.FvDir,self.FdUiName + '.fd')
        #
        # Write the buffer contents to Fd file
        #
        GenFdsGlobalVariable.VerboseLogger('Write the buffer contents to Fd file')
        SaveFileOnChange(FdFileName, FdBuffer.getvalue())
        FdBuffer.close();
        GenFds.ImageBinDict[self.FdUiName.upper() + 'fd'] = FdFileName
        return FdFileName
Example #28
0
    def segmentation(self):
        self.list_to_segment = []
        self.list_widget_regions.clear()
        self.list_widget_edges.clear()
        self.edges_list.clear()
        self.regions_list.clear()
        self.completed = 0
        self.progress_bar_seg.setValue(0)
        if self.check_box_all.isChecked():
            self.list_to_segment = self.images_list
        if self.check_box_a.isChecked():
            self.list_to_segment = self.images_group_a
        if self.check_box_b.isChecked():
            self.list_to_segment = self.images_group_b
        length = len(self.list_to_segment)
        if self.check_box_edge_seg.isChecked():
            self.seg_type = "Edge"
            for e in self.list_to_segment:
                edges, regions = edgeBasedSegmentation.segment_image(e)
                image = QtGui.QImage(edges.data, edges.shape[1], edges.shape[0], edges.shape[1],
                                     QtGui.QImage.Format_Grayscale8)
                icon = QtGui.QIcon()
                icon.addPixmap(QtGui.QPixmap.fromImage(image), QtGui.QIcon.Normal, QtGui.QIcon.Off)
                item = QListWidgetItem(self.getShortFilePath(e))
                item.setIcon(icon)
                self.list_widget_edges.addItem(item)
                self.edges_list.append(edges)

                image = QtGui.QImage(regions.data, regions.shape[1], regions.shape[0], regions.shape[1],
                                     QtGui.QImage.Format_Grayscale8)
                icon = QtGui.QIcon()
                icon.addPixmap(QtGui.QPixmap.fromImage(image), QtGui.QIcon.Normal, QtGui.QIcon.Off)
                item = QListWidgetItem(self.getShortFilePath(e))
                item.setIcon(icon)
                self.list_widget_regions.addItem(item)
                self.regions_list.append(regions)

                self.completed += int(100 / length)
                self.progress_bar_seg.setValue(self.completed)
            self.progress_bar_seg.setValue(100)
        if self.check_box_water.isChecked():
            self.seg_type = "Watershed"
            for e in self.list_to_segment:
                segmentation = watershedSegmentation.watershedSegmentation(e)
                edges, regions = segmentation.getResults()
                plt.imsave('images/temp.png', regions)
                regions = cv2.imread('images/temp.png')
                image = QtGui.QImage(edges.data, edges.shape[1], edges.shape[0], edges.shape[1],
                                     QtGui.QImage.Format_Grayscale8)
                icon = QtGui.QIcon()
                icon.addPixmap(QtGui.QPixmap.fromImage(image), QtGui.QIcon.Normal, QtGui.QIcon.Off)
                item = QListWidgetItem(self.getShortFilePath(e))
                item.setIcon(icon)
                self.list_widget_edges.addItem(item)
                self.edges_list.append(edges)
                image = QtGui.QImage(regions.data, regions.shape[1], regions.shape[0], 3 * regions.shape[1],
                                     QtGui.QImage.Format_RGB888).rgbSwapped()
                icon = QtGui.QIcon()
                icon.addPixmap(QtGui.QPixmap.fromImage(image), QtGui.QIcon.Normal, QtGui.QIcon.Off)
                item = QListWidgetItem(self.getShortFilePath(e))
                item.setIcon(icon)
                self.list_widget_regions.addItem(item)
                self.regions_list.append(regions)

                self.completed += int(100 / length)
                self.progress_bar_seg.setValue(self.completed)
            self.progress_bar_seg.setValue(100)
        if self.check_box_region.isChecked():
            self.seg_type = "Region"
            for e in self.list_to_segment:
                image = cv2.imread(e, 1)
                regions, edges = Region.auto_region_growing(image)
                image = QtGui.QImage(edges.data, edges.shape[1], edges.shape[0], edges.shape[1],
                                     QtGui.QImage.Format_Grayscale8)
                icon = QtGui.QIcon()
                icon.addPixmap(QtGui.QPixmap.fromImage(image), QtGui.QIcon.Normal, QtGui.QIcon.Off)
                item = QListWidgetItem(self.getShortFilePath(e))
                item.setIcon(icon)
                self.list_widget_edges.addItem(item)
                self.edges_list.append(edges)
                image = QtGui.QImage(regions.data, regions.shape[1], regions.shape[0], regions.shape[1],
                                     QtGui.QImage.Format_Grayscale8)
                icon = QtGui.QIcon()
                icon.addPixmap(QtGui.QPixmap.fromImage(image), QtGui.QIcon.Normal, QtGui.QIcon.Off)
                item = QListWidgetItem(self.getShortFilePath(e))
                item.setIcon(icon)
                self.list_widget_regions.addItem(item)
                self.regions_list.append(regions)

                self.completed += int(100 / length)
                self.progress_bar_seg.setValue(self.completed)
            self.progress_bar_seg.setValue(100)
Example #29
0
def main():
    trumpRace = {
        'White': .3,
        'African American': 0.01,
        'Hispanic': 0.01,
        'Asian': 0.1,
        'Other': 0.2
    }
    HillRace = {
        'White': .2,
        'African American': 0.35,
        'Hispanic': 0.35,
        'Asian': 0.1,
        'Other': 0.2
    }
    CruzRace = {
        'White': .3,
        'African American': 0.1,
        'Hispanic': 0.3,
        'Asian': 0.1,
        'Other': 0.2
    }
    KasichRace = {
        'White': .3,
        'African American': 0.1,
        'Hispanic': 0.1,
        'Asian': 0.1,
        'Other': 0.2
    }
    BernieRace = {
        'White': .3,
        'African American': 0.2,
        'Hispanic': 0.3,
        'Asian': 0.3,
        'Other': 0.3
    }
    c = Candidate.Candidate("Trump", .7, trumpRace)
    d = Candidate.Candidate("Hillary", .4, HillRace)
    e = Candidate.Candidate("Cruz", .8, CruzRace)
    f = Candidate.Candidate("Kasich", .55, KasichRace)
    g = Candidate.Candidate("Sanders", .2, BernieRace)
    candidates = [c, d, e, f, g]

    for candidate in candidates:
        pickle.dump(candidate, open(candidate.name + ".cand", "wb"))

    r1 = Region.Region(
        "Region_1",
        [.4, .2, .1, .1, .05],  ## race breakdown
        50,  ## avg Age
        10,  ## variation in age
        .6,  ## prob voting
        .1,  ## variation in voting
        candidates,  ## candidates
        [1.8, 1.8, .4, .1, .3],  ## candidate pref
        [.4, .4, .2, .01, .07],  ## variation in candidate pref
        .6,  # spectrum
        .07,  # variation in spectrum
        .1,  # immigrant prob
        [.05, .4, .4, .2, .2])  ## immigrant pref)

    r2 = Region.Region(
        "Region_2",
        [.3, .3, .2, .1, .1],  ## race breakdown
        40,  ## avg Age
        7,  ## variation in age
        .5,  ## prob voting
        .1,  ## variation in voting
        candidates,  ## candidates
        [.3, .4, .4, .2, .6],  ## candidate pref
        [.1, .1, .1, .1, .2],  ## variation in candidate pref
        .4,  # spectrum
        .15,  # variation in spectrum
        .2,  # immigrant prob
        [.05, .4, .4, .2, .2])  ## immigrant pref)
    r3 = Region.Region(
        "Region_3",
        [.4, .1, .3, .4, .1],  ## race breakdown
        45,  ## avg Age
        3,  ## variation in age
        .54,  ## prob voting
        .1,  ## variation in voting
        candidates,  ## candidates
        [.2, .4, .5, .2, .4],  ## candidate pref
        [.05, .1, .1, .05, .1],  ## variation in candidate pref
        .5,  # spectrum
        .2,  # variation in spectrum
        .3,  # immigrant prob
        [.05, .4, .4, .2, .2])  ## immigrant pref)
    r4 = Region.Region(
        "Region_4",
        [.1, .6, .1, .2, .3],  ## race breakdown
        4,  ## avg Age
        3,  ## variation in age
        .64,  ## prob voting
        .1,  ## variation in voting
        candidates,  ## candidates
        [.1, .4, .3, .2, .4],  ## candidate pref
        [.03, .1, .1, .05, .1],  ## variation in candidate pref
        .5,  # spectrum
        .2,  # variation in spectrum
        .1,  # immigrant prob
        [.05, .4, .4, .2, .2])  ## immigrant pref)
    regions = [r1, r2, r3, r4]

    for region in regions:
        pickle.dump(region, open(region.name + ".rgn", "wb"))
Example #30
0
vs = villagesize = int(options.villagesize)
scalefactor = float(options.scalefactor)
inputfile = options.inputfile
max_distance = distance_limit = int(options.distance_limit)


def flattenonce(iterable):
    returnlist = []
    for member in iterable:
        returnlist.extend(member)
    return returnlist


worldmap = [
    Region(37, 37, distance_limit, name="Europe"),
    Region(40, 40, distance_limit, name="Western_Africa"),
    Region(40, 40, distance_limit, name="Eastern_Africa"),
    Region(47, 47, distance_limit, name="Central_Asia"),
    Region(40, 40, distance_limit, name="Southern_Africa"),
    Region(44, 35, distance_limit, name="Middle_East"),
    Region(20, 20, distance_limit, name="France"),
    Region(15, 15, distance_limit, name="Spain"),
    Region(32, 32, distance_limit, name="India"),
    Region(10, 20, distance_limit, name="Madagascar"),
    Region(23, 23, distance_limit, name="South_Central_Siberia"),
    Region(23, 23, distance_limit, name="North_Central_Siberia"),
    Region(35, 35, distance_limit, name="Krasnoyarsk"),
    Region(50, 50, distance_limit, name="North_America"),
    Region(42, 42, distance_limit, name="East_Siberia"),
    Region(54, 54, distance_limit, name="Far_East"),
Example #31
0
channel.basic_consume(on_request, queue=Config.get("Admin", "queue"))
dev_status = Config.get("Admin", "dev_status")
route = Route.Route(channel)
karaf = Karaf.Karaf(Config.get("Karaf", "user"), Config.get("Karaf", "pass"),
                    Config.get("Admin", "app_storage"),
                    Config.get("General", "location") + "/apps/",
                    Config.get("General", "location") + "/configs/",
                    Config.get("Karaf", "location") + "/")
device = Device.Device(Config.get("couchDB", "user"),
                       Config.get("couchDB", "pass"), Config.items("DeviceQ"))
res = Resource.Resource(
    Config.get("couchDB", "user"), Config.get("couchDB", "pass"),
    Config.get("General", "Gateway_Name"), Config.items("ResourceQ")
)  ##Redo Resource so that they are store in config not admin
reg = Region.Region(Config.get("Amqp", "user"), Config.get("Amqp", "pass"),
                    Config.get("Amqp", "virt"), Config.get("couchDB", "user"),
                    Config.get("couchDB", "pass"))

#Do Initial Request and Modify what needs to be modified
print("Sending Initial Request to Cloud")
initialRequest(Config, reg)
#Set variables for later use and start RPC request queueu
controller_name = Config.get("General", "Gateway_Name")

print(" [x] Awaiting RPC requests")
try:
    channel.start_consuming()
except KeyboardInterrupt:
    print("Keyboard baby")
    channel.stop_consuming()
    channel.close()