Skip to content

Commit 07624dd

Browse files
flask8 tested localy some fixes
1 parent 3647f32 commit 07624dd

7 files changed

Lines changed: 352 additions & 344 deletions

File tree

Keithley_2400/Backends/IV_K2400_Loop_Backend_v10.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
# Changes_done:Working
4343
# ------------------------------------------------------------------------
4444

45+
import os
4546
import numpy as np
4647
import matplotlib.pyplot as plt
4748
from time import sleep
@@ -60,7 +61,7 @@ def main():
6061
sleep(2)
6162

6263
i = 0
63-
I = []
64+
current_values = []
6465
Volt = []
6566

6667
# user input ----------------------------------
@@ -83,7 +84,7 @@ def IV_Measure(cur):
8384
sleep(1.5)
8485
v_meas = keithley_2400.voltage
8586
sleep(1)
86-
I.append(cur * 1e-6) # Use the actual sourced value
87+
current_values.append(cur * 1e-6) # Use the actual sourced value
8788
Volt.append(v_meas)
8889
print(f"{cur * 1e-6:.3e} A {v_meas:.4f} V")
8990
i += 1
@@ -92,7 +93,7 @@ def IV_Measure(cur):
9293
for i1 in np.arange(0, I_range + I_step, I_step):
9394
IV_Measure(i1)
9495

95-
df = pd.DataFrame({'I': I, 'V': Volt})
96+
df = pd.DataFrame({'I': current_values, 'V': Volt})
9697
print("\n--- Measurement Complete ---")
9798
print(df)
9899

@@ -104,7 +105,7 @@ def IV_Measure(cur):
104105
keithley_2400.shutdown()
105106
print("Keithley 2400 shutdown complete.")
106107

107-
plt.plot(I, Volt, marker='o', linestyle='-', color='g', label='I-V Data')
108+
plt.plot(current_values, Volt, marker='o', linestyle='-', color='g', label='I-V Data')
108109
plt.xlabel('Current (A)')
109110
plt.ylabel('Voltage (V)')
110111
plt.title('I-V Curve')

Keithley_6517B/High_Resistance/Backends/IV_K6517B_L350_T_Control_Backend_v6.py

Lines changed: 97 additions & 109 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,100 @@ def perform_keithley_zero_check(keithley):
194194
# --- Main Program Execution ---
195195

196196

