Skip to content

Session

A Session is an authenticated connection to a Lablink instance, obtained from Instance.login. The session is the main object for interacting with the Lablink: listing and claiming instruments, starting measurements, retrieving stored measurements, etc.

Some calls are cached. For example, Session.instruments holds the result of the most recent Session.list_instruments call. They may be stale or empty. Call those methods to refresh.

Attribute Updated by
Session.info Session.get_info
Session.instrument_info Session.list_instruments, Session.get_instrument_info
Session.instruments Session.list_instruments, Session.get_instrument_info

Claims are held until released. Use async with so the claim is released even if the measurement raises an exception:

instruments = await session.list_instruments()
instrument, *_ = instruments

async with await instrument.claim() as claim:
    job = await claim.start_measurement(method=method)
    measurement = await job   # claim released here

data = await measurement.get_data()

To work with several instruments at once, use the batch methods on the session. session.claim(instruments) returns an InstrumentClaimBatch and session.start_measurement(claims, method=...) one MeasurementJob per instrument:

instruments = await session.list_instruments()

async with await session.claim(instruments) as claims:
    jobs = await session.start_measurement(claims, method=method)
    refs = await asyncio.gather(*jobs)   # claims released here

data = [await ref.get_data() for ref in refs]

Tip

Similarly named methods exist on both Session and Instrument. As a guideline, use Session for batch (multi-instrument) operations, use Instrument for single-instrument operations.

pypalmsens.lablink.Session

Session(host: str, token: str, port: int = 5000)

A session managing a connection to a Lablink instance.

Use Session.list_instruments to list instruments, Session.claim to claim them, and Session.start_measurement to run measurements.

Parameters:

  • host

    (str) –

    Base URL of the Lablink instance (e.g. 'lablink.example.com').

  • token

    (str) –

    Token used to authenticate API calls.

  • port

    (int, default: 5000 ) –

    Port for the API server, defaults to 5000.

Methods:

Attributes:

Source code in src/pypalmsens/lablink/_session.py
51
52
53
54
55
56
57
def __init__(
    self,
    host: str,
    token: str,
    port: int = 5000,
):
    self._init(HttpClient(f'{host}:{port}/api/v1', token=token))

info property

info: LablinkInfo | None

Last fetched metadata, or None if not yet fetched.

Use get_info to (re)populate this.

instrument_info property

instrument_info: dict[str, dict[str, Any]]

The instrument info from the most recent get_instrument_info call.

May be stale or empty. Use list_instruments or get_instrument_info to update the cache.

instruments property

instruments: list[Instrument]

The instruments from the most recent list_instruments call.

May be stale or empty. Use list_instruments or get_instrument_info update the cache.

abort_measurement async

abort_measurement(jobs: Sequence[MeasurementJob]) -> None

Abort a running measurement and cancel job.

Parameters:

Source code in src/pypalmsens/lablink/_session.py
383
384
385
386
387
388
389
390
391
392
393
394
395
396
async def abort_measurement(self, jobs: Sequence[MeasurementJob]) -> None:
    """Abort a running measurement and cancel job.

    Parameters
    ----------
    jobs : Sequence[MeasurementJob]
        The measurement to abort.
    """
    payload = {
        'AllInstrumentsMustSucceed': True,
        'InstrumentProperties': {job.serial_number: {} for job in jobs},
    }

    await self._http.post('/Instrument/AbortMeasurement', json=payload)

claim async

Claim multiple instruments.

The claim is held until you release it, or until the enclosing async with block exits.

Parameters:

  • instruments

    (Sequence[Instrument]) –

    The instruments to claim.

  • auto_release

    (bool, default: False ) –

    If True, the server releases the claims after measurement ends.

Returns:

  • claims ( ClaimBatch ) –

    A batch containing the instrument claims.

Source code in src/pypalmsens/lablink/_session.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
async def claim(
    self, instruments: Sequence[Instrument], *, auto_release: bool = False
) -> InstrumentClaimBatch:
    """Claim multiple instruments.

    The claim is held until you release it, or until the enclosing
    `async with` block exits.

    Parameters
    ----------
    instruments : Sequence[Instrument]
        The instruments to claim.
    auto_release : bool, optional
        If True, the server releases the claims after measurement ends.

    Returns
    -------
    claims : ClaimBatch
        A batch containing the instrument claims.
    """
    method = 'Claim' if auto_release else 'ManualClaim'

    props = {instrument.serial_number: EmptyProperty() for instrument in instruments}
    payload = SimpleInstrumentsCommand(
        InstrumentProperties=props, AllInstrumentsMustSucceed=True
    )

    await self._http.post(f'/Instruments/{method}', json=payload.model_dump())

    claims = [InstrumentClaim(instrument.serial_number, self) for instrument in instruments]
    return InstrumentClaimBatch(claims)

