Beispiel #1
0
def convert_notebook(
		nb_file: PathLike,
		outfile: PathLike,
		):
	"""
	Convert a notebook to a Python file.

	:param nb_file: Filename of the Jupyter Notebook to convert.
	:param outfile: The filename to store the Python output as.
	"""

	nb_file = PathPlus(nb_file)
	outfile = PathPlus(outfile)
	outfile.parent.maybe_make()

	script, *_ = py_exporter.from_file(str(nb_file))

	outfile.write_clean(script)

	with importlib_resources.path("notebook2script", "isort.cfg") as isort_config:
		with importlib_resources.path("notebook2script", "style.yapf") as yapf_style:
			reformat_file(outfile, yapf_style=str(yapf_style), isort_config_file=str(isort_config))

	linter.process_file(outfile)

	with open(outfile, "r+b") as f:
		fix_encoding_pragma(f, remove=True, expected_pragma=b"# coding: utf-8")
Beispiel #2
0
class CalibrationList(XMLList):
    """
	Represents a list of mass calibrations in :file:`DefaultMassCal.xml`.

	:param version: The version number of the calibration data.
	:param default_calibrations:
	"""
    def __init__(
        self,
        version: int,
        default_calibrations: Optional[Sequence[Calibration]] = None,
    ):
        super().__init__(int(version), default_calibrations)

    with importlib_resources.path(agilent_xsd,
                                  "DefaultMassCal.xsd") as schema_path:
        _schema = str(schema_path)
    _content_type = Calibration
    _content_xml_name = "DefaultCalibration"

    @classmethod
    def from_xml(
            cls,
            element: lxml.objectify.ObjectifiedElement) -> "CalibrationList":
        """
		Construct a :class:`~.CalibrationList` object from an XML element.

		:param element: The XML element to parse the data from
		"""

        class_ = cls(element.Version)
        class_._append_from_element(element.DefaultCalibrations)
        return class_
Beispiel #3
0
class DeviceList(XMLList):
    """
	Represents a list of devices in :file:`Devices.xml`.

	:param version:
	:param devices:
	"""
    def __init__(self,
                 version: int,
                 devices: Optional[Sequence[Device]] = None):
        super().__init__(version, devices)

    with importlib_resources.path(agilent_xsd, "Devices.xsd") as schema_path:
        _schema = str(schema_path)
    _content_type = Device
    _content_xml_name = "Device"

    @classmethod
    def from_xml(cls,
                 element: lxml.objectify.ObjectifiedElement) -> "DeviceList":
        """
		Construct a :class:`~.DeviceList` object from an XML element.

		:param element: The XML element to parse the data from.
		"""

        devices = cls(element.Version)
        devices._append_from_element(element)
        return devices
Beispiel #4
0
def resource(
		package: Union[str, ModuleType],
		resource: PathLike,
		) -> ContextManager[pathlib.Path]:
	"""
	Retrieve the path to a resource inside a package.

	.. versionadded:: $VERSION

	:param package: The name of the package, or a module object representing it.
	:param resource: The name of the resource.
	"""

	if sys.version_info < (3, 7) or sys.version_info >= (3, 11):
		return importlib_resources.as_file(importlib_resources.files(package) / os.fspath(resource))
	else:
		return importlib_resources.path(package, resource)
Beispiel #5
0
def extract() -> None:
	"""
	Extract the DLL files from the zip archive.
	"""

	dest_dir = PathPlus(pyms_agilent.mhdac.__file__).parent
	(dest_dir / "x64").maybe_make()
	(dest_dir / "x86").maybe_make()

	with tempfile.TemporaryDirectory() as tmpdir:
		src_dir = pathlib.Path(tmpdir)

		with importlib_resources.path(pyms_agilent.mhdac, "mhdac.zip") as zipfile:
			shutil.unpack_archive(str(zipfile), extract_dir=src_dir, format="zip")

		for filename in x64_filenames:
			(dest_dir / "x64" / filename).write_bytes((src_dir / "x64" / filename[::-1]).read_bytes()[::-1])
		for filename in x86_filenames:
			(dest_dir / "x86" / filename).write_bytes((src_dir / "x86" / filename[::-1]).read_bytes()[::-1])
