Load PDB file from rcsb.org.
359592
def _fetch_pdb(pdb_code):
        """"""
        txt = None
        url = 'http://www.rcsb.org/pdb/files/%s.pdb' % pdb_code.lower()
        try:
            response = urlopen(url)
            txt = response.read()
            if sys.version_info[0] >= 3:
                txt = txt.decode('utf-8')
            else:
                txt = txt.encode('ascii')
        except HTTPError as e:
            print('HTTP Error %s' % e.code)
        except URLError as e:
            print('URL Error %s' % e.args)
        return url, txt
1100015
def _read_pdb(path):
        """"""
        r_mode = 'r'
        openf = open
        if path.endswith('.gz'):
            r_mode = 'rb'
            openf = gzip.open
        with openf(path, r_mode) as f:
            txt = f.read()
        if path.endswith('.gz'):
            if sys.version_info[0] >= 3:
                txt = txt.decode('utf-8')
            else:
                txt = txt.encode('ascii')
        return path, txt
930537
def load_source(self):
    """"""
    if self.filename in self.STDIN_NAMES:
      self.filename = 'stdin'
      self.source = pycodestyle.stdin_get_value()
    else:
      with pep257.tokenize_open(self.filename) as fd:
        self.source = fd.read()
1337964
def pdb(self):
        """"""
        header_title = '{:<80}\n'.format('HEADER    {}'.format(self.id))
        data_type = '{:<80}\n'.format('EXPDTA    ISAMBARD Model')
        pdb_strs = []
        for ampal in self:
            if isinstance(ampal, Assembly):
                pdb_str = ampal.make_pdb(header=False, footer=False)
            else:
                pdb_str = ampal.make_pdb()
            pdb_strs.append(pdb_str)
        merged_strs = 'ENDMDL\n'.join(pdb_strs) + 'ENDMDL\n'
        merged_pdb = ''.join([header_title, data_type, merged_strs])
        return merged_pdb
674175
def load_mib(filenames):
    """"""
    the_mib = {'iso': ['1']}
    unresolved = {}
    for k in six.iterkeys(conf.mib):
        _mib_register(conf.mib[k], k.split("."), the_mib, unresolved)

    if isinstance(filenames, (str, bytes)):
        filenames = [filenames]
    for fnames in filenames:
        for fname in glob(fnames):
            f = open(fname)
            text = f.read()
            cleantext = " ".join(_mib_re_strings.split(" ".join(_mib_re_comments.split(text))))  # noqa: E501
            for m in _mib_re_oiddecl.finditer(cleantext):
                gr = m.groups()
                ident, oid = gr[0], gr[-1]
                ident = fixname(ident)
                oid = oid.split()
                for i, elt in enumerate(oid):
                    m = _mib_re_both.match(elt)
                    if m:
                        oid[i] = m.groups()[1]
                _mib_register(ident, oid, the_mib, unresolved)

    newmib = MIBDict(_name="MIB")
    for oid, key in six.iteritems(the_mib):
        newmib[".".join(key)] = oid
    for oid, key in six.iteritems(unresolved):
        newmib[".".join(key)] = oid

    conf.mib = newmib
1009705
def load_output(self, args, kwargs):
        """"""
        return db.find(self.get_output_key(args, kwargs))
233608
def write_pdb(self, mol, filename, name=None, num=None):
        

        # ugly hack to get around the openbabel issues with inconsistent
        # residue labelling.
        scratch = tempfile.gettempdir()
        with ScratchDir(scratch, copy_to_current_on_exit=False) as _:
            mol.to(fmt="pdb", filename="tmp.pdb")
            bma = BabelMolAdaptor.from_file("tmp.pdb", "pdb")

        num = num or 1
        name = name or "ml{}".format(num)

        # bma = BabelMolAdaptor(mol)
        pbm = pb.Molecule(bma._obmol)
        for i, x in enumerate(pbm.residues):
            x.OBResidue.SetName(name)
            x.OBResidue.SetNum(num)

        pbm.write(format="pdb", filename=filename, overwrite=True)
323517
def load_protocols(filename, _integer_base=10):
    """""""
    spaces = re.compile(b"[ \t]+|\n")
    dct = DADict(_name=filename)
    try:
        with open(filename, "rb") as fdesc:
            for line in fdesc:
                try:
                    shrp = line.find(b"#")
                    if shrp >= 0:
                        line = line[:shrp]
                    line = line.strip()
                    if not line:
                        continue
                    lt = tuple(re.split(spaces, line))
                    if len(lt) < 2 or not lt[0]:
                        continue
                    dct[lt[0]] = int(lt[1], _integer_base)
                except Exception as e:
                    log_loading.info(
                        "Couldn't parse file [%s]: line [%r] (%s)",
                        filename,
                        line,
                        e,
                    )
    except IOError:
        log_loading.info("Can't open %s file", filename)
    return dct
