예제 #1
0
 def generarorbes(self):
     index = self.buscarcapa("Orbeski")
     if index > -1:
         for i in self.datos["layers"][index]["objects"]:
             pos = (i["x"], i["y"])
             orb = comp.Orbes("Ki", pos)
             c.Grupos["orbes"].add(orb)
             c.Grupos["todos"].add(orb)
         for i in self.datos["layers"][index + 1]["objects"]:
             pos = (i["x"], i["y"])
             orb = comp.Orbes("Vida", pos)
             c.Grupos["orbes"].add(orb)
             c.Grupos["todos"].add(orb)
         for i in self.datos["layers"][index + 2]["objects"]:
             pos = (i["x"], i["y"])
             orb = comp.Orbes("Trampa", pos)
             c.Grupos["orbes"].add(orb)
             c.Grupos["todos"].add(orb)
         for i in self.datos["layers"][index + 3]["objects"]:
             pos = (i["x"], i["y"])
             orb = comp.Orbes("Exp", pos)
             c.Grupos["orbes"].add(orb)
             c.Grupos["todos"].add(orb)
     else:
         print "No se generaron orbes"
예제 #2
0
    def _build_tree_static(self, proc_mat, fraction, parent_id, idx_map):
        """ Recursive top-down (start at root) construction 
            of a tree. This construction is static, i.e. it
            is built from the same processed pair-wise matrix,
            the relationships do not change based on the level
            of the tree.
        """
    
        if fraction < 0:
            return

        c = Components(proc_mat)
        components = c.get_components(fraction, proc_mat)[0]

        for component in components:
            i_map = idx_map[component]
            b_mat = self.base_affinity_matrix[i_map,:][:,i_map]
            p_mat = self.proc_affinity_matrix[i_map,:][:,i_map]
            keys = self.key_list[i_map]
            n_id = len(self.nodes)
            
            n = Node(i_map, keys, b_mat, p_mat, n_id)
            n._parent = parent_id

            if parent_id is not None:
                self.nodes[parent_id]._children.append(n_id)
            
            self.nodes[n_id] = n
            
            fraction = fraction - 1/float(self.fixed_k)
            self._build_tree_static(p_mat, fraction, n_id, i_map)
예제 #3
0
    def make_transmitter_boxes(self):
        y_coord = 0 + Config.wall_padding
        x_start = 0 + Config.wall_padding

        i = 0
        for x_coord in Utils.frange(
                x_start,
                Config.wall_padding + (num_of_packets * Config.packet_width) +
            (num_of_packets * Config.packet_padding),
                Config.packet_padding + Config.packet_width):

            # First make the border for the packet
            border = Components.Box(
                x_coord - Config.border_width, y_coord - Config.border_width,
                Config.packet_width + 2 * Config.border_width,
                Config.packet_height + 2 * Config.border_width,
                Config.border_color)
            self.border_sprite_list.add(border)

            # Make the transmitter box
            new_transbox = Components.TransmitterBox(x_coord, y_coord)
            self.transmitter_list.add(new_transbox)
            self.transmitter_map[i] = new_transbox

            # Make the packet (with it's coordinates the same as the transmitter box)
            new_packet = Components.Packet(x_coord, y_coord)
            self.packet_list.add(new_packet)
            self.packet_map[i] = new_packet
            i += 1
예제 #4
0
    def makeboot(self):

        c.LevelTutorial["TeclasMovimiento"].convert_alpha()

        self.tuto = {
            "Teclas": True,
            "Espacio": False,
            "Orbes": False,
            "Busca": False,
            "Pelea": False
        }

        self.listaenemigos = {"Triceratops": False, "Generador": True}
        self.target = [None]
        self.listname = ["Espacio", "Orbes", "Busca", "Pelea"]

        self.bg = comp.Background(self.tamano_mundo,
                                  c.LevelTutorial["Background"])
        self.goku = comp.Goku(self.tamano_mundo, self.target)
        self.goku.rect.x = 320
        self.goku.rect.y = 512
        self.krilin = comp.Ciudadano((320, 512), 0)
        c.Grupos["usuarios"].add(self.goku)
        #Anadir objetos GRUPO TODOS
        self.generarmuros(self.listname)
        c.Grupos["todos"].add(self.bg)
        self.generarorbes()
        self.generarenemigos(self.listaenemigos)
        c.Grupos["todos"].add(self.krilin)
        c.Grupos["todos"].add(self.goku)

        self.generarforeground()
