version 1.0.0-rc.13

This commit is contained in:
2024-10-05 13:14:49 +02:00
parent e03a41ec73
commit e812918e2e
436 changed files with 53636 additions and 41327 deletions

View File

@@ -0,0 +1,67 @@
# coding: utf-8
# flake8: noqa
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
__version__ = "1.0.0"
# import apis into sdk package
from openapi_client.api.default_api import DefaultApi
# import ApiClient
from openapi_client.api_response import ApiResponse
from openapi_client.api_client import ApiClient
from openapi_client.configuration import Configuration
from openapi_client.exceptions import OpenApiException
from openapi_client.exceptions import ApiTypeError
from openapi_client.exceptions import ApiValueError
from openapi_client.exceptions import ApiKeyError
from openapi_client.exceptions import ApiAttributeError
from openapi_client.exceptions import ApiException
# import models into sdk package
from openapi_client.models.azim_int_settings import AzimIntSettings
from openapi_client.models.broker_status import BrokerStatus
from openapi_client.models.calibration_statistics_inner import CalibrationStatisticsInner
from openapi_client.models.dataset_settings import DatasetSettings
from openapi_client.models.dataset_settings_unit_cell import DatasetSettingsUnitCell
from openapi_client.models.detector import Detector
from openapi_client.models.detector_list import DetectorList
from openapi_client.models.detector_list_detectors_inner import DetectorListDetectorsInner
from openapi_client.models.detector_module import DetectorModule
from openapi_client.models.detector_module_direction import DetectorModuleDirection
from openapi_client.models.detector_selection import DetectorSelection
from openapi_client.models.detector_settings import DetectorSettings
from openapi_client.models.detector_status import DetectorStatus
from openapi_client.models.detector_type import DetectorType
from openapi_client.models.error_message import ErrorMessage
from openapi_client.models.fpga_status_inner import FpgaStatusInner
from openapi_client.models.image_format_settings import ImageFormatSettings
from openapi_client.models.image_pusher_type import ImagePusherType
from openapi_client.models.instrument_metadata import InstrumentMetadata
from openapi_client.models.jfjoch_settings import JfjochSettings
from openapi_client.models.measurement_statistics import MeasurementStatistics
from openapi_client.models.pcie_devices_inner import PcieDevicesInner
from openapi_client.models.plot import Plot
from openapi_client.models.plots import Plots
from openapi_client.models.preview_settings import PreviewSettings
from openapi_client.models.roi_box import RoiBox
from openapi_client.models.roi_box_list import RoiBoxList
from openapi_client.models.roi_circle import RoiCircle
from openapi_client.models.roi_circle_list import RoiCircleList
from openapi_client.models.rotation_axis import RotationAxis
from openapi_client.models.spot_finding_settings import SpotFindingSettings
from openapi_client.models.standard_detector_geometry import StandardDetectorGeometry
from openapi_client.models.zeromq_settings import ZeromqSettings

View File

@@ -0,0 +1,5 @@
# flake8: noqa
# import apis into api package
from openapi_client.api.default_api import DefaultApi

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,789 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import datetime
from dateutil.parser import parse
from enum import Enum
import decimal
import json
import mimetypes
import os
import re
import tempfile
from urllib.parse import quote
from typing import Tuple, Optional, List, Dict, Union
from pydantic import SecretStr
from openapi_client.configuration import Configuration
from openapi_client.api_response import ApiResponse, T as ApiResponseT
import openapi_client.models
from openapi_client import rest
from openapi_client.exceptions import (
ApiValueError,
ApiException,
BadRequestException,
UnauthorizedException,
ForbiddenException,
NotFoundException,
ServiceException
)
RequestSerialized = Tuple[str, str, Dict[str, str], Optional[str], List[str]]
class ApiClient:
"""Generic API client for OpenAPI client library builds.
OpenAPI generic API client. This client handles the client-
server communication, and is invariant across implementations. Specifics of
the methods and models for each application are generated from the OpenAPI
templates.
:param configuration: .Configuration object for this client
:param header_name: a header to pass when making calls to the API.
:param header_value: a header value to pass when making calls to
the API.
:param cookie: a cookie to include in the header when making calls
to the API
"""
PRIMITIVE_TYPES = (float, bool, bytes, str, int)
NATIVE_TYPES_MAPPING = {
'int': int,
'long': int, # TODO remove as only py3 is supported?
'float': float,
'str': str,
'bool': bool,
'date': datetime.date,
'datetime': datetime.datetime,
'decimal': decimal.Decimal,
'object': object,
}
_pool = None
def __init__(
self,
configuration=None,
header_name=None,
header_value=None,
cookie=None
) -> None:
# use default configuration if none is provided
if configuration is None:
configuration = Configuration.get_default()
self.configuration = configuration
self.rest_client = rest.RESTClientObject(configuration)
self.default_headers = {}
if header_name is not None:
self.default_headers[header_name] = header_value
self.cookie = cookie
# Set default User-Agent.
self.user_agent = 'OpenAPI-Generator/1.0.0/python'
self.client_side_validation = configuration.client_side_validation
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
pass
@property
def user_agent(self):
"""User agent for this API client"""
return self.default_headers['User-Agent']
@user_agent.setter
def user_agent(self, value):
self.default_headers['User-Agent'] = value
def set_default_header(self, header_name, header_value):
self.default_headers[header_name] = header_value
_default = None
@classmethod
def get_default(cls):
"""Return new instance of ApiClient.
This method returns newly created, based on default constructor,
object of ApiClient class or returns a copy of default
ApiClient.
:return: The ApiClient object.
"""
if cls._default is None:
cls._default = ApiClient()
return cls._default
@classmethod
def set_default(cls, default):
"""Set default instance of ApiClient.
It stores default ApiClient.
:param default: object of ApiClient.
"""
cls._default = default
def param_serialize(
self,
method,
resource_path,
path_params=None,
query_params=None,
header_params=None,
body=None,
post_params=None,
files=None, auth_settings=None,
collection_formats=None,
_host=None,
_request_auth=None
) -> RequestSerialized:
"""Builds the HTTP request params needed by the request.
:param method: Method to call.
:param resource_path: Path to method endpoint.
:param path_params: Path parameters in the url.
:param query_params: Query parameters in the url.
:param header_params: Header parameters to be
placed in the request header.
:param body: Request body.
:param post_params dict: Request post form parameters,
for `application/x-www-form-urlencoded`, `multipart/form-data`.
:param auth_settings list: Auth Settings names for the request.
:param files dict: key -> filename, value -> filepath,
for `multipart/form-data`.
:param collection_formats: dict of collection formats for path, query,
header, and post parameters.
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the authentication
in the spec for a single request.
:return: tuple of form (path, http_method, query_params, header_params,
body, post_params, files)
"""
config = self.configuration
# header parameters
header_params = header_params or {}
header_params.update(self.default_headers)
if self.cookie:
header_params['Cookie'] = self.cookie
if header_params:
header_params = self.sanitize_for_serialization(header_params)
header_params = dict(
self.parameters_to_tuples(header_params,collection_formats)
)
# path parameters
if path_params:
path_params = self.sanitize_for_serialization(path_params)
path_params = self.parameters_to_tuples(
path_params,
collection_formats
)
for k, v in path_params:
# specified safe chars, encode everything
resource_path = resource_path.replace(
'{%s}' % k,
quote(str(v), safe=config.safe_chars_for_path_param)
)
# post parameters
if post_params or files:
post_params = post_params if post_params else []
post_params = self.sanitize_for_serialization(post_params)
post_params = self.parameters_to_tuples(
post_params,
collection_formats
)
if files:
post_params.extend(self.files_parameters(files))
# auth setting
self.update_params_for_auth(
header_params,
query_params,
auth_settings,
resource_path,
method,
body,
request_auth=_request_auth
)
# body
if body:
body = self.sanitize_for_serialization(body)
# request url
if _host is None or self.configuration.ignore_operation_servers:
url = self.configuration.host + resource_path
else:
# use server/host defined in path or operation instead
url = _host + resource_path
# query parameters
if query_params:
query_params = self.sanitize_for_serialization(query_params)
url_query = self.parameters_to_url_query(
query_params,
collection_formats
)
url += "?" + url_query
return method, url, header_params, body, post_params
def call_api(
self,
method,
url,
header_params=None,
body=None,
post_params=None,
_request_timeout=None
) -> rest.RESTResponse:
"""Makes the HTTP request (synchronous)
:param method: Method to call.
:param url: Path to method endpoint.
:param header_params: Header parameters to be
placed in the request header.
:param body: Request body.
:param post_params dict: Request post form parameters,
for `application/x-www-form-urlencoded`, `multipart/form-data`.
:param _request_timeout: timeout setting for this request.
:return: RESTResponse
"""
try:
# perform request and return response
response_data = self.rest_client.request(
method, url,
headers=header_params,
body=body, post_params=post_params,
_request_timeout=_request_timeout
)
except ApiException as e:
raise e
return response_data
def response_deserialize(
self,
response_data: rest.RESTResponse,
response_types_map: Optional[Dict[str, ApiResponseT]]=None
) -> ApiResponse[ApiResponseT]:
"""Deserializes response into an object.
:param response_data: RESTResponse object to be deserialized.
:param response_types_map: dict of response types.
:return: ApiResponse
"""
msg = "RESTResponse.read() must be called before passing it to response_deserialize()"
assert response_data.data is not None, msg
response_type = response_types_map.get(str(response_data.status), None)
if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599:
# if not found, look for '1XX', '2XX', etc.
response_type = response_types_map.get(str(response_data.status)[0] + "XX", None)
# deserialize response data
response_text = None
return_data = None
try:
if response_type == "bytearray":
return_data = response_data.data
elif response_type == "file":
return_data = self.__deserialize_file(response_data)
elif response_type is not None:
match = None
content_type = response_data.getheader('content-type')
if content_type is not None:
match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type)
encoding = match.group(1) if match else "utf-8"
response_text = response_data.data.decode(encoding)
return_data = self.deserialize(response_text, response_type, content_type)
finally:
if not 200 <= response_data.status <= 299:
raise ApiException.from_response(
http_resp=response_data,
body=response_text,
data=return_data,
)
return ApiResponse(
status_code = response_data.status,
data = return_data,
headers = response_data.getheaders(),
raw_data = response_data.data
)
def sanitize_for_serialization(self, obj):
"""Builds a JSON POST object.
If obj is None, return None.
If obj is SecretStr, return obj.get_secret_value()
If obj is str, int, long, float, bool, return directly.
If obj is datetime.datetime, datetime.date
convert to string in iso8601 format.
If obj is decimal.Decimal return string representation.
If obj is list, sanitize each element in the list.
If obj is dict, return the dict.
If obj is OpenAPI model, return the properties dict.
:param obj: The data to serialize.
:return: The serialized form of data.
"""
if obj is None:
return None
elif isinstance(obj, Enum):
return obj.value
elif isinstance(obj, SecretStr):
return obj.get_secret_value()
elif isinstance(obj, self.PRIMITIVE_TYPES):
return obj
elif isinstance(obj, list):
return [
self.sanitize_for_serialization(sub_obj) for sub_obj in obj
]
elif isinstance(obj, tuple):
return tuple(
self.sanitize_for_serialization(sub_obj) for sub_obj in obj
)
elif isinstance(obj, (datetime.datetime, datetime.date)):
return obj.isoformat()
elif isinstance(obj, decimal.Decimal):
return str(obj)
elif isinstance(obj, dict):
obj_dict = obj
else:
# Convert model obj to dict except
# attributes `openapi_types`, `attribute_map`
# and attributes which value is not None.
# Convert attribute name to json key in
# model definition for request.
if hasattr(obj, 'to_dict') and callable(getattr(obj, 'to_dict')):
obj_dict = obj.to_dict()
else:
obj_dict = obj.__dict__
return {
key: self.sanitize_for_serialization(val)
for key, val in obj_dict.items()
}
def deserialize(self, response_text: str, response_type: str, content_type: Optional[str]):
"""Deserializes response into an object.
:param response: RESTResponse object to be deserialized.
:param response_type: class literal for
deserialized object, or string of class name.
:param content_type: content type of response.
:return: deserialized object.
"""
# fetch data from response object
if content_type is None:
try:
data = json.loads(response_text)
except ValueError:
data = response_text
elif content_type.startswith("application/json"):
if response_text == "":
data = ""
else:
data = json.loads(response_text)
elif content_type.startswith("text/plain"):
data = response_text
else:
raise ApiException(
status=0,
reason="Unsupported content type: {0}".format(content_type)
)
return self.__deserialize(data, response_type)
def __deserialize(self, data, klass):
"""Deserializes dict, list, str into an object.
:param data: dict, list or str.
:param klass: class literal, or string of class name.
:return: object.
"""
if data is None:
return None
if isinstance(klass, str):
if klass.startswith('List['):
m = re.match(r'List\[(.*)]', klass)
assert m is not None, "Malformed List type definition"
sub_kls = m.group(1)
return [self.__deserialize(sub_data, sub_kls)
for sub_data in data]
if klass.startswith('Dict['):
m = re.match(r'Dict\[([^,]*), (.*)]', klass)
assert m is not None, "Malformed Dict type definition"
sub_kls = m.group(2)
return {k: self.__deserialize(v, sub_kls)
for k, v in data.items()}
# convert str to class
if klass in self.NATIVE_TYPES_MAPPING:
klass = self.NATIVE_TYPES_MAPPING[klass]
else:
klass = getattr(openapi_client.models, klass)
if klass in self.PRIMITIVE_TYPES:
return self.__deserialize_primitive(data, klass)
elif klass == object:
return self.__deserialize_object(data)
elif klass == datetime.date:
return self.__deserialize_date(data)
elif klass == datetime.datetime:
return self.__deserialize_datetime(data)
elif klass == decimal.Decimal:
return decimal.Decimal(data)
elif issubclass(klass, Enum):
return self.__deserialize_enum(data, klass)
else:
return self.__deserialize_model(data, klass)
def parameters_to_tuples(self, params, collection_formats):
"""Get parameters as list of tuples, formatting collections.
:param params: Parameters as dict or list of two-tuples
:param dict collection_formats: Parameter collection formats
:return: Parameters as list of tuples, collections formatted
"""
new_params: List[Tuple[str, str]] = []
if collection_formats is None:
collection_formats = {}
for k, v in params.items() if isinstance(params, dict) else params:
if k in collection_formats:
collection_format = collection_formats[k]
if collection_format == 'multi':
new_params.extend((k, value) for value in v)
else:
if collection_format == 'ssv':
delimiter = ' '
elif collection_format == 'tsv':
delimiter = '\t'
elif collection_format == 'pipes':
delimiter = '|'
else: # csv is the default
delimiter = ','
new_params.append(
(k, delimiter.join(str(value) for value in v)))
else:
new_params.append((k, v))
return new_params
def parameters_to_url_query(self, params, collection_formats):
"""Get parameters as list of tuples, formatting collections.
:param params: Parameters as dict or list of two-tuples
:param dict collection_formats: Parameter collection formats
:return: URL query string (e.g. a=Hello%20World&b=123)
"""
new_params: List[Tuple[str, str]] = []
if collection_formats is None:
collection_formats = {}
for k, v in params.items() if isinstance(params, dict) else params:
if isinstance(v, bool):
v = str(v).lower()
if isinstance(v, (int, float)):
v = str(v)
if isinstance(v, dict):
v = json.dumps(v)
if k in collection_formats:
collection_format = collection_formats[k]
if collection_format == 'multi':
new_params.extend((k, str(value)) for value in v)
else:
if collection_format == 'ssv':
delimiter = ' '
elif collection_format == 'tsv':
delimiter = '\t'
elif collection_format == 'pipes':
delimiter = '|'
else: # csv is the default
delimiter = ','
new_params.append(
(k, delimiter.join(quote(str(value)) for value in v))
)
else:
new_params.append((k, quote(str(v))))
return "&".join(["=".join(map(str, item)) for item in new_params])
def files_parameters(self, files: Dict[str, Union[str, bytes]]):
"""Builds form parameters.
:param files: File parameters.
:return: Form parameters with files.
"""
params = []
for k, v in files.items():
if isinstance(v, str):
with open(v, 'rb') as f:
filename = os.path.basename(f.name)
filedata = f.read()
elif isinstance(v, bytes):
filename = k
filedata = v
else:
raise ValueError("Unsupported file value")
mimetype = (
mimetypes.guess_type(filename)[0]
or 'application/octet-stream'
)
params.append(
tuple([k, tuple([filename, filedata, mimetype])])
)
return params
def select_header_accept(self, accepts: List[str]) -> Optional[str]:
"""Returns `Accept` based on an array of accepts provided.
:param accepts: List of headers.
:return: Accept (e.g. application/json).
"""
if not accepts:
return None
for accept in accepts:
if re.search('json', accept, re.IGNORECASE):
return accept
return accepts[0]
def select_header_content_type(self, content_types):
"""Returns `Content-Type` based on an array of content_types provided.
:param content_types: List of content-types.
:return: Content-Type (e.g. application/json).
"""
if not content_types:
return None
for content_type in content_types:
if re.search('json', content_type, re.IGNORECASE):
return content_type
return content_types[0]
def update_params_for_auth(
self,
headers,
queries,
auth_settings,
resource_path,
method,
body,
request_auth=None
) -> None:
"""Updates header and query params based on authentication setting.
:param headers: Header parameters dict to be updated.
:param queries: Query parameters tuple list to be updated.
:param auth_settings: Authentication setting identifiers list.
:resource_path: A string representation of the HTTP request resource path.
:method: A string representation of the HTTP request method.
:body: A object representing the body of the HTTP request.
The object type is the return value of sanitize_for_serialization().
:param request_auth: if set, the provided settings will
override the token in the configuration.
"""
if not auth_settings:
return
if request_auth:
self._apply_auth_params(
headers,
queries,
resource_path,
method,
body,
request_auth
)
else:
for auth in auth_settings:
auth_setting = self.configuration.auth_settings().get(auth)
if auth_setting:
self._apply_auth_params(
headers,
queries,
resource_path,
method,
body,
auth_setting
)
def _apply_auth_params(
self,
headers,
queries,
resource_path,
method,
body,
auth_setting
) -> None:
"""Updates the request parameters based on a single auth_setting
:param headers: Header parameters dict to be updated.
:param queries: Query parameters tuple list to be updated.
:resource_path: A string representation of the HTTP request resource path.
:method: A string representation of the HTTP request method.
:body: A object representing the body of the HTTP request.
The object type is the return value of sanitize_for_serialization().
:param auth_setting: auth settings for the endpoint
"""
if auth_setting['in'] == 'cookie':
headers['Cookie'] = auth_setting['value']
elif auth_setting['in'] == 'header':
if auth_setting['type'] != 'http-signature':
headers[auth_setting['key']] = auth_setting['value']
elif auth_setting['in'] == 'query':
queries.append((auth_setting['key'], auth_setting['value']))
else:
raise ApiValueError(
'Authentication token must be in `query` or `header`'
)
def __deserialize_file(self, response):
"""Deserializes body to file
Saves response body into a file in a temporary folder,
using the filename from the `Content-Disposition` header if provided.
handle file downloading
save response body into a tmp file and return the instance
:param response: RESTResponse.
:return: file path.
"""
fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path)
os.close(fd)
os.remove(path)
content_disposition = response.getheader("Content-Disposition")
if content_disposition:
m = re.search(
r'filename=[\'"]?([^\'"\s]+)[\'"]?',
content_disposition
)
assert m is not None, "Unexpected 'content-disposition' header value"
filename = m.group(1)
path = os.path.join(os.path.dirname(path), filename)
with open(path, "wb") as f:
f.write(response.data)
return path
def __deserialize_primitive(self, data, klass):
"""Deserializes string to primitive type.
:param data: str.
:param klass: class literal.
:return: int, long, float, str, bool.
"""
try:
return klass(data)
except UnicodeEncodeError:
return str(data)
except TypeError:
return data
def __deserialize_object(self, value):
"""Return an original value.
:return: object.
"""
return value
def __deserialize_date(self, string):
"""Deserializes string to date.
:param string: str.
:return: date.
"""
try:
return parse(string).date()
except ImportError:
return string
except ValueError:
raise rest.ApiException(
status=0,
reason="Failed to parse `{0}` as date object".format(string)
)
def __deserialize_datetime(self, string):
"""Deserializes string to datetime.
The string should be in iso8601 datetime format.
:param string: str.
:return: datetime.
"""
try:
return parse(string)
except ImportError:
return string
except ValueError:
raise rest.ApiException(
status=0,
reason=(
"Failed to parse `{0}` as datetime object"
.format(string)
)
)
def __deserialize_enum(self, data, klass):
"""Deserializes primitive type to enum.
:param data: primitive type.
:param klass: class literal.
:return: enum value.
"""
try:
return klass(data)
except ValueError:
raise rest.ApiException(
status=0,
reason=(
"Failed to parse `{0}` as `{1}`"
.format(data, klass)
)
)
def __deserialize_model(self, data, klass):
"""Deserializes list or dict to model.
:param data: dict, list.
:param klass: class literal.
:return: model object.
"""
return klass.from_dict(data)