Beispiel #6
0
class SampleInfo(XMLList):
    """
	List of information about the sample, parsed from :file:`sample_info.xml`.

	Each piece of information is represented as a :class:`.~Field`

	:param version: The version number of the sample info data.
	:param fields:
	"""
    def __init__(
        self,
        version: int,
        fields: List[Field] = None,
    ):

        super().__init__(version, fields)

        self.version = int(version)

    _content_type = Field
    _content_xml_name = "Field"

    with importlib_resources.path(agilent_xsd, "sample_info.xsd") as path:
        _schema = str(path)

    @classmethod
    def from_xml(cls,
                 element: lxml.objectify.ObjectifiedElement) -> "SampleInfo":
        """
		Construct a :class:`~.SampleInfo` object from an XML element.

		:param element: The XML element to parse the data from
		"""

        version = int(element.Version)  # sample_info version number

        obj = cls(version)
        obj._append_from_element(element)
        return obj
class MSTimeSegments(XMLList):
    """
	Represents the list of MS time segments from :file:`MSTS.xml`.

	:param version:
	:param irm_status:
	:param time_segments:
	:type time_segments:
	"""
    def __init__(self,
                 version: int,
                 irm_status: int = 0,
                 time_segments: Optional[List[TimeSegment]] = None):
        super().__init__(version, time_segments)

        self.irm_status = int(irm_status)

    _content_type = TimeSegment
    _content_xml_name = "TimeSegment"

    with importlib_resources.path(agilent_xsd, "MSTS.xsd") as path:
        _schema = str(path)

    @classmethod
    def from_xml(
            cls,
            element: lxml.objectify.ObjectifiedElement) -> "MSTimeSegments":
        """
		Construct an :class:`~.MSTS` object from an XML element.

		:param element: The XML element to parse the data from
		"""

        version = int(element.Version)  # sample_info version number

        obj = cls(version, irm_status=element.IRMStatus)
        obj._append_from_element(element)
        return obj
Beispiel #8
0
class Contents(XMLFileMixin, Dictable):
    """
	Represents the contents of the ``.d`` datafile, parsed from :file:`Contents.xml`.

	:param version: The version number of the contents file.
	:param acquired_time: The acquisition time
	:param acq_status:
	:param instrument_name: The name of the instrument
	:param locked_mode:
	:param measurement_type:
	:param separation_technique: The separation technique used
	:param total_run_duration: The total time taken for acquisition in seconds
	:param acq_software_version: The version number of the software that acquired the data.
	"""
    def __init__(self,
                 version: int,
                 acquired_time: Union[str, datetime.datetime],
                 acq_status: Union[AcqStatusEnum, int],
                 instrument_name: str = '',
                 locked_mode: bool = False,
                 measurement_type: Union[MeasurementTypeEnum, int] = 0,
                 separation_technique: Union[SeparationTechniqueEnum, int] = 0,
                 total_run_duration: Union[float, datetime.timedelta] = 0.0,
                 acq_software_version: str = ''):
        super().__init__()

        self.version = int(version)

        if isinstance(acquired_time, datetime.datetime):
            self.acquired_time = acquired_time
        else:
            self.acquired_time = parse_worklist_datetime(acquired_time)

        self.acq_status = _get_from_enum(acq_status, AcqStatusEnum, int)
        self.instrument_name = str(instrument_name)
        self.locked_mode = bool(locked_mode)
        self.measurement_type = _get_from_enum(measurement_type,
                                               MeasurementTypeEnum, int)
        self.separation_technique = _get_from_enum(separation_technique,
                                                   SeparationTechniqueEnum,
                                                   int)

        if isinstance(total_run_duration, datetime.timedelta):
            self.total_run_duration = total_run_duration
        else:
            self.total_run_duration = datetime.timedelta(
                seconds=float(total_run_duration))

        self.acq_software_version = str(acq_software_version)

    __slots__ = [
        "version",
        "acquired_time",
        "acq_status",
        "instrument_name",
        "locked_mode",
        "measurement_type",
        "separation_technique",
        "total_run_duration",
        "acq_software_version",
    ]

    @property
    def __dict__(self):
        data = {}
        for key in self.__slots__:
            data[key] = getattr(self, key)

        return data

    with importlib_resources.path(agilent_xsd, "Contents.xsd") as schema_path:
        _schema = str(schema_path)

    @classmethod
    def from_xml(cls,
                 element: lxml.objectify.ObjectifiedElement) -> "Contents":
        """
		Construct a :class:`~.Contents` object from an XML element.

		:param element: The XML element to parse the data from.
		"""

        return cls(
            version=element.Version,
            acquired_time=element.AcquiredTime,
            acq_status=element.AcqStatus,
            instrument_name=element.InstrumentName,
            locked_mode=element_to_bool(element.LockedMode),
            measurement_type=element.MeasurementType,
            separation_technique=element.SeparationTechnique,
            total_run_duration=element.TotalRunDuration,
            acq_software_version=element.AcqSoftwareVersion,
        )