delete_measurements async

delete_measurements(measurements: list[Measurement | str]) -> None

Delete measurement data from Lablink.

Measurements are deleted by their unique identifier (GUID), either using the guid attribute from the Measurement instance or directly as a string.

Parameters:

  • measurements

    (list[Measurement | str]) –

    A list of measurements to delete. Each item in the list can be either an instance of Measurement or a GUID string.

Source code in src/pypalmsens/lablink/_session.py
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
async def delete_measurements(self, measurements: list[Measurement | str]) -> None:
    """Delete measurement data from Lablink.

    Measurements are deleted by their unique identifier (GUID),
    either using the `guid` attribute from the `Measurement` instance or
    directly as a string.

    Parameters
    ----------
    measurements : list[Measurement | str]
        A list of measurements to delete. Each item in the list can be
        either an instance of `Measurement` or a GUID string.
    """
    payload = [
        item.guid if isinstance(item, Measurement) else item for item in measurements
    ]

    await self._http.delete('/Measurements/BatchDelete', json=payload)

delete_user async

delete_user(user: UserInfo | str) -> None

Delete a user by their identifier.

Users are deleted using their unique identifier (GUID), either using the guid attribute from the UserInfo instance or directly as a string.

Parameters:

  • user

    (UserInfo | str) –

    The identifier for the user to delete. This can be either an instance of UserInfo, or a GUID string.

Source code in src/pypalmsens/lablink/_session.py
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
async def delete_user(self, user: UserInfo | str) -> None:
    """Delete a user by their identifier.

    Users are deleted using their unique identifier (GUID),
    either using the `guid` attribute from the `UserInfo` instance or
    directly as a string.

    Parameters
    ----------
    user: UserInfo | str
        The identifier for the user to delete. This can be either an instance
        of UserInfo, or a GUID string.
    """
    if isinstance(user, UserInfo):
        guid = user.guid
    else:
        guid = user

    await self._http.delete(f'/Users/{guid}')

get_info async

get_info() -> LablinkInfo

Fetch metadata for this instance.

Source code in src/pypalmsens/lablink/_session.py
82
83
84
85
86
async def get_info(self) -> LablinkInfo:
    """Fetch metadata for this instance."""
    data = await self._http.get('/Home/GetInfo')
    self._info = LablinkInfo.from_wire(data.json())
    return self._info

get_instrument_info async

get_instrument_info() -> dict[str, dict[str, Any]]

Get info dictionary for currently attached instruments.

Refreshes the instrument_info dictionary and caches it in-place.

Returns:

  • dict[str, dict[str, Any]] –

    A mapping from serial number to instrument info for each currently attached instrument.

Source code in src/pypalmsens/lablink/_session.py
114
115
116
117
118
119
120
121
122
123
124
125
126
async def get_instrument_info(self) -> dict[str, dict[str, Any]]:
    """Get info dictionary for currently attached instruments.

    Refreshes the [instrument_info][] dictionary and caches it in-place.

    Returns
    -------
    dict[str, dict[str, Any]]
        A mapping from serial number to instrument info for each currently
        attached instrument.
    """
    await self._get_instruments()
    return self._instrument_info

get_measurement async

get_measurement(measurement: Measurement | str) -> Dataset | DataTree

Fetch a specific measurement by its reference ID.

Parameters:

  • measurement

    (MeasurementRef | str) –

    The measurement to fetch. Can be a MeasurementRef or its string ID.

Returns:

Source code in src/pypalmsens/lablink/_session.py
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
async def get_measurement(self, measurement: Measurement | str) -> xr.Dataset | xr.DataTree:
    """Fetch a specific measurement by its reference ID.

    Parameters
    ----------
    measurement : MeasurementRef | str
        The measurement to fetch. Can be a MeasurementRef or its string ID.

    Returns
    -------
    xr.Dataset | xr.DataTree
        The parsed measurement data as an xarray object.
    """
    import numpy as np

    if isinstance(measurement, Measurement):
        guid = measurement.guid
    else:
        guid = measurement

    response = await self._http.get(f'/Measurements/{guid}')
    parsed = MeasurementResult.model_validate(response.json())

    # metadata = _to_measurement_metadata(parsed)

    datasets = []

    assert parsed.RawDataSets

    for dataset in parsed.RawDataSets:
        data_vars = {}
        attrs: dict[str, Any] = {}

        dataset, *_ = parsed.RawDataSets
        dataset_id = dataset.DataSetId

        assert dataset.DataArrays

        for array in dataset.DataArrays:
            assert array.DataValueType
            array_type = array.DataValueType.name
            # TODO, what is array ID used for?
            # array_id = array.DataArrayId
            values_id = array.DataValuesId

            response = await self._http.get(f'DataSets/{dataset_id}/{values_id}')
            raw = response.content

            if array_type == 'CurrentRange':
                pairs = np.frombuffer(raw, dtype=np.int32).reshape(-1, 2)
                data = pairs[:, 0]
                # TODO: what is other? factor? exponent? How to store.
                # other = pairs[:, 0]

            elif array_type in (
                'AppliedPotential',
                'Charge',
                'MeasuredCurrent',
                'AuxiliaryPotential',
                'ReverseCurrent',
                'ForwardCurrent',
            ):
                data = np.frombuffer(raw, dtype=np.float64)  # little-endian float64

            elif array_type in (
                'TimingStatus',
                'CurrentReadingStatus',
                'ForwardCurrentReadingStatus',
                'ReverseCurrentReadingStatus',
            ):
                data = np.frombuffer(raw, dtype=np.int8)  # int enum (8-bit signed integer)

            elif array_type in ('Index', 'CycleIndex', 'LevelIndex'):
                data = np.frombuffer(raw, dtype=np.int32)  # int enum (32 bit signed)

            elif array_type == 'Timestamp':
                ticks = np.frombuffer(raw, dtype=np.int64)  # 100-ns ticks
                data = ticks * 1e-7  # seconds

            else:
                print(f'Unknown data type: {array_type=}')
                print('  len:', len(response.content))
                print('  hex:', response.content[:32].hex())
                continue

            data_vars[array_type] = ('point', data, {'unit': '...'})

        coords = {'point': range(len(data))}

        ds = xr.Dataset(data_vars=data_vars, coords=coords, attrs=attrs)
        datasets.append(ds)

    if len(datasets) > 1:
        data = xr.concat(datasets, pd.Index(len(datasets), name='new_dim'))
    else:
        data = datasets[0]

    return data

list_instruments async

list_instruments() -> list[Instrument]

List currently attached instruments.

Refreshes the instruments list.

Returns:

  • list of Instrument –

    A list of currently attached instruments.

Source code in src/pypalmsens/lablink/_session.py
128
129
130
131
132
133
134
135
136
137
138
139
async def list_instruments(self) -> list[Instrument]:
    """List currently attached instruments.

    Refreshes the [instruments][] list.

    Returns
    -------
    list of Instrument
        A list of currently attached instruments.
    """
    await self._get_instruments()
    return self._instruments

list_measurements async

list_measurements() -> list[Measurement]

List all measurements.

Returns:

  • list of MeasurementRef –

    A list of measurement references.

Source code in src/pypalmsens/lablink/_session.py
188
189
190
191
192
193
194
195
196
197
198
199
async def list_measurements(self) -> list[Measurement]:
    """List all measurements.

    Returns
    -------
    list of MeasurementRef
        A list of measurement references.
    """
    data = await self._http.get('/Measurements')
    refs = [MeasurementListResult.model_validate(item) for item in data.json()]
    # TODO: Expose `MeasurementListResult` data via Measurement.info()
    return [Measurement(str(ref.Id), session=self) for ref in refs]

list_users async

list_users() -> list[UserInfo]

Get list of users.

Returns:

  • users ( list[UserInfo] ) –

    List of user info

Source code in src/pypalmsens/lablink/_session.py
419
420
421
422
423
424
425
426
427
428
async def list_users(self) -> list[UserInfo]:
    """Get list of users.

    Returns
    -------
    users : list[UserInfo]
        List of user info
    """
    data = await self._http.get('/Users')
    return [UserInfo.from_wire(item) for item in data.json()]

pause_measurement async

pause_measurement(jobs: Sequence[MeasurementJob]) -> None

Pause running measurements on the given jobs.

Parameters:

Source code in src/pypalmsens/lablink/_session.py
353
354
355
356
357
358
359
360
361
362
363
364
365
366
async def pause_measurement(self, jobs: Sequence[MeasurementJob]) -> None:
    """Pause running measurements on the given jobs.

    Parameters
    ----------
    jobs : Sequence[MeasurementJob]
        The measurement jobs to pause.
    """
    payload = {
        'AllInstrumentsMustSucceed': True,
        'InstrumentProperties': {job.serial_number: {} for job in jobs},
    }

    await self._http.post('/Instrument/PauseMeasurement', json=payload)