View File

@@ -0,0 +1,21 @@
"""API response object."""
from __future__ import annotations
from typing import Optional, Generic, Mapping, TypeVar
from pydantic import Field, StrictInt, StrictBytes, BaseModel
T = TypeVar("T")
class ApiResponse(BaseModel, Generic[T]):
"""
API response object
"""
status_code: StrictInt = Field(description="HTTP status code")
headers: Optional[Mapping[str, str]] = Field(None, description="HTTP headers")
data: T = Field(description="Deserialized data given the data type")
raw_data: StrictBytes = Field(description="Raw data (HTTP response body)")
model_config = {
"arbitrary_types_allowed": True
}

View File

@@ -0,0 +1,451 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import copy
import logging
from logging import FileHandler
import multiprocessing
import sys
from typing import Optional
import urllib3
import http.client as httplib
JSON_SCHEMA_VALIDATION_KEYWORDS = {
'multipleOf', 'maximum', 'exclusiveMaximum',
'minimum', 'exclusiveMinimum', 'maxLength',
'minLength', 'pattern', 'maxItems', 'minItems'
}
class Configuration:
"""This class contains various settings of the API client.
:param host: Base url.
:param ignore_operation_servers
Boolean to ignore operation servers for the API client.
Config will use `host` as the base url regardless of the operation servers.
:param api_key: Dict to store API key(s).
Each entry in the dict specifies an API key.
The dict key is the name of the security scheme in the OAS specification.
The dict value is the API key secret.
:param api_key_prefix: Dict to store API prefix (e.g. Bearer).
The dict key is the name of the security scheme in the OAS specification.
The dict value is an API key prefix when generating the auth data.
:param username: Username for HTTP basic authentication.
:param password: Password for HTTP basic authentication.
:param access_token: Access token.
:param server_index: Index to servers configuration.
:param server_variables: Mapping with string values to replace variables in
templated server configuration. The validation of enums is performed for
variables with defined enum values before.
:param server_operation_index: Mapping from operation ID to an index to server
configuration.
:param server_operation_variables: Mapping from operation ID to a mapping with
string values to replace variables in templated server configuration.
The validation of enums is performed for variables with defined enum
values before.
:param ssl_ca_cert: str - the path to a file of concatenated CA certificates
in PEM format.
:param retries: Number of retries for API requests.
"""
_default = None
def __init__(self, host=None,
api_key=None, api_key_prefix=None,
username=None, password=None,
access_token=None,
server_index=None, server_variables=None,
server_operation_index=None, server_operation_variables=None,
ignore_operation_servers=False,
ssl_ca_cert=None,
retries=None,
*,
debug: Optional[bool] = None
) -> None:
"""Constructor
"""
self._base_path = "http://localhost" if host is None else host
"""Default Base url
"""
self.server_index = 0 if server_index is None and host is None else server_index
self.server_operation_index = server_operation_index or {}
"""Default server index
"""
self.server_variables = server_variables or {}
self.server_operation_variables = server_operation_variables or {}
"""Default server variables
"""
self.ignore_operation_servers = ignore_operation_servers
"""Ignore operation servers
"""
self.temp_folder_path = None
"""Temp file folder for downloading files
"""
# Authentication Settings
self.api_key = {}
if api_key:
self.api_key = api_key
"""dict to store API key(s)
"""
self.api_key_prefix = {}
if api_key_prefix:
self.api_key_prefix = api_key_prefix
"""dict to store API prefix (e.g. Bearer)
"""
self.refresh_api_key_hook = None
"""function hook to refresh API key if expired
"""
self.username = username
"""Username for HTTP basic authentication
"""
self.password = password
"""Password for HTTP basic authentication
"""
self.access_token = access_token
"""Access token
"""
self.logger = {}
"""Logging Settings
"""
self.logger["package_logger"] = logging.getLogger("openapi_client")
self.logger["urllib3_logger"] = logging.getLogger("urllib3")
self.logger_format = '%(asctime)s %(levelname)s %(message)s'
"""Log format
"""
self.logger_stream_handler = None
"""Log stream handler
"""
self.logger_file_handler: Optional[FileHandler] = None
"""Log file handler
"""
self.logger_file = None
"""Debug file location
"""
if debug is not None:
self.debug = debug
else:
self.__debug = False
"""Debug switch
"""
self.verify_ssl = True
"""SSL/TLS verification
Set this to false to skip verifying SSL certificate when calling API
from https server.
"""
self.ssl_ca_cert = ssl_ca_cert
"""Set this to customize the certificate file to verify the peer.
"""
self.cert_file = None
"""client certificate file
"""
self.key_file = None
"""client key file
"""
self.assert_hostname = None
"""Set this to True/False to enable/disable SSL hostname verification.
"""
self.tls_server_name = None
"""SSL/TLS Server Name Indication (SNI)
Set this to the SNI value expected by the server.
"""
self.connection_pool_maxsize = multiprocessing.cpu_count() * 5
"""urllib3 connection pool's maximum number of connections saved
per pool. urllib3 uses 1 connection as default value, but this is
not the best value when you are making a lot of possibly parallel
requests to the same host, which is often the case here.
cpu_count * 5 is used as default value to increase performance.
"""
self.proxy: Optional[str] = None
"""Proxy URL
"""
self.proxy_headers = None
"""Proxy headers
"""
self.safe_chars_for_path_param = ''
"""Safe chars for path_param
"""
self.retries = retries
"""Adding retries to override urllib3 default value 3
"""
# Enable client side validation
self.client_side_validation = True
self.socket_options = None
"""Options to pass down to the underlying urllib3 socket
"""
self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z"
"""datetime format
"""
self.date_format = "%Y-%m-%d"
"""date format
"""
def __deepcopy__(self, memo):
cls = self.__class__
result = cls.__new__(cls)
memo[id(self)] = result
for k, v in self.__dict__.items():
if k not in ('logger', 'logger_file_handler'):
setattr(result, k, copy.deepcopy(v, memo))
# shallow copy of loggers
result.logger = copy.copy(self.logger)
# use setters to configure loggers
result.logger_file = self.logger_file
result.debug = self.debug
return result
def __setattr__(self, name, value):
object.__setattr__(self, name, value)
@classmethod
def set_default(cls, default):
"""Set default instance of configuration.
It stores default configuration, which can be
returned by get_default_copy method.
:param default: object of Configuration
"""
cls._default = default
@classmethod
def get_default_copy(cls):
"""Deprecated. Please use `get_default` instead.
Deprecated. Please use `get_default` instead.
:return: The configuration object.
"""
return cls.get_default()
@classmethod
def get_default(cls):
"""Return the default configuration.
This method returns newly created, based on default constructor,
object of Configuration class or returns a copy of default
configuration.
:return: The configuration object.
"""
if cls._default is None:
cls._default = Configuration()
return cls._default
@property
def logger_file(self):
"""The logger file.
If the logger_file is None, then add stream handler and remove file
handler. Otherwise, add file handler and remove stream handler.
:param value: The logger_file path.
:type: str
"""
return self.__logger_file
@logger_file.setter
def logger_file(self, value):
"""The logger file.
If the logger_file is None, then add stream handler and remove file
handler. Otherwise, add file handler and remove stream handler.
:param value: The logger_file path.
:type: str
"""
self.__logger_file = value
if self.__logger_file:
# If set logging file,
# then add file handler and remove stream handler.
self.logger_file_handler = logging.FileHandler(self.__logger_file)
self.logger_file_handler.setFormatter(self.logger_formatter)
for _, logger in self.logger.items():
logger.addHandler(self.logger_file_handler)
@property
def debug(self):
"""Debug status
:param value: The debug status, True or False.
:type: bool
"""
return self.__debug
@debug.setter
def debug(self, value):
"""Debug status
:param value: The debug status, True or False.
:type: bool
"""
self.__debug = value
if self.__debug:
# if debug status is True, turn on debug logging
for _, logger in self.logger.items():
logger.setLevel(logging.DEBUG)
# turn on httplib debug
httplib.HTTPConnection.debuglevel = 1
else:
# if debug status is False, turn off debug logging,
# setting log level to default `logging.WARNING`
for _, logger in self.logger.items():
logger.setLevel(logging.WARNING)
# turn off httplib debug
httplib.HTTPConnection.debuglevel = 0
@property
def logger_format(self):
"""The logger format.
The logger_formatter will be updated when sets logger_format.
:param value: The format string.
:type: str
"""
return self.__logger_format
@logger_format.setter
def logger_format(self, value):
"""The logger format.
The logger_formatter will be updated when sets logger_format.
:param value: The format string.
:type: str
"""
self.__logger_format = value
self.logger_formatter = logging.Formatter(self.__logger_format)
def get_api_key_with_prefix(self, identifier, alias=None):
"""Gets API key (with prefix if set).
:param identifier: The identifier of apiKey.
:param alias: The alternative identifier of apiKey.
:return: The token for api key authentication.
"""
if self.refresh_api_key_hook is not None:
self.refresh_api_key_hook(self)
key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None)
if key:
prefix = self.api_key_prefix.get(identifier)
if prefix:
return "%s %s" % (prefix, key)
else:
return key
def get_basic_auth_token(self):
"""Gets HTTP basic authentication header (string).
:return: The token for basic HTTP authentication.
"""
username = ""
if self.username is not None:
username = self.username
password = ""
if self.password is not None:
password = self.password
return urllib3.util.make_headers(
basic_auth=username + ':' + password
).get('authorization')
def auth_settings(self):
"""Gets Auth Settings dict for api client.
:return: The Auth Settings information dict.
"""
auth = {}
return auth
def to_debug_report(self):
"""Gets the essential information for debugging.
:return: The report for debugging.
"""
return "Python SDK Debug Report:\n"\
"OS: {env}\n"\
"Python Version: {pyversion}\n"\
"Version of the API: 1.0.0-rc.13\n"\
"SDK Package Version: 1.0.0".\
format(env=sys.platform, pyversion=sys.version)
def get_host_settings(self):
"""Gets an array of host settings
:return: An array of host settings
"""
return [
{
'url': "",
'description': "No description provided",
}
]
def get_host_from_settings(self, index, variables=None, servers=None):
"""Gets host URL based on the index and variables
:param index: array index of the host settings
:param variables: hash of variable and the corresponding value
:param servers: an array of host settings or None
:return: URL based on host settings
"""
if index is None:
return self._base_path
variables = {} if variables is None else variables
servers = self.get_host_settings() if servers is None else servers
try:
server = servers[index]
except IndexError:
raise ValueError(
"Invalid index {0} when selecting the host settings. "
"Must be less than {1}".format(index, len(servers)))
url = server['url']
# go through variables and replace placeholders
for variable_name, variable in server.get('variables', {}).items():
used_value = variables.get(
variable_name, variable['default_value'])
if 'enum_values' in variable \
and used_value not in variable['enum_values']:
raise ValueError(
"The variable `{0}` in the host URL has invalid value "
"{1}. Must be {2}.".format(
variable_name, variables[variable_name],
variable['enum_values']))
url = url.replace("{" + variable_name + "}", used_value)
return url
@property
def host(self):
"""Return generated host."""
return self.get_host_from_settings(self.server_index, variables=self.server_variables)
@host.setter
def host(self, value):
"""Fix base path."""
self._base_path = value
self.server_index = None