예제 #5
0
    def make_receiver_boxes(self):
        y_coord = Config.window_height - Config.wall_padding - Config.packet_height
        x_start = 0 + Config.wall_padding

        i = 0
        for x_coord in Utils.frange(
                x_start,
                Config.wall_padding + (num_of_packets * Config.packet_width) +
            (num_of_packets * Config.packet_padding),
                Config.packet_padding + Config.packet_width):

            # First make the border for the packet
            border = Components.Box(
                x_coord - Config.border_width, y_coord - Config.border_width,
                Config.packet_width + 2 * Config.border_width,
                Config.packet_height + 2 * Config.border_width,
                Config.border_color)
            self.border_sprite_list.add(border)

            # Make the new receiver box
            new_recbox = Components.ReceiverBox(x_coord, y_coord)
            self.receiver_list.add(new_recbox)
            self.receiver_map[i] = new_recbox

            # Make the ACK packet (with it's coordinates the same as the receiver box)
            ack_packet = Components.AckPacket(x_coord, y_coord)
            self.ack_list.add(ack_packet)
            self.ack_map[i] = ack_packet
            i += 1
    def _construct_CNN_input(self, input_model, p_size, kernels):

        # CNN input block
        model = cmp.Conv1D_input_layer(input_model,
                                       self.CNN_sizes[p_size[0]],
                                       kernel_shape=kernels[0])

        # CNN Res Block
        min_1 = (self.CNN_sizes[p_size[1]] -
                 1) if (self.CNN_sizes[p_size[1]] - 1) > -1 else 0
        filters_res = [min_1, min_1, self.CNN_sizes[p_size[1]]]
        model = cmp.Conv1D_res_block(model,
                                     n_filters=filters_res,
                                     kernel_shape=kernels[1])

        # Dropout
        model = self._add_dropout(model, DNN=False)

        # CNN Identity Block
        filters_id = [self.CNN_sizes[p_size[2]], self.CNN_sizes[p_size[1]]]
        model = cmp.Conv1D_identity_block(model,
                                          filters_id,
                                          kernel_shape=kernels[2])

        # Dropout
        model = self._add_dropout(model, DNN=False)

        return model
예제 #7
0
def GetMacCabeMetric(path):
    """
    """

    complexity = 0.0

    try:
        p = os.path.dirname(path)
        if p not in sys.path:
            sys.path.append(p)
        import maccabe as codepaths
    except ImportError as info:
        msg = 'ERROR: maccabe module not imported: %s\n' % info
        sys.stderr.write(msg)
        return complexity
    else:

        cls = Components.GetClass(path)
        if inspect.isclass(cls):
            args = Components.GetArgs(cls)
            devs = getInstance(cls, args)

            ### Get class of model
            if not path.endswith('.pyc'):

                ### mcCabe complexity
                ### beware to use tab for devs code of models

                L = [
                    getattr(cls, fct)
                    for fct in ('extTransition', 'intTransition', 'outputFnc')
                    if hasattr(cls, fct)
                ]

                source_list = list(map(inspect.getsource, L))

                L_args = []

                for text in source_list:
                    ### textwrap for deleting the indentation

                    ast = codepaths.ast.parse(textwrap.dedent(text).strip())
                    visitor = codepaths.PathGraphingAstVisitor()
                    visitor.preorder(ast, visitor)

                    for graph in visitor.graphs.values():
                        complexity += graph.complexity()

                return complexity
                ### for .pyc file
            else:
                return 0.0
        else:
            return 0.0
예제 #8
0
    def generarforeground(self):
        index = self.buscarcapa("Palmeras")
        if index > -1:
            for i in self.datos["layers"][index]["objects"]:
                pos = (i["x"], i["y"] - i["height"])
                m = comp.Palmera(pos)
                c.Grupos["todos"].add(m)

            for i in self.datos["layers"][index + 1]["objects"]:
                pos = (i["x"], i["y"] - i["height"])
                m = comp.Edificio(pos)
                c.Grupos["todos"].add(m)
        else:
            print "No se genero foreground"
    def _construct_CNN(self, input_, p_size, params):
        # Input block
        k_size = [
            params["k_size_input"], params["k_size_b1"], params["k_size_b2"],
            params["k_size_b3"]
        ]
        model = self._construct_CNN_input(input_, p_size, k_size)

        # Block 3 res
        min_3 = (self.CNN_sizes[p_size[3]] -
                 1) if (self.CNN_sizes[p_size[3]] - 1) > -1 else 0
        filters_res = [min_3, min_3, self.CNN_sizes[p_size[3]]]
        model = cmp.Conv1D_res_block(model, filters_res, k_size[3])

        # Dropout
        model = self._add_dropout(model, DNN=False)

        # Extra blocks, gotta get deep
        model = cmp.Conv1D_res_block(model, [128, 128, 128], kernel_shape=3)

        # Dropout
        model = self._add_dropout(model, DNN=False)

        model = cmp.Conv1D_res_block(model,
                                     [128, 128, self.CNN_sizes[p_size[3]]],
                                     kernel_shape=3)

        # Dropout
        model = self._add_dropout(model, DNN=False)

        if params["type_b4"] == 0:
            # Block 4 ID
            filters_id = [self.CNN_sizes[p_size[4]], self.CNN_sizes[p_size[3]]]
            model = cmp.Conv1D_identity_block(model,
                                              filters_id,
                                              kernel_shape=3)
            # Dropout
            model = self._add_dropout(model, DNN=False)
            # Flatten for dense
            model = kl.Flatten()(model)
        else:
            # Flatten for dense
            model = kl.Flatten()(model)
            # Dense ID Block 4
            model = cmp.dense_res_block(model, self.DNN_sizes[p_size[4]])
            # Dropout
            model = self._add_dropout(model, DNN=True)

        return model