release async

Release the given instruments back to Lablink.

Parameters:

Source code in src/pypalmsens/lablink/_session.py
173
174
175
176
177
178
179
180
181
182
183
184
185
186
async def release(self, instruments: Sequence[InstrumentClaim]) -> None:
    """Release the given instruments back to Lablink.

    Parameters
    ----------
    instruments : Sequence[InstrumentClaim]
        Claimed instruments to release.
    """
    props = {instrument.serial_number: EmptyProperty() for instrument in instruments}
    payload = SimpleInstrumentsCommand(
        InstrumentProperties=props, AllInstrumentsMustSucceed=True
    )

    await self._http.post('/Instruments/UnClaim', json=payload.model_dump())

resume_measurement async

resume_measurement(jobs: Sequence[MeasurementJob]) -> None

Resume a measurement that was previously paused.

Parameters:

Source code in src/pypalmsens/lablink/_session.py
368
369
370
371
372
373
374
375
376
377
378
379
380
381
async def resume_measurement(self, jobs: Sequence[MeasurementJob]) -> None:
    """Resume a measurement that was previously paused.

    Parameters
    ----------
    jobs : Sequence[MeasurementJob]
        The measurement jobs to resume.
    """
    payload = {
        'AllInstrumentsMustSucceed': True,
        'InstrumentProperties': {job.serial_number: {} for job in jobs},
    }

    await self._http.post('/Instrument/ResumeMeasurement', json=payload)

skip_pre_measurement_stage async

skip_pre_measurement_stage(jobs: Sequence[MeasurementJob]) -> None

Skip the pre-measurement stage on the given measurement jobs.

Parameters:

Source code in src/pypalmsens/lablink/_session.py
338
339
340
341
342
343
344
345
346
347
348
349
350
351
async def skip_pre_measurement_stage(self, jobs: Sequence[MeasurementJob]) -> None:
    """Skip the pre-measurement stage on the given measurement jobs.

    Parameters
    ----------
    jobs : Sequence[MeasurementJob]
        The running measurements to skip the pre-stage of.
    """
    payload = {
        'AllInstrumentsMustSucceed': True,
        'InstrumentProperties': {job.serial_number: {} for job in jobs},
    }

    await self._http.post('/Instrument/SkipPreMeasurementStage', json=payload)

start_measurement async

Start a measurement on each of the claimed instruments.

Parameters:

Returns:

  • list[MeasurementJob] –

    One job per instrument, each with an associated MeasurementJob.

Source code in src/pypalmsens/lablink/_session.py
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
async def start_measurement(
    self, instruments: Sequence[InstrumentClaim], *, method: MethodTypeCompatible
) -> list[MeasurementJob]:
    """Start a measurement on each of the claimed instruments.

    Parameters
    ----------
    instruments : Sequence[InstrumentClaim]
        Instruments (claimed) to start measuremeents on.
    method : MethodTypeCompatible
        The measurement method to apply.

    Returns
    -------
    list[MeasurementJob]
        One job per instrument, each with an associated MeasurementJob.
    """
    payload = {
        **to_payload(method),
        'AllInstrumentsMustSucceed': True,
        'InstrumentProperties': {
            instrument.serial_number: {} for instrument in instruments
        },
    }

    response = await self._http.post('/Instruments/StartMeasurement', json=payload)

    jobs = []
    claims = {claim.serial_number: claim for claim in instruments}

    for data in response.json():
        guid = data['result']
        serial = data['serial']
        claim = claims[serial]
        jobs.append(MeasurementJob(guid=guid, claim=claim))

    return jobs

start_workflow async

start_workflow(instruments: Sequence[InstrumentClaim], *, workflow: str) -> None

Start a workflow on the given instruments.

Parameters:

  • instruments

    (Sequence[InstrumentClaim]) –

    The claimed instruments that will run the workflow.

  • workflow

    (str) –

    Name of the workflow to start.

Source code in src/pypalmsens/lablink/_session.py
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
async def start_workflow(
    self, instruments: Sequence[InstrumentClaim], *, workflow: str
) -> None:
    """Start a workflow on the given instruments.

    Parameters
    ----------
    instruments : Sequence[InstrumentClaim]
        The claimed instruments that will run the workflow.
    workflow : str
        Name of the workflow to start.
    """
    data = {
        'AllInstrumentsMustSucceed': True,
        'InstrumentProperties': {
            instrument.serial_number: workflow for instrument in instruments
        },
    }
    payload = SendWorkflowCommand.model_validate(data).model_dump()
    await self._http.post('/Instrument/SendScript', json=payload)