View File

@@ -0,0 +1,200 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from typing import Any, Optional
from typing_extensions import Self
class OpenApiException(Exception):
"""The base exception class for all OpenAPIExceptions"""
class ApiTypeError(OpenApiException, TypeError):
def __init__(self, msg, path_to_item=None, valid_classes=None,
key_type=None) -> None:
""" Raises an exception for TypeErrors
Args:
msg (str): the exception message
Keyword Args:
path_to_item (list): a list of keys an indices to get to the
current_item
None if unset
valid_classes (tuple): the primitive classes that current item
should be an instance of
None if unset
key_type (bool): False if our value is a value in a dict
True if it is a key in a dict
False if our item is an item in a list
None if unset
"""
self.path_to_item = path_to_item
self.valid_classes = valid_classes
self.key_type = key_type
full_msg = msg
if path_to_item:
full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
super(ApiTypeError, self).__init__(full_msg)
class ApiValueError(OpenApiException, ValueError):
def __init__(self, msg, path_to_item=None) -> None:
"""
Args:
msg (str): the exception message
Keyword Args:
path_to_item (list) the path to the exception in the
received_data dict. None if unset
"""
self.path_to_item = path_to_item
full_msg = msg
if path_to_item:
full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
super(ApiValueError, self).__init__(full_msg)
class ApiAttributeError(OpenApiException, AttributeError):
def __init__(self, msg, path_to_item=None) -> None:
"""
Raised when an attribute reference or assignment fails.
Args:
msg (str): the exception message
Keyword Args:
path_to_item (None/list) the path to the exception in the
received_data dict
"""
self.path_to_item = path_to_item
full_msg = msg
if path_to_item:
full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
super(ApiAttributeError, self).__init__(full_msg)
class ApiKeyError(OpenApiException, KeyError):
def __init__(self, msg, path_to_item=None) -> None:
"""
Args:
msg (str): the exception message
Keyword Args:
path_to_item (None/list) the path to the exception in the
received_data dict
"""
self.path_to_item = path_to_item
full_msg = msg
if path_to_item:
full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
super(ApiKeyError, self).__init__(full_msg)
class ApiException(OpenApiException):
def __init__(
self,
status=None,
reason=None,
http_resp=None,
*,
body: Optional[str] = None,
data: Optional[Any] = None,
) -> None:
self.status = status
self.reason = reason
self.body = body
self.data = data
self.headers = None
if http_resp:
if self.status is None:
self.status = http_resp.status
if self.reason is None:
self.reason = http_resp.reason
if self.body is None:
try:
self.body = http_resp.data.decode('utf-8')
except Exception:
pass
self.headers = http_resp.getheaders()
@classmethod
def from_response(
cls,
*,
http_resp,
body: Optional[str],
data: Optional[Any],
) -> Self:
if http_resp.status == 400:
raise BadRequestException(http_resp=http_resp, body=body, data=data)
if http_resp.status == 401:
raise UnauthorizedException(http_resp=http_resp, body=body, data=data)
if http_resp.status == 403:
raise ForbiddenException(http_resp=http_resp, body=body, data=data)
if http_resp.status == 404:
raise NotFoundException(http_resp=http_resp, body=body, data=data)
if 500 <= http_resp.status <= 599:
raise ServiceException(http_resp=http_resp, body=body, data=data)
raise ApiException(http_resp=http_resp, body=body, data=data)
def __str__(self):
"""Custom error messages for exception"""
error_message = "({0})\n"\
"Reason: {1}\n".format(self.status, self.reason)
if self.headers:
error_message += "HTTP response headers: {0}\n".format(
self.headers)
if self.data or self.body:
error_message += "HTTP response body: {0}\n".format(self.data or self.body)
return error_message
class BadRequestException(ApiException):
pass
class NotFoundException(ApiException):
pass
class UnauthorizedException(ApiException):
pass
class ForbiddenException(ApiException):
pass
class ServiceException(ApiException):
pass
def render_path(path_to_item):
"""Returns a string representation of a path"""
result = ""
for pth in path_to_item:
if isinstance(pth, int):
result += "[{0}]".format(pth)
else:
result += "['{0}']".format(pth)
return result

View File

@@ -0,0 +1,50 @@
# coding: utf-8
# flake8: noqa
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
# import models into model package
from openapi_client.models.azim_int_settings import AzimIntSettings
from openapi_client.models.broker_status import BrokerStatus
from openapi_client.models.calibration_statistics_inner import CalibrationStatisticsInner
from openapi_client.models.dataset_settings import DatasetSettings
from openapi_client.models.dataset_settings_unit_cell import DatasetSettingsUnitCell
from openapi_client.models.detector import Detector
from openapi_client.models.detector_list import DetectorList
from openapi_client.models.detector_list_detectors_inner import DetectorListDetectorsInner
from openapi_client.models.detector_module import DetectorModule
from openapi_client.models.detector_module_direction import DetectorModuleDirection
from openapi_client.models.detector_selection import DetectorSelection
from openapi_client.models.detector_settings import DetectorSettings
from openapi_client.models.detector_status import DetectorStatus
from openapi_client.models.detector_type import DetectorType
from openapi_client.models.error_message import ErrorMessage
from openapi_client.models.fpga_status_inner import FpgaStatusInner
from openapi_client.models.image_format_settings import ImageFormatSettings
from openapi_client.models.image_pusher_type import ImagePusherType
from openapi_client.models.instrument_metadata import InstrumentMetadata
from openapi_client.models.jfjoch_settings import JfjochSettings
from openapi_client.models.measurement_statistics import MeasurementStatistics
from openapi_client.models.pcie_devices_inner import PcieDevicesInner
from openapi_client.models.plot import Plot
from openapi_client.models.plots import Plots
from openapi_client.models.preview_settings import PreviewSettings
from openapi_client.models.roi_box import RoiBox
from openapi_client.models.roi_box_list import RoiBoxList
from openapi_client.models.roi_circle import RoiCircle
from openapi_client.models.roi_circle_list import RoiCircleList
from openapi_client.models.rotation_axis import RotationAxis
from openapi_client.models.spot_finding_settings import SpotFindingSettings
from openapi_client.models.standard_detector_geometry import StandardDetectorGeometry
from openapi_client.models.zeromq_settings import ZeromqSettings