예제 #10
0
 def set_program(self, event):
     """ Kick off spacecraft info reading and display script names in windows
     
     Description: Creates Reader and Writer objects, commencing reading of inputs. Then displays script names.
      """
     # Clear output
     self.out_text.config(state=tkinter.NORMAL)
     self.out_text.delete(1.0,self.output_text_len+1.0)
     self.out_text.config(state=tkinter.DISABLED)
     
     # Clear listboxes
     self.a_htr_display.delete(0, len(self.ah_scripts))
     self.cf_htr_display.delete(0, len(self.cfh_scripts))
     self.twta_display.delete(0, len(self.twta_scripts))
     
     # Create spacecraft
     self.spacecraft = Components.Spacecraft()
     self.spacecraft.name = self.program_combo.get()
     self.spacecraft.script_dir = self.programs[self.spacecraft.name][0]
     self.spacecraft.data_dir = self.programs[self.spacecraft.name][1]
     self.spacecraft.db_dir = self.programs[self.spacecraft.name][2]
     self.author = self.author_text.get()
     
     # Create I/O objects
     try:
         self.reader = IOUtils.Reader(gui=self, spacecraft=self.spacecraft)
         self.reader.execute()
         self.writer = IOUtils.Writer(gui=self, dbase=self.reader.dbase, spacecraft=self.spacecraft, author=self.author)
         self.output_text('')
     except Exception as error:
         self.output_text('Failed to read spacecraft info: %s' % error)
         out = traceback.format_exc()
         self.output_text(out)
         print(out)
예제 #11
0
    def __init__(self, in_channels, out_channels):
        super(cSAWGANGeneratorV1, self).__init__()
        # (N, in_channels, 1, 1)
        self.l1 = nn.Sequential(
            nn.utils.spectral_norm(nn.ConvTranspose2d(in_channels=in_channels, out_channels=1024, kernel_size=4, stride=1, padding=0)),
            nn.BatchNorm2d(num_features=1024),
            nn.LeakyReLU(0.1)
        )

        # (N, 1024, 4, 4)
        self.l2 = nn.Sequential(
            nn.utils.spectral_norm(nn.ConvTranspose2d(in_channels=1024, out_channels=512, kernel_size=4, stride=2, padding=1)),
            nn.BatchNorm2d(num_features=512),
            nn.LeakyReLU(0.1)
        )

        # (N, 512, 8, 8)
        self.l3 = nn.Sequential(
            nn.utils.spectral_norm(nn.ConvTranspose2d(in_channels=512, out_channels=256, kernel_size=4, stride=2, padding=1)),
            nn.BatchNorm2d(num_features=256),
            nn.LeakyReLU(0.1)
        )

        self.attn = Components.SelfAttention(in_channels=256)

        # (N, 256, 16, 16)
        self.l4 = nn.Sequential(
            nn.utils.spectral_norm(nn.ConvTranspose2d(in_channels=256, out_channels=out_channels, kernel_size=4, stride=2, padding=1)),
            nn.Tanh()
        )
    def _construct_DNN(self, input_, p_size):
        # Input blocks
        model = self._construct_DNN_input(input_, p_size)

        # Block 3 Dense Res
        model = cmp.dense_res_block(model, self.DNN_sizes[p_size[3]])

        model = self._add_dropout(model, DNN=True)

        # Block 4 Dense ID
        model = cmp.dense_identityblock(model, self.DNN_sizes[p_size[4]],
                                        self.DNN_sizes[p_size[3]])
        # Dropout
        model = self._add_dropout(model, DNN=True)

        return model