720855
def current_codes_from_pdb():
    
    url = 'http://www.rcsb.org/pdb/rest/getCurrent'
    r = requests.get(url)
    if r.status_code == 200:
        pdb_codes = [x.lower() for x in r.text.split('"') if len(x) == 4]
    else:
        print('Request for {0} failed with status code {1}'.format(url, r.status_code))
        return
    return pdb_codes
76312
def retrieve(cls, pdb_id, cache_dir = None):
        ''''''

        # Check to see whether we have a cached copy
        pdb_id = pdb_id.upper()
        if cache_dir:
            filename = os.path.join(cache_dir, "%s.pdb" % pdb_id)
            if os.path.exists(filename):
                return cls(read_file(filename))

        # Get a copy from the RCSB
        contents = rcsb.retrieve_pdb(pdb_id)

        # Create a cached copy if appropriate
        if cache_dir:
            write_file(os.path.join(cache_dir, "%s.pdb" % pdb_id), contents)

        # Return the object
        return cls(contents)
756322
def retrieve(pdb_id, cache_dir = None, bio_cache = None):
        ''''''

        pdb_id = pdb_id.upper()

        if bio_cache:
            return FASTA(bio_cache.get_fasta_contents(pdb_id))

        # Check to see whether we have a cached copy
        if cache_dir:
            filename = os.path.join(cache_dir, "%s.fasta" % pdb_id)
            if os.path.exists(filename):
                return FASTA(read_file(filename))
            else:
                filename += ".txt"
                if os.path.exists(filename):
                    return FASTA(read_file(filename))

        # Get a copy from the RCSB
        contents = rcsb.retrieve_fasta(pdb_id)

        # Create a cached copy if appropriate
        if cache_dir:
            write_file(os.path.join(cache_dir, "%s.fasta" % pdb_id), contents)

        # Return the object
        return FASTA(contents)
1186499
def _load(self):
        """'"""
        # loop over system path
        if self._loaded:
            return
        icon_paths = ['/usr/local/share/meqtrees'] + sys.path
        for path in icon_paths:
            path = path or '.'
            # for each entry, try <entry>/icons/<appname>'
            for a, b in [('icons', self._appname), (self._appname, 'icons')]:
                trydir = os.path.join(path, a, b)
                _dprint(3, 'trying icon path', trydir)
                try:
                    files = os.listdir(trydir)
                except:
                    continue
                _dprint(3, len(files), 'entries in', trydir)
                # loop over all files
                nicons = 0
                for f in files:
                    (name, ext) = os.path.splitext(f);  # check extension
                    if ext in ('.png', '.xpm', '.gif'):
                        f = os.path.join(trydir, f)
                        try:
                            pm = QPixmap(f)
                        except:
                            _dprint(3, 'error loading icon', name, sys.exc_value())
                            continue
                        # register pixmap
                        self._pixmaps[name] = QPixmapWrapper(pm)
                        nicons += 1
                        _dprint(4, 'loaded icon', f)
                    else:
                        _dprint(4, 'ignoring entry', f)
                _dprint(1, nicons, 'icons loaded from ', trydir)
                self._loaded = True
444911
def _pdb_frame(self):
        """"""
        if self._pdb_obj is not None and self._pdb_obj.curframe is not None:
            return self._pdb_obj.curframe
638946
def load_rc_file():
    
    # If an rc file is named in the config, use it.
    # Otherwise, fall back to looking in the HOME directory.
    # The fall back won't work under RPi because HOME will be root.
    if "uDMXrc" in config:
        rcfile = config["uDMXrc"]
    else:
        if os.name == "nt":
            # Windows
            rcfile = os.path.join(os.environ["USERPROFILE"], ".uDMXrc")
        else:
            # Mostly *nix type systems
            rcfile = os.path.join(os.environ["HOME"], ".uDMXrc")
    try:
        cf = open(rcfile, 'r')
        for line in cf:
            tokens = line.split()

            # Blank line
            if len(tokens) == 0:
                continue

            # A comment
            if tokens[0] == '#':
                continue
            # A channel alias
            elif tokens[0] == 'channel':
                # channel alias value
                if len(tokens) >= 3:
                    if is_valid_channel(tokens[2]):
                        add_channel(tokens[1], tokens[2])
                    else:
                        print(line)
                        print("Invalid channel value")
                else:
                    print(line)
                    print("Invalid channel statement")
            # A DMX value or values
            elif tokens[0] in ['value', 'values']:
                # value alias value
                if len(tokens) >= 3:
                    if are_valid_values(tokens[2:]):
                        add_values(tokens[1], tokens[2:])
                    else:
                        print(line)
                        print("Invalid value(s)")
                else:
                    print(line)
                    print("Invalid value statement")
            # Something we don't recognize
            else:
                print(line)
                print(tokens[0], "is not a recognized resource file statement")
        cf.close()
    except:
        print("Unable to open resource file", rcfile)