View File

@@ -0,0 +1,97 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt
from typing import Any, ClassVar, Dict, List, Optional, Union
from typing_extensions import Annotated
from typing import Optional, Set
from typing_extensions import Self
class AzimIntSettings(BaseModel):
"""
AzimIntSettings
""" # noqa: E501
polarization_factor: Optional[Union[Annotated[float, Field(le=1.0, strict=True, ge=-1.0)], Annotated[int, Field(le=1, strict=True, ge=-1)]]] = Field(default=None, description="If polarization factor is provided, than polarization correction is enabled.")
solid_angle_corr: StrictBool = Field(description="Apply solid angle correction for radial integration")
high_q_recip_a: Union[StrictFloat, StrictInt] = Field(alias="high_q_recipA")
low_q_recip_a: Union[StrictFloat, StrictInt] = Field(alias="low_q_recipA")
q_spacing: Union[StrictFloat, StrictInt]
__properties: ClassVar[List[str]] = ["polarization_factor", "solid_angle_corr", "high_q_recipA", "low_q_recipA", "q_spacing"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of AzimIntSettings from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of AzimIntSettings from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"polarization_factor": obj.get("polarization_factor"),
"solid_angle_corr": obj.get("solid_angle_corr") if obj.get("solid_angle_corr") is not None else True,
"high_q_recipA": obj.get("high_q_recipA"),
"low_q_recipA": obj.get("low_q_recipA"),
"q_spacing": obj.get("q_spacing")
})
return _obj

View File

@@ -0,0 +1,100 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional, Union
from typing_extensions import Annotated
from typing import Optional, Set
from typing_extensions import Self
class BrokerStatus(BaseModel):
"""
BrokerStatus
""" # noqa: E501
state: StrictStr
progress: Optional[Union[Annotated[float, Field(le=1.0, strict=True, ge=0.0)], Annotated[int, Field(le=1, strict=True, ge=0)]]] = None
indexing_rate: Optional[Union[Annotated[float, Field(le=1.0, strict=True, ge=0.0)], Annotated[int, Field(le=1, strict=True, ge=0)]]] = None
__properties: ClassVar[List[str]] = ["state", "progress", "indexing_rate"]
@field_validator('state')
def state_validate_enum(cls, value):
"""Validates the enum"""
if value not in set(['Inactive', 'Idle', 'Busy', 'Measuring', 'Pedestal', 'Error']):
raise ValueError("must be one of enum values ('Inactive', 'Idle', 'Busy', 'Measuring', 'Pedestal', 'Error')")
return value
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of BrokerStatus from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of BrokerStatus from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"state": obj.get("state"),
"progress": obj.get("progress"),
"indexing_rate": obj.get("indexing_rate")
})
return _obj

View File

@@ -0,0 +1,104 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, StrictFloat, StrictInt
from typing import Any, ClassVar, Dict, List, Union
from typing import Optional, Set
from typing_extensions import Self
class CalibrationStatisticsInner(BaseModel):
"""
CalibrationStatisticsInner
""" # noqa: E501
module_number: StrictInt
storage_cell_number: StrictInt
pedestal_g0_mean: Union[StrictFloat, StrictInt]
pedestal_g1_mean: Union[StrictFloat, StrictInt]
pedestal_g2_mean: Union[StrictFloat, StrictInt]
gain_g0_mean: Union[StrictFloat, StrictInt]
gain_g1_mean: Union[StrictFloat, StrictInt]
gain_g2_mean: Union[StrictFloat, StrictInt]
masked_pixels: StrictInt
__properties: ClassVar[List[str]] = ["module_number", "storage_cell_number", "pedestal_g0_mean", "pedestal_g1_mean", "pedestal_g2_mean", "gain_g0_mean", "gain_g1_mean", "gain_g2_mean", "masked_pixels"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of CalibrationStatisticsInner from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of CalibrationStatisticsInner from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"module_number": obj.get("module_number"),
"storage_cell_number": obj.get("storage_cell_number"),
"pedestal_g0_mean": obj.get("pedestal_g0_mean"),
"pedestal_g1_mean": obj.get("pedestal_g1_mean"),
"pedestal_g2_mean": obj.get("pedestal_g2_mean"),
"gain_g0_mean": obj.get("gain_g0_mean"),
"gain_g1_mean": obj.get("gain_g1_mean"),
"gain_g2_mean": obj.get("gain_g2_mean"),
"masked_pixels": obj.get("masked_pixels")
})
return _obj

View File

@@ -0,0 +1,167 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional, Union
from typing_extensions import Annotated
from openapi_client.models.dataset_settings_unit_cell import DatasetSettingsUnitCell
from openapi_client.models.rotation_axis import RotationAxis
from typing import Optional, Set
from typing_extensions import Self
class DatasetSettings(BaseModel):
"""
DatasetSettings
""" # noqa: E501
images_per_trigger: Optional[Annotated[int, Field(strict=True, ge=1)]] = Field(default=1, description="For standard synchrotron data collection - this is number of images collected per one TTL trigger For XFEL (pulsed source) - this number is ignored and set to 1 For storage cell mode - this number is ignored and set to number of storage cells ")
ntrigger: Optional[Annotated[int, Field(strict=True, ge=1)]] = Field(default=1, description="Number of TTL trigger that the detector is expected to receive during data collection ")
image_time_us: Optional[Annotated[int, Field(strict=True, ge=0)]] = Field(default=None, description="Image time. If not provided (or zero value) the frame time is assumed as default. Image time must be multiple of frame time; max value is 256 * frame_time. In XFEL mode: summation happens for frames collected with multiple triggers. Ignored for storage cells and if raw data are saved. ")
beam_x_pxl: Union[StrictFloat, StrictInt] = Field(description="/entry/detector/beam_center_x in NXmx Beam center in X direction [pixels] ")
beam_y_pxl: Union[StrictFloat, StrictInt] = Field(description="/entry/detector/beam_center_y in NXmx Beam center in X direction [pixels] ")
detector_distance_mm: Union[Annotated[float, Field(strict=True, ge=0)], Annotated[int, Field(strict=True, ge=0)]] = Field(description="/entry/detector/distance in NXmx Detector distance [mm]")
incident_energy_ke_v: Union[Annotated[float, Field(le=500.0, strict=True, ge=0.001)], Annotated[int, Field(le=500, strict=True, ge=1)]] = Field(description="Used to calculate /entry/beam/incident_wavelength in NXmx Incident particle (photon, electron) energy in keV ", alias="incident_energy_keV")
file_prefix: Optional[StrictStr] = Field(default='', description="Prefix for filenames. If left empty, no file will be saved.")
images_per_file: Optional[Annotated[int, Field(strict=True, ge=0)]] = Field(default=1000, description="Number of files in a single HDF5 data file (0 = write all images to a single data file).")
space_group_number: Optional[Annotated[int, Field(le=194, strict=True, ge=0)]] = 0
sample_name: Optional[StrictStr] = Field(default='', description="/entry/sample/name in NXmx Sample name ")
compression: Optional[StrictStr] = 'bslz4'
total_flux: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="/entry/beam/total_flux in NXmx Flux incident on beam plane in photons per second. In other words this is the flux integrated over area. [photons/s] ")
transmission: Optional[Union[Annotated[float, Field(le=1.0, strict=True, ge=0.0)], Annotated[int, Field(le=1, strict=True, ge=0)]]] = Field(default=None, description="/entry/instrument/attenuator/attenuator_transmission Transmission of attenuator (filter) [no units] ")
goniometer: Optional[RotationAxis] = None
header_appendix: Optional[Any] = Field(default=None, description="Header appendix, added as user_data/user to start message (can be any valid JSON)")
image_appendix: Optional[Any] = Field(default=None, description="Image appendix, added as user_data to image message (can be any valid JSON)")
data_reduction_factor_serialmx: Optional[Union[Annotated[float, Field(le=1.0, strict=True, ge=0.0)], Annotated[int, Field(le=1, strict=True, ge=0)]]] = Field(default=1.0, description="Rate at which non-indexed images are accepted to be forwarded to writer. Value of 1.0 (default) means that all images are written. Values below zero mean that non-indexed images will be accepted with a given probability. ")
pixel_value_low_threshold: Optional[Annotated[int, Field(strict=True, ge=0)]] = Field(default=None, description="Set all counts lower than the value to zero. When the value is set, negative numbers other than error pixel value are always set to zero. Setting to zero is equivalent to turning the option off. ")
run_number: Optional[Annotated[int, Field(strict=True, ge=0)]] = Field(default=None, description="Number of run within an experimental session. Transferred over CBOR stream as \"series ID\", though not saved in HDF5 file. It is highly recommended to keep this number unique for each data collection during experimental series. If not provided, the number will be automatically incremented. ")
run_name: Optional[StrictStr] = Field(default=None, description="Unique ID of run. Transferred over CBOR stream as \"unique series ID\", though not saved in HDF5 file. It is highly recommended to keep this name unique for each data collection during experimental series. If not provided, the name will be automatically generated as number + colon + file_prefix. ")
experiment_group: Optional[StrictStr] = Field(default=None, description="Name of group owning the data (e.g. p-group or proposal number). Transferred over CBOR stream, though not saved in HDF5 file. ")
poisson_compression: Optional[Annotated[int, Field(le=16, strict=True, ge=0)]] = Field(default=None, description="Enable lossy compression of pixel values that preserves Poisson statistics. Requires to provide a numerical factor SQ. Pixel value P will be transformed to round(sqrt(P) * SQ), with rounding to the closest integer. Compression is turned off if the value is missing or it is set to zero. ")
write_nxmx_hdf5_master: Optional[StrictBool] = Field(default=True, description="Write NXmx formatted HDF5 master file. Recommended to use for macromolecular crystallography experiments and to turn off for other experiments. ")
save_calibration: Optional[StrictBool] = Field(default=None, description="Forward image calibration (at the moment pedestal and pedestal RMS for JUNGFRAU) using the ZeroMQ stream to writer. If parameter is not provided calibration will be saved only if more than 4 images are recorded. ")
unit_cell: Optional[DatasetSettingsUnitCell] = None
__properties: ClassVar[List[str]] = ["images_per_trigger", "ntrigger", "image_time_us", "beam_x_pxl", "beam_y_pxl", "detector_distance_mm", "incident_energy_keV", "file_prefix", "images_per_file", "space_group_number", "sample_name", "compression", "total_flux", "transmission", "goniometer", "header_appendix", "image_appendix", "data_reduction_factor_serialmx", "pixel_value_low_threshold", "run_number", "run_name", "experiment_group", "poisson_compression", "write_nxmx_hdf5_master", "save_calibration", "unit_cell"]
@field_validator('compression')
def compression_validate_enum(cls, value):
"""Validates the enum"""
if value is None:
return value
if value not in set(['bslz4', 'bszstd', 'bszstd_rle', 'none']):
raise ValueError("must be one of enum values ('bslz4', 'bszstd', 'bszstd_rle', 'none')")
return value
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of DatasetSettings from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of goniometer
if self.goniometer:
_dict['goniometer'] = self.goniometer.to_dict()
# override the default output from pydantic by calling `to_dict()` of unit_cell
if self.unit_cell:
_dict['unit_cell'] = self.unit_cell.to_dict()
# set to None if header_appendix (nullable) is None
# and model_fields_set contains the field
if self.header_appendix is None and "header_appendix" in self.model_fields_set:
_dict['header_appendix'] = None
# set to None if image_appendix (nullable) is None
# and model_fields_set contains the field
if self.image_appendix is None and "image_appendix" in self.model_fields_set:
_dict['image_appendix'] = None
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of DatasetSettings from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"images_per_trigger": obj.get("images_per_trigger") if obj.get("images_per_trigger") is not None else 1,
"ntrigger": obj.get("ntrigger") if obj.get("ntrigger") is not None else 1,
"image_time_us": obj.get("image_time_us"),
"beam_x_pxl": obj.get("beam_x_pxl"),
"beam_y_pxl": obj.get("beam_y_pxl"),
"detector_distance_mm": obj.get("detector_distance_mm"),
"incident_energy_keV": obj.get("incident_energy_keV"),
"file_prefix": obj.get("file_prefix") if obj.get("file_prefix") is not None else '',
"images_per_file": obj.get("images_per_file") if obj.get("images_per_file") is not None else 1000,
"space_group_number": obj.get("space_group_number") if obj.get("space_group_number") is not None else 0,
"sample_name": obj.get("sample_name") if obj.get("sample_name") is not None else '',
"compression": obj.get("compression") if obj.get("compression") is not None else 'bslz4',
"total_flux": obj.get("total_flux"),
"transmission": obj.get("transmission"),
"goniometer": RotationAxis.from_dict(obj["goniometer"]) if obj.get("goniometer") is not None else None,
"header_appendix": obj.get("header_appendix"),
"image_appendix": obj.get("image_appendix"),
"data_reduction_factor_serialmx": obj.get("data_reduction_factor_serialmx") if obj.get("data_reduction_factor_serialmx") is not None else 1.0,
"pixel_value_low_threshold": obj.get("pixel_value_low_threshold"),
"run_number": obj.get("run_number"),
"run_name": obj.get("run_name"),
"experiment_group": obj.get("experiment_group"),
"poisson_compression": obj.get("poisson_compression"),
"write_nxmx_hdf5_master": obj.get("write_nxmx_hdf5_master") if obj.get("write_nxmx_hdf5_master") is not None else True,
"save_calibration": obj.get("save_calibration"),
"unit_cell": DatasetSettingsUnitCell.from_dict(obj["unit_cell"]) if obj.get("unit_cell") is not None else None
})
return _obj