예제 #13
0
    async def __worker(self, json_request):
        try:
            workflow_index = json_request["workflow_index"]
            item = json_request["item"]
            item_type = item["item_type"]
            item_name = item["item_name"]
            video = item.get("video", None)
            rules = item.get("rules", None)
        except KeyError as e:
            raise ServiceException(
                reason=f'Field {e} is missing in the payload.',
                status_code=400)

        meta_data = {"video": video, "rules": rules}

        workflow = self.workflow_lookup[workflow_index]
        item = Components.item_factory(item_type=item_type,
                                       item_name=item_name,
                                       item_step=None,
                                       **meta_data)
        item_index = len(self.item_lookup.keys())
        self.item_lookup[item_index] = item
        workflow.add_item(item)

        res = {
            "item_index":
            item_index,
            "message":
            f"Item {item.item_name} was added successfully to workflow of index {workflow_index}. "
            f"Item is now accessible at index {item_index}",
            "workflow":
            str(workflow)
        }
        return json.dumps(res)
예제 #14
0
 def __init__(self, pid, loc, dir):
     self.colliding = False
     self.image = pygame.Surface(
         [v.bullet_scale * v.cell_size, v.bullet_scale * v.cell_size])
     self.image.fill(pygame.Color(80, 50, 156, 255))
     self.velocity = Components.Velocity(dir * v.bullet_speed, 0, pid)
     Entity.__init__(self, pid, loc[0], loc[1])
예제 #15
0
 def paint_plane(self):
     self.big_jet_plane = Components.BigJetPlane(self)
     self.add(self.big_jet_plane,
              (WINDOW_WIDTH - Components.BigJetPlane.TEST_SIZE) / 2,
              (WINDOW_HEIGHT - Components.BigJetPlane.TEST_SIZE))
     self.addEventListener("click", self.click_listener)
     self.addEventListener("mousemove", self.big_jet_plane.move_listener)
예제 #16
0
 def generarenemigos(self, listaenemigos):
     index = self.buscarcapa("Triceratops")
     if index > -1:
         if listaenemigos["Triceratops"]:
             for i in self.datos["layers"][index]["objects"]:
                 pos = (i["x"], i["y"])
                 en = comp.Triceratops(pos, self.target)
                 c.Grupos["enemigos"].add(en)
                 c.Grupos["todos"].add(en)
         if listaenemigos["Generador"]:
             for i in self.datos["layers"][index + 1]["objects"]:
                 pos = (i["x"], i["y"])
                 en = comp.GeneradorMinions(pos, self.target)
                 #c.Grupos["enemigos"].add(en)
                 c.Grupos["todos"].add(en)
     else:
         print "No se generaron enemigos"
예제 #17
0
    def _build_tree_dynamic(self):
        """ Non-recursive bottom-up construction of the tree;
            at each level the pair-wise relationships are updated
            between components - where the instances inside components
            influence each others relationship to instances in other
            components
        """
        node_id = 0
        fractions = dice_fractions(self.fixed_k)

        c = Components(self.proc_affinity_matrix)
        #Build the bottom level
        components, comp_mat = c.get_components(fractions.next(), 
                                                self.proc_affinity_matrix,
                                                strongly_connected=True)
        for component in components:
            base_mat = self.base_affinity_matrix[component,:][:,component]
            proc_mat = self.proc_affinity_matrix[component,:][:,component]
            keys = self.key_list[component]
            n = Node(component, keys, base_mat, proc_mat, node_id)
            self.nodes[node_id] = n
            node_id += 1

        node_offset = temp_offset = 0
        for fraction in fractions:
            temp_offset += len(components) 
            c = Components(comp_mat)
            components, comp_mat = c.get_components(fraction, comp_mat, True)
            for component in components:
                instances = []
                for instance in component:
                    idx = instance + node_offset
                    self.nodes[idx]._parent = node_id
                    instances += self.nodes[idx].list_of_instances
                base_mat = self.base_affinity_matrix[instances,:][:,instances]
                proc_mat = self.proc_affinity_matrix[instances,:][:,instances]
                
                keys = self.key_list[instances]
                n = Node(instances, keys, base_mat, proc_mat, node_id)
                n._children = list(asanyarray(component) + node_offset) 
                self.nodes[node_id] = n
                node_id += 1
  
            node_offset = temp_offset
        self.root_id = node_id - 1