197+
def stabilize_temperature(lakeshore, target_temp):
198+
"""Actively controls the heater to reach and stabilize at the target temperature."""
199+
print(f"\nMoving to start temperature of {target_temp} K using active control...")
200+
while True:
201+
current_temp = lakeshore.get_temperature(SENSOR_INPUT)
202+
203+
if current_temp > target_temp + 0.2: # System is too warm
204+
print(f"Cooling... Current: {current_temp:.4f} K > Target: {target_temp} K", end='\r')
205+
lakeshore.set_heater_range(HEATER_OUTPUT, 'off')
206+
else: # System is too cold or within tolerance
207+
print(f"Heating... Current: {current_temp:.4f} K <= Target: {target_temp} K", end='\r')
208+
lakeshore.set_heater_range(HEATER_OUTPUT, 'medium')
209+
lakeshore.set_setpoint(HEATER_OUTPUT, target_temp)
210+
211+
if abs(current_temp - target_temp) < 0.1: # Stabilization tolerance
212+
print(f"\nStabilized at {current_temp:.4f} K. Waiting 5 seconds before starting ramp.")
213+
time.sleep(5)
214+
break
215+
time.sleep(2)
216+
217+
218+
def run_measurement_loop(lakeshore, keithley, filename, end_temp, safety_cutoff, source_voltage, delay):
219+
"""Runs the main data acquisition loop, logging data and updating the plot."""
220+
plt.ion()
221+
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 8))
222+
fig.suptitle('Live R-T Measurement', fontsize=16)
223+
line1, = ax1.plot([], [], 'b-o', markersize=3)
224+
ax1.set_xlabel('Elapsed Time (s)')
225+
ax1.set_ylabel('Temperature (K)')
226+
ax1.set_title('Temperature Ramp Profile')
227+
ax1.grid(True, linestyle=':')
228+
line2, = ax2.plot([], [], 'r-s', markersize=3)
229+
ax2.set_xlabel('Temperature (K)')
230+
ax2.set_ylabel('Resistance (Ω)')
231+
ax2.set_title('Resistance vs. Temperature')
232+
ax2.grid(True, linestyle=':')
233+
ax2.set_yscale('log')
234+
fig.tight_layout(rect=[0, 0.03, 1, 0.95])
235+
time_data, temp_data, res_data = [], [], []
236+
237+
start_time = time.time()
238+
239+
with open(filename, 'w', newline='') as file:
240+
writer = csv.writer(file)
241+
writer.writerow(["Timestamp", "Elapsed Time (s)", "Temperature (K)", "Heater Output (%)",
242+
"Applied Voltage (V)", "Measured Current (A)", "Resistance (Ohm)"])
243+
244+
while True:
245+
elapsed_time = time.time() - start_time
246+
current_temp = lakeshore.get_temperature(SENSOR_INPUT)
247+
heater_output = lakeshore.get_heater_output(HEATER_OUTPUT)
248+
249+
time.sleep(delay)
250+
resistance = keithley.resistance
251+
current = abs(source_voltage / resistance) if resistance != 0 else float('inf')
252+
253+
status_str = (
254+
f"Time: {elapsed_time:7.2f}s | "
255+
f"Temp: {current_temp:8.4f}K | "
256+
f"Resistance: {resistance:9.3e} Ω"
257+
)
258+
print(status_str, end='\r')
259+
260+
with open(filename, 'a', newline='') as file:
261+
writer = csv.writer(file)
262+
writer.writerow([
263+
datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
264+
f"{elapsed_time:.2f}", f"{current_temp:.4f}", f"{heater_output:.2f}",
265+
f"{source_voltage:.4e}", f"{current:.4e}", f"{resistance:.4e}"
266+
])
267+
268+
time_data.append(elapsed_time)
269+
temp_data.append(current_temp)
270+
res_data.append(resistance)
271+
272+
line1.set_data(time_data, temp_data)
273+
ax1.relim()
274+
ax1.autoscale_view()
275+
line2.set_data(temp_data, res_data)
276+
ax2.relim()
277+
ax2.autoscale_view()
278+
fig.canvas.draw()
279+
fig.canvas.flush_events()
280+
281+
if current_temp >= safety_cutoff:
282+
print(f"\n\n!!! SAFETY CUTOFF REACHED at {current_temp:.4f} K (Limit: {safety_cutoff} K) !!!")
283+
break
284+
if current_temp >= end_temp:
285+
print(f"\n\nTarget temperature of {end_temp} K reached.")
286+
break
287+
288+
time.sleep(2)
289+
290+
197291
def main():
198292
"""Main function to run the R-T experiment."""
199293
root = tk.Tk()
@@ -225,128 +319,22 @@ def main():
225319
keithley = Keithley6517B(KEITHLEY_VISA)
226320
print(f"Successfully connected to: {keithley.id}")
227321
perform_keithley_zero_check(keithley)
228-
322+
229323
keithley.source_voltage = source_voltage
230324
keithley.current_nplc = 1
231325
keithley.enable_source()
232326
print(f"\nKeithley source enabled and set to {source_voltage} V.")
233327