View File

@@ -0,0 +1,99 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field
from typing import Any, ClassVar, Dict, List, Union
from typing_extensions import Annotated
from typing import Optional, Set
from typing_extensions import Self
class DatasetSettingsUnitCell(BaseModel):
"""
Units of angstrom and degree
""" # noqa: E501
a: Union[Annotated[float, Field(strict=True, ge=0)], Annotated[int, Field(strict=True, ge=0)]]
b: Union[Annotated[float, Field(strict=True, ge=0)], Annotated[int, Field(strict=True, ge=0)]]
c: Union[Annotated[float, Field(strict=True, ge=0)], Annotated[int, Field(strict=True, ge=0)]]
alpha: Union[Annotated[float, Field(le=360, strict=True, ge=0)], Annotated[int, Field(le=360, strict=True, ge=0)]]
beta: Union[Annotated[float, Field(le=360, strict=True, ge=0)], Annotated[int, Field(le=360, strict=True, ge=0)]]
gamma: Union[Annotated[float, Field(le=360, strict=True, ge=0)], Annotated[int, Field(le=360, strict=True, ge=0)]]
__properties: ClassVar[List[str]] = ["a", "b", "c", "alpha", "beta", "gamma"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of DatasetSettingsUnitCell from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of DatasetSettingsUnitCell from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"a": obj.get("a"),
"b": obj.get("b"),
"c": obj.get("c"),
"alpha": obj.get("alpha"),
"beta": obj.get("beta"),
"gamma": obj.get("gamma")
})
return _obj

View File

@@ -0,0 +1,128 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional, Union
from typing_extensions import Annotated
from openapi_client.models.detector_module import DetectorModule
from openapi_client.models.detector_type import DetectorType
from openapi_client.models.standard_detector_geometry import StandardDetectorGeometry
from typing import Optional, Set
from typing_extensions import Self
class Detector(BaseModel):
"""
Detector
""" # noqa: E501
description: Annotated[str, Field(min_length=1, strict=True)]
serial_number: Annotated[str, Field(min_length=1, strict=True)]
type: Optional[DetectorType] = None
high_voltage_v: Optional[Annotated[int, Field(le=200, strict=True, ge=0)]] = Field(default=0, alias="high_voltage_V")
udp_interface_count: Optional[Annotated[int, Field(le=2, strict=True, ge=1)]] = 1
sensor_thickness_um: Optional[Union[Annotated[float, Field(strict=True, ge=0)], Annotated[int, Field(strict=True, ge=0)]]] = 320
calibration_file: Optional[List[StrictStr]] = Field(default=None, description="Gain file (JUNGFRAU) or trimbit file (EIGER). One entry per module. Either empty or number of module entries. ")
hostname: Optional[List[StrictStr]] = Field(default=None, description="Hostname for detector module. One entry per module One entry per module. Either empty or number of module entries. ")
sensor_material: Optional[StrictStr] = 'Si'
tx_delay: Optional[List[StrictInt]] = None
base_data_ipv4_address: Optional[StrictStr] = None
standard_geometry: Optional[StandardDetectorGeometry] = None
custom_geometry: Optional[List[DetectorModule]] = None
mirror_y: Optional[StrictBool] = Field(default=True, description="Mirror detector in Y direction to account for MX convention of (0,0) point in top left corner")
__properties: ClassVar[List[str]] = ["description", "serial_number", "type", "high_voltage_V", "udp_interface_count", "sensor_thickness_um", "calibration_file", "hostname", "sensor_material", "tx_delay", "base_data_ipv4_address", "standard_geometry", "custom_geometry", "mirror_y"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of Detector from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of standard_geometry
if self.standard_geometry:
_dict['standard_geometry'] = self.standard_geometry.to_dict()
# override the default output from pydantic by calling `to_dict()` of each item in custom_geometry (list)
_items = []
if self.custom_geometry:
for _item_custom_geometry in self.custom_geometry:
if _item_custom_geometry:
_items.append(_item_custom_geometry.to_dict())
_dict['custom_geometry'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of Detector from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"description": obj.get("description"),
"serial_number": obj.get("serial_number"),
"type": obj.get("type"),
"high_voltage_V": obj.get("high_voltage_V") if obj.get("high_voltage_V") is not None else 0,
"udp_interface_count": obj.get("udp_interface_count") if obj.get("udp_interface_count") is not None else 1,
"sensor_thickness_um": obj.get("sensor_thickness_um") if obj.get("sensor_thickness_um") is not None else 320,
"calibration_file": obj.get("calibration_file"),
"hostname": obj.get("hostname"),
"sensor_material": obj.get("sensor_material") if obj.get("sensor_material") is not None else 'Si',
"tx_delay": obj.get("tx_delay"),
"base_data_ipv4_address": obj.get("base_data_ipv4_address"),
"standard_geometry": StandardDetectorGeometry.from_dict(obj["standard_geometry"]) if obj.get("standard_geometry") is not None else None,
"custom_geometry": [DetectorModule.from_dict(_item) for _item in obj["custom_geometry"]] if obj.get("custom_geometry") is not None else None,
"mirror_y": obj.get("mirror_y") if obj.get("mirror_y") is not None else True
})
return _obj

View File

@@ -0,0 +1,98 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, StrictInt
from typing import Any, ClassVar, Dict, List
from openapi_client.models.detector_list_detectors_inner import DetectorListDetectorsInner
from typing import Optional, Set
from typing_extensions import Self
class DetectorList(BaseModel):
"""
DetectorList
""" # noqa: E501
detectors: List[DetectorListDetectorsInner]
current_id: StrictInt
__properties: ClassVar[List[str]] = ["detectors", "current_id"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of DetectorList from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of each item in detectors (list)
_items = []
if self.detectors:
for _item_detectors in self.detectors:
if _item_detectors:
_items.append(_item_detectors.to_dict())
_dict['detectors'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of DetectorList from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"detectors": [DetectorListDetectorsInner.from_dict(_item) for _item in obj["detectors"]] if obj.get("detectors") is not None else None,
"current_id": obj.get("current_id")
})
return _obj

View File

@@ -0,0 +1,103 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from typing import Optional, Set
from typing_extensions import Self
class DetectorListDetectorsInner(BaseModel):
"""
DetectorListDetectorsInner
""" # noqa: E501
id: Annotated[int, Field(strict=True, ge=0)]
description: StrictStr
serial_number: StrictStr
base_ipv4_addr: StrictStr
udp_interface_count: Optional[StrictInt] = Field(default=None, description="Number of UDP interfaces per detector module")
nmodules: StrictInt
width: StrictInt
height: StrictInt
__properties: ClassVar[List[str]] = ["id", "description", "serial_number", "base_ipv4_addr", "udp_interface_count", "nmodules", "width", "height"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of DetectorListDetectorsInner from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of DetectorListDetectorsInner from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"description": obj.get("description"),
"serial_number": obj.get("serial_number"),
"base_ipv4_addr": obj.get("base_ipv4_addr"),
"udp_interface_count": obj.get("udp_interface_count"),
"nmodules": obj.get("nmodules"),
"width": obj.get("width"),
"height": obj.get("height")
})
return _obj

View File

@@ -0,0 +1,95 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, StrictFloat, StrictInt
from typing import Any, ClassVar, Dict, List, Union
from openapi_client.models.detector_module_direction import DetectorModuleDirection
from typing import Optional, Set
from typing_extensions import Self
class DetectorModule(BaseModel):
"""
DetectorModule
""" # noqa: E501
x0: Union[StrictFloat, StrictInt]
y0: Union[StrictFloat, StrictInt]
fast_axis: DetectorModuleDirection
slow_axis: DetectorModuleDirection
__properties: ClassVar[List[str]] = ["x0", "y0", "fast_axis", "slow_axis"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of DetectorModule from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of DetectorModule from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"x0": obj.get("x0"),
"y0": obj.get("y0"),
"fast_axis": obj.get("fast_axis"),
"slow_axis": obj.get("slow_axis")
})
return _obj

View File

@@ -0,0 +1,40 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import json
from enum import Enum
from typing_extensions import Self
class DetectorModuleDirection(str, Enum):
"""
DetectorModuleDirection
"""
"""
allowed enum values
"""
XP = 'Xp'
XN = 'Xn'
YP = 'Yp'
YN = 'Yn'
@classmethod
def from_json(cls, json_str: str) -> Self:
"""Create an instance of DetectorModuleDirection from a JSON string"""
return cls(json.loads(json_str))

View File

@@ -0,0 +1,88 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, StrictInt
from typing import Any, ClassVar, Dict, List
from typing import Optional, Set
from typing_extensions import Self
class DetectorSelection(BaseModel):
"""
DetectorSelection
""" # noqa: E501
id: StrictInt
__properties: ClassVar[List[str]] = ["id"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of DetectorSelection from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of DetectorSelection from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id")
})
return _obj

View File

@@ -0,0 +1,115 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from typing import Optional, Set
from typing_extensions import Self
class DetectorSettings(BaseModel):
"""
DetectorSettings
""" # noqa: E501
frame_time_us: Annotated[int, Field(strict=True, ge=450)] = Field(description="Interval between consecutive frames.")
count_time_us: Optional[StrictInt] = Field(default=None, description="Integration time of the detector. If not provided count time will be set to maximum value for a given frame time.")
storage_cell_count: Annotated[int, Field(le=16, strict=True, ge=1)]
internal_frame_generator: StrictBool = Field(description="Use internal frame generator in FPGA instead of getting data from a real detector")
internal_frame_generator_images: Annotated[int, Field(le=128, strict=True, ge=1)]
pedestal_g0_frames: Annotated[int, Field(strict=True, ge=0)]
pedestal_g1_frames: Annotated[int, Field(strict=True, ge=0)]
pedestal_g2_frames: Annotated[int, Field(strict=True, ge=0)]
pedestal_g0_rms_limit: Annotated[int, Field(strict=True, ge=0)] = Field(description="Pixels with pedestal G0 RMS above the threshold are marked as masked pixels")
pedestal_window_size: Annotated[int, Field(strict=True, ge=32)] = Field(description="Running average window size for pedestal calculations")
storage_cell_delay_ns: Annotated[int, Field(strict=True, ge=2100)] = Field(description="Delay between two storage cells [ns]")
detector_trigger_delay_ns: Optional[Annotated[int, Field(strict=True, ge=0)]] = Field(default=0, description="Delay between TTL trigger and acquisition start [ns]")
fixed_gain_g1: Optional[StrictBool] = Field(default=False, description="Fix gain to G1 (can be useful for storage cells)")
use_gain_hg0: Optional[StrictBool] = Field(default=False, description="Use high G0 (for low energy applications)")
__properties: ClassVar[List[str]] = ["frame_time_us", "count_time_us", "storage_cell_count", "internal_frame_generator", "internal_frame_generator_images", "pedestal_g0_frames", "pedestal_g1_frames", "pedestal_g2_frames", "pedestal_g0_rms_limit", "pedestal_window_size", "storage_cell_delay_ns", "detector_trigger_delay_ns", "fixed_gain_g1", "use_gain_hg0"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of DetectorSettings from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of DetectorSettings from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"frame_time_us": obj.get("frame_time_us"),
"count_time_us": obj.get("count_time_us"),
"storage_cell_count": obj.get("storage_cell_count") if obj.get("storage_cell_count") is not None else 1,
"internal_frame_generator": obj.get("internal_frame_generator") if obj.get("internal_frame_generator") is not None else False,
"internal_frame_generator_images": obj.get("internal_frame_generator_images") if obj.get("internal_frame_generator_images") is not None else 1,
"pedestal_g0_frames": obj.get("pedestal_g0_frames") if obj.get("pedestal_g0_frames") is not None else 2000,
"pedestal_g1_frames": obj.get("pedestal_g1_frames") if obj.get("pedestal_g1_frames") is not None else 300,
"pedestal_g2_frames": obj.get("pedestal_g2_frames") if obj.get("pedestal_g2_frames") is not None else 300,
"pedestal_g0_rms_limit": obj.get("pedestal_g0_rms_limit") if obj.get("pedestal_g0_rms_limit") is not None else 100,
"pedestal_window_size": obj.get("pedestal_window_size") if obj.get("pedestal_window_size") is not None else 128,
"storage_cell_delay_ns": obj.get("storage_cell_delay_ns") if obj.get("storage_cell_delay_ns") is not None else 5000,
"detector_trigger_delay_ns": obj.get("detector_trigger_delay_ns") if obj.get("detector_trigger_delay_ns") is not None else 0,
"fixed_gain_g1": obj.get("fixed_gain_g1") if obj.get("fixed_gain_g1") is not None else False,
"use_gain_hg0": obj.get("use_gain_hg0") if obj.get("use_gain_hg0") is not None else False
})
return _obj

