Create a cube object by loading data from a file.

           *Arguemnts:*

           filename
                The file to load. It must contain the header with the
                description of the grid and the molecule.
975980
def from_file(cls, filename):
        '''
        '''
        with open(filename) as f:
            molecule, origin, axes, nrep, subtitle, nuclear_charges = \
                read_cube_header(f)
            data = np.zeros(tuple(nrep), float)
            tmp = data.ravel()
            counter = 0
            while True:
                line = f.readline()
                if len(line) == 0:
                    break
                words = line.split()
                for word in words:
                    tmp[counter] = float(word)
                    counter += 1
        return cls(molecule, origin, axes, nrep, data, subtitle, nuclear_charges)
971503
def from_file(self, file_name=None):
        """"""

        file_name = self._check_file_name(file_name)

        with open(file_name, 'r') as infile:
            top_level_dict = json.load(infile)

        pages_dict = top_level_dict['info_df']
        pages = pd.DataFrame(pages_dict)
        self.pages = pages
        self.file_name = file_name
        self._prm_packer(top_level_dict['metadata'])
        self.generate_folder_names()
        self.paginate()
939871
def load(filename, compressed=True, prealloc=None):
        
        # switch load based on file ext
        _, file_ext = os.path.splitext(filename)
        if compressed:
            if file_ext != COMPRESSED_TENSOR_EXT:
                raise ValueError('Can only load compressed tensor with %s extension' %(COMPRESSED_TENSOR_EXT))
            data = np.load(filename)['arr_0']
        else:
            if file_ext != TENSOR_EXT:
                raise ValueError('Can only load tensor with .npy extension')
            data = np.load(filename)
            
        # fill prealloc tensor
        if prealloc is not None:
            prealloc.reset()
            prealloc.add_batch(data)
            return prealloc
            
        # init new tensor
        tensor = Tensor(data.shape, data.dtype, data=data)
        return tensor
1059023
def cell(filename=None, mass=None, instrument=None, logging_mode="INFO",
         cycle_mode=None, auto_summary=True):
    """"""

    from cellpy import log

    log.setup_logging(default_level=logging_mode)
    cellpy_instance = setup_cellpy_instance()

    if instrument is not None:
        cellpy_instance.set_instrument(instrument=instrument)

    if cycle_mode is not None:
        cellpy_instance.cycle_mode = cycle_mode

    if filename is not None:
        filename = Path(filename)

        if filename.suffix in [".h5", ".hdf5", ".cellpy", ".cpy"]:
            logging.info(f"Loading cellpy-file: {filename}")
            cellpy_instance.load(filename)
        else:
            logging.info(f"Loading raw-file: {filename}")
            cellpy_instance.from_raw(filename)
            if mass is not None:
                logging.info("Setting mass")
                cellpy_instance.set_mass(mass)
            if auto_summary:
                logging.info("Creating step table")
                cellpy_instance.make_step_table()
                logging.info("Creating summary data")
                cellpy_instance.make_summary()

    logging.info("Created CellpyData object")
    return cellpy_instance
1294879
def save_voxel_grid(voxel_grid, file_name):
    
    try:
        with open(file_name, 'wb') as fp:
            for voxel in voxel_grid:
                fp.write(struct.pack("<I", voxel))
    except IOError as e:
        print("An error occurred: {}".format(e.args[-1]))
        raise e
    except Exception:
        raise
366659
def create(cls, h:int, w:int, bboxes:Collection[Collection[int]], labels:Collection=None, classes:dict=None,
               pad_idx:int=0, scale:bool=True)->'ImageBBox':
        ""
        if isinstance(bboxes, np.ndarray) and bboxes.dtype == np.object: bboxes = np.array([bb for bb in bboxes])
        bboxes = tensor(bboxes).float()
        tr_corners = torch.cat([bboxes[:,0][:,None], bboxes[:,3][:,None]], 1)
        bl_corners = bboxes[:,1:3].flip(1)
        bboxes = torch.cat([bboxes[:,:2], tr_corners, bl_corners, bboxes[:,2:]], 1)
        flow = FlowField((h,w), bboxes.view(-1,2))
        return cls(flow, labels=labels, classes=classes, pad_idx=pad_idx, y_first=True, scale=scale)
138887
def load_file(self, file_obj, verbose):
        
        if verbose: printDebug("----------")
        if verbose: printDebug("Reading: <%s> ...'" % file_obj.name)

        if type(file_obj) == file:
            self.rdfgraph = self.rdfgraph + file_obj
            self.sources_valid += [file_obj.NAME]
        else:
            self.loading_failed(self.rdf_format_opts)
            self.sources_invalid += [file_obj.NAME]
588880
def _openFile(self):
        
        if self.filename is not None:
            self.h5 = h5py.File(self.filename)
        else:
            return

        if 'bp' not in self.h5:
            self.h5.create_group('bp')

        if 'bps' not in self.h5:
            self.h5.create_group('bps')

        for bp_type in ['bp', 'bps']:
            for bp_num in self.data[bp_type]:

                # Create group in case if new hdf5 file is opened
                if bp_num not in self.h5[bp_type]:
                    self.h5[bp_type].create_group(bp_num)

                # Sync data if old file is opened
                for parameters in self.h5[bp_type][bp_num]:
                    self.data[bp_type][bp_num][parameters] = self.h5[bp_type][bp_num][parameters]

        if 'mask' in self.h5:
            self.mask = self.h5['mask'][:]

        if 'time' in self.h5:
            self.time = self.h5['time'][:]

        if 'num_bp' in self.h5.attrs:
            self.num_bp = self.h5.attrs['num_bp']
        else:
            self.h5.attrs['num_bp'] = self.num_bp

        if 'num_step' in self.h5.attrs:
            self.num_step = self.h5.attrs['num_step']
        else:
            self.h5.attrs['num_step'] = self.num_step

        if 'startBP' in self.h5.attrs:
            self.startBP = self.h5.attrs['startBP']
        else:
            self.h5.attrs['startBP'] = self.startBP