예제 #18
0
	def initUI(self, name, parent, tracker):
        #parsePlantXML(name)
		#FOR TESTING PURPOSES ONLY!!!!!
		lastDigit = name[-1]
		componentList = ["M-"+lastDigit+"-1","M-"+lastDigit+"-2","M-"+lastDigit+"-3",
						"T-"+lastDigit+"-1","T-"+lastDigit+"-2","T-"+lastDigit+"-3", 
						"M-"+lastDigit+"-4","M-"+lastDigit+"-5","M-"+lastDigit+"-6"]

		grid = QtGui.QGridLayout()
		upperPartLayout = QtGui.QHBoxLayout()
		grid.setSpacing(10)
		grid.setVerticalSpacing(20)
		
        #floorList is returned by xml parser --> ["Floor 1","Floor 2",...]
        #create instances of FloorButton (extends AbstractButton) from floorList
		for i in range(len(componentList)):
			
			theComponent = Components(componentList[i],self,self.tracker) #should be Component
			theComponentButton = ComponentButton(componentList[i],self,theComponent)
			theComponent.addButton(theComponentButton)

			self.componentButtonList.append(theComponentButton) #was GtGui.QPushButton
			#uncomment when ComponentButton is written!!!!!!!!!!!!!!!!!!!!!!1
			#self.roomButtonList.append(RoomButton(roomList[i], self, theRoom)) #abstract button --> FloorButton

			self.componentObjectList.append(theComponent)

			theComponent.addToFinalComponentList()

		for k in range(len(self.componentButtonList)):
			upperPartLayout.addWidget(self.componentButtonList[k])
			grid.addLayout(upperPartLayout, 0,0,1,2)
			grid.addWidget(self.componentObjectList[k], 1, 0)
			
			test = QtGui.QGroupBox('test',self)
			test.setStyleSheet("""QGroupBox { border: 2px solid rgb(0, 34, 102); background-color: rgb(0, 34, 102); 
			border-radius: 6px; padding-top: 20px; }""")
			grid.addWidget(test,1,1)
		# for k in range(len(self.floorObjectList)):
		# 	grid.addWidget(self.floorObjectList[k], 1, 0, 1, len(self.floorButtonList))
		self.setLayout(grid)
		self.setStyleSheet(""".Room { background-color: rgb(255, 255, 255); font-size: 10px; border-radius: 6px; } 
			.Room::title { color: transparent; background-color: transparent; padding-top: 5px; padding-left: 5px;}""")
    def _construct_DNN_input(self, input_model, p_size):

        # Input
        model = cmp.dense_simple_layer(input_model, self.DNN_sizes[p_size[0]])

        # Dense Res Block
        model = cmp.dense_res_block(model, self.DNN_sizes[p_size[1]])

        # Dropout
        model = self._add_dropout(model)

        # Dense Identity Block
        model = cmp.dense_identityblock(model, self.DNN_sizes[p_size[2]],
                                        self.DNN_sizes[p_size[1]])

        # Dropout
        model = self._add_dropout(model)

        return model
예제 #20
0
def AddObject():
    global listDraw
    global listPlatformCollider
    global listEnemy
    # add the ground
    ground = COMP.GameObject()
    ground.SetSolid(RED,800,300)
    ground.rect.y = 500

    # Create enemy.
    Info2 = COMP.GameObject()
    Info2.SetSprite(alien)
    Info2.objectName = "alien"
    Info2.SetLocation([750,410])
    
    listDraw.add(ground)
    listDraw.add(Info2)
    listPlatformCollider.add(ground)
    listEnemy.append(Info2)
예제 #21
0
    def makeboot(self):

        self.listaenemigos = {"Triceratops": False, "Generador": True}
        self.target = [None]
        comp.Global_posicion_x = -256
        comp.Global_posicion_y = -335

        self.misiones = ["Derrota a Cell"]

        self.bg = comp.Background(self.tamano_mundo,
                                  c.LevelFinalGraficos["Background"])
        self.goku = comp.Goku(self.tamano_mundo, self.target)
        self.goku.rect.x = 100
        self.goku.rect.y = 512
        c.Grupos["usuarios"].add(self.goku)
        #Anadir objetos GRUPO TODOS
        self.generarmuros()
        c.Grupos["todos"].add(self.bg)
        #self.generarorbes()
        #self.generarenemigos(self.listaenemigos)
        c.Grupos["todos"].add(self.goku)
예제 #22
0
    def generarmuros(self, listname=None):
        index = self.buscarcapa("Muros")
        print index
        if index > -1:
            for i in self.datos["layers"][index]["objects"]:
                possize = (i["x"], i["y"], i["width"], i["height"])
                m = comp.Muro(possize)
                c.Grupos["muros"].add(m)
                c.Grupos["todos"].add(m)
            if listname != None:
                j = 0
                for i in self.datos["layers"][index + 1]["objects"]:
                    possize = (i["x"], i["y"], i["width"], i["height"])
                    m = comp.CollisionChecker(possize)
                    m.name = listname[j]
                    j += 1
                    c.Grupos["collisions"].add(m)
                    c.Grupos["todos"].add(m)

        else:
            print "No se generaron muros"