View File

@@ -0,0 +1,112 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List
from typing import Optional, Set
from typing_extensions import Self
class DetectorStatus(BaseModel):
"""
DetectorStatus
""" # noqa: E501
state: StrictStr = Field(description="Current state of the detector")
powerchip: StrictStr = Field(description="Power on of ASICs")
server_version: StrictStr = Field(description="Detector server (on read-out boards) version")
number_of_triggers_left: StrictInt = Field(description="Remaining triggers to the detector (max of all modules)")
fpga_temp_deg_c: List[StrictInt] = Field(description="Temperature of detector FPGAs", alias="fpga_temp_degC")
high_voltage_v: List[StrictInt] = Field(description="High voltage for detector modules", alias="high_voltage_V")
__properties: ClassVar[List[str]] = ["state", "powerchip", "server_version", "number_of_triggers_left", "fpga_temp_degC", "high_voltage_V"]
@field_validator('state')
def state_validate_enum(cls, value):
"""Validates the enum"""
if value not in set(['Idle', 'Waiting', 'Busy', 'Error']):
raise ValueError("must be one of enum values ('Idle', 'Waiting', 'Busy', 'Error')")
return value
@field_validator('powerchip')
def powerchip_validate_enum(cls, value):
"""Validates the enum"""
if value not in set(['PowerOn', 'PowerOff', 'Partial']):
raise ValueError("must be one of enum values ('PowerOn', 'PowerOff', 'Partial')")
return value
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of DetectorStatus from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of DetectorStatus from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"state": obj.get("state"),
"powerchip": obj.get("powerchip"),
"server_version": obj.get("server_version"),
"number_of_triggers_left": obj.get("number_of_triggers_left"),
"fpga_temp_degC": obj.get("fpga_temp_degC"),
"high_voltage_V": obj.get("high_voltage_V")
})
return _obj

View File

@@ -0,0 +1,38 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import json
from enum import Enum
from typing_extensions import Self
class DetectorType(str, Enum):
"""
DetectorType
"""
"""
allowed enum values
"""
EIGER = 'EIGER'
JUNGFRAU = 'JUNGFRAU'
@classmethod
def from_json(cls, json_str: str) -> Self:
"""Create an instance of DetectorType from a JSON string"""
return cls(json.loads(json_str))

View File

@@ -0,0 +1,97 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List
from typing import Optional, Set
from typing_extensions import Self
class ErrorMessage(BaseModel):
"""
ErrorMessage
""" # noqa: E501
msg: StrictStr = Field(description="Human readable message")
reason: StrictStr = Field(description="Enumerate field for automated analysis")
__properties: ClassVar[List[str]] = ["msg", "reason"]
@field_validator('reason')
def reason_validate_enum(cls, value):
"""Validates the enum"""
if value not in set(['WrongDAQState', 'Other']):
raise ValueError("must be one of enum values ('WrongDAQState', 'Other')")
return value
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of ErrorMessage from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of ErrorMessage from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"msg": obj.get("msg"),
"reason": obj.get("reason")
})
return _obj

View File

@@ -0,0 +1,96 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictFloat, StrictInt
from typing import Any, ClassVar, Dict, List, Optional, Union
from typing import Optional, Set
from typing_extensions import Self
class FpgaStatusInner(BaseModel):
"""
FpgaStatusInner
""" # noqa: E501
eth_link_count: Optional[StrictInt] = None
eth_link_status: Optional[StrictInt] = None
power_usage_w: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="power_usage_W")
fpga_temp_c: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="fpga_temp_C")
hbm_temp_c: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="hbm_temp_C")
__properties: ClassVar[List[str]] = ["eth_link_count", "eth_link_status", "power_usage_W", "fpga_temp_C", "hbm_temp_C"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of FpgaStatusInner from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of FpgaStatusInner from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"eth_link_count": obj.get("eth_link_count"),
"eth_link_status": obj.get("eth_link_status"),
"power_usage_W": obj.get("power_usage_W"),
"fpga_temp_C": obj.get("fpga_temp_C"),
"hbm_temp_C": obj.get("hbm_temp_C")
})
return _obj

View File

@@ -0,0 +1,113 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, field_validator
from typing import Any, ClassVar, Dict, List, Optional, Union
from typing_extensions import Annotated
from typing import Optional, Set
from typing_extensions import Self
class ImageFormatSettings(BaseModel):
"""
ImageFormatSettings
""" # noqa: E501
summation: StrictBool = Field(description="Enable summation of images to a given image_time If disabled images are saved according to original detector speed, but image count is adjusted ")
geometry_transform: StrictBool = Field(description="Place module read-out into their location on composed detector and extend multipixels ")
jungfrau_conversion: StrictBool = Field(description="Convert pixel value in ADU to photon counts/energy Only affects JUNGFRAU detector ")
jungfrau_conversion_factor_ke_v: Optional[Union[Annotated[float, Field(le=500.0, strict=True, ge=0.001)], Annotated[int, Field(le=500, strict=True, ge=1)]]] = Field(default=None, description="Used to convert energy deposited into pixel to counts If not provided incident_energy_keV is used ", alias="jungfrau_conversion_factor_keV")
bit_depth_image: Optional[StrictInt] = Field(default=None, description="Bit depth of resulting image (it doesn't affect the original detector value) If not provided value is adjusted automatically ")
signed_output: Optional[StrictBool] = Field(default=None, description="Controls if pixels have signed output If not provided value is adjusted automatically ")
mask_module_edges: StrictBool = Field(description="Mask 1 pixel on the module boundary ")
mask_chip_edges: StrictBool = Field(description="Mask multipixels on chip boundary ")
__properties: ClassVar[List[str]] = ["summation", "geometry_transform", "jungfrau_conversion", "jungfrau_conversion_factor_keV", "bit_depth_image", "signed_output", "mask_module_edges", "mask_chip_edges"]
@field_validator('bit_depth_image')
def bit_depth_image_validate_enum(cls, value):
"""Validates the enum"""
if value is None:
return value
if value not in set([16, 32]):
raise ValueError("must be one of enum values (16, 32)")
return value
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of ImageFormatSettings from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of ImageFormatSettings from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"summation": obj.get("summation"),
"geometry_transform": obj.get("geometry_transform"),
"jungfrau_conversion": obj.get("jungfrau_conversion"),
"jungfrau_conversion_factor_keV": obj.get("jungfrau_conversion_factor_keV"),
"bit_depth_image": obj.get("bit_depth_image"),
"signed_output": obj.get("signed_output"),
"mask_module_edges": obj.get("mask_module_edges") if obj.get("mask_module_edges") is not None else True,
"mask_chip_edges": obj.get("mask_chip_edges") if obj.get("mask_chip_edges") is not None else True
})
return _obj

View File

@@ -0,0 +1,40 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import json
from enum import Enum
from typing_extensions import Self
class ImagePusherType(str, Enum):
"""
ImagePusherType
"""
"""
allowed enum values
"""
ZEROMQ = 'ZeroMQ'
HDF5 = 'HDF5'
CBOR = 'CBOR'
NONE = 'None'
@classmethod
def from_json(cls, json_str: str) -> Self:
"""Create an instance of ImagePusherType from a JSON string"""
return cls(json.loads(json_str))

View File

@@ -0,0 +1,94 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
class InstrumentMetadata(BaseModel):
"""
Metadata for a measurement instrument
""" # noqa: E501
source_name: StrictStr
source_type: Optional[StrictStr] = Field(default='', description="Type of radiation source. NXmx gives a fixed dictionary, though Jungfraujoch is not enforcing compliance. https://manual.nexusformat.org/classes/base_classes/NXsource.html#nxsource NXsource allows the following: Spallation Neutron Source Pulsed Reactor Neutron Source Reactor Neutron Source Synchrotron X-ray Source Pulsed Muon Source Rotating Anode X-ray Fixed Tube X-ray UV Laser Free-Electron Laser Optical Laser Ion Source UV Plasma Source Metal Jet X-ray ")
instrument_name: StrictStr
pulsed_source: Optional[StrictBool] = Field(default=False, description="Settings specific to XFEL (e.g., every image has to come from TTL trigger, save pulse ID and event code)")
__properties: ClassVar[List[str]] = ["source_name", "source_type", "instrument_name", "pulsed_source"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of InstrumentMetadata from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of InstrumentMetadata from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"source_name": obj.get("source_name"),
"source_type": obj.get("source_type") if obj.get("source_type") is not None else '',
"instrument_name": obj.get("instrument_name"),
"pulsed_source": obj.get("pulsed_source") if obj.get("pulsed_source") is not None else False
})
return _obj

View File

@@ -0,0 +1,148 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from openapi_client.models.azim_int_settings import AzimIntSettings
from openapi_client.models.detector import Detector
from openapi_client.models.detector_settings import DetectorSettings
from openapi_client.models.image_format_settings import ImageFormatSettings
from openapi_client.models.image_pusher_type import ImagePusherType
from openapi_client.models.instrument_metadata import InstrumentMetadata
from openapi_client.models.pcie_devices_inner import PcieDevicesInner
from openapi_client.models.zeromq_settings import ZeromqSettings
from typing import Optional, Set
from typing_extensions import Self
class JfjochSettings(BaseModel):
"""
Default settings for Jungfraujoch software. This structure is used to provide default settings using configuration JSON file and is not used in HTTP.
""" # noqa: E501
pcie: Optional[List[PcieDevicesInner]] = None
zeromq: Optional[ZeromqSettings] = None
instrument: Optional[InstrumentMetadata] = None
detector: List[Detector]
detector_settings: Optional[DetectorSettings] = None
azim_int: Optional[AzimIntSettings] = None
image_format: Optional[ImageFormatSettings] = None
image_buffer_mi_b: Optional[Annotated[int, Field(le=16384, strict=True, ge=128)]] = Field(default=2048, description="Size of internal buffer in MiB for images before they are sent to a stream", alias="image_buffer_MiB")
receiver_threads: Optional[Annotated[int, Field(le=512, strict=True, ge=1)]] = Field(default=64, description="Number of threads used by the receiver")
numa_policy: Optional[StrictStr] = Field(default=None, description="NUMA policy to bind CPUs")
frontend_directory: StrictStr = Field(description="Location of built JavaScript web frontend")
image_pusher: ImagePusherType
__properties: ClassVar[List[str]] = ["pcie", "zeromq", "instrument", "detector", "detector_settings", "azim_int", "image_format", "image_buffer_MiB", "receiver_threads", "numa_policy", "frontend_directory", "image_pusher"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of JfjochSettings from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of each item in pcie (list)
_items = []
if self.pcie:
for _item_pcie in self.pcie:
if _item_pcie:
_items.append(_item_pcie.to_dict())
_dict['pcie'] = _items
# override the default output from pydantic by calling `to_dict()` of zeromq
if self.zeromq:
_dict['zeromq'] = self.zeromq.to_dict()
# override the default output from pydantic by calling `to_dict()` of instrument
if self.instrument:
_dict['instrument'] = self.instrument.to_dict()
# override the default output from pydantic by calling `to_dict()` of each item in detector (list)
_items = []
if self.detector:
for _item_detector in self.detector:
if _item_detector:
_items.append(_item_detector.to_dict())
_dict['detector'] = _items
# override the default output from pydantic by calling `to_dict()` of detector_settings
if self.detector_settings:
_dict['detector_settings'] = self.detector_settings.to_dict()
# override the default output from pydantic by calling `to_dict()` of azim_int
if self.azim_int:
_dict['azim_int'] = self.azim_int.to_dict()
# override the default output from pydantic by calling `to_dict()` of image_format
if self.image_format:
_dict['image_format'] = self.image_format.to_dict()
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of JfjochSettings from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"pcie": [PcieDevicesInner.from_dict(_item) for _item in obj["pcie"]] if obj.get("pcie") is not None else None,
"zeromq": ZeromqSettings.from_dict(obj["zeromq"]) if obj.get("zeromq") is not None else None,
"instrument": InstrumentMetadata.from_dict(obj["instrument"]) if obj.get("instrument") is not None else None,
"detector": [Detector.from_dict(_item) for _item in obj["detector"]] if obj.get("detector") is not None else None,
"detector_settings": DetectorSettings.from_dict(obj["detector_settings"]) if obj.get("detector_settings") is not None else None,
"azim_int": AzimIntSettings.from_dict(obj["azim_int"]) if obj.get("azim_int") is not None else None,
"image_format": ImageFormatSettings.from_dict(obj["image_format"]) if obj.get("image_format") is not None else None,
"image_buffer_MiB": obj.get("image_buffer_MiB") if obj.get("image_buffer_MiB") is not None else 2048,
"receiver_threads": obj.get("receiver_threads") if obj.get("receiver_threads") is not None else 64,
"numa_policy": obj.get("numa_policy"),
"frontend_directory": obj.get("frontend_directory"),
"image_pusher": obj.get("image_pusher") if obj.get("image_pusher") is not None else ImagePusherType.NONE
})
return _obj

