Exemple #1
0
    def __init__(self, parameters):
        super().__init__(parameters)
        self.SUPPORTED_TYPES = {'man', 'woman', 'cat'}
        self._set_default_type_if_needed('human')
        chosen_type = self._get_chosen_type()

        face_params = self.parameters
        face_params[EP.ASPECT_RATIO] = 'fit'

        if chosen_type is None:
            print('{} head type not implemented!'.format(
                self.parameters[EP.TYPE]))
        elif chosen_type == 'man':
            self.parts.append(
                Part(entity=Face(face_params),
                     relative_position=RelativePosition(top=0.05)))
            self.parts.append(
                Part(entity=Hair(self.parameters),
                     relative_position=RelativePosition(top=0.0,
                                                        bottom=0.35,
                                                        left=0.1,
                                                        right=0.9)))
        elif chosen_type == 'woman':
            self.parts.append(
                Part(entity=Face(face_params),
                     relative_position=RelativePosition(top=0.05, bottom=0.9)))
            self.parts.append(
                Part(entity=Hair(self.parameters),
                     relative_position=RelativePosition()))
        elif chosen_type == 'cat':
            self.parts.append(Part(entity=Face(face_params)))
Exemple #2
0
    def __init__(self, xy):
        self.parts = []
        self.backup = []
        self.sensors = []
        self.colliding = []
        self.network = network()
        parts = self.parts
        backup = self.backup
        self.locked = [0, 0, 0, 0, 0, 0, 0, 0, 0]
        # add the head and body parts
        parts.append(Part(0, xy[0], xy[1], True))
        parts.append(Part(0, 0, 0, False))
        parts.append(Part(0, 0, 0, False))
        # Load the image files
        parts[0].loadImage("image_resources/body.png")
        parts[1].loadImage("image_resources/body.png")
        parts[2].loadImage("image_resources/head.png")
        # Set the constraints of the body parts so that the agents cannot fold in on themselves
        parts[0].setConstraint(((parts[1].getRotation() - 90) % 360,
                                (parts[1].getRotation() + 90) % 360))
        parts[1].setConstraint(((parts[0].getRotation() - 90) % 360,
                                (parts[0].getRotation() + 90) % 360))
        parts[2].setConstraint(((parts[1].getRotation() - 90) % 360,
                                (parts[1].getRotation() + 90) % 360))

        # Body parts and heads weight
        parts[0].setWeight(23.44)
        parts[1].setWeight(11.72)
        parts[2].setWeight(8.24)

        # Add the leg parts
        for i in range(0, 2):
            parts.append(part(310, 0, 0, False))
            parts.append(part(50, 0, 0, False))
            parts.append(part(50, 0, 0, False))
            parts.append(part(0, 0, 0, False))
            parts.append(part(0, 0, 0, False))
            parts.append(part(0, 0, 0, False))
        for l in range(3, 15):
            # Load the image files and set the constraints
            parts[l].loadImage("image_resources/leg.png")
            parts[l].setWeight(0.66)
            if l % 6 < 3:
                parts[l].setConstraint(((parts[l].getRotation() - 90) % 360,
                                        (parts[l].getRotation() + 90) % 360))
            else:
                parts[l].setConstraint((0, 360))

        # Initialise the backup storage for the parts information with 0 values
        for k in range(0, 15):
            backup.append(part(0, 0, 0, False))
            self.colliding.append(False)

        # Backup objects that can be used to revert object overlaps and handle collisions
        self.objects = []
        self.setSensors()
