File: agilent4294A.py

package info (click to toggle)
python-pymeasure 0.14.0-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 8,788 kB
  • sloc: python: 47,201; makefile: 155
file content (181 lines) | stat: -rw-r--r-- 5,889 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
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
172
173
174
175
176
177
178
179
180
181
#
# This file is part of the PyMeasure package.
#
# Copyright (c) 2013-2024 PyMeasure Developers
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#

from pymeasure.instruments import Instrument, SCPIMixin
from pymeasure.instruments.validators import strict_range, strict_discrete_set
import pandas as pd
import numpy as np
import os

# Set of valid arguments for the MEAS? command
MEASUREMENT_TYPES = [
    "IMPH",
    "IRIM",
    "LSR",
    "LSQ",
    "CSR",
    "CSQ",
    "CSD",
    "AMPH",
    "ARIM",
    "LPG",
    "LPQ",
    "CPG",
    "CPQ",
    "CPD",
    "COMP",
    "IMLS",
    "IMCS",
    "IMLP",
    "IMCP",
    "IMRS",
    "IMQ",
    "IMD",
    "LPR",
    "CPR",
]


class Agilent4294A(SCPIMixin, Instrument):
    """ Represents the Agilent 4294A Precision Impedance Analyzer """

    def __init__(self, adapter, name="Agilent 4294A Precision Impedance Analyzer",
                 read_termination="\n",
                 write_termination="\n",
                 timeout=5000,
                 **kwargs):

        super().__init__(
            adapter,
            name,
            read_termination=read_termination,
            write_termination=write_termination,
            timeout=timeout,
            **kwargs
        )

    start_frequency = Instrument.control(
        "STAR?", "STAR %d HZ", "Control the start frequency in Hz",
        validator=strict_range, values=[40, 140E6]
    )

    stop_frequency = Instrument.control(
        "STOP?", "STOP %d HZ", "Control the stop frequency in Hz",
        validator=strict_range, values=[40, 140E6]
    )

    num_points = Instrument.control(
        "POIN?", "POIN %d", "Control the number of points measured at each sweep",
        validator=strict_discrete_set, values=range(2, 802),
        cast=int,
    )

    measurement_type = Instrument.control(
        "MEAS?", "MEAS %d", "Control the measurement type. See MEASUREMENT_TYPES",
        validator=strict_discrete_set, values=MEASUREMENT_TYPES,
    )

    active_trace = Instrument.control(
        "TRAC?", "TRAC %s", "Control the active trace",
        validator=strict_discrete_set, values=["A", "B"]
    )

    title = Instrument.control(
        "TITL?", 'TITL "%s"', "Control the title of the active trace"
    )

    def save_graphics(self, path=""):
        """ Save graphics on the screen to a file on the local computer.
        Adapted from:
        https://www.keysight.com/se/en/lib/software-detail/programming-examples/4294a-data-transfer-program-excel-vba-1645196.html
        """

        self.write("STOD MEMO")  # store to internal memory
        self.write("PRIC VARI")  # save a color image

        root, ext = os.path.splitext(path)
        if ext != ".tiff":
            ext = ".tiff"
        if not root:
            root = "graphics"

        path = root + ext

        REMOTE_FILE = "agt4294a.tiff"  # Filename of the in-memory file on the device
        self.write(f'SAVDTIF "{REMOTE_FILE}"')

        vErr = self.ask("OUTPERRO?").split(",")
        if not int(vErr[0]) == 0:
            self.write(f'PURG "{REMOTE_FILE}"')
            self.write(f'SAVDTIF "{REMOTE_FILE}"')
            vErr = self.ask("OUTPERRO?").split(",")

        self.write(f'ROPEN "{REMOTE_FILE}"')
        lngFileSize = int(self.ask(f'FSIZE? "{REMOTE_FILE}"'))
        MAX_BUFF_SIZE = 16384
        iBufCnt = lngFileSize // MAX_BUFF_SIZE
        if lngFileSize % MAX_BUFF_SIZE > 0:
            iBufCnt += 1

        with open(path, 'wb') as file:
            for _ in range(iBufCnt):
                data = self.adapter.connection.query_binary_values("READ?", datatype='B',
                                                                   container=bytes)
                file.write(data)
        self.write(f'PURG "{REMOTE_FILE}"')

        return path

    def get_data(self, path=None):
        """
        Get the measurement data from the instrument after completion.

        :param path: Path for optional data export to CSV.
        :returns: Pandas Dataframe
        """
        prev_active_trace = self.active_trace

        num_points = self.num_points
        freqs = np.array(self.ask("OUTPSWPRM?").split(","), dtype=float)
        self.active_trace = "A"
        adata = np.array(self.ask("OUTPDTRC?").split(","), dtype=float).reshape(num_points, 2)

        self.active_trace = "B"
        bdata = np.array(self.ask("OUTPDTRC?").split(","), dtype=float).reshape(num_points, 2)

        # restore the previous state
        self.active_trace = prev_active_trace

        df = pd.DataFrame(
            np.hstack((freqs.reshape(-1, 1), adata, bdata)),
            columns=["Frequency", "A Real", "A Imag", "B Real", "B Imag"]
        )

        if path is not None:
            _, ext = os.path.splitext(path)
            if ext != ".csv":
                path = path + ".csv"
            df.to_csv(path, index=False)

        return df