View File

@@ -0,0 +1,133 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional, Union
from typing_extensions import Annotated
from typing import Optional, Set
from typing_extensions import Self
class MeasurementStatistics(BaseModel):
"""
MeasurementStatistics
""" # noqa: E501
file_prefix: Optional[StrictStr] = None
run_number: Optional[StrictInt] = Field(default=None, description="Number of data collection run. This can be either automatically incremented or provided externally for each data collection. ")
experiment_group: Optional[StrictStr] = Field(default=None, description="Name of group owning the data (e.g. p-group or proposal number). ")
images_expected: Optional[StrictInt] = None
images_collected: Optional[StrictInt] = Field(default=None, description="Images collected by the receiver. This number will be lower than images expected if there were issues with data collection performance. ")
images_sent: Optional[StrictInt] = Field(default=None, description="Images sent to the writer. The value does not include images discarded by lossy compression filter and images not forwarded due to full ZeroMQ queue. ")
images_discarded_lossy_compression: Optional[StrictInt] = Field(default=None, description="Images discarded by the lossy compression filter")
max_image_number_sent: Optional[StrictInt] = None
collection_efficiency: Optional[Union[Annotated[float, Field(le=1.0, strict=True, ge=0.0)], Annotated[int, Field(le=1, strict=True, ge=0)]]] = None
compression_ratio: Optional[Union[Annotated[float, Field(strict=True, ge=0.0)], Annotated[int, Field(strict=True, ge=0)]]] = None
cancelled: Optional[StrictBool] = None
max_receiver_delay: Optional[StrictInt] = None
indexing_rate: Optional[Union[StrictFloat, StrictInt]] = None
detector_width: Optional[StrictInt] = None
detector_height: Optional[StrictInt] = None
detector_pixel_depth: Optional[StrictInt] = None
bkg_estimate: Optional[Union[StrictFloat, StrictInt]] = None
unit_cell: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["file_prefix", "run_number", "experiment_group", "images_expected", "images_collected", "images_sent", "images_discarded_lossy_compression", "max_image_number_sent", "collection_efficiency", "compression_ratio", "cancelled", "max_receiver_delay", "indexing_rate", "detector_width", "detector_height", "detector_pixel_depth", "bkg_estimate", "unit_cell"]
@field_validator('detector_pixel_depth')
def detector_pixel_depth_validate_enum(cls, value):
"""Validates the enum"""
if value is None:
return value
if value not in set([2, 4]):
raise ValueError("must be one of enum values (2, 4)")
return value
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of MeasurementStatistics from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of MeasurementStatistics from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"file_prefix": obj.get("file_prefix"),
"run_number": obj.get("run_number"),
"experiment_group": obj.get("experiment_group"),
"images_expected": obj.get("images_expected"),
"images_collected": obj.get("images_collected"),
"images_sent": obj.get("images_sent"),
"images_discarded_lossy_compression": obj.get("images_discarded_lossy_compression"),
"max_image_number_sent": obj.get("max_image_number_sent"),
"collection_efficiency": obj.get("collection_efficiency"),
"compression_ratio": obj.get("compression_ratio"),
"cancelled": obj.get("cancelled"),
"max_receiver_delay": obj.get("max_receiver_delay"),
"indexing_rate": obj.get("indexing_rate"),
"detector_width": obj.get("detector_width"),
"detector_height": obj.get("detector_height"),
"detector_pixel_depth": obj.get("detector_pixel_depth"),
"bkg_estimate": obj.get("bkg_estimate"),
"unit_cell": obj.get("unit_cell")
})
return _obj

View File

@@ -0,0 +1,90 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
class PcieDevicesInner(BaseModel):
"""
PcieDevicesInner
""" # noqa: E501
blk: Optional[StrictStr] = Field(default=None, description="Block device name")
ipv4: Optional[StrictStr] = Field(default=None, description="IPv4 address of the block device")
__properties: ClassVar[List[str]] = ["blk", "ipv4"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of PcieDevicesInner from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of PcieDevicesInner from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"blk": obj.get("blk"),
"ipv4": obj.get("ipv4")
})
return _obj

View File

@@ -0,0 +1,92 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, StrictFloat, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Union
from typing import Optional, Set
from typing_extensions import Self
class Plot(BaseModel):
"""
x and y coordinates for plotting, it is OK to assume that both arrays have the same size; layout is optimized for Plotly
""" # noqa: E501
title: StrictStr
x: List[Union[StrictFloat, StrictInt]]
y: List[Union[StrictFloat, StrictInt]]
__properties: ClassVar[List[str]] = ["title", "x", "y"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of Plot from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of Plot from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"title": obj.get("title") if obj.get("title") is not None else '',
"x": obj.get("x"),
"y": obj.get("y")
})
return _obj

View File

@@ -0,0 +1,98 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from openapi_client.models.plot import Plot
from typing import Optional, Set
from typing_extensions import Self
class Plots(BaseModel):
"""
Plots
""" # noqa: E501
title: Optional[StrictStr] = None
plot: List[Plot]
__properties: ClassVar[List[str]] = ["title", "plot"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of Plots from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of each item in plot (list)
_items = []
if self.plot:
for _item_plot in self.plot:
if _item_plot:
_items.append(_item_plot.to_dict())
_dict['plot'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of Plots from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"title": obj.get("title"),
"plot": [Plot.from_dict(_item) for _item in obj["plot"]] if obj.get("plot") is not None else None
})
return _obj

View File

@@ -0,0 +1,101 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictBool
from typing import Any, ClassVar, Dict, List, Optional, Union
from typing_extensions import Annotated
from typing import Optional, Set
from typing_extensions import Self
class PreviewSettings(BaseModel):
"""
Settings for JPEG rendering of preview images
""" # noqa: E501
saturation: Annotated[int, Field(le=65535, strict=True, ge=0)] = Field(description="Saturation value to set contrast in the preview image")
show_spots: Optional[StrictBool] = Field(default=True, description="Show spot finding results on the image")
show_roi: Optional[StrictBool] = Field(default=False, description="Show ROI areas on the image")
jpeg_quality: Optional[Annotated[int, Field(le=100, strict=True, ge=0)]] = Field(default=100, description="Quality of JPEG image (100 - highest; 0 - lowest)")
show_indexed: Optional[StrictBool] = Field(default=False, description="Preview indexed images only")
show_user_mask: Optional[StrictBool] = Field(default=False, description="Show user mask")
resolution_ring: Optional[Union[Annotated[float, Field(le=100.0, strict=True, ge=0.1)], Annotated[int, Field(le=100, strict=True, ge=1)]]] = 0.1
__properties: ClassVar[List[str]] = ["saturation", "show_spots", "show_roi", "jpeg_quality", "show_indexed", "show_user_mask", "resolution_ring"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of PreviewSettings from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of PreviewSettings from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"saturation": obj.get("saturation"),
"show_spots": obj.get("show_spots") if obj.get("show_spots") is not None else True,
"show_roi": obj.get("show_roi") if obj.get("show_roi") is not None else False,
"jpeg_quality": obj.get("jpeg_quality") if obj.get("jpeg_quality") is not None else 100,
"show_indexed": obj.get("show_indexed") if obj.get("show_indexed") is not None else False,
"show_user_mask": obj.get("show_user_mask") if obj.get("show_user_mask") is not None else False,
"resolution_ring": obj.get("resolution_ring") if obj.get("resolution_ring") is not None else 0.1
})
return _obj

View File

@@ -0,0 +1,97 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field
from typing import Any, ClassVar, Dict, List
from typing_extensions import Annotated
from typing import Optional, Set
from typing_extensions import Self
class RoiBox(BaseModel):
"""
Box ROI
""" # noqa: E501
name: Annotated[str, Field(min_length=1, strict=True)] = Field(description="Name for the ROI; used in the plots")
min_x_pxl: Annotated[int, Field(strict=True, ge=0)] = Field(description="Lower bound (inclusive) in X coordinate for the box")
max_x_pxl: Annotated[int, Field(strict=True, ge=0)] = Field(description="Upper bound (inclusive) in X coordinate for the box")
min_y_pxl: Annotated[int, Field(strict=True, ge=0)] = Field(description="Lower bound (inclusive) in Y coordinate for the box")
max_y_pxl: Annotated[int, Field(strict=True, ge=0)] = Field(description="Upper bound (inclusive) in Y coordinate for the box")
__properties: ClassVar[List[str]] = ["name", "min_x_pxl", "max_x_pxl", "min_y_pxl", "max_y_pxl"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of RoiBox from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of RoiBox from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"name": obj.get("name"),
"min_x_pxl": obj.get("min_x_pxl"),
"max_x_pxl": obj.get("max_x_pxl"),
"min_y_pxl": obj.get("min_y_pxl"),
"max_y_pxl": obj.get("max_y_pxl")
})
return _obj

View File

@@ -0,0 +1,97 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from openapi_client.models.roi_box import RoiBox
from typing import Optional, Set
from typing_extensions import Self
class RoiBoxList(BaseModel):
"""
List of box ROIs
""" # noqa: E501
rois: Optional[Annotated[List[RoiBox], Field(max_length=32)]] = None
__properties: ClassVar[List[str]] = ["rois"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of RoiBoxList from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of each item in rois (list)
_items = []
if self.rois:
for _item_rois in self.rois:
if _item_rois:
_items.append(_item_rois.to_dict())
_dict['rois'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of RoiBoxList from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"rois": [RoiBox.from_dict(_item) for _item in obj["rois"]] if obj.get("rois") is not None else None
})
return _obj

View File

@@ -0,0 +1,95 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictFloat, StrictInt
from typing import Any, ClassVar, Dict, List, Union
from typing_extensions import Annotated
from typing import Optional, Set
from typing_extensions import Self
class RoiCircle(BaseModel):
"""
Circular ROI
""" # noqa: E501
name: Annotated[str, Field(min_length=1, strict=True)] = Field(description="Name for the ROI; used in the plots")
center_x_pxl: Union[StrictFloat, StrictInt] = Field(description="X coordinate of center of the circle [pixels]")
center_y_pxl: Union[StrictFloat, StrictInt] = Field(description="Y coordinate of center of the circle [pixels]")
radius_pxl: Union[Annotated[float, Field(strict=True, gt=0.0)], Annotated[int, Field(strict=True, gt=0)]] = Field(description="Radius of the circle [pixels]")
__properties: ClassVar[List[str]] = ["name", "center_x_pxl", "center_y_pxl", "radius_pxl"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of RoiCircle from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of RoiCircle from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"name": obj.get("name"),
"center_x_pxl": obj.get("center_x_pxl"),
"center_y_pxl": obj.get("center_y_pxl"),
"radius_pxl": obj.get("radius_pxl")
})
return _obj

View File

@@ -0,0 +1,97 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field
from typing import Any, ClassVar, Dict, List
from typing_extensions import Annotated
from openapi_client.models.roi_circle import RoiCircle
from typing import Optional, Set
from typing_extensions import Self
class RoiCircleList(BaseModel):
"""
List of circular ROIs
""" # noqa: E501
rois: Annotated[List[RoiCircle], Field(max_length=32)]
__properties: ClassVar[List[str]] = ["rois"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of RoiCircleList from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of each item in rois (list)
_items = []
if self.rois:
for _item_rois in self.rois:
if _item_rois:
_items.append(_item_rois.to_dict())
_dict['rois'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of RoiCircleList from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"rois": [RoiCircle.from_dict(_item) for _item in obj["rois"]] if obj.get("rois") is not None else None
})
return _obj

View File

@@ -0,0 +1,95 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictFloat, StrictInt
from typing import Any, ClassVar, Dict, List, Optional, Union
from typing_extensions import Annotated
from typing import Optional, Set
from typing_extensions import Self
class RotationAxis(BaseModel):
"""
Definition of a crystal rotation axis
""" # noqa: E501
name: Optional[Annotated[str, Field(min_length=1, strict=True)]] = Field(default='omega', description="Name of rotation axis (e.g., omega, phi)")
step: Union[StrictFloat, StrictInt] = Field(description="Angle step in degrees")
start: Optional[Union[StrictFloat, StrictInt]] = Field(default=0, description="Start angle in degrees")
vector: Annotated[List[Union[StrictFloat, StrictInt]], Field(min_length=3, max_length=3)] = Field(description="Rotation axis")
__properties: ClassVar[List[str]] = ["name", "step", "start", "vector"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of RotationAxis from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of RotationAxis from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"name": obj.get("name") if obj.get("name") is not None else 'omega',
"step": obj.get("step"),
"start": obj.get("start") if obj.get("start") is not None else 0,
"vector": obj.get("vector")
})
return _obj