Exemple #3
0
    def __init__(self):
        # The robotic parts are seperated from the obstacles so that the state could comprise of only the robotic_parts,
        # since these are the only entities that are affected by change, unlike the obstacles which are stationery.
        self.dimensions = [random.randint(1, 100), random.randint(1, 100)]
        self.obstacles = [0] * random.randint(
            1, self.dimensions[0] * self.dimensions[1])
        self.robotic_parts = [0] * random.randint(
            1, self.dimensions[0] * self.dimensions[1] - len(self.obstacles))

        # Generate a list of random nums used to allocate positions of robotic parts and obstacles
        random_cells = random.sample(
            xrange(self.dimensions[0] * self.dimensions[1]),
            len(self.robotic_parts) + len(self.obstacles))

        # Mapping the grid indexes to coordinates for both the parts and obstacles
        i = 0
        while i < len(self.robotic_parts):
            self.robotic_parts[i] = Part([
                random_cells[i] / self.dimensions[1],
                random_cells[i] % self.dimensions[1]
            ])  #
            i = i + 1

        i = 0
        while i < len(self.obstacles):
            self.obstacles[i] = [
                random_cells[i + len(self.robotic_parts)] / self.dimensions[1],
                random_cells[i + len(self.robotic_parts)] % self.dimensions[1]
            ]
            i = i + 1

        # Populating the adjacency lists for each of the robotic parts
        coord_transformations = [[1, 0], [-1, 0], [0, 1], [0, -1]]
        for part in self.robotic_parts:

            # Perform a bfs on each of the robotic parts to create its adjacency list.
            parts = Queue()
            parts.put(part)

            while not parts.empty():
                curr_part = parts.get_nowait()

                # Coordinates of the current part
                x = curr_parts.coords[0]
                y = curr_part.coords[1]

                # Check for parts in the 4 adjacent cells
                for i in xrange(4):

                    is_occupied = check_occupation([
                        x + coord_transformations[i][0],
                        y + coord_transformations[i][1]
                    ])

                    if is_occupied != False:
                        q.put(self.robotic_parts[is_occupied])
                        part.adj_list.add(
                            is_occupied
                        )  # Add the index of the part occupying the cell
Exemple #4
0
 def addPart(self, name):
     part = Part()
     part.name = name
     part.src = name.replace(" ", "").lower() + ".md"
     self._parts.append(part)
     with open(os.path.join(self.source_path, "parts", part.src), "w") as f:
         f.write("")
     self.save()
Exemple #5
0
    def __init__(self, parameters):
        super().__init__(parameters)

        self.parts.append(
            Part(entity=Oval(parameters),
                 relative_position=RelativePosition(left=0,
                                                    top=0,
                                                    right=1,
                                                    bottom=1)))
Exemple #6
0
 def parts(self):
     '''Return a list of part visualizations.'''
     parts = []
     for index, data in enumerate(self.data.parts):
         # create part
         part = Part(data, index, self.palette, self.show_dynamic, self.show_register)
         # visualize part and keep the result
         parts.append(part.visualize())
     return parts
Exemple #7
0
    def __init__(self, parameters):
        super().__init__(parameters)
        self.SUPPORTED_TYPES = {'human'}
        self._set_default_type_if_needed('human')
        chosen_type = self._get_chosen_type()

        if chosen_type is None:
            print('arms of {} not implemented!'.format(self.parameters[EP.TYPE]))
        elif  chosen_type == 'human':
            self.parts.append(Part(entity=Oval(self.parameters), relative_position=RelativePosition()))
Exemple #8
0
    def __init__(self, parameters):
        super().__init__(parameters)
        self.SUPPORTED_TYPES = {'human'}
        self._set_default_type_if_needed('human')
        chosen_type = self._get_chosen_type()

        if chosen_type == 'human':
            self.parts.append(
                Part(entity=Oval({EP.ASPECT_RATIO: Eye.ASPECT_RATIO['human']}),
                     relative_position=RelativePosition(left=0,
                                                        top=0,
                                                        right=1,
                                                        bottom=1)))
            self.parts.append(
                Part(entity=Oval({EP.ASPECT_RATIO: 1.0}),
                     relative_position=RelativePosition(top=0,
                                                        bottom=1,
                                                        left=0.25,
                                                        right=0.75)))
