• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python design.Design类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中upconvert.core.design.Design的典型用法代码示例。如果您正苦于以下问题:Python Design类的具体用法?Python Design怎么用?Python Design使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Design类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: parse

    def parse(self, filename, library_filename=None):
        """ Parse a kicad file into a design """

        design = Design()
        segments = set() # each wire segment
        junctions = set() # wire junction point (connects all wires under it)

        self.instance_names = []

        self.library = KiCADLibrary()

        if library_filename is None:
            directory, _ = split(filename)
            for dir_file in listdir(directory):
                if dir_file.endswith('.lib'):
                    self.library.parse(directory + '/' + dir_file)

        for cpt in self.library.components:
            design.add_component(cpt.name, cpt)

        with open(filename) as f:
            libs = []
            line = f.readline().strip()

            # parse the library references
            while line and line != "$EndDescr":
                if line.startswith('LIBS:'):
                    libs.extend(line.split(':', 1)[1].split(','))
                line = f.readline().strip()

            # Now parse wires and components, ignore connections, we get
            # connectivity from wire segments

            line = f.readline()

            while line:
                prefix = line.split()[0]

                if line.startswith('Wire Wire Line'):
                    self.parse_wire(f, segments)
                elif prefix == "Connection": # Store these to apply later
                    self.parse_connection(line, junctions)
                elif prefix == "Text":
                    design.design_attributes.add_annotation(
                        self.parse_text(f, line))
                elif prefix == "$Comp": # Component Instance
                    inst, comp = self.parse_component_instance(f)
                    design.add_component_instance(inst)
                    if comp is not None:
                        design.add_component(comp.name, comp)
                    self.ensure_component(design, inst.library_id, libs)

                line = f.readline()

        segments = self.divide(segments, junctions)
        design.nets = self.calc_nets(design, segments)

        design.scale(MULT)

        return design
开发者ID:BPheiffer,项目名称:schematic-file-converter,代码行数:60,代码来源:kicad.py


示例2: test_units

 def test_units(self):
     """ Capture absence of units. """
     layout = Layout()
     layout.units = None
     layout.layers.append(Layer())
     design = Design()
     design.layout = layout
     writer = Writer()
     writer.write(design)
开发者ID:evilnick,项目名称:schematic-file-converter,代码行数:9,代码来源:gerber_t.py


示例3: test_images

 def test_images(self):
     """ Capture images with no data. """
     layer = Layer()
     layer.images.append(Image())
     layout = Layout()
     layout.units = 'mm'
     layout.layers.append(layer)
     design = Design()
     design.layout = layout
     writer = Writer()
     writer.write(design)
开发者ID:evilnick,项目名称:schematic-file-converter,代码行数:11,代码来源:gerber_t.py


示例4: test_generating_geda_commands_for_toplevel_shapes

 def test_generating_geda_commands_for_toplevel_shapes(self):
     design = Design()
     design.shapes = [
         shape.Line((0, 0), (0, 50)),
         shape.Circle(0, 0, 300),
     ]
     design.pins = [
         components.Pin('E', (0, 0), (0, 30)),
         components.Pin('E', (0, 0), (0, 30)),
     ]
     commands = self.geda_writer.generate_body_commands(design)
     ## default pins require 6 commands, shapes require 1 command
     self.assertEquals(len(commands), 2*6 + 2*1)
开发者ID:PatMart,项目名称:schematic-file-converter,代码行数:13,代码来源:geda_t.py