312100
def load(fname: str) -> 'ParallelDataSet':
        
        data = mx.nd.load(fname)
        n = len(data) // 3
        source = data[:n]
        target = data[n:2 * n]
        label = data[2 * n:]
        assert len(source) == len(target) == len(label)
        return ParallelDataSet(source, target, label)
1003998
def load_data(self, filename):
        
        with zopen(filename, "rt") as f:
            self._data = json.load(f, cls=MontyDecoder)
229441
def create_append(filename: str, layers: Union[np.ndarray, Dict[str, np.ndarray], loompy.LayerManager], row_attrs: Dict[str, np.ndarray], col_attrs: Dict[str, np.ndarray], *, file_attrs: Dict[str, str] = None, fill_values: Dict[str, np.ndarray] = None) -> None:
	
	deprecated("'create_append' is deprecated. See https://github.com/linnarsson-lab/loompy/issues/42")
	if os.path.exists(filename):
		with connect(filename) as ds:
			ds.add_columns(layers, col_attrs, fill_values=fill_values)
	else:
		create(filename, layers, row_attrs, col_attrs, file_attrs=file_attrs)
596519
def new_from_file(self, filename: str, header_data: Optional[Header] = None,
                      mask_data: Optional[np.ndarray] = None):
        """"""
789330
def createFromFileName(cls, fileName):
        
        # See https://julien.danjou.info/blog/2013/guide-python-static-class-abstract-methods
        #logger.debug("Trying to create object of class: {!r}".format(cls))
        basename = os.path.basename(os.path.realpath(fileName)) # strips trailing slashes
        return cls(nodeName=basename, fileName=fileName)
235177
def polygon_load(filename):
    ''''''
    ret = []
    f = open(filename)
    for line in f:
        if line.startswith('#'):
            continue
        line = line.strip()
        if not line:
            continue
        a = line.split()
        if len(a) != 2:
            raise RuntimeError("invalid polygon line: %s" % line)
        ret.append((float(a[0]), float(a[1])))
    f.close()
    return ret
224342
def loadFile(self, fileName):
        

        # Assign QFile object with the current name.
        self.file = QtCore.QFile(fileName)
        if self.file.exists():
            self.qteText.append(open(fileName).read())
        else:
            msg = "File <b>{}</b> does not exist".format(self.qteAppletID())
            self.qteLogger.info(msg)
159141
def load_from_file_object(cls, fd, format=None):
        
        format = 'pickle' if format is None else format
        load = getattr(cls, "load_%s" % format, None)
        if load is None:
            raise ValueError("Unknown format '%s'." % format)
        return load(fd)
354994
def load(cls, filename, **kwargs):
        
        
        if not os.path.exists(filename):
            raise IOError("filename {0} does not exist" .format(filename))
        
        if filename.lower().endswith(".fits") \
        or filename.lower().endswith(".fits.gz"):
            image = fits.open(filename, **kwargs)
            
            header = image[0].header
            
            # Check for a tabular data structure
            if len(image) > 1 and image[0].data is None:

                names = [name.lower() for name in image[1].data.names]
                dispersion_key = 'wave' if 'wave' in names else 'disp'
                
                disp, flux = image[1].data[dispersion_key], image[1].data['flux']

                if 'error' in names or 'variance' in names:
                    variance_key = 'error' if 'error' in names else 'variance'
                    variance = image[1].data[variance_key]

            else:

                # According to http://iraf.net/irafdocs/specwcs.php ....
                #li = a.headers['LTM1_1'] * np.arange(a.headers['NAXIS1']) + a.headers['LTV1']
                #a.headers['CRVAL1'] + a.headers['CD1_1'] * (li - a.headers['CRPIX1'])

                if np.all([key in header.keys() for key in ('CDELT1', 'NAXIS1', 'CRVAL1')]):
                    disp = header['CRVAL1'] + (np.arange(header['NAXIS1']) \
                        - header.get("CRPIX1", 0)) * header['CDELT1']
            
                if "LTV1" in header.keys():
                    disp -= header['LTV1'] * header['CDELT1']

                #disp -= header['LTV1'] if header.has_key('LTV1') else 0
                flux = image[0].data

                # Check for an input_variance array
                extnames = [ext.header.get("EXTNAME", None) for ext in image[1:]]
                if "input_variance" in extnames:
                    index = 1 + extnames.index("input_variance")
                    variance = image[index].data
                    
                else:
                    variance = None
            
                # Check for logarithmic dispersion
                if "CTYPE1" in header.keys() and header["CTYPE1"] == "AWAV-LOG":
                    disp = np.exp(disp)

            # Add the headers in
            headers = {}
            for row in header.items():
                key, value = row
                
                # Check the value is valid
                try:
                    str(value)

                except TypeError:
                    logger.debug("Skipping header key {0}".format(key))
                    continue

                if len(key) == 0 or len(str(value)) == 0: continue
    
                if key in headers.keys():
                    if not isinstance(headers[key], list):
                        headers[key] = [headers[key]]
                    
                    headers[key].append(value)

                else:
                    headers[key] = value

            for key, value in headers.iteritems():
                if isinstance(value, list):
                    headers[key] = "\n".join(map(str, value))

        else:
            headers = {}
            try:
                disp, flux, variance = np.loadtxt(filename, unpack=True, **kwargs)
            except:
                disp, flux = np.loadtxt(filename, unpack=True, **kwargs)
            
        return cls(disp, flux, variance=variance, headers=headers)