Exemple #9
0
    def __init__(self, parameters):
        parameters[EP.TYPE] = 'woman'
        super().__init__(parameters)
        self._change_default_aspect_ratio_to_value(0.7)

        self.parts.append(
            Part(Head(self.parameters),
                 relative_position=RelativePosition(bottom=1 / 7.5,
                                                    left=0.38,
                                                    right=0.62)))
        self.parts.append(
            Part(Torso(self.parameters),
                 relative_position=RelativePosition(left=0.2,
                                                    right=0.8,
                                                    top=1 / 7.5,
                                                    bottom=4 / 7.5)))
        self.add_part(Leg, left=0.38, right=0.43, top=4 / 7.5)
        self.add_part(Leg, left=0.58, right=0.63, top=4 / 7.5)
        self.add_part(Arm, left=0.4, right=0.41, top=1 / 7.5, bottom=4 / 7.5)
        self.add_part(Arm, left=0.57, right=0.6, top=1 / 7.5, bottom=4 / 7.5)
Exemple #10
0
def loadJSONRegistry():
    loadedRegistry = {}
    with open('registry.json') as json_file:
        existingParts = json.load(json_file)
        for jsonPart in existingParts['Parts']:
            partName = jsonPart['Part Name']
            partType = jsonPart['Type']
            partVolume = jsonPart['Volume']
            newPart = Part(partName, partType, partVolume)

            loadedRegistry[partName] = newPart

    return loadedRegistry
Exemple #11
0
    def __init__(self):
        """
        Constructor
        """
        self.title = "Untitled"
        self.author = "Unauthored"

        self.parts = []

        # Add a default part
        self.parts.append(Part())

        # These events are global in scope
        self.globalEvents = []
Exemple #12
0
 def __init__(self, partsDescriptionDir = 'PartDescriptionFiles'):
     self._parts = {}
     """Parts lilsted by name."""
     for f in os.listdir(partsDescriptionDir):
         f = os.path.join(partsDescriptionDir, f)
         if not os.path.isfile(f):
             continue
         if not f.lower().endswith('.xml'):
             continue
         part = Part(f)
         name = part.getName()
         if name in self._parts:
             raise PgmError("Duplicate part names %s" % name)
         self._parts[part.getName()] = part
Exemple #13
0
    def __init__(self, params):
        super().__init__(params)
        self.SUPPORTED_TYPES = {'human'}
        self._set_default_type_if_needed('human')
        chosen_type = self._get_chosen_type()

        if chosen_type == 'human':
            self.parts.append(
                Part(
                    Triangle({
                        EP.TYPE: 'human_nose',
                        EP.ASPECT_RATIO: self.parameters[EP.ASPECT_RATIO]
                    }), RelativePosition()))
        else:
            'TODO'
 def create_part(self, part_name, model, dimensionality, part_type):
     self.write('#PART\n')
     part = Part(part_name, model, dimensionality, part_type)
     part_name = part.get_part_name()
     dimensionality = part.get_dimensionality()
     part_type = part.get_part_type()
     model_name = model.get_model_name()
     self.write(part_name + "=" + model_name + ".Part(dimensionality =" +
                dimensionality + " , name= '" + part_name + "' , type = " +
                part_type + ")\n")
     self.write('f, e = ' + part_name + '.faces, ' + part_name +
                '.edges #getting the edges and faces of the part\n')
     model.add_part(part)
     self.seperate_sec()
     return part
Exemple #15
0
    def handle_f3(self):
        """
        Format 3
        ReferenceDesignators;MPN;Manufacturer
        """
        bom_info = self.input_line.split(';')

        if not len(bom_info) == 3:
            return None

        part = Part(mpn=bom_info[1],
                    reference_designators=bom_info[0],
                    manufacturer=bom_info[2])

        return part
Exemple #16
0
 def add_part(self,
              part_type,
              top=0.0,
              bottom=1.0,
              left=0.0,
              right=1.0,
              aspect_ratio='default'):
     parameters = deepcopy(self.parameters)
     parameters[EP.ASPECT_RATIO] = aspect_ratio
     self.parts.append(
         Part(entity=part_type(parameters=parameters),
              relative_position=RelativePosition(left=left,
                                                 right=right,
                                                 top=top,
                                                 bottom=bottom)))