示例5: parse

    def parse(self, infile='.'):
        """ Parse tokens from gerber files into a design. """
        is_zip = infile.endswith('.zip')
        openarchive = ZipFile if is_zip else TarFile.open
        archive = batch_member = None
        try:
            # define multiple layers from folder
            if LAYERS_CFG in infile:
                archive = None
                cfg_name = infile
                cfg = open(cfg_name, 'r')

            # define multiple layers from archivea 
            else:
                archive = openarchive(infile)
                batch = archive.namelist if is_zip else archive.getnames
                batch_member = archive.open if is_zip else archive.extractfile
                cfg_name = [n for n in batch() if LAYERS_CFG in n][0]
                cfg = batch_member(cfg_name)

        # define single layer from single gerber file
        except ReadError:
            name, ext = path.split(infile)[1].rsplit('.', 1)
            layer_defs = [LayerDef(ext.lower() == 'ger' and name or ext,
                                   'unknown', infile)]
            self._gen_layers(layer_defs, None, None)

        # tidy up batch specs
        else:
            layer_defs = [LayerDef(rec[0],
                                   rec[1],
                                   path.join(path.split(cfg_name)[0], rec[2]))
                          for rec in
                          csv.reader(cfg, skipinitialspace=True)]
            cfg.close()
            self._gen_layers(layer_defs, archive, batch_member)

        # tidy up archive
        finally:
            if archive:
                archive.close()

        # compile design
        if DEBUG:
            self._debug_stdout()

        self.layout.units = (self.params['MO'] == 'IN' and 'inch' or 'mm')

        design = Design()
        design.layout = self.layout
        return design
开发者ID:ch3ka,项目名称:schematic-file-converter,代码行数:51,代码来源:gerber.py


示例6: parse

    def parse(self):
        '''Returns a Design built up from a schematic file that represents one
        sheet of the original schematic'''
        tree = ViewDrawBase.parse(self)
        # tree['lines'] is a [list of [list of lines]]
        tree['shape'].extend(sum(tree['lines'], []))
        ckt = Design()
        # TODO little weak here, a copy instead?
        ckt.components = self.lib

        for net in tree['net']:
            ckt.add_net(net)
        for inst in tree['inst']:
            ckt.add_component_instance(inst)
            # hold on tight, this is ugly
            for (netid, netpt, pinid) in inst.conns:
                net = [n for n in ckt.nets if n.net_id == netid][0]
                comp = ConnectedComponent(inst.instance_id, pinid)
                net.ibpts[netpt - 1].add_connected_component(comp)
            del inst.conns
        for net in ckt.nets:
            del net.ibpts

        for shape in tree['shape']:
            ckt.add_shape(shape)
            if isinstance(shape, Label):
                ann = Annotation(shape.text, shape.x, shape.y,
                                 shape._rotation, True)
                ckt.design_attributes.add_annotation(ann)

        for k, v, annot in tree['attr']:
            ckt.design_attributes.add_attribute(k, v)
            ckt.design_attributes.add_annotation(annot)

        return ckt
开发者ID:BPheiffer,项目名称:schematic-file-converter,代码行数:35,代码来源:viewdraw.py


示例7: __init__

    def __init__(self):
        self.design = Design()

        # map (component, gate name) to body indices
        self.cptgate2body_index = {}

        # map (component, gate name) to pin maps, dicts from strings
        # (pin names) to Pins. These are used during pinref processing
        # in segments.
        self.cptgate2pin_map = defaultdict(dict)

        # map (component, gate names) to annotation maps, dicts from
        # strings (name|value) to Annotations. These represent the
        # >NAME and >VALUE texts on eagle components, which must be
        # converted into component instance annotations since their
        # contents depend on the component instance name and value.
        self.cptgate2ann_map = defaultdict(dict)

        # map part names to component instances. These are used during
        # pinref processing in segments.
        self.part2inst = {}

        # map part names to gate names to symbol attributes. These
        # are used during pinref processing in segments.
        self.part2gate2symattr = defaultdict(dict)
开发者ID:patrickyeon,项目名称:schematic-file-converter,代码行数:25,代码来源:__init__.py