234328
# --- Setup Live Plot ---
235329
plt.ion()
236-
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 8))
237-
fig.suptitle('Live R-T Measurement', fontsize=16)
238-
line1, = ax1.plot([], [], 'b-o', markersize=3)
239-
ax1.set_xlabel('Elapsed Time (s)')
240-
ax1.set_ylabel('Temperature (K)')
241-
ax1.set_title('Temperature Ramp Profile')
242-
ax1.grid(True, linestyle=':')
243-
line2, = ax2.plot([], [], 'r-s', markersize=3)
244-
ax2.set_xlabel('Temperature (K)')
245-
ax2.set_ylabel('Resistance (Ω)')
246-
ax2.set_title('Resistance vs. Temperature')
247-
ax2.grid(True, linestyle=':')
248-
ax2.set_yscale('log')
249-
fig.tight_layout(rect=[0, 0.03, 1, 0.95])
250-
time_data, temp_data, res_data = [], [], []
251-
252-
# --- NEW: Go to Start Temp and Stabilize with Active Control ---
253-
print(
254-
f"\nMoving to start temperature of {start_temp} K using active control...")
255-
while True:
256-
current_temp = lakeshore.get_temperature(SENSOR_INPUT)
257-
258-
# Active heating/cooling logic
259-
if current_temp > start_temp + 0.2: # System is too warm
260-
print(
261-
f"Cooling... Current: {current_temp:.4f} K > Target: {start_temp} K",
262-
end='\r')
263-
lakeshore.set_heater_range(HEATER_OUTPUT, 'off')
264-
else: # System is too cold or within tolerance
265-
print(
266-
f"Heating... Current: {current_temp:.4f} K <= Target: {start_temp} K",
267-
end='\r')
268-
lakeshore.set_heater_range(HEATER_OUTPUT, 'medium')
269-
lakeshore.set_setpoint(HEATER_OUTPUT, start_temp)
270-
271-
# Check for stabilization
272-
if abs(current_temp - start_temp) < 0.1: # Stabilization tolerance
273-
print(
274-
f"\nStabilized at {current_temp:.4f} K. Waiting 5 seconds before starting ramp.")
275-
time.sleep(5)
276-
break
277-
time.sleep(2) # Interval for checking stabilization status
330+
stabilize_temperature(lakeshore, start_temp)
278331

279332
# --- Start Ramp and Data Logging ---
280333
lakeshore.setup_ramp(HEATER_OUTPUT, rate)
281334
lakeshore.set_setpoint(HEATER_OUTPUT, end_temp)
282-
# Ensure heater is on for the ramp
283335
lakeshore.set_heater_range(HEATER_OUTPUT, 'medium')
284336
print(f"Ramp started towards {end_temp} K at {rate} K/min.")
285-
286-
start_time = time.time()
287-
288-
with open(filename, 'w', newline='') as file:
289-
writer = csv.writer(file)
290-
writer.writerow(["Timestamp",
291-
"Elapsed Time (s)",
292-
"Temperature (K)",
293-
"Heater Output (%)",
294-
"Applied Voltage (V)",
295-
"Measured Current (A)",
296-
"Resistance (Ohm)"])
297-
298-
# --- Main experiment loop ---
299-
while True:
300-
elapsed_time = time.time() - start_time
301-
current_temp = lakeshore.get_temperature(SENSOR_INPUT)
302-
heater_output = lakeshore.get_heater_output(HEATER_OUTPUT)
303-
304-
time.sleep(delay)
305-
resistance = keithley.resistance
306-
current = abs(
307-
source_voltage /
308-
resistance) if resistance != 0 else float('inf')
309-
310-
status_str = (
311-
f"Time: {elapsed_time:7.2f}s | "
312-
f"Temp: {current_temp:8.4f}K | "
313-
f"Resistance: {resistance:9.3e} Ω"
314-
)
315-
print(status_str, end='\r')
316-
317-
with open(filename, 'a', newline='') as file:
318-
writer = csv.writer(file)
319-
writer.writerow([
320-
datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
321-
f"{elapsed_time:.2f}", f"{current_temp:.4f}", f"{heater_output:.2f}",
322-
f"{source_voltage:.4e}", f"{current:.4e}", f"{resistance:.4e}"
323-
])
324-
325-
time_data.append(elapsed_time)
326-
temp_data.append(current_temp)
327-
res_data.append(resistance)
328-
329-
line1.set_data(time_data, temp_data)
330-
ax1.relim()
331-
ax1.autoscale_view()
332-
line2.set_data(temp_data, res_data)
333-
ax2.relim()
334-
ax2.autoscale_view()
335-
fig.canvas.draw()
336-
fig.canvas.flush_events()
337-
338-
# --- Check for End Conditions ---
339-
if current_temp >= safety_cutoff:
340-
print(
341-
f"\n\n!!! SAFETY CUTOFF REACHED at {current_temp:.4f} K (Limit: {safety_cutoff} K) !!!")
342-
break
343-
if current_temp >= end_temp:
344-
print(f"\n\nTarget temperature of {end_temp} K reached.")
345-
break
346-
347-
# The main data logging interval. Should be independent of Keithley
348-
# delay.
349-
time.sleep(2)
337+
run_measurement_loop(lakeshore, keithley, filename, end_temp, safety_cutoff, source_voltage, delay)
350338