예제 #23
0
    def OnItemDeselected(self, event):
        """ Item has been deselected
		"""
        line_number = self.getColumnText(self.currentItem, 2)
        python_path = self.getColumnText(self.currentItem, 4)

        if line_number != "":
            ### DEVS model retrieve
            devs = getInstance(Components.GetClass(python_path))
            ### check error and change image
            if not isinstance(devs, tuple):
                self.SetItemImage(self.currentItem, self.idx2)
예제 #24
0
def AddEnemy(enemy):
    Info2 = COMP.GameObject()
    if(enemy == 5):
        Info2.SetSprite(flyingAlien)
        Info2.SetLocation([750, 215])
    else:
        Info2 .SetSprite(alien)
        Info2.SetLocation([750, 410])

    Info2.objectName = "alien"
    listDraw.add(Info2)
    listEnemy.append(Info2)
예제 #25
0
    def Save(self, obj_dumped, fileName=None):
        """ Function that save the codeblock on the disk.
		"""
        assert (fileName.endswith(tuple(DumpZipFile.ext)))

        ### local copy of paths
        python_path = obj_dumped.python_path
        image_path = obj_dumped.image_path

        ### Now, file paths are in the compressed file
        if os.path.isabs(python_path):
            obj_dumped.python_path = os.path.join(
                fileName, os.path.basename(obj_dumped.python_path))

        if os.path.isabs(image_path):
            obj_dumped.image_path = os.path.join(
                fileName, os.path.basename(obj_dumped.image_path))

        obj_dumped.model_path = fileName

        ### args is constructor args and we save these and not the current value
        if hasattr(obj_dumped, 'args'):
            obj_dumped.args = Components.GetArgs(
                Components.GetClass(obj_dumped.python_path))

        try:

            fn = 'DEVSimPyModel.dat'

            ### dump attributes in fn file
            cPickle.dump(obj=PickledCollection(obj_dumped),
                         file=open(fn, "wb"),
                         protocol=0)

        except Exception, info:

            sys.stderr.write(
                _("Problem saving (during the dump): %s -- %s\n") %
                (str(fileName), info))
            return False
예제 #26
0
    def __init__(self, parent, id, model=None):
        wx.Choicebook.__init__(self, parent, id)

        self.parent = parent

        cls = Components.GetClass(model.python_path)

        if inspect.isclass(cls):
            pageTexts = {
                _('Doc'):
                inspect.getdoc(cls),
                _('Class'):
                inspect.getsource(cls),
                _('Constructor'):
                inspect.getsource(cls.__init__),
                _('Internal Transition'):
                inspect.getsource(cls.intTransition),
                _('External Transition'):
                inspect.getsource(cls.extTransition),
                _('Output Function'):
                inspect.getsource(cls.outputFnc),
                _('Time Advance Function'):
                inspect.getsource(cls.timeAdvance),
                _('Finish Function'):
                inspect.getsource(cls.finish)
                if hasattr(cls, 'finish') else "\tpass"
            }
        else:
            pageTexts = {
                _("Importing Error"):
                _("Error trying to import the module: %s.\nChange the python path by clicking in the above 'python_path' cell.\n %s"
                  % (model.python_path, str(cls)))
            }

        # Now make a bunch of panels for the choice book
        for nameFunc in pageTexts:
            win = wx.Panel(self)
            box = wx.BoxSizer(wx.HORIZONTAL)
            st = wx.TextCtrl(win, wx.NewId(), '', style=wx.TE_MULTILINE)
            try:
                txt = unicode(pageTexts[nameFunc],
                              errors='replace').encode('utf-8')
            except TypeError:
                txt = pageTexts[nameFunc]

            st.AppendText(txt)
            st.ShowPosition(wx.TOP)
            st.SetEditable(False)
            box.Add(st, 1, wx.EXPAND)
            win.SetSizer(box)

            self.AddPage(win, nameFunc)
예제 #27
0
    def __init__(self,
                 x,
                 y,
                 char,
                 name,
                 color,
                 speed=10,
                 blocks=False,
                 blocks_sight=False,
                 delay=0,
                 fighter=None,
                 always_visible=False,
                 ai=None,
                 item=None,
                 equipment=None,
                 ranged=None):
        self.name = name
        self.blocks = blocks
        self.blocks_sight = blocks_sight
        self.x = x
        self.y = y
        self.delay = delay
        self.base_speed = speed
        self.char = char
        self.color = Color(color)
        self.always_visible = always_visible
        self.path = None
        self.status = Status.StatusList()

        # Optional Components
        self.fighter = fighter
        if self.fighter:  # let the fighter component know who owns it
            self.fighter.owner = self

        self.ranged = ranged
        if self.ranged:  # let the fighter component know who owns it
            self.ranged.owner = self

        self.ai = ai
        if self.ai:  # let the AI component know who owns it
            self.ai.owner = self

        self.item = item
        if self.item:  # let the Item component know who owns it
            self.item.owner = self

        self.equipment = equipment
        if self.equipment:  # let the Equipment component know who owns it
            self.equipment.owner = self
            self.item = Components.Item()
            self.item.owner = self