示例8: parse

    def parse(self, inputfile):
        """ Parse a gEDA file into a design.

            Returns the design corresponding to the gEDA file.
        """
        inputfiles = []

        ## check if inputfile is in ZIP format
        if zipfile.is_zipfile(inputfile):
            self.geda_zip = zipfile.ZipFile(inputfile)
            for filename in self.geda_zip.namelist():
                if filename.endswith('.sch'):
                    inputfiles.append(filename)
        else:
            inputfiles = [inputfile]

        self.design = Design()

        ## parse frame data of first schematic to extract
        ## page size (assumes same frame for all files)
        with self._open_file_or_zip(inputfiles[0]) as stream:
            self._check_version(stream)

            for line in stream.readlines():
                if 'title' in line and line.startswith('C'):
                    obj_type, params = self._parse_command(StringIO(line))
                    assert(obj_type == 'C')

                    params['basename'], _ = os.path.splitext(
                        params['basename'],
                    )

                    log.debug("using title file: %s", params['basename'])

                    self._parse_title_frame(params)

        ## store offset values in design attributes
        self.design.design_attributes.attributes.update({
            '_geda_offset_x': str(self.offset.x),
            '_geda_offset_y': str(self.offset.y),
            '_geda_frame_width': str(self.frame_width),
            '_geda_frame_height': str(self.frame_height),
        })

        for filename in inputfiles:
            f_in = self._open_file_or_zip(filename)
            self._check_version(f_in)

            self.parse_schematic(f_in)

            basename, _ = os.path.splitext(os.path.basename(filename))
            self.design.design_attributes.metadata.set_name(basename)

            ## modify offset for next page to be shifted to the right
            self.offset.x = self.offset.x - self.frame_width

            f_in.close()

        return self.design
开发者ID:ncsaba,项目名称:schematic-file-converter,代码行数:59,代码来源:geda.py


示例9: parse

    def parse(self):
        '''Returns a Design built up from a schematic file that represents one
        sheet of the original schematic'''
        tree = ViewDrawBase.parse(self)
        # tree['lines'] is a [list of [list of lines]]
        tree['shape'].extend(sum(tree['lines'], []))
        ckt = Design()
        # TODO little weak here, a copy instead?
        ckt.components = self.lib
        
        for net in tree['net']:
            ckt.add_net(net)
        for inst in tree['inst']:
            ckt.add_component_instance(inst)
            # hold on tight, this is ugly
            for (netid, netpt, pinid) in inst.conns:
                net = [n for n in ckt.nets if n.net_id == netid][0]
                comp = ConnectedComponent(inst.instance_id, pinid)
                net.ibpts[netpt - 1].add_connected_component(comp)
            del inst.conns
        for net in ckt.nets:
            del net.ibpts

        # too bad designs don't have top-level shapes (yet?)
        #map(ckt.add_shape, tree['shape'])
        
        for lbl in [s for s in tree['shapes'] if isinstance(s, Label)]:
            ann = Annotation(lbl.text, lbl.x, lbl.y, lbl.rotation, True)
            ckt.design_attributes.add_annotation(ann)
        
        for k, v in tree['attr']:
            ckt.design_attributes.add_attribute(k, v)

        self.correct_y(ckt, tree['Dbounds'][0])
        return ckt
开发者ID:ch3ka,项目名称:schematic-file-converter,代码行数:35,代码来源:viewdraw.py


示例10: parse

    def parse(self, filename):
        """ Parse a specctra file into a design """

        self.design = Design()

        with open(filename) as f:
            data = f.read()

        tree = DsnParser().parse(data)

        struct = self.walk(tree)
        self.resolution = struct.resolution
        self._convert(struct)

        return self.design
开发者ID:BPheiffer,项目名称:schematic-file-converter,代码行数:15,代码来源:specctra.py


示例11: __init__

    def __init__(self):
        self.design = Design()

        # This maps fritzing connector keys to (x, y) coordinates
        self.points = {} # (index, connid) -> (x, y)

        # This maps fritzing component indices to ComponentInstances
        self.component_instances = {} # index -> ComponentInstance

        # Map connector keys to the list of connector keys they
        # are connected to.
        self.connects = {} # (index, connid) -> [(index, connid)]

        self.components = {} # idref -> ComponentParser

        self.fritzing_version = None
        self.fzz_zipfile = None # The ZipFile if we are parsing an fzz
