Modifications in preparation to MAX IV experiment
This commit is contained in:
@@ -1,20 +1,76 @@
|
||||
import json
|
||||
# Uses DECTRIS Stream2 example
|
||||
|
||||
import zmq
|
||||
import numpy
|
||||
import numpy as np
|
||||
import sys
|
||||
|
||||
import signal
|
||||
import base64
|
||||
import cbor2
|
||||
import time
|
||||
|
||||
sys.path.insert(0, "/opt/dectris/albula/4.1/bin")
|
||||
sys.path.insert(0, "/opt/dectris/albula/4.1/python")
|
||||
|
||||
import dectris.albula as albula
|
||||
from dectris.albula import DNoObject, DDrawingEllipse, DDrawingString, DDrawingLine
|
||||
from dectris.compression import decompress
|
||||
from tifffile import imwrite
|
||||
|
||||
TERMINATE = False
|
||||
|
||||
|
||||
def decode_multi_dim_array(tag, column_major):
|
||||
dimensions, contents = tag.value
|
||||
if isinstance(contents, list):
|
||||
array = np.empty((len(contents),), dtype=object)
|
||||
array[:] = contents
|
||||
elif isinstance(contents, (np.ndarray, np.generic)):
|
||||
array = contents
|
||||
else:
|
||||
raise cbor2.CBORDecodeValueError("expected array or typed array")
|
||||
return array.reshape(dimensions, order="F" if column_major else "C")
|
||||
|
||||
|
||||
def decode_typed_array(tag, dtype):
|
||||
if not isinstance(tag.value, bytes):
|
||||
raise cbor2.CBORDecodeValueError("expected byte string in typed array")
|
||||
return np.frombuffer(tag.value, dtype=dtype)
|
||||
|
||||
|
||||
def decode_dectris_compression(tag):
|
||||
algorithm, elem_size, encoded = tag.value
|
||||
return decompress(encoded, algorithm, elem_size=elem_size)
|
||||
|
||||
|
||||
tag_decoders = {
|
||||
40: lambda tag: decode_multi_dim_array(tag, column_major=False),
|
||||
64: lambda tag: decode_typed_array(tag, dtype="u1"),
|
||||
65: lambda tag: decode_typed_array(tag, dtype=">u2"),
|
||||
66: lambda tag: decode_typed_array(tag, dtype=">u4"),
|
||||
67: lambda tag: decode_typed_array(tag, dtype=">u8"),
|
||||
68: lambda tag: decode_typed_array(tag, dtype="u1"),
|
||||
69: lambda tag: decode_typed_array(tag, dtype="<u2"),
|
||||
70: lambda tag: decode_typed_array(tag, dtype="<u4"),
|
||||
71: lambda tag: decode_typed_array(tag, dtype="<u8"),
|
||||
72: lambda tag: decode_typed_array(tag, dtype="i1"),
|
||||
73: lambda tag: decode_typed_array(tag, dtype=">i2"),
|
||||
74: lambda tag: decode_typed_array(tag, dtype=">i4"),
|
||||
75: lambda tag: decode_typed_array(tag, dtype=">i8"),
|
||||
77: lambda tag: decode_typed_array(tag, dtype="<i2"),
|
||||
78: lambda tag: decode_typed_array(tag, dtype="<i4"),
|
||||
79: lambda tag: decode_typed_array(tag, dtype="<i8"),
|
||||
80: lambda tag: decode_typed_array(tag, dtype=">f2"),
|
||||
81: lambda tag: decode_typed_array(tag, dtype=">f4"),
|
||||
82: lambda tag: decode_typed_array(tag, dtype=">f8"),
|
||||
83: lambda tag: decode_typed_array(tag, dtype=">f16"),
|
||||
84: lambda tag: decode_typed_array(tag, dtype="<f2"),
|
||||
85: lambda tag: decode_typed_array(tag, dtype="<f4"),
|
||||
86: lambda tag: decode_typed_array(tag, dtype="<f8"),
|
||||
87: lambda tag: decode_typed_array(tag, dtype="<f16"),
|
||||
1040: lambda tag: decode_multi_dim_array(tag, column_major=True),
|
||||
56500: lambda tag: decode_dectris_compression(tag),
|
||||
}
|
||||
|
||||
|
||||
def tag_hook(decoder, tag):
|
||||
tag_decoder = tag_decoders.get(tag.tag)
|
||||
return tag_decoder(tag) if tag_decoder else tag
|
||||
|
||||
|
||||
def signal_handler(signal, frame):
|
||||
global TERMINATE
|
||||
TERMINATE = True
|
||||
@@ -24,46 +80,20 @@ signal.signal(signal.SIGINT, signal_handler)
|
||||
|
||||
context = zmq.Context()
|
||||
socket = context.socket(zmq.SUB)
|
||||
socket.RCVTIMEO = 1000 # in milliseconds
|
||||
socket.connect("tcp://xbl-daq-38:5400")
|
||||
socket.RCVTIMEO = 20000 # in milliseconds
|
||||
socket.connect("tcp://127.0.0.1:5400")
|
||||
socket.setsockopt(zmq.SUBSCRIBE, b"")
|
||||
|
||||
OPTIONAL_DATA = albula.DImageOptionalData()
|
||||
|
||||
OPTIONAL_DATA.set_x_pixel_size(0.000075)
|
||||
OPTIONAL_DATA.set_y_pixel_size(0.000075)
|
||||
|
||||
albulaMain = albula.openMainFrame()
|
||||
albulaSubFrame = albulaMain.openSubFrame()
|
||||
startTime = time.time()
|
||||
|
||||
while not TERMINATE:
|
||||
try:
|
||||
msg = socket.recv_json()
|
||||
if round(time.time() - startTime) >= 60 * 60:
|
||||
albulaSubFrame.close()
|
||||
albulaSubFrame = albulaMain.openSubFrame()
|
||||
startTime = time.time()
|
||||
OPTIONAL_DATA.set_wavelength(msg["wavelength_A"])
|
||||
OPTIONAL_DATA.set_beam_center_x(msg["beam_x_pxl"])
|
||||
OPTIONAL_DATA.set_beam_center_y(msg["beam_y_pxl"])
|
||||
OPTIONAL_DATA.set_detector_distance(msg["detector_distance_mm"] * 0.001)
|
||||
OPTIONAL_DATA.set_saturation_value(int(msg["saturation_value"]))
|
||||
if int(msg["pixel_depth"]) == 2:
|
||||
image_array = numpy.frombuffer(base64.b64decode(msg["data"]), numpy.int16)
|
||||
else:
|
||||
image_array = numpy.frombuffer(base64.b64decode(msg["data"]), numpy.int32)
|
||||
height = int(msg["height"])
|
||||
width = int(msg["width"])
|
||||
image_number = int(msg["image_number"])
|
||||
image_array = numpy.reshape(image_array, (height, width))
|
||||
print("Received image %d %d %d %d" % (image_number, height, width, len(image_array)))
|
||||
dimage = albula.DImage(image_array)
|
||||
if image_number >= 0:
|
||||
dimage.setOptionalData(OPTIONAL_DATA)
|
||||
albulaSubFrame.loadImage(dimage)
|
||||
albulaSubFrame.setTitle("JUNGFRAU PREVIEW Dataset: %s Image: %d" % (msg["file_prefix"], image_number))
|
||||
else:
|
||||
OPTIONAL_DATA.set_pixel_mask(dimage)
|
||||
msg = socket.recv()
|
||||
msg = cbor2.loads(msg, tag_hook=tag_hook)
|
||||
imwrite('test.tif', msg['data']['default'])
|
||||
title = msg['series_unique_id']
|
||||
beam_center_x = msg['beam_center_x']
|
||||
beam_center_y = msg['beam_center_y']
|
||||
detector_distance = msg['detector_distance']
|
||||
energy = msg['incident_energy']
|
||||
print(msg["spots"])
|
||||
except:
|
||||
pass
|
||||
|
||||
123
python/preview_albula.py
Normal file
123
python/preview_albula.py
Normal file
@@ -0,0 +1,123 @@
|
||||
# Uses DECTRIS Stream2 example
|
||||
|
||||
import zmq
|
||||
import numpy as np
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, "/opt/dectris/albula/4.1/bin")
|
||||
sys.path.insert(0, "/opt/dectris/albula/4.1/python")
|
||||
|
||||
import dectris.albula as albula
|
||||
from dectris.albula import DNoObject, DDrawingEllipse, DDrawingString, DDrawingLine
|
||||
|
||||
import signal
|
||||
import cbor2
|
||||
import time
|
||||
from dectris.compression import decompress
|
||||
from tifffile import imwrite
|
||||
|
||||
TERMINATE = False
|
||||
|
||||
|
||||
def decode_multi_dim_array(tag, column_major):
|
||||
dimensions, contents = tag.value
|
||||
if isinstance(contents, list):
|
||||
array = np.empty((len(contents),), dtype=object)
|
||||
array[:] = contents
|
||||
elif isinstance(contents, (np.ndarray, np.generic)):
|
||||
array = contents
|
||||
else:
|
||||
raise cbor2.CBORDecodeValueError("expected array or typed array")
|
||||
return array.reshape(dimensions, order="F" if column_major else "C")
|
||||
|
||||
|
||||
def decode_typed_array(tag, dtype):
|
||||
if not isinstance(tag.value, bytes):
|
||||
raise cbor2.CBORDecodeValueError("expected byte string in typed array")
|
||||
return np.frombuffer(tag.value, dtype=dtype)
|
||||
|
||||
|
||||
def decode_dectris_compression(tag):
|
||||
algorithm, elem_size, encoded = tag.value
|
||||
return decompress(encoded, algorithm, elem_size=elem_size)
|
||||
|
||||
|
||||
tag_decoders = {
|
||||
40: lambda tag: decode_multi_dim_array(tag, column_major=False),
|
||||
64: lambda tag: decode_typed_array(tag, dtype="u1"),
|
||||
65: lambda tag: decode_typed_array(tag, dtype=">u2"),
|
||||
66: lambda tag: decode_typed_array(tag, dtype=">u4"),
|
||||
67: lambda tag: decode_typed_array(tag, dtype=">u8"),
|
||||
68: lambda tag: decode_typed_array(tag, dtype="u1"),
|
||||
69: lambda tag: decode_typed_array(tag, dtype="<u2"),
|
||||
70: lambda tag: decode_typed_array(tag, dtype="<u4"),
|
||||
71: lambda tag: decode_typed_array(tag, dtype="<u8"),
|
||||
72: lambda tag: decode_typed_array(tag, dtype="i1"),
|
||||
73: lambda tag: decode_typed_array(tag, dtype=">i2"),
|
||||
74: lambda tag: decode_typed_array(tag, dtype=">i4"),
|
||||
75: lambda tag: decode_typed_array(tag, dtype=">i8"),
|
||||
77: lambda tag: decode_typed_array(tag, dtype="<i2"),
|
||||
78: lambda tag: decode_typed_array(tag, dtype="<i4"),
|
||||
79: lambda tag: decode_typed_array(tag, dtype="<i8"),
|
||||
80: lambda tag: decode_typed_array(tag, dtype=">f2"),
|
||||
81: lambda tag: decode_typed_array(tag, dtype=">f4"),
|
||||
82: lambda tag: decode_typed_array(tag, dtype=">f8"),
|
||||
83: lambda tag: decode_typed_array(tag, dtype=">f16"),
|
||||
84: lambda tag: decode_typed_array(tag, dtype="<f2"),
|
||||
85: lambda tag: decode_typed_array(tag, dtype="<f4"),
|
||||
86: lambda tag: decode_typed_array(tag, dtype="<f8"),
|
||||
87: lambda tag: decode_typed_array(tag, dtype="<f16"),
|
||||
1040: lambda tag: decode_multi_dim_array(tag, column_major=True),
|
||||
56500: lambda tag: decode_dectris_compression(tag),
|
||||
}
|
||||
|
||||
|
||||
def tag_hook(decoder, tag):
|
||||
tag_decoder = tag_decoders.get(tag.tag)
|
||||
return tag_decoder(tag) if tag_decoder else tag
|
||||
|
||||
|
||||
def signal_handler(signal, frame):
|
||||
global TERMINATE
|
||||
TERMINATE = True
|
||||
|
||||
|
||||
signal.signal(signal.SIGINT, signal_handler)
|
||||
|
||||
context = zmq.Context()
|
||||
socket = context.socket(zmq.SUB)
|
||||
socket.RCVTIMEO = 20000 # in milliseconds
|
||||
socket.connect("tcp://127.0.0.1:5400")
|
||||
socket.setsockopt(zmq.SUBSCRIBE, b"")
|
||||
|
||||
albulaMain = albula.openMainFrame()
|
||||
albulaSubFrame = albulaMain.openSubFrame()
|
||||
startTime = time.time()
|
||||
|
||||
OPTIONAL_DATA = albula.DImageOptionalData()
|
||||
|
||||
OPTIONAL_DATA.set_x_pixel_size(0.000075)
|
||||
OPTIONAL_DATA.set_y_pixel_size(0.000075)
|
||||
|
||||
while not TERMINATE:
|
||||
try:
|
||||
print("a")
|
||||
msg = socket.recv()
|
||||
if round(time.time() - startTime) >= 60 * 60:
|
||||
albulaSubFrame.close()
|
||||
albulaSubFrame = albulaMain.openSubFrame()
|
||||
startTime = time.time()
|
||||
print("b")
|
||||
msg = cbor2.loads(msg, tag_hook=tag_hook)
|
||||
print(msg)
|
||||
#OPTIONAL_DATA.set_wavelength(12398/msg["incident_energy"])
|
||||
#OPTIONAL_DATA.set_beam_center_x(msg['beam_center_x'])
|
||||
#OPTIONAL_DATA.set_beam_center_y(msg['beam_center_y'])
|
||||
#OPTIONAL_DATA.set_detector_distance(msg["detector_distance"])
|
||||
|
||||
dimage = albula.DImage(msg['data']['default'])
|
||||
dimage.setOptionalData(OPTIONAL_DATA)
|
||||
albulaSubFrame.loadImage(dimage)
|
||||
#albulaSubFrame.setTitle("JUNGFRAU PREVIEW Dataset: %s Image: %d" % (msg["unique_series_id"], msg['number']))
|
||||
except:
|
||||
pass
|
||||
0
python/preview_w_adxv/.gitkeep
Normal file
0
python/preview_w_adxv/.gitkeep
Normal file
28
python/preview_w_adxv/README.md
Normal file
28
python/preview_w_adxv/README.md
Normal file
@@ -0,0 +1,28 @@
|
||||
# To use the preview
|
||||
```python
|
||||
source /opt/conda/etc/profile.d/conda.sh
|
||||
conda activate /mxn/groups/sw/mxsw/jfjoch/envs/cbor-py37-24a
|
||||
./start_adxv.sh -p 8100
|
||||
<ctrl+z>
|
||||
bg
|
||||
python preview.py "tcp://172.16.230.69:2345"
|
||||
# port 2345: testing data
|
||||
# port 5400: jf detector data
|
||||
```
|
||||
spot_type.txt can be edited to change spot color and spot size
|
||||
|
||||
# Attention
|
||||
This can be run using duo_user_name@clu0-fe-1 and duo_user_name@b-micromax-cc-4
|
||||
Might need to change paths
|
||||
|
||||
|
||||
# Credits
|
||||
start_adxv.sh and adxvSocketh5.py are contributed by Jie Nan (Max IV)
|
||||
|
||||
|
||||
# To-do
|
||||
- more documentations
|
||||
- more error feedbacks
|
||||
- make the adxv backgorund process automated
|
||||
- make spot_type.txt file path more robust in the preview.py code
|
||||
|
||||
192
python/preview_w_adxv/adxvSocketh5.py
Normal file
192
python/preview_w_adxv/adxvSocketh5.py
Normal file
@@ -0,0 +1,192 @@
|
||||
"adxvSocketh5.py" 190L, 7371C
|
||||
#!/usr/bin/env python
|
||||
"""
|
||||
Library for adxv-socketh5
|
||||
"""
|
||||
__author__ = "JieNan"
|
||||
__date__ = "2022/05/12"
|
||||
__version__ = "0.1"
|
||||
|
||||
|
||||
import argparse
|
||||
import socket
|
||||
import os
|
||||
#import h5py
|
||||
import time
|
||||
import numpy as np
|
||||
|
||||
class adxvSocketh5:
|
||||
def __init__(self, host="localhost", port = 8100, spot_type_file = None):
|
||||
#def __init__(self, host="localhost", spot_type_file = None):
|
||||
self.adxv_sock = None
|
||||
self.host = host
|
||||
self.port = 8100
|
||||
self.cont_size = None
|
||||
self.master_file = None
|
||||
self.img_num = None
|
||||
self.num_spots_groups = 0 # number of sets of spots
|
||||
self.spot_type_file = spot_type_file
|
||||
|
||||
def __del__(self):
|
||||
try:
|
||||
if self.adxv_sock is not None:
|
||||
self.adxv_sock.close()
|
||||
except:
|
||||
pass
|
||||
|
||||
def init(self):
|
||||
try:
|
||||
self.adxv_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
|
||||
print("init adxv socket...... {} {}".format(self.host,self.port))
|
||||
self.adxv_sock.connect((self.host,self.port))
|
||||
self.run_adxv_cmd("rings on")
|
||||
self.run_adxv_cmd("colors Heat")
|
||||
self.run_adxv_cmd("raise_window Magnify")
|
||||
self.clear_spot()
|
||||
self.set_spot_type()
|
||||
except:
|
||||
raise Exception("Init Error: Could not connect to adxv host")
|
||||
self.adxv_sock.close()
|
||||
def set_spot_type(self):
|
||||
if self.spot_type_file:
|
||||
with open(self.spot_type_file) as fp:
|
||||
lines = fp.read().splitlines()
|
||||
for line in lines:
|
||||
tmp= line.split()
|
||||
color = tmp[1]
|
||||
radius = tmp[2]
|
||||
print("define_type {} color {} radius {}\n".format(tmp[0],color,radius))
|
||||
self.run_adxv_cmd("define_type {} color {} radius {}\n".format(tmp[0],color,radius))
|
||||
|
||||
def run_adxv_cmd(self, cmd=""):
|
||||
self.adxv_sock.sendall("{}\n".format(cmd).encode())
|
||||
|
||||
def get_h5_num(self, img_num):
|
||||
h5_img_num = (img_num -1) % self.cont_size + 1
|
||||
h5_cont_num = int((img_num -1) / self.cont_size) + 1
|
||||
h5_cont = self.master_file.replace("_master.h5","_data_%06d.h5" % h5_cont_num)
|
||||
return h5_cont, h5_img_num
|
||||
|
||||
|
||||
def load_tiff(self, tiff_path):
|
||||
weak_data = 1
|
||||
self.run_adxv_cmd("weak_data {}".format(weak_data))
|
||||
self.run_adxv_cmd("load_image {}".format(tiff_path))
|
||||
|
||||
def load_image(self, slabs=1):
|
||||
h5_cont, h5_img_num = self.get_h5_num(self.img_num)
|
||||
print("will try to load file {}".format(h5_cont))
|
||||
if not os.path.exists(h5_cont):
|
||||
raise Exception("Error: data file {} doesn't exist".format(h5_cont))
|
||||
weak_data = 1
|
||||
self.run_adxv_cmd("set_slab {}".format(h5_img_num))
|
||||
self.run_adxv_cmd("weak_data {}".format(weak_data))
|
||||
self.run_adxv_cmd("set_slabs {}".format(slabs))
|
||||
self.run_adxv_cmd("load_image {}".format(h5_cont)
|
||||
|
||||
def add_spots(self, spots_sets, total_num_spots):
|
||||
# spots_sets is a list of numpy array, each array is a set/group of spots
|
||||
# spots_sets[i][j][0] is pos_x, spots[i][j][0] is pos_y
|
||||
self.num_spots_groups = len(spots_sets)
|
||||
self.run_adxv_cmd("load_spots {}\n".format(total_num_spots))
|
||||
spots_group = 1
|
||||
for spots in spots_sets:
|
||||
for spot in spots:
|
||||
self.run_adxv_cmd("{} {} {}\n".format(spot[0],spot[1], spots_group))
|
||||
spots_group +=1
|
||||
self.run_adxv_cmd("end_of_pack\n")
|
||||
|
||||
def clear_spot(self):
|
||||
#self.
|
||||
self.num_spots_groups = 0
|
||||
self.run_adxv_cmd("load_spots 0\n")
|
||||
self.run_adxv_cmd("end_of_pack\n")
|
||||
|
||||
|
||||
def save_img(self, img_file="", overwrite=False):
|
||||
if overwrite and os.path.exists(img_file):
|
||||
try:
|
||||
os.remove(img_file)
|
||||
except:
|
||||
raise Exception("Error: File {} already exists and cannot overwrite it, please check the permission".format(img_file))
|
||||
self.run_adxv_cmd("save_image {}".format(img_file))
|
||||
|
||||
def set_color(self, color="Grey"):
|
||||
self.run_adxv_cmd("colors {}".format(color))
|
||||
|
||||
def update_slabs(self, slabs = 1):
|
||||
self.run_adxv_cmd("slabs {}".format(slabs))
|
||||
|
||||
def update_meta(self, master_file=""):
|
||||
# make sure the first data container is available before calling
|
||||
data_h5 = master_file.replace("_master.h5", "_data_000001.h5")
|
||||
if not os.path.exists(data_h5):
|
||||
raise Exception ("Error: {} doesn't exist...".format(data_h5) )
|
||||
self.master_file = master_file
|
||||
with h5py.File(master_file, 'r') as f:
|
||||
self.cont_size = f['/entry/data/data_000001'].shape[0]
|
||||
# update the meta info in adxv
|
||||
self.run_adxv_cmd("load_image {}".format(self.master_file))
|
||||
|
||||
def load_image_from_h5(self, h5_cont, img_num):
|
||||
self.run_adxv_cmd("set_slab {}".format(img_num))
|
||||
self.run_adxv_cmd("load_image {}".format(h5_cont))
|
||||
|
||||
def load_image_from_master(self, master_file, img_num =1):
|
||||
if not os.access(master_file, os.R_OK):
|
||||
raise Exception("Error: No access to master file {}".format(master_file))
|
||||
self.update_meta(master_file=master_file)
|
||||
self.img_num = img_num
|
||||
self.load_image()
|
||||
|
||||
|
||||
def read_spots_from_file(self, spots_file):
|
||||
try:
|
||||
with open(spots_file) as fp:
|
||||
lines = fp.read().splitlines()
|
||||
spots = np.loadtxt(lines)
|
||||
except Exception as ex:
|
||||
raise Exception("Error when reading spots from file {}".format(spots_file))
|
||||
return spots.astype(int)
|
||||
|
||||
def save_sptxt(tiff_path):
|
||||
|
||||
return
|
||||
|
||||
def parseArgs():
|
||||
"""
|
||||
parse user input and return arguments
|
||||
"""
|
||||
parser = argparse.ArgumentParser(description = "test adxv lib")
|
||||
parser.add_argument("-m", "--master_file", help="master file", type=str, default=None)
|
||||
parser.add_argument("-n", "--img_num", help="image number", type=int, default=None)
|
||||
parser.add_argument("-sp1", "--spot_file1", help="spot file1", type=str, default=None)
|
||||
parser.add_argument("-sp2", "--spot_file2", help="spot file2", type=str, default=None)
|
||||
parser.add_argument("-s", "--socket", help="socket number", type=int, default=8100)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
args = parseArgs()
|
||||
adxv = adxvSocketh5(port = args.socket, spot_type_file = "spot_type.txt")
|
||||
# adxv = adxvSocketh5(spot_type_file = "spot_type.txt")
|
||||
adxv.init()
|
||||
# spots_file = "t1.adx"
|
||||
# spots_file2 = "t3.adx"
|
||||
# h5_cont = "/data/visitors/micromax/20231830/tests/ref_data/j4m_lys_2k/Lyso-2kHz_1_data_000001.h5"
|
||||
spots_file = "/data/visitors/micromax/20231830/tests/dawn/preview/noindexed.adx"
|
||||
spots_file2 = "/data/visitors/micromax/20231830/tests/dawn/preview/indexed.adx"
|
||||
# adxv.load_image_from_h5(h5_cont,1)
|
||||
tiff_path = "/data/visitors/micromax/20231830/tests/dawn/preview/test.tif"
|
||||
adxv.load_tiff(tiff_path)
|
||||
spots_sets_list=[]
|
||||
total_spots_num =0
|
||||
spots = adxv.read_spots_from_file(spots_file)
|
||||
spots_sets_list.append(spots)
|
||||
total_spots_num += spots.shape[0]
|
||||
spots = adxv.read_spots_from_file(spots_file2)
|
||||
spots_sets_list.append(spots)
|
||||
total_spots_num += spots.shape[0]
|
||||
adxv.add_spots(spots_sets_list, total_spots_num)
|
||||
print(len(spots_sets_list), total_spots_num)
|
||||
168
python/preview_w_adxv/preview.py
Normal file
168
python/preview_w_adxv/preview.py
Normal file
@@ -0,0 +1,168 @@
|
||||
# Uses DECTRIS Stream2 example
|
||||
|
||||
import zmq
|
||||
import numpy as np
|
||||
import sys
|
||||
import subprocess
|
||||
import os
|
||||
import signal
|
||||
import cbor2
|
||||
import time
|
||||
from dectris.compression import decompress
|
||||
from tifffile import imwrite
|
||||
|
||||
import argparse
|
||||
import socket
|
||||
sys.path.append('/data/visitors/micromax/20231830/tests/sw/adxv_live_view')
|
||||
import adxvSocketh5 #as jna5
|
||||
from adxvSocketh5 import adxvSocketh5
|
||||
|
||||
TERMINATE = False
|
||||
|
||||
|
||||
def decode_multi_dim_array(tag, column_major):
|
||||
dimensions, contents = tag.value
|
||||
if isinstance(contents, list):
|
||||
array = np.empty((len(contents),), dtype=object)
|
||||
array[:] = contents
|
||||
elif isinstance(contents, (np.ndarray, np.generic)):
|
||||
array = contents
|
||||
else:
|
||||
raise cbor2.CBORDecodeValueError("expected array or typed array")
|
||||
return array.reshape(dimensions, order="F" if column_major else "C")
|
||||
|
||||
|
||||
def decode_typed_array(tag, dtype):
|
||||
if not isinstance(tag.value, bytes):
|
||||
raise cbor2.CBORDecodeValueError("expected byte string in typed array")
|
||||
return np.frombuffer(tag.value, dtype=dtype)
|
||||
|
||||
|
||||
def decode_dectris_compression(tag):
|
||||
algorithm, elem_size, encoded = tag.value
|
||||
return decompress(encoded, algorithm, elem_size=elem_size)
|
||||
|
||||
def tag_hook(decoder, tag):
|
||||
tag_decoder = tag_decoders.get(tag.tag)
|
||||
return tag_decoder(tag) if tag_decoder else tag
|
||||
|
||||
tag_decoders = {
|
||||
40: lambda tag: decode_multi_dim_array(tag, column_major=False),
|
||||
64: lambda tag: decode_typed_array(tag, dtype="u1"),
|
||||
65: lambda tag: decode_typed_array(tag, dtype=">u2"),
|
||||
66: lambda tag: decode_typed_array(tag, dtype=">u4"),
|
||||
67: lambda tag: decode_typed_array(tag, dtype=">u8"),
|
||||
68: lambda tag: decode_typed_array(tag, dtype="u1"),
|
||||
69: lambda tag: decode_typed_array(tag, dtype="<u2"),
|
||||
70: lambda tag: decode_typed_array(tag, dtype="<u4"),
|
||||
71: lambda tag: decode_typed_array(tag, dtype="<u8"),
|
||||
72: lambda tag: decode_typed_array(tag, dtype="i1"),
|
||||
73: lambda tag: decode_typed_array(tag, dtype=">i2"),
|
||||
74: lambda tag: decode_typed_array(tag, dtype=">i4"),
|
||||
75: lambda tag: decode_typed_array(tag, dtype=">i8"),
|
||||
77: lambda tag: decode_typed_array(tag, dtype="<i2"),
|
||||
78: lambda tag: decode_typed_array(tag, dtype="<i4"),
|
||||
79: lambda tag: decode_typed_array(tag, dtype="<i8"),
|
||||
80: lambda tag: decode_typed_array(tag, dtype=">f2"),
|
||||
81: lambda tag: decode_typed_array(tag, dtype=">f4"),
|
||||
82: lambda tag: decode_typed_array(tag, dtype=">f8"),
|
||||
83: lambda tag: decode_typed_array(tag, dtype=">f16"),
|
||||
84: lambda tag: decode_typed_array(tag, dtype="<f2"),
|
||||
85: lambda tag: decode_typed_array(tag, dtype="<f4"),
|
||||
86: lambda tag: decode_typed_array(tag, dtype="<f8"),
|
||||
87: lambda tag: decode_typed_array(tag, dtype="<f16"),
|
||||
1040: lambda tag: decode_multi_dim_array(tag, column_major=True),
|
||||
56500: lambda tag: decode_dectris_compression(tag),
|
||||
}
|
||||
|
||||
if len(sys.argv) != 2:
|
||||
print("Please provide address: python preview.py <address>")
|
||||
sys.exit(1)
|
||||
|
||||
address = sys.argv[1]
|
||||
|
||||
context = zmq.Context()
|
||||
socket = context.socket(zmq.SUB)
|
||||
socket.RCVTIMEO = 20000 # in milliseconds
|
||||
socket.connect(address) #plut in the address here, get address from sys.argv[1]
|
||||
#socket.connect("tcp://127.0.0.1:5400")
|
||||
socket.setsockopt(zmq.SUBSCRIBE, b"")
|
||||
|
||||
|
||||
|
||||
#===========trying to start adxv in the background listening to images=======
|
||||
#command = "/data/visitors/micromax/20231830/tests/sw/adxv_live_view/start_adxv.sh -p 8100"
|
||||
#background_process = subprocess.Popen(f"{command} &", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
#try:
|
||||
# Simulate Ctrl + Z by sending SIGTSTP to the subprocess
|
||||
# os.kill(background_process.pid, signal.SIGTSTP)
|
||||
#except KeyboardInterrupt:
|
||||
# Handle Ctrl + C if needed
|
||||
# pass
|
||||
# Optionally, capture the output and error (if needed)
|
||||
#output, error = background_process.communicate()
|
||||
# Check if there was an error
|
||||
#if background_process.returncode != 0:
|
||||
# print(f"Error occurred: {error.decode('utf-8')}")
|
||||
#else:
|
||||
# print("Command started in the background.")
|
||||
|
||||
#===========trying to start adxv in the background listening to images=======
|
||||
|
||||
adxv = adxvSocketh5(port = 8100, spot_type_file = "/data/visitors/micromax/20231830/tests/sw/adxv_live_view/spot_type.txt")
|
||||
|
||||
adxv.init()
|
||||
print("adxv init...")
|
||||
spots_file = "noindexed.adx"
|
||||
spots_file2 = "indexed.adx"
|
||||
tiff_path = "/data/visitors/micromax/20231830/tests/dawn/preview/test.tif"
|
||||
while not TERMINATE:
|
||||
try:
|
||||
msg = socket.recv()
|
||||
msg = cbor2.loads(msg, tag_hook=tag_hook)
|
||||
imwrite('test.tif', msg['data']['default'])
|
||||
title = msg['series_unique_id']
|
||||
beam_center_x = msg['beam_center_x']
|
||||
beam_center_y = msg['beam_center_y']
|
||||
detector_distance = msg['detector_distance']
|
||||
energy = msg['incident_energy']
|
||||
|
||||
with open('indexed.adx', 'w') as file0, open('noindexed.adx', 'w') as file1:
|
||||
|
||||
for i in range(len(msg["spots"])):
|
||||
index_status=msg["spots"][i]["indexed"]
|
||||
if index_status:
|
||||
#print("indexed: ",msg["spots"][i])
|
||||
# Write i string to the file
|
||||
x0=int(msg["spots"][i]["x"])
|
||||
y0=int(msg["spots"][i]["y"])
|
||||
ind0=float(msg["spots"][i]["I"])
|
||||
thing_to_write0 = "{} {} {} 1 1 \n".format(x0, y0, ind0)
|
||||
file0.write(thing_to_write0)
|
||||
else:
|
||||
# Write a string to the file
|
||||
x1=str(msg["spots"][i]["x"])
|
||||
y1=str(msg["spots"][i]["y"])
|
||||
ind1=str(msg["spots"][i]["I"])
|
||||
thing_to_write1 = "{} {} {} 1 1 \n".format(x1, y1, ind1)
|
||||
file1.write(thing_to_write1)
|
||||
print('writes')
|
||||
#print(msg["spots"][1])
|
||||
#print(msg["spots"][3])
|
||||
#print(len(msg["spots"]))
|
||||
|
||||
adxv.load_tiff(tiff_path)
|
||||
spots_sets_list=[]
|
||||
total_spots_num =0
|
||||
spots = adxv.read_spots_from_file(spots_file)
|
||||
spots_sets_list.append(spots)
|
||||
total_spots_num += spots.shape[0]
|
||||
spots = adxv.read_spots_from_file(spots_file2)
|
||||
spots_sets_list.append(spots)
|
||||
total_spots_num += spots.shape[0]
|
||||
adxv.add_spots(spots_sets_list, total_spots_num)
|
||||
#print(len(spots_sets_list), total_spots_num)
|
||||
print("Running try")
|
||||
except:
|
||||
print("Running except")
|
||||
pass
|
||||
2
python/preview_w_adxv/spot_type.txt
Normal file
2
python/preview_w_adxv/spot_type.txt
Normal file
@@ -0,0 +1,2 @@
|
||||
1 white 10
|
||||
2 green 20
|
||||
29
python/preview_w_adxv/start_adxv.sh
Normal file
29
python/preview_w_adxv/start_adxv.sh
Normal file
@@ -0,0 +1,29 @@
|
||||
pkill -9 -f "adxv -socket"
|
||||
source /mxn/groups/sw/mxsw/env_setup/adxv_env.sh
|
||||
trial=1
|
||||
port=8100
|
||||
pids=""
|
||||
while [ $trial -le 10 ]
|
||||
do
|
||||
adxv -socket $port tau1_000001.cbf 2> ~/.adxv_err &
|
||||
sleep 1
|
||||
err=`grep "cannot bind socket" ~/.adxv_err`
|
||||
pids="$pids $!"
|
||||
if [ -z "$err" ]
|
||||
then
|
||||
echo "start adxv with port $port"
|
||||
break
|
||||
fi
|
||||
echo "$port is used already, will try another port"
|
||||
port=`expr $port + 1`
|
||||
trial=`expr $trial + 1`
|
||||
done
|
||||
#echo $pids
|
||||
pids="$pids $!"
|
||||
#trap "kill -15 $pids" 2 15
|
||||
|
||||
#change adxv window size
|
||||
echo "will change adxv window size"
|
||||
sleep 5
|
||||
xdotool search --onlyvisible --name "Adxv -" |awk '{system("xdotool windowsize "$1 " 1000 1000")}'
|
||||
wait
|
||||
Reference in New Issue
Block a user