Exemple #17
0
 def __init__(self, element, server):
     self.server = server
     self.element = element
     self.part = Part(element.find('.Part'), self.server)
     try:
         self.videoFrameRate = element.attrib['videoFrameRate']
         self.videoCodec = element.attrib['videoCodec']
         self.container = element.attrib['container']
         self.bitrate = int(element.attrib['bitrate'])
         self.height = int(element.attrib['height'])
         self.width = int(element.attrib['width'])
         self.videoResolution = element.attrib['videoResolution']
         self.audioCodec = element.attrib['audioCodec']
     except KeyError as e:
         print "Missing key in element: ", e.message
Exemple #18
0
    def handle_f1(self):
        """
        Format 1
        MPN:Manufacturer:ReferenceDesignators
        TSR-1002:Panasonic:A1,D2
        """
        bom_info = self.input_line.split(':')

        if not len(bom_info) == 3:
            return None

        part = Part(mpn=bom_info[0],
                    manufacturer=bom_info[1],
                    reference_designators=bom_info[2])

        return part
Exemple #19
0
    def handle_f2(self):
        """
        Format 2
        Manufacturer -- MPN:ReferenceDesignators
        Panasonic -- TSR-1002:A1
        """
        bom_info = self.input_line.split('--')
        mpn_rd = bom_info[1].split(':')

        if not (len(bom_info) == 2 and len(mpn_rd) == 2):
            return None

        part = Part(mpn=mpn_rd[0],
                    manufacturer=bom_info[0],
                    reference_designators=mpn_rd[1])

        return part
Exemple #20
0
    def set_filename(self):
        filenames_str = filedialog.askopenfilenames(filetypes=[("*.STL",
                                                                "*.stl")])
        print("filenames_str {0}".format(filenames_str))
        print("Adding STL files:")
        for stl_file in list(filenames_str):
            print("- {0} ".format(stl_file))
            part_name = stl_file.split("/")[-1].replace(".STL", "")
            if (part_name in self.order.parts.keys()):
                print("!!!! Warning part already in order !!!!")
            part = Part(part_name)
            part.read_mesh(stl_file)
            part.calc_props()

            self.order.parts[part_name] = part
        #print ("filenames {0}".format(filenames_str.splitlist()))

        self.write_stls()
Exemple #21
0
    def __init__(self, xy):
        self.sensors = []
        self.colliding = []
        self.network = Network()
        self.locked = [0, 0, 0, 0, 0, 0, 0, 0, 0]
        self.cog = (0, 0)
        self.counter = 0
        self.xy = xy
        self.reset(False, 0, True)

        # Initialise the backup storage for the parts information with 0 values
        self.backup = []
        for k in range(0, 15):
            self.backup.append(Part(0, 0, 0, False))
            self.colliding.append(False)

        # Backup objects that can be used to revert object overlaps and handle collisions
        self.objects = []
Exemple #22
0
    def reset(self, stage, score, init):
        parts = []
        # add the head and body parts
        parts.append(Part(0, self.xy[0], self.xy[1], True))
        parts.append(Part(0, 0, 0, False))
        parts.append(Part(0, 0, 0, False))
        # Load the image files
        parts[0].loadImage("image_resources/body.png")
        parts[1].loadImage("image_resources/body.png")
        parts[2].loadImage("image_resources/head.png")
        # Body parts and heads weight
        parts[0].setWeight(23.44)
        parts[1].setWeight(11.72)
        parts[2].setWeight(8.24)

        # Add the leg parts
        for i in range(0, 2):
            parts.append(Part(310, 0, 0, False))
            parts.append(Part(50, 0, 0, False))
            parts.append(Part(50, 0, 0, False))
            parts.append(Part(0, 0, 0, False))
            parts.append(Part(0, 0, 0, False))
            parts.append(Part(0, 0, 0, False))
        for l in range(3, 15):
            # Load the image files and set the constraints
            parts[l].loadImage("image_resources/leg.png")
            parts[l].setWeight(0.66)
        self.parts = parts
        self.centerOfGravity()
        self.setSensors()
        self.setConstraints()
        if not init:
            if stage:
                self.network.nextGame(self.getCog()[0] - score)
            else:
                self.network.nextGameCompleted(self.getCog()[0] - score)