开发者ID:iparshin,项目名称:schematic-file-converter,代码行数:17,代码来源:fritzing.py


示例12: parse

    def parse(self, filename, library_filename=None):
        """ Parse a kicad file into a design """

        design = Design()
        segments = set() # each wire segment
        junctions = set() # wire junction point (connects all wires under it)

        if library_filename is None:
            library_filename = splitext(filename)[0] + '-cache.lib'
            if exists(library_filename):
                for cpt in parse_library(library_filename):
                    design.add_component(cpt.name, cpt)

        with open(filename) as f:
            libs = []
            line = f.readline().strip()

            # parse the library references
            while line and line != "$EndDescr":
                if line.startswith('LIBS:'):
                    libs.extend(line.split(':', 1)[1].split(','))
                line = f.readline().strip()

            # Now parse wires and components, ignore connections, we get
            # connectivity from wire segments

            line = f.readline()

            while line:
                prefix = line.split()[0]

                if line.startswith('Wire Wire Line'):
                    self.parse_wire(f, segments)
                elif prefix == "Connection": # Store these to apply later
                    self.parse_connection(line, junctions)
                elif prefix == "Text":
                    design.design_attributes.add_annotation(
                        self.parse_text(f, line))
                elif prefix == "$Comp": # Component Instance
                    inst = self.parse_component_instance(f)
                    design.add_component_instance(inst)
                    if inst.library_id not in design.components.components:
                        cpt = lookup_part(inst.library_id, libs)
                        if cpt is not None:
                            design.components.add_component(cpt.name, cpt)

                line = f.readline()

        segments = self.divide(segments, junctions)
        design.nets = self.calc_nets(segments)
        self.calc_connected_components(design)

        return design
开发者ID:ncsaba,项目名称:schematic-file-converter,代码行数:53,代码来源:kicad.py


示例13: parse_schematic

    def parse_schematic(self, stream):
        """ Parse a gEDA schematic provided as a *stream* object into a
            design.

            Returns the design corresponding to the schematic.
        """
        # pylint: disable=R0912
        if self.design is None:
            self.design = Design()

        self.segments = set()
        self.net_points = dict()
        self.net_names = dict()

        obj_type, params = self._parse_command(stream)

        while obj_type is not None:

            objects = getattr(self, "_parse_%s" % obj_type)(stream, params)

            attributes = self._parse_environment(stream)
            self.design.design_attributes.attributes.update(attributes or {})

            self.add_objects_to_design(self.design, objects)

            obj_type, params = self._parse_command(stream)

        ## process net segments into nets & net points and add to design
        self.divide_segments()

        calculated_nets = self.calculate_nets()

        for cnet in sorted(calculated_nets, key=lambda n : n.net_id):
            self.design.add_net(cnet)

        return self.design
开发者ID:ncsaba,项目名称:schematic-file-converter,代码行数:36,代码来源:geda.py


示例14: DesignTests