View File

@@ -0,0 +1,109 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt
from typing import Any, ClassVar, Dict, List, Optional, Union
from typing_extensions import Annotated
from typing import Optional, Set
from typing_extensions import Self
class SpotFindingSettings(BaseModel):
"""
SpotFindingSettings
""" # noqa: E501
enable: StrictBool = Field(description="Enable spot finding. This is temporary setting, i.e. can be changed anytime during data collection. Even if disabled spot finding information will still be send and written, though always with zero spots. ")
indexing: StrictBool = Field(description="Enable indexing. This is temporary setting, i.e. can be changed anytime during data collection. ")
filter_powder_rings: Optional[StrictBool] = Field(default=False, description="Filter spots which form powder rings (e.g., ice rings)")
min_spot_count_powder_ring: Optional[Annotated[int, Field(strict=True, ge=5)]] = Field(default=None, description="Minimum number of spots to consider a thin resolution shell (0.01 A^-1) a powder ring and filter out.")
signal_to_noise_threshold: Union[Annotated[float, Field(strict=True, ge=0)], Annotated[int, Field(strict=True, ge=0)]]
photon_count_threshold: Annotated[int, Field(strict=True, ge=0)]
min_pix_per_spot: Annotated[int, Field(strict=True, ge=1)]
max_pix_per_spot: Annotated[int, Field(strict=True, ge=1)]
high_resolution_limit: Union[StrictFloat, StrictInt]
low_resolution_limit: Union[StrictFloat, StrictInt]
indexing_tolerance: Union[Annotated[float, Field(le=1.0, strict=True, ge=0.0)], Annotated[int, Field(le=1, strict=True, ge=0)]] = Field(description="Acceptance tolerance for spots after the indexing run - the larger the number, the more spots will be accepted")
__properties: ClassVar[List[str]] = ["enable", "indexing", "filter_powder_rings", "min_spot_count_powder_ring", "signal_to_noise_threshold", "photon_count_threshold", "min_pix_per_spot", "max_pix_per_spot", "high_resolution_limit", "low_resolution_limit", "indexing_tolerance"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of SpotFindingSettings from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of SpotFindingSettings from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"enable": obj.get("enable") if obj.get("enable") is not None else True,
"indexing": obj.get("indexing") if obj.get("indexing") is not None else True,
"filter_powder_rings": obj.get("filter_powder_rings") if obj.get("filter_powder_rings") is not None else False,
"min_spot_count_powder_ring": obj.get("min_spot_count_powder_ring"),
"signal_to_noise_threshold": obj.get("signal_to_noise_threshold"),
"photon_count_threshold": obj.get("photon_count_threshold"),
"min_pix_per_spot": obj.get("min_pix_per_spot"),
"max_pix_per_spot": obj.get("max_pix_per_spot"),
"high_resolution_limit": obj.get("high_resolution_limit"),
"low_resolution_limit": obj.get("low_resolution_limit"),
"indexing_tolerance": obj.get("indexing_tolerance")
})
return _obj

View File

@@ -0,0 +1,95 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from typing import Optional, Set
from typing_extensions import Self
class StandardDetectorGeometry(BaseModel):
"""
Regular rectangular geometry, first module is in the bottom left corner of the detector
""" # noqa: E501
nmodules: Annotated[int, Field(strict=True, ge=1)] = Field(description="Number of modules in the detector")
gap_x: Optional[Annotated[int, Field(strict=True, ge=0)]] = Field(default=8, description="Gap size in X direction [pixels]")
gap_y: Optional[Annotated[int, Field(strict=True, ge=0)]] = Field(default=36, description="Gap size in Y direction [pixels]")
modules_in_row: Optional[Annotated[int, Field(strict=True, ge=1)]] = Field(default=1, description="Number of modules in one row")
__properties: ClassVar[List[str]] = ["nmodules", "gap_x", "gap_y", "modules_in_row"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of StandardDetectorGeometry from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of StandardDetectorGeometry from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"nmodules": obj.get("nmodules"),
"gap_x": obj.get("gap_x") if obj.get("gap_x") is not None else 8,
"gap_y": obj.get("gap_y") if obj.get("gap_y") is not None else 36,
"modules_in_row": obj.get("modules_in_row") if obj.get("modules_in_row") is not None else 1
})
return _obj

View File

@@ -0,0 +1,95 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from typing import Optional, Set
from typing_extensions import Self
class ZeromqSettings(BaseModel):
"""
ZeroMQ configuration for Jungfraujoch software. This structure is used to provide default settings using configuration JSON file and is not used in HTTP.
""" # noqa: E501
send_watermark: Optional[Annotated[int, Field(le=16384, strict=True, ge=2)]] = Field(default=100, description="Watermark for ZeroMQ send queue (number of outstanding messages queued on Jungfraujoch server per queue)")
image_socket: Optional[List[StrictStr]] = Field(default=None, description="PUSH ZeroMQ socket for images. In case multiple sockets are provided, images are streamed over multiple sockets. Images are serialized using CBOR. Address follows ZeroMQ convention for sockets - in practice ipc://<socket file> and tpc://<IP address>:<port> sockets are OK. 0.0.0.0 instead of IP address is accepted and means listening on all network interfaces. ")
preview_socket: Optional[StrictStr] = Field(default=None, description="PUB ZeroMQ socket for preview images. This socket operates at a reduced frame rate. Images are serialized using CBOR. Address follows ZeroMQ convention for sockets - in practice ipc://<socket file> and tpc://<IP address>:<port> sockets are OK. 0.0.0.0 instead of IP address is accepted and means listening on all network interfaces. ")
writer_notification_socket: Optional[StrictStr] = Field(default=None, description="PULL ZeroMQ socket for notifications from writer that it finished operation. This allows Jungfraujoch to operate in a synchronous manner, with end of acquisition being also end of writing. Address follows ZeroMQ convention for sockets - in practice ipc://<socket file> and tpc://<IP address>:<port> sockets are OK. 0.0.0.0 instead of IP address should be avoided, as this socket address is forwarded to the writer process via START ZerOMQ message and in case of multiple ineterfaces the address might be ambigous. Using * (star) instead of port number is allowed and it means a random free port number. ")
__properties: ClassVar[List[str]] = ["send_watermark", "image_socket", "preview_socket", "writer_notification_socket"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of ZeromqSettings from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of ZeromqSettings from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"send_watermark": obj.get("send_watermark") if obj.get("send_watermark") is not None else 100,
"image_socket": obj.get("image_socket"),
"preview_socket": obj.get("preview_socket"),
"writer_notification_socket": obj.get("writer_notification_socket")
})
return _obj

View File

View File

@@ -0,0 +1,258 @@
# coding: utf-8
"""
Jungfraujoch
Jungfraujoch Broker Web API
The version of the OpenAPI document: 1.0.0-rc.13
Contact: filip.leonarski@psi.ch
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import io
import json
import re
import ssl
import urllib3
from openapi_client.exceptions import ApiException, ApiValueError
SUPPORTED_SOCKS_PROXIES = {"socks5", "socks5h", "socks4", "socks4a"}
RESTResponseType = urllib3.HTTPResponse
def is_socks_proxy_url(url):
if url is None:
return False
split_section = url.split("://")
if len(split_section) < 2:
return False
else:
return split_section[0].lower() in SUPPORTED_SOCKS_PROXIES
class RESTResponse(io.IOBase):
def __init__(self, resp) -> None:
self.response = resp
self.status = resp.status
self.reason = resp.reason
self.data = None
def read(self):
if self.data is None:
self.data = self.response.data
return self.data
def getheaders(self):
"""Returns a dictionary of the response headers."""
return self.response.headers
def getheader(self, name, default=None):
"""Returns a given response header."""
return self.response.headers.get(name, default)
class RESTClientObject:
def __init__(self, configuration) -> None:
# urllib3.PoolManager will pass all kw parameters to connectionpool
# https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501
# https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501
# Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501
# cert_reqs
if configuration.verify_ssl:
cert_reqs = ssl.CERT_REQUIRED
else:
cert_reqs = ssl.CERT_NONE
pool_args = {
"cert_reqs": cert_reqs,
"ca_certs": configuration.ssl_ca_cert,
"cert_file": configuration.cert_file,
"key_file": configuration.key_file,
}
if configuration.assert_hostname is not None:
pool_args['assert_hostname'] = (
configuration.assert_hostname
)
if configuration.retries is not None:
pool_args['retries'] = configuration.retries
if configuration.tls_server_name:
pool_args['server_hostname'] = configuration.tls_server_name
if configuration.socket_options is not None:
pool_args['socket_options'] = configuration.socket_options
if configuration.connection_pool_maxsize is not None:
pool_args['maxsize'] = configuration.connection_pool_maxsize
# https pool manager
self.pool_manager: urllib3.PoolManager
if configuration.proxy:
if is_socks_proxy_url(configuration.proxy):
from urllib3.contrib.socks import SOCKSProxyManager
pool_args["proxy_url"] = configuration.proxy
pool_args["headers"] = configuration.proxy_headers
self.pool_manager = SOCKSProxyManager(**pool_args)
else:
pool_args["proxy_url"] = configuration.proxy
pool_args["proxy_headers"] = configuration.proxy_headers
self.pool_manager = urllib3.ProxyManager(**pool_args)
else:
self.pool_manager = urllib3.PoolManager(**pool_args)
def request(
self,
method,
url,
headers=None,
body=None,
post_params=None,
_request_timeout=None
):
"""Perform requests.
:param method: http request method
:param url: http request url
:param headers: http request headers
:param body: request json body, for `application/json`
:param post_params: request post parameters,
`application/x-www-form-urlencoded`
and `multipart/form-data`
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
"""
method = method.upper()
assert method in [
'GET',
'HEAD',
'DELETE',
'POST',
'PUT',
'PATCH',
'OPTIONS'
]
if post_params and body:
raise ApiValueError(
"body parameter cannot be used with post_params parameter."
)
post_params = post_params or {}
headers = headers or {}
timeout = None
if _request_timeout:
if isinstance(_request_timeout, (int, float)):
timeout = urllib3.Timeout(total=_request_timeout)
elif (
isinstance(_request_timeout, tuple)
and len(_request_timeout) == 2
):
timeout = urllib3.Timeout(
connect=_request_timeout[0],
read=_request_timeout[1]
)
try:
# For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE`
if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']:
# no content type provided or payload is json
content_type = headers.get('Content-Type')
if (
not content_type
or re.search('json', content_type, re.IGNORECASE)
):
request_body = None
if body is not None:
request_body = json.dumps(body)
r = self.pool_manager.request(
method,
url,
body=request_body,
timeout=timeout,
headers=headers,
preload_content=False
)
elif content_type == 'application/x-www-form-urlencoded':
r = self.pool_manager.request(
method,
url,
fields=post_params,
encode_multipart=False,
timeout=timeout,
headers=headers,
preload_content=False
)
elif content_type == 'multipart/form-data':
# must del headers['Content-Type'], or the correct
# Content-Type which generated by urllib3 will be
# overwritten.
del headers['Content-Type']
# Ensures that dict objects are serialized
post_params = [(a, json.dumps(b)) if isinstance(b, dict) else (a,b) for a, b in post_params]
r = self.pool_manager.request(
method,
url,
fields=post_params,
encode_multipart=True,
timeout=timeout,
headers=headers,
preload_content=False
)
# Pass a `string` parameter directly in the body to support
# other content types than JSON when `body` argument is
# provided in serialized form.
elif isinstance(body, str) or isinstance(body, bytes):
r = self.pool_manager.request(
method,
url,
body=body,
timeout=timeout,
headers=headers,
preload_content=False
)
elif headers['Content-Type'] == 'text/plain' and isinstance(body, bool):
request_body = "true" if body else "false"
r = self.pool_manager.request(
method,
url,
body=request_body,
preload_content=False,
timeout=timeout,
headers=headers)
else:
# Cannot generate the request from given parameters
msg = """Cannot prepare a request message for provided
arguments. Please check that your arguments match
declared content type."""
raise ApiException(status=0, reason=msg)
# For `GET`, `HEAD`
else:
r = self.pool_manager.request(
method,
url,
fields={},
timeout=timeout,
headers=headers,
preload_content=False
)
except urllib3.exceptions.SSLError as e:
msg = "\n".join([type(e).__name__, str(e)])
raise ApiException(status=0, reason=msg)
return RESTResponse(r)