Exemple #23
0
 def __init__(self, avid):
     logging.info('downloading post info ...')
     initinfo = utility.getPostInfo(str(avid))
     if initinfo == None:
         logging.error('Failed to get video info. Maybe non-exists.')
         quit()
     self.avid = initinfo['aid']
     self.title = initinfo['videoData']['title']
     self.desc = initinfo['videoData']['desc']
     self.duration = utility.durationToTime(
         initinfo['videoData']['duration'])
     self.pubdate = time.localtime(initinfo['videoData']['pubdate'])
     self.authorName = initinfo['upData']['name']
     self.authorUID = initinfo['upData']['mid']
     self.parts = []
     for p in initinfo['videoData']['pages']:
         part = Part(p['cid'], self.title, p['part'],
                     utility.durationToTime(p['duration']))
         self.parts.append(part)
Exemple #24
0
    def custom_part_formatter(part_list, record_count):
        """
        Requires a list of Part Objects and Returns custom json output.
        Requires list of records to return.
        """

        formatted_parts = []
        part_group_keys = list(set([part.part_key for part in part_list]))

        for part_key in part_group_keys:
            count = 0
            reference_designator_all = []
            for part in part_list:
                if part_key == part.part_key:
                    count += 1
                    reference_designator_all.extend(part.reference_designators)
                    manufacturer = part.manufacturer
                    mpn = part.mpn

            # remove dupes.
            reference_designator_all = list(set(reference_designator_all))

            new_part = Part(
                mpn=mpn,
                manufacturer=manufacturer,
                reference_designators=reference_designator_all,
            )

            # override the num occurences with current part count
            new_part.num_occurences = count
            formatted_parts.append(new_part)

        # sorts the list by num occurences, and num reference designators descending.
        # filters by number of records requested when calling custom_part_formatter()
        newlist = sorted([part.as_dict() for part in formatted_parts],
                         key=lambda k:
                         (k['NumOccurences'], len(k['ReferenceDesignators'])),
                         reverse=True)[:record_count]

        return newlist
Exemple #25
0
    def __init__(self, backup, position, step):
        self.array = []
        self.training_step = step + 1
        self.init = False
        self.given = False
        # If this is an agents backup store default values for all parts
        if backup:
            for k in range(0, 15):
                self.array.append(Part(0, 0))
        # Otherwise spawn agent in a random position
        else:
            # Initialise the body and head of the agent
            random = randint(-30, 30)
            # The back of the agent is the heaviest so that it does ot topple forwards
            if self.training_step == 1:
                self.array.append(
                    Part(random + randint(-89, 89), 50, 23.44, position))
                self.array.append(Part(random, 50, 11.72))
                self.array.append(Part(random + randint(-89, 89), 50, 8.24))
            else:
                self.array.append(Part(0, 50, 23.44, position))
                self.array.append(Part(0, 50, 11.72))
                self.array.append(Part(0, 50, 8.24))
            # Load the head and bodies image files
            self.array[0].load_image("image_resources/body.png")
            self.array[1].load_image("image_resources/body.png")
            self.array[2].load_image("image_resources/head.png")

            # Initialise the legs of the agent
            for i in range(0, 2):
                random_values = [randint(0, 360), randint(-90, 90)]
                # The legs on each side of the agent should have matching rotations
                # The weight of each leg is 0.66 * 2 (Since each leg is made of 2 parts)
                self.array.append(Part(random_values[0], 12, 0.66))
                self.array.append(Part(random_values[0], 12, 0.66))
                self.array.append(Part(random_values[0], 12, 0.66))
                self.array.append(
                    Part(random_values[0] + random_values[1], 12, 0.66))
                self.array.append(
                    Part(random_values[0] + random_values[1], 12, 0.66))
                self.array.append(
                    Part(random_values[0] + random_values[1], 12, 0.66))

            # Load the image files for the legs
            for j in range(3, 15):
                self.array[j].load_image("image_resources/leg.png")
            # Set each parts position and constraints
            self.set_positions(position)
            self.set_constraints()