class DesignTests(unittest.TestCase):
    """ The tests of the core module design feature """

    def setUp(self):
        """ Setup the test case. """
        self.des = Design()

    def tearDown(self):
        """ Teardown the test case. """
        pass

    def test_create_new_design(self):
        """ Test the creation of a new empty design. """
        self.assertEqual(len(self.des.nets), 0)

    def test_empty_bounds(self):
        '''bounds() on an empty design is to include just the origin'''
        for point in self.des.bounds():
            self.assertEqual(point.x, 0)
            self.assertEqual(point.y, 0)

    def test_bounds_nets(self):
        '''Test bounds() with just the design's nets'''
        leftnet = Net('foo1')
        topnet = Net('foo2')
        rightnet = Net('foo3')
        botnet = Net('foo4')
        # limits minx=2, miny=1, maxx=7, maxy=9
        mkbounds(leftnet, 2, 3, 3, 3)
        mkbounds(topnet, 3, 1, 3, 3)
        mkbounds(rightnet, 3, 3, 7, 3)
        mkbounds(botnet, 3, 3, 3, 9)
        self.des.add_net(topnet)
        self.des.add_net(rightnet)
        self.des.add_net(leftnet)
        self.des.add_net(botnet)

        top_left, btm_right = self.des.bounds()
        self.assertEqual(top_left.x, 2)
        self.assertEqual(top_left.y, 1)
        self.assertEqual(btm_right.x, 7)
        self.assertEqual(btm_right.y, 9)

    def test_bounds_annots(self):
        '''Test bounds() with just Annotations added as design attributes'''
        left = Annotation('foo1', 3, 3, 0, True)
        top = Annotation('foo2', 3, 3, 0, True)
        right = Annotation('foo3', 3, 3, 0, True)
        bot = Annotation('foo4', 3, 3, 0, True)
        mkbounds(left, 2, 3, 3, 3)
        mkbounds(top, 3, 2, 3, 3)
        mkbounds(right, 3, 3, 5, 3)
        mkbounds(bot, 3, 3, 3, 6)
        for anno in (left, right, bot, top):
            self.des.design_attributes.add_annotation(anno)

        top_left, btm_right = self.des.bounds()
        self.assertEqual(top_left.x, 2)
        self.assertEqual(top_left.y, 2)
        self.assertEqual(btm_right.x, 5)
        self.assertEqual(btm_right.y, 6)

    def test_bounds_parts(self):
        '''test bounds() with just components in the design'''
        libcomp = Component('bar')
        libcomp.add_symbol(Symbol())
        libcomp.symbols[0].add_body(Body())
        mkbounds(libcomp.symbols[0].bodies[0], 0, 0, 10, 10)
        self.des.add_component('foo', libcomp)
        for (x, y) in ((1, 3), (3, 2), (5, 3), (3, 7)):
            compinst = ComponentInstance(str((x, y)), 'foo', 0)
            compinst.add_symbol_attribute(SymbolAttribute(x, y, 0, False))
            self.des.add_component_instance(compinst)

        top_left, btm_right = self.des.bounds()
        self.assertEqual(top_left.x, 1)
        self.assertEqual(top_left.y, 2)
        self.assertEqual(btm_right.x, 15)
        self.assertEqual(btm_right.y, 17)

    def test_bounds_neg_coords(self):
        '''Test bounds() when the schematic is all negative coordinates'''
        net = Net('foo')
        mkbounds(net, -1, -2, -3, -4)
        self.des.add_net(net)

        top_left, btm_right = self.des.bounds()
        self.assertEqual(top_left.x, -3)
        self.assertEqual(top_left.y, -4)
        self.assertEqual(btm_right.x, -1)
        self.assertEqual(btm_right.y, -2)

    def test_bounds_all_elts(self):
        '''bounds() with all the elements competing'''
        net = Net('foo')
        mkbounds(net, 3, 3, -1, -2)
        self.des.add_net(net)

        annot = Annotation('foo', 3, 3, 0, True)
        mkbounds(annot, 3, 3, 3, 5)
#.........这里部分代码省略.........
开发者ID:ncsaba,项目名称:schematic-file-converter,代码行数:101,代码来源:design_t.py


示例15: __init__