예제 #28
0
def getComponents( matches, max_distance = 0, min_overlap = 0, by_query = False ):
    """return overlapping matches.
    
    max_distance
       allow reads to be joined if they are # residues apart. 
       Adjacent reads are 1 residue apart, overlapping reads are 0 residues
       apart
    min_overlap
       require at least # residues to be overlapping

    """

    addAlignments( matches, by_query = by_query )

    components = Components.IComponents()

    for x in range(0, len(matches)):
        components.add( x, x)

    if min_overlap > 0 and max_distance > 0:
        raise ValueError( "both min_overlap (%i) and max_distance (%i) > 0" % (min_overlap, max_distance) )

    if by_query:
        if min_overlap > 0:
            f = lambda x,y: alignlib_lite.py_getAlignmentOverlap( \
                matches[x].mMapQuery2Target, 
                matches[y].mMapQuery2Target, 
                alignlib_lite.py_RR ) >= min_overlap
        else:
            f = lambda x,y: alignlib_lite.py_getAlignmentShortestDistance( \
                    matches[x].mMapQuery2Target, 
                    matches[y].mMapQuery2Target, 
                    alignlib_lite.py_RR ) <= max_distance
    else:
        if min_overlap > 0:
            f = lambda x,y: alignlib_lite.py_getAlignmentOverlap( \
                matches[x].mMapTarget2Query, 
                matches[y].mMapTarget2Query, 
                alignlib_lite.py_RR ) >= min_overlap
        else:
            f = lambda x,y: alignlib_lite.py_getAlignmentShortestDistance( \
                    matches[x].mMapTarget2Query, 
                    matches[y].mMapTarget2Query, 
                    alignlib_lite.py_RR ) <= max_distance

    for x in range(len(matches)):
        for y in range(0, x):
            if f(x,y): components.add( x, y )

    return components.getComponents()
예제 #29
0
def computeMW(mol):
    """mol -> mw of largest fragment, mw of total molecule"""
    fragments = []
    total = 0.0
    if not mol.atoms: return 0.0, 0.0
    for atoms, bonds in Components.components(mol):
        mw = 0.0
        for atom in atoms:
            mw += atom.mass + atom.hcount
            fragments.append(mw)
        total += mw

    largest = max(fragments)
    return largest, total
예제 #30
0
    def applyMethod(self):
        """index the graph.        
        """
        componentor = Components.SComponents()

        infile = open(self.mFilenameAlignments, "r")

        naccepted, nrejected_score, nrejected_aligned = 0, 0, 0
        for line in infile:
            if line[0] == "#": continue
            if line.startswith("passed"): continue

            (qdomain, sdomain, estimate, code,
             qstart, qend, qali, sstart, send, sali,
             score, naligned, ngaps, zscore) =\
             line[:-1].split("\t")

            if code == "+":
                if int(naligned) >= self.mMinAlignedResidues:
                    componentor.add(qdomain, sdomain)
                    naccepted += 1
                else:
                    nrejected_aligned += 1
            nrejected_score += 1

        self.info( "computing components with %i accepted links (%i rejected score, %i rejected alignment length)" %\
                   (naccepted, nrejected_score, nrejected_aligned ) )

        components = componentor.getComponents()
        self.mOutfile.write("nid\tstart\tend\tfamily\n")

        noutput = 0
        family_id = 0

        nids = set()
        for domains in components:
            family_id += 1
            for domain in domains:
                nid, start, end = domain.split("_")
                nids.add(nid)
                self.mOutfile.write( "%s\t%s\t%s\t%s\n" % \
                                         ( nid, start, end, self.mPatternFamily % family_id ) )

                noutput += 1

        self.info("output from mst: nsequences=%i, nclusters=%i, ndomains=%i" %
                  (len(nids), family_id, noutput))

        self.mOutfile.close()