351339
except ConnectionError as e:
352340
print(f"\nCould not start experiment due to a connection failure: {e}")

Keithley_6517B/High_Resistance/RT_K6517B_L350_T_Control_GUI_v13.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -988,6 +988,39 @@ def _process_data_queue(self):
988988
if self.is_running or self.is_stabilizing:
989989
self.root.after(200, self._process_data_queue)
990990

991+
def _handle_new_data_point(self, data):
992+
"""Helper to process a single data point from the queue."""
993+
temp, htr, cur, res, elapsed = data
994+
self.log(
995+
f"T:{temp:.3f}K | R:{res:.3e}Ω | Htr:{htr:.1f}% ({self.current_heater_range})")
996+
with open(self.data_filepath, 'a', newline='') as f:
997+
writer = csv.writer(f)
998+
writer.writerow(
999+
[
1000+
datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
1001+
f"{elapsed:.2f}",
1002+
f"{temp:.4f}",
1003+
f"{htr:.2f}",
1004+
f"{self.backend.params['source_voltage']:.4e}",
1005+
f"{cur:.4e}",
1006+
f"{res:.4e}"])
1007+
1008+
self.data_storage['time'].append(elapsed)
1009+
self.data_storage['temperature'].append(temp)
1010+
self.data_storage['current'].append(cur)
1011+
self.data_storage['resistance'].append(res)
1012+
1013+
# Update plot data
1014+
self.line_main.set_data(
1015+
self.data_storage['temperature'],
1016+
self.data_storage['resistance'])
1017+
self.line_sub1.set_data(
1018+
self.data_storage['temperature'],
1019+
self.data_storage['current'])
1020+
self.line_sub2.set_data(
1021+
self.data_storage['time'],
1022+
self.data_storage['temperature'])
1023+
9911024
def _scan_for_visa_instruments(self):
9921025
if not pyvisa:
9931026
self.log("ERROR: PyVISA is not installed.")

Keithley_6517B/Pyroelectricity/Backends/Current_K6517B_Simple_Backend_v10.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@
88
import pandas as pd
99
from pymeasure.instruments.keithley import Keithley6517B
1010

11-
I = []
12-
t = []
11+
time_data = []
12+
current_data = []
1313

1414
try:
1515
keithley = Keithley6517B("GPIB0::27::INSTR")
@@ -23,17 +23,17 @@
2323
while True:
2424
elapsed_time = time.time() - start_time
2525
current = keithley.current
26-
t.append(elapsed_time)
27-
I.append(current)
26+
time_data.append(elapsed_time)
27+
current_data.append(current)
2828
print(f"Time: {elapsed_time:.2f} | Current: {current} A")
2929
time.sleep(2)
3030

3131
except KeyboardInterrupt:
3232
print("\nMeasurement stopped by User.")
3333

3434
# --- THIS IS THE FIX ---
35-
if t and I:
36-
data_df = pd.DataFrame({"Timestamp": t, "Current (A)": I})
35+
if time_data and current_data:
36+
data_df = pd.DataFrame({"Timestamp": time_data, "Current (A)": current_data})
3737
data_df.to_csv("demo_data.dat", index=False)
3838
print("Data saved to file: demo_data.dat")
3939

Utilities/GPIB_Interface_Rescue_Simple_Backened_v2_.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ def run_rescue(visa_address: str):
1212
"""
1313
Connects to a hung instrument and attempts to clear its error state.
1414
"""
15-
print(f"--- Instrument Rescue Script Initialized ---")
15+
print("--- Instrument Rescue Script Initialized ---")
1616
rm = pyvisa.ResourceManager()
1717
instrument = None # Initialize to None to ensure it exists for the 'finally' block
1818

0 commit comments

Comments
 (0)