#.........这里部分代码省略.........
            confidence += 0.25
        if 'netname=' in data:
            confidence += 0.25
        return confidence

    def set_offset(self, point):
        """ Set the offset point for the gEDA output. As OpenJSON
            positions the origin in the center of the viewport and
            gEDA usually uses (40'000, 40'000) as page origin, this
            allows for translating from one coordinate system to
            another. It expects a *point* object providing a *x* and
            *y* attribute.
        """
        ## create an offset of 5 grid squares from origin (0,0)
        self.offset.x = point.x
        self.offset.y = point.y

    def parse(self, inputfile):
        """ Parse a gEDA file into a design.

            Returns the design corresponding to the gEDA file.
        """
        inputfiles = []

        ## check if inputfile is in ZIP format
        if zipfile.is_zipfile(inputfile):
            self.geda_zip = zipfile.ZipFile(inputfile)
            for filename in self.geda_zip.namelist():
                if filename.endswith('.sch'):
                    inputfiles.append(filename)
        else:
            inputfiles = [inputfile]

        self.design = Design()

        ## parse frame data of first schematic to extract
        ## page size (assumes same frame for all files)
        with self._open_file_or_zip(inputfiles[0]) as stream:
            self._check_version(stream)

            for line in stream.readlines():
                if 'title' in line and line.startswith('C'):
                    obj_type, params = self._parse_command(StringIO(line))
                    assert(obj_type == 'C')

                    params['basename'], _ = os.path.splitext(
                        params['basename'],
                    )

                    log.debug("using title file: %s", params['basename'])

                    self._parse_title_frame(params)

        ## store offset values in design attributes
        self.design.design_attributes.attributes.update({
            '_geda_offset_x': str(self.offset.x),
            '_geda_offset_y': str(self.offset.y),
            '_geda_frame_width': str(self.frame_width),
            '_geda_frame_height': str(self.frame_height),
        })

        for filename in inputfiles:
            f_in = self._open_file_or_zip(filename)
            self._check_version(f_in)

            self.parse_schematic(f_in)
开发者ID:ncsaba,项目名称:schematic-file-converter,代码行数:67,代码来源:geda.py


示例16: __init__

    def __init__(self):
        self.design = Design()

        # map components to gate names to symbol indices
        self.cpt2gate2symbol_index = defaultdict(dict)
开发者ID:aivarsk,项目名称:schematic-file-converter,代码行数:5,代码来源:__init__.py


示例17: test_layers

 def test_layers(self):
     """ Capture absence of layers. """
     design = Design()
     design.layout = Layout()
     writer = Writer()
     writer.write(design)
开发者ID:evilnick,项目名称:schematic-file-converter,代码行数:6,代码来源:gerber_t.py


示例18: JSON

class JSON(object):
    """ The Open JSON Format Parser
    This is mostly for sanity checks, it reads in the Open JSON format,
    and then outputs it. """

    def __init__(self):
        self.design = Design()


    @staticmethod
    def auto_detect(filename):
        """ Return our confidence that the given file is an openjson file """
        with open(filename, 'r') as f:
            data = f.read()
        confidence = 0
        if 'component_instances' in data:
            confidence += 0.3
        if 'design_attributes' in data:
            confidence += 0.6
        return confidence


    def parse(self, filename):
        """ Parse the openjson file into the core. """
        log.debug('Starting parse of %s', filename)
        with open(filename) as f:
            read = json.loads(f.read())

        self.parse_components(read.get('components'))
        self.parse_component_instances(read.get('component_instances'))
        if read.get('shapes') is not None:
            self.parse_sch_shapes(read.get('shapes'))
        self.parse_design_attributes(read.get('design_attributes'))
        self.parse_nets(read.get('nets'))
        self.parse_version(read.get('version'))

        # layout aspects
        self.parse_layer_options(read.get('layer_options'))
        self.parse_trace_segments(read.get('trace_segments'))
        self.parse_layout_objects(read.get('gen_objs'))
        self.parse_paths(read.get('paths'))
        self.parse_pours(read.get('pours'))
        self.parse_pcb_text(read.get('text'))

        return self.design


    def parse_version(self, version):
        """ Extract the file version. """
        file_version = version.get('file_version')
        exporter = version.get('exporter')
        self.design.set_version(file_version, exporter)


    def parse_layer_options(self, layer_options_json):
        if layer_options_json is None:
            return None

        for layer_option_json in layer_options_json:
            self.design.layer_options.append(Layer(layer_option_json['name']))


    def parse_trace_segments(self, segments_json):
        if segments_json is None:
            return None

        for segment_json in segments_json:
            p1 = Point(segment_json['p1']['x'], segment_json['p1']['y'])
            p2 = Point(segment_json['p2']['x'], segment_json['p2']['y'])
            segment = Segment(segment_json['layer'], p1, p2, segment_json['width'])
            self.design.trace_segments.append(segment)


    def parse_paths(self, paths_json):
        if paths_json is None:
            return None

        for path_json in paths_json:
            points = [Point(point_json['x'], point_json['y']) for point_json in path_json['points']]
            width = path_json['width']
            is_closed = path_json['is_closed']
            layer = path_json['layer']
            path = Path(layer, points, width, is_closed)
            self.design.paths.append(path)


    def parse_pours(self, pours_json):
        if pours_json is None:
            return None

        for pour_json in pours_json:
            points = [Point(point_json['x'], point_json['y']) for point_json in pour_json['points']]

            layer = pour_json['layer']
            subtractive_shapes = [];
            if 'subtractive_shapes' in pour_json:
                subtractive_shapes = [self.parse_shape(shape_json) for shape_json in pour_json['subtractive_shapes']]
            if 'readded_shapes' in pour_json:
                readded_shapes = [self.parse_shape(shape_json) for shape_json in pour_json['readded_shapes']]