Exemple #26
0
def load_item(json_string, object_dec, json_filename):
    s = json_string.read()
    jdict = json.loads(s, object_hook=object_dec.decode_component)
    jdict.__dict__['json_id'] = json_filename
    item = Part(**(jdict.to_dict()))
    return item
Exemple #27
0
 def addToHead(self, location):
     self.body.addBegin((Part(self.surface, location, self.color,
                              self.size)))
Exemple #28
0
 def createPart(self, loc):
     return Part(self.surface, loc, self.color, self.size)
Exemple #29
0
    )
    ap.add_argument(
        '-c',
        '--cid-mode',
        action='store_true',
        help=
        'Specify videos by cid rather than avid. Argument "avid" will be regarded as cid. Use space to seperate multiple cids.'
    )
    args = ap.parse_args()

    if not args.cid_mode:
        for avid in args.avid:
            if avid.startswith('av'): avid = avid[2:]
            logging.info('Downloading post av%s' % avid)
            post = Post(avid)
            post.showInfo()
            if args.download:
                if args.part == -1:
                    logging.info('Downloading post: %s (%d parts in total)' %
                                 (post.title, len(post.parts)))
                    for p in post.parts:
                        p.download()
                    logging.info('Download finished!')
                else:
                    post.parts[args.part - 1].download()
    else:
        if args.download:
            for cid in args.avid:
                p = Part(cid, str(cid), str(cid), None)
                p.download()
Exemple #30
0
    def __init__(self, parameters):
        super().__init__(parameters)
        self.SUPPORTED_TYPES = {'man', 'woman'}
        self._set_default_type_if_needed('human')
        chosen_type = self._get_chosen_type()

        if chosen_type is None:
            print('{} hair type not implemented!'.format(
                self.parameters[EP.TYPE]))
        elif chosen_type == 'man':
            self.parts.append(
                Part(entity=Oval({
                    EP.LINE_THICKNESS: -1,
                    EP.COLOR: self.parameters[EP.COLOR]
                }),
                     relative_position=RelativePosition(left=0.0,
                                                        right=1.0,
                                                        top=0.0,
                                                        bottom=0.8)))
            self.parts.append(
                Part(entity=Oval({
                    EP.LINE_THICKNESS: -1,
                    EP.COLOR: self.parameters[EP.COLOR]
                }),
                     relative_position=RelativePosition(left=0.0,
                                                        right=0.1,
                                                        top=0.0,
                                                        bottom=1.0)))
            self.parts.append(
                Part(entity=Oval({
                    EP.LINE_THICKNESS: -1,
                    EP.COLOR: self.parameters[EP.COLOR]
                }),
                     relative_position=RelativePosition(left=0.9,
                                                        right=1.0,
                                                        top=0.0,
                                                        bottom=1.0)))
        elif chosen_type == 'woman':
            self.parts.append(
                Part(entity=Oval({
                    EP.LINE_THICKNESS: -1,
                    EP.COLOR: self.parameters[EP.COLOR]
                }),
                     relative_position=RelativePosition(left=0.0,
                                                        right=1.0,
                                                        top=0.0,
                                                        bottom=0.2)))
            self.parts.append(
                Part(entity=Oval({
                    EP.LINE_THICKNESS: -1,
                    EP.COLOR: self.parameters[EP.COLOR]
                }),
                     relative_position=RelativePosition(left=0.0,
                                                        right=0.1,
                                                        top=0.0,
                                                        bottom=1.0)))
            self.parts.append(
                Part(entity=Oval({
                    EP.LINE_THICKNESS: -1,
                    EP.COLOR: self.parameters[EP.COLOR]
                }),
                     relative_position=RelativePosition(left=0.9,
                                                        right=1.0,
                                                        top=0.0,
                                                        bottom=1.0)))