1316679
def load(self):
        """"""

        for drpins in self.iload(self.entry):
            self.drps[drpins.name] = drpins

        return self
54891
def load_stubs(self, log_mem=False):
        
        # Initialize parameter related to diagnostic output of memory usage
        if log_mem:
            import psutil
            process = psutil.Process(os.getpid())
            rss = process.memory_info().rss
            LOG_MEMORY_INT = 1000
            MEMORY_LIMIT = 1000.0

        def _add_stub_manually(_fname):
            """Create and add a 'stub' by manually loading parameters from
            JSON files.

            Previously this was done by creating a full `Entry` instance, then
            using the `Entry.get_stub()` method to trim it down.  This was very
            slow and memory intensive, hence this improved approach.
            """
            # FIX: should this be ``fi.endswith(``.gz')`` ?
            fname = uncompress_gz(_fname) if '.gz' in _fname else _fname

            stub = None
            stub_name = None
            with codecs.open(fname, 'r') as jfil:
                # Load the full JSON file
                data = json.load(jfil, object_pairs_hook=OrderedDict)
                # Extract the top-level keys (should just be the name of the
                # entry)
                stub_name = list(data.keys())
                # Make sure there is only a single top-level entry
                if len(stub_name) != 1:
                    err = "json file '{}' has multiple keys: {}".format(
                        fname, list(stub_name))
                    self._log.error(err)
                    raise ValueError(err)
                stub_name = stub_name[0]

                # Make sure a non-stub entry doesnt already exist with this
                # name
                if stub_name in self.entries and not self.entries[
                        stub_name]._stub:
                    err_str = (
                        "ERROR: non-stub entry already exists with name '{}'"
                        .format(stub_name))
                    self.log.error(err_str)
                    raise RuntimeError(err_str)

                # Remove the outmost dict level
                data = data[stub_name]
                # Create a new `Entry` (subclass) instance
                proto = self.proto
                stub = proto(catalog=self, name=stub_name, stub=True)
                # Add stub parameters if they are available
                if proto._KEYS.ALIAS in data:
                    stub[proto._KEYS.ALIAS] = data[proto._KEYS.ALIAS]
                if proto._KEYS.DISTINCT_FROM in data:
                    stub[proto._KEYS.DISTINCT_FROM] = data[
                        proto._KEYS.DISTINCT_FROM]
                if proto._KEYS.RA in data:
                    stub[proto._KEYS.RA] = data[proto._KEYS.RA]
                if proto._KEYS.DEC in data:
                    stub[proto._KEYS.DEC] = data[proto._KEYS.DEC]
                if proto._KEYS.DISCOVER_DATE in data:
                    stub[proto._KEYS.DISCOVER_DATE] = data[
                        proto._KEYS.DISCOVER_DATE]
                if proto._KEYS.SOURCES in data:
                    stub[proto._KEYS.SOURCES] = data[
                        proto._KEYS.SOURCES]

            # Store the stub
            self.entries[stub_name] = stub
            self.log.debug("Added stub for '{}'".format(stub_name))

        currenttask = 'Loading entry stubs'
        files = self.PATHS.get_repo_output_file_list()
        for ii, _fname in enumerate(pbar(files, currenttask)):
            # Run normally
            # _add_stub(_fname)

            # Run 'manually' (extract stub parameters directly from JSON)
            _add_stub_manually(_fname)

            if log_mem:
                rss = process.memory_info().rss / 1024 / 1024
                if ii % LOG_MEMORY_INT == 0 or rss > MEMORY_LIMIT:
                    log_memory(self.log, "\nLoaded stub {}".format(ii),
                               logging.INFO)
                    if rss > MEMORY_LIMIT:
                        err = (
                            "Memory usage {}, has exceeded {} on file {} '{}'".
                            format(rss, MEMORY_LIMIT, ii, _fname))
                        self.log.error(err)
                        raise RuntimeError(err)

        return self.entries
972463
def retrieve_xml(pdb_id, silent = True):
    ''''''
    xml_gz = retrieve_file_from_RCSB(get_rcsb_files_connection(), "/download/%s.xml.gz" % pdb_id, silent = silent)
    cf = StringIO.StringIO()
    cf.write(xml_gz)
    cf.seek(0)
    df = gzip.GzipFile(fileobj = cf, mode='rb')
    contents = df.read()
    df.close()
    return contents