#.........这里部分代码省略.........
开发者ID:jsharf,项目名称:schematic-file-converter,代码行数:101,代码来源:openjson.py


示例19: __init__

class JSON:
    """ The Open JSON Format Parser
    This is mostly for sanity checks, it reads in the Open JSON format,
    and then outputs it. """

    def __init__(self):
        self.design = Design()


    @staticmethod
    def auto_detect(filename):
        """ Return our confidence that the given file is an openjson file """
        with open(filename, 'r') as f:
            data = f.read()
        confidence = 0
        if 'component_instances' in data:
            confidence += 0.3
        if 'design_attributes' in data:
            confidence += 0.6
        return confidence


    def parse(self, filename):
        """ Parse the openjson file into the core. """
        with open(filename) as f:
            read = json.loads(f.read())

        self.parse_component_instances(read.get('component_instances'))
        self.parse_components(read.get('components'))
        if read.get('shapes') is not None:
            self.parse_sch_shapes(read.get('shapes'))
        self.parse_design_attributes(read.get('design_attributes'))
        self.parse_nets(read.get('nets'))
        self.parse_version(read.get('version'))

        return self.design


    def parse_version(self, version):
        """ Extract the file version. """
        file_version = version.get('file_version')
        exporter = version.get('exporter')
        self.design.set_version(file_version, exporter)


    def parse_component_instances(self, component_instances):
        """ Extract the component instances. """
        for instance in component_instances:
            # Get instance_id, library_id and symbol_index
            instance_id = instance.get('instance_id')
            library_id = instance.get('library_id')
            symbol_index = int(instance.get('symbol_index'))
            # Make the ComponentInstance()
            inst = ComponentInstance(instance_id, library_id, symbol_index)

            # Get the SymbolAttributes
            for symbol_attribute in instance.get('symbol_attributes'):
                attr = self.parse_symbol_attribute(symbol_attribute)
                inst.add_symbol_attribute(attr)

            # Get the Attributes
            for key, value in instance.get('attributes').items():
                inst.add_attribute(key, value)

            # Add the ComponentInstance
            self.design.add_component_instance(inst)


    def parse_symbol_attribute(self, symbol_attribute):
        """ Extract attributes from a symbol. """
        x = int(symbol_attribute.get('x') or 0)
        y = int(symbol_attribute.get('y') or 0)

        rotation = float(symbol_attribute.get('rotation'))

        # Make SymbolAttribute
        symbol_attr = SymbolAttribute(x, y, rotation)

        # Add Annotations
        for annotation in symbol_attribute.get('annotations'):
            anno = self.parse_annotation(annotation)
            symbol_attr.add_annotation(anno)

        # Return SymbolAttribute to be added to it's ComponentInstance
        return symbol_attr


    def parse_annotation(self, annotation):
        """ Extract an annotation. """
        value = annotation.get('value')
        x = int(annotation.get('x'))
        y = int(annotation.get('y'))
        rotation = float(annotation.get('rotation'))
        visible = annotation.get('visible')
        if visible is not None and visible.lower() == 'false':
            visible = 'false'
        else:
            visible = 'true'
        return Annotation(value, x, y, rotation, visible)