예제 #31
0
    def makeboot(self):

        self.listaenemigos = {"Triceratops": True, "Generador": True}
        self.target = [None]
        self.framescont = 0
        self.sec = 59
        self.min = 1
        self.timecount = False
        self.mision1 = False

        self.and17 = False
        self.androide17 = None

        self.misiones = [
            "Salava a Bulma y a Milk", "El tiempo se agota!!, sube tu nivel"
        ]

        self.bg = comp.Background(self.tamano_mundo,
                                  c.Level1Graficos["Background"])
        self.goku = comp.Goku(self.tamano_mundo, self.target)
        self.goku.rect.x = 100
        self.goku.rect.y = 512
        self.bulma = comp.Ciudadano((1946, 1396), 1)
        self.milk = comp.Ciudadano((1908, 3295), 2)
        c.Grupos["ciudadanos"].add(self.bulma)
        c.Grupos["ciudadanos"].add(self.milk)
        c.Grupos["usuarios"].add(self.goku)
        #Anadir objetos GRUPO TODOS
        self.generarmuros()
        c.Grupos["todos"].add(self.bg)
        self.generarorbes()
        self.generarenemigos(self.listaenemigos)
        c.Grupos["todos"].add(self.bulma)
        c.Grupos["todos"].add(self.milk)
        c.Grupos["todos"].add(self.goku)
        self.generarforeground()
예제 #32
0
    def OnDoubleClick(self, event):
        """ Double click on cell has been invocked
		"""
        line_number = self.getColumnText(self.currentItem, 2)
        python_path = self.getColumnText(self.currentItem, 4)

        if line_number != "":
            devscomp = Components.DEVSComponent()
            devscomp.setDEVSPythonPath(python_path)

            editor_frame = Components.DEVSComponent.OnEditor(devscomp, event)
            if editor_frame:
                editor_frame.text.GotoLine(int(line_number))

        event.Skip()
예제 #33
0
    def __init__(self, in_channels, num_classes):
        super(cSAWGANDiscriminatorV1, self).__init__()
        # (N, in_channels, 32, 32)
        self.l1 = nn.Sequential(
            nn.utils.spectral_norm(
                nn.Conv2d(in_channels=in_channels,
                          out_channels=256,
                          kernel_size=4,
                          stride=2,
                          padding=1)), nn.BatchNorm2d(num_features=256),
            nn.LeakyReLU(0.2))

        self.attn = Components.SelfAttention(in_channels=256)

        # (N, 256, 16, 16)
        self.l2 = nn.Sequential(
            nn.utils.spectral_norm(
                nn.Conv2d(in_channels=256,
                          out_channels=512,
                          kernel_size=4,
                          stride=2,
                          padding=1)), nn.BatchNorm2d(num_features=512),
            nn.LeakyReLU(0.2))

        # (N, 512, 32, 32)
        self.l3 = nn.Sequential(
            nn.utils.spectral_norm(
                nn.Conv2d(in_channels=512,
                          out_channels=1024,
                          kernel_size=4,
                          stride=2,
                          padding=1)), nn.BatchNorm2d(num_features=1024),
            nn.LeakyReLU(0.2))

        # (N, 1024, 4, 4)
        self.l4 = nn.Sequential(
            nn.utils.spectral_norm(
                nn.Conv2d(in_channels=1024,
                          out_channels=1024,
                          kernel_size=4,
                          stride=1,
                          padding=0)), nn.BatchNorm2d(num_features=1024),
            nn.LeakyReLU(0.2))

        # (N, 1024, 1, 1)
        self.l5 = nn.Sequential(
            nn.utils.spectral_norm(
                nn.Linear(in_features=1024 + num_classes, out_features=1)))
예제 #34
0
파일: driver.py 프로젝트: a-temlyakov/brian
#cost_mat = genfromtxt(data_path + '/cost-matrices/' + sys.argv[1])

""" Compute the bullseye score.
    Assuming MPEG-7 data is loaded
"""
e = Evaluation(cost_mat, 20, 70)
print "Top 40 bullseye score: ", e.bullseye(40)

""" Compute a new similarity matrix using dice coefficient
    as a population cue
"""
#Geometric mean, to ensure symmetry
cost_mat = sqrt(cost_mat * cost_mat.transpose())
p = Population(cost_mat, 20, 70, verbose=True)
#Not setting k will attempt to automatically find it!
processed_matrix = p.generate_diff(k=13) 

e = Evaluation(processed_matrix, 20, 70)
print "Top 40 bullseye score using dice: ", e.bullseye(40)

""" Update the similarity matrix further using the previous
    matrix to build components 
"""
c = Components(processed_matrix)
c.get_components(0.3, strongly_connected=False)
comp_mat = c._expand_component_difference()

e = Evaluation(comp_mat, 20, 70)
print "Top 40 bullseye score after components: ", e.bullseye(40)