#.........这里部分代码省略.........
开发者ID:aivarsk,项目名称:schematic-file-converter,代码行数:101,代码来源:openjson.py


示例20: Fritzing

class Fritzing(object):
    """ The Fritzing Format Parser

    Connection points in a fritzing file are identified by a 'module
    index' which references a component instance or a wire, and a
    'connector id' which references a specific pin. Together the
    (index, connid) tuple uniquely identifies a connection point.
    """

    def __init__(self):
        self.design = Design()
        self.body = None

        # This maps fritzing connector keys to (x, y) coordinates
        self.connkey2xy = {} # (index, connid) -> (x, y)

        # This maps fritzing component indices to ComponentInstances
        self.component_instances = {} # index -> ComponentInstance

        # Map connector keys to the list of connector keys they
        # are connected to.
        self.connects = {} # (index, connid) -> [(index, connid)]

        self.components = {} # idref -> ComponentParser

        self.fritzing_version = None
        self.fzz_zipfile = None # The ZipFile if we are parsing an fzz


    @staticmethod
    def auto_detect(filename):
        """ Return our confidence that the given file is an fritzing file """
        with open(filename, 'r') as f:
            data = f.read(4096)
        confidence = 0
        if 'fritzingVersion' in data:
            confidence += 0.9
        elif filename.endswith('.fzz'):
            confidence += 0.9
        if confidence == 0 and zipfile.is_zipfile(filename):
            zip_file = zipfile.ZipFile(filename)
            for name in zip_file.namelist():
                if name.endswith('.fz'):
                    confidence += 0.9
                    break
            zip_file.close()
        return confidence


    def parse(self, filename):
        """ Parse a Fritzing file into a design """

        tree = self.make_tree(filename)

        self.fritzing_version = tree.getroot().get('fritzingVersion', '0')

        for element in tree.findall('instances/instance'):
            self.parse_instance(element)

        for idref, cpt_parser in self.components.iteritems():
            self.design.add_component(idref, cpt_parser.component)

        for cptinst in self.component_instances.itervalues():
            self.design.add_component_instance(cptinst)

        for net in self.build_nets():
            self.design.add_net(net)

        return self.design


    def make_tree(self, filename):
        """
        Return an ElementTree for the given file name.
        """

        if zipfile.is_zipfile(filename):
            self.fzz_zipfile = zipfile.ZipFile(filename)
            fz_name = [name for name in self.fzz_zipfile.namelist()
                       if name.endswith('.fz')][0]
            fz_file = self.fzz_zipfile.open(fz_name)
        else:
            fz_file = filename

        return ElementTree(file=fz_file)

    def parse_instance(self, instance):
        """ Parse a Fritzing instance block """

        if instance.get('moduleIdRef') == 'WireModuleID':
            self.parse_wire(instance)
        else:
            self.parse_component_instance(instance)


    def parse_wire(self, inst):
        """ Parse a Fritzing wire instance """

        view = inst.find('views/schematicView')

#.........这里部分代码省略.........
开发者ID:EasyPCB,项目名称:schematic-file-converter,代码行数:101,代码来源:fritzing.py



注:本文中的upconvert.core.design.Design类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python kicad.KiCAD类代码示例发布时间:2022-05-27
下一篇:
Python components.Component类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap